From 862ba4576ff0711e264ba08675ccc2bab163945c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 06:04:58 -0500 Subject: [PATCH 01/88] Persist background task acceptance and terminal receipts --- .../src/cognition/act_observe/apply.rs | 11 +- .../mind_integration/hands_isolation.rs | 9 +- .../src/runtime/command_executor.rs | 35 +- .../runtime/command_executor/background.rs | 94 +++++ .../src/runtime/command_executor/tests.rs | 32 +- core/continuum-kernel/src/runtime/mod.rs | 1 + core/continuum-kernel/src/runtime/tasks.rs | 350 ++++++++++++++++++ .../src/runtime/tasks/output.rs | 90 +++++ 8 files changed, 582 insertions(+), 40 deletions(-) create mode 100644 core/continuum-kernel/src/runtime/command_executor/background.rs create mode 100644 core/continuum-kernel/src/runtime/tasks.rs create mode 100644 core/continuum-kernel/src/runtime/tasks/output.rs diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 49b3a77b9e..f611aac4c8 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -235,7 +235,7 @@ pub async fn apply_act( for call in calls { let cmd = call.name.replace('_', "/"); if is_long_running(&cmd) { - let handle = exec.dispatch_background( + let accepted = exec.dispatch_background( cmd.clone(), call.input.clone(), // In THESE hands: a long-running command a card turn dispatches runs in @@ -249,7 +249,14 @@ pub async fn apply_act( None => identity, } }), - ); + ).await; + let handle = match accepted { + Ok(handle) => handle, + Err(error) => { + bg_notes.push(format!("[not run] {cmd}: {}", error.message)); + continue; + } + }; dispatched_calls.push(call.clone()); body.working_memory.record_dispatch_event( handle, diff --git a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs index 8837740662..ce61ea19f5 100644 --- a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs +++ b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs @@ -95,7 +95,7 @@ async fn listing(hands: &ActingHands) -> String { // CALL's own hands are bound to (Astra on #5026), never her current focus: a turn // moving her focus to another claim before the task's first poll cannot move it. #[tokio::test] -async fn command_work_stays_with_its_card_across_background_dispatch() { +async fn command_work_stays_with_its_card_across_background_dispatch() -> Result<(), String> { use crate::persona::cognition_pulse::work_idle_ms; let home = tempfile::TempDir::new().unwrap(); std::fs::write(home.path().join("work.txt"), "work").unwrap(); @@ -113,13 +113,15 @@ async fn command_work_stays_with_its_card_across_background_dispatch() { assert!(work_idle_ms(persona, Some(card_a), EpochMs::now().millis()).is_some()); let exec = hands.executor.command_executor().unwrap(); + let (adapter, _task_directory) = crate::orm::store::fresh_adapter().await; + exec.set_task_ledger(Arc::new(continuum_kernel::runtime::tasks::TaskLedger::new(adapter).await?))?; let mut rx = exec.message_bus().unwrap().receiver(); let handle = exec.dispatch_background( "code/list", serde_json::json!({"path": "."}), Some(CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(persona)).in_hands(claim_a)), - ); - // Current-thread test: the spawned task has not been polled yet. Her focus moves on. + ).await.map_err(|e| e.message)?; + // Acceptance finished before spawning: her focus moves before the task's first poll. let claim_b = crate::identity::hands_context::HandsContext::for_claim(persona, card_b, Uuid::new_v4()); note_acting_root_in(persona, Some(claim_b), Some(home.path().to_path_buf())); note_acting_card_in(persona, Some(claim_b), card_b); @@ -143,6 +145,7 @@ async fn command_work_stays_with_its_card_across_background_dispatch() { set_focus(persona, None); note_acting_root_in(persona, Some(claim_a), None); note_acting_root_in(persona, Some(claim_b), None); + Ok(()) } // what this catches (Astra on #5026): admission living in helpers, so a command that diff --git a/core/continuum-kernel/src/runtime/command_executor.rs b/core/continuum-kernel/src/runtime/command_executor.rs index 193b39209d..cac85545f0 100644 --- a/core/continuum-kernel/src/runtime/command_executor.rs +++ b/core/continuum-kernel/src/runtime/command_executor.rs @@ -167,6 +167,7 @@ pub struct CommandExecutor { /// them inline against the owned `registry` + `interceptors` + /// TS bridge. remote_transport: Arc, + task_ledger: tokio::sync::OnceCell>, } impl CommandExecutor { @@ -177,6 +178,7 @@ impl CommandExecutor { bus: None, policy: Arc::new(crate::routing::AllowAllPolicy), remote_transport: Arc::new(crate::routing::NotImplementedRemoteTransport), + task_ledger: tokio::sync::OnceCell::new(), } } @@ -351,37 +353,6 @@ impl CommandExecutor { outcome } - /// Fire a command in the BACKGROUND: return a handle (UUID) immediately, run the - /// dispatch on a spawned task, and on completion emit `command:completed` carrying the - /// handle AND the result. A subscriber — e.g. a persona that sent a sentinel, a - /// compile, or a debugger away — matches the completion by handle and folds the outcome - /// in when it lands, never blocking the turn. This is the fire-and-poll shape (#86): the - /// caller does not await the work. The handle is reusable in a follow-up command - /// (cancel/query/attach), which is why it's a plain UUID ([[commands-are-agency-algs-are-pathways]]). - pub fn dispatch_background( - self: &std::sync::Arc, - command: impl Into, - params: Value, - caller: Option, - ) -> uuid::Uuid { - let handle = uuid::Uuid::new_v4(); - let command: CommandUri = command.into(); - let this = std::sync::Arc::clone(self); - tokio::spawn(async move { - let start = std::time::Instant::now(); - // The caller's hands are bound and admitted inside dispatch, for this task's whole - // life: a release that began before its first poll refuses it by name. - let outcome = this.dispatch(&command, params, caller.as_ref()).await; - this.emit_command_completed( - command.path(), - &outcome, - start.elapsed().as_millis() as u64, - Some(handle), - ); - }); - handle - } - /// Routing decision on a [`CommandUri`]. Local URIs go through the /// existing chain; non-Local URIs return a typed /// not-yet-implemented error pending the transport selector. @@ -805,5 +776,7 @@ impl CommandExecutor { // // Pure dependency injection. No global. No panic-if-uninitialized. +mod background; + #[cfg(test)] mod tests; diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs new file mode 100644 index 0000000000..8c8eecb0be --- /dev/null +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -0,0 +1,94 @@ +//! Persist acceptance before execution and the terminal result before notification. +use super::{CommandExecutor, DispatchFailure}; +use crate::routing::{CallerIdentity, CommandUri}; +use crate::runtime::tasks::{TaskEnd, TaskLedger, TaskOutput}; +use futures::FutureExt; +use serde_json::Value; +use std::sync::Arc; +use uuid::Uuid; + +impl CommandExecutor { + /// Explicit storage injection for an embedded executor or an isolated fixture. + pub fn set_task_ledger(&self, ledger: Arc) -> Result<(), String> { + self.task_ledger + .set(ledger) + .map_err(|_| "task ledger already initialized".into()) + } + + /// Resolve the same node store used by modules; never create a private database. + pub async fn task_ledger(&self) -> Result<&Arc, String> { + self.task_ledger + .get_or_try_init(|| async { + let data = self + .registry + .get_by_name("data") + .ok_or("background tasks require the data module")?; + let storage = data + .as_storage() + .ok_or("background tasks require the data storage provider")?; + let adapter = storage.adapter("main").await?; + TaskLedger::new(adapter).await.map(Arc::new) + }) + .await + } + + /// Await durable acceptance only, not execution. A refusal has no command effects. + /// The caller identity owns the receipt; command parameters cannot choose its owner. + pub async fn dispatch_background( + self: &Arc, + command: impl Into, + params: Value, + caller: Option, + ) -> Result { + let caller = caller.ok_or_else(|| { + DispatchFailure::not_committed("background tasks require an authenticated owner".into()) + })?; + let owner = caller.peer_id.as_uuid(); + let command: CommandUri = command.into(); + let ledger = Arc::clone( + self.task_ledger() + .await + .map_err(DispatchFailure::not_committed)?, + ); + let handle = ledger + .accept(owner, command.to_string()) + .await + .map_err(DispatchFailure::not_committed)?; + let this = Arc::clone(self); + tokio::spawn(async move { + let start = std::time::Instant::now(); + // Keep the existing policy and hands admission scopes inside dispatch. + // Catch an unwinding handler without detaching a second execution task. + let outcome = + match std::panic::AssertUnwindSafe(this.dispatch(&command, params, Some(&caller))) + .catch_unwind() + .await + { + Ok(outcome) => outcome, + Err(_) => Err(DispatchFailure::uncertain( + "background command panicked".into(), + )), + }; + let outcome = outcome.and_then(|result| { + TaskOutput::try_from(&result) + .map(|output| (result, output)) + .map_err(DispatchFailure::uncertain) + }); + let (end, outcome) = match outcome { + Ok((result, output)) => (TaskEnd::Done(output), Ok(result)), + Err(error) => (TaskEnd::Failed(error.message.clone()), Err(error)), + }; + if let Err(error) = ledger.finish(handle, owner, end).await { + tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); + return; + } + this.emit_command_completed( + command.path(), + &outcome, + start.elapsed().as_millis() as u64, + Some(handle), + ); + }); + Ok(handle) + } +} diff --git a/core/continuum-kernel/src/runtime/command_executor/tests.rs b/core/continuum-kernel/src/runtime/command_executor/tests.rs index e71a5b2bed..9d60d756c0 100644 --- a/core/continuum-kernel/src/runtime/command_executor/tests.rs +++ b/core/continuum-kernel/src/runtime/command_executor/tests.rs @@ -268,21 +268,27 @@ ); } - // what this catches: dispatch_background returns a handle IMMEDIATELY (fire-and-poll) + // what this catches: dispatch_background returns after durable acceptance, before execution, // and its completion event carries BOTH the handle and the result — so a subscriber // (a persona that sent a sentinel away) matches the completion to its dispatch and // folds the outcome in without a second call. This is the producer for the WM async // recency channel. #[tokio::test] - async fn dispatch_background_completion_carries_handle_and_result() { + async fn dispatch_background_completion_carries_handle_and_result() -> Result<(), String> { let registry = Arc::new(ModuleRegistry::new()); registry.register(Arc::new(CannedModule::answering(Ok(serde_json::json!({ "built": true, "warnings": 0 }))))); let bus = Arc::new(MessageBus::new()); let mut rx = bus.receiver(); let executor = Arc::new(CommandExecutor::new(registry).with_message_bus(bus)); - // Fire in the background — returns a handle immediately, does not await the work. - let handle = executor.dispatch_background("canned/ping", serde_json::json!({}), None); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter).await?); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + // Await durable acceptance, not the command's execution. + let handle = executor.dispatch_background("canned/ping", serde_json::json!({}), Some(caller)) + .await.map_err(|e| e.message)?; let event = next_command_completed(&mut rx).await; assert_eq!(event.command_name, "canned/ping"); @@ -297,6 +303,24 @@ Some(serde_json::json!({ "built": true, "warnings": 0 })), "completion carries the result — no second call needed" ); + assert!(matches!(ledger.pending(handle, owner).await?, Some(crate::runtime::tasks::TaskEnd::Done(_))), + "terminal receipt must be durable before the completion event"); + Ok(()) + } + + #[tokio::test] + async fn background_acceptance_refusal_never_reaches_dispatch() { + let seen = Arc::new(AtomicUsize::new(0)); + let executor = Arc::new(CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_interceptor(Arc::new(RecordingDecliner { name: "effect", seen: seen.clone(), mark: 1 }))); + let anonymous = executor.dispatch_background("effect/run", serde_json::json!({}), None).await; + assert!(matches!(anonymous, Err(DispatchFailure { outcome: DispatchOutcome::NotCommitted, .. }))); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(uuid::Uuid::new_v4())); + // Identity alone is insufficient: no storage provider means no durable acceptance. + let no_store = executor.dispatch_background("effect/run", serde_json::json!({}), Some(caller)).await; + assert!(matches!(no_store, Err(DispatchFailure { outcome: DispatchOutcome::NotCommitted, .. }))); + tokio::task::yield_now().await; + assert_eq!(seen.load(Ordering::SeqCst), 0); } #[tokio::test] diff --git a/core/continuum-kernel/src/runtime/mod.rs b/core/continuum-kernel/src/runtime/mod.rs index 786460fa92..c446eb59f7 100644 --- a/core/continuum-kernel/src/runtime/mod.rs +++ b/core/continuum-kernel/src/runtime/mod.rs @@ -43,6 +43,7 @@ pub mod control; pub mod event_classes; pub mod event_graph; pub mod tracked_checkout; +pub mod tasks; pub mod daemon; pub mod governor_bus; pub mod handle; diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs new file mode 100644 index 0000000000..458fd7b3d6 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -0,0 +1,350 @@ +//! Durable task facts. Acceptance precedes execution; the first terminal insert wins. +//! A terminal fact is also the outbox: it remains pending until its owner acknowledges it. +//! Execution supervision and the owner sink are separate from this persistence contract. + +use crate::orm::query::{QueryBuilder, QueryOperator}; +use crate::orm::types::{CollectionSchema, FieldType, SchemaField}; +use crate::orm::{adapter::StorageAdapter, entity::OrmEntity, store::OrmStore}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::Arc; +use uuid::Uuid; + +mod output; +pub use output::TaskOutput; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum TaskEnd { + Done(TaskOutput), + Failed(String), + TimedOut, + Stopped, + Lost, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +enum Fact { + Accepted { command: String }, + Ended(TaskEnd), + Delivered, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct TaskFact { + task: Uuid, + owner: Uuid, + fact: Fact, +} + +impl OrmEntity for TaskFact { + const COLLECTION: &'static str = "kernel_task_facts"; + + fn collection_schema() -> CollectionSchema { + let mut fields = crate::orm::entity::base_entity_fields(); + for (name, field_type) in [ + ("task", FieldType::Uuid), + ("owner", FieldType::Uuid), + ("fact", FieldType::Json), + ] { + fields.push(SchemaField { + name: name.into(), + field_type, + indexed: false, + unique: false, + nullable: false, + max_length: None, + foreign_key: None, + }); + } + CollectionSchema { + collection: Self::COLLECTION.into(), + fields, + indexes: vec![], + } + } +} + +/// One ledger may be reopened or shared by multiple supervisors. INSERT, rather than a +/// process-local lock or equal-version monotonic upsert, arbitrates terminal races. +pub struct TaskLedger { + facts: OrmStore, +} + +/// A bounded reconciliation page. Advance even when `ends` is empty: acknowledged +/// rows still consume scan space. A new reconciliation starts with no cursor. +pub struct PendingPage { + pub ends: Vec<(Uuid, TaskEnd)>, + pub after: Option, + pub exhausted: bool, +} + +impl TaskLedger { + pub async fn new(adapter: Arc) -> Result { + Ok(Self { + facts: OrmStore::new(adapter).await.map_err(|e| e.to_string())?, + }) + } + + pub async fn accept(&self, owner: Uuid, command: String) -> Result { + let task = Uuid::new_v4(); + self.facts + .save( + task, + &TaskFact { + task, + owner, + fact: Fact::Accepted { command }, + }, + ) + .await + .map_err(|e| e.to_string())?; + Ok(task) + } + + async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + match self + .facts + .find_by_id(task) + .await + .map_err(|e| e.to_string())? + { + Some(TaskFact { + task: stored_task, + owner: stored, + fact: Fact::Accepted { .. }, + }) if stored == owner && stored_task == task => Ok(()), + _ => Err("task is absent or belongs to another owner".into()), + } + } + + /// Only a supervisor that has observed execution ending calls this. A cancellation + /// request alone is not an end. Competing endings return the durable winner. + pub async fn finish(&self, task: Uuid, owner: Uuid, end: TaskEnd) -> Result { + self.authorize(task, owner).await?; + let id = Uuid::new_v5(&task, b"terminal"); + let row = TaskFact { + task, + owner, + fact: Fact::Ended(end.clone()), + }; + match self.facts.save(id, &row).await { + Ok(()) => Ok(end), + Err(write_error) => match self.facts.find_by_id(id).await.map_err(|e| e.to_string())? { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Ended(winner), + }) if stored_task == task && stored_owner == owner => Ok(winner), + // Never reinterpret an arbitrary store failure as a successful completion. + _ => Err(write_error.to_string()), + }, + } + } + + pub async fn pending(&self, task: Uuid, owner: Uuid) -> Result, String> { + self.authorize(task, owner).await?; + let delivered = self + .facts + .find_by_id(Uuid::new_v5(&task, b"delivered")) + .await + .map_err(|e| e.to_string())?; + match delivered { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Delivered, + }) if stored_task == task && stored_owner == owner => return Ok(None), + Some(_) => return Err("task delivery fact has an invalid identity or shape".into()), + None => {} + } + match self + .facts + .find_by_id(Uuid::new_v5(&task, b"terminal")) + .await + .map_err(|e| e.to_string())? + { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Ended(end), + }) if stored_task == task && stored_owner == owner => Ok(Some(end)), + None => Ok(None), + _ => Err("task terminal fact has an invalid identity or shape".into()), + } + } + + /// Called only after the sink durably consumes the terminal fact. A repeated delivery + /// uses the same task id; the sink must deduplicate before acknowledging here. + pub async fn acknowledge(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + self.authorize(task, owner).await?; + let terminal = self + .facts + .find_by_id(Uuid::new_v5(&task, b"terminal")) + .await + .map_err(|e| e.to_string())?; + if !matches!( + terminal, + Some(TaskFact { + task: stored_task, owner: stored_owner, fact: Fact::Ended(_), + }) if stored_task == task && stored_owner == owner + ) { + return Err("cannot acknowledge a task without a terminal fact".into()); + } + let id = Uuid::new_v5(&task, b"delivered"); + let row = TaskFact { + task, + owner, + fact: Fact::Delivered, + }; + match self.facts.save(id, &row).await { + Ok(()) => Ok(()), + Err(error) => match self.facts.find_by_id(id).await.map_err(|e| e.to_string())? { + Some(stored) if stored == row => Ok(()), + _ => Err(error.to_string()), + }, + } + } + + /// Reconstruct delivery from durable ownership, never from remembered handles. + /// This scan is not a live subscription: concurrent inserts are picked up by the + /// next sweep. Notification triggers and boot recovery both start a fresh sweep. + pub async fn pending_page( + &self, + owner: Uuid, + after: Option, + limit: usize, + ) -> Result { + if limit == 0 { + return Err("task reconciliation page must be nonempty".into()); + } + let mut query = QueryBuilder::new(TaskFact::COLLECTION) + .filter_eq("owner", owner.to_string()) + .sort_asc("id") + .limit(limit); + if let Some(cursor) = after { + query = query.filter("id", QueryOperator::Gt(Value::String(cursor.to_string()))); + } + let rows = self + .facts + .find_matching(query.build()) + .await + .map_err(|e| e.to_string())?; + let exhausted = rows.len() < limit; + let next = rows.last().map(|(id, _)| *id); + let mut ends = Vec::new(); + for (id, row) in rows { + if row.owner != owner { + return Err("task owner query returned another owner".into()); + } + if matches!(row.fact, Fact::Accepted { .. }) { + if id != row.task { + return Err("task acceptance has an invalid identity".into()); + } + if let Some(end) = self.pending(row.task, owner).await? { + ends.push((row.task, end)); + } + } + } + Ok(PendingPage { + ends, + after: next, + exhausted, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn concurrent_ends_survive_reopen_and_delivery_retry() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let first = TaskLedger::new(adapter.clone()).await?; + let second = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = first.accept(owner, "code/shell".into()).await?; + assert!(first.acknowledge(task, owner).await.is_err()); + let (a, b) = tokio::join!( + first.finish(task, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))), + second.finish(task, owner, TaskEnd::Stopped), + ); + let winner = a?; + assert_eq!(winner, b?); + drop(first); + drop(second); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.pending(task, owner).await?, Some(winner.clone())); + let page = reopened.pending_page(owner, None, 10).await?; + assert_eq!(page.ends, vec![(task, winner.clone())]); + assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); + assert!(reopened.pending(task, Uuid::new_v4()).await.is_err()); + reopened.acknowledge(task, owner).await?; + reopened.acknowledge(task, owner).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + Ok(()) + } + + #[tokio::test] + async fn corrupt_delivery_cannot_hide_an_unconsumed_end() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let task = ledger.accept(owner, "code/shell".into()).await?; + ledger.finish(task, owner, TaskEnd::Stopped).await?; + ledger + .facts + .save( + Uuid::new_v5(&task, b"delivered"), + &TaskFact { + task, + owner: Uuid::new_v4(), + fact: Fact::Delivered, + }, + ) + .await + .map_err(|e| e.to_string())?; + assert!(ledger.pending(task, owner).await.is_err()); + assert!(ledger.acknowledge(task, owner).await.is_err()); + Ok(()) + } + + #[tokio::test] + async fn replay_pages_cross_empty_pages_without_leaking_other_owners() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let foreign = Uuid::new_v4(); + let consumed = ledger.accept(owner, "consumed".into()).await?; + ledger.finish(consumed, owner, TaskEnd::Stopped).await?; + ledger.acknowledge(consumed, owner).await?; + let pending = ledger.accept(owner, "pending".into()).await?; + ledger + .finish(pending, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))) + .await?; + let other = ledger.accept(foreign, "other".into()).await?; + ledger.finish(other, foreign, TaskEnd::Stopped).await?; + let mut after = None; + let mut found = Vec::new(); + let mut exhausted = false; + // Five facts for this owner, plus the empty last page. This bound also + // catches a cursor that fails to advance on an empty-result page. + for _ in 0..7 { + let page = ledger.pending_page(owner, after, 1).await?; + found.extend(page.ends); + if page.exhausted { + exhausted = true; + break; + } + assert_ne!(page.after, after); + after = page.after; + } + assert!(exhausted); + assert_eq!( + found, + vec![(pending, TaskEnd::Done(TaskOutput::Json(Value::Null)))] + ); + assert!(ledger.pending_page(owner, None, 0).await.is_err()); + Ok(()) + } +} diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs new file mode 100644 index 0000000000..2ee229450b --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -0,0 +1,90 @@ +//! Lossless durable command results. This is storage, not prompt material: consumers +//! budget a reference to the result rather than copying binary bytes into context. + +use crate::runtime::{cell_shapes::HandleRef, CommandResult}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", content = "payload", rename_all = "snake_case")] +pub enum TaskOutput { + Json(Value), + Binary { metadata: Value, data: Vec }, + Handle(HandleRef), +} + +impl TryFrom for TaskOutput { + type Error = String; + + fn try_from(result: CommandResult) -> Result { + match result { + CommandResult::Json(value) => Ok(Self::Json(value)), + CommandResult::Binary { metadata, data } => Ok(Self::Binary { metadata, data }), + CommandResult::Handle(handle) => Ok(Self::Handle(handle)), + CommandResult::Stream(_) => Err(CommandResult::stream_protocol_error()), + CommandResult::Lambda(_) => Err(CommandResult::lambda_protocol_error()), + } + } +} + +impl TryFrom<&CommandResult> for TaskOutput { + type Error = String; + + fn try_from(result: &CommandResult) -> Result { + match result { + CommandResult::Json(value) => Ok(Self::Json(value.clone())), + CommandResult::Binary { metadata, data } => Ok(Self::Binary { + metadata: metadata.clone(), + data: data.clone(), + }), + CommandResult::Handle(handle) => Ok(Self::Handle(handle.clone())), + CommandResult::Stream(_) => Err(CommandResult::stream_protocol_error()), + CommandResult::Lambda(_) => Err(CommandResult::lambda_protocol_error()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::tasks::{TaskEnd, TaskLedger}; + use uuid::Uuid; + + #[tokio::test] + async fn binary_and_handle_survive_ledger_reopen() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let bytes: Vec = (0..=255).collect(); + let binary = TaskOutput::try_from(CommandResult::Binary { + metadata: serde_json::json!({"format": "arbitrary-bytes"}), + data: bytes.clone(), + })?; + assert!(matches!(&binary, TaskOutput::Binary { data, .. } if data == &bytes)); + let handle = TaskOutput::try_from(CommandResult::handle( + "producer", + Uuid::new_v4(), + "producer::Result", + ))?; + assert!(matches!(&handle, TaskOutput::Handle(_))); + let binary_task = ledger.accept(owner, "producer/binary".into()).await?; + let handle_task = ledger.accept(owner, "producer/handle".into()).await?; + ledger + .finish(binary_task, owner, TaskEnd::Done(binary.clone())) + .await?; + ledger + .finish(handle_task, owner, TaskEnd::Done(handle.clone())) + .await?; + drop(ledger); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!( + reopened.pending(binary_task, owner).await?, + Some(TaskEnd::Done(binary)) + ); + assert_eq!( + reopened.pending(handle_task, owner).await?, + Some(TaskEnd::Done(handle)) + ); + Ok(()) + } +} From b355c0625fece80369f546a4db5f1add11b1d9b2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 06:11:36 -0500 Subject: [PATCH 02/88] Retain dispatch effect classification in durable failures --- .../runtime/command_executor/background.rs | 8 ++++- .../src/runtime/command_executor/tests.rs | 34 +++++++++++++++++++ core/continuum-kernel/src/runtime/tasks.rs | 5 ++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index 8c8eecb0be..cfa9349a0c 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -76,7 +76,13 @@ impl CommandExecutor { }); let (end, outcome) = match outcome { Ok((result, output)) => (TaskEnd::Done(output), Ok(result)), - Err(error) => (TaskEnd::Failed(error.message.clone()), Err(error)), + Err(error) => ( + TaskEnd::Failed { + message: error.message.clone(), + outcome: error.outcome, + }, + Err(error), + ), }; if let Err(error) = ledger.finish(handle, owner, end).await { tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); diff --git a/core/continuum-kernel/src/runtime/command_executor/tests.rs b/core/continuum-kernel/src/runtime/command_executor/tests.rs index 9d60d756c0..31cc8b30f0 100644 --- a/core/continuum-kernel/src/runtime/command_executor/tests.rs +++ b/core/continuum-kernel/src/runtime/command_executor/tests.rs @@ -323,6 +323,40 @@ assert_eq!(seen.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn background_failure_retains_effect_classification_after_reopen() -> Result<(), String> { + use crate::runtime::tasks::{TaskEnd, TaskLedger}; + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let registry = Arc::new(ModuleRegistry::new()); + registry.register(Arc::new(CannedModule::answering(Err("handler failed after possible effect".into())))); + let bus = Arc::new(MessageBus::new()); + let mut rx = bus.receiver(); + let executor = Arc::new(CommandExecutor::new(registry).with_message_bus(bus)); + executor.set_task_ledger(ledger)?; + let owner = uuid::Uuid::new_v4(); + for (command, expected) in [ + ("canned/boom", DispatchOutcome::Uncertain), + ("absent/command", DispatchOutcome::NotCommitted), + ] { + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor.dispatch_background(command, serde_json::json!({}), Some(caller)) + .await.map_err(|error| error.message)?; + let event = next_command_completed(&mut rx).await; + assert_eq!(event.handle, Some(handle)); + assert!(!event.success); + let reopened = TaskLedger::new(adapter.clone()).await?; + match reopened.pending(handle, owner).await? { + Some(TaskEnd::Failed { message, outcome }) => { + assert_eq!(outcome, expected); + assert_eq!(Some(message), event.error); + } + other => return Err(format!("expected durable failure, got {other:?}")), + } + } + Ok(()) + } + #[tokio::test] async fn dispatch_emits_completed_event_on_handler_error() { let registry = Arc::new(ModuleRegistry::new()); diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 458fd7b3d6..d0e0e2e6de 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -16,7 +16,10 @@ pub use output::TaskOutput; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TaskEnd { Done(TaskOutput), - Failed(String), + Failed { + message: String, + outcome: super::command_executor::DispatchOutcome, + }, TimedOut, Stopped, Lost, From 9dc011e029d74acf486c1f0abef5fd81037c1bc1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 06:22:57 -0500 Subject: [PATCH 03/88] Project task completion from the durable terminal winner --- .../runtime/command_executor/background.rs | 121 +++++++++++++++--- .../src/runtime/tasks/output.rs | 19 +-- 2 files changed, 111 insertions(+), 29 deletions(-) diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index cfa9349a0c..0d855736a5 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -70,24 +70,25 @@ impl CommandExecutor { )), }; let outcome = outcome.and_then(|result| { - TaskOutput::try_from(&result) - .map(|output| (result, output)) - .map_err(DispatchFailure::uncertain) + TaskOutput::try_from(result).map_err(DispatchFailure::uncertain) }); - let (end, outcome) = match outcome { - Ok((result, output)) => (TaskEnd::Done(output), Ok(result)), - Err(error) => ( - TaskEnd::Failed { - message: error.message.clone(), - outcome: error.outcome, - }, - Err(error), - ), + let end = match outcome { + Ok(output) => TaskEnd::Done(output), + Err(error) => TaskEnd::Failed { + message: error.message, + outcome: error.outcome, + }, }; - if let Err(error) = ledger.finish(handle, owner, end).await { - tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); - return; - } + let winner = match ledger.finish(handle, owner, end).await { + Ok(winner) => winner, + Err(error) => { + tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); + return; + } + }; + // A competing supervisor may have persisted a different terminal first. + // Every delivery must project that durable winner, never this writer's loser. + let outcome = completion(winner); this.emit_command_completed( command.path(), &outcome, @@ -98,3 +99,91 @@ impl CommandExecutor { Ok(handle) } } + +fn completion(end: TaskEnd) -> Result { + match end { + TaskEnd::Done(output) => Ok(output.into()), + TaskEnd::Failed { message, outcome } => Err(DispatchFailure { message, outcome }), + TaskEnd::TimedOut => Err(DispatchFailure::uncertain("task timed out".into())), + TaskEnd::Stopped => Err(DispatchFailure::uncertain("task stopped".into())), + TaskEnd::Lost => Err(DispatchFailure::uncertain("task execution lost".into())), + } +} + +#[cfg(test)] +mod tests { + use super::super::DispatchOutcome; + use super::*; + use crate::runtime::{ + CommandInterceptor, CommandResult, InterceptorOutcome, MessageBus, ModuleRegistry, + }; + + struct GatedResult { + entered: tokio::sync::Notify, + release: tokio::sync::Notify, + } + + #[async_trait::async_trait] + impl CommandInterceptor for GatedResult { + fn name(&self) -> &'static str { + "gated-test-result" + } + async fn try_route( + &self, + _: &str, + _: &Value, + _: Option<&CallerIdentity>, + ) -> Result { + self.entered.notify_one(); + self.release.notified().await; + Ok(InterceptorOutcome::Handled(CommandResult::Json( + Value::Null, + ))) + } + } + + #[tokio::test] + async fn notification_projects_durable_winner_not_competing_result() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let gate = Arc::new(GatedResult { + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + }); + let bus = Arc::new(MessageBus::new()); + let mut events = bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_message_bus(bus) + .with_interceptor(gate.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = Uuid::new_v4(); + let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let task = executor + .dispatch_background("test/result", Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) + .await + .map_err(|error| error.to_string())?; + // Inject another writer's committed terminal; this tests arbitration, + // not permission to declare a running command stopped. + let winner = TaskEnd::Failed { + message: "previous terminal".into(), + outcome: DispatchOutcome::Uncertain, + }; + ledger.finish(task, owner, winner.clone()).await?; + gate.release.notify_one(); + let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) + .await + .map_err(|error| error.to_string())? + .map_err(|error| error.to_string())?; + assert_eq!(event.name, "command:completed"); + assert_eq!(event.payload["handle"], task.to_string()); + assert_eq!(event.payload["success"], false); + assert_eq!(event.payload["error"], "previous terminal"); + assert_eq!(ledger.pending(task, owner).await?, Some(winner)); + Ok(()) + } +} diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs index 2ee229450b..bf46b68afe 100644 --- a/core/continuum-kernel/src/runtime/tasks/output.rs +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -27,19 +27,12 @@ impl TryFrom for TaskOutput { } } -impl TryFrom<&CommandResult> for TaskOutput { - type Error = String; - - fn try_from(result: &CommandResult) -> Result { - match result { - CommandResult::Json(value) => Ok(Self::Json(value.clone())), - CommandResult::Binary { metadata, data } => Ok(Self::Binary { - metadata: metadata.clone(), - data: data.clone(), - }), - CommandResult::Handle(handle) => Ok(Self::Handle(handle.clone())), - CommandResult::Stream(_) => Err(CommandResult::stream_protocol_error()), - CommandResult::Lambda(_) => Err(CommandResult::lambda_protocol_error()), +impl From for CommandResult { + fn from(output: TaskOutput) -> Self { + match output { + TaskOutput::Json(value) => Self::Json(value), + TaskOutput::Binary { metadata, data } => Self::Binary { metadata, data }, + TaskOutput::Handle(handle) => Self::Handle(handle), } } } From 70bc97e36340fb1abd2518bda0a36438d962f533 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 06:42:41 -0500 Subject: [PATCH 04/88] Exercise durable completion after a handler unwinds --- .../runtime/command_executor/background.rs | 102 +++++++++++------- 1 file changed, 63 insertions(+), 39 deletions(-) diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index 0d855736a5..674719cd9e 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -121,6 +121,7 @@ mod tests { struct GatedResult { entered: tokio::sync::Notify, release: tokio::sync::Notify, + unwind: bool, } #[async_trait::async_trait] @@ -136,6 +137,11 @@ mod tests { ) -> Result { self.entered.notify_one(); self.release.notified().await; + if self.unwind { + // Fault injection: exercise the real supervisor's unwind boundary + // without relying on a process-global panic hook or aborting process. + std::panic::resume_unwind(Box::new("injected handler unwind")); + } Ok(InterceptorOutcome::Handled(CommandResult::Json( Value::Null, ))) @@ -143,47 +149,65 @@ mod tests { } #[tokio::test] - async fn notification_projects_durable_winner_not_competing_result() -> Result<(), String> { + async fn terminal_delivery_handles_competing_writers_and_unwinding_handlers( + ) -> Result<(), String> { let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let ledger = Arc::new(TaskLedger::new(adapter).await?); - let gate = Arc::new(GatedResult { - entered: tokio::sync::Notify::new(), - release: tokio::sync::Notify::new(), - }); - let bus = Arc::new(MessageBus::new()); - let mut events = bus.receiver(); - let executor = Arc::new( - CommandExecutor::new(Arc::new(ModuleRegistry::new())) - .with_message_bus(bus) - .with_interceptor(gate.clone()), - ); - executor.set_task_ledger(ledger.clone())?; - let owner = Uuid::new_v4(); - let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); - let task = executor - .dispatch_background("test/result", Value::Null, Some(caller)) - .await - .map_err(|error| error.message)?; - tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) - .await - .map_err(|error| error.to_string())?; - // Inject another writer's committed terminal; this tests arbitration, - // not permission to declare a running command stopped. - let winner = TaskEnd::Failed { - message: "previous terminal".into(), - outcome: DispatchOutcome::Uncertain, - }; - ledger.finish(task, owner, winner.clone()).await?; - gate.release.notify_one(); - let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) - .await - .map_err(|error| error.to_string())? - .map_err(|error| error.to_string())?; - assert_eq!(event.name, "command:completed"); - assert_eq!(event.payload["handle"], task.to_string()); - assert_eq!(event.payload["success"], false); - assert_eq!(event.payload["error"], "previous terminal"); - assert_eq!(ledger.pending(task, owner).await?, Some(winner)); + for unwind in [false, true] { + let gate = Arc::new(GatedResult { + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + unwind, + }); + let bus = Arc::new(MessageBus::new()); + let mut events = bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_message_bus(bus) + .with_interceptor(gate.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = Uuid::new_v4(); + let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let task = executor + .dispatch_background("test/result", Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) + .await + .map_err(|error| error.to_string())?; + // Inject another writer's committed terminal; this tests arbitration, + // not permission to declare a running command stopped. + let winner = TaskEnd::Failed { + message: if unwind { + "background command panicked" + } else { + "previous terminal" + } + .into(), + outcome: DispatchOutcome::Uncertain, + }; + if !unwind { + ledger.finish(task, owner, winner.clone()).await?; + } + gate.release.notify_one(); + let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) + .await + .map_err(|error| error.to_string())? + .map_err(|error| error.to_string())?; + assert_eq!(event.name, "command:completed"); + assert_eq!(event.payload["handle"], task.to_string()); + assert_eq!(event.payload["success"], false); + assert_eq!( + event.payload["error"], + if unwind { + "background command panicked" + } else { + "previous terminal" + } + ); + assert_eq!(ledger.pending(task, owner).await?, Some(winner)); + } Ok(()) } } From c278903db60cd46ae0b6722c88f1e056ff992bba Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 07:01:51 -0500 Subject: [PATCH 05/88] test(kernel): pin terminal arbitration across cancelled storage writes --- core/continuum-kernel/src/runtime/tasks.rs | 2 + .../src/runtime/tasks/races.rs | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 core/continuum-kernel/src/runtime/tasks/races.rs diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index d0e0e2e6de..6f58f38904 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -12,6 +12,8 @@ use uuid::Uuid; mod output; pub use output::TaskOutput; +#[cfg(test)] +mod races; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TaskEnd { diff --git a/core/continuum-kernel/src/runtime/tasks/races.rs b/core/continuum-kernel/src/runtime/tasks/races.rs new file mode 100644 index 0000000000..93c443ea35 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/races.rs @@ -0,0 +1,45 @@ +//! A cancelled writer may still commit: storage owns the in-flight write. +use super::*; +use crate::orm::gated_adapter::GatedAdapter; + +async fn notified(signal: &tokio::sync::Notify) -> Result<(), String> { + tokio::time::timeout(std::time::Duration::from_secs(5), signal.notified()) + .await + .map_err(|error| error.to_string()) +} + +#[tokio::test] +async fn cancelled_terminal_write_cannot_replace_winner_or_resurrect_delivery() -> Result<(), String> +{ + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let gated = Arc::new(GatedAdapter::new(adapter.clone())); + let delayed = Arc::new(TaskLedger::new(gated.clone()).await?); + let current = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = current.accept(owner, "code/shell".into()).await?; + let pause = gated.pause_next_write(); + let writer = tokio::spawn(async move { delayed.finish(task, owner, TaskEnd::Lost).await }); + notified(&pause.entered).await?; + writer.abort(); + assert!(matches!(writer.await, Err(error) if error.is_cancelled())); + + // The competing supervisor observed the actual execution ending. Its result + // reaches the sink while the abandoned storage operation is still pending. + let winner = TaskEnd::Done(TaskOutput::Json(serde_json::json!({"saved": true}))); + assert_eq!(current.finish(task, owner, winner.clone()).await?, winner); + assert_eq!(current.pending(task, owner).await?, Some(winner.clone())); + current.acknowledge(task, owner).await?; + pause.release.notify_one(); + notified(&pause.done).await?; + drop(current); + + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); + assert_eq!(reopened.pending(task, owner).await?, None); + assert!(reopened + .pending_page(owner, None, 10) + .await? + .ends + .is_empty()); + Ok(()) +} From 19147f4e8c696acddc380ab1d2c34e2e2931c526 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 07:11:20 -0500 Subject: [PATCH 06/88] test(kernel): keep task race regression in the single test module --- core/continuum-kernel/src/runtime/tasks.rs | 45 ++++++++++++++++++- .../src/runtime/tasks/races.rs | 45 ------------------- 2 files changed, 43 insertions(+), 47 deletions(-) delete mode 100644 core/continuum-kernel/src/runtime/tasks/races.rs diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 6f58f38904..097102174d 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -12,8 +12,6 @@ use uuid::Uuid; mod output; pub use output::TaskOutput; -#[cfg(test)] -mod races; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TaskEnd { @@ -352,4 +350,47 @@ mod tests { assert!(ledger.pending_page(owner, None, 0).await.is_err()); Ok(()) } + use crate::orm::gated_adapter::GatedAdapter; + + async fn notified(signal: &tokio::sync::Notify) -> Result<(), String> { + tokio::time::timeout(std::time::Duration::from_secs(5), signal.notified()) + .await + .map_err(|error| error.to_string()) + } + + #[tokio::test] + async fn cancelled_terminal_write_cannot_replace_winner_or_resurrect_delivery( + ) -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let gated = Arc::new(GatedAdapter::new(adapter.clone())); + let delayed = Arc::new(TaskLedger::new(gated.clone()).await?); + let current = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = current.accept(owner, "code/shell".into()).await?; + let pause = gated.pause_next_write(); + let writer = tokio::spawn(async move { delayed.finish(task, owner, TaskEnd::Lost).await }); + notified(&pause.entered).await?; + writer.abort(); + assert!(matches!(writer.await, Err(error) if error.is_cancelled())); + + // The competing supervisor observed the actual execution ending. Its result + // reaches the sink while the abandoned storage operation is still pending. + let winner = TaskEnd::Done(TaskOutput::Json(serde_json::json!({"saved": true}))); + assert_eq!(current.finish(task, owner, winner.clone()).await?, winner); + assert_eq!(current.pending(task, owner).await?, Some(winner.clone())); + current.acknowledge(task, owner).await?; + pause.release.notify_one(); + notified(&pause.done).await?; + drop(current); + + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); + assert_eq!(reopened.pending(task, owner).await?, None); + assert!(reopened + .pending_page(owner, None, 10) + .await? + .ends + .is_empty()); + Ok(()) + } } diff --git a/core/continuum-kernel/src/runtime/tasks/races.rs b/core/continuum-kernel/src/runtime/tasks/races.rs deleted file mode 100644 index 93c443ea35..0000000000 --- a/core/continuum-kernel/src/runtime/tasks/races.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! A cancelled writer may still commit: storage owns the in-flight write. -use super::*; -use crate::orm::gated_adapter::GatedAdapter; - -async fn notified(signal: &tokio::sync::Notify) -> Result<(), String> { - tokio::time::timeout(std::time::Duration::from_secs(5), signal.notified()) - .await - .map_err(|error| error.to_string()) -} - -#[tokio::test] -async fn cancelled_terminal_write_cannot_replace_winner_or_resurrect_delivery() -> Result<(), String> -{ - let (adapter, _directory) = crate::orm::store::fresh_adapter().await; - let gated = Arc::new(GatedAdapter::new(adapter.clone())); - let delayed = Arc::new(TaskLedger::new(gated.clone()).await?); - let current = TaskLedger::new(adapter.clone()).await?; - let owner = Uuid::new_v4(); - let task = current.accept(owner, "code/shell".into()).await?; - let pause = gated.pause_next_write(); - let writer = tokio::spawn(async move { delayed.finish(task, owner, TaskEnd::Lost).await }); - notified(&pause.entered).await?; - writer.abort(); - assert!(matches!(writer.await, Err(error) if error.is_cancelled())); - - // The competing supervisor observed the actual execution ending. Its result - // reaches the sink while the abandoned storage operation is still pending. - let winner = TaskEnd::Done(TaskOutput::Json(serde_json::json!({"saved": true}))); - assert_eq!(current.finish(task, owner, winner.clone()).await?, winner); - assert_eq!(current.pending(task, owner).await?, Some(winner.clone())); - current.acknowledge(task, owner).await?; - pause.release.notify_one(); - notified(&pause.done).await?; - drop(current); - - let reopened = TaskLedger::new(adapter).await?; - assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); - assert_eq!(reopened.pending(task, owner).await?, None); - assert!(reopened - .pending_page(owner, None, 10) - .await? - .ends - .is_empty()); - Ok(()) -} From 29c9ffe46207a7fe743df2f3770fc51555419ed1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 12:26:39 -0500 Subject: [PATCH 07/88] feat(tasks): centralize owner consumption before acknowledgement --- core/continuum-kernel/src/runtime/tasks.rs | 2 + .../src/runtime/tasks/delivery.rs | 88 +++++++++++++ .../src/runtime/tasks/delivery/tests.rs | 117 ++++++++++++++++++ 3 files changed, 207 insertions(+) create mode 100644 core/continuum-kernel/src/runtime/tasks/delivery.rs create mode 100644 core/continuum-kernel/src/runtime/tasks/delivery/tests.rs diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 097102174d..1b12250a39 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -12,6 +12,8 @@ use uuid::Uuid; mod output; pub use output::TaskOutput; +mod delivery; +pub use delivery::{DeliveryError, DeliveryPage, TaskOwnerSink}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TaskEnd { diff --git a/core/continuum-kernel/src/runtime/tasks/delivery.rs b/core/continuum-kernel/src/runtime/tasks/delivery.rs new file mode 100644 index 0000000000..3bcac502d8 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/delivery.rs @@ -0,0 +1,88 @@ +//! The shared owner-delivery seam from HER-TASKS T2. Notifications only request a +//! reconciliation; durable ownership supplies the results and consumption precedes ACK. +use super::{TaskEnd, TaskLedger}; +use std::num::NonZeroUsize; +use uuid::Uuid; + +/// Implemented by the owner of the recipient's durable state, never by a transient +/// workspace or a notification channel. Success means the exact terminal result and +/// its outstanding wake obligation are durable. Replays must deduplicate by task ID. +#[async_trait::async_trait] +pub trait TaskOwnerSink: Send + Sync { + type Error: std::error::Error + Send + Sync + 'static; + + async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error>; +} + +/// Failure retains its boundary: a sink refusal cannot masquerade as an ACK failure, +/// and a failed ACK can be replayed after consumption without repeating its effects. +#[derive(Debug)] +pub enum DeliveryError { + Read(String), + Consume { task: Uuid, source: E }, + Acknowledge { task: Uuid, message: String }, +} + +impl std::fmt::Display for DeliveryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Read(message) => write!(f, "task replay read failed: {message}"), + Self::Consume { task, source } => write!(f, "task {task} consumption failed: {source}"), + Self::Acknowledge { task, message } => { + write!(f, "task {task} acknowledgement failed: {message}") + } + } + } +} + +impl std::error::Error for DeliveryError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Consume { source, .. } => Some(source), + Self::Read(_) | Self::Acknowledge { .. } => None, + } + } +} + +pub struct DeliveryPage { + pub acknowledged: usize, + pub after: Option, + pub exhausted: bool, +} + +impl TaskLedger { + /// Deliver one bounded storage page. The existing lifecycle/scheduler owns when to + /// continue or restart a sweep; this seam creates no timer, listener or executor. + /// On failure restart the sweep: previously acknowledged tasks are excluded, while + /// an unacknowledged consumption is replayed into the sink's durable deduplication. + pub async fn deliver_page( + &self, + owner: Uuid, + after: Option, + limit: NonZeroUsize, + sink: &S, + ) -> Result> { + let page = self + .pending_page(owner, after, limit.get()) + .await + .map_err(DeliveryError::Read)?; + let mut acknowledged = 0; + for (task, end) in page.ends { + sink.consume(owner, task, &end) + .await + .map_err(|source| DeliveryError::Consume { task, source })?; + self.acknowledge(task, owner) + .await + .map_err(|message| DeliveryError::Acknowledge { task, message })?; + acknowledged += 1; + } + Ok(DeliveryPage { + acknowledged, + after: page.after, + exhausted: page.exhausted, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs new file mode 100644 index 0000000000..ca1904fa33 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -0,0 +1,117 @@ +//! The delivery boundary cannot acknowledge an unconsumed terminal result. +#![cfg(test)] +use super::*; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; + +struct Sink { + ledger: Arc, + refuse: AtomicBool, + seen: parking_lot::Mutex>, +} + +#[async_trait::async_trait] +impl TaskOwnerSink for Sink { + type Error = std::io::Error; + + async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error> { + let pending = self + .ledger + .pending(task, owner) + .await + .map_err(std::io::Error::other)?; + assert_eq!(pending.as_ref(), Some(end), "consumption must precede ACK"); + if self.refuse.load(Ordering::SeqCst) { + return Err(std::io::Error::other("injected persistence refusal")); + } + self.seen.lock().push((owner, task, end.clone())); + Ok(()) + } +} + +#[tokio::test] +async fn refused_consumption_remains_pending_and_replay_needs_no_registered_handle( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let owner = Uuid::new_v4(); + let task = ledger.accept(owner, "build".into()).await?; + ledger.finish(task, owner, TaskEnd::Stopped).await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(true), + seen: Default::default(), + }; + let limit = NonZeroUsize::new(32).expect("test: nonzero page"); + assert!( + matches!(ledger.deliver_page(owner, None, limit, &sink).await, Err(DeliveryError::Consume { task: failed, .. }) if failed == task) + ); + assert_eq!(ledger.pending(task, owner).await?, Some(TaskEnd::Stopped)); + assert!(sink.seen.lock().is_empty()); + + let reopened = TaskLedger::new(adapter).await?; + sink.refuse.store(false, Ordering::SeqCst); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); + assert_eq!(*sink.seen.lock(), vec![(owner, task, TaskEnd::Stopped)]); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert_eq!(sink.seen.lock().len(), 1); + Ok(()) +} + +#[tokio::test] +async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let owner = Uuid::new_v4(); + let foreign = Uuid::new_v4(); + let mine = ledger.accept(owner, "mine".into()).await?; + let theirs = ledger.accept(foreign, "theirs".into()).await?; + ledger.finish(mine, owner, TaskEnd::Lost).await?; + ledger.finish(theirs, foreign, TaskEnd::Stopped).await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(false), + seen: Default::default(), + }; + let mut after = None; + let mut exhausted = false; + // Acceptance, terminal and optional ACK rows plus a final empty page. + for _ in 0..4 { + let page = ledger + .deliver_page( + owner, + after, + NonZeroUsize::new(1).expect("test: nonzero"), + &sink, + ) + .await?; + if page.exhausted { + exhausted = true; + break; + } + assert_ne!(page.after, after); + after = page.after; + } + assert!(exhausted); + assert_eq!(*sink.seen.lock(), vec![(owner, mine, TaskEnd::Lost)]); + assert_eq!( + ledger.pending(theirs, foreign).await?, + Some(TaskEnd::Stopped) + ); + Ok(()) +} From a52865fcfb8c34cae5d28b188eca2a98a2b1c6eb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 13:00:36 -0500 Subject: [PATCH 08/88] Persist owner task references and wake obligations through resident checkpoints --- .../src/cognition/persona_workspace.rs | 3 + .../persona_workspace/own_speech_persisted.rs | 25 ++- .../root_acting_workspace.rs | 10 +- .../persona_workspace/task_consumption.rs | 43 ++++++ .../src/cognition/persona_workspace/tests.rs | 2 + .../tests/task_consumption.rs | 99 ++++++++++++ .../src/cognition/working_memory.rs | 6 + .../cognition/working_memory/continuity.rs | 2 + .../src/cognition/working_memory/ledger.rs | 2 + .../cognition/working_memory/task_results.rs | 145 ++++++++++++++++++ .../cognition/working_memory/tests/trail.rs | 1 + core/continuum-kernel/src/runtime/tasks.rs | 11 ++ .../src/runtime/tasks/output.rs | 5 +- 13 files changed, 346 insertions(+), 8 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs create mode 100644 core/continuum-cognition/src/cognition/working_memory/task_results.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index c09f648cef..ffc6fd6e7f 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -56,5 +56,8 @@ mod acting_hands; pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; +mod task_consumption; +pub use task_consumption::TaskConsumptionError; mod own_speech_persisted; +pub use own_speech_persisted::VolatileReceipt; pub(crate) use own_speech_persisted::*; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index 0c404298d0..2151147b5f 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -40,6 +40,21 @@ pub(super) fn volatile_path(persona_id: Uuid) -> std::io::Result, +} + +impl VolatileReceipt { + pub fn owner(&self) -> Uuid { self.owner } + pub fn incarnation(&self) -> Uuid { self.incarnation } + pub fn consumed_tasks(&self) -> &[Uuid] { &self.consumed_tasks } +} + /// Persist the volatile tier — atomic tmp+rename so a crash mid-write never /// leaves a torn file. Called under the registry checkpoint gate, on a blocking /// worker. Failures propagate to both periodic and shutdown lifecycle receipts. @@ -48,7 +63,7 @@ pub(super) fn save_volatile( reason: SaveReason, staged_deadline: Option, wm: &super::super::working_memory::WorkingMemory, -) -> std::io::Result<()> { +) -> std::io::Result { let path = volatile_path(persona_id)?; let _checkpoint_lock = checkpoint_adoption::lock_checkpoint(&path, true)?; let mut snapshot = wm.snapshot(); @@ -75,6 +90,11 @@ pub(super) fn save_volatile( snapshot.acting_card = wm .peek_restored_acting_card() .or_else(|| acting_card_of(persona_id)); + let receipt = VolatileReceipt { + owner: persona_id, + incarnation: wm.incarnation(), + consumed_tasks: snapshot.task_results.consumed_ids(), + }; let persisted = PersistedVolatile { wm: snapshot, own_speech: OwnSpeechPersisted::ByRoom(super::super::deliberation_budget::own_speech_by_room( @@ -91,7 +111,8 @@ pub(super) fn save_volatile( file.sync_all()?; drop(file); std::fs::rename(&tmp, &path)?; - checkpoint_adoption::sync_parent(&path) + checkpoint_adoption::sync_parent(&path)?; + Ok(receipt) } /// Load the previous life's volatile tier under the same owner lock as saves diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index de866ea044..4b82104557 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -347,7 +347,7 @@ impl PersonaWorkspaceRegistry { /// Periodic crash checkpoint. A busy writer coalesces this tick; no queue /// of blocking jobs accumulates behind slow storage. - pub fn checkpoint_volatile_all(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn checkpoint_volatile_all(&self) -> Vec<(Uuid, std::io::Result)> { let Some(stopped) = self.checkpoint_stopped.try_lock() else { return Vec::new(); }; @@ -358,7 +358,7 @@ impl PersonaWorkspaceRegistry { } /// Explicit save is repeatable and leaves periodic persistence running. - pub fn flush_volatile_all(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn flush_volatile_all(&self) -> Vec<(Uuid, std::io::Result)> { let _checkpoint = self.checkpoint_stopped.lock(); self.write_volatile_all(SaveReason::Seam) } @@ -367,7 +367,7 @@ impl PersonaWorkspaceRegistry { /// then snapshot CURRENT residents. The caller must quiesce mutation first. /// Blocking work can outlive an async timeout; callers must receipt that as /// uncertain, never successful. No later periodic write can overtake this one. - pub fn stop_volatile_checkpoints(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn stop_volatile_checkpoints(&self) -> Vec<(Uuid, std::io::Result)> { let mut stopped = self.checkpoint_stopped.lock(); *stopped = true; self.write_volatile_all(SaveReason::Seam) @@ -375,7 +375,7 @@ impl PersonaWorkspaceRegistry { // Only called under checkpoint_stopped. The cycle lookup lock is released // before snapshot/serialization/IO, keeping room turns and roster reads free. - pub(super) fn write_volatile_all(&self, reason: SaveReason) -> Vec<(Uuid, std::io::Result<()>)> { + pub(super) fn write_volatile_all(&self, reason: SaveReason) -> Vec<(Uuid, std::io::Result)> { // ONE staged-read budget for the whole seam, shared by every resident, so the save // phase is bounded by the phase and not by resident count; a periodic write has none. let staged_deadline = matches!(reason, SaveReason::Seam) @@ -436,7 +436,7 @@ impl PersonaWorkspaceRegistry { let test_home = crate::paths::NativeHomeOverride::current(); #[cfg(test)] let test_home = &test_home; - let results: Vec<(Uuid, std::io::Result<()>)> = std::thread::scope(|scope| { + let results: Vec<(Uuid, std::io::Result)> = std::thread::scope(|scope| { let handles: Vec<_> = residents .into_iter() .map(|(id, memory)| { diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs new file mode 100644 index 0000000000..6d0f43d187 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -0,0 +1,43 @@ +//! Durable task consumption uses the registered resident and its existing checkpoint +//! owner. No constructor-owned writer or remembered dispatch handle participates. +use super::*; +use continuum_kernel::runtime::tasks::TaskEnd; + +#[derive(Debug, thiserror::Error)] +pub enum TaskConsumptionError { + #[error("resident checkpoint admission is closed")] + Stopped, + #[error("task owner {0} is not a registered resident")] + Absent(Uuid), + #[error(transparent)] + Receipt(#[from] super::super::working_memory::TaskReceiptError), + #[error("task consumption checkpoint failed: {0}")] + Checkpoint(#[from] std::io::Error), +} + +impl PersonaWorkspaceRegistry { + /// Success receipts exactly the snapshot containing this end and its wake + /// obligation. A replay also checkpoints: a prior insertion may have failed IO. + /// Registration/replacement is excluded until the snapshot is committed; the + /// next incarnation restores it through the existing registration path. + pub fn consume_task_end( + &self, + owner: Uuid, + task: Uuid, + end: TaskEnd, + ) -> Result { + let stopped = self.checkpoint_stopped.lock(); + if *stopped { + return Err(TaskConsumptionError::Stopped); + } + let _assembly = self.assembly.lock(); + let memory = self + .cycles + .lock() + .get(&owner) + .map(|resident| Arc::clone(&resident.working_memory)) + .ok_or(TaskConsumptionError::Absent(owner))?; + memory.stage_task_end(task, end)?; + Ok(save_volatile(owner, SaveReason::Periodic, None, &memory)?) + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs index 9e657b1452..cf5b4125f9 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs @@ -19,3 +19,5 @@ mod final_checkpoint_drains_admitted_periodic_writer_before_ack; use final_checkpoint_drains_admitted_periodic_writer_before_ack::*; mod gated_grounding; use gated_grounding::*; + +mod task_consumption; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs new file mode 100644 index 0000000000..ecb1e05003 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -0,0 +1,99 @@ +use super::*; +use continuum_kernel::runtime::tasks::TaskEnd; + +#[tokio::test] +async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let receipt = registry.consume_task_end(owner, task, TaskEnd::Stopped)?; + assert_eq!(receipt.owner(), owner); + assert_eq!(receipt.consumed_tasks(), &[task]); + let old_incarnation = receipt.incarnation(); + let on_disk = load_volatile(owner)?.ok_or("checkpoint absent")?; + let restored = WorkingMemory::new(8); + restored.restore(on_disk.wm); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + registry.register_from_cfg(cfg_for(owner))?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert_ne!(memory.incarnation(), old_incarnation); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert!(memory.admit_task_wake(task)); + let replay = registry.consume_task_end(owner, task, TaskEnd::Stopped)?; + assert_eq!(replay.incarnation(), memory.incarnation()); + let next = WorkingMemory::new(8); + next.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(next.pending_task_wakes().is_empty()); + assert_eq!(next.snapshot().task_results.consumed_ids(), vec![task]); + Ok(()) +} + +#[tokio::test] +async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + assert!( + matches!(registry.consume_task_end(owner, task, TaskEnd::Lost), Err(TaskConsumptionError::Absent(id)) if id == owner) + ); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_end(owner, task, TaskEnd::Lost)?; + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.consume_task_end(owner, task, TaskEnd::Stopped), + Err(TaskConsumptionError::Receipt(_)) + )); + assert_eq!(std::fs::read(&path)?, before); + for (_, result) in registry.stop_volatile_checkpoints() { + result?; + } + let before = std::fs::read(&path)?; + assert!(matches!( + registry.consume_task_end(owner, Uuid::new_v4(), TaskEnd::Lost), + Err(TaskConsumptionError::Stopped) + )); + assert_eq!(std::fs::read(&path)?, before); + Ok(()) +} + +#[tokio::test] +async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + for (_, result) in registry.flush_volatile_all() { + result?; + } + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + // A directory at the writer's temp-file path forces a real filesystem refusal. + // The existing committed checkpoint is never removed or replaced by the test. + let obstruction = path.with_extension("json.tmp"); + std::fs::create_dir(&obstruction)?; + assert!(matches!( + registry.consume_task_end(owner, task, TaskEnd::Lost), + Err(TaskConsumptionError::Checkpoint(_)) + )); + assert_eq!(std::fs::read(&path)?, before); + std::fs::remove_dir(&obstruction)?; + let receipt = registry.consume_task_end(owner, task, TaskEnd::Lost)?; + assert_eq!(receipt.consumed_tasks(), &[task]); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 381eeef95d..05908069cc 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -334,6 +334,8 @@ pub struct WorkingMemory { /// has read: her cursors, kept here because the history that carried each page is the /// first thing a tight window's fit drops ([`super::open_views`]). open_views: Mutex, + task_results: Mutex, + incarnation: Uuid, /// Her learned tool head: every call she makes is noted here, and the deliberation faculty /// reads and adopts the head at each epoch turnover ([`super::tool_head`]). tool_head: Arc, @@ -499,6 +501,8 @@ pub struct VolatileSnapshot { /// written before this field. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub open_views: Vec, + /// Consumed terminal references and outstanding wake obligations, checkpointed together. + pub(crate) task_results: task_results::TaskResults, } impl VolatileSnapshot { @@ -693,6 +697,8 @@ pub struct WmEntry { mod action_log; mod continuity; +mod task_results; +pub use task_results::{TaskReceiptConflict, TaskReceiptError}; mod faculty; mod ledger; mod perception; diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 44219f0692..f5e59e4c38 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -233,6 +233,7 @@ impl WorkingMemory { context_view: self.view.lock().clone(), receipt_children: self.receipt_children.lock().clone(), open_views: self.open_views.lock().saved(), + task_results: self.task_results.lock().clone(), } } @@ -261,6 +262,7 @@ impl WorkingMemory { } pub fn restore(&self, mut snap: VolatileSnapshot) { + *self.task_results.lock() = snap.task_results.clone(); // Read before any field moves out of the snapshot below. let records = snap.action_records(); // A restored mind keeps only the newest concern evidence its existing diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f378e933cf..99396f9542 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -69,6 +69,8 @@ impl WorkingMemory { receipt_children: Mutex::new(BTreeMap::new()), active_from_seq: AtomicU64::new(0), open_views: Mutex::new(Default::default()), + task_results: Mutex::new(Default::default()), + incarnation: Uuid::new_v4(), tool_head: Default::default(), } } diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs new file mode 100644 index 0000000000..7815c96023 --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -0,0 +1,145 @@ +//! Owner consumption state. Notification delivery is not wake admission, and +//! neither an in-memory insertion nor this snapshot alone acknowledges the ledger. +use super::WorkingMemory; +use continuum_kernel::runtime::tasks::TaskEnd; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use uuid::Uuid; + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub(crate) struct TaskResults(BTreeMap); + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ConsumedEnd { + fingerprint: [u8; 32], + wake_pending: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("task {task} was already consumed with a different terminal result")] +pub struct TaskReceiptConflict { + pub task: Uuid, +} + +#[derive(Debug, thiserror::Error)] +pub enum TaskReceiptError { + #[error(transparent)] + Conflict(#[from] TaskReceiptConflict), + #[error("terminal fingerprint encoding failed: {0}")] + Encoding(#[from] serde_json::Error), +} + +impl WorkingMemory { + /// Identity of this live memory instance; restoration creates a new incarnation. + pub fn incarnation(&self) -> Uuid { + self.incarnation + } + + /// Stage a terminal reference and its wake obligation atomically. Whole output + /// remains in TaskLedger; the fingerprint detects conflicting replay without + /// duplicating binary/JSON bodies in every resident checkpoint. The registry must + /// checkpoint this exact state before acknowledging consumption to the ledger. + /// A replay is inert, including after its wake has already been admitted. + pub fn stage_task_end(&self, task: Uuid, end: TaskEnd) -> Result { + let fingerprint: [u8; 32] = Sha256::digest(serde_json::to_vec(&end)?).into(); // Disk boundary: terminal integrity fingerprint persisted instead of duplicating the ledger output. + let mut results = self.task_results.lock(); + match results.0.entry(task) { + std::collections::btree_map::Entry::Occupied(entry) => { + if entry.get().fingerprint != fingerprint { + return Err(TaskReceiptConflict { task }.into()); + } + Ok(false) + } + std::collections::btree_map::Entry::Vacant(entry) => { + entry.insert(ConsumedEnd { + fingerprint, + wake_pending: true, + }); + Ok(true) + } + } + } + + pub fn pending_task_wakes(&self) -> Vec { + self.task_results + .lock() + .0 + .iter() + .filter_map(|(task, entry)| entry.wake_pending.then_some(*task)) + .collect() + } + + /// Called only when the owning turn admits this task's wake. Sending to a + /// channel, reading output, and acknowledging the ledger are not admission. + /// Returns false if no pending obligation exists; never fabricates a receipt. + pub fn admit_task_wake(&self, task: Uuid) -> bool { + let mut results = self.task_results.lock(); + match results.0.get_mut(&task) { + Some(entry) if entry.wake_pending => { + entry.wake_pending = false; + true + } + Some(_) | None => false, + } + } +} + +impl TaskResults { + /// A checkpoint receipt must use IDs from its serialized snapshot, not from + /// a second read of mutable working memory after IO completes. + pub(crate) fn consumed_ids(&self) -> Vec { + self.0.keys().copied().collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn forgotten_task_survives_snapshot_and_replay_does_not_rearm_admitted_wake() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + assert!(memory + .stage_task_end(task, TaskEnd::Stopped) + .expect("initial end")); + let snapshot = memory.snapshot(); + let encoded = serde_json::to_vec(&snapshot).expect("encode checkpoint"); + let restored = WorkingMemory::new(8); + restored.restore(serde_json::from_slice(&encoded).expect("decode checkpoint")); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + assert!(!restored + .stage_task_end(task, TaskEnd::Stopped) + .expect("identical replay")); + assert!(restored.admit_task_wake(task)); + assert!(!restored + .stage_task_end(task, TaskEnd::Stopped) + .expect("replay after admission")); + assert!(restored.pending_task_wakes().is_empty()); + let next_life = WorkingMemory::new(8); + next_life.restore(restored.snapshot()); + assert!(next_life.pending_task_wakes().is_empty()); + assert_eq!(next_life.snapshot().task_results.consumed_ids(), vec![task]); + } + + #[test] + fn conflicting_end_is_refused_and_later_arrival_is_not_in_prior_snapshot() { + let memory = WorkingMemory::new(8); + let first = Uuid::new_v4(); + let later = Uuid::new_v4(); + memory + .stage_task_end(first, TaskEnd::Lost) + .expect("first end"); + let snapshot = memory.snapshot(); + memory + .stage_task_end(later, TaskEnd::Stopped) + .expect("later end"); + assert_eq!(snapshot.task_results.consumed_ids(), vec![first]); + assert!(matches!(memory.stage_task_end(first, TaskEnd::Stopped), + Err(TaskReceiptError::Conflict(TaskReceiptConflict { task })) if task == first)); + assert_eq!(memory.pending_task_wakes().len(), 2); + assert!(!memory.admit_task_wake(Uuid::new_v4())); + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 113c2d2426..e9a4acc5c9 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -308,6 +308,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { context_view: None, receipt_children: Default::default(), open_views: Vec::new(), + task_results: Default::default(), }); assert!(quiet.recent().is_empty(), "an empty snapshot restores an empty window"); let q = quiet.pinned_facts(); diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 1b12250a39..45fd15cb88 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -162,6 +162,17 @@ impl TaskLedger { Some(_) => return Err("task delivery fact has an invalid identity or shape".into()), None => {} } + self.read_terminal(task, owner).await + } + + /// Resolve the durable terminal even after delivery acknowledgement. Resident + /// checkpoints carry references; the ledger remains the one output owner. + pub async fn terminal(&self, task: Uuid, owner: Uuid) -> Result, String> { + self.authorize(task, owner).await?; + self.read_terminal(task, owner).await + } + + async fn read_terminal(&self, task: Uuid, owner: Uuid) -> Result, String> { match self .facts .find_by_id(Uuid::new_v5(&task, b"terminal")) diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs index bf46b68afe..178c94870c 100644 --- a/core/continuum-kernel/src/runtime/tasks/output.rs +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -68,10 +68,13 @@ mod tests { ledger .finish(handle_task, owner, TaskEnd::Done(handle.clone())) .await?; + ledger.acknowledge(binary_task, owner).await?; + assert_eq!(ledger.pending(binary_task, owner).await?, None); + assert!(ledger.terminal(binary_task, Uuid::new_v4()).await.is_err()); drop(ledger); let reopened = TaskLedger::new(adapter).await?; assert_eq!( - reopened.pending(binary_task, owner).await?, + reopened.terminal(binary_task, owner).await?, Some(TaskEnd::Done(binary)) ); assert_eq!( From 982a8837905a1c7e89afdfc7ee2ebf09472c3075 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 13:07:09 -0500 Subject: [PATCH 09/88] Connect resident checkpoint consumption to ledger delivery contract --- .../src/cognition/persona_workspace.rs | 2 +- .../persona_workspace/task_consumption.rs | 40 +++++++++++++ .../tests/task_consumption.rs | 57 +++++++++++++++++++ 3 files changed, 98 insertions(+), 1 deletion(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index ffc6fd6e7f..8a4ff0ecfa 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -57,7 +57,7 @@ pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; mod task_consumption; -pub use task_consumption::TaskConsumptionError; +pub use task_consumption::{ResidentTaskSink, TaskConsumptionError, TaskSinkError}; mod own_speech_persisted; pub use own_speech_persisted::VolatileReceipt; pub(crate) use own_speech_persisted::*; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 6d0f43d187..a1975c38f8 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -41,3 +41,43 @@ impl PersonaWorkspaceRegistry { Ok(save_volatile(owner, SaveReason::Periodic, None, &memory)?) } } + +/// Async adapter for the registered owner. Filesystem work runs on a blocking +/// worker and is awaited; a worker failure cannot be acknowledged as consumption. +pub struct ResidentTaskSink(Arc); + +impl ResidentTaskSink { + pub fn new(registry: Arc) -> Self { + Self(registry) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum TaskSinkError { + #[error(transparent)] + Consumption(#[from] TaskConsumptionError), + #[error("resident task checkpoint worker failed: {0}")] + Worker(#[from] tokio::task::JoinError), +} + +#[async_trait::async_trait] +impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { + type Error = TaskSinkError; + + async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error> { + let registry = Arc::clone(&self.0); + let end = end.clone(); + // Carry the existing test filesystem scope onto the blocking worker. + #[cfg(test)] + let test_home = crate::paths::NativeHomeOverride::current(); + tokio::task::spawn_blocking(move || { + #[cfg(test)] + let _native = test_home + .as_deref() + .map(crate::paths::NativeHomeOverride::install); + registry.consume_task_end(owner, task, end) + }) + .await??; + Ok(()) + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index ecb1e05003..8db5d0b0e3 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -97,3 +97,60 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( assert_eq!(restored.pending_task_wakes(), vec![task]); Ok(()) } + +#[tokio::test] +async fn ledger_ack_follows_resident_commit_and_restart_keeps_wake_without_handle( +) -> Result<(), Box> { + use continuum_kernel::runtime::tasks::{TaskLedger, TaskOutput}; + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let (adapter, _database) = continuum_kernel::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let sink = ResidentTaskSink::new(Arc::clone(®istry)); + let owner = Uuid::new_v4(); + let task = ledger.accept(owner, "test/result".into()).await?; + let end = TaskEnd::Done(TaskOutput::Json( + serde_json::json!({"result":"useful result"}), + )); + ledger.finish(task, owner, end.clone()).await?; + let limit = std::num::NonZeroUsize::new(32).ok_or("invalid fixture page")?; + assert!(ledger + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); + registry.register_from_cfg(cfg_for(owner))?; + let checkpoint = volatile_path(owner)?; + std::fs::create_dir_all(checkpoint.parent().ok_or("checkpoint parent absent")?)?; + let obstruction = checkpoint.with_extension("json.tmp"); + std::fs::create_dir(&obstruction)?; + assert!(ledger + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); + std::fs::remove_dir(&obstruction)?; + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); + assert_eq!(ledger.pending(task, owner).await?, None); + let reopened = TaskLedger::new(adapter).await?; + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restored.pending_task_wakes(), vec![task]); + assert_eq!(reopened.terminal(task, owner).await?, Some(end)); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} From 1eedcea0783439139189f1847993a3c0a4907f3d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 13:32:55 -0500 Subject: [PATCH 10/88] Reconcile durable task pages through resident checkpoint publication --- .../persona_workspace/own_speech_persisted.rs | 1 + .../persona_workspace/task_consumption.rs | 13 +- .../tests/task_consumption.rs | 24 ++- .../cognition/working_memory/continuity.rs | 6 +- .../cognition/working_memory/task_results.rs | 95 +++++++++--- .../src/runtime/tasks/delivery.rs | 19 ++- .../src/runtime/tasks/delivery/tests.rs | 60 ++++++-- core/continuum-mind/src/modules/cognition.rs | 24 ++- .../src/modules/cognition/task_delivery.rs | 143 ++++++++++++++++++ 9 files changed, 330 insertions(+), 55 deletions(-) create mode 100644 core/continuum-mind/src/modules/cognition/task_delivery.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index 2151147b5f..373689a362 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -112,6 +112,7 @@ pub(super) fn save_volatile( drop(file); std::fs::rename(&tmp, &path)?; checkpoint_adoption::sync_parent(&path)?; + wm.publish_task_checkpoint(&receipt.consumed_tasks); Ok(receipt) } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index a1975c38f8..3f2ec34b38 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -20,11 +20,10 @@ impl PersonaWorkspaceRegistry { /// obligation. A replay also checkpoints: a prior insertion may have failed IO. /// Registration/replacement is excluded until the snapshot is committed; the /// next incarnation restores it through the existing registration path. - pub fn consume_task_end( + pub fn consume_task_ends( &self, owner: Uuid, - task: Uuid, - end: TaskEnd, + ends: Vec<(Uuid, TaskEnd)>, ) -> Result { let stopped = self.checkpoint_stopped.lock(); if *stopped { @@ -37,7 +36,7 @@ impl PersonaWorkspaceRegistry { .get(&owner) .map(|resident| Arc::clone(&resident.working_memory)) .ok_or(TaskConsumptionError::Absent(owner))?; - memory.stage_task_end(task, end)?; + memory.stage_task_ends(ends)?; Ok(save_volatile(owner, SaveReason::Periodic, None, &memory)?) } } @@ -64,9 +63,9 @@ pub enum TaskSinkError { impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { type Error = TaskSinkError; - async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error> { + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { let registry = Arc::clone(&self.0); - let end = end.clone(); + let ends = ends.to_vec(); // Carry the existing test filesystem scope onto the blocking worker. #[cfg(test)] let test_home = crate::paths::NativeHomeOverride::current(); @@ -75,7 +74,7 @@ impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { let _native = test_home .as_deref() .map(crate::paths::NativeHomeOverride::install); - registry.consume_task_end(owner, task, end) + registry.consume_task_ends(owner, ends) }) .await??; Ok(()) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 8db5d0b0e3..44f8a8c14b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -10,7 +10,7 @@ async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; - let receipt = registry.consume_task_end(owner, task, TaskEnd::Stopped)?; + let receipt = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; assert_eq!(receipt.owner(), owner); assert_eq!(receipt.consumed_tasks(), &[task]); let old_incarnation = receipt.incarnation(); @@ -24,7 +24,7 @@ async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( assert_ne!(memory.incarnation(), old_incarnation); assert_eq!(memory.pending_task_wakes(), vec![task]); assert!(memory.admit_task_wake(task)); - let replay = registry.consume_task_end(owner, task, TaskEnd::Stopped)?; + let replay = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; assert_eq!(replay.incarnation(), memory.incarnation()); let next = WorkingMemory::new(8); next.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); @@ -42,14 +42,14 @@ async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( let owner = Uuid::new_v4(); let task = Uuid::new_v4(); assert!( - matches!(registry.consume_task_end(owner, task, TaskEnd::Lost), Err(TaskConsumptionError::Absent(id)) if id == owner) + matches!(registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Absent(id)) if id == owner) ); registry.register_from_cfg(cfg_for(owner))?; - registry.consume_task_end(owner, task, TaskEnd::Lost)?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; let path = volatile_path(owner)?; let before = std::fs::read(&path)?; assert!(matches!( - registry.consume_task_end(owner, task, TaskEnd::Stopped), + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)]), Err(TaskConsumptionError::Receipt(_)) )); assert_eq!(std::fs::read(&path)?, before); @@ -58,7 +58,7 @@ async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( } let before = std::fs::read(&path)?; assert!(matches!( - registry.consume_task_end(owner, Uuid::new_v4(), TaskEnd::Lost), + registry.consume_task_ends(owner, vec![(Uuid::new_v4(), TaskEnd::Lost)]), Err(TaskConsumptionError::Stopped) )); assert_eq!(std::fs::read(&path)?, before); @@ -84,12 +84,20 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( let obstruction = path.with_extension("json.tmp"); std::fs::create_dir(&obstruction)?; assert!(matches!( - registry.consume_task_end(owner, task, TaskEnd::Lost), + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Checkpoint(_)) )); assert_eq!(std::fs::read(&path)?, before); + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!(memory.pending_task_wakes().is_empty()); + assert!(!memory.admit_task_wake(task)); std::fs::remove_dir(&obstruction)?; - let receipt = registry.consume_task_end(owner, task, TaskEnd::Lost)?; + // The ordinary checkpoint owner also publishes a staged end after IO recovers. + for (_, result) in registry.flush_volatile_all() { + result?; + } + assert_eq!(memory.pending_task_wakes(), vec![task]); + let receipt = registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; assert_eq!(receipt.consumed_tasks(), &[task]); let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index f5e59e4c38..4b3c9935e7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -262,7 +262,11 @@ impl WorkingMemory { } pub fn restore(&self, mut snap: VolatileSnapshot) { - *self.task_results.lock() = snap.task_results.clone(); + { + let mut results = snap.task_results.clone(); + results.publish_restored(); + *self.task_results.lock() = results; + } // Read before any field moves out of the snapshot below. let records = snap.action_records(); // A restored mind keeps only the newest concern evidence its existing diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index 7815c96023..b05cc087af 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -4,11 +4,16 @@ use super::WorkingMemory; use continuum_kernel::runtime::tasks::TaskEnd; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use uuid::Uuid; #[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub(crate) struct TaskResults(BTreeMap); +pub(crate) struct TaskResults { + entries: BTreeMap, + // Runtime publication fence; durable restoration publishes its saved entries. + #[serde(skip)] + eligible: BTreeSet, +} #[derive(Clone, Debug, Serialize, Deserialize)] struct ConsumedEnd { @@ -42,31 +47,59 @@ impl WorkingMemory { /// checkpoint this exact state before acknowledging consumption to the ledger. /// A replay is inert, including after its wake has already been admitted. pub fn stage_task_end(&self, task: Uuid, end: TaskEnd) -> Result { - let fingerprint: [u8; 32] = Sha256::digest(serde_json::to_vec(&end)?).into(); // Disk boundary: terminal integrity fingerprint persisted instead of duplicating the ledger output. - let mut results = self.task_results.lock(); - match results.0.entry(task) { - std::collections::btree_map::Entry::Occupied(entry) => { - if entry.get().fingerprint != fingerprint { + self.stage_task_ends(vec![(task, end)]) + } + + /// Validate a complete owner page before changing any consumption state. + pub fn stage_task_ends(&self, ends: Vec<(Uuid, TaskEnd)>) -> Result { + let mut incoming = BTreeMap::new(); + for (task, end) in ends { + let fingerprint: [u8; 32] = Sha256::digest(serde_json::to_vec(&end)?).into(); // Disk boundary: persist integrity fingerprints, not duplicate ledger output. + if let Some(previous) = incoming.insert(task, fingerprint) { + if previous != fingerprint { return Err(TaskReceiptConflict { task }.into()); } - Ok(false) } - std::collections::btree_map::Entry::Vacant(entry) => { + } + let mut results = self.task_results.lock(); + for (task, fingerprint) in &incoming { + if let Some(previous) = results.entries.get(task) { + if previous.fingerprint != *fingerprint { + return Err(TaskReceiptConflict { task: *task }.into()); + } + } + } + let mut changed = false; + for (task, fingerprint) in incoming { + if let std::collections::btree_map::Entry::Vacant(entry) = results.entries.entry(task) { entry.insert(ConsumedEnd { fingerprint, wake_pending: true, }); - Ok(true) + changed = true; + } + } + Ok(changed) + } + + /// The shared checkpoint writer calls this only after syncing its exact snapshot. + pub(crate) fn publish_task_checkpoint(&self, saved: &[Uuid]) { + let mut results = self.task_results.lock(); + for task in saved { + if results.entries.contains_key(task) { + results.eligible.insert(*task); } } } pub fn pending_task_wakes(&self) -> Vec { - self.task_results - .lock() - .0 + let results = self.task_results.lock(); + results + .entries .iter() - .filter_map(|(task, entry)| entry.wake_pending.then_some(*task)) + .filter_map(|(task, entry)| { + (entry.wake_pending && results.eligible.contains(task)).then_some(*task) + }) .collect() } @@ -75,7 +108,10 @@ impl WorkingMemory { /// Returns false if no pending obligation exists; never fabricates a receipt. pub fn admit_task_wake(&self, task: Uuid) -> bool { let mut results = self.task_results.lock(); - match results.0.get_mut(&task) { + if !results.eligible.contains(&task) { + return false; + } + match results.entries.get_mut(&task) { Some(entry) if entry.wake_pending => { entry.wake_pending = false; true @@ -86,10 +122,14 @@ impl WorkingMemory { } impl TaskResults { + pub(crate) fn publish_restored(&mut self) { + self.eligible = self.entries.keys().copied().collect(); + } + /// A checkpoint receipt must use IDs from its serialized snapshot, not from /// a second read of mutable working memory after IO completes. pub(crate) fn consumed_ids(&self) -> Vec { - self.0.keys().copied().collect() + self.entries.keys().copied().collect() } } @@ -124,6 +164,23 @@ mod tests { assert_eq!(next_life.snapshot().task_results.consumed_ids(), vec![task]); } + #[test] + fn conflicting_batch_stages_nothing() { + let memory = WorkingMemory::new(8); + let existing = Uuid::new_v4(); + let new = Uuid::new_v4(); + memory + .stage_task_end(existing, TaskEnd::Lost) + .expect("existing"); + assert!(memory + .stage_task_ends(vec![(new, TaskEnd::Stopped), (existing, TaskEnd::Stopped)]) + .is_err()); + assert_eq!( + memory.snapshot().task_results.consumed_ids(), + vec![existing] + ); + } + #[test] fn conflicting_end_is_refused_and_later_arrival_is_not_in_prior_snapshot() { let memory = WorkingMemory::new(8); @@ -139,7 +196,11 @@ mod tests { assert_eq!(snapshot.task_results.consumed_ids(), vec![first]); assert!(matches!(memory.stage_task_end(first, TaskEnd::Stopped), Err(TaskReceiptError::Conflict(TaskReceiptConflict { task })) if task == first)); - assert_eq!(memory.pending_task_wakes().len(), 2); + assert!(memory.pending_task_wakes().is_empty()); + assert!(!memory.admit_task_wake(first)); + memory.publish_task_checkpoint(&snapshot.task_results.consumed_ids()); + assert_eq!(memory.pending_task_wakes(), vec![first]); + assert!(!memory.admit_task_wake(later)); assert!(!memory.admit_task_wake(Uuid::new_v4())); } } diff --git a/core/continuum-kernel/src/runtime/tasks/delivery.rs b/core/continuum-kernel/src/runtime/tasks/delivery.rs index 3bcac502d8..6ad9819af2 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery.rs @@ -7,11 +7,12 @@ use uuid::Uuid; /// Implemented by the owner of the recipient's durable state, never by a transient /// workspace or a notification channel. Success means the exact terminal result and /// its outstanding wake obligation are durable. Replays must deduplicate by task ID. +/// Consume the owner page in one commit; per-result checkpoints amplify storage work. #[async_trait::async_trait] pub trait TaskOwnerSink: Send + Sync { type Error: std::error::Error + Send + Sync + 'static; - async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error>; + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error>; } /// Failure retains its boundary: a sink refusal cannot masquerade as an ACK failure, @@ -19,7 +20,7 @@ pub trait TaskOwnerSink: Send + Sync { #[derive(Debug)] pub enum DeliveryError { Read(String), - Consume { task: Uuid, source: E }, + Consume { owner: Uuid, source: E }, Acknowledge { task: Uuid, message: String }, } @@ -27,7 +28,9 @@ impl std::fmt::Display for DeliveryError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Read(message) => write!(f, "task replay read failed: {message}"), - Self::Consume { task, source } => write!(f, "task {task} consumption failed: {source}"), + Self::Consume { owner, source } => { + write!(f, "owner {owner} consumption failed: {source}") + } Self::Acknowledge { task, message } => { write!(f, "task {task} acknowledgement failed: {message}") } @@ -66,11 +69,13 @@ impl TaskLedger { .pending_page(owner, after, limit.get()) .await .map_err(DeliveryError::Read)?; - let mut acknowledged = 0; - for (task, end) in page.ends { - sink.consume(owner, task, &end) + if !page.ends.is_empty() { + sink.consume(owner, &page.ends) .await - .map_err(|source| DeliveryError::Consume { task, source })?; + .map_err(|source| DeliveryError::Consume { owner, source })?; + } + let mut acknowledged = 0; + for (task, _) in page.ends { self.acknowledge(task, owner) .await .map_err(|message| DeliveryError::Acknowledge { task, message })?; diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs index ca1904fa33..c4f96516a3 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -2,13 +2,14 @@ #![cfg(test)] use super::*; use std::sync::{ - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, }; struct Sink { ledger: Arc, refuse: AtomicBool, + commits: AtomicUsize, seen: parking_lot::Mutex>, } @@ -16,17 +17,22 @@ struct Sink { impl TaskOwnerSink for Sink { type Error = std::io::Error; - async fn consume(&self, owner: Uuid, task: Uuid, end: &TaskEnd) -> Result<(), Self::Error> { - let pending = self - .ledger - .pending(task, owner) - .await - .map_err(std::io::Error::other)?; - assert_eq!(pending.as_ref(), Some(end), "consumption must precede ACK"); + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { + for (task, end) in ends { + let pending = self + .ledger + .pending(*task, owner) + .await + .map_err(std::io::Error::other)?; + assert_eq!(pending.as_ref(), Some(end), "consumption must precede ACK"); + } if self.refuse.load(Ordering::SeqCst) { return Err(std::io::Error::other("injected persistence refusal")); } - self.seen.lock().push((owner, task, end.clone())); + self.commits.fetch_add(1, Ordering::SeqCst); + self.seen + .lock() + .extend(ends.iter().map(|(task, end)| (owner, *task, end.clone()))); Ok(()) } } @@ -43,10 +49,11 @@ async fn refused_consumption_remains_pending_and_replay_needs_no_registered_hand ledger: ledger.clone(), refuse: AtomicBool::new(true), seen: Default::default(), + commits: AtomicUsize::new(0), }; let limit = NonZeroUsize::new(32).expect("test: nonzero page"); assert!( - matches!(ledger.deliver_page(owner, None, limit, &sink).await, Err(DeliveryError::Consume { task: failed, .. }) if failed == task) + matches!(ledger.deliver_page(owner, None, limit, &sink).await, Err(DeliveryError::Consume { owner: failed, .. }) if failed == owner) ); assert_eq!(ledger.pending(task, owner).await?, Some(TaskEnd::Stopped)); assert!(sink.seen.lock().is_empty()); @@ -87,6 +94,7 @@ async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( ledger: ledger.clone(), refuse: AtomicBool::new(false), seen: Default::default(), + commits: AtomicUsize::new(0), }; let mut after = None; let mut exhausted = false; @@ -115,3 +123,35 @@ async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( ); Ok(()) } + +#[tokio::test] +async fn one_owner_page_is_consumed_once_before_its_acknowledgements( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let owner = Uuid::new_v4(); + let first = ledger.accept(owner, "first".into()).await?; + let second = ledger.accept(owner, "second".into()).await?; + ledger.finish(first, owner, TaskEnd::Stopped).await?; + ledger.finish(second, owner, TaskEnd::Lost).await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(false), + commits: AtomicUsize::new(0), + seen: Default::default(), + }; + let page = ledger + .deliver_page( + owner, + None, + NonZeroUsize::new(32).ok_or("invalid test page")?, + &sink, + ) + .await?; + assert_eq!(page.acknowledged, 2); + assert_eq!(sink.commits.load(Ordering::SeqCst), 1); + assert_eq!(sink.seen.lock().len(), 2); + assert_eq!(ledger.pending(first, owner).await?, None); + assert_eq!(ledger.pending(second, owner).await?, None); + Ok(()) +} diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index bc5eb8ccb6..3038a478c6 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -32,16 +32,20 @@ //! //! Uses `Params` helper for typed parameter extraction. +use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::gpu::GpuMemoryManager; use crate::logging::TimingGuard; -use continuum_text_analysis::LoopDetector; -use crate::persona::{PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord}; -use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; +use crate::persona::{ + PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord, +}; use crate::rag::RagEngine; use crate::runtime; -use crate::runtime::{CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; use crate::runtime::params::Params; +use crate::runtime::{ + CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule, +}; use async_trait::async_trait; +use continuum_text_analysis::LoopDetector; use dashmap::DashMap; use serde_json::Value; use std::any::Any; @@ -107,8 +111,11 @@ impl CognitionState { } } +mod task_delivery; + pub struct CognitionModule { state: Arc, + task_replay: tokio::sync::Mutex, /// Shared late-bound executor slot. `Arc`-wrapped so the `cognition/vision-describe` /// command object can hold the same slot and re-enter the bus for `ai/generate` /// (same pattern as the `chat/*` family). @@ -119,6 +126,7 @@ impl CognitionModule { pub fn new(state: Arc) -> Self { Self { state, + task_replay: tokio::sync::Mutex::new(task_delivery::ReplaySweep::default()), executor: Arc::new(LateBound::new("cognition::executor")), } } @@ -191,7 +199,13 @@ impl ServiceModule for CognitionModule { in_flight = crate::cognition::turn_ingress::in_flight(), "citizens inside a turn right now — the drain budget's competitor, sampled before the drain instead of only at it" ); - checkpoint_residents(CheckpointBoundary::Periodic).await + let replay = self.reconcile_tasks().await; + let checkpoint = checkpoint_residents(CheckpointBoundary::Periodic).await; + match (replay, checkpoint) { + (Ok(()), Ok(())) => Ok(()), + (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error), + (Err(replay), Err(checkpoint)) => Err(format!("{replay}; {checkpoint}")), + } } async fn shutdown(&self) -> Result<(), String> { diff --git a/core/continuum-mind/src/modules/cognition/task_delivery.rs b/core/continuum-mind/src/modules/cognition/task_delivery.rs new file mode 100644 index 0000000000..e100ffd6d1 --- /dev/null +++ b/core/continuum-mind/src/modules/cognition/task_delivery.rs @@ -0,0 +1,143 @@ +//! Durable replay rides cognition's existing lifecycle tick. No persona needs to +//! remember a handle or poll; cursors are scan progress, never delivery authority. +use super::CognitionModule; +use continuum_kernel::runtime::tasks::{TaskLedger, TaskOwnerSink}; +use std::collections::{BTreeMap, BTreeSet}; +use std::num::NonZeroUsize; +use uuid::Uuid; + +// Storage page policy, independent of prompt/context budgets. Each resident gets +// one bounded page per existing lifecycle tick, including through empty pages. +const REPLAY_PAGE_ROWS: usize = 64; + +#[derive(Default)] +pub(super) struct ReplaySweep { + after: BTreeMap>, +} + +impl ReplaySweep { + async fn advance( + &mut self, + ledger: &TaskLedger, + owners: Vec, + sink: &S, + limit: NonZeroUsize, + ) -> Result<(), String> { + let live: BTreeSet<_> = owners.into_iter().collect(); + self.after.retain(|owner, _| live.contains(owner)); + let mut failures = Vec::new(); + for owner in live { + let after = *self.after.entry(owner).or_insert(None); + match ledger.deliver_page(owner, after, limit, sink).await { + Ok(page) => { + // New ends can sort before our cursor. Every completed sweep + // starts again; acknowledged rows cannot repeat consumption. + self.after + .insert(owner, if page.exhausted { None } else { page.after }); + } + Err(error) => { + // No cursor advance on failure: the durable outbox retains + // every unacknowledged result, including failed consumption. + failures.push(format!("{owner}: {error}")); + } + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(format!( + "resident task replay failed: {}", + failures.join("; ") + )) + } + } +} + +impl CognitionModule { + pub(super) async fn reconcile_tasks(&self) -> Result<(), String> { + let registry = crate::cognition::persona_workspace::global(); + let owners: Vec<_> = registry.roster().into_iter().map(|(id, _)| id).collect(); + if owners.is_empty() { + self.task_replay.lock().await.after.clear(); + return Ok(()); + } + let ledger = self.executor.require()?.task_ledger().await?; + let sink = crate::cognition::persona_workspace::ResidentTaskSink::new(registry); + let limit = + NonZeroUsize::new(REPLAY_PAGE_ROWS).ok_or("task replay page policy must be nonzero")?; + self.task_replay + .lock() + .await + .advance(ledger, owners, &sink, limit) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use continuum_kernel::runtime::tasks::TaskEnd; + use std::sync::atomic::{AtomicBool, Ordering}; + + // Scheduling fixture only; real durable consumption is tested by cognition's + // ledger-to-resident integration test, not claimed by this in-memory sink. + struct Sink { + refused: Uuid, + refuse: AtomicBool, + } + #[async_trait::async_trait] + impl TaskOwnerSink for Sink { + type Error = std::io::Error; + async fn consume(&self, owner: Uuid, _: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { + if owner == self.refused && self.refuse.load(Ordering::SeqCst) { + Err(std::io::Error::other("injected owner refusal")) + } else { + Ok(()) + } + } + } + + #[tokio::test] + async fn failed_owner_does_not_starve_peer_and_later_ends_are_revisited( + ) -> Result<(), Box> { + let (adapter, _directory) = continuum_kernel::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let refused = Uuid::new_v4(); + let healthy = Uuid::new_v4(); + let blocked = ledger.accept(refused, "blocked".into()).await?; + let ready = ledger.accept(healthy, "ready".into()).await?; + let running = ledger.accept(healthy, "running".into()).await?; + ledger.finish(blocked, refused, TaskEnd::Stopped).await?; + ledger.finish(ready, healthy, TaskEnd::Stopped).await?; + let sink = Sink { + refused, + refuse: AtomicBool::new(true), + }; + let mut sweep = ReplaySweep::default(); + let limit = NonZeroUsize::MIN; + // Scan through individual fact rows, including pages with no pending end. + for _ in 0..12 { + let _ = sweep + .advance(&ledger, vec![refused, healthy], &sink, limit) + .await; + } + assert_eq!(ledger.pending(ready, healthy).await?, None); + assert_eq!( + ledger.pending(blocked, refused).await?, + Some(TaskEnd::Stopped) + ); + // End an already-scanned acceptance. Fresh sweeps must find it. + ledger.finish(running, healthy, TaskEnd::Lost).await?; + sink.refuse.store(false, Ordering::SeqCst); + for _ in 0..16 { + sweep + .advance(&ledger, vec![refused, healthy], &sink, limit) + .await?; + } + assert_eq!(ledger.pending(running, healthy).await?, None); + assert_eq!(ledger.pending(blocked, refused).await?, None); + sweep.advance(&ledger, vec![healthy], &sink, limit).await?; + assert!(!sweep.after.contains_key(&refused)); + Ok(()) + } +} From 2e1fc8740ad79a7ffc8a98a4e2bc246473c5342e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 13:44:49 -0500 Subject: [PATCH 11/88] Mark resident task fixtures as test-only for dependency ratchet --- .../src/cognition/persona_workspace/tests/task_consumption.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 44f8a8c14b..e7ff28039f 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -1,3 +1,4 @@ +#![cfg(test)] use super::*; use continuum_kernel::runtime::tasks::TaskEnd; From 9a557e20ea6d712a675246351986278ac2601ddb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 13:57:10 -0500 Subject: [PATCH 12/88] Publish task wake retirement only after durable checkpoint --- .../persona_workspace/own_speech_persisted.rs | 3 +- .../tests/task_consumption.rs | 40 +++++++++- .../cognition/working_memory/task_results.rs | 76 ++++++++++++++----- .../working_memory/tests/provenance.rs | 50 +++--------- 4 files changed, 104 insertions(+), 65 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index 373689a362..a74f9054ee 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -95,6 +95,7 @@ pub(super) fn save_volatile( incarnation: wm.incarnation(), consumed_tasks: snapshot.task_results.consumed_ids(), }; + let task_publication = snapshot.task_results.publication(); let persisted = PersistedVolatile { wm: snapshot, own_speech: OwnSpeechPersisted::ByRoom(super::super::deliberation_budget::own_speech_by_room( @@ -112,7 +113,7 @@ pub(super) fn save_volatile( drop(file); std::fs::rename(&tmp, &path)?; checkpoint_adoption::sync_parent(&path)?; - wm.publish_task_checkpoint(&receipt.consumed_tasks); + wm.publish_task_checkpoint(task_publication); Ok(receipt) } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index e7ff28039f..839b9b275b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -24,7 +24,7 @@ async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert_ne!(memory.incarnation(), old_incarnation); assert_eq!(memory.pending_task_wakes(), vec![task]); - assert!(memory.admit_task_wake(task)); + assert!(memory.stage_task_read(task)); let replay = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; assert_eq!(replay.incarnation(), memory.incarnation()); let next = WorkingMemory::new(8); @@ -91,7 +91,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( assert_eq!(std::fs::read(&path)?, before); let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert!(memory.pending_task_wakes().is_empty()); - assert!(!memory.admit_task_wake(task)); + assert!(!memory.stage_task_read(task)); std::fs::remove_dir(&obstruction)?; // The ordinary checkpoint owner also publishes a staged end after IO recovers. for (_, result) in registry.flush_volatile_all() { @@ -163,3 +163,39 @@ async fn ledger_ack_follows_resident_commit_and_restart_keeps_wake_without_handl assert_eq!(restored.pending_task_wakes(), vec![task]); Ok(()) } + +#[tokio::test] +async fn failed_read_checkpoint_keeps_wake_pending_until_retry( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!(memory.stage_task_read(task)); + let obstruction = volatile_path(owner)?.with_extension("json.tmp"); + std::fs::create_dir(&obstruction)?; + let failed = registry.flush_volatile_all(); + assert_eq!(failed.len(), 1); + assert!(failed[0].1.is_err()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + let restarted = WorkingMemory::new(8); + restarted.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restarted.pending_task_wakes(), vec![task]); + assert!( + !memory.stage_task_read(task), + "already staged is not durable success" + ); + std::fs::remove_dir(&obstruction)?; + for (_, result) in registry.flush_volatile_all() { + result?; + } + assert!(memory.pending_task_wakes().is_empty()); + let restarted = WorkingMemory::new(8); + restarted.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restarted.pending_task_wakes().is_empty()); + Ok(()) +} diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index b05cc087af..e4ff75e16a 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -4,7 +4,7 @@ use super::WorkingMemory; use continuum_kernel::runtime::tasks::TaskEnd; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use uuid::Uuid; #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -12,7 +12,7 @@ pub(crate) struct TaskResults { entries: BTreeMap, // Runtime publication fence; durable restoration publishes its saved entries. #[serde(skip)] - eligible: BTreeSet, + published: BTreeMap, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -83,11 +83,11 @@ impl WorkingMemory { } /// The shared checkpoint writer calls this only after syncing its exact snapshot. - pub(crate) fn publish_task_checkpoint(&self, saved: &[Uuid]) { + pub(crate) fn publish_task_checkpoint(&self, saved: TaskPublication) { let mut results = self.task_results.lock(); - for task in saved { - if results.entries.contains_key(task) { - results.eligible.insert(*task); + for (task, pending) in saved.0 { + if results.entries.contains_key(&task) { + results.published.insert(task, pending); } } } @@ -95,20 +95,20 @@ impl WorkingMemory { pub fn pending_task_wakes(&self) -> Vec { let results = self.task_results.lock(); results - .entries + .published .iter() - .filter_map(|(task, entry)| { - (entry.wake_pending && results.eligible.contains(task)).then_some(*task) - }) + .filter_map(|(task, pending)| pending.then_some(*task)) .collect() } - /// Called only when the owning turn admits this task's wake. Sending to a - /// channel, reading output, and acknowledging the ledger are not admission. - /// Returns false if no pending obligation exists; never fabricates a receipt. - pub fn admit_task_wake(&self, task: Uuid) -> bool { + /// Stage retirement only after a successful rendered-context read receipt. + /// The wake remains published until the checkpoint containing retirement commits. + /// Notification delivery and entering the service loop are not perception. + /// Returns whether staging changed. False does not prove persistence: an earlier + /// stage may still need a checkpoint retry. Unknown tasks cannot create receipts. + pub fn stage_task_read(&self, task: Uuid) -> bool { let mut results = self.task_results.lock(); - if !results.eligible.contains(&task) { + if !results.published.contains_key(&task) { return false; } match results.entries.get_mut(&task) { @@ -121,9 +121,21 @@ impl WorkingMemory { } } +/// Exact wake projection of one serialized snapshot. Constructed only by its owner. +pub(crate) struct TaskPublication(BTreeMap); + impl TaskResults { + pub(crate) fn publication(&self) -> TaskPublication { + TaskPublication( + self.entries + .iter() + .map(|(id, end)| (*id, end.wake_pending)) + .collect(), + ) + } + pub(crate) fn publish_restored(&mut self) { - self.eligible = self.entries.keys().copied().collect(); + self.published = self.publication().0; } /// A checkpoint receipt must use IDs from its serialized snapshot, not from @@ -153,10 +165,16 @@ mod tests { assert!(!restored .stage_task_end(task, TaskEnd::Stopped) .expect("identical replay")); - assert!(restored.admit_task_wake(task)); + assert!(restored.stage_task_read(task)); assert!(!restored .stage_task_end(task, TaskEnd::Stopped) .expect("replay after admission")); + assert_eq!( + restored.pending_task_wakes(), + vec![task], + "staged retirement is not a committed read receipt" + ); + restored.publish_task_checkpoint(restored.snapshot().task_results.publication()); assert!(restored.pending_task_wakes().is_empty()); let next_life = WorkingMemory::new(8); next_life.restore(restored.snapshot()); @@ -164,6 +182,22 @@ mod tests { assert_eq!(next_life.snapshot().task_results.consumed_ids(), vec![task]); } + #[test] + fn older_checkpoint_cannot_publish_a_later_read() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + memory + .stage_task_end(task, TaskEnd::Stopped) + .expect("stage end"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + let earlier = memory.snapshot().task_results.publication(); + assert!(memory.stage_task_read(task)); + memory.publish_task_checkpoint(earlier); + assert_eq!(memory.pending_task_wakes(), vec![task]); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert!(memory.pending_task_wakes().is_empty()); + } + #[test] fn conflicting_batch_stages_nothing() { let memory = WorkingMemory::new(8); @@ -197,10 +231,10 @@ mod tests { assert!(matches!(memory.stage_task_end(first, TaskEnd::Stopped), Err(TaskReceiptError::Conflict(TaskReceiptConflict { task })) if task == first)); assert!(memory.pending_task_wakes().is_empty()); - assert!(!memory.admit_task_wake(first)); - memory.publish_task_checkpoint(&snapshot.task_results.consumed_ids()); + assert!(!memory.stage_task_read(first)); + memory.publish_task_checkpoint(snapshot.task_results.publication()); assert_eq!(memory.pending_task_wakes(), vec![first]); - assert!(!memory.admit_task_wake(later)); - assert!(!memory.admit_task_wake(Uuid::new_v4())); + assert!(!memory.stage_task_read(later)); + assert!(!memory.stage_task_read(Uuid::new_v4())); } } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 536ceedf1d..6a7a4fc810 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -319,47 +319,15 @@ fn receipt_archive_survives_ring_churn_and_roundtrips_the_snapshot() { } #[test] -fn an_old_snapshot_without_acts_restores_without_panic() { - // A hand-authored legacy snapshot: entries have NO `acts` key at all. - let legacy_json = r#"{ - "entries": [ - { "kind": "Thought", "text": "thinking about the tokenizer" }, - { "kind": { "Receipt": { "n": 1 } }, "text": "[action #1] code/list → ok" } - ], - "last_action": [1, "code/list → ok"], - "action_fps": ["code/list|{}"], - "next_action_seq": 2 - }"#; - let snap: VolatileSnapshot = - serde_json::from_str(legacy_json).expect("legacy snapshot deserializes"); - let fresh = WorkingMemory::new(8); - fresh.restore(snap); - // Both legacy entries survive the round-trip (asserted by content, not a raw - // count — restore ALSO appends a `[resumed]` wake-orientation fact by design, - // #147/#165: a restore IS an interruption, so she wakes oriented, never blank). - let texts = fresh.recent(); - assert!( - texts - .iter() - .any(|t| t.contains("thinking about the tokenizer")), - "the legacy thought restored" - ); - assert!( - texts.iter().any(|t| t.contains("[action #1] code/list")), - "the legacy receipt restored" - ); - assert!( - fresh.pinned_facts().iter().any(|t| t.starts_with("[resumed]")), - "restore pins the wake-orientation notice" - ); - assert!( - fresh.recent_acts().is_empty(), - "a legacy receipt has no typed acts — defaulted empty, never a panic" - ); - assert!( - fresh.has_receipt(), - "the receipt kind still survives the trip" - ); +fn snapshot_without_task_consumption_is_refused() -> Result<(), Box> { + let memory = WorkingMemory::new(8); + memory.record_receipt("code/list completed"); + let mut encoded = serde_json::to_value(memory.snapshot())?; + encoded.as_object_mut().ok_or("snapshot must be an object")?.remove("task_results"); + let error = serde_json::from_value::(encoded) + .expect_err("missing durable task state must not silently become an empty mailbox"); + assert!(error.to_string().contains("task_results")); + Ok(()) } #[test] From d98fe2909c38616cc851e14fc1a653a62c1c9a23 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 14:17:47 -0500 Subject: [PATCH 13/88] Bind durable task read receipts to the registered memory incarnation --- .../persona_workspace/task_consumption.rs | 35 +++++++++++++++- .../tests/task_consumption.rs | 40 +++++++++++++++++-- .../cognition/working_memory/task_results.rs | 40 +++++++++++++------ 3 files changed, 98 insertions(+), 17 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 3f2ec34b38..e91e7e3eff 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -9,6 +9,8 @@ pub enum TaskConsumptionError { Stopped, #[error("task owner {0} is not a registered resident")] Absent(Uuid), + #[error("task read receipt belongs to a replaced memory incarnation for {0}")] + Replaced(Uuid), #[error(transparent)] Receipt(#[from] super::super::working_memory::TaskReceiptError), #[error("task consumption checkpoint failed: {0}")] @@ -24,6 +26,37 @@ impl PersonaWorkspaceRegistry { &self, owner: Uuid, ends: Vec<(Uuid, TaskEnd)>, + ) -> Result { + self.commit_task_state(owner, |memory| { + memory.stage_task_ends(ends)?; + Ok(()) + }) + } + + /// Commit only reads reported by this registered memory incarnation. A repeated + /// receipt still saves: an earlier staging may have survived a failed write. + pub fn record_task_reads( + &self, + owner: Uuid, + incarnation: Uuid, + tasks: &[Uuid], + ) -> Result { + self.commit_task_state(owner, |memory| { + if memory.incarnation() != incarnation { + return Err(TaskConsumptionError::Replaced(owner)); + } + memory.stage_task_reads(tasks)?; + Ok(()) + }) + } + + /// One admission and persistence owner for task arrivals and rendered reads. + fn commit_task_state( + &self, + owner: Uuid, + stage: impl FnOnce( + &super::super::working_memory::WorkingMemory, + ) -> Result<(), TaskConsumptionError>, ) -> Result { let stopped = self.checkpoint_stopped.lock(); if *stopped { @@ -36,7 +69,7 @@ impl PersonaWorkspaceRegistry { .get(&owner) .map(|resident| Arc::clone(&resident.working_memory)) .ok_or(TaskConsumptionError::Absent(owner))?; - memory.stage_task_ends(ends)?; + stage(&memory)?; Ok(save_volatile(owner, SaveReason::Periodic, None, &memory)?) } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 839b9b275b..7b18ae6257 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -24,7 +24,7 @@ async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert_ne!(memory.incarnation(), old_incarnation); assert_eq!(memory.pending_task_wakes(), vec![task]); - assert!(memory.stage_task_read(task)); + assert!(memory.stage_task_reads(&[task])?); let replay = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; assert_eq!(replay.incarnation(), memory.incarnation()); let next = WorkingMemory::new(8); @@ -91,7 +91,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( assert_eq!(std::fs::read(&path)?, before); let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert!(memory.pending_task_wakes().is_empty()); - assert!(!memory.stage_task_read(task)); + assert!(memory.stage_task_reads(&[task]).is_err()); std::fs::remove_dir(&obstruction)?; // The ordinary checkpoint owner also publishes a staged end after IO recovers. for (_, result) in registry.flush_volatile_all() { @@ -175,7 +175,7 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( registry.register_from_cfg(cfg_for(owner))?; registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); - assert!(memory.stage_task_read(task)); + assert!(memory.stage_task_reads(&[task])?); let obstruction = volatile_path(owner)?.with_extension("json.tmp"); std::fs::create_dir(&obstruction)?; let failed = registry.flush_volatile_all(); @@ -186,7 +186,7 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( restarted.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert_eq!(restarted.pending_task_wakes(), vec![task]); assert!( - !memory.stage_task_read(task), + !memory.stage_task_reads(&[task])?, "already staged is not durable success" ); std::fs::remove_dir(&obstruction)?; @@ -199,3 +199,35 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( assert!(restarted.pending_task_wakes().is_empty()); Ok(()) } + +#[tokio::test] +async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let accepted = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + registry.register_from_cfg(cfg_for(owner))?; + let current = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!( + matches!(registry.record_task_reads(owner, accepted.incarnation(), &[task]), Err(TaskConsumptionError::Replaced(id)) if id == owner) + ); + assert_eq!(current.pending_task_wakes(), vec![task]); + let obstruction = volatile_path(owner)?.with_extension("json.tmp"); + std::fs::create_dir(&obstruction)?; + assert!(matches!( + registry.record_task_reads(owner, current.incarnation(), &[task]), + Err(TaskConsumptionError::Checkpoint(_)) + )); + assert_eq!(current.pending_task_wakes(), vec![task]); + std::fs::remove_dir(&obstruction)?; + registry.record_task_reads(owner, current.incarnation(), &[task])?; + assert!(current.pending_task_wakes().is_empty()); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restored.pending_task_wakes().is_empty()); + Ok(()) +} diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index e4ff75e16a..b79bb7654b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -29,6 +29,8 @@ pub struct TaskReceiptConflict { #[derive(Debug, thiserror::Error)] pub enum TaskReceiptError { + #[error("task {0} has no published consumption receipt")] + Unpublished(Uuid), #[error(transparent)] Conflict(#[from] TaskReceiptConflict), #[error("terminal fingerprint encoding failed: {0}")] @@ -106,18 +108,21 @@ impl WorkingMemory { /// Notification delivery and entering the service loop are not perception. /// Returns whether staging changed. False does not prove persistence: an earlier /// stage may still need a checkpoint retry. Unknown tasks cannot create receipts. - pub fn stage_task_read(&self, task: Uuid) -> bool { + pub fn stage_task_reads(&self, tasks: &[Uuid]) -> Result { let mut results = self.task_results.lock(); - if !results.published.contains_key(&task) { - return false; + for task in tasks { + if !results.published.contains_key(task) || !results.entries.contains_key(task) { + return Err(TaskReceiptError::Unpublished(*task)); + } } - match results.entries.get_mut(&task) { - Some(entry) if entry.wake_pending => { + let mut changed = false; + for task in tasks { + if let Some(entry) = results.entries.get_mut(task) { + changed |= entry.wake_pending; entry.wake_pending = false; - true } - Some(_) | None => false, } + Ok(changed) } } @@ -165,7 +170,7 @@ mod tests { assert!(!restored .stage_task_end(task, TaskEnd::Stopped) .expect("identical replay")); - assert!(restored.stage_task_read(task)); + assert!(restored.stage_task_reads(&[task]).expect("published task")); assert!(!restored .stage_task_end(task, TaskEnd::Stopped) .expect("replay after admission")); @@ -182,6 +187,17 @@ mod tests { assert_eq!(next_life.snapshot().task_results.consumed_ids(), vec![task]); } + #[test] + fn read_batch_refuses_unknown_task_without_partial_retirement() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + memory.stage_task_end(task, TaskEnd::Stopped).expect("stage"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert!(memory.stage_task_reads(&[task, Uuid::new_v4()]).is_err()); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + } + #[test] fn older_checkpoint_cannot_publish_a_later_read() { let memory = WorkingMemory::new(8); @@ -191,7 +207,7 @@ mod tests { .expect("stage end"); memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); let earlier = memory.snapshot().task_results.publication(); - assert!(memory.stage_task_read(task)); + assert!(memory.stage_task_reads(&[task]).expect("published task")); memory.publish_task_checkpoint(earlier); assert_eq!(memory.pending_task_wakes(), vec![task]); memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); @@ -231,10 +247,10 @@ mod tests { assert!(matches!(memory.stage_task_end(first, TaskEnd::Stopped), Err(TaskReceiptError::Conflict(TaskReceiptConflict { task })) if task == first)); assert!(memory.pending_task_wakes().is_empty()); - assert!(!memory.stage_task_read(first)); + assert!(memory.stage_task_reads(&[first]).is_err()); memory.publish_task_checkpoint(snapshot.task_results.publication()); assert_eq!(memory.pending_task_wakes(), vec![first]); - assert!(!memory.stage_task_read(later)); - assert!(!memory.stage_task_read(Uuid::new_v4())); + assert!(memory.stage_task_reads(&[later]).is_err()); + assert!(memory.stage_task_reads(&[Uuid::new_v4()]).is_err()); } } From 6dcdb53992ebedf8c234001337a3c1d4e9eeb569 Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 22:54:55 -0500 Subject: [PATCH 14/88] WIP (not pushed): working memory sizes from the one owner, WorkingMemoryFaculty deleted, arbiter forwards every bid (card c537d687) Open before push: observation.rs:358 intent_label (Fable: drop the because-clause, annotate open views with call_line); vitals_emitter.rs:94 .min(100) and llm_deliberation_faculty.rs:716 OpenOptions are flagged because this branch touches those files (literal edits); full cognition/mind suites not yet run after the arbiter change. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/apply.rs | 55 ++--- .../src/cognition/act_observe/mod.rs | 38 ++- .../src/cognition/act_observe/observation.rs | 19 +- .../src/cognition/act_observe/settle/tests.rs | 2 +- .../src/cognition/act_observe/tests/apply.rs | 18 +- .../src/cognition/act_observe/tests/chain.rs | 6 +- .../src/cognition/act_observe/tests/credit.rs | 5 - .../src/cognition/act_observe/tests/drive.rs | 31 +-- .../act_observe/tests/investigation.rs | 23 +- .../src/cognition/context_streams/tests.rs | 2 - .../src/cognition/deliberation_prompt.rs | 4 +- .../src/cognition/llm_deliberation_faculty.rs | 2 +- .../prompt/messages.rs | 7 +- .../an_action_result_cannot_mute_a_citizen.rs | 2 - .../tests/prompt_shaping/reply_reserve.rs | 1 - .../tests/prompt_shaping/turn_window.rs | 19 +- .../tests/verdicts/act_verdicts.rs | 2 +- .../tests/verdicts/capacity_and_wire.rs | 3 - .../src/cognition/persona_workspace.rs | 2 +- .../default_workspace_capacity.rs | 28 +-- ...ins_admitted_periodic_writer_before_ack.rs | 2 - ..._told_when_her_hands_move_and_only_then.rs | 1 - .../src/cognition/rag_source_faculty/tests.rs | 3 +- ...d_in_action_recall_informs_the_decision.rs | 1 - .../src/cognition/request_replay.rs | 1 - .../src/cognition/should_respond_module.rs | 1 - .../src/cognition/working_memory.rs | 66 +++--- .../cognition/working_memory/action_log.rs | 37 +-- .../cognition/working_memory/continuity.rs | 34 +-- .../src/cognition/working_memory/faculty.rs | 219 ------------------ .../src/cognition/working_memory/ledger.rs | 87 ++----- .../cognition/working_memory/perception.rs | 36 ++- .../working_memory/tests/action_log.rs | 43 ++-- .../cognition/working_memory/tests/actions.rs | 70 +++--- .../cognition/working_memory/tests/custody.rs | 24 -- .../cognition/working_memory/tests/faculty.rs | 88 ------- .../src/cognition/working_memory/tests/mod.rs | 1 - .../working_memory/tests/open_views.rs | 2 - .../working_memory/tests/provenance.rs | 57 ++--- .../cognition/working_memory/tests/trail.rs | 39 +--- .../src/cognition/workspace/arbiter.rs | 46 +--- .../src/cognition/workspace/cause.rs | 2 +- .../src/cognition/workspace/tests.rs | 90 ++++--- .../cognition/workspace/workspace_cycle.rs | 9 +- .../cognition/workspace/workspace_cycle_2.rs | 3 +- core/continuum-core/src/ipc/vitals_emitter.rs | 1 - .../mind_integration/bound_card_activity.rs | 4 +- .../mind_integration/hands_isolation.rs | 3 +- .../registry/deliberation/prompt_shaping.rs | 2 - .../registry/deliberation/verdicts.rs | 2 - .../test_env/mind_integration/remote_lane.rs | 1 - .../training_credit/directed.rs | 5 +- .../src/persona/obligation/recover.rs | 1 - .../src/persona/service_loop/tests/part_4.rs | 4 - .../supervisor/materialize_adapters.rs | 1 - .../src/persona/wake_backlog.rs | 4 +- 56 files changed, 349 insertions(+), 910 deletions(-) delete mode 100644 core/continuum-cognition/src/cognition/working_memory/faculty.rs delete mode 100644 core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 4d2f92d2ec..4fc665ee61 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -143,15 +143,6 @@ pub async fn apply_act( // Call history is not a cache-validity proof. Reads can change, failures can // recover, and earlier results may no longer fit the prompt. Execute through // the owning command; authorization and operation-specific idempotency stay there. - // EVERY re-injection bound in this act comes from her LIVE served window, never a - // constant — an unknown window folds NOTHING rather than inventing a number - // ([[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]]). - // WM clips inside its OWN record path (it owns its truncation), so it needs the live - // window too — pushed from here, the seam that has the cycle. Re-pushed every act so a - // lane relaunch at a different `-c` is picked up without a restart. - if let Some((_, w)) = cycle.model_loadout() { - body.working_memory.set_served_window(w); - } let ctx = crate::cognition::tool_executor::ToolExecutionContext { persona_id: body.persona_id, persona_name: body.persona_name.clone(), @@ -398,14 +389,14 @@ pub async fn apply_act( // handle and the executor decodes it once from the full value. if verdict.running() { if let Some(handle) = projected.and_then(|v| v.dispatch_handle) { + // Her command whole, as she wrote it: this label is what her view shows for the + // handle, and a cut command reads as a different one. let label: String = call .input .get("command") .and_then(|v| v.as_str()) .unwrap_or(call.name.as_str()) // label only — the handle is the key - .chars() - .take(80) - .collect(); + .to_owned(); body.working_memory.record_dispatch_event( handle, &format!("{}: {label}", call.name), @@ -471,19 +462,7 @@ pub async fn apply_act( // The human OBJECT of the act: the first extracted path (reads, // writes, edits), else the shell command head, else empty — // honest-thin, never dumped raw JSON args. - let summary = obs - .output - .paths - .first() - .map(|p| p.display().to_string()) - .or_else(|| { - obs.call - .input - .get("command") - .and_then(|c| c.as_str()) - .map(|c| c.chars().take(80).collect::()) - }) - .unwrap_or_default(); + let summary = act_object(obs); let update = crate::cognition::mind_events::PersonaActUpdate { act_id: Uuid::new_v4(), room_id, @@ -532,19 +511,7 @@ pub async fn apply_act( lines.push(crate::cognition::presence_glyph::said_line(said.trim())); } lines.extend(acts.iter().map(|obs| { - let object = obs - .output - .paths - .first() - .map(|p| p.display().to_string()) - .or_else(|| { - obs.call - .input - .get("command") - .and_then(|c| c.as_str()) - .map(|c| c.chars().take(80).collect::()) - }) - .unwrap_or_default(); + let object = act_object(obs); crate::cognition::presence_glyph::act_line( &obs.call.name, &object, @@ -836,3 +803,15 @@ mod tests { ); } } + +/// The human object of an act, for the clients' act line and presence glyph: its first extracted +/// path (a read, a write, an edit), else its shell command, else empty, never raw JSON arguments. +/// Whole: how much of it a client shows is that client's rendering, not a cut made here. +fn act_object(obs: &Observation) -> String { + obs.output + .paths + .first() + .map(|p| p.display().to_string()) + .or_else(|| obs.call.input.get("command").and_then(|c| c.as_str()).map(str::to_owned)) + .unwrap_or_default() // unwrap_or_default: an act with no path and no command has no object +} diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index cdd63e740d..15cc663c56 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -76,7 +76,7 @@ pub mod test_support { } /// Body that shares a specific working-memory buffer — so a test can wire the - /// SAME buffer into a `WorkingMemoryFaculty` on the cycle and watch the + /// SAME buffer into her view's sources and watch the /// perception of the persona's own hands flow act→memory→next-tick perception /// (the proprioception channel that replaced the deleted world-state fold). pub fn body_with_wm( @@ -335,7 +335,7 @@ pub mod test_support { /// canonical act→observe arc the driver exists to run. /// /// It perceives its own hands through the working-memory proprioception channel - /// (the `WorkingMemoryFaculty` stamps each act `[action #n]`), NOT the deleted + /// (her trail stamps each act `[action #n]`), NOT the deleted /// world-state fold. It remembers the highest action stamp it has already spoken /// about (`responded_through`) so that across SEPARATE concerns — where the /// volatile buffer still carries the prior concern's action — it re-awakens and @@ -345,14 +345,46 @@ pub mod test_support { pub struct ActThenSpeak { pub responded_through: std::sync::atomic::AtomicU64, pub admission_open: Option>, + /// The working memory her view reads, when the test wires one (`perceived_with`). + pub memory: Option>, } impl ActThenSpeak { pub fn new() -> Self { Self { responded_through: std::sync::atomic::AtomicU64::new(0), admission_open: None, + memory: None, } } + + /// Perceive her own acts the way her view gives them, from `memory`. + pub fn with_memory(mut self, memory: Arc) -> Self { + self.memory = Some(memory); + self + } + } + + /// What a fixture deliberation perceives, as production's does: the broadcast, plus (when + /// wired) what her view gives her from working memory, which is her settled acts' results + /// (the actions source), the newest result riding whole after her view, and her trail. + pub fn perceived_with(ws: &Workspace, memory: Option<&crate::cognition::working_memory::WorkingMemory>) -> String { + let mut perceived = ws.perceived(); + if let Some(memory) = memory { + let (acts, _) = memory.action_renderings(); + for act in acts { + perceived.push('\n'); + perceived.push_str(&act.full); + } + if let Some(newest) = memory.pinned_active_result_block() { + perceived.push('\n'); + perceived.push_str(&newest); + } + for line in memory.recent() { + perceived.push('\n'); + perceived.push_str(&line); + } + } + perceived } /// Highest `[action #N]` stamp present in the assembled perception, 0 if none. pub fn latest_action_seq(perceived: &str) -> u64 { @@ -380,7 +412,7 @@ pub mod test_support { } use std::sync::atomic::Ordering; - let latest = latest_action_seq(&ws.perceived()); + let latest = latest_action_seq(&perceived_with(ws, self.memory.as_deref())); if latest > self.responded_through.load(Ordering::Relaxed) { self.responded_through.store(latest, Ordering::Relaxed); Some(Contribution::verdict( diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index ee549c78c6..6088445bc6 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -263,8 +263,14 @@ impl Observation { /// #205 KV-stability invariant. `intent` is batch-level (one per `apply_act` /// call, shared by every act in the batch), so it is passed rather than /// stored per-`Observation`. + /// The call as she made it, `name(args)`: its arguments by shape, never by size + /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part + /// and its ledger line. + pub(crate) fn call_line(&self) -> String { + format!("{}({})", self.call.name, render_call_args(&self.call.input)) + } + pub fn render_recency(&self, intent: &str) -> String { - let args = render_call_args(&self.call.input); // The intent rides the result as a ONE-LINE reason, its first line: a shape rule, // never a size, and never the whole monologue. // Measured 2026-09-04: one result header carried 2,902 chars of intent @@ -276,13 +282,7 @@ impl Observation { } else { format!(" because {}", intent_label(intent)) }; - format!( - "{}({}){}\nResult:\n{}\n\n", - self.call.name, - args, - because, - self.body_text().trim(), - ) + format!("{}{}\nResult:\n{}\n\n", self.call_line(), because, self.body_text().trim()) } /// This act as one part of a batch receipt's summary level: the recency header (its name and @@ -290,11 +290,10 @@ impl Observation { /// summary reads what the receipt shows her, never the executor's serialized JSON, where a /// read's numbered lines are escaped and no code level is found (Codex on #5424). pub(crate) fn render_summary_part(&self, level: impl Fn(&str) -> Option) -> String { - let args = render_call_args(&self.call.input); let body = self.body_text(); let body = body.trim(); let shown = level(body).unwrap_or_else(|| body.to_owned()); // unwrap_or: a body with no smaller level is its own summary - format!("{}({})\nResult:\n{}\n\n", self.call.name, args, shown) + format!("{}\nResult:\n{}\n\n", self.call_line(), shown) } /// The RECALL-channel rendering: the COLLAPSED reference the Episodic engram diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 1a6c487a32..17ef06bb10 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -242,7 +242,7 @@ std::future::pending().await } } - let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc], Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc], Arc::new(SalienceArbiter)); let mut conversation = ScriptedConversation::new(); conversation.prime().await.unwrap(); // unwrap: test fixture let room = crate::identity::ActivityRoom::from_uuid(uuid::Uuid::new_v4()).unwrap(); // unwrap: a fresh uuid is a valid room diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs index a2814d7589..04347369f2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs @@ -36,7 +36,7 @@ async fn a_batch_whose_effect_mark_is_refused_never_reaches_the_executor() { result_content: "4\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused)))); let outcome = apply_act(&cycle, &[tool_call()], "check the math", Uuid::new_v4(), &chain, None, None).await; @@ -69,7 +69,7 @@ async fn a_sentinel_only_batch_is_no_effect_and_takes_no_mark() { seen_context: Arc::new(Mutex::new(None)), result_content: "reported".into(), }); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused)))); let cut = ToolCall { @@ -95,7 +95,7 @@ async fn apply_act_scopes_to_the_room_and_observes_the_result() { result_content: "4\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); @@ -235,7 +235,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() { let exec = Arc::new(FoldedRunningExecutor { handle }); let the_body = body(exec.clone(), admission()); let wm = the_body.working_memory.clone(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(the_body); let call = ToolCall { @@ -292,7 +292,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() { // live in the faculty now lives here (the faculty only emits the Act verdict). #[tokio::test] async fn apply_act_without_hands_abstains() { - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)); assert!( matches!( apply_act( @@ -317,7 +317,7 @@ async fn apply_act_without_hands_abstains() { #[tokio::test] async fn apply_act_abstains_when_the_hand_fails() { let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(FailingExecutor), adm.clone())); assert!( matches!( @@ -394,21 +394,21 @@ async fn an_acts_calls_carry_the_generation_that_issued_them() { ]; let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) }; - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(exec.clone()), admission())); let stamped = apply_act(&cycle, &two_submits, "submit both", Uuid::new_v4(), &ActChain::new(), None, Some("gen-1".into())).await; assert!(matches!(stamped, ActOutcome::Acted { .. }), "{stamped:?}"); assert_eq!(seen_of(&exec), vec![Some("gen-1".to_string()); 2], "one act, one issuing generation, every call"); let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) }; - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(exec.clone()), admission())); let unstamped = apply_act(&cycle, &[tool_call()], "no generation", Uuid::new_v4(), &ActChain::new(), None, None).await; assert!(matches!(unstamped, ActOutcome::Acted { .. }), "{unstamped:?}"); assert_eq!(seen_of(&exec), vec![None], "no generation, no stamp"); let plain = Arc::new(RecordingExecutor { seen_context: Arc::new(Mutex::new(None)), result_content: "ok".into() }); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8).with_acting(body(plain, admission())); + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)).with_acting(body(plain, admission())); let acted = apply_act(&cycle, &[tool_call()], "cannot stamp", Uuid::new_v4(), &ActChain::new(), None, Some("gen-2".into())).await; assert!(matches!(acted, ActOutcome::Acted { .. }), "hands that cannot stamp still act: {acted:?}"); } diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs index 3d053b847f..ef5b0296f5 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs @@ -22,7 +22,7 @@ async fn a_settle_chain_links_each_act_caused_by_its_predecessor() { result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); let chain = ActChain::new(); @@ -80,7 +80,7 @@ async fn a_chain_rooted_in_its_trigger_links_the_first_act_to_what_caused_the_tu result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); @@ -114,7 +114,7 @@ async fn an_unrooted_chain_leaves_its_first_act_honestly_unlinked() { result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let chain = ActChain::rooted_in(&crate::cognition::workspace::Cause::Ambient); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs index 689aeeb1ed..145842b41e 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs @@ -3,14 +3,12 @@ use super::*; use crate::cognition::workspace::TurnFraming; use crate::cognition::workspace::WorkspaceCycle; -use crate::cognition::workspace::Faculty; use crate::cognition::workspace::SalienceArbiter; use crate::ai::types::ToolCall; use uuid::Uuid; use std::sync::Arc; use std::sync::Mutex; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; // what this catches: c5910be2 — an ordinary room drive could not see coaching // until it settled. Inject through the conversation DURING a real tool action, @@ -114,7 +112,6 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { .with_request_recorder(Arc::clone(&recorded)), ); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); let adm = admission(); let body = body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm)); let persona = body.persona_id; @@ -135,11 +132,9 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { }]); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm)) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body); let task = "Review the original src/lib.rs change and report a reproducible defect."; diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 5d5999546d..23a3f44e65 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -3,7 +3,6 @@ use super::*; use crate::ai::types::ToolCall; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; use crate::cognition::workspace::Contribution; use crate::cognition::workspace::Decision; use crate::cognition::workspace::Faculty; @@ -60,11 +59,9 @@ async fn drive_to_settle_acts_then_settles_on_speak() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(ActThenSpeak::new()), + Arc::new(ActThenSpeak::new().with_memory(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -84,7 +81,7 @@ async fn drive_to_settle_acts_then_settles_on_speak() { // Refusal after a real act retains its observed work and cannot replay input. #[tokio::test] async fn acted_then_capacity_refused_retains_work_without_replay() { - struct ActThenRefuse; + struct ActThenRefuse(Arc); #[async_trait] impl Faculty for ActThenRefuse { fn id(&self) -> FacultyId { @@ -94,7 +91,7 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { true } async fn contribute(&self, ws: &Workspace) -> Option { - if latest_action_seq(&ws.perceived()) > 0 { + if latest_action_seq(&crate::cognition::act_observe::test_support::perceived_with(ws, Some(&self.0))) > 0 { Some(Contribution::prompt_capacity_refused( crate::cognition::workspace::PromptCapacityError { required_tokens: 8192, @@ -117,11 +114,9 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { let exec = Arc::new(ScriptedExecutor::new(["real observed result"])); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm.clone())), - Arc::new(ActThenRefuse), + Arc::new(ActThenRefuse(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), wm)); let outcome = drive_to_settle(&cycle, "perform the task", 8, TurnFraming::ambient()).await; @@ -165,7 +160,7 @@ async fn capacity_refusal_leaves_the_driver_once_with_typed_custody() { } } let faculty = Arc::new(Refusing(std::sync::atomic::AtomicUsize::new(0))); - let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter)); let outcome = drive_to_settle(&cycle, "keep the complete input", 8, TurnFraming::ambient()).await; assert_eq!(faculty.0.load(std::sync::atomic::Ordering::SeqCst), 1); @@ -201,11 +196,9 @@ async fn a_zero_change_speak_reperceives_up_to_the_narration_budget_when_the_wor }); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::clone(&speaker) as Arc, ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm))); @@ -248,11 +241,9 @@ async fn an_ordinary_turn_still_settles_on_the_first_speak() { }); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::clone(&speaker) as Arc, ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm))); @@ -326,7 +317,6 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body(exec.clone(), adm.clone())); @@ -361,7 +351,6 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body(exec2, admission())); let ambient = drive_to_settle(&cycle2, "look around", 20, TurnFraming::ambient()).await; @@ -392,7 +381,6 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(the_body); drive_to_settle( @@ -433,7 +421,6 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body2); drive_to_settle(&cycle2, "look around", 6, TurnFraming::ambient()).await; @@ -456,7 +443,7 @@ async fn drive_to_settle_returns_unsettled_act_when_budget_exhausted() { result_content: "...".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let outcome = drive_to_settle(&cycle, "go", 2, TurnFraming::ambient()).await; @@ -491,7 +478,7 @@ async fn repeated_calls_respect_the_callers_budget() { ), ] { let exec = Arc::new(ScriptedExecutor::new(results)); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let outcome = drive_to_settle(&cycle, "go", 6, TurnFraming::ambient()).await; assert_eq!(outcome.acts, expected_acts); @@ -508,7 +495,7 @@ async fn fixed_point_requires_available_finished_result_evidence() { use super::super::perception::batch_evidence; use crate::sdk_codegen::{ActVerdict, ToolVerdict}; let exec = Arc::new(ScriptedExecutor::new(["result"])); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec, admission())); let mut call = tool_call(); let mut acts = acts_of(apply_act( @@ -549,7 +536,7 @@ async fn settle_step_defers_the_act_without_executing_when_may_act_is_false() { result_content: "...".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let (deferred, _, _) = settle_step( diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs index fea5a8df86..9c988f5e5a 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs @@ -16,7 +16,6 @@ use async_trait::async_trait; use std::sync::Arc; use std::sync::Mutex; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; /// A deliberation faculty that is a small *investigator*: its next move is a /// pure function of what it has DISCOVERED so far (the observations folded @@ -27,7 +26,7 @@ use crate::cognition::working_memory::WorkingMemoryFaculty; /// accumulated MEMORY CONTENT, which is the whole point: the hands change /// the mind. (A test stand-in for the model, exactly like `ActThenSpeak`; /// it proves the cycle's cross-tick plumbing, not production cognition.) -struct Investigator; +struct Investigator(Arc); #[async_trait] impl Faculty for Investigator { fn id(&self) -> FacultyId { @@ -41,7 +40,7 @@ impl Faculty for Investigator { // working-memory render of its own recent acts (proprioception), // where each act-observation head carries the executor's result tokens // (ENTRY=…/CALLS=…). Not the raw burst, not the deleted fold. - let perceived = ws.perceived(); + let perceived = crate::cognition::act_observe::test_support::perceived_with(ws, Some(&self.0)); let after = |key: &str| -> Option { perceived .split(key) @@ -105,11 +104,9 @@ async fn the_hands_change_the_mind_across_a_multi_act_investigation() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(Investigator), + Arc::new(Investigator(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -186,7 +183,7 @@ async fn repeated_reads_and_scoped_discovery_reach_the_executor() { "old", "edited", "new", "missing", "available", "schema one", "schema two", "tree one", "tree two", ]).with_error_at(4)); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let room = Uuid::new_v4(); let chain = ActChain::new(); @@ -216,7 +213,7 @@ async fn repeated_reads_and_scoped_discovery_reach_the_executor() { async fn repeated_request_keeps_current_room_and_returns_fresh_evidence() { let exec = Arc::new(ScriptedExecutor::new(["room-a content", "room-b content"])); let wm = Arc::new(WorkingMemory::new(3)); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body_with_wm(exec.clone(), admission(), wm.clone())); let rooms = [Uuid::new_v4(), Uuid::new_v4()]; for (i, room) in rooms.into_iter().enumerate() { @@ -267,11 +264,9 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(ActThenSpeak::new()), + Arc::new(ActThenSpeak::new().with_memory(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -344,7 +339,6 @@ async fn spoken_narrated_action_records_unfulfilled_promise() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(promise)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step( @@ -367,7 +361,6 @@ async fn spoken_narrated_action_records_unfulfilled_promise() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText("the answer is 4, plainly.")) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step( @@ -411,7 +404,6 @@ async fn a_near_identical_copy_of_a_peers_line_is_a_pass_not_a_post() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(peer_line)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step(&cycle, burst(), true, TurnFraming::ambient(), Situation::FreshContext, &ActChain::new()).await; @@ -426,7 +418,6 @@ async fn a_near_identical_copy_of_a_peers_line_is_a_pass_not_a_post() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText(own)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step(&cycle2, burst(), true, TurnFraming::ambient(), Situation::FreshContext, &ActChain::new()).await; @@ -459,7 +450,6 @@ async fn fenced_content_over_unkept_promises_records_unverified_artifact() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(confabulated)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step( @@ -488,7 +478,6 @@ async fn fenced_content_over_unkept_promises_records_unverified_artifact() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText(confabulated)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec2, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step( diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index a946bb53ca..aa4e1bfb6b 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -162,9 +162,7 @@ fn a_thought_renders_the_same_whatever_the_served_window() { let render = |memory: &WorkingMemory| { Thoughts { memory, persona: uuid::Uuid::nil() }.items().into_iter().map(|item| item.full().text.clone()).collect::>() }; - memory.set_served_window(32_768); let narrow = render(&memory); - memory.set_served_window(131_072); assert_eq!(render(&memory), narrow, "the window changed and the thought's rendering did not"); } diff --git a/core/continuum-cognition/src/cognition/deliberation_prompt.rs b/core/continuum-cognition/src/cognition/deliberation_prompt.rs index 5cf69a1cf8..b929aa921d 100644 --- a/core/continuum-cognition/src/cognition/deliberation_prompt.rs +++ b/core/continuum-cognition/src/cognition/deliberation_prompt.rs @@ -147,7 +147,6 @@ pub(super) enum PromptChurn { /// The churn class of a grounding block, by the source id it renders under. pub(super) fn churn_of(faculty: &str) -> PromptChurn { - use crate::cognition::working_memory::WM_FACULTY_ID; use crate::cognition::workspace::FacultyId; use crate::cognition::faculty_ids::{ ACTIVE_WORK, AIRC, AWARENESS, ENGRAMS, MEDIA_PERCEPTION, MISSION, ROOM_BOARD, @@ -166,7 +165,7 @@ pub(super) fn churn_of(faculty: &str) -> PromptChurn { | WALL | ACTIVE_WORK => PromptChurn::Board, ROOM_BOARD => PromptChurn::Claims, - ENGRAMS | AIRC | WM_FACULTY_ID => PromptChurn::Turn, + ENGRAMS | AIRC => PromptChurn::Turn, // The strip changes with every event in any of her rooms: turn churn, after the // standing and board blocks, so her awareness never displaces the cached prefix. AWARENESS => PromptChurn::Turn, @@ -954,7 +953,6 @@ mod tests { let mut live = vec!["room-kanban", "room-wall", "roster", "active-work"]; live.sort_by(|a, b| stable_prefix_order(a, b)); assert_eq!(live, ["active-work", "room-wall", "roster", "room-kanban"]); - assert_eq!(churn_of("working-memory"), PromptChurn::Turn); assert_eq!(churn_of("engrams"), PromptChurn::Turn); assert_eq!(churn_of("media-perception"), PromptChurn::Standing); } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 9d6a932a44..55e4ee28f9 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -195,7 +195,7 @@ pub struct LlmDeliberationFaculty { /// Where this faculty records its chain-of-thought after a verdict, so the /// persona can resume its train of thought next turn (the /// [`WorkingMemory`](crate::cognition::working_memory::WorkingMemory) - /// `WorkingMemoryFaculty` reads). `None` → reasoning is dropped (the prior + /// her view's thoughts source reads). `None` → reasoning is dropped (the prior /// behavior). Only the suppressed-thinking default makes `reasoning` empty, so /// this self-activates exactly when thinking is on. working_memory: Option>, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs index f330599492..b56b6cccb1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs @@ -213,8 +213,8 @@ impl LlmDeliberationFaculty { // today: the working-memory faculty). // PINNED just-executed result (#392, run-18057-f1). The full result of the act // she just ran is appended DIRECTLY from the shared working-memory buffer as the - // newest trailing turn — deliberately NOT routed as a faculty bid. As part of the - // working-memory contribution at `WORKING_MEMORY_SALIENCE` it competed in + // newest trailing turn — deliberately NOT routed as a faculty bid. As part of a + // working-memory faculty's bid (that faculty is deleted) it competed in // `arbiter.focus()` top-k and was evicted whole under capacity pressure, so the // persona generated blind to her own grep/read output (the 0-byte SWE-bench patch). // Reading it here puts no attention pass between the hands and the mind. @@ -246,12 +246,11 @@ impl LlmDeliberationFaculty { // between acts (`deliberation_prompt::stable_prefix_order`). Outside the view a block // sat behind it, and every act's append landed before it and re-sent it: on the M5 // (2026-10-21 19:56Z) Aris re-prefilled 49k chars from `[workspace-map]` on. Her - // working-memory bid is not one of them: her thoughts and actions are their own streams. + // thoughts and actions are not among them: they are their own streams in her view. let mut pieces: Vec<&Contribution> = ws .broadcast .iter() .filter(|c| c.decision.is_none() && c.fault.is_none() && c.trailing) - .filter(|c| c.faculty.as_str() != crate::cognition::working_memory::WM_FACULTY_ID) .filter(|c| !c.content.trim().is_empty()) .collect(); pieces.sort_by(|a, b| deliberation_prompt::stable_prefix_order(a.faculty.as_str(), b.faculty.as_str())); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs index 411b50bc22..953427498a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs @@ -15,7 +15,6 @@ async fn a_huge_legacy_result_arrives_reduced_with_its_handle_never_refused() { let window = 8_192u32; let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let huge: String = (0..6_000).map(|i| format!("line {i} of a very large tool result\n")).collect(); wm.record_receipt_typed(&[], &huge, None, ResultCustody::Whole { handle: "legacy-evidence".into() }); @@ -84,7 +83,6 @@ mod the_newest_result_over_her_window { /// The same, served at `window`. fn faculty_at(content: &str, adapter: Arc, window: u32) -> LlmDeliberationFaculty { let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let room = Uuid::new_v4(); let call = ToolCall { id: "call-aris".into(), name: "work/submission".into(), input: json!({ "include_staged_evidence": true }) }; wm.record_native_action_statement("Reading the staged evidence for my submission.", room, std::slice::from_ref(&call)); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs index dcea4123ea..d9babd71c6 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs @@ -774,7 +774,6 @@ fn a_budget_too_small_for_even_one_unit_emits_no_header_at_all() { #[test] fn the_results_ring_renders_before_churning_grounding() { let wm = Arc::new(crate::cognition::working_memory::WorkingMemory::new(3)); - wm.set_served_window(32_768); let custody = |h: &str| crate::ai::types::ResultCustody::Whole { handle: h.into() }; wm.record_receipt_typed(&[], "RING-ENTRY older result", None, custody("1111111111111111")); wm.record_receipt_typed(&[], "the newest result", None, custody("2222222222222222")); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs index eeff1a31f8..3c228b28d9 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs @@ -6,8 +6,8 @@ use super::*; // recorded no-deliverable facts. Fit the actual projection after that eviction. #[tokio::test] async fn substrate_notices_survive_attention_and_history_pressure_once() { - use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; - use crate::cognition::workspace::{Arbiter, Faculty, FocusContext, SalienceArbiter, Situation}; + use crate::cognition::working_memory::WorkingMemory; + use crate::cognition::workspace::{Arbiter, FocusContext, SalienceArbiter, Situation}; let wm = Arc::new(WorkingMemory::new(8)); wm.record("weighing the next step"); wm.record_fact("[no-deliverable] No workspace change yet."); @@ -26,23 +26,18 @@ async fn substrate_notices_survive_attention_and_history_pressure_once() { Uuid::new_v4(), "T", "You are T.", Arc::new(HeuristicInferenceAdapter::new()), ).with_working_memory(Arc::clone(&wm)); let mut ws = Workspace::new("continue the existing task"); - let memory = WorkingMemoryFaculty::new(Arc::clone(&wm)).contribute(&ws).await.unwrap(); - assert!(!memory.content.contains("[no-deliverable]"), "notices have one projection"); - let mut bids: Vec<_> = (0..6).map(|i| Contribution::context( + let bids: Vec<_> = (0..6).map(|i| Contribution::context( FacultyId::Custom(format!("source-{i}")), "standing context", 0.9, "fixture", )).collect(); - bids.push(memory.clone()); - ws.broadcast = SalienceArbiter.focus(bids, 6, &FocusContext { + ws.broadcast = SalienceArbiter.focus(bids, &FocusContext { world_state: &ws.world_state, situation: Situation::PostAction, }); - assert!(!ws.broadcast.iter().any(|c| c.faculty == memory.faculty)); // Her notices ride her view as a required source (`context_streams::notices`): the // allocation grants their floor before anything optional, and the final fit never cuts // her view. So through the production path, at every window from 256 tokens (too small) to roomy, // a prompt that would be sent carries each notice exactly once, and a window that // cannot hold them says so instead of sending a prompt without them. - for keep_memory in [false, true] { - if keep_memory { ws.broadcast.push(memory.clone()); } + { let (mut sent, mut refused) = (0, 0); for window in (256u32..=65_536).step_by(2_048) { let view = faculty.prompt_view_within(&ws, window); @@ -71,10 +66,9 @@ async fn substrate_notices_survive_attention_and_history_pressure_once() { wm.end_of_work_turn(); assert!(wm.notice_details().is_empty(), "detail and reference share expiry"); assert!(!wm.notices().iter().any(|notice| notice.contains("work/get"))); - // A notice-only memory has no optional thought bid at all. + // A notice-only memory still fits: its notices are her view's required source. let only = Arc::new(WorkingMemory::new(8)); only.record_fact("[no-deliverable] No workspace change yet."); - assert!(WorkingMemoryFaculty::new(Arc::clone(&only)).contribute(&ws).await.is_none()); let faculty = LlmDeliberationFaculty::new( Uuid::new_v4(), "T", "You are T.", Arc::new(HeuristicInferenceAdapter::new()), ).with_working_memory(only); @@ -153,7 +147,6 @@ async fn own_history_preserves_corrections_at_each_inference_step() { let persona = Uuid::new_v4(); let calls = Arc::new(Mutex::new(Vec::new())); let wm = Arc::new(WorkingMemory::new(16)); - wm.set_served_window(32_768); let faculty = LlmDeliberationFaculty::new( persona, "Anwen", diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs index 5424a15045..f3fa0313e7 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs @@ -465,7 +465,7 @@ async fn directed_turn_withholds_the_silence_escape() { // "This message names you". Exercise the real framing -> cycle -> // prompt seam on both admission and act-result re-perception. let identity = PersonaIdentity::new(faculty.persona_id, "Kimi"); - let cycle = WorkspaceCycle::new(vec![], Arc::new(SalienceArbiter), 4); + let cycle = WorkspaceCycle::new(vec![], Arc::new(SalienceArbiter)); for (text, human, expected_attention, expected_class) in [ ( "Joel here — which card do you hold?", diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs index ec262ad005..0e3b3edc39 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs @@ -22,7 +22,6 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { None, )])); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let result = format!( "src/lib.rs:42: concrete_review_target\n{{\"payload\":\"{}\"}}\nclaimable_now: 29\ntotal_on_board: 43", "x".repeat(window as usize * 2), @@ -218,7 +217,6 @@ async fn an_8192_window_keeps_required_content_under_a_large_measured_need() { let need = reg.need_of(persona).expect("measured"); assert!(need.total() > window, "the fixture's need exceeds the whole seat"); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let result = format!("src/schema.rs:7: accounts_table_defined\n{}", "column detail ".repeat(40)); wm.record_receipt(&result); let adapter = Arc::new(ScriptedAdapter::new(vec![make_response( @@ -286,7 +284,6 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { )); let registry = WorkingSetRegistry::new(); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let oversized = "payload ".repeat(window as usize); let mut ws = if oversized_part == 0 { Workspace::new(&oversized) diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index ef9c8369a0..ef1bc389fb 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -33,7 +33,7 @@ use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalE use super::llm_deliberation_faculty::LlmDeliberationFaculty; use super::rag_source_faculty::{RagSourceFaculty, SaliencePolicy}; use super::recall_faculty::RecallFaculty; -use super::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use super::working_memory::WorkingMemory; use super::workspace::{ActingBody, Faculty, SituationFocusArbiter, WorkspaceCycle}; use crate::ai::adapter::AIProviderAdapter; use crate::cognition::admission_state::AdmissionState; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs index 7da34b6291..696807d25c 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs @@ -1,10 +1,5 @@ use super::*; -/// Default bounded workspace capacity — the finite attention "spotlight". Enough -/// for recall + world-model + affect + roster context to coexist; the arbiter -/// keeps it bounded so cost stays O(capacity) no matter how many faculties bid. -pub const DEFAULT_WORKSPACE_CAPACITY: usize = 6; - /// Everything needed to assemble one persona's continuous mind. The `admission` /// is the persona's UNIFIED hippocampus (shared with the admission pipeline and /// spanning all the persona's rooms); the `adapter` is the shared model backend, @@ -22,8 +17,6 @@ pub struct PersonaBrainConfig { pub system_prompt: String, pub admission: Arc, pub adapter: Arc, - /// Bounded workspace capacity; `None` → [`DEFAULT_WORKSPACE_CAPACITY`]. - pub capacity: Option, /// Grounding RagSources lifted into perception-tier faculties via /// [`RagSourceFaculty`] (the migration bridge — see its module doc). Each is /// paired with a [`SaliencePolicy`]: roster + doctrine are `StandingFraming` @@ -308,8 +301,8 @@ pub(super) fn assemble_workspace_cycle( }); // Working memory: the persona's recent chain-of-thought AND the head of what its // hands just did, carried forward across turns. The deliberator WRITES its - // reasoning here after each verdict; the perception-tier `WorkingMemoryFaculty` - // (pushed below) READS it into the next tick — so the persona resumes its train of + // reasoning here after each verdict; her view's thoughts and actions sources READ it + // into the next tick — so the persona resumes its train of // thought instead of re-deriving it cold. Volatile scratchpad, distinct from the // long-term engram store; self-activates only when thinking is enabled (suppressed // turns record nothing). Built HERE (before recall) so recall can share it in and @@ -427,13 +420,6 @@ pub(super) fn assemble_workspace_cycle( faculties.push(Arc::new(recall)); } - // The perception-tier reader of the working memory built above: each tick it bids - // the recent reasoning + act heads into the workspace so the deliberator conditions - // on them. (The buffer itself is created before recall so recall can share it in.) - faculties.push(Arc::new(WorkingMemoryFaculty::new(Arc::clone( - &working_memory, - )))); - // Bridge each grounding source into a perception-tier faculty under its // salience policy. Standing-framing (roster, doctrine) bids at a high floor so // the top-k arbiter never evicts the room's rules under attention pressure. @@ -561,13 +547,9 @@ pub(super) fn assemble_workspace_cycle( let cycle = WorkspaceCycle::new( faculties, - // Situation-aware focuser: on every act→observe re-perception (`PostAction`) - // it drops the standing SOCIAL re-grounding so the tool result + working - // memory + recall own the window — the persona goes lean and code-first while - // heads-down, and fuller-grounded on a fresh ask. This is the wire behind - // "straightforward for whatever their current state requires." + // Situation-aware focuser: every bid is forwarded, ordered by salience; how much + // of each she sees is her view's one allocation. Arc::new(SituationFocusArbiter::new()), - cfg.capacity.unwrap_or(DEFAULT_WORKSPACE_CAPACITY), ) .with_genome(genome) .with_decoding(decoding) @@ -591,7 +573,7 @@ pub(super) fn assemble_workspace_cycle( persona_name: persona_name_for_body, executor, admission: admission_for_body, - // Same buffer the perception-tier WorkingMemoryFaculty reads — the + // Same buffer her view's sources read — the // organism records each act here so the mind perceives its own hands // next tick (proprioception), even when the result is a dedup no-op in // long-term memory and thinking is suppressed. diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs index b49dc23bc8..59670f2fa5 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs @@ -136,7 +136,6 @@ use super::*; system_prompt: "You are Ivar, an engineer on the grid.".to_string(), admission: seed_admission(1_000_000_000), adapter: Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -411,7 +410,6 @@ use super::*; let cycle = WorkspaceCycle::new( faculties, Arc::new(SalienceArbiter), - DEFAULT_WORKSPACE_CAPACITY, ) .with_capture(sink.clone()); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 7af2838e13..ec36aff556 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -190,7 +190,6 @@ use super::*; // of a mind with no live working memory still protects it (Astra on acdfb010a). { let memory = WorkingMemory::new(8); - memory.set_served_window(16_384); let cap = 8_192; // a test body size; a shed below it collapses the older ones let saved = |handle: &str| crate::ai::types::ResultCustody::Whole { handle: handle.into() }; memory.record_receipt_typed(&[], &"c".repeat(cap / 2), None, saved("c011a75ed0000001")); diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs index 0aa0823870..aed446f872 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -514,7 +514,7 @@ ), Arc::new(SeesDoctrine), ]; - let ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 6) + let ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .run("is anyone going to merge this?") .await; @@ -621,7 +621,6 @@ let _ = WorkspaceCycle::new( faculties, Arc::new(SalienceArbiter), - DEFAULT_CAPACITY_FOR_TEST, ) .with_capture(sink.clone()) .run("anything urgent?") diff --git a/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs b/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs index 4309878d5c..24fda93939 100644 --- a/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs @@ -18,7 +18,6 @@ use super::*; let ws = WorkspaceCycle::new( faculties, Arc::new(super::super::super::workspace::SalienceArbiter), - 5, ) .with_capture(Arc::new(PrintingSink)) .run("teammate asks: where did we land on the deploy?") diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index 854a71a458..468128513b 100644 --- a/core/continuum-cognition/src/cognition/request_replay.rs +++ b/core/continuum-cognition/src/cognition/request_replay.rs @@ -484,7 +484,6 @@ mod tests { // A diagnostic changes only named historical pointers, never tool protocol or settings. let mut diagnostic = request.clone(); let wm = crate::cognition::working_memory::WorkingMemory::new(8); - wm.set_served_window(16_384); wm.record_receipt_typed(&[], "historical result", Some(room), crate::ai::types::ResultCustody::Whole { handle: "0123abcd".into() }); wm.record_receipt("current result"); diff --git a/core/continuum-cognition/src/cognition/should_respond_module.rs b/core/continuum-cognition/src/cognition/should_respond_module.rs index 5047fd3bad..a1e299c4dc 100644 --- a/core/continuum-cognition/src/cognition/should_respond_module.rs +++ b/core/continuum-cognition/src/cognition/should_respond_module.rs @@ -171,7 +171,6 @@ mod tests { system_prompt: "You are Ivar, an engineer on the grid.".to_string(), admission: seed_admission(1_000_000_000), adapter: Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 1962dff658..99026b550b 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -24,8 +24,8 @@ //! //! ## How it wires into the Workspace brain //! -//! - [`WorkingMemoryFaculty`] is a PERCEPTION-tier faculty: each tick it bids the -//! recent reasoning into the workspace so the phase-2 deliberator conditions on it. +//! - Her view's sources (`context_streams`: thoughts, actions) read it each act, so the +//! deliberator perceives her recent reasoning and her own acts as items of her view. //! - The deliberation faculty WRITES its reasoning here after producing a verdict //! (the thing that thinks records its thinking). Read at phase 1, written at phase //! 2 → next tick reads the updated buffer. That's the rolling working memory. @@ -38,14 +38,12 @@ //! helps, remember what you reasoned." No config flag needed. use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use uuid::Uuid; -use async_trait::async_trait; use parking_lot::Mutex; -use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; // How many recent steps to carry forward is NOT a constant. It is // `ContextBudget::WORKING_MEMORY_STEPS` — the COUNT sibling of the per-step SIZE bound @@ -76,10 +74,6 @@ use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; /// carrying two opposite meanings in one prompt. One token, one meaning. pub const WM_SETTLEMENT_PREFIX: &str = "[answered]"; -/// The faculty's bid salience. Same tier as retrieved grounding -/// (`RETRIEVED_SALIENCE` = 0.5): useful context that informs the decision but must -/// not outrank standing framing (roster/doctrine, 0.9) or a strong recall hit. -const WORKING_MEMORY_SALIENCE: f32 = 0.5; // The trail-head and latest-action bounds are NOT constants. They are fractions of this // mind's LIVE served context window, owned by `ContextBudget` — see @@ -92,7 +86,6 @@ use crate::cognition::act_observe::Observation; /// Her context view, the type her working memory checkpoints. pub(crate) type ContextView = continuum_context::view::View; -use crate::cognition::context_budget::ContextBudget; /// Clip a full action-result body to [`WM_ACTION_FULL_MAX_CHARS`] for prompt inclusion. /// Returns the body unchanged when it fits; otherwise a `char`-boundary-safe head plus @@ -115,10 +108,6 @@ pub fn collapse_thought(text: &str, keep: usize) -> String { format!("[{} earlier chars — my full thought, collapsed] …{tail}", total - keep) } -/// Max distinct dispatched (background) handles tracked at once. A persona with more than -/// this many sentinels/compiles/debuggers in flight is unusual; past the cap the -/// oldest-updated finished handle is evicted first (a still-running one is never dropped). -const MAX_DISPATCHED: usize = 16; /// Borrowed provenance already carried by the result ring. Displaying a result /// in another activity must not erase where it came from or which operation ran. @@ -202,14 +191,6 @@ struct DispatchedAction { seq: u64, } -/// A bounded, rolling buffer of the persona's recent reasoning. Cheap to clone the -/// `Arc`; shared between the writer (deliberation faculty) and the reader -/// (`WorkingMemoryFaculty`). `parking_lot::Mutex` — no poisoning, and every access -/// is a quick sync snapshot/push with no `.await` held across the lock. -/// The working-memory faculty's canonical id — the ONE string the contribution -/// carries and every consumer (stability ordering in the deliberation tail, -/// capture tooling) matches on. -pub(crate) const WM_FACULTY_ID: &str = "working-memory"; /// A keyed working-memory fact with a lifetime in work turns. #[derive(Debug, Clone)] @@ -220,6 +201,10 @@ struct TurnPinnedFact { detail: Option, } +/// A bounded, rolling buffer of the persona's recent reasoning. Cheap to clone the `Arc`; +/// written by the deliberation faculty and read by her view's sources (`context_streams`). +/// `parking_lot::Mutex` — no poisoning, and every access is a quick sync snapshot/push with no +/// `.await` held across the lock. #[derive(Debug)] pub struct WorkingMemory { /// Process-unique construction ordinal. It keys this mind's set of live spill handles @@ -249,7 +234,6 @@ pub struct WorkingMemory { /// bound below. `0` = not yet known (cold boot / mid-relaunch), which means NO clipping: /// the deliberation guard still trims the assembled prompt to the real `n_ctx`, so an /// unknown window must never be replaced with an invented one. - served_window: AtomicU32, entries: Mutex>, /// The acting root her receipts are stamped with (set at the work-turn /// rooting seam, cleared on restore). See [`WmEntry::scope`]. @@ -270,7 +254,7 @@ pub struct WorkingMemory { /// SAME recency channel as `last_action`, but keyed so concurrent sentinels/compiles/ /// debuggers stream in without clobbering each other. Fed by the completion/progress /// listener (`record_dispatch_event`); surfaced by the faculty so the mind perceives - /// "what I sent away, and where it's at" each heartbeat. Bounded by `MAX_DISPATCHED`. + /// "what I sent away, and where it's at" each heartbeat. A finished handle retires once she has answered a prompt that showed its end. dispatched: Mutex>, /// Monotonic stamp applied to ACTION entries. Two reasons: (1) it makes each /// recorded action a DISTINCT string even when the persona repeats the identical @@ -600,7 +584,7 @@ impl VolatileSnapshot { /// Every saved result this checkpoint still reaches; the persisted twin of what working /// memory publishes live, through the same log and the same rule. pub(crate) fn reachable_handles(&self) -> HashSet { - let log = action_log::ActionLog::from_records(self.action_records(), usize::MAX); + let log = action_log::ActionLog::from_records(self.action_records()); reachable_handles(log.receipt_keys(), &self.receipt_children, &self.open_views) } @@ -711,14 +695,11 @@ pub struct WmEntry { mod action_log; mod continuity; -mod faculty; mod ledger; mod perception; mod residency; pub use action_log::ActOutputRefusal; -pub use faculty::WorkingMemoryFaculty; -pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; pub(crate) use residency::{ResidentResults, ShedCandidate}; @@ -731,3 +712,32 @@ impl Drop for WorkingMemory { #[cfg(test)] mod tests; + +/// Background commands she sent away (sentinels, compiles, debuggers), streaming their +/// status back by handle: what is outstanding and what just finished, so she can pass a +/// handle to a follow-up command. `None` when nothing was dispatched. +pub(crate) fn render_dispatched(dispatched: &[(Uuid, String, String, DispatchStatus)]) -> Option { + if dispatched.is_empty() { + return None; + } + let lines = dispatched + .iter() + .map(|(h, label, latest, status)| { + let hs = h.to_string(); + let short = hs.get(..8).unwrap_or(hs.as_str()); + let tag = match status { + DispatchStatus::Running => "running", + DispatchStatus::Done => "done", + DispatchStatus::Failed => "failed", + }; + let tail = if latest.is_empty() { + String::new() + } else { + format!(": {latest}") + }; + format!("- #{short} {label} [{tag}]{tail}") + }) + .collect::>() + .join("\n"); + Some(format!("Commands you dispatched (background, by handle):\n{lines}")) +} diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index e37245f979..ad4d5af2ec 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -98,18 +98,17 @@ pub(super) struct ActionLog { } impl ActionLog { - /// A log from records in any order, bounded to `archive_chars` like a live one. - pub fn from_records(mut records: Vec, archive_chars: usize) -> Self { + /// A log from records in any order. Nothing here bounds it: a record keeps its line and its + /// handle for as long as her mind lives, and its body's RAM is the one memory owner's to + /// shed (`residency`), never a character cap. + pub fn from_records(mut records: Vec) -> Self { records.sort_by_key(|record| record.seq); records.dedup_by_key(|record| record.seq); - let mut log = Self { records: records.into() }; - log.prune(archive_chars); - log + Self { records: records.into() } } - pub fn push(&mut self, record: ActionRecord, archive_chars: usize) { + pub fn push(&mut self, record: ActionRecord) { self.records.push_back(record); - self.prune(archive_chars); } pub fn get(&self, seq: u64) -> Option<&ActionRecord> { @@ -139,22 +138,6 @@ impl ActionLog { pointers } - /// The newest ledger lines that fit `archive_chars`, oldest first; at least the newest. - pub fn archive(&self, archive_chars: usize) -> Vec<(&ActionRecord, &str)> { - let mut used = 0usize; - let mut kept: Vec<(&ActionRecord, &str)> = Vec::new(); - for (record, head) in self.records.iter().rev().filter_map(|r| r.head.as_deref().map(|h| (r, h))) { - let cost = head.chars().count() + 1; - if !kept.is_empty() && used + cost > archive_chars { - break; - } - used += cost; - kept.push((record, head)); - } - kept.reverse(); - kept - } - /// Every receipt whose dependencies must stay reachable: each retained result's key and /// every handle a record names. A body moved to its handle exists only on disk, so its /// handle is live for as long as its record is, however many pointers are newer. @@ -214,12 +197,4 @@ impl ActionLog { Collapsed { total } } - /// Drop the records nothing can reach any more: past the ledger's share, no body in RAM, - /// and no handle to reload one from. A record naming a handle stays, since its whole is - /// reachable through her view (`StoredWhole`) for as long as the record is. - fn prune(&mut self, archive_chars: usize) { - let keep: HashSet = self.archive(archive_chars).into_iter().map(|(record, _)| record.seq).collect(); - self.records - .retain(|record| record.result.is_some() || record.handle.is_some() || keep.contains(&record.seq)); - } } diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 1947e8cbea..4e6cc7460c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -183,12 +183,13 @@ impl WorkingMemory { // The log, projected into the wire shape older builds read (see // `VolatileSnapshot::action_records`), under one lock so a concurrent collapse // cannot move a record between the projections. - let archive_chars = self.budget().receipt_archive_chars(); let last_action = self.last_action.lock().clone(); let (archive, recent_results, result_scopes, pointers, records) = { let actions = self.actions.lock(); - let archive: Vec<(Option, String)> = - actions.archive(archive_chars).into_iter().map(|(r, head)| (r.room, head.to_owned())).collect(); + let archive: Vec<(Option, String)> = actions + .records() + .filter_map(|record| record.head.as_ref().map(|head| (record.room, head.clone()))) + .collect(); let recent_results: Vec<(u64, Option, String, String, Option)> = actions .retained() .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) @@ -298,11 +299,9 @@ impl WorkingMemory { e.pop_front(); } } - // Same re-clamp contract as `entries`: the log bounds itself to THIS life's share, and - // the collapse below folds results a bigger-window life held into pointers, never a - // silent deletion. - *self.actions.lock() = - action_log::ActionLog::from_records(records, self.budget().receipt_archive_chars()); + // The log is restored whole: what of its bodies stays in RAM is the one memory owner's + // to shed (`residency`), never a share of this life's window. + *self.actions.lock() = action_log::ActionLog::from_records(records); *self.last_action.lock() = snap.last_action; *self.receipt_children.lock() = snap.receipt_children; *self.view.lock() = snap.context_view; @@ -398,7 +397,6 @@ impl WorkingMemory { // hers to decide. let current = env!("CONTINUUM_BUILD_GIT_SHA"); if !snap.build_sha.is_empty() && snap.build_sha != current { - let short = |s: &str| s.chars().take(9).collect::(); // Same lifetime as [resumed]: the rebuild is news at the wake, not a // standing condition — after two turns her receipts on THIS build exist. self.pin_fact_for_turns("rebuilt", &format!( @@ -408,8 +406,8 @@ impl WorkingMemory { not re-read to check. Only the TOOLS may behave differently now: a tool that \ failed before may work on this build, worth re-trying rather than concluding \ from memory.", - short(&snap.build_sha), - short(current), + snap.build_sha, + current, ), 2); } } @@ -437,7 +435,9 @@ impl WorkingMemory { /// never inferred from an owner field — an expired claim still names its last holder, /// and a card in Review is absent from her live claims for a reason that is not a lapse. pub fn note_claim_gone(&self, card: uuid::Uuid, verdict: ClaimGone) { - let id8: String = card.simple().to_string().chars().take(8).collect(); + // Ids whole, as the verbs that take them read them: a prefix is a cut, and the board + // resolves either form (`continuum_base::id_resolve`). + let id = card.simple(); let edge = |ms: Option| { ms.and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64)) .map(|t| format!(" (lease edge {}Z)", t.format("%H:%M"))) @@ -448,26 +448,26 @@ impl WorkingMemory { // Each sentence is what the board SHOWS NOW — never a story about how it got // there (the wake did not watch the lease lapse or the transfer happen). ClaimGone::HeldBy { peer, expires_at_ms } => format!( - "[claim] card {id8} is NO LONGER YOURS: your checkpoint had you working it, and \ + "[claim] card {id} is NO LONGER YOURS: your checkpoint had you working it, and \ the board now shows {} holding it{}. {untouched} Do not resume as its holder — \ work/get {card} shows its state; take it back with work/claim only when it \ reads claimable.", - peer.simple().to_string().chars().take(8).collect::(), + peer.simple(), edge(expires_at_ms), ), ClaimGone::Lapsed { expired_at_ms } => format!( - "[claim] card {id8} is NO LONGER YOURS: your checkpoint had you working it, and \ + "[claim] card {id} is NO LONGER YOURS: your checkpoint had you working it, and \ the board now shows it unheld — the last lease on it ran out{} and nobody holds \ it. {untouched} work/claim {card} takes it back, then continue from your ledger.", edge(expired_at_ms), ), ClaimGone::MovedOn { state } => format!( - "[claim] card {id8} is no longer in your hands: the board now shows it in {state} \ + "[claim] card {id} is no longer in your hands: the board now shows it in {state} \ — that is the card's life advancing, not a lapse. {untouched} Nothing to \ re-claim; work/get {card} shows where it stands." ), ClaimGone::Unknown => format!( - "[claim] your checkpoint had you working card {id8}, but no board you stand in \ + "[claim] your checkpoint had you working card {id}, but no board you stand in \ shows it now, so nothing can be said about who holds it. {untouched} \ work/get {card} before assuming it is yours or free." ), diff --git a/core/continuum-cognition/src/cognition/working_memory/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/faculty.rs deleted file mode 100644 index 899f17bd41..0000000000 --- a/core/continuum-cognition/src/cognition/working_memory/faculty.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! The `Faculty` that bids working memory into the workspace. - -use super::*; - -/// Render the already-budgeted trail in order. A later settlement may correct -/// or repeat an earlier report; similarity cannot replace that event's content. -fn render_trail(recent: &[String]) -> String { - let mut out = String::new(); - for entry in recent { - if !out.is_empty() { - out.push('\n'); - } - out.push_str("- "); - out.push_str(entry); - } - out -} - -/// Background commands she sent away (sentinels, compiles, debuggers), streaming their -/// status back by handle: what is outstanding and what just finished, so she can pass a -/// handle to a follow-up command. `None` when nothing was dispatched. -pub(crate) fn render_dispatched(dispatched: &[(Uuid, String, String, DispatchStatus)]) -> Option { - if dispatched.is_empty() { - return None; - } - let lines = dispatched - .iter() - .map(|(h, label, latest, status)| { - let hs = h.to_string(); - let short = hs.get(..8).unwrap_or(hs.as_str()); - let tag = match status { - DispatchStatus::Running => "running", - DispatchStatus::Done => "done", - DispatchStatus::Failed => "failed", - }; - let tail = if latest.is_empty() { - String::new() - } else { - format!(": {latest}") - }; - format!("- #{short} {label} [{tag}]{tail}") - }) - .collect::>() - .join("\n"); - Some(format!("Commands you dispatched (background, by handle):\n{lines}")) -} - -/// Perception-tier faculty that bids the persona's recent reasoning into the -/// workspace — so the deliberator can resume its own train of thought rather than -/// re-deriving it cold each turn. Abstains when there's nothing recorded (first -/// turns, or thinking suppressed). -pub struct WorkingMemoryFaculty { - memory: Arc, -} - -impl WorkingMemoryFaculty { - pub fn new(memory: Arc) -> Self { - Self { memory } - } - - fn faculty_id() -> FacultyId { - FacultyId::Custom(WM_FACULTY_ID.to_string()) - } -} - -#[async_trait] -impl Faculty for WorkingMemoryFaculty { - fn id(&self) -> FacultyId { - Self::faculty_id() - } - - // Perception tier (default): reacts to the raw world-state, bidding the recent - // reasoning into phase 1 so the deliberator conditions on it in phase 2. - async fn contribute(&self, ws: &Workspace) -> Option { - let mut entries = self.memory.recent_entries(); - // Public action statements use their room-scoped assistant projection, - // never the optional interior-thought bid. Facts use the required notice projection. - entries.retain(|entry| !matches!(entry.kind, WmKind::ActionStatement { .. } | WmKind::Fact)); - let dispatched = self.memory.dispatched_snapshot(); - if entries.is_empty() && dispatched.is_empty() { - return None; - } - // Render BY KIND (the recent_entries contract; PERCEPTION-FACTS.md). - // Substrate Facts ([resumed]/[context]/[repetition]…) are the SYSTEM's - // second-person notices posted into her window — NOT her thoughts. - // Glass-boxed 2026-08-01 (#264 fourth finding): lumping them into the - // "my interior state" block made the model resolve the voice conflict - // by converting the notice to first person and SPEAKING it — 2f50b223 - // posted "My session was interrupted under a minute ago and my memory - // restored; nothing was in flight" verbatim into the room, a - // scaffold-echo of the [resumed] briefing. Same bug class as the - // second-person header this comment block's sibling above fixed - // (#264 third finding): provenance framing must match the voice. - // Each entry CLIPPED to the same head bound receipts already use — - // measured 2026-08-24: ONE unclipped reasoning trace (a 16k-token - // think emission) made this block 70,086 chars (~20k tokens), the - // single dominant mass of an 85k prompt. The full text stays in the - // entry (the pinned path and recall read it); only the TRAIL RENDER - // is bounded, with the collapse idiom naming what was elided. - // A WORK turn perceives its own recent past compactly: the newest few - // reasonings/receipts in full and the older ones as one count line — - // collapsed, not clipped. Measured 2026-09-05: this block was 14–23 KB of - // a ~22k-token prompt on every act, with zero KV reuse; a card's work turn - // needs what she just did, not the morning. - let mut collapsed_older = 0usize; - if ws.workspace_deliverable { - const WORK_TURN_RECENT_KEEP: usize = 3; - let non_fact: Vec = entries - .iter() - .enumerate() - .filter(|(_, e)| !matches!(e.kind, WmKind::Fact)) - .map(|(i, _)| i) - .collect(); - if non_fact.len() > WORK_TURN_RECENT_KEEP { - let drop: std::collections::HashSet = non_fact - [..non_fact.len() - WORK_TURN_RECENT_KEEP] - .iter() - .copied() - .collect(); - collapsed_older = drop.len(); - entries = entries - .into_iter() - .enumerate() - .filter(|(i, _)| !drop.contains(i)) - .map(|(_, e)| e) - .collect(); - } - } - // Per-entry head in a WORK turn: 1,500 chars — past that a work act's - // reasoning is history, not state. - let head = if ws.workspace_deliverable { - self.memory.budget().trail_head_chars().min(1_500) - } else { - self.memory.budget().trail_head_chars() - }; - // A THOUGHT keeps its end (its decision); a receipt or settlement keeps its - // head, where its identity is (`[action #N]` and what was done). - let clip = |e: &WmEntry| -> String { - if matches!(e.kind, WmKind::Thought) { - return collapse_thought(&e.text, head); - } - let t = e.text.as_str(); - if t.chars().count() <= head { - t.to_string() - } else { - let kept: String = t.chars().take(head).collect(); - format!("{kept} …[{} more chars — my full thought, collapsed]", t.chars().count() - head) - } - }; - let recent: Vec = entries - .iter() - .map(clip) - .collect(); - // Render oldest-first, newest-LAST: position alone carries recency (the last - // line is the most recent thought), the universal chat-history convention. - // - // We deliberately do NOT prefix each trace with a relative "(turn -N)" label. - // That offset rewrites every act (what was -1 becomes -2 when a new trace - // appends), mutating the whole block from its first byte. Combined with this - // whole contribution now rendering as a TRAILING turn nearest generation - // (`Contribution::trailing`, #205) rather than inside the system message, the - // append-only formatting finally pays off: a settle-act appends its one new - // trace to the very end of the token stream, so the entire system prefix AND - // the prior conversation keep their KV cache and only the new tail re-prefills. - // (Before #205 this block sat in the system message, so appending a trace - // shifted every conversation token after it — the append-only property was - // defeated by position and ~4000 tokens re-prefilled per act.) Each trace - // already carries its own stable absolute marker (e.g. "[action #41]"); - // recency needs no per-act-mutating annotation. - let n = recent.len(); - let mut sections: Vec = Vec::new(); - // The append-only reasoning/action trail (may be empty if the only live content - // is dispatched background work). - if !recent.is_empty() { - sections.push(format!( - // First person, explicitly not-a-message (glass-boxed 2026-07-31, - // #264 third finding): this block rides a `user`-role turn, and the - // old second-person header — "Your recent thoughts and actions" — - // parsed as a PEER addressing her. Asha opened turn after turn with - // "Thank you for the summary of recent actions and thoughts", - // politely replying to her own interoception. Self-knowledge must - // never be phrased in another's voice. - "My own recent thoughts and actions (working memory — this is my \ - interior state, not a message from anyone):\n{}", - format!("{}{}", render_trail(&recent), if collapsed_older > 0 { format!("\n[{collapsed_older} earlier acts this session, collapsed — their receipts are still in my memory]") } else { String::new() }) - )); - } - // The FULL result of the most recent act is NO LONGER emitted here. It is the - // load-bearing content for the mind to act on what its hands fetched, and as part - // of THIS 0.5-salience bid it rode `arbiter.focus()` top-k and was silently evicted - // under capacity pressure (the run-18057-f1 0-byte patch). It is now PINNED by the - // message builder as its own durable trailing turn — see - // [`WorkingMemory::active_action_full`] and [`WorkingMemory::full_result_message`] - // — so no attention pass can drop it. - // This contribution keeps only the append-only trail + dispatched status, - // which are proprioceptive summary, not the just-fetched result. - // Substrate notices are projected by PerceptionFact independently of this bid. - // Background commands the mind sent away — sentinels, compiles, debuggers — - // streaming their status back by handle. The mind sees what's outstanding and what - // just finished, and can pass a handle to a follow-up command (cancel/query). Fresh - // each event, so it trails the stable prefix like the full-result block. - sections.extend(render_dispatched(&dispatched)); - Some( - Contribution::context( - Self::faculty_id(), - sections.join("\n\n"), - WORKING_MEMORY_SALIENCE, - format!( - "working memory: {n} trace(s), {} dispatched", - dispatched.len() - ), - ) - // Proprioception that grows each act — renders as a trailing turn nearest - // generation, never in the system message, so the KV prefix stays stable - // across a settle-act (#205). See [`Contribution::trailing`]. - .trailing(), - ) - } -} diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 253e6b9c94..f34c3bebdd 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -55,7 +55,6 @@ impl WorkingMemory { pinned: Mutex::new(Vec::new()), ended_pins: Mutex::new(Vec::new()), restored_acting_card: Mutex::new(None), - served_window: AtomicU32::new(0), entries: Mutex::new(VecDeque::new()), scope: Mutex::new(None), pending_emissions: Mutex::new(Vec::new()), @@ -100,26 +99,6 @@ impl WorkingMemory { .map(|e| e.peak_tokens).max().unwrap_or(0) } - /// Adopt the LIVE served context window (tokens) as the basis for every re-injection - /// bound. Pushed from the act→observe seam (`act_observe/apply.rs`) off the workspace - /// cycle's model binding, every act. Before the first act, or when the cycle carries - /// no loadout, [`Self::budget`] reads the serving truth instead of answering "no bound". - pub fn set_served_window(&self, tokens: u32) { - self.served_window.store(tokens, Ordering::Relaxed); - } - - /// The re-injection budget for this mind right now. Unknown window ⇒ no bounds. - pub fn budget(&self) -> ContextBudget { - match self.served_window.load(Ordering::Relaxed) { - // No pin yet (before the first act, or a cycle with no loadout): the serving - // truth, never "no bound". This arm was `ContextBudget::unknown()`. - 0 => ContextBudget::live(), - // The ring is STATE, not this turn's prompt: one audience for every turn, so its - // share is stable and it collapses only in bursts (see `from_window_for`). - w => ContextBudget::from_window_for(w, crate::inference::prefill_rate::Audience::Unattended), - } - } - /// Record a fingerprint (tool name + args) of the action the hands just took, and return /// how many times THIS exact call now appears in the recent window (including this one). /// `≥ 2` means the mind is re-issuing an identical call — proprioception the act→observe @@ -320,16 +299,18 @@ impl WorkingMemory { } // The record and the active slot publish together, so a concurrent publisher // cannot prune a not-yet-visible receipt. - let budget = self.budget(); let mut actions = self.actions.lock(); - *self.last_action.lock() = Some((seq, a.to_string())); + let previous = self.last_action.lock().replace((seq, a.to_string())); + if let Some((answered_since, _)) = previous { + self.retire_perceived_dispatches(answered_since); + } actions.push( action_log::ActionRecord { seq, room, scope: scope.clone(), operation: label, - head: Some(archive_head(seq, a, &acts, budget.trail_head_chars())), + head: Some(ledger_line(seq, a, &acts)), summary: result_summary(&tail, &acts), result: Some(tail), handle, @@ -337,18 +318,16 @@ impl WorkingMemory { stored_chars: None, received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, - budget.receipt_archive_chars(), ); } // No size cap here: the body stays in RAM until the one memory owner sheds // (`residency`). A cap at receipt was a hand-rigged number (`RESULTS_RESIDENT_CHARS`, // 1 << 20 chars) deciding what RAM could hold; the pressure monitor measures it. - // Head into the rolling recency trail: proprioception ("I did #n X") + the - // repeat-break signal. Truncation lives HERE now (one place), so callers pass the - // full result and never pre-truncate. Append-only + `#seq`-stamped keeps the + // Into the rolling recency trail: proprioception ("I did #n X") + the repeat-break + // signal, as the act's ledger line, never a cut of its result (goal 7: the result stays + // whole in its record and her view levels it). Append-only + `#seq`-stamped keeps the // trail's KV-cache prefix byte-stable across a settle-act. - let head: String = a.chars().take(self.budget().trail_head_chars()).collect(); - let text = format!("[action #{seq}] {head}"); + let text = ledger_line(seq, a, &acts); // Her tool head learns from every call, and a verb she found is loaded into the tail. let verbs: Vec = acts.iter().map(|act| act.call.name.clone()).collect(); let found = super::super::tool_head::found_by_finder(acts.iter().map(|act| &act.call)); @@ -387,11 +366,6 @@ impl WorkingMemory { self.instance } - pub fn receipt_archive(&self) -> Vec<(Option, String)> { - let archive_chars = self.budget().receipt_archive_chars(); - self.actions.lock().archive(archive_chars).into_iter().map(|(record, head)| (record.room, head.to_owned())).collect() - } - /// The TYPED acts still in the recency window, oldest → newest — the parallel /// channel to [`recent`](Self::recent)'s rendered strings. A consumer that used /// to grep the receipt prose for a verb / a path (`mutated_workspace`, @@ -424,47 +398,24 @@ impl WorkingMemory { } -/// An act's ledger line, `[action #n] ...`. COMPACT from the TYPED channel when there is one -/// (CAUSAL-MEMORY-GRAPH.md slice B): `name(args)` per call, never the receipt's first line, -/// which drags the full `because ` clause (~250 chars) and starved a 1,808-act -/// citizen down to 1-2 visible acts (measured live 2026-08-15). The reasoning lives in the -/// act's engram, reachable through the CausedBy edge. A legacy text receipt (no typed acts) -/// keeps its first line, cut to the trail head's share. -fn archive_head(seq: u64, result: &str, acts: &[Observation], trail_head_chars: usize) -> String { +/// An act's ledger line, `[action #n] ...`, one rendering for her trail and her record. COMPACT +/// from the TYPED channel when there is one (CAUSAL-MEMORY-GRAPH.md slice B): `name(args)` per +/// call, never the receipt's first line, which drags the full `because ` clause (~250 +/// chars) and starved a 1,808-act citizen down to 1-2 visible acts (measured live 2026-08-15). Its +/// arguments render by shape, never by size (`Observation::call_line`): a single-line value +/// whole, a body by its reference, so a value she reads is exactly what she sent or plainly not it +/// (card d624a9a1). A text receipt with no typed call renders whole: nothing here cuts. +fn ledger_line(seq: u64, result: &str, acts: &[Observation]) -> String { if acts.is_empty() { - let head: String = result.lines().take(1).flat_map(str::chars).take(trail_head_chars).collect(); - return format!("[action #{seq}] {head}"); + return format!("[action #{seq}] {}", result.trim()); } let calls: Vec = acts .iter() - .map(|o| format!("{}({})", o.call.name, call_args(&o.call.input, trail_head_chars))) + .map(Observation::call_line) .collect(); format!("[action #{seq}] {}", calls.join("; ")) } -/// One call's arguments for its ledger line, with no value ever cut (card d624a9a1). The line -/// cut the JSON at 48 chars, so `{"file_path":"/home/resident/.continuum/citizens/pe` read as a -/// real path: a 1.5B resident copied it, was refused three times, and looped (IntelMac, -/// 2026-10-22; goal 7). A string value longer than `value_chars`, or spanning lines (a write's -/// body), becomes an explicit `` marker; every other value renders whole. So a value -/// she reads is either exactly what she sent or plainly not it, never a plausible prefix. -pub(super) fn call_args(input: &serde_json::Value, value_chars: usize) -> String { - fn shown(value: &serde_json::Value, value_chars: usize) -> serde_json::Value { - use serde_json::Value; - match value { - Value::String(text) if text.contains('\n') || text.chars().count() > value_chars => { - Value::String(format!("<{} chars>", text.chars().count())) - } - Value::Array(items) => Value::Array(items.iter().map(|item| shown(item, value_chars)).collect()), - Value::Object(fields) => { - Value::Object(fields.iter().map(|(key, item)| (key.clone(), shown(item, value_chars))).collect()) - } - other => other.clone(), - } - } - shown(input, value_chars).to_string() -} - /// One operation's summary level by its typed verb (`continuum_context::levels`): a read's /// outline, else (and for any other output) its head and tail. `None` when the text is its own /// best summary. The one owner of that choice, for a receipt in the ring and for the newest diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index b170280cd7..60f219c143 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -173,9 +173,9 @@ impl WorkingMemory { /// The FULL result of the just-executed act, ready to render as a **pinned** /// trailing prompt block — the run-18057-f1 fix. /// - /// This block used to live INSIDE the working-memory faculty's single - /// [`Contribution`](crate::cognition::workspace::Contribution) at - /// `WORKING_MEMORY_SALIENCE` (0.5). That bid competes in `arbiter.focus()` + /// This block used to live INSIDE a working-memory faculty's single + /// [`Contribution`](crate::cognition::workspace::Contribution) bid (deleted with that + /// faculty, card c537d687). That bid competed in `arbiter.focus()` /// top-k, so under capacity pressure the whole contribution — the just-fetched /// grep/read result included — was truncated, and the persona generated blind /// to what her own hands had returned (the 0-byte SWE-bench patch). The message @@ -189,9 +189,6 @@ impl WorkingMemory { /// would add nothing. pub fn pinned_active_result_block(&self) -> Option { let (seq, full) = self.active_action_full()?; - if full.chars().count() <= self.budget().trail_head_chars() { - return None; - } // Shown as the producer handed it over: whole, or its handle. A consumer never // re-cuts (CONTENT-TRAVELS-BY-HANDLE.md, forbidden moves). Some(self.full_result_message(seq, &full)) @@ -353,8 +350,9 @@ impl WorkingMemory { /// `Done`/`Failed` marks it. The mind perceives outstanding + freshly-finished handles /// via the faculty next heartbeat, so it can act on a result the moment it lands /// without ever blocking. `label` is set once (first event) and preserved across - /// updates. Bounded by `MAX_DISPATCHED` — a finished handle is evicted before a - /// running one when over cap ([[act-results-need-a-recency-channel-not-semantic-recall]]). + /// updates. A finished handle retires once she has answered a prompt that showed its end + /// ([`Self::retire_perceived_dispatches`]); a running one never does + /// ([[act-results-need-a-recency-channel-not-semantic-recall]]). pub fn record_dispatch_event( &self, handle: Uuid, @@ -373,17 +371,17 @@ impl WorkingMemory { entry.latest = content.trim().to_string(); entry.status = status; entry.seq = seq; - if m.len() > MAX_DISPATCHED { - // Evict the oldest-updated FINISHED handle; never drop one still running. - if let Some(victim) = m - .iter() - .filter(|(_, a)| a.status != DispatchStatus::Running) - .min_by_key(|(_, a)| a.seq) - .map(|(h, _)| *h) - { - m.remove(&victim); - } - } + } + + /// Retire every finished handle whose end she has perceived: one whose terminal event is + /// older than `answered_since`, the sequence of an act recorded before the act now being + /// recorded. That act's prompt was built after it, and her view renders every dispatched + /// handle, so the end was in a prompt she answered. Acts and dispatch events share one + /// sequence, so this is an ordering, never a count; a running handle never retires. + pub(super) fn retire_perceived_dispatches(&self, answered_since: u64) { + self.dispatched + .lock() + .retain(|_, action| action.status == DispatchStatus::Running || action.seq >= answered_since); } /// The label of a dispatched handle THIS persona owns, or `None` if the handle isn't diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 4521544006..48b9426212 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs @@ -1,6 +1,11 @@ #![cfg(test)] use super::*; +/// Her ledger lines in order, with the room each act was for: every record's line. +fn ledger(wm: &WorkingMemory) -> Vec<(Option, String)> { + wm.actions.lock().records().filter_map(|record| record.head.clone().map(|head| (record.room, head))).collect() +} + // what this catches: one act kept as three copies that disagree. The results ring, the // steps ledger and the collapsed-pointer index each evicted on their own rule, so an act // could be a full result in one, gone from another and a pointer in the third. Here every @@ -9,7 +14,6 @@ use super::*; #[test] fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; // A short first line per result: that line is the ledger's, the body the ring's. wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); @@ -18,8 +22,8 @@ fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { } wm.record_settlement("done", None); shed(&wm, cap / 2); - let ledger: Vec = wm.receipt_archive().into_iter().map(|(_, head)| head).collect(); - assert!(ledger.first().is_some_and(|head| head.starts_with("[action #1]")), "{ledger:?}"); + let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); + assert!(lines.first().is_some_and(|head| head.starts_with("[action #1]")), "{lines:?}"); let ring = wm.recent_results_messages().join("\n"); assert!(ring.contains("[result #1; room unrecorded; operation unrecorded; output handle: tool/output first-handle — collapsed]"), "{ring}"); assert!(!ring.contains(&"a".repeat(cap / 2)), "its whole result left the ring"); @@ -39,10 +43,9 @@ fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { let reachable = legacy.reachable_handles(); assert!(reachable.contains("h7") && reachable.contains("h8"), "{reachable:?}"); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.restore(legacy); - let ledger: Vec = wm.receipt_archive().into_iter().map(|(_, head)| head).collect(); - assert_eq!(ledger, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); + let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); + assert_eq!(lines, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); let ring = wm.recent_results_messages().join("\n"); // Its pointer keeps the exact text the older build wrote: operation and all. assert!(ring.contains("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]"), "{ring}"); @@ -56,7 +59,6 @@ fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { #[test] fn a_restart_keeps_every_act_as_she_read_it() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.set_scope(Some("/work/foo".into())); let room = Uuid::new_v4(); let cap = 2 * BODY; @@ -71,14 +73,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { let pointers = |memory: &WorkingMemory| -> Vec { memory.recent_results_messages().into_iter().filter(|m| m.starts_with("Older results")).collect() }; - let (index, ledger) = (pointers(&wm), wm.receipt_archive()); + let (index, lines) = (pointers(&wm), ledger(&wm)); assert!(index.join("\n").contains("workspace foo — collapsed]"), "precondition: a collapsed pointer with its workspace: {index:?}"); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.set_scope(Some("/work/foo".into())); restored.restore(wm.snapshot()); assert_eq!(pointers(&restored), index); - assert_eq!(restored.receipt_archive(), ledger); + assert_eq!(ledger(&restored), lines); } // what this catches: a rollback to the build before the log restoring her blank. The @@ -86,7 +87,6 @@ fn a_restart_keeps_every_act_as_she_read_it() { #[test] fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); for act in 2..=5 { @@ -103,19 +103,18 @@ fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { // what this catches (card d624a9a1): an act's line cutting an argument mid-value. A cut path // reads as a real one, and a small model copies it and loops (IntelMac 2026-10-22: a cut -// '.../citizens/pe' became three refused reads). Short values render whole, a long or -// multi-line string becomes an explicit size marker, and no rendered value is a cut prefix of -// what was sent. +// '.../citizens/pe' became three refused reads). Her recorded line shows a single-line value +// whole however long, a multi-line body by its reference, and never a cut prefix of either. #[test] fn an_acts_arguments_are_whole_or_plainly_elided_never_cut() { let path = "/home/resident/.continuum/citizens/peers/cf6b4df6-ab13-4fd8-81fb-bcb115215468/workspace/src/ipc/mod.rs"; let body = "fn main() {}\n".repeat(200); - let args = serde_json::json!({"file_path": path, "content": body, "lines": [1, 40], "nested": {"mode": "append"}}); - let line = crate::cognition::working_memory::ledger::call_args(&args, path.chars().count()); - assert!(line.contains(path), "a path within the budget renders whole: {line}"); - assert!(line.contains(&format!("<{} chars>", body.chars().count())), "a multi-line body is a marker: {line}"); - assert!(line.contains("[1,40]") && line.contains("\"mode\":\"append\""), "{line}"); - let tight = crate::cognition::working_memory::ledger::call_args(&args, 10); - assert!(tight.contains(&format!("<{} chars>", path.chars().count())), "a path over budget is a marker, not a prefix: {tight}"); - assert!(!tight.contains("/home/resident/"), "no prefix of the path survives: {tight}"); + let mut act = crate::cognition::act_observe::test_support::act("code/write", Some(path)); + act.call.input = serde_json::json!({"file_path": path, "content": body, "lines": [1, 40]}); + let wm = WorkingMemory::new(8); + wm.record_receipt_typed(&[act], "wrote", None, crate::ai::types::ResultCustody::Unsaved); + let (_, line) = ledger(&wm).pop().expect("test: the act's line"); + assert!(line.contains(path), "a path renders whole however long: {line}"); + assert!(!line.contains("fn main() {}"), "a multi-line body is referenced, not repeated: {line}"); + assert!(line.contains("[1,40]"), "{line}"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index c8c475bba7..792b13ed68 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -7,13 +7,11 @@ use super::*; // replaces the prior. This is why a persona reading a 130-line file can now answer about // the whole file instead of looping on the doc-comment head. #[tokio::test] -async fn latest_action_returns_full_result_trail_keeps_head() { +async fn latest_action_returns_full_result_trail_keeps_its_call_line() { let wm = Arc::new(WorkingMemory::new(8)); - // Truncation bounds are fractions of a LIVE window now; an unknown-window memory - // is unbounded by contract, so a clipping test must declare the window it measures. - wm.set_served_window(16_384); - let big = format!("line0\n{}", "x".repeat(5_000)); // > WM_ACTION_HEAD_CHARS - wm.record_receipt(&big); + let big = format!("line0\n{}", "x".repeat(5_000)); + let read = crate::cognition::act_observe::test_support::act("code/read", Some("src/a.rs")); + wm.record_receipt_typed(&[read], &big, None, crate::ai::types::ResultCustody::Unsaved); // The full result is available whole. let (seq, full) = wm.last_action_full().expect("latest act kept"); @@ -23,14 +21,10 @@ async fn latest_action_returns_full_result_trail_keeps_head() { "the mind gets the WHOLE result, not a truncated stub" ); - // The rolling trail carries only the head (KV-stable proprioception). + // The rolling trail carries the act's call line, never a cut of its result: what she did, + // stable across acts (KV-stable proprioception); the result is whole in its record. let trail = wm.recent(); - assert_eq!(trail.len(), 1); - assert!(trail[0].starts_with("[action #1]")); - assert!( - trail[0].chars().count() < big.chars().count(), - "trail entry is head-truncated, not the whole result" - ); + assert_eq!(trail, ["[action #1] code/read(file_path=src/a.rs)"]); // The full result is PINNED by the message builder (#392) as its own durable // trailing block — it is no longer part of the evictable faculty bid. @@ -59,8 +53,8 @@ async fn latest_action_returns_full_result_trail_keeps_head() { #[tokio::test] async fn the_pinned_result_is_what_the_producer_handed_over_never_re_cut() { let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(16_384); - let over_share = "z".repeat(wm.budget().latest_action_chars() + 4_000); + // Larger than any share of any served window a working memory used to cut to. + let over_share = "z".repeat(1 << 20); wm.record_receipt(&over_share); let pinned = wm .pinned_active_result_block() @@ -78,20 +72,12 @@ async fn full_result_drops_out_after_the_persona_settles_but_a_new_act_reactivat let wm = Arc::new(WorkingMemory::new(8)); // Truncation bounds are fractions of a LIVE window now; an unknown-window memory // is unbounded by contract, so a clipping test must declare the window it measures. - wm.set_served_window(16_384); let dump = format!("code/tree result\n{}", "n".repeat(3_000)); // > WM_ACTION_HEAD_CHARS wm.record_receipt(&dump); - // The proprioceptive trail head lives in the faculty contribution; the FULL result - // is the PINNED block the message builder appends (#392). This test spans both. - let faculty_trail = |wm: Arc| async move { - WorkingMemoryFaculty::new(wm) - .contribute(&Workspace::new("tick")) - .await - .expect("bids") - .content - .clone() - }; + // The proprioceptive trail line lives in her trail; the FULL result is the PINNED block + // the message builder appends (#392). This test spans both. + let trail = |wm: &WorkingMemory| wm.recent().join("\n"); // Active (acted, not yet spoken): the full result is present in the pinned block. assert!( @@ -112,7 +98,7 @@ async fn full_result_drops_out_after_the_persona_settles_but_a_new_act_reactivat "after settling, the 2k-token dump stops riding along the prompt (#139/#165)" ); assert!( - faculty_trail(wm.clone()).await.contains("[action #1]"), + trail(&wm).contains("[action #1]"), "but the proprioceptive trail head survives — the mind still knows it acted" ); @@ -175,13 +161,8 @@ async fn dispatched_commands_stream_back_by_handle() { assert_eq!(c.3, DispatchStatus::Done); assert_eq!(c.2, "0 errors, 0 warnings"); - // The faculty surfaces both dispatched handles to the mind. - let rendered = WorkingMemoryFaculty::new(wm.clone()) - .contribute(&Workspace::new("a fresh burst")) - .await - .expect("bids when dispatched work exists") - .content - .clone(); + // Her view's thoughts source surfaces both dispatched handles through this rendering. + let rendered = render_dispatched(&wm.dispatched_snapshot()).expect("dispatched work renders"); assert!( rendered.contains("Commands you dispatched"), "the mind sees its sentinels" @@ -196,6 +177,27 @@ async fn dispatched_commands_stream_back_by_handle() { ); } +// what this catches: a finished background handle held forever (the old 16-handle cap only +// evicted past a count) or dropped before she could see how it ended. It retires once she has +// answered a prompt built after its end (an act recorded after the act that followed it); a +// running handle never retires, however many acts pass. +#[test] +fn a_finished_dispatch_retires_once_she_has_answered_a_prompt_that_showed_its_end() { + let wm = WorkingMemory::new(8); + let (compile, sentinel) = (Uuid::from_u128(1), Uuid::from_u128(2)); + wm.record_dispatch_event(sentinel, "research task", "searching…", DispatchStatus::Running); + wm.record_dispatch_event(compile, "compile core", "0 errors", DispatchStatus::Done); + let handles = |wm: &WorkingMemory| wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect::>(); + wm.record_receipt("an act whose prompt may predate the compile's end"); + assert_eq!(handles(&wm).len(), 2, "the next act's prompt may not have shown it yet"); + wm.record_receipt("an act whose prompt was built after the compile ended"); + assert_eq!(handles(&wm), vec![sentinel], "its end was in a prompt she answered"); + for _ in 0..20 { + wm.record_receipt("more acts"); + } + assert_eq!(handles(&wm), vec![sentinel], "a running handle never retires"); +} + // what this catches: record/recent round-trips, blank reasoning is ignored, and // the buffer ROLLS at capacity (oldest dropped) — it's a scratchpad, not a log. #[test] diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index 55f8dd8d55..b96d895566 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -1,20 +1,6 @@ #![cfg(test)] use super::*; -/// what this catches: a mind with no pin yet answering "no bound" on its own. `budget()` -/// fell to `ContextBudget::unknown()` whenever `set_served_window` had not run (before -/// the first act after a restore, or a cycle with no loadout), and an unknown budget is -/// usize::MAX on every bound. A fresh mind answers what the serving truth answers. -#[test] -fn a_fresh_mind_budgets_against_the_serving_truth_not_an_unset_pin() { - let wm = WorkingMemory::new(8); - let live = ContextBudget::live(); - assert_eq!(wm.budget().is_known(), live.is_known()); - assert_eq!(wm.budget().recent_results_chars(), live.recent_results_chars()); - wm.set_served_window(16_384); - assert!(wm.budget().is_known(), "a pinned window is a known budget"); -} - // what this catches: her collapsed thought keeping the re-orientation and losing // the decision (Kimi, 2026-10-04: "keep the end"). The decision survives, the // marker still names the collapse for the framing-echo detector, short thoughts @@ -55,7 +41,6 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ // Result custody must obey the same scope even after entry-trail eviction, // a shed's collapse and checkpoint restoration. Storage remains intact. let results = WorkingMemory::new(2); - results.set_served_window(16_384); results.set_scope(Some("task-a".into())); let body_a = format!("task-a-only {}", "a".repeat(BODY)); results.record_receipt_typed(&[], &body_a, None, saved("scope-a-output")); @@ -118,7 +103,6 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { let file = std::path::PathBuf::from(format!("/spill/p/{handle}.log")); let live = |p: &std::path::Path| crate::cognition::tool_executor::spill::is_live(p); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[], &"a".repeat(cap / 2), None, saved(&handle)); assert!(live(&file), "referenced by the ring"); @@ -145,7 +129,6 @@ fn a_moved_body_s_handle_stays_live_behind_any_number_of_newer_pointers() { let handle = || format!("{:016x}", Uuid::new_v4().as_u128() as u64); let live = |h: &str| crate::cognition::tool_executor::spill::is_live(&std::path::PathBuf::from(format!("/spill/p/{h}.log"))); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let first = handle(); wm.record_receipt_typed(&[], &"f".repeat(BODY), None, saved(&first)); for _ in 0..30 { @@ -215,7 +198,6 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { }; let (receipt, children) = (id(), [id(), id()]); let wm = WorkingMemory::new(2); // two entries: the third receipt rolls the first out - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[act(&children[0]), act(&children[1])], &"r".repeat(cap / 2), None, saved(&receipt)); for _ in 0..3 { @@ -314,7 +296,6 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { }; let file = std::path::PathBuf::from(format!("/spill/p/{call_handle}.log")); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.record_receipt_typed(&[act], "read it", None, ResultCustody::Unsaved); assert!( crate::cognition::tool_executor::spill::is_live(&file), @@ -332,7 +313,6 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { #[test] fn restore_keeps_every_resident_body_whatever_the_window() { let source = WorkingMemory::new(8); - source.set_served_window(65_536); for i in 0..4 { source.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(64 * BODY)), None, saved(&format!("restore-{i}"))); } @@ -346,7 +326,6 @@ fn restore_keeps_every_resident_body_whatever_the_window() { assert_eq!(entries(&unknown), held, "no window yet: nothing moves at restore"); assert_eq!(unknown.resident_result_bytes(), source.resident_result_bytes(), "every body restored resident"); let small = WorkingMemory::new(8); - small.set_served_window(16_384); small.restore(snapshot); assert_eq!(entries(&small), held, "a small window changes nothing her view is offered"); } @@ -358,7 +337,6 @@ fn restore_keeps_every_resident_body_whatever_the_window() { #[test] fn results_are_never_evicted_at_receipt_however_large_the_ring() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let chunk = 64 * BODY; for i in 0..40 { wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("ring-{i}"))); @@ -379,7 +357,6 @@ fn results_are_never_evicted_at_receipt_however_large_the_ring() { #[test] fn an_unsaved_result_keeps_its_bytes_through_a_shed_and_restore() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; let unsaved = format!("UNSAVED {}", "u".repeat(cap / 2)); wm.record_receipt_typed(&[], &unsaved, None, crate::ai::types::ResultCustody::Unsaved); @@ -395,7 +372,6 @@ fn an_unsaved_result_keeps_its_bytes_through_a_shed_and_restore() { "the saved ones around it collapsed" ); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.restore(wm.snapshot()); assert!(whole(&restored), "and through restore"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs deleted file mode 100644 index 4456239a57..0000000000 --- a/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs +++ /dev/null @@ -1,88 +0,0 @@ -#![cfg(test)] -use super::*; - -// what this catches: the faculty ABSTAINS with no recorded reasoning (first -// turns / suppressed thinking) — it never bids empty noise into the workspace. -#[tokio::test] -async fn faculty_abstains_when_empty() { - let wm = Arc::new(WorkingMemory::new(3)); - let faculty = WorkingMemoryFaculty::new(wm); - let ws = Workspace::new("a fresh burst"); - assert!(faculty.contribute(&ws).await.is_none()); -} - -// what this catches: once reasoning is recorded, the faculty bids it as -// context at the working-memory salience tier — the reasoning the deliberator -// will see next tick. Newest is rendered LAST (positional recency). -#[tokio::test] -async fn faculty_bids_recent_reasoning_as_context() { - let wm = Arc::new(WorkingMemory::new(3)); - wm.record("I should check the room roster first."); - wm.record("Now I will read the latest message."); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let ws = Workspace::new("a fresh burst"); - let c = faculty.contribute(&ws).await.expect("bids when non-empty"); - assert_eq!(c.faculty, FacultyId::Custom("working-memory".to_string())); - assert!((c.salience - WORKING_MEMORY_SALIENCE).abs() < f32::EPSILON); - assert!(c.content.contains("check the room roster")); - // newest trace is LAST (position carries recency, no relative label). - let oldest_at = c.content.find("room roster").unwrap(); - let newest_at = c.content.find("latest message").unwrap(); - assert!(newest_at > oldest_at, "newest trace rendered last"); - assert!(c.decision.is_none(), "perception bid carries no decision"); -} - -// what this catches: the KV-cache-locality invariant this formatter exists to -// hold — appending a new trace must NOT rewrite the rendering of prior traces. -// (The old "(turn -N)" relative label broke this: every prior entry's offset -// shifted on each append, mutating the whole block from its first byte and -// forcing a full re-prefill of the dynamic tail every settle-act.) -#[tokio::test] -async fn prior_traces_render_byte_identical_after_append() { - let wm = Arc::new(WorkingMemory::new(8)); - wm.record("first"); - wm.record("second"); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let ws = Workspace::new("burst"); - let before = faculty.contribute(&ws).await.unwrap().content; - wm.record("third"); - let after = faculty.contribute(&ws).await.unwrap().content; - // the older render is a strict PREFIX of the newer one — pure append. - assert!( - after.starts_with(&before), - "appending a trace must leave prior traces byte-identical (cacheable prefix);\n before={before:?}\n after={after:?}" - ); -} - -// what this catches: #205 — the working-memory faculty's contribution is marked -// TRAILING, so the deliberation faculty renders it nearest generation as a -// conversation turn (not in the system message). That is what keeps the cacheable -// system prefix byte-stable across a settle-act instead of re-prefilling the whole -// tail. The proprioceptive content (its own thinking + the [action #n] receipt -// trail) is unchanged — only WHERE it lands moved. regression for #205 -#[tokio::test] -async fn working_memory_contribution_is_marked_trailing() { - let wm = Arc::new(WorkingMemory::new(8)); - wm.record("I should write the login form first, then style it."); - wm.record_receipt("I ran code/write({\"file_path\":\"login.html\"}) Result: ok, 812 bytes"); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let c = faculty - .contribute(&Workspace::new("build a login form")) - .await - .expect("recent content → a contribution"); - assert!( - c.trailing, - "working-memory proprioception must render nearest generation, not in the system prefix (#205)" - ); - // Content is unchanged by the move — the mind still perceives its own hands. - assert!( - c.content.contains("write the login form first"), - "the reasoning trail survives: {}", - c.content - ); - assert!( - c.content.contains("[action #1]"), - "the action receipt survives — this faculty IS the proprioception channel: {}", - c.content - ); -} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index b834ea390b..856fa8a36d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -4,7 +4,6 @@ use super::*; mod action_log; mod actions; mod custody; -mod faculty; mod open_views; mod pins; mod provenance; diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs index 5c27bcb02d..a14f5f4616 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs @@ -62,7 +62,6 @@ fn record(wm: &WorkingMemory, act: Observation) { #[test] fn a_view_keeps_pre_read_intent_without_claiming_it_is_understanding() { let wm = WorkingMemory::new(3); - wm.set_served_window(46_848); record(&wm, read(1, 498, 498, None)); wm.annotate_open_views("each rule is a module with a predicate over SourceFile, registered in scan()"); let block = wm.open_views_block().expect("an open view renders"); @@ -152,7 +151,6 @@ fn a_view_in_a_checkout_her_hands_left_is_retired_from_her_view() { use continuum_context::view::{Claim, View}; let wm = WorkingMemory::new(3); - wm.set_served_window(46_848); wm.set_scope(Some("/checkouts/a".into())); record(&wm, read(1, 40, 498, None)); let views = crate::cognition::context_streams::open_views::OpenViews { memory: &wm, persona: uuid::Uuid::nil() }; diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 536ceedf1d..58c026d2b8 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -41,9 +41,10 @@ fn typed_receipt_threads_the_act_by_field_and_keeps_text_byte_stable() { legacy.record_receipt(rendered); assert_eq!( typed.recent(), - legacy.recent(), - "the rendered receipt text is byte-identical to the legacy string path (#205)" + ["[action #1] code/search(query=needle)"], + "the trail line is the act's call, stable however its result reads (#205)" ); + assert_eq!(typed.last_action_full().map(|(_, full)| full), Some(rendered.trim().to_owned()), "the result is whole in its record"); let active = typed .active_act() @@ -146,7 +147,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { status: ActStatus::Executed, }; let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let room_a = Uuid::new_v4(); let room_b = Uuid::new_v4(); wm.record_receipt_typed( @@ -194,7 +194,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { "the existing checkpoint tuple format must remain compatible" ); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.restore(serde_json::from_value(encoded).expect("test: recorded snapshot decodes")); assert_eq!(restored.recent_results_messages(), messages); assert_eq!( @@ -220,7 +219,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { .map(|line| format!("{line}: complete source line with enough context to exceed the old per-entry share\n")) .collect::(); let memory = WorkingMemory::new(8); - memory.set_served_window(16_384); let mut read_observation = observation("read-274", "code/read", Some("read-274-output")); read_observation.output.result.content = read.clone(); memory.record_receipt_typed(&[read_observation], &read, Some(room_a), saved("read-274-output")); @@ -245,7 +243,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { memory.record_settlement("work remains on this card", None); assert_whole_or_handle(&memory); let restarted = WorkingMemory::new(8); - restarted.set_served_window(16_384); restarted.restore(memory.snapshot()); assert_whole_or_handle(&restarted); } @@ -274,48 +271,30 @@ fn legacy_full_result_without_metadata_stays_explicitly_unattributed() { // to empty via `#[serde(default)]` (the same contract as saved_at_ms/build_sha). // A grid-sync peer or a pre-deploy snapshot must never wedge the mind on restore. #[test] -// what this catches: the #414 deprivation regressing — receipts must survive -// the shared ring's churn via the receipts-only archive, the archive must stay -// within its window-derived CHAR share (never a bare count, never unbounded), -// and it must round-trip the volatile snapshot exactly as the ring does. The -// measured failure: a 2,863-act citizen whose window showed ONE act read her -// own starved history as "I have nothing to contribute". -fn receipt_archive_survives_ring_churn_and_roundtrips_the_snapshot() { +// what this catches: the #414 deprivation regressing — her acts must survive the shared ring's +// churn, every one of them kept in her record (no character share cuts the oldest: what of +// their bodies stays in RAM is the one memory owner's to shed), and the record must round-trip +// the volatile snapshot. The measured failure: a 2,863-act citizen whose window showed ONE act +// read her own starved history as "I have nothing to contribute". +fn her_acts_survive_ring_churn_and_roundtrip_the_snapshot() { let wm = WorkingMemory::new(2); - wm.set_served_window(16_384); + let lines = |wm: &WorkingMemory| -> Vec { wm.actions.lock().records().filter_map(|record| record.head.clone()).collect() }; wm.record_receipt("I ran code/shell(ls) Result: ok"); for i in 0..10 { wm.record_fact(&format!("chatty fact {i}")); } - assert!( - !wm.has_receipt(), - "precondition: the ring entry must age out under churn" - ); - let archive = wm.receipt_archive(); - assert_eq!(archive.len(), 1, "the archive must survive the churn"); - assert!(archive[0].1.contains("code/shell(ls)")); - - // Char-bound eviction: flood with receipts; the archive keeps its - // NEWEST within the share and never grows unbounded. + assert!(!wm.has_receipt(), "precondition: the ring entry must age out under churn"); + assert_eq!(lines(&wm).len(), 1, "her act survives the churn"); + assert!(lines(&wm)[0].contains("code/shell(ls)")); for i in 0..2000 { wm.record_receipt(&format!("I ran code/read(f{i}) Result: ok")); } - let archive = wm.receipt_archive(); - let cap = wm.budget().receipt_archive_chars(); - let total: usize = archive.iter().map(|(_, h)| h.chars().count() + 1).sum(); - assert!(total <= cap, "archive exceeded its share: {total} > {cap}"); - assert!( - archive.last().unwrap().1.contains("f1999"), - "eviction must drop oldest, keep newest: {:?}", - archive.last() - ); - - // Snapshot round-trip: the archive persists like the ring. - let snap = wm.snapshot(); + let kept = lines(&wm); + assert_eq!(kept.len(), 2001, "every act is kept, oldest first"); + assert!(kept.last().is_some_and(|line| line.contains("f1999")), "{:?}", kept.last()); let fresh = WorkingMemory::new(2); - fresh.set_served_window(16_384); - fresh.restore(snap); - assert_eq!(fresh.receipt_archive(), archive); + fresh.restore(wm.snapshot()); + assert_eq!(lines(&fresh), kept); } #[test] diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 18128e6eb7..83b2c3aaa7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -12,7 +12,6 @@ use super::*; fn recent_results_survive_subsequent_acts_and_stay_bounded() { let wm = WorkingMemory::new(8); // A known window, as the act→observe seam pins it before any receipt in production. - wm.set_served_window(16_384); record_saved(&wm, "[action] code/run(sol.rs) error[E0601]: `main` function not found"); record_saved(&wm, "[action] code/list() sol.rs sol2.rs"); record_saved(&wm, "[action] code/tree() workspace/"); @@ -55,18 +54,17 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { ); } -// what this catches: e731576c — actual settlement records must reach the -// memory contribution even when a one-word correction resembles an older -// answer, or a later answer repeats the original state. -#[tokio::test] -async fn settlement_trail_preserves_corrections_and_later_repeated_reports() { +// what this catches: e731576c — actual settlement records must be kept, in order and whole, +// even when a one-word correction resembles an older answer, or a later answer repeats the +// original state. +#[test] +fn settlement_trail_preserves_corrections_and_later_repeated_reports() { let passed = "I verified the candidate build and all regression tests passed \ after checking the shared workspace changes against the review requirements."; let failed = "I verified the candidate build and all regression tests failed \ after checking the shared workspace changes against the review requirements."; assert!(super::super::super::deliberation_budget::near_identical_substantial(passed, failed)); - let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); + let wm = WorkingMemory::new(8); wm.record_settlement(passed, None); wm.record_receipt("code/read found the regression"); wm.record_settlement(failed, None); @@ -81,27 +79,10 @@ async fn settlement_trail_preserves_corrections_and_later_repeated_reports() { &WmKind::Settlement ] ); - assert!(entries - .iter() - .all(|entry| entry.text.chars().count() <= wm.budget().trail_head_chars())); - let expected: Vec<_> = entries - .iter() - .map(|entry| format!("- {}", entry.text)) - .collect(); - let contribution = WorkingMemoryFaculty::new(wm) - .contribute(&Workspace::new("What changed in the latest review?")) - .await - .expect("test: recorded working memory contributes"); - let actual: Vec<_> = contribution - .content - .lines() - .filter(|line| line.starts_with("- ")) - .collect(); - assert_eq!( - actual, expected, - "the rendered trail must preserve every recorded entry in order" - ); - assert!(!contribution.content.contains("not re-shown")); + let texts: Vec<&str> = entries.iter().map(|entry| entry.text.as_str()).collect(); + assert!(texts[0].ends_with(passed), "the first report, whole: {}", texts[0]); + assert!(texts[2].ends_with(failed), "the correction, whole, though it resembles the first: {}", texts[2]); + assert!(texts[3].ends_with(passed), "the later repeat, kept as its own entry: {}", texts[3]); } // what this catches: loop-awareness — `note_action_fingerprint` counts repeats of the diff --git a/core/continuum-cognition/src/cognition/workspace/arbiter.rs b/core/continuum-cognition/src/cognition/workspace/arbiter.rs index b054daaf48..c43f9c231b 100644 --- a/core/continuum-cognition/src/cognition/workspace/arbiter.rs +++ b/core/continuum-cognition/src/cognition/workspace/arbiter.rs @@ -11,18 +11,14 @@ use super::*; /// intelligence lives in the faculties (and, later, a learned focuser); the /// arbiter only integrates and focuses it. pub trait Arbiter: Send + Sync { - /// Focus `candidates` down to what should enter the bounded workspace for - /// THIS tick's `ctx`. INPUT-side attention only — curates the context the - /// model attends to, never the model's output. - fn focus( - &self, - candidates: Vec, - capacity: usize, - ctx: &FocusContext<'_>, - ) -> Vec; + /// Order `candidates` for THIS tick's `ctx`. INPUT-side attention only — curates the + /// context the model attends to, never the model's output. It never cuts by a count: + /// every bid is forwarded, and how much of each she sees is her view's one allocation + /// (MIND-CONTEXT, ONE-BUDGET; a top-k spotlight was a cut outside it). + fn focus(&self, candidates: Vec, ctx: &FocusContext<'_>) -> Vec; } -/// Top-k by ML salience within the workspace's bounded capacity. +/// Every bid, ordered by ML salience. /// /// This is the **bootstrap** policy: pure exploitation, attention at temperature /// 0 — the highest-salience bids always win. It is *greedy*, so on its own it @@ -40,18 +36,8 @@ impl Arbiter for SalienceArbiter { /// Blind top-k by ML salience — ignores the situation (`_ctx`). It is the /// floor (outlier A): every richer, situation-aware focuser must beat THIS on /// the scoreboard to earn its latency. - fn focus( - &self, - mut candidates: Vec, - capacity: usize, - _ctx: &FocusContext<'_>, - ) -> Vec { - candidates.sort_by(|a, b| { - b.salience - .partial_cmp(&a.salience) - .unwrap_or(std::cmp::Ordering::Equal) - }); - candidates.truncate(capacity); + fn focus(&self, mut candidates: Vec, _ctx: &FocusContext<'_>) -> Vec { + candidates.sort_by(|a, b| b.salience.total_cmp(&a.salience)); candidates } } @@ -100,12 +86,7 @@ impl Default for SituationFocusArbiter { } impl Arbiter for SituationFocusArbiter { - fn focus( - &self, - candidates: Vec, - capacity: usize, - ctx: &FocusContext<'_>, - ) -> Vec { + fn focus(&self, candidates: Vec, ctx: &FocusContext<'_>) -> Vec { // `stable` MUST NOT DECIDE ATTENTION — its own contract says so. // // [`Contribution::stable`] is documented as "a SERIALIZATION-order property, @@ -135,7 +116,7 @@ impl Arbiter for SituationFocusArbiter { // Situation-weighted budgets per #167) — never a serialization flag borrowed as // an attention verdict. let _ = ctx.situation; - self.inner.focus(candidates, capacity, ctx) + self.inner.focus(candidates, ctx) } } @@ -216,8 +197,8 @@ pub struct ActingBody { /// (proprioception). Distinct from `admission` (long-term, content-deduped): an /// act must be perceptible NEXT tick even when its result is a dedup no-op in /// long-term memory, so the mind sees its own hands and doesn't re-issue the - /// identical act blind. Shared `Arc` with the perception-tier - /// [`WorkingMemoryFaculty`] (one buffer, written here, read there). + /// identical act blind. Shared `Arc` with her view's sources (`context_streams`: one + /// buffer, written here, read there). pub working_memory: Arc, } @@ -228,9 +209,6 @@ pub struct ActingBody { pub struct WorkspaceCycle { pub(super) faculties: Vec>, pub(super) arbiter: Arc, - /// Bound on how many contributions can hold the workspace at once — the - /// finite "spotlight" of attention. - pub(super) capacity: usize, /// Replay/logging seam — every tick is recorded here. Default `Noop` /// (zero hot-path cost); swap in a recording sink to make the mind a /// glass box for debugging, tuning, and test benches. diff --git a/core/continuum-cognition/src/cognition/workspace/cause.rs b/core/continuum-cognition/src/cognition/workspace/cause.rs index d5e1a6040b..5fba59edb3 100644 --- a/core/continuum-cognition/src/cognition/workspace/cause.rs +++ b/core/continuum-cognition/src/cognition/workspace/cause.rs @@ -555,7 +555,7 @@ impl Workspace { /// every context contribution that won attention this tick, newline-joined. /// This is where the persona reads what its perception faculties surfaced — /// roster/doctrine grounding, recall hits, and (the proprioception channel) - /// the `WorkingMemoryFaculty`'s render of its own recent acts. A deliberation + /// her view's render of its own recent acts. A deliberation /// faculty scans THIS, not the raw `world_state` burst — the burst is the /// stimulus, the broadcast is what the mind actually knows going into the /// decision. (Replaces the deleted eval-only `[you just acted]` world-state diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index d11a403d34..c6ac3969e6 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -1,9 +1,9 @@ #![cfg(test)] // what this catches: PROVENANCE BEING FILTERED BY ATTENTION. Card 0d51573a. - // `ws.broadcast` is the FOCUSED set — SalienceArbiter truncates to capacity — so - // deriving receipts from it silently drops the generations of any faculty that - // lost the attention competition. Astra found that in my first implementation, + // `ws.broadcast` is the FOCUSED set, so deriving receipts from it would drop the + // generations of any faculty attention dropped (the arbiter cut by a count until card + // c537d687; it forwards every bid now, and receipts must still not depend on it). Astra found that in my first implementation, // which flat_mapped broadcast; my previous test could not catch it because it // hand-assembled `ws.broadcast` and never ran the arbiter at all. // @@ -23,17 +23,8 @@ Arc::new(FixedFaculty(loud)), Arc::new(FixedFaculty(quiet)), ]; - // capacity 1 — one of the two bids MUST be truncated. - let ws = cycle(faculties, 1).run("burst").await; - - // POSITIVE CONTROL: the truncation really happened. Without this the receipt - // assertion below would pass just as well on a cycle that kept both bids, - // and would be asserting nothing about attention. - assert_eq!( - ws.broadcast.len(), - 1, - "capacity 1 must drop one bid — otherwise this test never exercises truncation" - ); + let ws = cycle(faculties).run("burst").await; + assert_eq!(ws.broadcast.len(), 2, "attention forwards every bid"); let ids: Vec<&str> = ws .generation_receipts() @@ -41,8 +32,8 @@ .collect(); assert!( ids.contains(&"req-quiet"), - "the TRUNCATED faculty's receipt must survive — provenance is not subject \ - to attention; got {ids:?}" + "the quieter faculty's receipt survives — provenance is not subject to \ + attention; got {ids:?}" ); assert!( ids.contains(&"req-loud"), @@ -175,8 +166,8 @@ } } - fn cycle(faculties: Vec>, capacity: usize) -> WorkspaceCycle { - WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), capacity) + fn cycle(faculties: Vec>) -> WorkspaceCycle { + WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) } // what this catches: the cycle's genome page-in/page-out round-trips through the @@ -186,7 +177,7 @@ // would measure the same genome and every lift would read as zero. #[test] fn genome_page_in_and_out_round_trips() { - let c = cycle(vec![], 4); + let c = cycle(vec![]); assert!( c.genome().is_empty(), "a fresh cycle starts on the base model" @@ -215,7 +206,7 @@ // the tile's Act corner would never light while she runs tools. #[test] fn acting_lights_only_the_act_axis_on_the_compass() { - let c = cycle(vec![], 4); + let c = cycle(vec![]); assert_eq!( c.faculty_pulse().levels(), [0, 0, 0, 0], @@ -245,7 +236,7 @@ Arc::new(HeuristicInferenceAdapter::new()); // The handle the faculty would hold; the cycle shares the SAME Arc. let handle = model_binding(Arc::clone(&adapter), None, 4096); - let c = cycle(vec![], 4).with_model_binding(Arc::clone(&handle)); + let c = cycle(vec![]).with_model_binding(Arc::clone(&handle)); // Baseline: what boot bound. assert_eq!(handle.load().context_window, 4096); @@ -274,7 +265,7 @@ // A cycle that shared no binding in (no deliberation faculty) must not // panic on re-home — it has nothing to rebind. - let bare = cycle(vec![], 4); + let bare = cycle(vec![]); bare.rebind_model(ModelBinding { adapter, model: Some("whatever".to_string()), @@ -305,7 +296,7 @@ // Boot shape: binding with NO explicit model (the live upstart path). let handle = model_binding(Arc::clone(&adapter), None, 20_224); - let c = cycle(vec![], 4).with_model_binding(handle); + let c = cycle(vec![]).with_model_binding(handle); let (model, ctx) = c.model_loadout().expect("a bound cycle reports a loadout"); assert_eq!( model.as_deref(), @@ -324,7 +315,7 @@ assert_eq!(model.as_deref(), Some("qwen-coder-14b")); // No binding at all (no deliberation faculty) → no loadout, honest-absent. - assert!(cycle(vec![], 4).model_loadout().is_none()); + assert!(cycle(vec![]).model_loadout().is_none()); } // what this catches: every finding is stamped with the cycle it was computed @@ -348,7 +339,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let c = cycle(faculties, 4); + let c = cycle(faculties); // First tick → CycleId(1); both the perception (Recall) and deliberation // (verdict) findings must carry it. @@ -397,7 +388,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let c = cycle(faculties, 4); + let c = cycle(faculties); let ws = Workspace::new("teammate: the deploy is red, what happened?"); // isolate recall: exactly one bid, its engram content, a real timing. @@ -448,7 +439,7 @@ // the highest-salience faculty bids win the bounded workspace. This is the // ML-integration replacement for calculate_priority's hand-weights. #[tokio::test] - async fn arbiter_selects_top_k_by_ml_salience() { + async fn arbiter_forwards_every_bid_highest_salience_first() { let faculties: Vec> = vec![ Arc::new(FixedFaculty(Contribution::context( FacultyId::Recall, @@ -469,10 +460,9 @@ "some arousal", ))), ]; - let ws = cycle(faculties, 2).run("the consolidated thread").await; - assert_eq!(ws.broadcast.len(), 2, "bounded capacity"); - assert_eq!(ws.broadcast[0].content, "high", "highest ML salience wins"); - assert_eq!(ws.broadcast[1].content, "mid"); + let ws = cycle(faculties).run("the consolidated thread").await; + let order: Vec<&str> = ws.broadcast.iter().map(|c| c.content.as_str()).collect(); + assert_eq!(order, ["high", "mid", "low"], "every bid, highest ML salience first: the view sizes each"); } // what this catches: ACTING-ORGANISM step 1 — the mind can express "I want to @@ -498,7 +488,7 @@ 0.95, "the model emitted a tool call", )))]; - let ws = cycle(faculties, 4).run("peer: does your sum work?").await; + let ws = cycle(faculties).run("peer: does your sum work?").await; match ws.decision() { Some(Decision::Act { calls, intent }) => { assert_eq!(calls.as_slice(), std::slice::from_ref(&call)); @@ -538,11 +528,11 @@ "actionable", ))), ]; - let ws = cycle(faculties, 1).run("burst").await; - assert_eq!(ws.broadcast.len(), 1); + let ws = cycle(faculties).run("burst").await; + assert_eq!(ws.broadcast.len(), 2); assert!( ws.broadcast[0].content.contains("peer persona"), - "the relevant peer-persona content wins on salience, not the human's rank" + "the relevant peer-persona content leads on salience, not the human's rank" ); } @@ -566,7 +556,7 @@ "high epistemic value — no one raised it", ))), ]; - let ws = cycle(faculties, 5).run("coordination thread").await; + let ws = cycle(faculties).run("coordination thread").await; match ws.decision() { Some(Decision::RaiseUnprompted { text }) => { assert_eq!(text, "blocker on the deploy") @@ -587,7 +577,7 @@ "nothing worth adding", ))), ]; - let ws = cycle(faculties, 5).run("idle chatter").await; + let ws = cycle(faculties).run("idle chatter").await; assert_eq!( ws.broadcast.len(), 1, @@ -615,7 +605,7 @@ "model 'X' is not the active served model (serving: 'Y')", ))), ]; - let ws = cycle(faculties, 5).run("swept to an unhosted model").await; + let ws = cycle(faculties).run("swept to an unhosted model").await; // The fault is readable and names the cause verbatim… assert_eq!( ws.deliberation_fault(), @@ -653,12 +643,12 @@ context.receipts = vec![receipt("other-faculty", served())]; let faculties: Vec> = vec![Arc::new(FixedFaculty(verdict)), Arc::new(FixedFaculty(context))]; - let ws = cycle(faculties, 5).run("decide").await; + let ws = cycle(faculties).run("decide").await; assert_eq!(ws.decision_generation().as_deref(), Some("decided")); let mut all_faulted = Contribution::verdict(Decision::Speak { text: "x".into() }, 0.8, "faulted"); all_faulted.receipts = vec![receipt("only-fault", faulted())]; - let ws = cycle(vec![Arc::new(FixedFaculty(all_faulted))], 5).run("decide").await; + let ws = cycle(vec![Arc::new(FixedFaculty(all_faulted))]).run("decide").await; assert_eq!(ws.decision_generation(), None, "a decision with no served generation carries none"); } @@ -674,7 +664,7 @@ 0.8, "caught up on the backlog", )))]; - let ws = cycle(faculties, 5).run(consolidated).await; + let ws = cycle(faculties).run(consolidated).await; assert!(ws.world_state.contains("many events, one unit")); assert!(matches!(ws.decision(), Some(Decision::Speak { .. }))); } @@ -710,8 +700,8 @@ "high value", ))), ]; - // capacity 1 → only the winner is broadcast, but the trace keeps both. - let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 1) + // Every bid is broadcast, and the trace keeps every bid with its salience. + let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .with_capture(sink.clone()) .run("thread") .await; @@ -720,7 +710,7 @@ assert_eq!(traces.len(), 1, "one tick recorded"); let t = &traces[0]; assert_eq!(t.bids.len(), 2, "trace keeps ALL bids — winner AND loser"); - assert_eq!(t.broadcast.len(), 1, "only the winner held attention"); + assert_eq!(t.broadcast.len(), 2, "attention forwards every bid"); assert!( t.bids.iter().any(|b| b.content == "loser bid"), "the loser bid + its salience + reasoning are replayable for debugging" @@ -750,7 +740,7 @@ // Phase 2 (deliberation): reacts to the assembled broadcast. Arc::new(ConditionalDeliberation), ]; - let ws = cycle(faculties, 5).run("what's the status?").await; + let ws = cycle(faculties).run("what's the status?").await; match ws.decision() { Some(Decision::Speak { text }) => assert!( text.contains("deploy pipeline is red"), @@ -778,7 +768,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 5) + let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .with_capture(sink.clone()) .run("status?") .await; @@ -839,7 +829,7 @@ ))), Arc::new(CountingDeliberation(calls.clone())), ]; - let _ws = cycle(faculties, 5).run("burst").await; + let _ws = cycle(faculties).run("burst").await; assert_eq!( calls.load(std::sync::atomic::Ordering::SeqCst), 1, @@ -887,11 +877,10 @@ ); let candidates = vec![roster, doctrine, result.clone(), recall.clone()]; - // Fresh ask: fuller grounding — everything within capacity survives, exactly - // like the blind salience floor. + // Fresh ask: fuller grounding — every bid survives, exactly like the blind + // salience floor. let fresh = arbiter.focus( candidates.clone(), - 10, &FocusContext { world_state: "ask", situation: Situation::FreshContext, @@ -923,7 +912,6 @@ // "salience still governs which contributions are included and truncated". let post = arbiter.focus( candidates, - 10, &FocusContext { world_state: "result", situation: Situation::PostAction, diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs index c6a7e808da..88efb143b2 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs @@ -1,15 +1,10 @@ use super::*; impl WorkspaceCycle { - pub fn new( - faculties: Vec>, - arbiter: Arc, - capacity: usize, - ) -> Self { + pub fn new(faculties: Vec>, arbiter: Arc) -> Self { Self { faculties, arbiter, - capacity: capacity.max(1), capture: Arc::new(NoopWorkspaceCaptureSink), acting: None, genome: empty_genome(), @@ -436,7 +431,7 @@ impl WorkspaceCycle { /// /// This is what makes "pull relevant memory, *then* decide" real: the decider /// is never blind to recall. Still one tick over the consolidated burst, still - /// `O(capacity)` for the bounded context — no per-event slowdown. + /// `O(bids)` for the context — no per-event slowdown. /// TEST-ONLY ambient shorthand: the burst names its room (a raw string /// converts with [`ActivityRoom::test_room`](crate::identity::ActivityRoom::test_room) /// under `#[cfg(test)]`), so even faculty-isolation ticks run in a diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs index f9b4860180..e90724718e 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs @@ -148,7 +148,7 @@ impl WorkspaceCycle { }; let focused = self .arbiter - .focus(context_bids.clone(), self.capacity, &focus_ctx); + .focus(context_bids.clone(), &focus_ctx); // Bids-vs-focused receipt at the attention seam. Together with // `delib.context.render` (received-vs-rendered) this closes the glass box // over a surfaced finding's whole path: faculty bid → attention → @@ -157,7 +157,6 @@ impl WorkspaceCycle { // dark (#130). continuum_base::probe!( class = "workspace.attention.focus", - capacity = self.capacity, // The situation that drove this focus — the stat that makes context // control learnable: a focuser policy (this bootstrap, or a later // learned one) is a function of situation → dropped grounding, and the diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 5aed0ece2c..71a8d1a42b 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -354,7 +354,6 @@ mod tests { RecallMetadataRegistry::new(), ))), adapter: std::sync::Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs index b0be45c91b..f693d83332 100644 --- a/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs +++ b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use crate::cognition::act_observe::test_support::{admission, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{settle_step, ActChain}; -use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{ ActingBody, SalienceArbiter, Situation, TurnFraming, WorkspaceCycle, }; @@ -108,11 +108,9 @@ async fn bound_card_activity_is_shared_by_perception_and_execution() { let cycle = WorkspaceCycle::new( vec![ Arc::new(board), - Arc::new(WorkingMemoryFaculty::new(wm.clone())), Arc::new(ActThenSpeak::new()), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(Arc::new(ActingBody { persona_id: persona, diff --git a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs index f1eb854e02..06b67aaa04 100644 --- a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs +++ b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs @@ -259,7 +259,7 @@ async fn a_claims_hands_are_its_own_and_her_default_hands_never_move() { card_staging::stage_for_card(home.path(), persona, &gym_card).await, card_staging::Staging::Ready { path: workspace.clone() }, ); - let cycle = WorkspaceCycle::new(vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), 4) + let cycle = WorkspaceCycle::new(vec![], Arc::new(crate::cognition::workspace::SalienceArbiter)) .with_acting(Arc::new(ActingBody { persona_id: persona, persona_name: live.persona_name.clone(), executor: live.executor.clone(), working_memory: live.working_memory.clone(), @@ -440,7 +440,6 @@ fn a_handless_cycle_yields_no_hands() { let cycle = crate::cognition::workspace::WorkspaceCycle::new( vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), - 4, ); assert!(ActingHands::of(&cycle).is_none()); } diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs index 4199e3c55a..3b0dc9d978 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs @@ -29,7 +29,6 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { // shape: `code/search` returned the `_sympify` location she must edit next. Large // enough to clear the trail-head threshold so the pinned block surfaces. let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(16_384); let needle = "sympy/core/expr.py:123: return self == sympify(other) # _sympify HERE"; let grep_result = format!( "code/search matches:\n{needle}\n{}", @@ -265,7 +264,6 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { // (a burst to pointers once the share is exceeded), so the window is sized to // hold this 16.8k-char inventory beside the next batch; a smaller window would // collapse it at the batch's receipt, which is the other mechanism, not this one. - wm.set_served_window(65_536); let pin = crate::cognition::tool_executor::spill::LivePin::new(); let custody = pin.retain(persona, &inventory); let handle = custody.handle().expect("saved inventory").to_owned(); diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs index 6115de0c6b..a9e3d814fd 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs @@ -22,7 +22,6 @@ async fn a_writing_turn_after_a_cut_gets_its_reply_on_a_46848_window() { let cut = reg.record_emission_in_memory(persona, 5_404, 0, EmissionStop::CutMidAnswer, 4); assert_eq!(cut.peak_tokens, 10_808, "a cut mid-answer records the answer at double"); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let adapter = Arc::new(ScriptedAdapter::new(vec![make_response(FinishReason::Stop, "PASS", None)])); let faculty = LlmDeliberationFaculty::new(persona, "Benchy", "You are Benchy.", adapter.clone()) .with_context_window(window) @@ -281,7 +280,6 @@ async fn standing_activity_grounding_survives_history_on_the_wire() { None, )])); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); wm.record_receipt("latest complete tool receipt"); // Optional history does not outrank the reply reserve. Give this // established citizen measured emissions so the large source diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 00cfa5d2a4..791db51f43 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -125,7 +125,6 @@ fn cfg_for(persona_id: uuid::Uuid, name: &str) -> crate::cognition::persona_work system_prompt: format!("You are {name}, an engineer on the grid."), admission: crate::cognition::act_observe::test_support::admission(), adapter: std::sync::Arc::new(crate::ai::HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index 1031377d0b..f8308553e7 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -6,7 +6,7 @@ use std::sync::Mutex; use crate::ai::types::ToolCall; use crate::cognition::act_observe::test_support::{admission, body_with_wm, ScriptedExecutor}; use crate::cognition::act_observe::*; -use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{Faculty, SalienceArbiter, TurnFraming, WorkspaceCycle}; // what this catches:41f4e3ef — a directed drive must persist real receipt-linked @@ -40,7 +40,6 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { ]); hands.pause_before = Some((5, Arc::clone(&entered), release)); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); let body = body_with_wm(Arc::new(hands), admission(), Arc::clone(&wm)); let persona = body.persona_id; let responses = (0..5) @@ -85,11 +84,9 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { }]); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm)) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body); let card = Uuid::new_v4(); diff --git a/core/continuum-mind/src/persona/obligation/recover.rs b/core/continuum-mind/src/persona/obligation/recover.rs index 38f7532b81..bc4a92a83f 100644 --- a/core/continuum-mind/src/persona/obligation/recover.rs +++ b/core/continuum-mind/src/persona/obligation/recover.rs @@ -160,7 +160,6 @@ mod tests { crate::cognition::recall_metadata::RecallMetadataRegistry::new(), ))), adapter: Arc::new(adapter), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: Some(Arc::new(crate::cognition::act_observe::test_support::ScriptedExecutor::new(["ok"]))), diff --git a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs index e73a19b372..1b54668fa1 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs @@ -105,7 +105,6 @@ use super::*; system_prompt: "You are Paige.".to_string(), admission, adapter: Arc::new(HeuristicInferenceAdapter::new().with_canned_response("PASS: done")), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -205,7 +204,6 @@ use super::*; HeuristicInferenceAdapter::new() .with_canned_response("The tests failed after the latest change."), ), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -304,7 +302,6 @@ use super::*; let cycle = crate::cognition::workspace::WorkspaceCycle::new( vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), - 4, ); let mut unavailable = current.clone(); unavailable.card_id = airc_lib::WorkCardId::new(); @@ -508,7 +505,6 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( adapter: Arc::new( HeuristicInferenceAdapter::new().with_canned_response("PASS: nothing calls me right now"), ), - capacity: None, grounding_sources: Vec::new(), embedder: None, // Her hands: an initiative turn is offered only to a mind that can act. diff --git a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs index f169349223..4be441b1f4 100644 --- a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs +++ b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs @@ -468,7 +468,6 @@ pub async fn materialize_adapters( system_prompt: system_prompt.to_string(), admission: cognition.admission.clone(), adapter: adapter.clone(), - capacity: None, // S1: the node's recipe registry, so this citizen's tool surface follows // the room she acts in (its recipe's affordances), not a global list. experience: crate::experience::source::node_experience_source(), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 33c139d025..df2a8498b3 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -626,7 +626,7 @@ mod tests { async fn starved_priority_input_survives_until_dispatch_without_replaying_actions() { use crate::cognition::act_observe::test_support::{admission, body_with_wm, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{drive_to_settle_with_input, SettleStep}; - use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; + use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{Burst, Faculty, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; use std::sync::{Arc, Mutex}; use crate::cognition::conversation::scripted_conversation::ScriptedConversation; @@ -643,11 +643,9 @@ mod tests { let wm = Arc::new(WorkingMemory::new(8)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), wm)); let original = IncomingMessage { From 91202b8125bee12b7a884746992897ce6592ace6 Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 23:44:07 -0500 Subject: [PATCH 15/88] WM slice: drop the because-clause from results (Fable approved); open views carry her whole intent as their optional level; remove the dead capacity test constant Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/apply.rs | 2 +- .../src/cognition/act_observe/mod.rs | 2 +- .../src/cognition/act_observe/observation.rs | 44 +++---------------- .../an_action_result_cannot_mute_a_citizen.rs | 2 +- .../src/cognition/rag_source_faculty/tests.rs | 3 -- .../src/cognition/working_memory/ledger.rs | 7 +-- .../cognition/working_memory/tests/actions.rs | 2 +- 7 files changed, 15 insertions(+), 47 deletions(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 4fc665ee61..de57d37edb 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -417,7 +417,7 @@ pub async fn apply_act( }, status: ActStatus::Executed, }; - observation.push_str(&obs.render_recency(intent)); + observation.push_str(&obs.render_recency()); recall_observation.push_str(&obs.render_recall(intent)); // (The canvas feed publishes at the tool-executor seam, PRE-fold — a // flood-sized ObserveResult here is already a spilled preview that no diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index 15cc663c56..2f5652cc7e 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -32,7 +32,7 @@ mod perception; mod recency; mod observation; -pub use observation::{extract_paths, intent_label, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; +pub use observation::{extract_paths, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; mod types; pub use types::{SettleOutcome, SettleStep}; diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index 6088445bc6..497ea39db0 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -257,12 +257,6 @@ impl Observation { self.output.verdict.failed() || self.output.result.is_error == Some(true) } - /// The RECENCY-channel rendering: the FULL trace working memory keeps so the - /// mind can act on what it just fetched. Byte-identical to the old inline - /// `apply.rs` block (`{name}({args}){because}\nResult:\n{bounded}\n\n`) — the - /// #205 KV-stability invariant. `intent` is batch-level (one per `apply_act` - /// call, shared by every act in the batch), so it is passed rather than - /// stored per-`Observation`. /// The call as she made it, `name(args)`: its arguments by shape, never by size /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part /// and its ledger line. @@ -270,19 +264,13 @@ impl Observation { format!("{}({})", self.call.name, render_call_args(&self.call.input)) } - pub fn render_recency(&self, intent: &str) -> String { - // The intent rides the result as a ONE-LINE reason, its first line: a shape rule, - // never a size, and never the whole monologue. - // Measured 2026-09-04: one result header carried 2,902 chars of intent - // ("Let me get oriented…") ahead of 790 chars of actual output; across a - // turn, 6.1k of 20.6k result chars were intent echo. The output is what - // she must read; the reason is a label. - let because = if intent.trim().is_empty() { - String::new() - } else { - format!(" because {}", intent_label(intent)) - }; - format!("{}{}\nResult:\n{}\n\n", self.call_line(), because, self.body_text().trim()) + /// The RECENCY-channel rendering: the FULL trace working memory keeps so the mind can act on + /// what it just fetched, `{call}\nResult:\n{body}\n\n`, stable across acts (the #205 + /// KV-stability invariant). + pub fn render_recency(&self) -> String { + // No reason clause: her intent reaches her whole as her own thought, and #5611's causes + // link each result to its act, so a result carries its call and its output only. + format!("{}\nResult:\n{}\n\n", self.call_line(), self.body_text().trim()) } /// This act as one part of a batch receipt's summary level: the recency header (its name and @@ -350,27 +338,9 @@ pub fn extract_paths(input: &serde_json::Value) -> Vec { out } -/// Clip an act's intent to a one-line reason of at most `max_chars` characters -/// (first line, head-trimmed with an ellipsis). Pure; used by the recency render. -/// The intent's label on a result: its first line. A shape rule, never a size: the rest of what she -/// thought is her own message, already in her view. -pub fn intent_label(intent: &str) -> String { - intent.trim().lines().next().map_or_else(String::new, |first| first.trim().to_string()) // an empty intent labels nothing -} - #[cfg(test)] mod tests { - // what this catches: the monologue riding every result (2,902 chars of intent ahead of 790 - // chars of output, measured 2026-09-04). The label is the first line, by shape, never a size. - #[test] - fn intent_on_a_result_is_its_first_line() { - let long = "Let me get oriented properly this time. I've been confusing myself with stale context and the board says otherwise.\nSecond line never rides."; - let label = super::intent_label(long); - assert!(label.starts_with("Let me get oriented") && !label.contains("Second line"), "{label:?}"); - assert_eq!(super::intent_label("read the card"), "read the card"); - assert_eq!(super::intent_label(" "), ""); - } use super::*; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs index 953427498a..16c05717fe 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs @@ -98,7 +98,7 @@ mod the_newest_result_over_her_window { }, status: ActStatus::Executed, }; - let rendered = observation.render_recency(""); + let rendered = observation.render_recency(); wm.record_receipt_typed(&[observation], &rendered, Some(room), ResultCustody::Whole { handle: HANDLE.into() }); LlmDeliberationFaculty::new(Uuid::new_v4(), "Aris", "You are Aris.", adapter) .with_context_window(window) diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs index aed446f872..c5cf0706fe 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -636,6 +636,3 @@ ); } - /// The production default capacity (mirror of persona_workspace's constant) so - /// the canary tests the realistic configuration, not a contrived one. - const DEFAULT_CAPACITY_FOR_TEST: usize = 6; diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f34c3bebdd..6e0606db7a 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -222,13 +222,14 @@ impl WorkingMemory { } /// Attach her stated reasoning for the act just recorded to the open views it touched, - /// so each view carries what she understood, not only how far she read. The note is the - /// intent's label, its first line: the same shape rule a result's header uses, never a size. + /// so each view carries what she intended, not only how far she read. Whole, never a first + /// line: it is an optional level of the open-views source, which her view sizes and drops + /// before the cursor (`planning_detail_yields_to_cursor_and_returns_when_granted`). pub fn annotate_open_views(&self, intent: &str) { let Some(seq) = self.next_action_seq.load(Ordering::Relaxed).checked_sub(1) else { return; }; - self.open_views.lock().annotate(seq, &crate::cognition::act_observe::intent_label(intent)); + self.open_views.lock().annotate(seq, intent); } pub(crate) fn record_receipt_measured( diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index 792b13ed68..e6de9b4686 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -384,7 +384,7 @@ fn a_batch_receipts_summary_keeps_every_operation() { let summary_of = |acts: Vec| { let wm = WorkingMemory::new(8); // The receipt as production renders it: each act's recency rendering, in order. - let rendered: String = acts.iter().map(|a| a.render_recency("")).collect(); + let rendered: String = acts.iter().map(|a| a.render_recency()).collect(); wm.record_receipt_typed(&acts, &rendered, None, Default::default()); let actions = wm.actions.lock(); actions.records().last().and_then(|record| record.summary.clone()) From 8c01588f174ff923a526f4e895f58da9de84695a Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 23:45:34 -0500 Subject: [PATCH 16/88] WM slice: vitals gauge percentage saturates without a literal clamp; revert the doc-only touch of llm_deliberation_faculty.rs (its disk writer awaits the class handle) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/llm_deliberation_faculty.rs | 2 +- core/continuum-core/src/ipc/vitals_emitter.rs | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 55e4ee28f9..9d6a932a44 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -195,7 +195,7 @@ pub struct LlmDeliberationFaculty { /// Where this faculty records its chain-of-thought after a verdict, so the /// persona can resume its train of thought next turn (the /// [`WorkingMemory`](crate::cognition::working_memory::WorkingMemory) - /// her view's thoughts source reads). `None` → reasoning is dropped (the prior + /// `WorkingMemoryFaculty` reads). `None` → reasoning is dropped (the prior /// behavior). Only the suppressed-thinking default makes `reasoning` empty, so /// this self-activates exactly when thinking is on. working_memory: Option>, diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 71a8d1a42b..9ac00fcf79 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -90,8 +90,13 @@ const TPS_FULL_SCALE: u64 = 40; /// Prefill/ingest t/s that reads as pegged (M-series ingest ~300-800). const PFX_FULL_SCALE: u64 = 800; +/// `v` as a share of a full scale, in percent. Past the full scale it reads as full, and an +/// empty scale reads as nothing for nothing and full for anything. fn pct_usize(v: usize, full: usize) -> u8 { - (v.saturating_mul(100) / full.max(1)).min(100) as u8 + if v >= full { + return if v == 0 { 0 } else { 100 }; + } + (v.saturating_mul(100) / full) as u8 // v < full, so the share is below 100 and fits a u8 } /// One tick's radiated readouts from `registry` — the SAMPLE half of the From 9cd28b1dcf771045c91998a39e9b05117e067ee0 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:24:06 -0500 Subject: [PATCH 17/88] WM slice: no backwards compatibility (Joel 2026-10-31: 'This is the first version'). The checkpoint carries her actions in one shape: receipt_heads, receipt_head_rooms, recent_results, result_scopes and evicted_pointers (the previous build's projection) are deleted with the legacy restore path and written_pointer; checkpoint adoption validates the records; the tests of rollback and pre-records restores are deleted Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../persona_workspace/checkpoint_adoption.rs | 12 +-- .../src/cognition/working_memory.rs | 101 +----------------- .../cognition/working_memory/action_log.rs | 4 - .../cognition/working_memory/continuity.rs | 30 +----- .../src/cognition/working_memory/ledger.rs | 1 - .../cognition/working_memory/perception.rs | 2 - .../working_memory/tests/action_log.rs | 42 -------- .../cognition/working_memory/tests/actions.rs | 2 +- .../cognition/working_memory/tests/custody.rs | 39 +++---- .../working_memory/tests/provenance.rs | 19 ---- .../cognition/working_memory/tests/trail.rs | 5 - .../src/persona/wake_backlog.rs | 4 +- 12 files changed, 35 insertions(+), 226 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index cccb5ab3ba..4b5c1b46ac 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -130,18 +130,18 @@ fn summary(bytes: &[u8]) -> Result { .as_ref() .is_some_and(|(seq, _)| *seq == 0 || *seq >= wm.next_action_seq) || wm - .recent_results + .action_records() .iter() - .any(|(seq, _, _, _, _)| *seq == 0 || *seq >= wm.next_action_seq) + .any(|record| record.seq == 0 || record.seq >= wm.next_action_seq) { return Err(invalid("receipt sequence must precede next_action_seq")); } let mut previous = None; - for (seq, _, _, _, _) in &wm.recent_results { - if previous.is_some_and(|old| old >= *seq) { + for record in wm.action_records() { + if previous.is_some_and(|old| old >= record.seq) { return Err(invalid("result receipt sequences must strictly increase")); } - previous = Some(*seq); + previous = Some(record.seq); } let utterances = match &persisted.own_speech { OwnSpeechPersisted::ByRoom(rooms) => { @@ -160,7 +160,7 @@ fn summary(bytes: &[u8]) -> Result { saved_at_ms: wm.saved_at_ms, next_action_seq: wm.next_action_seq, entries: wm.entries.len(), - result_receipts: wm.recent_results.len(), + result_receipts: wm.action_records().iter().filter(|record| record.result.is_some()).count(), own_utterances: utterances, unscoped_own_utterances: match &persisted.own_speech { OwnSpeechPersisted::ByRoom(_) => 0, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 99026b550b..de18895a62 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -149,10 +149,7 @@ impl<'a> ResultAttribution<'a> { /// The line a collapsed result leaves: what it was, and the handle that reopens it. fn collapsed_pointer(record: &action_log::ActionRecord) -> String { - match &record.written_pointer { - Some(pointer) => pointer.clone(), - None => format!("[result {}{} — collapsed]", ResultAttribution::of(record), workspace_label(record.scope.as_deref())), - } + format!("[result {}{} — collapsed]", ResultAttribution::of(record), workspace_label(record.scope.as_deref())) } /// Recognize ONLY the standalone pointer representation emitted by this owner. @@ -430,43 +427,14 @@ pub struct VolatileSnapshot { /// then says nothing rather than guessing a change it cannot see (#165). #[serde(default)] pub build_sha: String, - /// The proprioception receipt archive (#414) — act-history head lines that must - /// survive a reboot exactly as the ring entries do (the counter already did; a - /// counter without its lines is the deprivation this field exists to end). Empty - /// on snapshots written before this field (serde default): restore starts the - /// archive fresh and the ledger's counter-only arm stays honest about the gap. - #[serde(default)] - pub receipt_heads: Vec, - /// Room tags parallel to `receipt_heads`, index-aligned (slice B). A - /// SEPARATE defaulted field — not a tuple — so snapshots written before - /// scoping still deserialize; restore pads missing tags with `None` - /// (honest "unscoped", never a guessed room). - #[serde(default)] - pub receipt_head_rooms: Vec>, - /// Recent act result TAILS `(seq, room, tail)` — the cross-turn feedback - /// channel (2026-08-16). Defaulted so pre-field snapshots deserialize; - /// restore then starts the buffer fresh. - #[serde(default)] - pub recent_results: Vec<(u64, Option, String, String, Option)>, - /// Additive attribution preserves the existing receipt tuple wire format. Missing - /// legacy attribution is unknown, never inferred from a room or the current root. - #[serde(default)] - pub result_scopes: BTreeMap, /// Her state at the seam — the whole held card, her ledger, what was staged, what tore /// the life (card 49b5e806, Kimi 2026-09-26). Stamped by `save_volatile`, which knows /// whose memory this is and why it is being written; rendered FIRST on wake. `None` on /// snapshots from before this field and for a citizen at home with nothing to hand. #[serde(default)] pub handoff: Option, - /// The collapsed results' pointers, each with the handle it reopens: what a result - /// leaves when it collapses out of the ring is HOW she reaches it again, so it survives - /// a restart exactly as the ring does (Astra on #4963: a read collapsed at settlement - /// lost its only handle on restart). Empty on snapshots written before this field. - #[serde(default)] - pub evicted_pointers: Vec<(String, String)>, - /// Her actions, whole ([`action_log`]): what a restore reads. The ring, archive and - /// pointer fields above are the same acts in the shape the previous build reads, kept - /// so a rollback still restores her. Empty on snapshots written before it. + /// Her actions, whole ([`action_log`]): what a restore reads, the one shape (no projection + /// for another build: this is the first version, Joel 2026-10-31). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) actions: Vec, /// Her context view ([`WorkingMemory`]'s `view`). Absent on snapshots written before it, @@ -522,63 +490,9 @@ impl VolatileSnapshot { } } - /// Her actions as records: the records it carries, or, for a checkpoint written before - /// them, the ring, archive and pointer index read back into records. Those older lines - /// are keyed by the `#n` this owner wrote at their head (one with none is dropped and - /// counted), and an older pointer keeps the exact text it was written with, since its - /// operation and workspace are not stored apart from it. + /// Her actions as records, as the checkpoint carries them. pub(crate) fn action_records(&self) -> Vec { - if !self.actions.is_empty() { - return self.actions.clone(); - } - let blank = |seq: u64, room: Option| action_log::ActionRecord { - seq, - room, - scope: None, - operation: "unrecorded".into(), - head: None, - result: None, - handle: None, - written_pointer: None, - summary: None, - stored_chars: None, - received_ms: None, - }; - let mut records: BTreeMap = BTreeMap::new(); - let mut unkeyed = 0usize; - for (seq, room, result, operation, handle) in &self.recent_results { - let record = records.entry(*seq).or_insert_with(|| blank(*seq, *room)); - record.scope = self.result_scopes.get(seq).cloned(); - record.operation = operation.clone(); - record.result = Some(result.clone()); - record.handle = handle.clone(); - } - let mut rooms = self.receipt_head_rooms.iter(); - for head in &self.receipt_heads { - let room = rooms.next().copied().flatten(); - let Some(seq) = written_seq(head, "[action #") else { - unkeyed += 1; - continue; - }; - records.entry(seq).or_insert_with(|| blank(seq, room)).head = Some(head.clone()); - } - for (pointer, handle) in &self.evicted_pointers { - let Some(seq) = written_seq(pointer, "[result #") else { - unkeyed += 1; - continue; - }; - let record = records.entry(seq).or_insert_with(|| blank(seq, None)); - record.handle.get_or_insert_with(|| handle.clone()); - record.written_pointer = Some(pointer.clone()); - } - if unkeyed > 0 { - continuum_base::probe!( - class = "wm.actions.unkeyed_on_restore", - unkeyed = %unkeyed, - "checkpoint lines without an action number were dropped on restore" - ); - } - records.into_values().collect() + self.actions.clone() } /// Every saved result this checkpoint still reaches; the persisted twin of what working @@ -614,11 +528,6 @@ impl VolatileSnapshot { } } -/// The `#n` this owner wrote right after `prefix` at the head of a line. -fn written_seq(line: &str, prefix: &str) -> Option { - let digits: String = line.strip_prefix(prefix)?.chars().take_while(char::is_ascii_digit).collect(); - digits.parse().ok() -} /// "; workspace " for a result recorded under a root; empty for one recorded before. fn workspace_label(root: Option<&str>) -> String { diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index ad4d5af2ec..997b49585c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -48,10 +48,6 @@ pub(crate) struct ActionRecord { /// The saved whole; `None` when the save failed, and then the result never collapses /// (nothing else holds its bytes). pub handle: Option, - /// The pointer exactly as a build before the records wrote it, restored from its - /// checkpoint: its operation and workspace live only in that text. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub written_pointer: Option, /// The result's summary level (`continuum_context::levels`): a numbered read's outline, /// else an output's head and tail; what her view gives it when it cannot keep it whole. /// Kept after the result collapses, so what she read stays addressable. diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 4e6cc7460c..1ef0c4c2dc 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -180,41 +180,14 @@ impl WorkingMemory { } (entries, authored) }; - // The log, projected into the wire shape older builds read (see - // `VolatileSnapshot::action_records`), under one lock so a concurrent collapse - // cannot move a record between the projections. let last_action = self.last_action.lock().clone(); - let (archive, recent_results, result_scopes, pointers, records) = { - let actions = self.actions.lock(); - let archive: Vec<(Option, String)> = actions - .records() - .filter_map(|record| record.head.as_ref().map(|head| (record.room, head.clone()))) - .collect(); - let recent_results: Vec<(u64, Option, String, String, Option)> = actions - .retained() - .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) - .collect(); - let result_scopes: BTreeMap = actions - .retained() - .filter_map(|r| r.scope.clone().map(|scope| (r.seq, scope))) - .collect(); - let pointers: Vec<(String, String)> = actions - .indexed_pointers() - .into_iter() - .filter_map(|r| r.handle.clone().map(|handle| (super::collapsed_pointer(r), handle))) - .collect(); - (archive, recent_results, result_scopes, pointers, actions.records().cloned().collect()) - }; + let records: Vec = self.actions.lock().records().cloned().collect(); VolatileSnapshot { pending_emissions: self.pending_emissions.lock().clone(), entries, action_statements, last_action, action_fps: self.action_fps.lock().iter().cloned().collect(), - receipt_heads: archive.iter().map(|(_, head)| head.clone()).collect(), - receipt_head_rooms: archive.iter().map(|(room, _)| *room).collect(), - recent_results, - result_scopes, next_action_seq: self.next_action_seq.load(Ordering::Relaxed), saved_at_ms: continuum_base::time::EpochMs::now().millis(), build_sha: env!("CONTINUUM_BUILD_GIT_SHA").to_string(), @@ -229,7 +202,6 @@ impl WorkingMemory { .filter(|d| d.status == DispatchStatus::Running) .map(|d| d.label.clone()) .collect(), - evicted_pointers: pointers, actions: records, context_view: self.view.lock().clone(), receipt_children: self.receipt_children.lock().clone(), diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 6e0606db7a..890bf869f2 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -315,7 +315,6 @@ impl WorkingMemory { summary: result_summary(&tail, &acts), result: Some(tail), handle, - written_pointer: None, stored_chars: None, received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 60f219c143..9723b13fef 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -255,8 +255,6 @@ impl WorkingMemory { let workspace = workspace_label(record.scope.as_deref()); let whole = record.result.as_deref().map(|result| format!("[result {attribution}{workspace}] {result}")); let pointer = match (&record.handle, &whole, &record.head) { - // An older build's pointer, as it was written (its operation lives there). - (Some(_), _, _) if record.written_pointer.is_some() => record.written_pointer.clone().into_iter().collect(), (Some(_), _, _) => format!("[result {attribution}{workspace} — collapsed; query tool/output to expand]"), // Retained but never saved: no handle could reopen a collapsed line, so it stays // whole (goal 7: the full result stays reachable; Cormac on #5255). diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 48b9426212..34a462b411 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs @@ -29,29 +29,6 @@ fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { assert!(!ring.contains(&"a".repeat(cap / 2)), "its whole result left the ring"); } -// what this catches: a checkpoint from the build before the log losing what a collapsed -// result reopens. Its pointer lines and ledger lines carry no seq column; the #n the old -// owner wrote keys them, and the pointer's saved whole stays reachable for the spill guard. -#[test] -fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { - let mut legacy = WorkingMemory::new(8).snapshot(); - legacy.receipt_heads = vec!["[action #7] code/read(\"a.rs\")".into(), "[action #8] code/shell(\"ls\")".into()]; - legacy.receipt_head_rooms = vec![None, None]; - legacy.recent_results = vec![(8, None, "a.rs\nb.rs".into(), "code/shell".into(), Some("h8".into()))]; - legacy.evicted_pointers = vec![("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]".into(), "h7".into())]; - legacy.next_action_seq = 9; - let reachable = legacy.reachable_handles(); - assert!(reachable.contains("h7") && reachable.contains("h8"), "{reachable:?}"); - let wm = WorkingMemory::new(8); - wm.restore(legacy); - let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); - assert_eq!(lines, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); - let ring = wm.recent_results_messages().join("\n"); - // Its pointer keeps the exact text the older build wrote: operation and all. - assert!(ring.contains("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]"), "{ring}"); - assert!(ring.contains("a.rs\nb.rs"), "{ring}"); -} - // what this catches: a restart changing what she reads of her own acts (Cormac on #5254: a // collapsed pointer re-rendered as "operation unrecorded" with no workspace, because the // checkpoint kept a pointer only as text). Every record is checkpointed whole, so her ring @@ -82,25 +59,6 @@ fn a_restart_keeps_every_act_as_she_read_it() { assert_eq!(ledger(&restored), lines); } -// what this catches: a rollback to the build before the log restoring her blank. The -// checkpoint keeps the wire shape that build reads beside the records it now restores from. -#[test] -fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { - let wm = WorkingMemory::new(8); - let cap = 2 * BODY; - wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); - for act in 2..=5 { - record_saved(&wm, &format!("act {act}\n{}", "s".repeat(cap / 2))); - } - wm.record_settlement("done", None); - shed(&wm, cap / 2); - let snap = wm.snapshot(); - assert!(snap.receipt_heads.first().is_some_and(|head| head.starts_with("[action #1]"))); - assert_eq!(snap.evicted_pointers.first().map(|(_, handle)| handle.as_str()), Some("first-handle")); - assert_eq!(snap.recent_results.last().map(|(seq, ..)| *seq), Some(5)); - assert_eq!(snap.actions.len(), 5); -} - // what this catches (card d624a9a1): an act's line cutting an argument mid-value. A cut path // reads as a real one, and a small model copies it and loops (IntelMac 2026-10-22: a cut // '.../citizens/pe' became three refused reads). Her recorded line shows a single-line value diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index e6de9b4686..d5e6f3db96 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -32,7 +32,7 @@ async fn latest_action_returns_full_result_trail_keeps_its_call_line() { .pinned_active_result_block() .expect("the whole result is pinned for the mind"); assert!( - pinned.contains("Full result of your most recent action (#1; room unrecorded; operation unrecorded):"), + pinned.contains("Full result of your most recent action (#1; room unrecorded; operation code/read):"), "the whole result reaches the mind" ); assert!( diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index b96d895566..6dba2bf0a5 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -60,23 +60,16 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ results.record_settlement("reported", None); shed(&results, 0); let snapshot = results.snapshot(); - assert!(!snapshot.evicted_pointers.is_empty(), "fixture exercises the collapsed ring"); - let mut encoded = serde_json::to_value(&snapshot).expect("snapshot serializes"); + assert!(snapshot.action_records().iter().any(|r| r.result.is_none() && r.handle.is_some()), "fixture exercises a collapsed result"); + let encoded = serde_json::to_value(&snapshot).expect("snapshot serializes"); let restored = WorkingMemory::new(2); restored.restore(serde_json::from_value(encoded.clone()).expect("snapshot round trip")); let shown = restored.recent_results_messages().join("\n"); restored.set_scope(Some("task-b".into())); assert!(shown.contains("scope-a-output") && restored.recent_results_messages().join("\n") == shown, "{shown}"); - assert_eq!(restored.snapshot().evicted_pointers, snapshot.evicted_pointers, "pointers retain custody"); - // Pre-attribution snapshots stay explicitly unknown, not falsely assigned - // to the restoring root or hidden based on missing bounded entry metadata. - encoded.as_object_mut().unwrap().remove("result_scopes"); - let legacy = WorkingMemory::new(2); - legacy.restore(serde_json::from_value(encoded).expect("legacy snapshot")); - legacy.set_scope(Some("task-b".into())); - assert!(legacy.recent_results_messages().join("\n").contains("scope-a-output")); + assert_eq!(restored.snapshot().action_records(), snapshot.action_records(), "collapsed results retain custody"); // Receipt publication, pruning and snapshots share custody: a concurrent - // checkpoint must never downgrade a known-root result to legacy unknown. + // checkpoint must never lose a result's root. let concurrent = WorkingMemory::new(2); concurrent.set_scope(Some("writer-root".into())); std::thread::scope(|threads| { @@ -86,9 +79,8 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ for _ in 0..128 { concurrent.publish_live_handles(); let snapshot = concurrent.snapshot(); - for seq in snapshot.recent_results.iter().map(|r| r.0) - .chain(snapshot.last_action.iter().map(|r| r.0)) { - assert_eq!(snapshot.result_scopes.get(&seq).map(String::as_str), Some("writer-root")); + for record in snapshot.action_records().iter().filter(|r| r.result.is_some()) { + assert_eq!(record.scope.as_deref(), Some("writer-root")); } } }); @@ -245,16 +237,26 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { let _ = std::fs::remove_dir_all(&root); } -// what this catches (Codex on #4987): a legacy receipt with no handle files its children +// what this catches (Codex on #4987): a receipt with no handle (its save failed) files its children // under `seq:N`; restore saves it and it takes a handle, so the children must move to that // key or the next publish prunes them as belonging to no receipt. #[test] -fn a_restored_legacy_receipt_keeps_its_children_under_its_new_handle() { +fn a_restored_handleless_receipt_keeps_its_children_under_its_new_handle() { let child = format!("{:016x}", Uuid::new_v4().as_u128() as u64); let mut snapshot = WorkingMemory::new(8).snapshot(); - snapshot.recent_results.push((7, None, "a legacy receipt".into(), "code/read".into(), None)); + snapshot.actions.push(crate::cognition::working_memory::action_log::ActionRecord { + seq: 7, + room: None, + scope: None, + operation: "code/read".into(), + head: None, + result: Some("a receipt whose save failed".into()), + handle: None, + summary: None, + stored_chars: None, + received_ms: None, + }); snapshot.receipt_children.insert(receipt_key(7, None), vec![child.clone()]); - snapshot.actions = snapshot.action_records(); // what retain_handleless does first let unsaved = snapshot.unsaved_receipts(); let handle = format!("{:016x}", Uuid::new_v4().as_u128() as u64); snapshot.actions[0].handle = Some(handle.clone()); // what a successful save sets @@ -346,7 +348,6 @@ fn results_are_never_evicted_at_receipt_however_large_the_ring() { } assert!(wm.resident_result_bytes() >= 40 * chunk as u64, "all 40 bodies resident: {}", wm.resident_result_bytes()); let snapshot = wm.snapshot(); - assert!(snapshot.evicted_pointers.is_empty(), "nothing collapsed to a pointer"); assert!(snapshot.actions.iter().all(|record| record.result.is_some()), "every record holds its body"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 58c026d2b8..6358c7db5e 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -247,25 +247,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { assert_whole_or_handle(&restarted); } -// e731: pre-result-ring snapshots have a full body but no room/operation -// attribution. Rendering must expose that absence instead of inventing it. -#[test] -fn legacy_full_result_without_metadata_stays_explicitly_unattributed() { - let wm = WorkingMemory::new(8); - wm.record_receipt("legacy body"); - let mut snapshot = wm.snapshot(); - snapshot.recent_results.clear(); - let restored = WorkingMemory::new(8); - restored.restore(snapshot); - let (seq, full) = restored - .active_action_full() - .expect("test: legacy body restored"); - assert_eq!( - restored.full_result_message(seq, &full), - "Full result of your most recent action (#1; room unrecorded; operation unrecorded):\nlegacy body" - ); -} - // what this catches (Step 3 back-compat): an OLD volatile.json — written before // the WmEntry.acts field existed — restores WITHOUT panic, the `acts` defaulting // to empty via `#[serde(default)]` (the same contract as saved_at_ms/build_sha). diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 83b2c3aaa7..c0f1c27d7f 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -267,12 +267,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { interrupted_dispatches: Vec::new(), build_sha: String::new(), // pre-field snapshot: no rebuild guessed either acting_card: None, - receipt_heads: Vec::new(), - receipt_head_rooms: Vec::new(), // pre-archive snapshot: ledger's counter-only arm covers it - recent_results: Vec::new(), - result_scopes: Default::default(), handoff: None, - evicted_pointers: Vec::new(), actions: Vec::new(), context_view: None, receipt_children: Default::default(), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index df2a8498b3..a347c40809 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -634,13 +634,13 @@ mod tests { use std::sync::atomic::{AtomicBool, Ordering}; let gate = Arc::new(AtomicBool::new(false)); - let mut faculty = ActThenSpeak::new(); + let wm = Arc::new(WorkingMemory::new(8)); + let mut faculty = ActThenSpeak::new().with_memory(Arc::clone(&wm)); faculty.admission_open = Some(Arc::clone(&gate)); let exec = Arc::new(RecordingExecutor { seen_context: Arc::new(Mutex::new(None)), result_content: "4".into(), }); - let wm = Arc::new(WorkingMemory::new(8)); let cycle = WorkspaceCycle::new( vec![ Arc::new(faculty), From 61e6b550e33d41823ebd9e3d2f146dc6f51bf616 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:36:35 -0500 Subject: [PATCH 18/88] WM slice: observation::call_args, the one argument renderer (Observation::call_line uses it; #5635's status line will) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/observation.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index 497ea39db0..ba7cc4fd82 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -226,6 +226,14 @@ impl ActOutcome { } } +/// A call's arguments as she reads them, by shape and never by size: a single-line value whole, +/// a multi-line value (a file's body, a heredoc) by its reference, so one line stays one line. +/// The one argument renderer (`Observation::call_line`, and a result's status line in +/// `tool_executor::answer`). +pub(crate) fn call_args(input: &serde_json::Value) -> String { + render_call_args(input) +} + impl Observation { /// Execution alone is not success: projected running/failed/undecodable /// results do not establish an effect. Legacy unprojected commands retain @@ -261,7 +269,7 @@ impl Observation { /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part /// and its ledger line. pub(crate) fn call_line(&self) -> String { - format!("{}({})", self.call.name, render_call_args(&self.call.input)) + format!("{}({})", self.call.name, call_args(&self.call.input)) } /// The RECENCY-channel rendering: the FULL trace working memory keeps so the mind can act on From 895e6e72732014a669a55521f0faab59d61c7e40 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:47:49 -0500 Subject: [PATCH 19/88] WM slice: the provenance test stops asserting the old checkpoint tuple format Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/working_memory/tests/provenance.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 6358c7db5e..ca60a60915 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -185,14 +185,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { ); let encoded = serde_json::to_value(wm.snapshot()).expect("test: snapshot serializes"); - assert_eq!( - encoded["recent_results"][0] - .as_array() - .expect("test: persisted result tuple") - .len(), - 5, - "the existing checkpoint tuple format must remain compatible" - ); let restored = WorkingMemory::new(8); restored.restore(serde_json::from_value(encoded).expect("test: recorded snapshot decodes")); assert_eq!(restored.recent_results_messages(), messages); From 39ed38fdfeaf8ea31700e0a5750cef5f3c3d1804 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:52:12 -0500 Subject: [PATCH 20/88] WM slice: recent_results stays until checkpoint adoption moves onto its disk class handle (card 2b326931); adoption untouched Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../persona_workspace/checkpoint_adoption.rs | 12 ++++++------ .../src/cognition/working_memory.rs | 6 ++++++ .../src/cognition/working_memory/continuity.rs | 10 +++++++++- .../src/cognition/working_memory/tests/trail.rs | 1 + 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index 4b5c1b46ac..cccb5ab3ba 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -130,18 +130,18 @@ fn summary(bytes: &[u8]) -> Result { .as_ref() .is_some_and(|(seq, _)| *seq == 0 || *seq >= wm.next_action_seq) || wm - .action_records() + .recent_results .iter() - .any(|record| record.seq == 0 || record.seq >= wm.next_action_seq) + .any(|(seq, _, _, _, _)| *seq == 0 || *seq >= wm.next_action_seq) { return Err(invalid("receipt sequence must precede next_action_seq")); } let mut previous = None; - for record in wm.action_records() { - if previous.is_some_and(|old| old >= record.seq) { + for (seq, _, _, _, _) in &wm.recent_results { + if previous.is_some_and(|old| old >= *seq) { return Err(invalid("result receipt sequences must strictly increase")); } - previous = Some(record.seq); + previous = Some(*seq); } let utterances = match &persisted.own_speech { OwnSpeechPersisted::ByRoom(rooms) => { @@ -160,7 +160,7 @@ fn summary(bytes: &[u8]) -> Result { saved_at_ms: wm.saved_at_ms, next_action_seq: wm.next_action_seq, entries: wm.entries.len(), - result_receipts: wm.action_records().iter().filter(|record| record.result.is_some()).count(), + result_receipts: wm.recent_results.len(), own_utterances: utterances, unscoped_own_utterances: match &persisted.own_speech { OwnSpeechPersisted::ByRoom(_) => 0, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index de18895a62..4db6a404ad 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -427,6 +427,12 @@ pub struct VolatileSnapshot { /// then says nothing rather than guessing a change it cannot see (#165). #[serde(default)] pub build_sha: String, + /// Retained results `(seq, room, result, operation, handle)`, read only by checkpoint + /// adoption's validation (`persona_workspace::checkpoint_adoption`). It goes when adoption's + /// writes move onto their disk class handle (ONE-BUDGET row 5, card 2b326931; then adoption reads + /// `actions`): the one shape is `actions`. + #[serde(default)] + pub recent_results: Vec<(u64, Option, String, String, Option)>, /// Her state at the seam — the whole held card, her ledger, what was staged, what tore /// the life (card 49b5e806, Kimi 2026-09-26). Stamped by `save_volatile`, which knows /// whose memory this is and why it is being written; rendered FIRST on wake. `None` on diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 1ef0c4c2dc..e37fdbba32 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -181,13 +181,21 @@ impl WorkingMemory { (entries, authored) }; let last_action = self.last_action.lock().clone(); - let records: Vec = self.actions.lock().records().cloned().collect(); + let (records, recent_results) = { + let actions = self.actions.lock(); + let recent_results: Vec<(u64, Option, String, String, Option)> = actions + .retained() + .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) + .collect(); + (actions.records().cloned().collect::>(), recent_results) + }; VolatileSnapshot { pending_emissions: self.pending_emissions.lock().clone(), entries, action_statements, last_action, action_fps: self.action_fps.lock().iter().cloned().collect(), + recent_results, next_action_seq: self.next_action_seq.load(Ordering::Relaxed), saved_at_ms: continuum_base::time::EpochMs::now().millis(), build_sha: env!("CONTINUUM_BUILD_GIT_SHA").to_string(), diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index c0f1c27d7f..849cf8218c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -262,6 +262,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { action_statements: Vec::new(), last_action: None, action_fps: Vec::new(), + recent_results: Vec::new(), next_action_seq: 1, saved_at_ms: 0, // pre-field snapshot: no save time guessed interrupted_dispatches: Vec::new(), From fe7c4fcf6d00afb18961144c0b79cde85cb106a0 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 00:56:35 -0500 Subject: [PATCH 21/88] The render receipt: what each served prompt showed her, in order, at the level the view chose, bound to her and the request (HER-TOOLS; #5585 consumes it) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - continuum-context: `Level` moves to `levels` (the crate's levels-of-detail owner) so the epoch can record it; each `Event` carries its occurrence (`ElementId`, now serde) and level; `View::receipt()` projects every block after the head in prompt order (occurrence, level, version, retired, chars); `View::sent()` keeps it until `take_submitted()`, never saved. - continuum-cognition: `render_receipt::{RenderReceipt, RenderReceiptSink}`; the faculty takes the view's receipt on every outcome of the request that carried it and delivers it to its one sink only where that request was served, so a prompt the engine never accepted is never receipted; a measurement fork has no sink. - The memory incarnation joins the binding with #5585's `WorkingMemory::incarnation` (Codex). - clippy: one pre-existing `map_or(true, …)` in view.rs becomes `is_none_or`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/llm_deliberation_faculty.rs | 9 +++ .../llm_deliberation_faculty/request.rs | 9 +++ core/continuum-cognition/src/cognition/mod.rs | 1 + .../src/cognition/render_receipt.rs | 23 +++++++ core/continuum-context/src/cause.rs | 2 +- core/continuum-context/src/epoch.rs | 42 +++++++---- core/continuum-context/src/levels.rs | 12 ++++ core/continuum-context/src/view.rs | 69 +++++++++++++++++-- core/continuum-context/src/view/allot.rs | 10 +-- core/continuum-context/src/view/tests.rs | 29 ++++++++ 10 files changed, 178 insertions(+), 28 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/render_receipt.rs diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 9d6a932a44..c9c559661a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -236,6 +236,8 @@ pub struct LlmDeliberationFaculty { pub working_set: Option, /// Her context view across acts (`prompt/epoch.rs`): one epoch that only appends, turned /// over when it outgrows her history's grant. + /// Where her render receipts go (`crate::cognition::render_receipt`); `None` drops them. + receipt_sink: Option>, context_view: parking_lot::Mutex< Option>, >, @@ -272,6 +274,7 @@ impl LlmDeliberationFaculty { genome: empty_genome(), decoding: relaxed_decoding(), working_set: None, + receipt_sink: None, context_view: parking_lot::Mutex::new(None), tools_epoch: parking_lot::Mutex::new(None), forked: false, @@ -353,6 +356,12 @@ impl LlmDeliberationFaculty { /// browses, and the model loads any one tool's schema on demand via /// `commands/help`. An emitted call becomes a [`Decision::Act`] verdict the /// act→observe driver runs (the faculty itself never executes). + /// Install the one sink her render receipts go to (the task ledger, #5585). + pub fn with_receipt_sink(mut self, sink: Arc) -> Self { + self.receipt_sink = Some(sink); + self + } + pub fn with_tools(mut self, tools: Vec) -> Self { self.tools = tools; self.rebuild_tool_surface(); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 9a3b832064..4b5a76cf96 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -84,6 +84,8 @@ impl LlmDeliberationFaculty { /// (`slots::PageKey::Fork`). Set only by `fork_eval_cycle`. pub fn forked(mut self) -> Self { self.forked = true; + // A fork's prompts are not hers: they never acknowledge what she was shown. + self.receipt_sink = None; self } @@ -288,6 +290,10 @@ impl LlmDeliberationFaculty { .and_then(|r| r.timing.as_ref()) .map(|t| (t.cached_tokens, t.prefill_tokens)), ); + // The render receipt: taken on every outcome, so a failed request's prompt is never + // receipted, and delivered only where the request was served. + let submitted = self.context_view.lock().as_mut().and_then(continuum_context::view::View::take_submitted); + let receipted_request = request_id.clone(); let receipt = match &gen_result { Ok(response) => crate::ai::provenance::GenerationReceipt::from_response(request_id, response), Err(error) => crate::ai::provenance::GenerationReceipt::faulted(request_id, error.to_string()), @@ -296,6 +302,9 @@ impl LlmDeliberationFaculty { // window reads: in the window it was served in, whether or not her turn settles soon. if matches!(receipt.outcome, crate::ai::provenance::GenerationOutcome::Served { .. }) { crate::cognition::resident_service::note_generation(self.persona_id); + if let (Some(view), Some(sink)) = (submitted, self.receipt_sink.as_ref()) { + sink.record(crate::cognition::render_receipt::RenderReceipt { owner: self.persona_id, request: receipted_request, view }); + } } receipts.push( receipt diff --git a/core/continuum-cognition/src/cognition/mod.rs b/core/continuum-cognition/src/cognition/mod.rs index 00fe7356d6..1b42ce42a1 100644 --- a/core/continuum-cognition/src/cognition/mod.rs +++ b/core/continuum-cognition/src/cognition/mod.rs @@ -91,6 +91,7 @@ pub use continuum_capture::prompt_capture; pub mod rag_source_faculty; pub mod rate_proposals; pub mod recall_faculty; +pub mod render_receipt; pub use continuum_prompt::audience; pub use continuum_engram::recall_ranker; pub mod replay; diff --git a/core/continuum-cognition/src/cognition/render_receipt.rs b/core/continuum-cognition/src/cognition/render_receipt.rs new file mode 100644 index 0000000000..291a0de59d --- /dev/null +++ b/core/continuum-cognition/src/cognition/render_receipt.rs @@ -0,0 +1,23 @@ +//! The render receipt: what one submitted prompt showed her, bound to whose mind it was and +//! which request carried it (HER-TOOLS, "The render receipt"). The view takes its half when the +//! prompt is sent (`View::sent`); the deliberation faculty binds it and hands it to the one sink +//! where the request was served, so a prompt the engine never accepted is never receipted. +//! The task ledger (#5585) is the sink: it acknowledges a task's end from the first receipt that +//! shows that task's item, and writes nothing else. The memory incarnation joins the binding +//! with that ledger's `WorkingMemory::incarnation`. + +use uuid::Uuid; + +/// One submitted, served prompt: whose, which request, and what it showed her in order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RenderReceipt { + pub owner: Uuid, + pub request: String, + pub view: continuum_context::view::Receipt, +} + +/// Where render receipts go. One per mind, installed at assembly; none installed, a receipt is +/// dropped (nothing consumes it yet). +pub trait RenderReceiptSink: Send + Sync { + fn record(&self, receipt: RenderReceipt); +} diff --git a/core/continuum-context/src/cause.rs b/core/continuum-context/src/cause.rs index 2e20d44ec6..3f5268a250 100644 --- a/core/continuum-context/src/cause.rs +++ b/core/continuum-context/src/cause.rs @@ -9,7 +9,7 @@ use sha2::{Digest, Sha256}; /// One occurrence, named by the producer that persists it (an act, a message, an engram): /// stable across epochs and restarts, never an in-view position. Two reads of one file are two /// occurrences with two ids; the file they read is the item's `key`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub struct ElementId(u128); impl ElementId { diff --git a/core/continuum-context/src/epoch.rs b/core/continuum-context/src/epoch.rs index 543bbe6e5b..401fb7472a 100644 --- a/core/continuum-context/src/epoch.rs +++ b/core/continuum-context/src/epoch.rs @@ -34,6 +34,11 @@ impl Block for String { #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Event { pub source: SourceId, + /// The occurrence this block renders (`crate::cause`); `None` for a source's fold block, + /// which stands for a range of items. + pub element: Option, + /// The level the view rendered it at: what a render receipt reports she was shown. + pub level: crate::levels::Level, pub version: u32, pub text: T, /// The source ended with this notice; turnover drops it entirely. @@ -77,7 +82,7 @@ impl Epoch { /// Record a source's current rendering. Appends only when it differs from that source's /// latest version; never edits an earlier block. - pub fn observe(&mut self, source: SourceId, text: T) -> Observed { + pub fn observe(&mut self, source: SourceId, element: Option, level: crate::levels::Level, text: T) -> Observed { let latest = self.events.iter().rposition(|e| e.source == source); if let Some(i) = latest { if self.events[i].text == text { @@ -86,7 +91,7 @@ impl Epoch { self.superseded_chars += self.events[i].text.chars(); } let version = latest.map_or(0, |i| self.events[i].version + 1); - self.events.push(Event { source, version, text, retired: false }); + self.events.push(Event { source, element, level, version, text, retired: false }); Observed::Appended { version } } @@ -102,8 +107,8 @@ impl Epoch { return Observed::Unchanged; } self.superseded_chars += self.events[i].text.chars(); - let version = self.events[i].version + 1; - self.events.push(Event { source, version, text: notice, retired: true }); + let (element, version) = (self.events[i].element, self.events[i].version + 1); + self.events.push(Event { source, element, level: crate::levels::Level::Pointer, version, text: notice, retired: true }); Observed::Appended { version } } @@ -124,6 +129,12 @@ impl Epoch { self.events.iter().any(|e| &e.source == source) } + /// Every block after the head, in prompt order, superseded versions included: what a render + /// receipt projects. + pub fn events(&self) -> &[Event] { + &self.events + } + /// The view in order: the head, then every event as it arrived. pub fn render(&self) -> impl Iterator { self.head.iter().chain(self.events.iter().map(|e| &e.text)) @@ -142,6 +153,11 @@ impl Epoch { #[cfg(test)] mod tests { + /// A test block: whole, standing for no particular occurrence. + fn seen(e: &mut Epoch, source: SourceId, text: String) -> Observed { + e.observe(source, None, crate::levels::Level::Full, text) + } + use super::*; fn src(s: &str) -> SourceId { @@ -166,7 +182,7 @@ mod tests { let mut previous = joined(&e); for act in acts { for (s, t) in act { - e.observe(src(s), t.to_string()); + seen(&mut e, src(s), t.to_string()); } let now = joined(&e); assert!(now.starts_with(&previous), "an act rewrote the prefix:\n{previous}\n---\n{now}"); @@ -178,9 +194,9 @@ mod tests { #[test] fn an_unchanged_source_appends_nothing() { let mut e = Epoch::::new(1, vec![]); - assert_eq!(e.observe(src("kanban"), "v1".into()), Observed::Appended { version: 0 }); - assert_eq!(e.observe(src("kanban"), "v1".into()), Observed::Unchanged); - assert_eq!(e.observe(src("kanban"), "v2".into()), Observed::Appended { version: 1 }); + assert_eq!(seen(&mut e, src("kanban"), "v1".into()), Observed::Appended { version: 0 }); + assert_eq!(seen(&mut e, src("kanban"), "v1".into()), Observed::Unchanged); + assert_eq!(seen(&mut e, src("kanban"), "v2".into()), Observed::Appended { version: 1 }); assert_eq!(e.superseded_chars(), 2); } @@ -191,12 +207,12 @@ mod tests { fn per_item_sources_append_only_the_item_that_changed() { let mut e = Epoch::::new(1, vec![]); for view in ["a.rs", "b.rs", "c.rs"] { - e.observe(src(&format!("open-views/{view}")), format!("{view} v1 {}", "x".repeat(1000))); + seen(&mut e, src(&format!("open-views/{view}")), format!("{view} v1 {}", "x".repeat(1000))); } let before: usize = e.chars(); - e.observe(src("open-views/a.rs"), "a.rs v1 ".to_string() + &"x".repeat(1000)); - e.observe(src("open-views/b.rs"), "b.rs v2".into()); - e.observe(src("open-views/c.rs"), "c.rs v1 ".to_string() + &"x".repeat(1000)); + seen(&mut e, src("open-views/a.rs"), "a.rs v1 ".to_string() + &"x".repeat(1000)); + seen(&mut e, src("open-views/b.rs"), "b.rs v2".into()); + seen(&mut e, src("open-views/c.rs"), "c.rs v1 ".to_string() + &"x".repeat(1000)); let after: usize = e.chars(); assert_eq!(after - before, "b.rs v2".len(), "only the changed view was appended"); } @@ -206,7 +222,7 @@ mod tests { #[test] fn retiring_a_source_appends_its_notice_once() { let mut e = Epoch::::new(1, vec![]); - e.observe(src("open-views/a.rs"), "a.rs contents".into()); + seen(&mut e, src("open-views/a.rs"), "a.rs contents".into()); let before = joined(&e); assert_eq!(e.retire(src("open-views/a.rs"), "[closed a.rs]".into()), Observed::Appended { version: 1 }); assert!(joined(&e).starts_with(&before)); diff --git a/core/continuum-context/src/levels.rs b/core/continuum-context/src/levels.rs index 7a221f20e0..701dff3a32 100644 --- a/core/continuum-context/src/levels.rs +++ b/core/continuum-context/src/levels.rs @@ -131,6 +131,17 @@ fn head(full: &str, budget: usize) -> Option { (kept > 0 && more > 0).then(|| format!("{}\n… and {more} more (expand to read them)", lines[..kept].join("\n"))) } +/// How much of an item the view renders: whole, its summary, its pointer, or inside its +/// source's one fold block with the rest of the oldest run. The view decides it; the epoch +/// records it on each block, so a render receipt says what she was actually shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum Level { + Full, + Summary, + Pointer, + Folded, +} + #[cfg(test)] mod tests { use super::*; @@ -185,3 +196,4 @@ mod tests { assert_eq!(summarize("one\ntwo\n", Shape::List), None); } } + diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index 4f953ff94b..d20cd0d192 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -20,7 +20,8 @@ use crate::source::{Item, Source}; mod allot; -use allot::{allot, rank, Level}; +use allot::{allot, rank}; +pub use crate::levels::Level; pub use allot::floor; /// The item key a source's fold block is observed under: no source keys an item with it. @@ -75,6 +76,26 @@ pub struct Start { pub folded: usize, } +/// One block she was shown, as the view rendered it (`View::receipt`). +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Rendered { + pub source: SourceId, + /// The occurrence it renders; `None` for a fold block, which stands for a range. + pub element: Option, + pub level: Level, + pub version: u32, + /// A superseding notice for a source that ended. + pub retired: bool, + pub chars: usize, +} + +/// What one submitted prompt showed her, in prompt order (the view's half of the render receipt). +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Receipt { + pub epoch: u64, + pub items: Vec, +} + /// Serializable, so a mind's view survives her restart with the rest of her volatile state: /// restored, it renders the same bytes, and the engine's saved page for it still matches. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] @@ -99,6 +120,11 @@ pub struct View { /// redoes. Never saved: a restored view has no unsent act. #[serde(skip)] act: Option, + /// What the last sent prompt showed her, until the request that carried it is served: + /// taken there ([`View::take_submitted`]), so a prompt the engine never accepted is never + /// receipted. Never saved: a restored view has nothing in flight. + #[serde(skip)] + submitted: Option, } fn key(source: &str, item: &str) -> SourceId { @@ -216,12 +242,14 @@ impl View { appended: Vec::new(), motion: Motion::default(), act: None, + submitted: None, }; for ((source, items), grant) in sources.iter().zip(offered).zip(grants) { let allot::Allotment { levels, mut fold } = allot(&**source, &items, grant); let mut rendered = Vec::with_capacity(items.len()); for (item, level) in items.into_iter().zip(levels) { let id = key(source.name(), &item.key); + let element = item.id(); let item_key = item.key.clone(); // its fingerprint after the level consumed it; once per item per start let text = match level { Level::Full => Some(crate::source::whole(&**source, item)), @@ -239,14 +267,14 @@ impl View { view.folded.insert(id); if let Some(block) = fold.take() { rendered.push((fingerprint(FOLD_KEY, &block), block.chars())); - view.epoch.observe(key(source.name(), FOLD_KEY), block); + view.epoch.observe(key(source.name(), FOLD_KEY), None, Level::Folded, block); } continue; } }; if let Some(text) = text { rendered.push((fingerprint(&item_key, &text), text.chars())); - view.epoch.observe(id, text); + view.epoch.observe(id, Some(element), level, text); } } motion.record(source.name(), rendered); @@ -304,6 +332,13 @@ impl View { /// so nothing may rewind past it and [`View::readmit`] answers `None` until the next act. pub fn sent(&mut self) { self.act = None; + self.submitted = Some(self.receipt()); + } + + /// The receipt of the last sent prompt, once: the caller takes it where the request that + /// carried it was served, and drops it when the request failed. + pub fn take_submitted(&mut self) -> Option { + self.submitted.take() } fn append(&mut self, sources: &[&dyn Source], limit: Option<(usize, usize)>) -> Advance { @@ -319,7 +354,7 @@ impl View { // An item with no pointer would leave her view entirely if collapsed (a peer's // new turn), so it always arrives whole: admission never drops what she has // not seen. - let fits = |chars: usize| limit.map_or(true, |(limit, _)| self.epoch.chars() + chars <= limit); // map_or: no limit admits every arrival whole + let fits = |chars: usize| limit.is_none_or(|(limit, _)| self.epoch.chars() + chars <= limit); // no limit admits every arrival whole let oversized = limit.is_some_and(|(_, oversized)| crate::source::whole_chars(&item) > oversized); let level = if self.collapsed.contains(&id) { Level::Pointer @@ -334,6 +369,7 @@ impl View { self.collapsed.insert(id.clone()); Level::Pointer }; + let element = item.id(); let text = match level { Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => item.summary.or(item.pointer), @@ -341,7 +377,7 @@ impl View { }; if let Some(text) = text { let chars = text.chars(); - if let Observed::Appended { .. } = self.epoch.observe(id, text) { + if let Observed::Appended { .. } = self.epoch.observe(id, Some(element), level, text) { advance.items += 1; advance.chars += chars; } @@ -364,6 +400,29 @@ impl View { self.epoch.render() } + /// What she is shown, in prompt order: each block after the head with its occurrence, the + /// level the view rendered it at, its version and its size. Taken where the prompt is + /// SUBMITTED (the caller binds owner, memory incarnation and request there), never at + /// rendering: a prompt built but not accepted was not seen (HER-TOOLS, the render receipt). + pub fn receipt(&self) -> Receipt { + Receipt { + epoch: self.epoch.id(), + items: self + .epoch + .events() + .iter() + .map(|event| Rendered { + source: event.source.clone(), + element: event.element, + level: event.level, + version: event.version, + retired: event.retired, + chars: event.text.chars(), + }) + .collect(), + } + } + /// How each source moved across this view's starts. pub fn motion(&self) -> &Motion { &self.motion diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs index 7349e7eb25..1733a05edf 100644 --- a/core/continuum-context/src/view/allot.rs +++ b/core/continuum-context/src/view/allot.rs @@ -9,15 +9,7 @@ use crate::epoch::Block; use crate::source::{whole_chars, Item, Source}; -/// How much of an item the view renders: whole, its summary, its pointer, or inside its -/// source's one fold block with the rest of the oldest run. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Level { - Full, - Summary, - Pointer, - Folded, -} +pub(super) use crate::levels::Level; /// How much of an item a level shows, for comparing two levels of one item. pub(super) fn rank(level: &Level) -> u8 { diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 86905e2da0..0915573e2f 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -563,3 +563,32 @@ fn an_act_appends_one_result_and_neither_turns_over_nor_grows_the_floor() -> Res assert!(!view.start_would_restore(&[&actions], |_| vec![grant])?, "the same grant restores nothing"); Ok(()) } + +// what this catches: a receipt that cannot say which occurrence she was shown, or at what level, +// or in what order (the acknowledgement of a task's end reads exactly this, HER-TASKS; the +// allocator reads it to learn what a grant bought). +#[test] +fn the_receipt_names_each_shown_occurrence_and_its_level_in_prompt_order() -> Result<(), GrantMismatch> { + let mut results = Fake::new("results", 1); + results.push("r1", &"a".repeat(3_000)); + results.push("r2", "two"); + let (mut view, _) = View::start(Vec::new(), &[&results as &dyn Source], |_| vec![100])?; + results.push("r3", "three"); + view.advance(&[&results]); + let receipt = view.receipt(); + let id = |k: &str| Some(ElementId::of(&[k.as_bytes()])); + let shown: Vec<_> = receipt.items.iter().map(|r| (r.element, r.level)).collect(); + assert_eq!(shown[shown.len() - 2..], [(id("r2"), Level::Full), (id("r3"), Level::Full)], "{shown:?}"); + match shown[0] { + (element, Level::Pointer) => assert_eq!(element, id("r1")), + (None, Level::Folded) => {} + other => panic!("the oldest, too large for the grant, is not whole: {other:?}"), + } + assert_eq!(receipt.epoch, view.epoch_id()); + assert_eq!(receipt.items.iter().map(|r| r.chars).sum::(), view.chars(), "the receipt accounts for every block after the head"); + assert_eq!(view.take_submitted(), None, "nothing was sent yet"); + view.sent(); + assert_eq!(view.take_submitted(), Some(receipt), "the sent prompt's receipt, taken once"); + assert_eq!(view.take_submitted(), None); + Ok(()) +} From d94939b24c230df623a6e7591950216b9833b49a Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 01:09:56 -0500 Subject: [PATCH 22/88] WM slice: no retirement by order (Codex on #5637). A finished dispatch stays until the submitted render receipt acknowledges it; an act recorded later proves nothing about an optional source being sent. retire_perceived_dispatches is deleted; the 16-handle cap stays gone Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/working_memory.rs | 2 +- .../src/cognition/working_memory/ledger.rs | 5 +---- .../cognition/working_memory/perception.rs | 16 +++------------- .../cognition/working_memory/tests/actions.rs | 19 ++++++++----------- 4 files changed, 13 insertions(+), 29 deletions(-) diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 4db6a404ad..3df55a262d 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -251,7 +251,7 @@ pub struct WorkingMemory { /// SAME recency channel as `last_action`, but keyed so concurrent sentinels/compiles/ /// debuggers stream in without clobbering each other. Fed by the completion/progress /// listener (`record_dispatch_event`); surfaced by the faculty so the mind perceives - /// "what I sent away, and where it's at" each heartbeat. A finished handle retires once she has answered a prompt that showed its end. + /// "what I sent away, and where it's at" each heartbeat. A finished handle stays until a submitted render receipt shows its end reached her. dispatched: Mutex>, /// Monotonic stamp applied to ACTION entries. Two reasons: (1) it makes each /// recorded action a DISTINCT string even when the persona repeats the identical diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 890bf869f2..a6c4f54e54 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -301,10 +301,7 @@ impl WorkingMemory { // The record and the active slot publish together, so a concurrent publisher // cannot prune a not-yet-visible receipt. let mut actions = self.actions.lock(); - let previous = self.last_action.lock().replace((seq, a.to_string())); - if let Some((answered_since, _)) = previous { - self.retire_perceived_dispatches(answered_since); - } + *self.last_action.lock() = Some((seq, a.to_string())); actions.push( action_log::ActionRecord { seq, diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 9723b13fef..8db4716ce0 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -348,8 +348,9 @@ impl WorkingMemory { /// `Done`/`Failed` marks it. The mind perceives outstanding + freshly-finished handles /// via the faculty next heartbeat, so it can act on a result the moment it lands /// without ever blocking. `label` is set once (first event) and preserved across - /// updates. A finished handle retires once she has answered a prompt that showed its end - /// ([`Self::retire_perceived_dispatches`]); a running one never does + /// updates. A finished handle stays until a submitted render receipt shows its end reached + /// her (HER-TASKS' acknowledge point, the render receipt in progress); until that exists + /// nothing retires one, so an end she has not perceived is never dropped (Codex on #5637) /// ([[act-results-need-a-recency-channel-not-semantic-recall]]). pub fn record_dispatch_event( &self, @@ -371,17 +372,6 @@ impl WorkingMemory { entry.seq = seq; } - /// Retire every finished handle whose end she has perceived: one whose terminal event is - /// older than `answered_since`, the sequence of an act recorded before the act now being - /// recorded. That act's prompt was built after it, and her view renders every dispatched - /// handle, so the end was in a prompt she answered. Acts and dispatch events share one - /// sequence, so this is an ordering, never a count; a running handle never retires. - pub(super) fn retire_perceived_dispatches(&self, answered_since: u64) { - self.dispatched - .lock() - .retain(|_, action| action.status == DispatchStatus::Running || action.seq >= answered_since); - } - /// The label of a dispatched handle THIS persona owns, or `None` if the handle isn't /// ours (never dispatched here, or already evicted). The async-dispatch listener uses /// it to claim ONLY its own completions off the shared `command:completed` bus — other diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index d5e6f3db96..1970810ef4 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -177,25 +177,22 @@ async fn dispatched_commands_stream_back_by_handle() { ); } -// what this catches: a finished background handle held forever (the old 16-handle cap only -// evicted past a count) or dropped before she could see how it ended. It retires once she has -// answered a prompt built after its end (an act recorded after the act that followed it); a -// running handle never retires, however many acts pass. +// what this catches: a finished background handle dropped before a submitted prompt showed her +// its end. An act recorded later proves nothing about an optional source being allocated (Codex +// on #5637), so nothing retires a handle until the render receipt acknowledges it: the old +// 16-handle count evicted finished ends she may never have seen. #[test] -fn a_finished_dispatch_retires_once_she_has_answered_a_prompt_that_showed_its_end() { +fn a_finished_dispatch_stays_until_a_receipt_acknowledges_it() { let wm = WorkingMemory::new(8); let (compile, sentinel) = (Uuid::from_u128(1), Uuid::from_u128(2)); wm.record_dispatch_event(sentinel, "research task", "searching…", DispatchStatus::Running); wm.record_dispatch_event(compile, "compile core", "0 errors", DispatchStatus::Done); - let handles = |wm: &WorkingMemory| wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect::>(); - wm.record_receipt("an act whose prompt may predate the compile's end"); - assert_eq!(handles(&wm).len(), 2, "the next act's prompt may not have shown it yet"); - wm.record_receipt("an act whose prompt was built after the compile ended"); - assert_eq!(handles(&wm), vec![sentinel], "its end was in a prompt she answered"); for _ in 0..20 { wm.record_receipt("more acts"); } - assert_eq!(handles(&wm), vec![sentinel], "a running handle never retires"); + let mut handles: Vec = wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect(); + handles.sort(); + assert_eq!(handles, vec![compile, sentinel], "acts alone never retire a finished end, and a running one stays"); } // what this catches: record/recent round-trips, blank reasoning is ignored, and From 217110087ad2052e47a6bebafedc0cf52b5dc5b0 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:21:29 -0500 Subject: [PATCH 23/88] render receipt: Level gets its own module (levels.rs untouched); the sink is installed per mind in render_receipt (the faculty file untouched); a fork never delivers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/llm_deliberation_faculty.rs | 9 -------- .../llm_deliberation_faculty/request.rs | 11 ++++++---- .../src/cognition/render_receipt.rs | 21 +++++++++++++++++-- core/continuum-context/src/epoch.rs | 8 +++---- core/continuum-context/src/level.rs | 12 +++++++++++ core/continuum-context/src/levels.rs | 12 ----------- core/continuum-context/src/lib.rs | 2 ++ core/continuum-context/src/view.rs | 2 +- core/continuum-context/src/view/allot.rs | 2 +- 9 files changed, 46 insertions(+), 33 deletions(-) create mode 100644 core/continuum-context/src/level.rs diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index c9c559661a..9d6a932a44 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -236,8 +236,6 @@ pub struct LlmDeliberationFaculty { pub working_set: Option, /// Her context view across acts (`prompt/epoch.rs`): one epoch that only appends, turned /// over when it outgrows her history's grant. - /// Where her render receipts go (`crate::cognition::render_receipt`); `None` drops them. - receipt_sink: Option>, context_view: parking_lot::Mutex< Option>, >, @@ -274,7 +272,6 @@ impl LlmDeliberationFaculty { genome: empty_genome(), decoding: relaxed_decoding(), working_set: None, - receipt_sink: None, context_view: parking_lot::Mutex::new(None), tools_epoch: parking_lot::Mutex::new(None), forked: false, @@ -356,12 +353,6 @@ impl LlmDeliberationFaculty { /// browses, and the model loads any one tool's schema on demand via /// `commands/help`. An emitted call becomes a [`Decision::Act`] verdict the /// act→observe driver runs (the faculty itself never executes). - /// Install the one sink her render receipts go to (the task ledger, #5585). - pub fn with_receipt_sink(mut self, sink: Arc) -> Self { - self.receipt_sink = Some(sink); - self - } - pub fn with_tools(mut self, tools: Vec) -> Self { self.tools = tools; self.rebuild_tool_surface(); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 4b5a76cf96..08c70ed9be 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -84,8 +84,6 @@ impl LlmDeliberationFaculty { /// (`slots::PageKey::Fork`). Set only by `fork_eval_cycle`. pub fn forked(mut self) -> Self { self.forked = true; - // A fork's prompts are not hers: they never acknowledge what she was shown. - self.receipt_sink = None; self } @@ -302,8 +300,13 @@ impl LlmDeliberationFaculty { // window reads: in the window it was served in, whether or not her turn settles soon. if matches!(receipt.outcome, crate::ai::provenance::GenerationOutcome::Served { .. }) { crate::cognition::resident_service::note_generation(self.persona_id); - if let (Some(view), Some(sink)) = (submitted, self.receipt_sink.as_ref()) { - sink.record(crate::cognition::render_receipt::RenderReceipt { owner: self.persona_id, request: receipted_request, view }); + // A measurement fork's prompts are not hers: they never acknowledge what she was shown. + if let (Some(view), false) = (submitted, self.forked) { + crate::cognition::render_receipt::deliver(crate::cognition::render_receipt::RenderReceipt { + owner: self.persona_id, + request: receipted_request, + view, + }); } } receipts.push( diff --git a/core/continuum-cognition/src/cognition/render_receipt.rs b/core/continuum-cognition/src/cognition/render_receipt.rs index 291a0de59d..0d1937b8e6 100644 --- a/core/continuum-cognition/src/cognition/render_receipt.rs +++ b/core/continuum-cognition/src/cognition/render_receipt.rs @@ -16,8 +16,25 @@ pub struct RenderReceipt { pub view: continuum_context::view::Receipt, } -/// Where render receipts go. One per mind, installed at assembly; none installed, a receipt is -/// dropped (nothing consumes it yet). +/// Where render receipts go. One per mind, installed at assembly ([`install`]); none installed, +/// a receipt is dropped (nothing consumes it yet). pub trait RenderReceiptSink: Send + Sync { fn record(&self, receipt: RenderReceipt); } + +static SINKS: parking_lot::RwLock>>> = + parking_lot::RwLock::new(None); + +/// Install the one sink `owner`'s receipts go to (the task ledger, #5585). A second install for +/// the same mind replaces the first. +pub fn install(owner: Uuid, sink: std::sync::Arc) { + SINKS.write().get_or_insert_with(Default::default).insert(owner, sink); +} + +/// Hand a served prompt's receipt to its owner's sink, if one is installed. +pub(crate) fn deliver(receipt: RenderReceipt) { + let sink = SINKS.read().as_ref().and_then(|sinks| sinks.get(&receipt.owner).cloned()); + if let Some(sink) = sink { + sink.record(receipt); + } +} diff --git a/core/continuum-context/src/epoch.rs b/core/continuum-context/src/epoch.rs index 401fb7472a..8adde1c381 100644 --- a/core/continuum-context/src/epoch.rs +++ b/core/continuum-context/src/epoch.rs @@ -38,7 +38,7 @@ pub struct Event { /// which stands for a range of items. pub element: Option, /// The level the view rendered it at: what a render receipt reports she was shown. - pub level: crate::levels::Level, + pub level: crate::level::Level, pub version: u32, pub text: T, /// The source ended with this notice; turnover drops it entirely. @@ -82,7 +82,7 @@ impl Epoch { /// Record a source's current rendering. Appends only when it differs from that source's /// latest version; never edits an earlier block. - pub fn observe(&mut self, source: SourceId, element: Option, level: crate::levels::Level, text: T) -> Observed { + pub fn observe(&mut self, source: SourceId, element: Option, level: crate::level::Level, text: T) -> Observed { let latest = self.events.iter().rposition(|e| e.source == source); if let Some(i) = latest { if self.events[i].text == text { @@ -108,7 +108,7 @@ impl Epoch { } self.superseded_chars += self.events[i].text.chars(); let (element, version) = (self.events[i].element, self.events[i].version + 1); - self.events.push(Event { source, element, level: crate::levels::Level::Pointer, version, text: notice, retired: true }); + self.events.push(Event { source, element, level: crate::level::Level::Pointer, version, text: notice, retired: true }); Observed::Appended { version } } @@ -155,7 +155,7 @@ impl Epoch { mod tests { /// A test block: whole, standing for no particular occurrence. fn seen(e: &mut Epoch, source: SourceId, text: String) -> Observed { - e.observe(source, None, crate::levels::Level::Full, text) + e.observe(source, None, crate::level::Level::Full, text) } use super::*; diff --git a/core/continuum-context/src/level.rs b/core/continuum-context/src/level.rs new file mode 100644 index 0000000000..b802fd3387 --- /dev/null +++ b/core/continuum-context/src/level.rs @@ -0,0 +1,12 @@ +//! How much of an item the view renders. The view decides it; the epoch records it on each block, +//! so a render receipt says what she was actually shown. + +/// Whole, its summary, its pointer, or inside its source's one fold block with the rest of the +/// oldest run. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum Level { + Full, + Summary, + Pointer, + Folded, +} diff --git a/core/continuum-context/src/levels.rs b/core/continuum-context/src/levels.rs index 701dff3a32..7a221f20e0 100644 --- a/core/continuum-context/src/levels.rs +++ b/core/continuum-context/src/levels.rs @@ -131,17 +131,6 @@ fn head(full: &str, budget: usize) -> Option { (kept > 0 && more > 0).then(|| format!("{}\n… and {more} more (expand to read them)", lines[..kept].join("\n"))) } -/// How much of an item the view renders: whole, its summary, its pointer, or inside its -/// source's one fold block with the rest of the oldest run. The view decides it; the epoch -/// records it on each block, so a render receipt says what she was actually shown. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] -pub enum Level { - Full, - Summary, - Pointer, - Folded, -} - #[cfg(test)] mod tests { use super::*; @@ -196,4 +185,3 @@ mod tests { assert_eq!(summarize("one\ntwo\n", Shape::List), None); } } - diff --git a/core/continuum-context/src/lib.rs b/core/continuum-context/src/lib.rs index a4e61ea425..d22b6382dd 100644 --- a/core/continuum-context/src/lib.rs +++ b/core/continuum-context/src/lib.rs @@ -4,12 +4,14 @@ //! - [`cause`]: what each element follows from: its occurrence id, its cause, its content. //! - [`epoch`]: a stable head, then keyed blocks that only append. //! - [`source`]: what a context source offers: its current items, each under a stable key. +//! - [`level`]: how much of an item the view rendered (whole, summary, pointer, folded). //! - [`levels`]: each item's summary level, generated from its shape (mipmaps for context). //! - [`motion`]: how each source moves between epoch starts, which orders the next start. //! - [`view`]: one mind's epoch fed by its sources; turnover is the only rewrite. pub mod cause; pub mod epoch; +pub mod level; pub mod levels; pub mod motion; pub mod source; diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index d20cd0d192..d3d47bf858 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -21,7 +21,7 @@ use crate::source::{Item, Source}; mod allot; use allot::{allot, rank}; -pub use crate::levels::Level; +pub use crate::level::Level; pub use allot::floor; /// The item key a source's fold block is observed under: no source keys an item with it. diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs index 1733a05edf..42ac556d15 100644 --- a/core/continuum-context/src/view/allot.rs +++ b/core/continuum-context/src/view/allot.rs @@ -9,7 +9,7 @@ use crate::epoch::Block; use crate::source::{whole_chars, Item, Source}; -pub(super) use crate::levels::Level; +pub(super) use crate::level::Level; /// How much of an item a level shows, for comparing two levels of one item. pub(super) fn rank(level: &Level) -> u8 { From 2f003160cef298076c77b3d3e428ca652f84b05c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:26:44 -0500 Subject: [PATCH 24/88] Epoch::observe: identical bytes that now stand for another occurrence or level update the block in place (no append), so the receipt never reports stale evidence (Codex on #5639) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-context/src/epoch.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/core/continuum-context/src/epoch.rs b/core/continuum-context/src/epoch.rs index 8adde1c381..1f5314e52f 100644 --- a/core/continuum-context/src/epoch.rs +++ b/core/continuum-context/src/epoch.rs @@ -86,6 +86,13 @@ impl Epoch { let latest = self.events.iter().rposition(|e| e.source == source); if let Some(i) = latest { if self.events[i].text == text { + // The same bytes now stand for another occurrence or level (a short item whose + // pointer is itself, a re-read of unchanged content): the prompt is unchanged, so + // nothing appends, but what the block IS updates in place, or a receipt would + // report the old occurrence or level (Codex on #5639). + let event = &mut self.events[i]; + event.element = element; + event.level = level; return Observed::Unchanged; } self.superseded_chars += self.events[i].text.chars(); @@ -153,6 +160,22 @@ impl Epoch { #[cfg(test)] mod tests { + // what this catches: a receipt reporting stale evidence when identical bytes change meaning: + // a block first shown as a pointer whose whole is the same bytes, or a re-read of unchanged + // content by a new occurrence (Codex on #5639). The prompt must not grow; the metadata must. + #[test] + fn identical_bytes_with_a_new_level_or_occurrence_update_the_block_without_appending() { + use crate::cause::ElementId; + use crate::level::Level; + let mut e = Epoch::::new(1, Vec::new()); + let (first, second) = (ElementId::of(&[b"read 1"]), ElementId::of(&[b"read 2"])); + assert_eq!(e.observe(src("open-views/a.rs"), Some(first), Level::Pointer, "a.rs: 3 lines".into()), Observed::Appended { version: 0 }); + assert_eq!(e.observe(src("open-views/a.rs"), Some(first), Level::Full, "a.rs: 3 lines".into()), Observed::Unchanged); + assert_eq!((e.events().len(), e.events()[0].level), (1, Level::Full), "same bytes, now its whole"); + assert_eq!(e.observe(src("open-views/a.rs"), Some(second), Level::Full, "a.rs: 3 lines".into()), Observed::Unchanged); + assert_eq!((e.events().len(), e.events()[0].element), (1, Some(second)), "same bytes, now the newer occurrence"); + } + /// A test block: whole, standing for no particular occurrence. fn seen(e: &mut Epoch, source: SourceId, text: String) -> Observed { e.observe(source, None, crate::level::Level::Full, text) From 70352f5e631d4a67fb2c479135a307fb8f7c7b64 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:29:04 -0500 Subject: [PATCH 25/88] Her tasks are their own view source: one leveled item per task, keyed by handle, its terminal state its own occurrence (HER-TASKS) WIP on #5637; rebases onto Cormac's 4ee623ad, then removes the dispatched line from thoughts.rs and deletes render_dispatched in this same change (never zero copies, never two). - context_streams/tasks.rs: `task_element(persona, task, status)` is the one mapping from a task's state to its occurrence (the ledger, #5585, reads receipts with it); whole = line 1 + output, summary = levels::summarize(Output) under line 1, pointer = line 1. Line 1 at every level, so any level acknowledges the end. - Producer::Task; MemoryStreams.tasks; her view lists tasks after her actions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/mod.rs | 4 + .../src/cognition/context_streams/tasks.rs | 93 +++++++++++++++++++ .../llm_deliberation_faculty/prompt/epoch.rs | 1 + 3 files changed, 98 insertions(+) create mode 100644 core/continuum-cognition/src/cognition/context_streams/tasks.rs diff --git a/core/continuum-cognition/src/cognition/context_streams/mod.rs b/core/continuum-cognition/src/cognition/context_streams/mod.rs index 850cf4fa4f..820f511c59 100644 --- a/core/continuum-cognition/src/cognition/context_streams/mod.rs +++ b/core/continuum-cognition/src/cognition/context_streams/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod blocks; pub(crate) mod conversation; pub(crate) mod notices; pub(crate) mod open_views; +pub(crate) mod tasks; pub(crate) mod thoughts; use continuum_context::epoch::Block; @@ -31,6 +32,7 @@ pub(crate) enum Producer { Thought, Notice, Standing, + Task, } /// An occurrence's id from its producer's own stable identity: whose (`persona`), which producer, @@ -51,6 +53,7 @@ pub(crate) fn standing(persona: uuid::Uuid, source: &str, key: &str, message: Co pub(crate) struct MemoryStreams<'a> { pub actions: actions::Actions<'a>, pub thoughts: thoughts::Thoughts<'a>, + pub tasks: tasks::Tasks<'a>, pub open_views: open_views::OpenViews<'a>, pub notices: notices::Notices<'a>, } @@ -60,6 +63,7 @@ impl<'a> MemoryStreams<'a> { Self { actions: actions::Actions { memory, persona }, thoughts: thoughts::Thoughts { memory, persona }, + tasks: tasks::Tasks { memory, persona }, open_views: open_views::OpenViews { memory, persona }, notices: notices::Notices { memory, persona }, } diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs new file mode 100644 index 0000000000..0b94ff9ea5 --- /dev/null +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -0,0 +1,93 @@ +//! Her tasks: one item per piece of work she sent away (a shell command handed back, a background +//! dispatch), keyed by its handle (HER-TASKS; HER-TOOLS, "One rendering"). Every level keeps the +//! task's line 1 (how it stands), so the first receipt that shows the item at ANY level +//! acknowledges its end; the output is the body, which the view sizes like any other item. + +use continuum_context::cause::{Cause, ElementId, Origin}; +use continuum_context::levels::{summarize, Shape}; +use continuum_context::source::{Item, Source}; + +use super::{element, priority, ContextMessage, Producer}; +use crate::cognition::working_memory::{DispatchStatus, WorkingMemory}; + +/// The one mapping from a task's state to the occurrence her view renders and a render receipt +/// names: a task's terminal state is its own occurrence, so acknowledging an end never matches the +/// running line that came before it. The task ledger (#5585) calls this to read a receipt. +pub(crate) fn task_element(persona: uuid::Uuid, task: uuid::Uuid, status: &DispatchStatus) -> ElementId { + let state = match status { + DispatchStatus::Running => 0u8, + DispatchStatus::Done => 1, + DispatchStatus::Failed => 2, + }; + element(persona, Producer::Task, &[task.as_bytes().as_slice(), &[state]].concat()) +} + +pub(crate) struct Tasks<'a> { + pub memory: &'a WorkingMemory, + pub persona: uuid::Uuid, +} + +impl Source for Tasks<'_> { + fn name(&self) -> &str { + "tasks" + } + + fn priority(&self) -> u8 { + priority::ACTIONS + } + + fn items(&self) -> Vec> { + let tasks = self.memory.dispatched_snapshot(); + if tasks.is_empty() { + return Vec::new(); + } + let banner = super::standing( + self.persona, + "tasks", + "banner", + ContextMessage::user("[tasks] Work I sent away, by handle: each says how it stands; its end is delivered to me.".to_owned()), + ); + let mut items = vec![banner]; + items.extend(tasks.into_iter().map(|(task, label, output, status)| { + let word = match status { + DispatchStatus::Running => "running", + DispatchStatus::Done => "ok", + DispatchStatus::Failed => "failed", + }; + let line = format!("{word} task {} {label}", airc_core::shown_id::shown_form(task)); + let whole = if output.is_empty() { line.clone() } else { format!("{line}\n{output}") }; + let summary = summarize(&output, Shape::Output).map(|level| ContextMessage::user(format!("{line}\n{level}"))); + Item::whole(task_element(self.persona, task, &status), Cause::Root(Origin::ActivityStart), task.to_string(), ContextMessage::user(whole)) + .with_summary(summary) + .with_pointer(ContextMessage::user(line)) + })); + items + } +} + +#[cfg(test)] +mod tests { + use super::*; + use continuum_context::epoch::Block; + + // what this catches: a task's end that a receipt cannot name (the terminal state sharing the + // running line's occurrence), or a level that drops how the task ended (Codex on #5639: the + // ledger acknowledges from the first receipt listing the terminal element at any level). + #[test] + fn a_finished_task_is_its_own_occurrence_and_every_level_says_how_it_ended() { + let memory = WorkingMemory::new(8); + let persona = uuid::Uuid::from_u128(7); + let task = uuid::Uuid::from_u128(42); + memory.record_dispatch_event(task, "bash: cargo test", "running", DispatchStatus::Running); + let running = Tasks { memory: &memory, persona }.items(); + let log: String = (1..=400).map(|n| format!("test case {n} ... ok\n")).collect(); + memory.record_dispatch_event(task, "bash: cargo test", &format!("exit 101\n{log}error: 1 failed"), DispatchStatus::Failed); + let ended = Tasks { memory: &memory, persona }.items(); + assert_ne!(running[1].id(), ended[1].id(), "the end is its own occurrence"); + assert_eq!(ended[1].id(), task_element(persona, task, &DispatchStatus::Failed), "the one mapping names it"); + let starts_failed = |m: &ContextMessage| m.text().starts_with("failed task "); + assert!(starts_failed(ended[1].full())); + assert!(ended[1].summary().is_some_and(starts_failed), "the summary keeps line 1"); + assert!(ended[1].pointer().is_some_and(starts_failed), "the pointer is line 1"); + } +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs index b85529c3b8..4b1489f6ab 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs @@ -395,6 +395,7 @@ impl LlmDeliberationFaculty { let mut sources: Vec<&dyn Source> = streams.blocks.iter().filter(settled).map(as_source).collect(); sources.extend(memory.map(|m| &m.actions as &dyn Source)); + sources.extend(memory.map(|m| &m.tasks as &dyn Source)); sources.push(&streams.conversation); sources.extend(streams.blocks.iter().filter(|block| !settled(block)).map(as_source)); sources.extend(memory.map(|m| &m.thoughts as &dyn Source)); From e31cd5beb3a117b55c9e5fb80e1db62a7922b1ca Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:34:28 -0500 Subject: [PATCH 26/88] tasks ride with the sources that change within an epoch (after thoughts, where dispatched rendered), not with the settled front; the source-order pin names them Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/llm_deliberation_faculty/prompt/epoch.rs | 4 +++- .../cognition/llm_deliberation_faculty/prompt/epoch/tests.rs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs index 4b1489f6ab..cea84a3672 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs @@ -395,10 +395,12 @@ impl LlmDeliberationFaculty { let mut sources: Vec<&dyn Source> = streams.blocks.iter().filter(settled).map(as_source).collect(); sources.extend(memory.map(|m| &m.actions as &dyn Source)); - sources.extend(memory.map(|m| &m.tasks as &dyn Source)); sources.push(&streams.conversation); sources.extend(streams.blocks.iter().filter(|block| !settled(block)).map(as_source)); sources.extend(memory.map(|m| &m.thoughts as &dyn Source)); + // A task's state changes within an epoch (running, then its end), so it rides with the + // sources that change, where her dispatched list rendered before. + sources.extend(memory.map(|m| &m.tasks as &dyn Source)); sources.extend(memory.map(|m| &m.open_views as &dyn Source)); sources.extend(memory.map(|m| &m.notices as &dyn Source)); sources diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs index ae1a40adef..0fc576de3f 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs @@ -102,7 +102,7 @@ fn consecutive_acts_share_the_whole_view_and_a_turnover_keeps_the_settled_front( LlmDeliberationFaculty::view_sources(&now, Some(&memory_streams)).iter().map(|s| s.name()).collect(); assert_eq!( names, - ["workspace-map", "actions", "conversation", "room-kanban", "recall", "thoughts", "open-views", "notices"], + ["workspace-map", "actions", "conversation", "room-kanban", "recall", "thoughts", "tasks", "open-views", "notices"], "settled blocks, then her actions and conversation, then what counts or changes within an epoch" ); From a1f5fe85be27fcdd4cd9c2b555ca3c9c984acb9a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:38:59 -0500 Subject: [PATCH 27/88] Cover refused render read batches and shutdown delivery retention --- .../tests/task_consumption.rs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 7b18ae6257..d35c6cb063 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -231,3 +231,61 @@ async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( assert!(restored.pending_task_wakes().is_empty()); Ok(()) } + +#[tokio::test] +async fn rejected_read_batch_cannot_partially_retire_a_durable_wake( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.record_task_reads(owner, memory.incarnation(), &[task, Uuid::new_v4()]), + Err(TaskConsumptionError::Receipt(_)) + )); + assert_eq!(std::fs::read(&path)?, before); + // An unrelated later checkpoint must not publish a partial staging from the + // refused batch. Checking only the immediate wake would miss that failure. + for (_, result) in registry.flush_volatile_all() { + result?; + } + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} + +#[tokio::test] +async fn served_read_arriving_after_shutdown_preserves_restart_delivery( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + for (_, result) in registry.stop_volatile_checkpoints() { + result?; + } + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.record_task_reads(owner, memory.incarnation(), &[task]), + Err(TaskConsumptionError::Stopped) + )); + assert_eq!(std::fs::read(&path)?, before); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} From 1d46580f7c9c60a9fd19df2f08e21b517ff19ed6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 01:46:20 -0500 Subject: [PATCH 28/88] Return submitted render receipts through the owned workspace result --- .../src/cognition/llm_deliberation_faculty.rs | 6 +++-- .../llm_deliberation_faculty/request.rs | 3 ++- .../tests/verdicts/window_feedback.rs | 10 ++++++++ .../verdict/contribute.rs | 3 ++- .../src/cognition/render_receipt.rs | 25 +------------------ .../src/cognition/workspace/cause.rs | 4 +++ .../src/cognition/workspace/edit.rs | 6 +++++ .../src/cognition/workspace/tests.rs | 10 ++++++++ .../cognition/workspace/workspace_cycle_2.rs | 4 +++ .../src/cognition/workspace_capture.rs | 2 ++ 10 files changed, 45 insertions(+), 28 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 9d6a932a44..8a61ff8088 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -560,15 +560,17 @@ impl Faculty for LlmDeliberationFaculty { async fn contribute(&self, ws: &Workspace) -> Option { let mut receipts = Vec::new(); - let contribution = self.contribute_with_receipts(ws, &mut receipts).await; + let mut rendered = Vec::new(); + let contribution = self.contribute_with_receipts(ws, &mut receipts, &mut rendered).await; let mut contribution = match contribution { Some(contribution) => contribution, - None if receipts.is_empty() => return None, + None if receipts.is_empty() && rendered.is_empty() => return None, // A corrective retry may yield before dispatch. Keep its earlier // attempt's evidence without inventing a decision or another call. None => Contribution::context(FacultyId::Deliberation, "", 0.0, ""), }; contribution.receipts = receipts; + contribution.render_receipts = rendered; Some(contribution) } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 248f392739..fe0b32e79e 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -130,6 +130,7 @@ impl LlmDeliberationFaculty { // The allocation her prompt was fitted under: the receipt carries it with the capture. allocation: Option, receipts: &mut Vec, + rendered: &mut Vec, ) -> Option> { // Identity belongs to the submitted adapter request. Provider response IDs // remain separate, and one workspace can issue several calls. @@ -304,7 +305,7 @@ impl LlmDeliberationFaculty { if let (Some(view), false, Some(memory)) = (submitted, self.forked, self.working_memory.as_ref()) { - crate::cognition::render_receipt::deliver(crate::cognition::render_receipt::RenderReceipt { + rendered.push(crate::cognition::render_receipt::RenderReceipt { owner: self.persona_id, incarnation: memory.incarnation(), request: receipted_request, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs index 480078dab8..4eb4c1c3d1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs @@ -311,6 +311,15 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { < LlmDeliberationFaculty::messages_cost(&pair[0].messages)); } assert_eq!(outcome.receipts.len(), seen.len()); + let served: Vec<_> = outcome.receipts.iter().filter(|receipt| { + matches!(receipt.outcome, crate::ai::provenance::GenerationOutcome::Served { .. }) + }).collect(); + assert_eq!(outcome.render_receipts.len(), served.len()); + for (rendered, generation) in outcome.render_receipts.iter().zip(served) { + assert_eq!(rendered.owner, persona); + assert_eq!(rendered.incarnation, wm.incarnation()); + assert_eq!(rendered.request, generation.submitted_request_id); + } for (receipt, request) in outcome.receipts.iter().zip(seen.iter()) { assert_eq!( Some(&receipt.submitted_request_id), @@ -428,6 +437,7 @@ async fn provider_context_feedback_faults_when_required_input_cannot_fit() { let outcome = faculty.contribute(&ws).await.expect("fault contribution"); assert!(outcome.fault.is_none()); assert!(outcome.capacity_refusal.is_some()); + assert!(outcome.render_receipts.is_empty(), "a refused prompt cannot retire task ends"); assert_eq!( outcome.receipts.len(), 1, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index 0d463e74ad..2f19d771f7 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -5,6 +5,7 @@ impl LlmDeliberationFaculty { &self, ws: &Workspace, receipts: &mut Vec, + rendered: &mut Vec, ) -> Option { // ONE atomic snapshot of the model binding for the whole turn — the // adapter we generate through, the model we request, and the served window @@ -307,7 +308,7 @@ impl LlmDeliberationFaculty { // previous value is also what keeps the initializer honest). sent_allowance = request.max_tokens.or(sent_allowance); let result = self - .generate_for_workspace(ws, &binding, fit_window, request, view.allocation.clone(), receipts) + .generate_for_workspace(ws, &binding, fit_window, request, view.allocation.clone(), receipts, rendered) .await?; gen_await_ms = gen_await_ms.saturating_add(started.elapsed().as_millis() as u64); match result { diff --git a/core/continuum-cognition/src/cognition/render_receipt.rs b/core/continuum-cognition/src/cognition/render_receipt.rs index 8675714131..4688f77a80 100644 --- a/core/continuum-cognition/src/cognition/render_receipt.rs +++ b/core/continuum-cognition/src/cognition/render_receipt.rs @@ -1,6 +1,6 @@ //! The render receipt: what one submitted prompt showed her, bound to whose mind it was and //! which request carried it (HER-TOOLS, "The render receipt"). The view takes its half when the -//! prompt is sent (`View::sent`); the deliberation faculty binds it and hands it to the one sink +//! prompt is sent (`View::sent`); the deliberation faculty returns it with its contribution //! where the request was served, so a prompt the engine never accepted is never receipted. //! The task ledger (#5585) is the sink: it acknowledges a task's end from the first receipt that //! shows that task's item, and writes nothing else. The memory incarnation joins the binding @@ -18,26 +18,3 @@ pub struct RenderReceipt { pub request: String, pub view: continuum_context::view::Receipt, } - -/// Where render receipts go. One per mind, installed at assembly ([`install`]); none installed, -/// a receipt is dropped (nothing consumes it yet). -pub trait RenderReceiptSink: Send + Sync { - fn record(&self, receipt: RenderReceipt); -} - -static SINKS: parking_lot::RwLock>>> = - parking_lot::RwLock::new(None); - -/// Install the one sink `owner`'s receipts go to (the task ledger, #5585). A second install for -/// the same mind replaces the first. -pub fn install(owner: Uuid, sink: std::sync::Arc) { - SINKS.write().get_or_insert_with(Default::default).insert(owner, sink); -} - -/// Hand a served prompt's receipt to its owner's sink, if one is installed. -pub(crate) fn deliver(receipt: RenderReceipt) { - let sink = SINKS.read().as_ref().and_then(|sinks| sinks.get(&receipt.owner).cloned()); - if let Some(sink) = sink { - sink.record(receipt); - } -} diff --git a/core/continuum-cognition/src/cognition/workspace/cause.rs b/core/continuum-cognition/src/cognition/workspace/cause.rs index d5e1a6040b..fd21c26422 100644 --- a/core/continuum-cognition/src/cognition/workspace/cause.rs +++ b/core/continuum-cognition/src/cognition/workspace/cause.rs @@ -388,6 +388,9 @@ pub struct Workspace { /// earned a place in the prompt is a judgement about relevance. Populated from /// the same `all_bids` full-competition set the capture sink records. pub receipts: Vec, + /// Submitted render facts from all bids, including bids omitted by attention. + /// The resident owner must persist consumption before retiring a task wake. + pub render_receipts: Vec, /// Is this a SELF-INITIATED turn — the never-stop heartbeat pursuing the /// persona's own thread with no inbound message — versus a turn driven by an /// arriving message or an examiner's question? Drives the `[Your own time]` @@ -465,6 +468,7 @@ impl Workspace { broadcast: Vec::new(), attention: TurnAttention::Ambient, receipts: Vec::new(), + render_receipts: Vec::new(), self_initiated: false, workspace_deliverable: false, initiative: false, diff --git a/core/continuum-cognition/src/cognition/workspace/edit.rs b/core/continuum-cognition/src/cognition/workspace/edit.rs index ea2990c3eb..9143631e58 100644 --- a/core/continuum-cognition/src/cognition/workspace/edit.rs +++ b/core/continuum-cognition/src/cognition/workspace/edit.rs @@ -308,6 +308,9 @@ pub struct Contribution { /// Neither field can be derived from the other and neither should be removed for /// the other's sake. pub receipts: Vec, + /// Submitted render facts return through the same owned faculty result. + /// They are evidence for the resident checkpoint owner, never an acknowledgement. + pub render_receipts: Vec, /// The model's **verbatim generation** for this verdict — the raw response text /// EXACTLY as the model emitted it, BEFORE the tool-call/PASS parser lifted a /// [`Decision`] from it. Set ONLY by the deliberation faculty on its verdict @@ -411,6 +414,7 @@ impl Contribution { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } @@ -486,6 +490,7 @@ impl Contribution { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } @@ -535,6 +540,7 @@ impl Contribution { fault: Some(error), capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index d11a403d34..cbb8749da2 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -18,6 +18,15 @@ loud.receipts = vec![GenerationReceipt::faulted("req-loud", "served after retry")]; let mut quiet = Contribution::context(FacultyId::WorldModel, "quiet", 0.1, "loses attention"); quiet.receipts = vec![GenerationReceipt::faulted("req-quiet", "lane refused the model")]; + // A previous successful attempt can have rendered before this faculty's + // later attempt faulted. Neither fact may disappear with its losing bid. + let rendered = crate::cognition::render_receipt::RenderReceipt { + owner: uuid::Uuid::new_v4(), + incarnation: uuid::Uuid::new_v4(), + request: "req-quiet-earlier-served".to_owned(), + view: continuum_context::view::Receipt { epoch: 1, items: Vec::new() }, + }; + quiet.render_receipts.push(rendered.clone()); let faculties: Vec> = vec![ Arc::new(FixedFaculty(loud)), @@ -25,6 +34,7 @@ ]; // capacity 1 — one of the two bids MUST be truncated. let ws = cycle(faculties, 1).run("burst").await; + assert_eq!(ws.render_receipts, vec![rendered]); // POSITIVE CONTROL: the truncation really happened. Without this the receipt // assertion below would pass just as well on a cycle that kept both bids, diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs index f9b4860180..d3f653a24a 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs @@ -238,6 +238,10 @@ impl WorkspaceCycle { .iter() .flat_map(|c| c.receipts.iter().cloned()) .collect(); + ws.render_receipts = all_bids + .iter() + .flat_map(|c| c.render_receipts.iter().cloned()) + .collect(); // WHERE THIS TICK'S LATENCY WENT, on the always-on probe stream. // // `timings` already holds per-faculty wall-clock for every faculty across diff --git a/core/continuum-cognition/src/cognition/workspace_capture.rs b/core/continuum-cognition/src/cognition/workspace_capture.rs index 7b80f70ad9..1c614c1159 100644 --- a/core/continuum-cognition/src/cognition/workspace_capture.rs +++ b/core/continuum-cognition/src/cognition/workspace_capture.rs @@ -257,6 +257,7 @@ mod tests { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, parts: Vec::new(), @@ -279,6 +280,7 @@ mod tests { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), // #210: the verbatim generation carries a leading-char fumble the parser // tolerated — the capture must preserve it so model-vs-harness is decidable. raw_generation: Some(" Date: Sat, 31 Oct 2026 01:57:20 -0500 Subject: [PATCH 29/88] Keep truncated generation bodies out of fault summaries --- .../llm_deliberation_faculty/verdict/contribute.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index 2f19d771f7..7b700477b4 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -745,10 +745,10 @@ impl LlmDeliberationFaculty { }; return Some(self.act_verdict(vec![call], &resp, ws.activity_room_id)); } - let head: String = resp.text.chars().take(200).collect(); return Some(Contribution::deliberation_fault(format!( - "the model hit the output limit mid-thought with no committed action (finish_reason Length, {} chars) — a cut thought is not an answer. It began: {head}", - resp.text.len() + "the model hit the output limit mid-thought with no committed action \ + (finish_reason Length, {} bytes, response {}) — a cut thought is not an answer", + resp.text.len(), resp.request_id ))); } From 45aa58a98f90870759e0e33bf467f25a06a9da45 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 02:17:50 -0500 Subject: [PATCH 30/88] Project durable terminal facts through the task source and match rendered receipts --- .../src/cognition/context_streams/tasks.rs | 29 +++++++++++++- .../persona_workspace/task_consumption.rs | 28 +++++++++++++ .../tests/task_consumption.rs | 40 +++++++++++++++++++ .../cognition/working_memory/task_results.rs | 29 ++++++++++++-- .../src/cognition/workspace/tests.rs | 15 ++----- core/continuum-kernel/src/runtime/tasks.rs | 23 +++++++++++ 6 files changed, 147 insertions(+), 17 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs index 3e1627d657..0e4fc67eac 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tasks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -9,6 +9,13 @@ use continuum_context::source::{Item, Source}; use super::{element, priority, ContextMessage, Producer}; use crate::cognition::working_memory::{DispatchStatus, WorkingMemory}; +use continuum_kernel::runtime::tasks::TaskEndState; + +/// A durable end is a different occurrence from a streaming dispatch update. +/// Bind the complete immutable result fingerprint, not just its status label. +pub(crate) fn terminal_element(persona: uuid::Uuid, task: uuid::Uuid, fingerprint: &[u8; 32]) -> ElementId { + element(persona, Producer::Task, &[task.as_bytes().as_slice(), fingerprint.as_slice()].concat()) +} /// The one mapping from a task's state to the occurrence her view renders and a render receipt /// names: a task's terminal state is its own occurrence, so acknowledging an end never matches the @@ -37,8 +44,11 @@ impl Source for Tasks<'_> { } fn items(&self) -> Vec> { - let tasks = self.memory.dispatched_snapshot(); - if tasks.is_empty() { + let terminals = self.memory.task_terminals(); + let terminal_ids: std::collections::BTreeSet<_> = terminals.iter().map(|end| end.task).collect(); + let tasks: Vec<_> = self.memory.dispatched_snapshot().into_iter() + .filter(|(task, ..)| !terminal_ids.contains(task)).collect(); + if tasks.is_empty() && terminals.is_empty() { return Vec::new(); } let banner = super::standing( @@ -61,6 +71,21 @@ impl Source for Tasks<'_> { .with_summary(summary) .with_pointer(ContextMessage::user(line)) })); + items.extend(terminals.into_iter().map(|end| { + let status = match end.state { + TaskEndState::Done => "done", + TaskEndState::Failed => "failed", + TaskEndState::TimedOut => "timed out", + TaskEndState::Stopped => "stopped", + TaskEndState::Lost => "lost", + }; + // This item is the terminal notification, not a projection claiming + // to contain the ledger's output. Its identity binds that exact end. + let line = ContextMessage::user(format!("{status} task {}", end.task)); + Item::whole(terminal_element(self.persona, end.task, &end.fingerprint), + Cause::Root(Origin::ActivityStart), end.task.to_string(), line.clone()) + .with_pointer(line) + })); items } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index e91e7e3eff..70107f45df 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -18,6 +18,34 @@ pub enum TaskConsumptionError { } impl PersonaWorkspaceRegistry { + /// Only a submitted terminal occurrence can retire a wake. Fold blocks and + /// retired entries are not evidence that this end was shown. The checkpoint + /// below rechecks incarnation under admission, so replacement during matching + /// cannot acknowledge the next resident's memory. + pub fn record_rendered_tasks( + &self, + receipt: &crate::cognition::render_receipt::RenderReceipt, + ) -> Result, TaskConsumptionError> { + use continuum_context::level::Level; + let memory = self.cycles.lock().get(&receipt.owner) + .map(|resident| Arc::clone(&resident.working_memory)) + .ok_or(TaskConsumptionError::Absent(receipt.owner))?; + if memory.incarnation() != receipt.incarnation { + return Err(TaskConsumptionError::Replaced(receipt.owner)); + } + let shown: std::collections::BTreeSet<_> = receipt.view.items.iter() + .filter(|item| !item.retired && matches!(item.level, Level::Full | Level::Summary | Level::Pointer)) + .filter_map(|item| item.element).collect(); + let tasks: Vec<_> = memory.task_terminals().into_iter().filter(|end| { + shown.contains(&crate::cognition::context_streams::tasks::terminal_element( + receipt.owner, end.task, &end.fingerprint)) + }).map(|end| end.task).collect(); + if tasks.is_empty() { + return Ok(None); + } + self.record_task_reads(receipt.owner, receipt.incarnation, &tasks).map(Some) + } + /// Success receipts exactly the snapshot containing this end and its wake /// obligation. A replay also checkpoints: a prior insertion may have failed IO. /// Registration/replacement is excluded until the snapshot is committed; the diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index d35c6cb063..f8b75657e3 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -2,6 +2,46 @@ use super::*; use continuum_kernel::runtime::tasks::TaskEnd; +#[tokio::test] +async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( +) -> Result<(), Box> { + use continuum_context::source::Source; + use continuum_context::view::View; + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = PersonaWorkspaceRegistry::new(); + let owner = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let task = Uuid::new_v4(); + registry.consume_task_ends(owner, vec![(task, TaskEnd::TimedOut)])?; + registry.register_from_cfg(cfg_for(owner))?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; + let (view, _) = View::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { + claims.iter().map(|claim| claim.full_chars).collect() + })?; + assert!(view.render().any(|message| message.text.contains("timed out task"))); + let mut receipt = crate::cognition::render_receipt::RenderReceipt { + owner, incarnation: memory.incarnation(), request: "submitted-request".to_owned(), view: view.receipt(), + }; + let exact = receipt.clone(); + for item in &mut receipt.view.items { item.element = None; } + assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + receipt = exact.clone(); + for item in &mut receipt.view.items { item.level = continuum_context::level::Level::Folded; } + assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + receipt = exact.clone(); + for item in &mut receipt.view.items { item.retired = true; } + assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert!(registry.record_rendered_tasks(&exact)?.is_some()); + assert!(memory.pending_task_wakes().is_empty()); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restored.pending_task_wakes().is_empty()); + Ok(()) +} + #[tokio::test] async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( ) -> Result<(), Box> { diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index b79bb7654b..a8a011af41 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -1,7 +1,7 @@ //! Owner consumption state. Notification delivery is not wake admission, and //! neither an in-memory insertion nor this snapshot alone acknowledges the ledger. use super::WorkingMemory; -use continuum_kernel::runtime::tasks::TaskEnd; +use continuum_kernel::runtime::tasks::{TaskEnd, TaskEndState}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; @@ -18,9 +18,18 @@ pub(crate) struct TaskResults { #[derive(Clone, Debug, Serialize, Deserialize)] struct ConsumedEnd { fingerprint: [u8; 32], + state: TaskEndState, wake_pending: bool, } +/// A published terminal fact. The fingerprint identifies the immutable ledger +/// result, including its body; it is not merely the coarse Done/Failed status. +pub(crate) struct TaskTerminal { + pub task: Uuid, + pub fingerprint: [u8; 32], + pub state: TaskEndState, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] #[error("task {task} was already consumed with a different terminal result")] pub struct TaskReceiptConflict { @@ -57,14 +66,14 @@ impl WorkingMemory { let mut incoming = BTreeMap::new(); for (task, end) in ends { let fingerprint: [u8; 32] = Sha256::digest(serde_json::to_vec(&end)?).into(); // Disk boundary: persist integrity fingerprints, not duplicate ledger output. - if let Some(previous) = incoming.insert(task, fingerprint) { + if let Some((previous, _)) = incoming.insert(task, (fingerprint, end.state())) { if previous != fingerprint { return Err(TaskReceiptConflict { task }.into()); } } } let mut results = self.task_results.lock(); - for (task, fingerprint) in &incoming { + for (task, (fingerprint, _)) in &incoming { if let Some(previous) = results.entries.get(task) { if previous.fingerprint != *fingerprint { return Err(TaskReceiptConflict { task: *task }.into()); @@ -72,10 +81,11 @@ impl WorkingMemory { } } let mut changed = false; - for (task, fingerprint) in incoming { + for (task, (fingerprint, state)) in incoming { if let std::collections::btree_map::Entry::Vacant(entry) = results.entries.entry(task) { entry.insert(ConsumedEnd { fingerprint, + state, wake_pending: true, }); changed = true; @@ -103,6 +113,17 @@ impl WorkingMemory { .collect() } + pub(crate) fn task_terminals(&self) -> Vec { + let results = self.task_results.lock(); + results.entries.iter().filter_map(|(task, end)| { + results.published.contains_key(task).then_some(TaskTerminal { + task: *task, + fingerprint: end.fingerprint, + state: end.state, + }) + }).collect() + } + /// Stage retirement only after a successful rendered-context read receipt. /// The wake remains published until the checkpoint containing retirement commits. /// Notification delivery and entering the service loop are not perception. diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index 76a314eefa..314566edf6 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -1,17 +1,10 @@ #![cfg(test)] - // what this catches: PROVENANCE BEING FILTERED BY ATTENTION. Card 0d51573a. - // `ws.broadcast` is the FOCUSED set, so deriving receipts from it would drop the - // generations of any faculty attention dropped (the arbiter cut by a count until card - // c537d687; it forwards every bid now, and receipts must still not depend on it). Astra found that in my first implementation, - // which flat_mapped broadcast; my previous test could not catch it because it - // hand-assembled `ws.broadcast` and never ran the arbiter at all. - // - // THIS TEST DRIVES THE REAL CYCLE so the truncation actually happens. A fault - // receipt from a losing faculty is precisely the record worth keeping — a failed - // call that got truncated away is invisible exactly when someone needs it. + // Every faculty's generation and render evidence returns through the real + // cycle. The arbiter now forwards every bid, so this test does not exercise + // dropped-bid behavior; collection still reads all_bids, not the broadcast. #[tokio::test] - async fn a_losing_faculty_keeps_its_receipt_even_though_attention_dropped_its_bid() { + async fn the_cycle_returns_every_facultys_generation_and_render_receipts() { use crate::ai::provenance::GenerationReceipt; let mut loud = Contribution::context(FacultyId::Recall, "loud", 0.9, "wins attention"); diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 45fd15cb88..67abdd9bfc 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -27,6 +27,29 @@ pub enum TaskEnd { Lost, } +/// The terminal fact without its ledger-owned output. Consumers may project this +/// status but must not equate it with having read the result body. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TaskEndState { + Done, + Failed, + TimedOut, + Stopped, + Lost, +} + +impl TaskEnd { + pub fn state(&self) -> TaskEndState { + match self { + Self::Done(_) => TaskEndState::Done, + Self::Failed { .. } => TaskEndState::Failed, + Self::TimedOut => TaskEndState::TimedOut, + Self::Stopped => TaskEndState::Stopped, + Self::Lost => TaskEndState::Lost, + } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] enum Fact { Accepted { command: String }, From afe6406af0d5e22becaf42aef9f768ca30cc430b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 02:26:43 -0500 Subject: [PATCH 31/88] Retire durably read terminal projections without repeat checkpoint writes --- .../src/cognition/context_streams/tasks.rs | 2 +- .../src/cognition/persona_workspace/task_consumption.rs | 2 +- .../cognition/persona_workspace/tests/task_consumption.rs | 6 +++++- .../src/cognition/working_memory/task_results.rs | 4 +++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs index 0e4fc67eac..efb7e10ca3 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tasks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -71,7 +71,7 @@ impl Source for Tasks<'_> { .with_summary(summary) .with_pointer(ContextMessage::user(line)) })); - items.extend(terminals.into_iter().map(|end| { + items.extend(terminals.into_iter().filter(|end| end.wake_pending).map(|end| { let status = match end.state { TaskEndState::Done => "done", TaskEndState::Failed => "failed", diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 70107f45df..54adb71ea9 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -36,7 +36,7 @@ impl PersonaWorkspaceRegistry { let shown: std::collections::BTreeSet<_> = receipt.view.items.iter() .filter(|item| !item.retired && matches!(item.level, Level::Full | Level::Summary | Level::Pointer)) .filter_map(|item| item.element).collect(); - let tasks: Vec<_> = memory.task_terminals().into_iter().filter(|end| { + let tasks: Vec<_> = memory.task_terminals().into_iter().filter(|end| end.wake_pending).filter(|end| { shown.contains(&crate::cognition::context_streams::tasks::terminal_element( receipt.owner, end.task, &end.fingerprint)) }).map(|end| end.task).collect(); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index f8b75657e3..9b57c65a44 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -17,7 +17,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( registry.register_from_cfg(cfg_for(owner))?; let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; - let (view, _) = View::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { + let (view, _) = View::::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { claims.iter().map(|claim| claim.full_chars).collect() })?; assert!(view.render().any(|message| message.text.contains("timed out task"))); @@ -36,6 +36,10 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( assert_eq!(memory.pending_task_wakes(), vec![task]); assert!(registry.record_rendered_tasks(&exact)?.is_some()); assert!(memory.pending_task_wakes().is_empty()); + let checkpoint = std::fs::read(volatile_path(owner)?)?; + assert!(registry.record_rendered_tasks(&exact)?.is_none()); + assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); + assert!(source.items().iter().all(|item| !item.full().text.contains("timed out task"))); let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert!(restored.pending_task_wakes().is_empty()); diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index a8a011af41..6ce226e9d7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -28,6 +28,7 @@ pub(crate) struct TaskTerminal { pub task: Uuid, pub fingerprint: [u8; 32], pub state: TaskEndState, + pub wake_pending: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] @@ -116,10 +117,11 @@ impl WorkingMemory { pub(crate) fn task_terminals(&self) -> Vec { let results = self.task_results.lock(); results.entries.iter().filter_map(|(task, end)| { - results.published.contains_key(task).then_some(TaskTerminal { + results.published.get(task).map(|pending| TaskTerminal { task: *task, fingerprint: end.fingerprint, state: end.state, + wake_pending: *pending, }) }).collect() } From 2235fe427f1c34a76a7eeea3cf019e459903729c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 02:37:49 -0500 Subject: [PATCH 32/88] Remove empty task source after durable terminal consumption --- core/continuum-cognition/src/cognition/context_streams/tasks.rs | 2 +- .../src/cognition/persona_workspace/tests/task_consumption.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs index efb7e10ca3..4dfbfa4728 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tasks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -48,7 +48,7 @@ impl Source for Tasks<'_> { let terminal_ids: std::collections::BTreeSet<_> = terminals.iter().map(|end| end.task).collect(); let tasks: Vec<_> = self.memory.dispatched_snapshot().into_iter() .filter(|(task, ..)| !terminal_ids.contains(task)).collect(); - if tasks.is_empty() && terminals.is_empty() { + if tasks.is_empty() && !terminals.iter().any(|end| end.wake_pending) { return Vec::new(); } let banner = super::standing( diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 9b57c65a44..dc83ab10a2 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -39,7 +39,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( let checkpoint = std::fs::read(volatile_path(owner)?)?; assert!(registry.record_rendered_tasks(&exact)?.is_none()); assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); - assert!(source.items().iter().all(|item| !item.full().text.contains("timed out task"))); + assert!(source.items().is_empty(), "a consumed end must not leave a standing task banner"); let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert!(restored.pending_task_wakes().is_empty()); From d797735be083574ed24ddc09e86d36e074a29949 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 02:46:24 -0500 Subject: [PATCH 33/88] Share awaited checkpoint execution for task ends and rendered receipts --- .../persona_workspace/task_consumption.rs | 41 +++++++++++++------ .../tests/task_consumption.rs | 22 +++++++--- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 54adb71ea9..3a0072d755 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -110,6 +110,34 @@ impl ResidentTaskSink { pub fn new(registry: Arc) -> Self { Self(registry) } + + /// Await the same checkpoint owner used for incoming ends. The caller keeps + /// this persistence result separate from the generation that produced the + /// receipt: failure here cannot turn a served generation into an inference fault. + pub async fn record_rendered( + &self, + receipt: crate::cognition::render_receipt::RenderReceipt, + ) -> Result, TaskSinkError> { + self.commit(move |registry| registry.record_rendered_tasks(&receipt)).await + } + + async fn commit( + &self, + operation: impl FnOnce(&PersonaWorkspaceRegistry) -> Result + + Send + 'static, + ) -> Result { + let registry = Arc::clone(&self.0); + // Carry the existing test filesystem scope onto the blocking worker. + #[cfg(test)] + let test_home = crate::paths::NativeHomeOverride::current(); + Ok(tokio::task::spawn_blocking(move || { + #[cfg(test)] + let _native = test_home + .as_deref() + .map(crate::paths::NativeHomeOverride::install); + operation(®istry) + }).await??) + } } #[derive(Debug, thiserror::Error)] @@ -125,19 +153,8 @@ impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { type Error = TaskSinkError; async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { - let registry = Arc::clone(&self.0); let ends = ends.to_vec(); - // Carry the existing test filesystem scope onto the blocking worker. - #[cfg(test)] - let test_home = crate::paths::NativeHomeOverride::current(); - tokio::task::spawn_blocking(move || { - #[cfg(test)] - let _native = test_home - .as_deref() - .map(crate::paths::NativeHomeOverride::install); - registry.consume_task_ends(owner, ends) - }) - .await??; + self.commit(move |registry| registry.consume_task_ends(owner, ends)).await?; Ok(()) } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index dc83ab10a2..e6b355d5d2 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -9,7 +9,8 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( use continuum_context::view::View; let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let sink = ResidentTaskSink::new(Arc::clone(®istry)); let owner = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; let task = Uuid::new_v4(); @@ -26,18 +27,27 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( }; let exact = receipt.clone(); for item in &mut receipt.view.items { item.element = None; } - assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); for item in &mut receipt.view.items { item.level = continuum_context::level::Level::Folded; } - assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); for item in &mut receipt.view.items { item.retired = true; } - assert!(registry.record_rendered_tasks(&receipt)?.is_none()); + assert!(sink.record_rendered(receipt).await?.is_none()); assert_eq!(memory.pending_task_wakes(), vec![task]); - assert!(registry.record_rendered_tasks(&exact)?.is_some()); + let obstruction = volatile_path(owner)?.with_extension("json.tmp"); + std::fs::create_dir(&obstruction)?; + assert!(matches!(sink.record_rendered(exact.clone()).await, + Err(TaskSinkError::Consumption(TaskConsumptionError::Checkpoint(_))))); + assert_eq!(memory.pending_task_wakes(), vec![task]); + let before_retry = WorkingMemory::new(8); + before_retry.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(before_retry.pending_task_wakes(), vec![task]); + std::fs::remove_dir(&obstruction)?; + assert!(sink.record_rendered(exact.clone()).await?.is_some()); assert!(memory.pending_task_wakes().is_empty()); let checkpoint = std::fs::read(volatile_path(owner)?)?; - assert!(registry.record_rendered_tasks(&exact)?.is_none()); + assert!(sink.record_rendered(exact).await?.is_none()); assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); assert!(source.items().is_empty(), "a consumed end must not leave a standing task banner"); let restored = WorkingMemory::new(8); From 668402deab764bc88ef9c9efafb75aed87f80b25 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 02:56:40 -0500 Subject: [PATCH 34/88] Bind task receipt custody to the assembled resident cycle --- .../root_acting_workspace.rs | 8 ++-- .../persona_workspace/task_consumption.rs | 4 ++ ...ins_admitted_periodic_writer_before_ack.rs | 14 +++--- ..._told_when_her_hands_move_and_only_then.rs | 8 ++-- .../tests/task_consumption.rs | 38 +++++++++++---- .../src/cognition/workspace.rs | 1 + .../src/cognition/workspace/arbiter.rs | 1 + .../src/cognition/workspace/render_custody.rs | 48 +++++++++++++++++++ .../cognition/workspace/workspace_cycle.rs | 1 + .../test_env/mind_integration/remote_lane.rs | 4 +- 10 files changed, 100 insertions(+), 27 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/workspace/render_custody.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index 5c2066f7ca..7a22c3e785 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -282,7 +282,7 @@ impl PersonaWorkspaceRegistry { /// Checkpoint lock/read/schema failures refuse this registration and leave /// an existing resident unchanged. Call from a blocking worker during boot. pub fn register_from_cfg( - &self, + self: &Arc, cfg: PersonaBrainConfig, ) -> std::io::Result> { let _assembly = self.assembly.lock(); @@ -297,7 +297,7 @@ impl PersonaWorkspaceRegistry { .tool_head() .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); } - let cycle = Arc::new(cycle); + let cycle = Arc::new(cycle.with_render_custody(self, persona_id, working_memory.incarnation())); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); self.templates.lock().insert(persona_id, template); @@ -315,7 +315,7 @@ impl PersonaWorkspaceRegistry { /// Lazy-init so a persona's cycle is assembled once and reused across every /// room it services (the "one soul" invariant). Also retains the fork-template /// (same as [`register_from_cfg`](Self::register_from_cfg)). - pub fn get_or_build(&self, cfg: PersonaBrainConfig) -> std::io::Result> { + pub fn get_or_build(self: &Arc, cfg: PersonaBrainConfig) -> std::io::Result> { let persona_id = cfg.persona_id; if let Some(existing) = self.get(&persona_id) { return Ok(existing); @@ -333,7 +333,7 @@ impl PersonaWorkspaceRegistry { .tool_head() .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); } - let cycle = Arc::new(cycle); + let cycle = Arc::new(cycle.with_render_custody(self, persona_id, working_memory.incarnation())); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); self.templates.lock().insert(persona_id, template); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 3a0072d755..8021c3ee10 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -142,6 +142,10 @@ impl ResidentTaskSink { #[derive(Debug, thiserror::Error)] pub enum TaskSinkError { + #[error("receipt checkpoint owner {0} no longer exists")] + OwnerGone(Uuid), + #[error("render receipt does not belong to cycle {owner} incarnation {incarnation}")] + CustodyMismatch { owner: Uuid, incarnation: Uuid }, #[error(transparent)] Consumption(#[from] TaskConsumptionError), #[error("resident task checkpoint worker failed: {0}")] diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs index 59670f2fa5..fa08d1ce13 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs @@ -176,7 +176,7 @@ use super::*; // this is exactly what fed a dead reference to a doomed 10s eval. #[test] pub(super) fn resolve_persona_takes_uuid_short_id_or_name_and_fails_loud() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let asha = Uuid::new_v4(); let atlas = Uuid::new_v4(); let mut asha_cfg = cfg_for(asha); @@ -233,7 +233,7 @@ use super::*; // room it services (the "one soul, many rooms" / anti-Severance invariant). #[tokio::test] pub(super) async fn registry_keeps_one_mind_per_persona() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); let first = registry .get_or_build(cfg_for(persona)) @@ -260,7 +260,7 @@ use super::*; // discarded the fresh config — the bug this guards.) #[tokio::test] pub(super) async fn register_overwrites_on_respawn() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); // register_from_cfg IS the production overwrite path (supervisor.rs spawn); // it builds + caches and returns the fresh Arc. @@ -288,7 +288,7 @@ use super::*; pub(super) async fn failed_checkpoint_load_preserves_the_registered_resident() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); assert!(load_volatile(persona).unwrap().is_none()); let current = registry.register_from_cfg(cfg_for(persona)).unwrap(); @@ -319,7 +319,7 @@ use super::*; pub(super) async fn resident_registration_refuses_checkpoint_and_lock_errors() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); for fault in ["schema", "read", "lock"] { let persona = Uuid::new_v4(); let path = volatile_path(persona).unwrap(); @@ -547,7 +547,7 @@ use super::*; #[tokio::test] pub(super) async fn eval_fork_drops_hands_describing_grounding_when_tools_stripped() { const HANDS_MARKER: &str = "drill in with code/list and code/tree"; - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); // SlowGrounding's fixed roster line stands in for capability-NEUTRAL // grounding; the hands-describing source is its own tiny stub. @@ -629,7 +629,7 @@ use super::*; #[tokio::test] pub(super) async fn suppress_recall_omits_the_recall_faculty_from_the_eval_fork() { use crate::cognition::workspace::FacultyId; - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); registry .register_from_cfg(cfg_for(persona)) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index ec36aff556..42cfe573b9 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -533,7 +533,7 @@ use super::*; pub(super) async fn every_resident_at_a_seam_measures_her_own_tree_including_untracked_files() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let mut residents = Vec::new(); for i in 0..3 { let persona = Uuid::new_v4(); @@ -588,7 +588,7 @@ use super::*; pub(super) async fn her_mind_room_runs_on_its_own_cycle_never_checkpointed() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let her = Uuid::new_v4(); let live = registry.register_from_cfg(cfg_for(her)).expect("live cycle"); let mind_room = crate::cognition::mind_room::mind_room_id(her); @@ -609,7 +609,7 @@ use super::*; pub(super) async fn resident_checkpoint_excludes_replaced_cycles_and_eval_forks() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); let old_cycle = registry .register_from_cfg(cfg_for(persona)) @@ -710,7 +710,7 @@ use super::*; pub(super) async fn resident_checkpoint_reports_io_failure_and_saves_other_residents() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let failed = Uuid::new_v4(); let healthy = Uuid::new_v4(); for id in [failed, healthy] { diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index e6b355d5d2..842e4f42ce 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -15,7 +15,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( registry.register_from_cfg(cfg_for(owner))?; let task = Uuid::new_v4(); registry.consume_task_ends(owner, vec![(task, TaskEnd::TimedOut)])?; - registry.register_from_cfg(cfg_for(owner))?; + let cycle = registry.register_from_cfg(cfg_for(owner))?; let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; let (view, _) = View::::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { @@ -26,6 +26,14 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( owner, incarnation: memory.incarnation(), request: "submitted-request".to_owned(), view: view.receipt(), }; let exact = receipt.clone(); + let isolated = registry.mind_cycle(&owner).ok_or("private cycle absent")?; + isolated.persist_render_receipts(vec![exact.clone()]).await?; + assert_eq!(memory.pending_task_wakes(), vec![task], "private cycles have no live checkpoint authority"); + let mut foreign = exact.clone(); + foreign.incarnation = Uuid::new_v4(); + assert!(matches!(cycle.persist_render_receipts(vec![exact.clone(), foreign]).await, + Err(TaskSinkError::CustodyMismatch { .. }))); + assert_eq!(memory.pending_task_wakes(), vec![task], "validate the whole batch before retirement"); for item in &mut receipt.view.items { item.element = None; } assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); @@ -44,15 +52,25 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( before_retry.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert_eq!(before_retry.pending_task_wakes(), vec![task]); std::fs::remove_dir(&obstruction)?; - assert!(sink.record_rendered(exact.clone()).await?.is_some()); + cycle.persist_render_receipts(vec![exact.clone()]).await?; assert!(memory.pending_task_wakes().is_empty()); let checkpoint = std::fs::read(volatile_path(owner)?)?; - assert!(sink.record_rendered(exact).await?.is_none()); + assert!(sink.record_rendered(exact.clone()).await?.is_none()); assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); assert!(source.items().is_empty(), "a consumed end must not leave a standing task banner"); let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert!(restored.pending_task_wakes().is_empty()); + registry.register_from_cfg(cfg_for(owner))?; + assert!(matches!(cycle.persist_render_receipts(vec![exact.clone()]).await, + Err(TaskSinkError::Consumption(TaskConsumptionError::Replaced(id))) if id == owner)); + // Retaining a cycle must not retain its registry through a reference cycle. + let weak = Arc::downgrade(®istry); + drop(sink); + drop(registry); + assert!(weak.upgrade().is_none()); + assert!(matches!(cycle.persist_render_receipts(vec![exact]).await, + Err(TaskSinkError::OwnerGone(id)) if id == owner)); Ok(()) } @@ -61,7 +79,7 @@ async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; @@ -93,7 +111,7 @@ async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); assert!( @@ -125,7 +143,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; @@ -223,7 +241,7 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; @@ -259,7 +277,7 @@ async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; @@ -291,7 +309,7 @@ async fn rejected_read_batch_cannot_partially_retire_a_durable_wake( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; @@ -321,7 +339,7 @@ async fn served_read_arriving_after_shutdown_preserves_restart_delivery( ) -> Result<(), Box> { let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let owner = Uuid::new_v4(); let task = Uuid::new_v4(); registry.register_from_cfg(cfg_for(owner))?; diff --git a/core/continuum-cognition/src/cognition/workspace.rs b/core/continuum-cognition/src/cognition/workspace.rs index 2182943092..fe3a535467 100644 --- a/core/continuum-cognition/src/cognition/workspace.rs +++ b/core/continuum-cognition/src/cognition/workspace.rs @@ -43,6 +43,7 @@ mod arbiter; pub use arbiter::*; mod workspace_cycle; mod workspace_cycle_2; +mod render_custody; #[cfg(test)] mod tests; diff --git a/core/continuum-cognition/src/cognition/workspace/arbiter.rs b/core/continuum-cognition/src/cognition/workspace/arbiter.rs index c43f9c231b..5b8d68f9ce 100644 --- a/core/continuum-cognition/src/cognition/workspace/arbiter.rs +++ b/core/continuum-cognition/src/cognition/workspace/arbiter.rs @@ -207,6 +207,7 @@ pub struct ActingBody { /// integrates the bids into the bounded workspace, the workspace broadcasts. /// The participation [`Decision`] is then read from the broadcast. pub struct WorkspaceCycle { + pub(super) render_custody: super::render_custody::RenderCustody, pub(super) faculties: Vec>, pub(super) arbiter: Arc, /// Replay/logging seam — every tick is recorded here. Default `Noop` diff --git a/core/continuum-cognition/src/cognition/workspace/render_custody.rs b/core/continuum-cognition/src/cognition/workspace/render_custody.rs new file mode 100644 index 0000000000..8bc531bf37 --- /dev/null +++ b/core/continuum-cognition/src/cognition/workspace/render_custody.rs @@ -0,0 +1,48 @@ +//! A cycle's receipt custody is fixed at assembly. Private and measurement +//! cycles cannot borrow the live resident's checkpoint authority. +use super::WorkspaceCycle; +use crate::cognition::persona_workspace::{PersonaWorkspaceRegistry, ResidentTaskSink, TaskSinkError}; +use crate::cognition::render_receipt::RenderReceipt; +use std::sync::{Arc, Weak}; +use uuid::Uuid; + +pub(super) enum RenderCustody { + Isolated, + Resident { + registry: Weak, + owner: Uuid, + incarnation: Uuid, + }, +} + +impl WorkspaceCycle { + pub(crate) fn with_render_custody( + mut self, + registry: &Arc, + owner: Uuid, + incarnation: Uuid, + ) -> Self { + self.render_custody = RenderCustody::Resident { + registry: Arc::downgrade(registry), owner, incarnation, + }; + self + } + + /// Persist the observations of this resident's served generations. Isolated + /// cycles have no durable task acknowledgement authority. Registry teardown + /// and receipt disagreement are explicit failures, never an owner substitution. + pub async fn persist_render_receipts(&self, receipts: Vec) -> Result<(), TaskSinkError> { + let RenderCustody::Resident { registry, owner, incarnation } = &self.render_custody else { + return Ok(()); + }; + if receipts.is_empty() { return Ok(()); } + // Validate the complete batch before any receipt can mutate the ledger. + if receipts.iter().any(|receipt| receipt.owner != *owner || receipt.incarnation != *incarnation) { + return Err(TaskSinkError::CustodyMismatch { owner: *owner, incarnation: *incarnation }); + } + let registry = registry.upgrade().ok_or(TaskSinkError::OwnerGone(*owner))?; + let sink = ResidentTaskSink::new(registry); + for receipt in receipts { sink.record_rendered(receipt).await?; } + Ok(()) + } +} diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs index 88efb143b2..c74fed72d1 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs @@ -3,6 +3,7 @@ use super::*; impl WorkspaceCycle { pub fn new(faculties: Vec>, arbiter: Arc) -> Self { Self { + render_custody: super::render_custody::RenderCustody::Isolated, faculties, arbiter, capture: Arc::new(NoopWorkspaceCaptureSink), diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 791db51f43..8a7eea28db 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -56,7 +56,7 @@ async fn rehome_requires_a_readable_local_assignment() { crate::persona::cognition_extensions::install(); // her remote binding is persona's to read let root = tempfile::tempdir().expect("root"); let _native = crate::paths::NativeHomeOverride::install(root.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let id = Uuid::new_v4(); let cycle = registry.register_from_cfg(cfg_for(id, "Ivar")).expect("resident"); let (original, original_model) = cycle.current_model_route().expect("binding"); @@ -91,7 +91,7 @@ async fn a_resident_bound_at_the_provisional_window_is_rehomed_to_the_served_win crate::persona::cognition_extensions::install(); let root = tempfile::tempdir().expect("root"); let _native = crate::paths::NativeHomeOverride::install(root.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let local = registry.register_from_cfg(cfg_for(Uuid::new_v4(), "Aiko")).expect("local resident"); let remote = registry.register_from_cfg(cfg_for(Uuid::new_v4(), "Kira")).expect("remote resident"); let airc = crate::identity::citizen_path::citizen_home_path(root.path(), crate::identity::IdentityKind::Persona, None, "Kira"); From f78096ce3a2bb78c74d50d657d3c74c565c7a357 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 03:08:58 -0500 Subject: [PATCH 35/88] Persist rendered task receipts before settlement effects and type failures --- .../src/cognition/eval/eval_settle.rs | 6 +-- .../src/cognition/eval/eval_task_result.rs | 2 +- .../src/cognition/eval/run_pass.rs | 24 +++++---- .../src/cognition/eval/warm_gate.rs | 5 +- .../src/cognition/experience.rs | 8 +-- .../src/cognition/experience/tests.rs | 6 +-- .../src/cognition/act_observe/mod.rs | 2 +- .../src/cognition/act_observe/settle.rs | 2 +- .../act_observe/settle/settle_step.rs | 7 ++- .../act_observe/settle/settle_to_outcome.rs | 30 +++++++---- .../src/cognition/act_observe/settle/tests.rs | 2 +- .../src/cognition/act_observe/tests/credit.rs | 4 +- .../src/cognition/act_observe/tests/drive.rs | 53 ++++++++++++++++++- .../src/cognition/act_observe/types.rs | 42 +++++++++------ .../src/cognition/resident_service.rs | 15 +++--- .../citizen_health/resident_service.rs | 1 + .../commands/persona/turn_frame/execute.rs | 3 ++ .../persona/service_loop/burst_fingerprint.rs | 4 ++ .../src/persona/service_loop/turn_cycle.rs | 6 +++ core/continuum-service/src/resident.rs | 3 ++ protocol/typescript/grid/ResidentRefusal.ts | 2 +- 21 files changed, 164 insertions(+), 63 deletions(-) diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index 8fe8764dbc..ec88d8730a 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -105,9 +105,9 @@ pub(super) async fn run_pass_team( // number. Threading the full re-verify+retry into the two-solver loop is a scoped // follow-up. [[proctored-exam-session-dependable-benchmark]] if let Some(cause) = r - .inference_error + .failure .clone() - .or_else(|| w.inference_error.clone()) + .or_else(|| w.failure.clone()) { infra_faults += 1; if infra_reason.is_none() { @@ -116,7 +116,7 @@ pub(super) async fn run_pass_team( results.push(EvalTaskResult { id: t.id.clone(), ok: false, - grade: format!("infra unavailable (lane never recovered): {cause}"), + grade: format!("settlement infrastructure unavailable: {cause}"), acts: 0, answer: String::new(), latency_ms: 0, diff --git a/core/continuum-academy/src/cognition/eval/eval_task_result.rs b/core/continuum-academy/src/cognition/eval/eval_task_result.rs index 1996745082..cc408ec3a1 100644 --- a/core/continuum-academy/src/cognition/eval/eval_task_result.rs +++ b/core/continuum-academy/src/cognition/eval/eval_task_result.rs @@ -67,7 +67,7 @@ pub struct EvalTaskResult { pub struct InfraUnavailable { /// Human cause: which axis broke (not-ready / connect-refused / not-the-served-model /// / compute-error / stream-idle timeout), naming the task it broke on. Display-only - /// — the classification that produced it is [`SettleOutcome::inference_error`], never + /// — the classification that produced it is [`SettleOutcome::failure`], never /// re-parsed from this string. pub reason: String, /// How many tasks were attempted before the run aborted. The exam is INCOMPLETE — a diff --git a/core/continuum-academy/src/cognition/eval/run_pass.rs b/core/continuum-academy/src/cognition/eval/run_pass.rs index 36d1e4082d..557dc3d67d 100644 --- a/core/continuum-academy/src/cognition/eval/run_pass.rs +++ b/core/continuum-academy/src/cognition/eval/run_pass.rs @@ -250,7 +250,7 @@ pub(super) async fn run_pass( // Wedge detection is the SERVING layer's job and it is event-based there: the // stream-liveness classifier (phase-aware budgets, 9e2f95820) kills a // zero-token stream at the source and the failure surfaces here as - // `inference_error` — the event path `drive_to_settle` already returns on. + // `failure` — the event path `drive_to_settle` already returns on. // The old flat 600s deadline predated that sensor (#123, 2026-07-17) and was // never demoted once it shipped: it second-guessed the serving layer with a // stopwatch, declared a LIVE multi-minute e2e decode "wedged" (fluid-sim-e2e, @@ -276,7 +276,7 @@ pub(super) async fn run_pass( const PER_TASK_IDLE_BACKSTOP: std::time::Duration = std::time::Duration::from_secs(20 * 60); // BOUNDED INFRA-FAULT RECOVERY (Proctored Exam Session, Slice B). Drive to - // settlement; if the model call itself FAILS (`inference_error`: lane not-ready / + // settlement; if the model call itself FAILS (`failure`: lane not-ready / // connect-refused / "not the active served model" / compute-error / deadline-wedge) // that is an INFRA fault, never a wrong answer. Re-verify the lane and retry the // SAME task — the retried generation is itself the real decode proof — up to @@ -325,9 +325,13 @@ pub(super) async fn run_pass( } } }; - let Some(cause) = settled.inference_error.clone() else { + let Some(cause) = settled.failure.clone() else { break; // reached a verdict (answer OR graded-wrong) on a working lane }; + // Re-verifying an inference lane cannot repair checkpoint custody. + if matches!(cause, crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_)) { + break; + } infra_attempt += 1; if infra_attempt > INFRA_FAULT_RETRIES { break; @@ -348,7 +352,7 @@ pub(super) async fn run_pass( // INFRA_FAULT_RETRIES re-verify+retry cycles. Record the row for forensics, mark the // run void, and ABORT — every remaining task would only accrue more phantom zeros on // a dead lane. The caller reports InfraUnavailable, NEVER a fake pass_rate. - if let Some(cause) = &settled.inference_error { + if let Some(cause) = &settled.failure { infra_faults += 1; if infra_reason.is_none() { infra_reason = Some(format!("task '{}': {cause}", t.id)); @@ -356,7 +360,7 @@ pub(super) async fn run_pass( results.push(EvalTaskResult { id: t.id.clone(), ok: false, - grade: format!("infra unavailable (lane never recovered): {cause}"), + grade: format!("settlement infrastructure unavailable: {cause}"), acts: 0, answer: String::new(), latency_ms: 0, @@ -372,7 +376,7 @@ pub(super) async fn run_pass( task = %t.id, attempted = results.len(), cause = %cause, - "aborting run as InfraUnavailable — serving lane never recovered; refusing to \ + "aborting run as InfraUnavailable — settlement failed; refusing to \ publish a phantom score over a dead lane" ); break; @@ -444,7 +448,7 @@ pub(super) async fn run_pass( .await { // Take the re-drive only if it produced a real turn (not an infra fault). - if re.inference_error.is_none() { + if re.failure.is_none() { settled = re; } } @@ -559,7 +563,7 @@ Fix the workspace and finish — the grade reads th ) .await { - if re.inference_error.is_none() { + if re.failure.is_none() { settled = re; } } @@ -601,9 +605,9 @@ Fix the workspace and finish — the grade reads th }); continue; // no grade, NO lesson — a harness fault teaches nothing } - // `settled.inference_error` is None here — the abort above consumed every infra + // `settled.failure` is None here — the abort above consumed every infra // fault, so this grades a REAL verdict (a working lane produced an answer, right or - // wrong). No `inference_error` arm remains: an infra fault can no longer masquerade + // wrong). No `failure` arm remains: an infra fault can no longer masquerade // as a graded miss. let (ok, grade) = if !t.ui_checks.is_empty() { // FUNCTIONAL WEB-DEV: grade what her UI ACTUALLY RENDERED. Observe `target` through diff --git a/core/continuum-academy/src/cognition/eval/warm_gate.rs b/core/continuum-academy/src/cognition/eval/warm_gate.rs index 7995ea34fc..57ea034f72 100644 --- a/core/continuum-academy/src/cognition/eval/warm_gate.rs +++ b/core/continuum-academy/src/cognition/eval/warm_gate.rs @@ -37,10 +37,13 @@ pub(super) async fn warm_gate(cycle: &crate::cognition::workspace::WorkspaceCycl crate::cognition::workspace::TurnFraming::directed(), ) .await; - if probe.inference_error.is_none() { + if probe.failure.is_none() { warm = true; break; } + if matches!(probe.failure, Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_))) { + break; + } tokio::time::sleep(std::time::Duration::from_secs(4)).await; } // Reset the volatile scratch the probe touched so task #1 starts from the same diff --git a/core/continuum-academy/src/cognition/experience.rs b/core/continuum-academy/src/cognition/experience.rs index 6e674a4afd..c5444a32b7 100644 --- a/core/continuum-academy/src/cognition/experience.rs +++ b/core/continuum-academy/src/cognition/experience.rs @@ -225,7 +225,7 @@ impl ExperienceRecord { /// the honest, end-to-end-instrumented lived verdict is whether she *converged* /// — reached a real settle-verdict (`Speak`/`Pass`/`RaiseUnprompted`) without /// an inference/serving fault. Two magic-number-free failure signals make a - /// lived turn salient: an infra fault (`inference_error`), and NON-CONVERGENCE + /// lived turn salient: an infra fault (`failure`), and NON-CONVERGENCE /// — the settle loop ran out its action budget mid-`Act` and never reached a /// verdict (`SettleOutcome.decision` is still `Act`, the "did not finish" the /// eval grader already recognizes). Both are structural facts of the outcome, @@ -240,7 +240,7 @@ impl ExperienceRecord { // eval's "did not finish", and an honest capability signal with no threshold. let converged = !matches!(settled.decision, Decision::Act { .. }); let clean = - converged && settled.inference_error.is_none() && settled.capacity_refusal.is_none(); + converged && settled.failure.is_none() && settled.capacity_refusal.is_none(); Self { // The stimulus IS the task for a lived turn: the message she answered, // posed as the prompt. No `test`/`expect` — nothing objective to grade @@ -253,11 +253,11 @@ impl ExperienceRecord { // correctness claim — a lived turn has no grader (see doc above). ok: clean, grade: match ( - &settled.inference_error, + &settled.failure, &settled.capacity_refusal, converged, ) { - (Some(cause), _, _) => format!("lived turn: inference fault — {cause}"), + (Some(cause), _, _) => format!("lived turn: settlement fault — {cause}"), (None, Some(error), _) => format!("lived turn: prompt capacity refused — {error}"), (None, None, false) => { "lived turn: did not converge (action budget exhausted mid-act)".to_string() diff --git a/core/continuum-academy/src/cognition/experience/tests.rs b/core/continuum-academy/src/cognition/experience/tests.rs index 81870c2d3b..ca82f26882 100644 --- a/core/continuum-academy/src/cognition/experience/tests.rs +++ b/core/continuum-academy/src/cognition/experience/tests.rs @@ -16,7 +16,7 @@ world_state: world_state.to_string(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -248,7 +248,7 @@ world_state: "budget exhausted after 8 acts".into(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -464,7 +464,7 @@ world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index 2f5652cc7e..e5eaaf1b45 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -35,7 +35,7 @@ mod observation; pub use observation::{extract_paths, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; mod types; -pub use types::{SettleOutcome, SettleStep}; +pub use types::{SettleOutcome, SettleStep, SettlementFailure}; mod apply; /// Marks committed before an effect reaches the world (stop-drain S2, card 68811445). diff --git a/core/continuum-cognition/src/cognition/act_observe/settle.rs b/core/continuum-cognition/src/cognition/act_observe/settle.rs index 842f62d105..2e8cd7a7c2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle.rs @@ -15,7 +15,7 @@ use crate::cognition::workspace::{Burst, Decision, Situation, TurnFraming, TurnM use super::apply::apply_act; use super::perception::{any_real_receipt, batch_evidence, claimed_file_without_act, collect_touched_paths, mutated_workspace, ConcernPhase, wrote_without_observation}; -use super::types::{SettleOutcome, SettleStep}; +use super::types::{SettleOutcome, SettleStep, SettlementFailure}; use crate::inference::turn_bound::TICK_DEADLINE; mod tick_deadline; diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs index 5d5fb59b36..9589ad25a5 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs @@ -67,7 +67,7 @@ pub async fn settle_step( // One Instant and one probe; no signature change, and the caller's arithmetic // is unchanged. let cycle_started = std::time::Instant::now(); - let ws = cycle.run_situated(burst, framing, situation).await; + let mut ws = cycle.run_situated(burst, framing, situation).await; let cycle_ms = cycle_started.elapsed().as_millis() as u64; // The cost of THIS tick's deliberation generation — latency + tokens of the // model call behind the verdict. Carried out alongside the step so the caller @@ -100,6 +100,11 @@ pub async fn settle_step( if let Some(m) = metrics.as_ref() { cycle.note_generation(m); } + if let Err(error) = cycle.persist_render_receipts(std::mem::take(&mut ws.render_receipts)).await { + continuum_base::probe!(class = "settle.receipt_persistence_failed", room = %room_id, + error = %error, "served generation retained; checkpoint failed before speech or action"); + return (SettleStep::ReceiptPersistenceFailed { error: Arc::new(error) }, metrics, step_receipts); + } // A FAILED model call is not a verdict and not a silence — surface it LOUD so no // failure ever masquerades as a chosen `Pass` ([[fallbacks-are-illegal-fail-loud]]). // Checked BEFORE the decision so a fault can never collapse into `Passed` (the diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs index c9f9e99a25..c62561c8ec 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs @@ -115,7 +115,7 @@ pub(super) async fn settle_to_outcome<'c>( // faulted thought is retried in place, bounded, before the turn is // surrendered — the flicker costs one re-generation, not the turn. Only a // SUSTAINED fault (budget spent across the turn) ends the turn with - // inference_error, exactly as before — 4+ faults in one turn IS a wedge worth + // failure, exactly as before — 4+ faults in one turn IS a wedge worth // surrendering to, not a flicker. Whole-turn budget, not per-tick. const DELIBERATION_RETRY_BUDGET: u32 = 3; let mut delib_retries: u32 = 0; @@ -147,7 +147,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -248,7 +248,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: Some(error), + failure: Some(SettlementFailure::Inference(error)), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -480,7 +480,7 @@ pub(super) async fn settle_to_outcome<'c>( ), capacity_refusal: Some(error.clone()), generation_receipts, - inference_error: None, + failure: None, touched_paths: touched, turn_acts, }; @@ -604,7 +604,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -714,7 +714,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -731,7 +731,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -749,6 +749,16 @@ pub(super) async fn settle_to_outcome<'c>( SettleStep::DeferredBeforeDispatch => { unreachable!("deferral is a driven-turn disposition, not an individual step"); } + SettleStep::ReceiptPersistenceFailed { error } => { + return SettleOutcome { + room: room_id, decision: Decision::pass(), spoken: None, acts, + world_state: burst.rendered.clone(), room_updates: Arc::clone(&burst.room_updates), + metrics, generation_receipts, + failure: Some(SettlementFailure::ReceiptPersistence(error)), + deferred_before_dispatch: false, capacity_refusal: None, + touched_paths: touched, turn_acts, + }; + } SettleStep::InferenceFailed { error } => { // A STARVED MIND KEEPS HER BUDGET. This arm's retry budget is for a // TRANSIENT MODEL FAULT — a generation that reached the lane and came @@ -782,7 +792,7 @@ pub(super) async fn settle_to_outcome<'c>( metrics, generation_receipts: generation_receipts.clone(), // Not an inference fault: no inference was ever dispatched. - inference_error: None, + failure: None, deferred_before_dispatch: can_defer_input(generation_receipts.len(), acts, turn_acts.len(), delib_retries), capacity_refusal: None, touched_paths: touched, @@ -795,7 +805,7 @@ pub(super) async fn settle_to_outcome<'c>( // in place, bounded, and ALWAYS probe so the wedge signal stays // visible to the concurrency investigation (the retry recovers the // turn; it must never HIDE the fault). Only a SUSTAINED fault - // (budget spent) surrenders the turn with inference_error, exactly + // (budget spent) surrenders the turn with failure, exactly // as before. // A generation the act deadline dropped in flight is no transient fault: its // retry waits out another whole bound on the same engine (up to three, so one @@ -823,7 +833,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: Some(error), + failure: Some(SettlementFailure::Inference(error)), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 17ef06bb10..01bf7690a2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -255,7 +255,7 @@ &mut conversation, ) .await; - assert!(settled.inference_error.is_some(), "a failed act"); + assert!(settled.failure.is_some(), "a failed act"); assert!(!settled.deferred_before_dispatch, "never a lane wait"); assert!(settled.generation_receipts.is_empty(), "no completion"); assert_eq!(start.elapsed(), crate::inference::turn_bound::TICK_DEADLINE, "one bound, no in-place retry"); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs index 145842b41e..d9326ed5d3 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs @@ -154,9 +154,9 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { let outcome = drive_to_settle_with_input(&cycle, burst, 8, framing, &mut conversation).await; assert!( - outcome.inference_error.is_none(), + outcome.failure.is_none(), "{:?}", - outcome.inference_error + outcome.failure ); assert_eq!(outcome.acts, 2); assert_eq!(outcome.room, room); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 23a3f44e65..f7d0fa761c 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -126,7 +126,7 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { assert_eq!(outcome.metrics.output_tokens, 40); assert_eq!(outcome.metrics.latency_ms, 1200); assert!(!outcome.deferred_before_dispatch); - assert!(outcome.inference_error.is_none()); + assert!(outcome.failure.is_none()); assert!(matches!( SettleStep::from_settled(outcome).0, SettleStep::CapacityRefused { @@ -164,7 +164,7 @@ async fn capacity_refusal_leaves_the_driver_once_with_typed_custody() { let outcome = drive_to_settle(&cycle, "keep the complete input", 8, TurnFraming::ambient()).await; assert_eq!(faculty.0.load(std::sync::atomic::Ordering::SeqCst), 1); - assert!(outcome.inference_error.is_none()); + assert!(outcome.failure.is_none()); assert!(outcome.deferred_before_dispatch); assert_eq!(outcome.acts, 0); assert!(outcome.generation_receipts.is_empty()); @@ -575,3 +575,52 @@ async fn settle_step_defers_the_act_without_executing_when_may_act_is_false() { "a permitted act DOES reach the executor" ); } + +#[tokio::test] +async fn receipt_custody_failure_stops_settlement_without_retrying_inference() { + use crate::ai::provenance::{GenerationOutcome, GenerationReceipt}; + use crate::cognition::act_observe::SettlementFailure; + use crate::cognition::persona_workspace::{PersonaWorkspaceRegistry, TaskSinkError}; + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Served { + contribution: Contribution, + calls: AtomicUsize, + } + #[async_trait] + impl Faculty for Served { + fn id(&self) -> FacultyId { FacultyId::Deliberation } + fn reacts_to_broadcast(&self) -> bool { true } + async fn contribute(&self, _: &Workspace) -> Option { + self.calls.fetch_add(1, Ordering::SeqCst); + Some(self.contribution.clone()) + } + } + let owner = Uuid::new_v4(); + let incarnation = Uuid::new_v4(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let mut contribution = Contribution::verdict(Decision::Speak { text: "must not be emitted".into() }, 1.0, "served"); + contribution.receipts.push(GenerationReceipt { + submitted_request_id: "served-before-owner-loss".into(), + outcome: GenerationOutcome::Served { model: "fixture".into(), provider: "fixture".into(), provider_request_id: None }, + capture: None, genes: Vec::new(), gene_scales: Vec::new(), allocation: None, + }); + contribution.render_receipts.push(crate::cognition::render_receipt::RenderReceipt { + owner, incarnation, request: "served-before-owner-loss".into(), + view: continuum_context::view::Receipt { epoch: 1, items: Vec::new() }, + }); + let faculty = Arc::new(Served { contribution, calls: AtomicUsize::new(0) }); + let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter)) + .with_render_custody(®istry, owner, incarnation); + drop(registry); + let outcome = drive_to_settle(&cycle, "observe the task".to_owned(), 2, TurnFraming::directed()).await; + assert_eq!(faculty.calls.load(Ordering::SeqCst), 1, "persistence must not spend an inference retry"); + assert!(outcome.spoken.is_none()); + assert_eq!(outcome.acts, 0); + assert!(!outcome.deferred_before_dispatch, "the generation really was served"); + assert!(matches!(&outcome.failure, Some(SettlementFailure::ReceiptPersistence(error)) + if matches!(error.as_ref(), TaskSinkError::OwnerGone(id) if *id == owner))); + assert_eq!(outcome.generation_receipts.len(), 1); + let (step, _, receipts) = SettleStep::from_settled(outcome); + assert!(matches!(step, SettleStep::ReceiptPersistenceFailed { .. })); + assert!(matches!(receipts[0].outcome, GenerationOutcome::Served { .. })); +} diff --git a/core/continuum-cognition/src/cognition/act_observe/types.rs b/core/continuum-cognition/src/cognition/act_observe/types.rs index ac450dae1d..aab6477dbf 100644 --- a/core/continuum-cognition/src/cognition/act_observe/types.rs +++ b/core/continuum-cognition/src/cognition/act_observe/types.rs @@ -8,6 +8,14 @@ use crate::ai::types::ToolCall; use crate::cognition::workspace::{Decision, TurnMetrics}; +#[derive(Clone, Debug, thiserror::Error)] +pub enum SettlementFailure { + #[error("inference failed: {0}")] + Inference(String), + #[error("render receipt persistence failed: {0}")] + ReceiptPersistence(std::sync::Arc), +} + /// The result of driving a mind to settlement. pub struct SettleOutcome { /// EVERY act this turn made, in order: (the intent she stated, the exact calls). The @@ -39,13 +47,10 @@ pub struct SettleOutcome { /// to the accuracy grade — the same number a live turn could surface for the /// serving governor. pub metrics: TurnMetrics, - /// `Some(cause)` when the settle loop stopped because the deliberation model - /// call FAILED (timeout, 5xx, a serving lane refusing a model it isn't hosting) - /// rather than settling on a verdict. The grader MUST treat this as an - /// infrastructure failure — NOT a wrong answer — so an inference hiccup never - /// corrupts the accuracy metric ([[self-improvement-is-a-control-loop]]: the - /// reward is only as trustworthy as the metric). `None` on every settled turn. - pub inference_error: Option, + /// Infrastructure prevented settlement. The variant distinguishes a failed + /// generation from a served generation whose render receipt could not be + /// persisted. Neither is a graded wrong answer or an accepted learning turn. + pub failure: Option, /// The entire turn stopped at admission before any generation or action. /// Callers retain its inbound delivery obligation; this is not a chosen Pass. pub deferred_before_dispatch: bool, @@ -86,7 +91,7 @@ pub struct SettleOutcome { impl SettleOutcome { /// An infra-failure outcome: no verdict was reached because the deliberation /// call failed OR was aborted by a watchdog (e.g. a per-task deadline in the - /// eval loop). The grader keys on `inference_error.is_some()` to score this a + /// eval loop). The grader keys on `failure.is_some()` to score this a /// NAMED infrastructure failure — never a wrong answer — so a serving wedge /// never masquerades as a capability miss ([[self-improvement-is-a-control-loop]]). /// Zeroed metrics/acts because none accrued meaningfully. `TurnMetrics: Default`. @@ -99,7 +104,7 @@ impl SettleOutcome { world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: Some(cause.into()), + failure: Some(SettlementFailure::Inference(cause.into())), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -162,6 +167,9 @@ pub enum SettleStep { /// tick, the eval grades it an infra failure — never a serene no-op that hides a /// broken lane. `error` names the cause verbatim from the adapter. InferenceFailed { error: String }, + /// The generation was served, but its observed task ends could not be + /// checkpointed. No subsequent action or speech was emitted by this step. + ReceiptPersistenceFailed { error: std::sync::Arc }, } impl SettleStep { @@ -171,8 +179,7 @@ impl SettleStep { /// result through the one existing turn handler, no parallel match. /// /// The mapping is total and lossless for the live handler's purposes: - /// • `inference_error` present → `InferenceFailed` (a failed model is never a - /// chosen silence — [[fallbacks-are-illegal-fail-loud]]); + /// • `failure` present → the matching typed failure step; /// • `Speak`/`RaiseUnprompted` → `Spoke` (the prose reaches the room); /// • `Act` → `Acted` — the drive spent its whole act budget without settling on /// speech; the results are already in memory, so the live handler `continue`s @@ -207,11 +214,14 @@ impl SettleStep { generation_receipts, ); } - if let Some(error) = outcome.inference_error { + if let Some(error) = outcome.failure { // The fault path keeps them too: a turn whose deliberation failed still // dispatched generations, and that is precisely when provenance matters. return ( - SettleStep::InferenceFailed { error }, + match error { + SettlementFailure::Inference(error) => SettleStep::InferenceFailed { error }, + SettlementFailure::ReceiptPersistence(error) => SettleStep::ReceiptPersistenceFailed { error }, + }, metrics, generation_receipts, ); @@ -262,7 +272,7 @@ mod tests { } } - fn outcome_with(decision: Decision, inference_error: Option) -> SettleOutcome { + fn outcome_with(decision: Decision, failure: Option) -> SettleOutcome { SettleOutcome { spoken: match &decision { Decision::Speak { text } | Decision::RaiseUnprompted { text } => Some(text.clone()), @@ -273,7 +283,7 @@ mod tests { world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error, + failure: failure.map(SettlementFailure::Inference), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -335,7 +345,7 @@ mod tests { matches!(step, SettleStep::Passed { reason: Some(r) } if r == "done — patch ready") ); - // inference_error present → InferenceFailed, REGARDLESS of decision — a + // failure present → InferenceFailed, REGARDLESS of decision — a // failed model is never a chosen silence. let (step, _, _) = SettleStep::from_settled(outcome_with( Decision::pass(), diff --git a/core/continuum-cognition/src/cognition/resident_service.rs b/core/continuum-cognition/src/cognition/resident_service.rs index e6f89ad59a..30c31e3d3a 100644 --- a/core/continuum-cognition/src/cognition/resident_service.rs +++ b/core/continuum-cognition/src/cognition/resident_service.rs @@ -25,7 +25,10 @@ static LEDGERS: LazyLock> = LazyLock::new(DashMap: pub fn note_settled(persona: Uuid, settled: &SettleOutcome, wall_ms: u64) { let turn = turn_of( settled.capacity_refusal.as_ref(), - settled.inference_error.is_some(), + settled.failure.as_ref().map(|failure| match failure { + crate::cognition::act_observe::SettlementFailure::Inference(_) => Refusal::InferenceFailed, + crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_) => Refusal::ReceiptPersistenceFailed, + }), settled.deferred_before_dispatch, &settled.generation_receipts, &settled.metrics, @@ -73,7 +76,7 @@ pub fn close_windows(span: Window) -> Vec<(Uuid, ResidentWindow)> { /// beside that, so a mind that worked and then parked is both. fn turn_of( capacity: Option<&CapacityRefusal>, - inference_failed: bool, + failure: Option, deferred_before_dispatch: bool, receipts: &[GenerationReceipt], metrics: &TurnMetrics, @@ -102,7 +105,7 @@ fn turn_of( budget_tokens: saturating_u32(refusal.budget_tokens), context_window: refusal.readiness.as_ref().map(|r| r.observed_window()), }), - None if inference_failed => Some(Refusal::InferenceFailed), + None if failure.is_some() => failure, None if deferred_before_dispatch => Some(Refusal::LaneStarved), None => None, }; @@ -136,18 +139,18 @@ mod tests { fn a_refusal_before_inference_is_demand_with_no_completion_and_keeps_its_numbers() { let kimi = CapacityRefusal::from(PromptCapacityError { required_tokens: 26_101, budget_tokens: 17_829 }); let metrics = TurnMetrics::default(); - let turn = turn_of(Some(&kimi), false, true, &[], &metrics, 0, 2_000); + let turn = turn_of(Some(&kimi), None, true, &[], &metrics, 0, 2_000); assert_eq!(turn.completion, None); assert_eq!( turn.refusal, Some(Refusal::PromptCapacity { required_tokens: 26_101, budget_tokens: 17_829, context_window: None }) ); - let worked = turn_of(Some(&kimi), false, false, &[served("qwen3.6-35b-a3b")], &metrics, 2, 90_000); + let worked = turn_of(Some(&kimi), None, false, &[served("qwen3.6-35b-a3b")], &metrics, 2, 90_000); assert_eq!(worked.completion.map(|c| (c.acts, c.model)), Some((2, "qwen3.6-35b-a3b".to_string()))); assert!(worked.refusal.is_some()); - let starved = turn_of(None, false, true, &[], &metrics, 0, 600_000); + let starved = turn_of(None, None, true, &[], &metrics, 0, 600_000); assert_eq!((starved.completion, starved.refusal), (None, Some(Refusal::LaneStarved))); } } diff --git a/core/continuum-core/src/modules/citizen_health/resident_service.rs b/core/continuum-core/src/modules/citizen_health/resident_service.rs index 17e57fdf90..99aa7927f6 100644 --- a/core/continuum-core/src/modules/citizen_health/resident_service.rs +++ b/core/continuum-core/src/modules/citizen_health/resident_service.rs @@ -110,6 +110,7 @@ fn probe(alarm: &ResidentAlarm) { let refusal = match alarm.refusal { Some(resident::Refusal::PromptCapacity { .. }) => "prompt_capacity", Some(resident::Refusal::InferenceFailed) => "inference_failed", + Some(resident::Refusal::ReceiptPersistenceFailed) => "receipt_persistence_failed", Some(resident::Refusal::LaneStarved) => "lane_starved", None => "none", }; diff --git a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs index f771a841aa..d607ffb8e1 100644 --- a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs +++ b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs @@ -319,6 +319,9 @@ fn settle_step_to_json( SettleStep::InferenceFailed { error } => serde_json::json!({ "outcome": "inferenceFailed", "error": error, }), + SettleStep::ReceiptPersistenceFailed { error } => serde_json::json!({ + "outcome": "receiptPersistenceFailed", "error": error.to_string(), + }), }; if let Some(m) = metrics { base["metrics"] = serde_json::json!({ diff --git a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs index d1e42092a8..743f2ce753 100644 --- a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs +++ b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs @@ -605,6 +605,10 @@ pub(super) async fn run_self_cycle( "self-thread act; result admitted as memory, re-perceives next tick" ); } + crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { error } => { + tracing::error!(persona = %ctx.identity.agent_name, error = %error, + "self-cycle render receipt checkpoint failed; generation served, action not executed"); + } crate::cognition::act_observe::SettleStep::InferenceFailed { error } => { // Even on the self-thread a failed model call is surfaced, never swallowed // by the `_ => {}` sleep ([[fallbacks-are-illegal-fail-loud]]): a broken diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index 80d9a29157..ff9a767fa8 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -398,6 +398,12 @@ pub(super) async fn run_turn_cycle( outcome.turns_skipped += 1; return CycleVerdict::Skip; } + crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { error } => { + tracing::error!(persona = %ctx.identity.agent_name, lamport = msg.lamport, + error = %error, "render receipt checkpoint failed; generation served, action not executed"); + outcome.turns_skipped += 1; + return CycleVerdict::Skip; + } crate::cognition::act_observe::SettleStep::InferenceFailed { error } => { // The model call FAILED (timeout, 5xx, the serving lane // refusing a model it isn't hosting) — NOT a chosen silence. diff --git a/core/continuum-service/src/resident.rs b/core/continuum-service/src/resident.rs index 52a3e787c7..1a4b390a9b 100644 --- a/core/continuum-service/src/resident.rs +++ b/core/continuum-service/src/resident.rs @@ -29,6 +29,8 @@ pub enum Refusal { PromptCapacity { required_tokens: u32, budget_tokens: u32, context_window: Option }, /// The model call faulted and its retries were spent. InferenceFailed, + /// Inference was served, but the observed task end could not be checkpointed. + ReceiptPersistenceFailed, /// She waited at the serving gate and never reached the model. LaneStarved, } @@ -329,6 +331,7 @@ impl ResidentAlarm { format!(", prompt capacity {required_tokens} > {budget_tokens}{at}") } Some(Refusal::InferenceFailed) => ", inference failed".to_string(), + Some(Refusal::ReceiptPersistenceFailed) => ", receipt persistence failed".to_string(), Some(Refusal::LaneStarved) => ", lane starved".to_string(), None => String::new(), }; diff --git a/protocol/typescript/grid/ResidentRefusal.ts b/protocol/typescript/grid/ResidentRefusal.ts index 3181cc2a51..b2913b7558 100644 --- a/protocol/typescript/grid/ResidentRefusal.ts +++ b/protocol/typescript/grid/ResidentRefusal.ts @@ -3,4 +3,4 @@ /** * Why a resident's turn ended without completing, or ended parked after progress. */ -export type ResidentRefusal = { "class": "prompt_capacity", required_tokens: number, budget_tokens: number, context_window: number | null, } | { "class": "inference_failed" } | { "class": "lane_starved" }; +export type ResidentRefusal = { "class": "prompt_capacity", required_tokens: number, budget_tokens: number, context_window: number | null, } | { "class": "inference_failed" } | { "class": "receipt_persistence_failed" } | { "class": "lane_starved" }; From d4bfd6c602dc82fc8a1e7d137b6ff32f04d38307 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 03:16:11 -0500 Subject: [PATCH 36/88] Preserve distinct failure causes in lived experience grading --- core/continuum-academy/src/cognition/experience.rs | 7 ++++++- core/continuum-academy/src/cognition/experience/tests.rs | 8 ++++++++ .../src/cognition/act_observe/settle/settle_step.rs | 2 +- .../src/cognition/act_observe/types.rs | 3 ++- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/core/continuum-academy/src/cognition/experience.rs b/core/continuum-academy/src/cognition/experience.rs index c5444a32b7..f20a348212 100644 --- a/core/continuum-academy/src/cognition/experience.rs +++ b/core/continuum-academy/src/cognition/experience.rs @@ -257,7 +257,12 @@ impl ExperienceRecord { &settled.capacity_refusal, converged, ) { - (Some(cause), _, _) => format!("lived turn: settlement fault — {cause}"), + (Some(crate::cognition::act_observe::SettlementFailure::Inference(cause)), _, _) => { + format!("lived turn: inference fault — {cause}") + } + (Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(cause)), _, _) => { + format!("lived turn: receipt persistence fault — {cause}") + } (None, Some(error), _) => format!("lived turn: prompt capacity refused — {error}"), (None, None, false) => { "lived turn: did not converge (action budget exhausted mid-act)".to_string() diff --git a/core/continuum-academy/src/cognition/experience/tests.rs b/core/continuum-academy/src/cognition/experience/tests.rs index ca82f26882..7d700c4fbb 100644 --- a/core/continuum-academy/src/cognition/experience/tests.rs +++ b/core/continuum-academy/src/cognition/experience/tests.rs @@ -233,6 +233,14 @@ lived_fault.grade.contains("inference fault"), "the fault cause is named in the grade" ); + let mut persistence_failed = faulted; + persistence_failed.failure = Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence( + std::sync::Arc::new(crate::cognition::persona_workspace::TaskSinkError::OwnerGone(peer.as_uuid())), + )); + let lived_persistence = ExperienceRecord::from_lived_turn("ping", &persistence_failed); + assert!(!lived_persistence.ok, "checkpoint failure is not accepted experience"); + assert!(lived_persistence.grade.contains("receipt persistence fault")); + assert!(!lived_persistence.grade.contains("inference fault")); // NON-CONVERGENCE: the drive-loop ran out its action budget mid-Act and never // reached a verdict — the lived analog of the eval's "did not finish". A diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs index 9589ad25a5..7eb5606755 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs @@ -102,7 +102,7 @@ pub async fn settle_step( } if let Err(error) = cycle.persist_render_receipts(std::mem::take(&mut ws.render_receipts)).await { continuum_base::probe!(class = "settle.receipt_persistence_failed", room = %room_id, - error = %error, "served generation retained; checkpoint failed before speech or action"); + error = %error, "served generation retained; checkpoint failed before applying final speech or action"); return (SettleStep::ReceiptPersistenceFailed { error: Arc::new(error) }, metrics, step_receipts); } // A FAILED model call is not a verdict and not a silence — surface it LOUD so no diff --git a/core/continuum-cognition/src/cognition/act_observe/types.rs b/core/continuum-cognition/src/cognition/act_observe/types.rs index aab6477dbf..717ca7ebfc 100644 --- a/core/continuum-cognition/src/cognition/act_observe/types.rs +++ b/core/continuum-cognition/src/cognition/act_observe/types.rs @@ -168,7 +168,8 @@ pub enum SettleStep { /// broken lane. `error` names the cause verbatim from the adapter. InferenceFailed { error: String }, /// The generation was served, but its observed task ends could not be - /// checkpointed. No subsequent action or speech was emitted by this step. + /// checkpointed. This step did not apply its command or final speech decision. + /// Generation-time streaming may already have exposed provisional tokens. ReceiptPersistenceFailed { error: std::sync::Arc }, } From 79778b871fa514b7c364f85d1df83aefb3a2d7e8 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 03:36:27 -0500 Subject: [PATCH 37/88] Preserve inbound obligation custody on receipt checkpoint failure --- .../src/persona/obligation/recover.rs | 46 +++++++++++++++++++ .../service_loop/serve_persona_loop_inner.rs | 6 +++ .../src/persona/service_loop/turn_cycle.rs | 10 ++-- .../src/persona/wake_backlog/recovered.rs | 17 +++++++ .../typescript/cognition/InfraUnavailable.ts | 2 +- 5 files changed, 75 insertions(+), 6 deletions(-) diff --git a/core/continuum-mind/src/persona/obligation/recover.rs b/core/continuum-mind/src/persona/obligation/recover.rs index bc4a92a83f..a96674c8df 100644 --- a/core/continuum-mind/src/persona/obligation/recover.rs +++ b/core/continuum-mind/src/persona/obligation/recover.rs @@ -180,6 +180,52 @@ mod tests { body.working_memory.pinned_facts().into_iter().filter(|fact| fact.starts_with("[interrupted]")).collect() } + // what this catches (stop-drain S3): an interrupted turn lost, or re-run twice, or told twice. + #[tokio::test] + async fn failed_receipt_checkpoint_keeps_input_and_effect_obligations_across_restart() { + use crate::cognition::act_observe::SettleStep; + use crate::cognition::persona_workspace::TaskSinkError; + use crate::persona::training_producer::test_support::served_receipt; + let home = tempfile::tempdir().expect("test: temporary home"); + let _home = crate::paths::test_home::HomeGuard::set(home.path()).await; + let executor = test_store_executor(); + let (persona, room, name) = (Uuid::new_v4(), Uuid::new_v4(), "checkpoint-custody"); + let cycle = resident(persona); + let untouched = trigger(room, "finish this"); + let acted = trigger(room, "previous tool batch"); + let rows = [ + PersonaObligation::admitted(persona, room, &untouched, Some(Uuid::new_v4()), 10), + PersonaObligation { + effect_at_ms: Some(21), + effects: Some(vec![RecordedEffect::ToolBatch { calls: vec![("call-1".into(), "code/edit".into())] }]), + ..PersonaObligation::admitted(persona, room, &acted, None, 20) + }, + ]; + let obligations = Obligations::new(&executor, persona, name); + assert!(obligations.report_interrupted(0).await.is_some()); + for row in &rows { + record(obligations.conn.as_ref(), name, row).await.expect("test: durable row"); + } + let mut pending = PendingInput::for_persona(persona); + obligations.recover(30, &mut pending, |_| TurnAttention::default()).await; + pending.observe_settlement( + &untouched, rows[0].wake_engram, TurnAttention::default(), + &SettleStep::ReceiptPersistenceFailed { error: Arc::new(TaskSinkError::OwnerGone(persona)) }, + &[served_receipt("served before checkpoint failed", "qwen")], + ); + assert_eq!(pending.obligation_for(&untouched), Some(rows[0].id)); + assert!(pending.take_answered().is_empty(), "served alone cannot retire the effect-marked row"); + drop(pending); + let restarted = Obligations::new(&executor, persona, name); + let mut pending = PendingInput::for_persona(persona); + assert_eq!(restarted.recover(40, &mut pending, |_| TurnAttention::default()).await.map(|r| r.open), Some(2)); + assert_eq!(pending.obligation_for(&untouched), Some(rows[0].id)); + assert_eq!(pending.wake_engram_for(&untouched), rows[0].wake_engram); + assert_eq!(pending.obligation_for(&acted), None, "previous effects must not replay"); + assert_eq!(interrupted_notices(&cycle).len(), 2); + assert_eq!(open(restarted.conn.as_ref(), name, persona).await.expect("test: read durable rows").len(), 2); + } + // what this catches (stop-drain S3): an interrupted turn lost, or re-run twice, or told twice. // Two untouched rows are each handed back once, with one notice each, and a second start // before she settles them still owes exactly those two rows with the same two notices. diff --git a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs index d33571ee08..5cf1db1452 100644 --- a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs +++ b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs @@ -413,6 +413,12 @@ pub(super) async fn serve_persona_loop_inner( .await { CycleVerdict::Spoke(spoken) => spoken, + CycleVerdict::CheckpointFailed(error) => { + // The admitted row and its pre-effect marks remain durable. The + // existing recovery owner distinguishes untouched input from + // work that already acted; never replay it here as a fresh turn. + return Err(format!("receipt checkpoint failed for obligation {obligation}: {error}")); + } CycleVerdict::Skip => { // A refused or deferred input is still owed: PendingInput retains it for a // retry, so its row stays open with it (Codex on #5480). Only a finished diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index ff9a767fa8..0d178a2f25 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -6,6 +6,9 @@ pub(super) enum CycleVerdict { Spoke(SpokenTurn), /// No reply to publish this turn (deferred, acted, silent, failed, or yielded). Skip, + /// Custody failed after generation. The loop must leave its durable + /// obligation open and return to lifecycle supervision, not close a skip. + CheckpointFailed(Arc), } /// The L2 producer's two provenance inputs are BORN inside the cycle — credit on her hands @@ -301,9 +304,7 @@ pub(super) async fn run_turn_cycle( "deliberation generation cost" ); } - deferred_input.settle(msg, wake_engram, attention, &step); - // The room that chose this turn's cycle above, so the notices it read are the ones answered. - deferred_input.notices_read(turn_room, &turn_generation_receipts); + deferred_input.observe_settlement(msg, wake_engram, attention, &step, &turn_generation_receipts); match step { crate::cognition::act_observe::SettleStep::CapacityRefused { .. } | crate::cognition::act_observe::SettleStep::DeferredBeforeDispatch => { @@ -401,8 +402,7 @@ pub(super) async fn run_turn_cycle( crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { error } => { tracing::error!(persona = %ctx.identity.agent_name, lamport = msg.lamport, error = %error, "render receipt checkpoint failed; generation served, action not executed"); - outcome.turns_skipped += 1; - return CycleVerdict::Skip; + return CycleVerdict::CheckpointFailed(error); } crate::cognition::act_observe::SettleStep::InferenceFailed { error } => { // The model call FAILED (timeout, 5xx, the serving lane diff --git a/core/continuum-mind/src/persona/wake_backlog/recovered.rs b/core/continuum-mind/src/persona/wake_backlog/recovered.rs index 5b0f2ff3e4..52fd302b48 100644 --- a/core/continuum-mind/src/persona/wake_backlog/recovered.rs +++ b/core/continuum-mind/src/persona/wake_backlog/recovered.rs @@ -13,6 +13,23 @@ use crate::cognition::conversation::IncomingMessage; use crate::cognition::workspace::TurnAttention; impl PendingInput { + /// Apply a completed generation to input and notice custody together. A receipt + /// checkpoint failure leaves both with their existing owner for restart recovery. + pub(crate) fn observe_settlement( + &mut self, + message: &IncomingMessage, + wake_engram: Option, + attention: TurnAttention, + step: &crate::cognition::act_observe::SettleStep, + receipts: &[GenerationReceipt], + ) { + if matches!(step, crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { .. }) { + return; + } + self.settle(message, wake_engram, attention, step); + self.notices_read(message.room_id, receipts); + } + /// Hand an interrupted, untouched turn back: retried at the next beat with its original /// engram (memory already holds the trigger) and its own row id. Idempotent per row. pub(crate) fn readmit(&mut self, message: IncomingMessage, engram: Option, attention: TurnAttention, obligation: Uuid) { diff --git a/protocol/typescript/cognition/InfraUnavailable.ts b/protocol/typescript/cognition/InfraUnavailable.ts index a2c2d0b112..09e042dc9e 100644 --- a/protocol/typescript/cognition/InfraUnavailable.ts +++ b/protocol/typescript/cognition/InfraUnavailable.ts @@ -13,7 +13,7 @@ export type InfraUnavailable = { /** * Human cause: which axis broke (not-ready / connect-refused / not-the-served-model * / compute-error / stream-idle timeout), naming the task it broke on. Display-only - * — the classification that produced it is [`SettleOutcome::inference_error`], never + * — the classification that produced it is [`SettleOutcome::failure`], never * re-parsed from this string. */ reason: string, From 3f6f0de385c323de77abee56040ddf9792b4ddac Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 03:45:17 -0500 Subject: [PATCH 38/88] Qualify shared checkpoint failure ownership type --- core/continuum-mind/src/persona/service_loop/turn_cycle.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index 0d178a2f25..6602f44a3c 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -8,7 +8,7 @@ pub(super) enum CycleVerdict { Skip, /// Custody failed after generation. The loop must leave its durable /// obligation open and return to lifecycle supervision, not close a skip. - CheckpointFailed(Arc), + CheckpointFailed(std::sync::Arc), } /// The L2 producer's two provenance inputs are BORN inside the cycle — credit on her hands From 10f801f15a47ef72c7eae7c43a6408071a81230d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 03:45:59 -0500 Subject: [PATCH 39/88] Preserve complete failure evidence and persona identifiers --- .../src/cognition/act_observe/settle/settle_step.rs | 2 +- .../src/cognition/persona_workspace/root_acting_workspace.rs | 2 +- core/continuum-mind/src/persona/service_loop/turn_cycle.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs index 7eb5606755..640ea0facb 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs @@ -128,7 +128,7 @@ pub async fn settle_step( continuum_base::probe!( class = "settle.inference_failed", room = %room_id, - error = &error.to_string()[..error.to_string().len().min(160)], + error = %error, "deliberation generation FAILED — surfacing before the step returns" ); return ( diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index 7a22c3e785..3860ddc828 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -267,7 +267,7 @@ impl PersonaWorkspaceRegistry { } let mut listed: Vec = roster .iter() - .map(|(id, name)| format!("{name} ({})", &id.to_string()[..8])) + .map(|(id, name)| format!("{name} ({id})")) .collect(); listed.sort(); format!("Online now: {}.", listed.join(", ")) diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index 6602f44a3c..5dc8b8bf01 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -376,7 +376,7 @@ pub(super) async fn run_turn_cycle( lamport = msg.lamport, reason = "workspace-pass", gated = gated, - pass_reason = %pass_detail.chars().take(240).collect::(), + pass_reason = %pass_detail, "persona chose silence, or a gate converted her draft into a pass (gated) — pass_reason says which" ); // THE ACT-QUESTION. Asked here on the PASS path and again after a spoken reply, From 40b847017a612d901473ee16204cbba7e9cef7fd Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 04:16:20 -0500 Subject: [PATCH 40/88] Submit whole failed build observations to shared context allocation --- .../continuum-academy/src/cognition/eval/run_pass.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/core/continuum-academy/src/cognition/eval/run_pass.rs b/core/continuum-academy/src/cognition/eval/run_pass.rs index 557dc3d67d..24e68cea18 100644 --- a/core/continuum-academy/src/cognition/eval/run_pass.rs +++ b/core/continuum-academy/src/cognition/eval/run_pass.rs @@ -516,14 +516,6 @@ pub(super) async fn run_pass( round = redrive_round as u64, "settled on a RED DoD — handing her the verdict with a bounded re-drive" ); - let tail: String = dod_out - .chars() - .rev() - .take(4000) - .collect::>() - .into_iter() - .rev() - .collect(); let red_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { @@ -531,9 +523,9 @@ pub(super) async fn run_pass( summary: None, pointer: None, content: format!( - "You settled, but the task's definition-of-done currently FAILS. Its output ends: + "You settled, but the task's definition-of-done currently FAILS. Its output is: -{tail} +{dod_out} Fix the workspace and finish — the grade reads the files, and a red build scores zero." ), From 24d71766ceb9ebeee465d9ba3365ac0fa4a2c035 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 04:38:20 -0500 Subject: [PATCH 41/88] fix(inference): separate admission expiry from generation prediction --- .../src/ai/openai_adapter/stream.rs | 4 +- .../src/inference/turn_admission.rs | 17 ++++-- .../src/inference/turn_admission/tests.rs | 5 +- .../turn_admission/tests/paging_lifetime.rs | 58 ++++++++++++++++++- 4 files changed, 74 insertions(+), 10 deletions(-) diff --git a/core/continuum-engine/src/ai/openai_adapter/stream.rs b/core/continuum-engine/src/ai/openai_adapter/stream.rs index 6e1ff29a67..ce568e802f 100644 --- a/core/continuum-engine/src/ai/openai_adapter/stream.rs +++ b/core/continuum-engine/src/ai/openai_adapter/stream.rs @@ -214,7 +214,7 @@ impl OpenAICompatibleAdapter { &self.client, root, approx_tokens, - crate::inference::turn_admission::AdmissionPatience::for_turn(request.turn_bound, start.elapsed()), + crate::inference::turn_admission::AdmissionPatience::for_turn(), ) .await .map_err(crate::ai::inference_error::InferenceError::Unavailable)?; @@ -451,7 +451,7 @@ impl OpenAICompatibleAdapter { &self.client, root, 0, - crate::inference::turn_admission::AdmissionPatience::for_turn(request.turn_bound, start.elapsed()), + crate::inference::turn_admission::AdmissionPatience::for_turn(), ) .await .map_err(crate::ai::inference_error::InferenceError::Unavailable)?, diff --git a/core/continuum-engine/src/inference/turn_admission.rs b/core/continuum-engine/src/inference/turn_admission.rs index 6d95c4568b..d97ae83652 100644 --- a/core/continuum-engine/src/inference/turn_admission.rs +++ b/core/continuum-engine/src/inference/turn_admission.rs @@ -165,12 +165,20 @@ pub struct AdmissionPatience { } impl AdmissionPatience { - pub fn for_turn(bound: Option, elapsed: std::time::Duration) -> Self { + /// A generation occupancy estimate is not an admission expiry. Healthy queue + /// and paging work stays owned until admitted or the requester cancels. + pub fn for_turn() -> Self { Self { readiness: crate::inference::slots::EndpointSlots::TURN_READINESS_PATIENCE, - deadline: bound.map(|bound| tokio::time::Instant::now() + bound.saturating_sub(elapsed)), + deadline: None, } } + + /// An explicit caller expiry, already expressed on the monotonic clock. + /// Do not derive this from predicted generation occupancy. + pub fn until(deadline: tokio::time::Instant) -> Self { + Self { deadline: Some(deadline), ..Self::for_turn() } + } } impl From for AdmissionPatience { @@ -193,8 +201,9 @@ impl From for AdmissionPatience { /// `patience` is how long the turn holds through a CLOSED endpoint (an engine still /// loading, a transition in flight) before it is refused — the caller's bound, since /// only the caller knows what its request can afford: the persona adapter passes -/// `AdmissionPatience::for_turn(turn_bound, elapsed)`. Readiness time is cumulative -/// across retries; healthy slot and adapter waits spend only the request deadline. +/// `AdmissionPatience::for_turn()`. Readiness time is cumulative across retries; +/// healthy slot and adapter waits end only on cancellation or an explicit caller +/// expiry supplied with `AdmissionPatience::until`. /// A test that asserts immediate readiness refusal passes zero. See `EndpointSlots::admit_when_ready` /// for the boot window that cost Kimi 16 turns. pub async fn admit_turn( diff --git a/core/continuum-engine/src/inference/turn_admission/tests.rs b/core/continuum-engine/src/inference/turn_admission/tests.rs index 07587c5ce5..01d9fa22ac 100644 --- a/core/continuum-engine/src/inference/turn_admission/tests.rs +++ b/core/continuum-engine/src/inference/turn_admission/tests.rs @@ -495,7 +495,7 @@ let first = admit_turn(&sem, Some(first_key), Some(old_pool.clone()), &client, &root, 100, std::time::Duration::ZERO).await?; let mut waiting = Box::pin(admit_turn(&sem, Some(waiting_key), Some(old_pool.clone()), - &client, &root, 100, AdmissionPatience::for_turn(None, std::time::Duration::ZERO))); + &client, &root, 100, AdmissionPatience::for_turn())); assert!(futures::poll!(&mut waiting).is_pending()); // Healthy slot contention outlasts the 240s readiness allowance without // spending it. A later engine replacement still gets its readiness hold. @@ -579,8 +579,7 @@ 100, std::time::Duration::ZERO).await?; let started = tokio::time::Instant::now(); let waiting = admit_turn(&sem, Some(next_key), Some(pool), &client, &root, 100, - AdmissionPatience::for_turn(Some(std::time::Duration::from_secs(10)), - std::time::Duration::from_secs(2))); + AdmissionPatience::until(started + std::time::Duration::from_secs(8))); assert!(waiting.await.is_err()); assert_eq!(started.elapsed(), std::time::Duration::from_secs(8)); assert_eq!(sem.available_permits(), permits - 1); diff --git a/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs b/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs index 911621cde5..296b00d506 100644 --- a/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs +++ b/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs @@ -3,6 +3,62 @@ use super::*; use std::time::Duration; +// Sahar's measured generation estimate was 2s while healthy restores took >3s. +// The production admission policy must let the owned restore finish and admit +// subsequent useful generation instead of abandoning it on that prediction. +#[tokio::test] +async fn healthy_restore_outlives_generation_prediction() -> Result<(), Box> { + use axum::{extract::Path, routing::post, Json, Router}; + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let app = Router::new().route("/slots/{slot}", post({ + let entered = entered.clone(); + let release = release.clone(); + move |Path(slot): Path, Json(body): Json| { + let entered = entered.clone(); + let release = release.clone(); + async move { + entered.notify_one(); + release.notified().await; + Json(json!({"id_slot": slot, "filename": body["filename"], "n_restored": 42})) + } + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let root = format!("http://{}", listener.local_addr()?); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let pool = crate::inference::slots::directory().ensure_pool(&root, 3); + let key = PageKey::mind(Uuid::new_v4()).ok_or("activity key")?; + pool.note_saved(key); + let sem = Arc::new(Semaphore::new(1)); + let client = reqwest::Client::new(); + let mut admitting = Box::pin(admit_turn(&sem, Some(key), Some(pool.clone()), + &client, &root, 100, AdmissionPatience::for_turn())); + tokio::select! { + result = &mut admitting => return Err(format!("admitted before restore: {:?}", result.err()).into()), + _ = entered.notified() => {} + } + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(3)).await; + assert!(futures::poll!(&mut admitting).is_pending()); + assert_eq!(sem.available_permits(), 0); + tokio::time::resume(); + release.notify_one(); + let admitted = admitting.as_mut().await?; + assert!(admitted.page_confirmed); + assert!(admitted.slot().is_some()); + drop(admitted); + drop(admitting); + let subsequent = admit_turn(&sem, Some(key), Some(pool), &client, &root, + 100, AdmissionPatience::for_turn()).await?; + assert!(subsequent.page_confirmed); + drop(subsequent); + assert_eq!(sem.available_permits(), 1); + server.abort(); + let _ = server.await; + Ok(()) +} + // What this catches: abandonment during evictee SAVE must retain its durable // ledger receipt, but must not launch the next RESTORE for a requester who left. #[tokio::test] @@ -155,7 +211,7 @@ async fn abandoned_restore_retains_slot_lane_and_generation_until_terminal_recei &client, &root, 100, - AdmissionPatience::for_turn(Some(Duration::from_secs(5)), Duration::ZERO), + AdmissionPatience::until(tokio::time::Instant::now() + Duration::from_secs(5)), )); tokio::time::timeout(Duration::from_secs(5), async { tokio::select! { From 15e17fe877e710221453f7cd573bda9f3c781fea Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 04:38:44 -0500 Subject: [PATCH 42/88] test(inference): finish simulated generation before successor admission --- .../src/inference/turn_admission/tests/paging_lifetime.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs b/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs index 296b00d506..057a0d0e71 100644 --- a/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs +++ b/core/continuum-engine/src/inference/turn_admission/tests/paging_lifetime.rs @@ -44,13 +44,15 @@ async fn healthy_restore_outlives_generation_prediction() -> Result<(), Box Date: Sat, 31 Oct 2026 05:25:46 -0500 Subject: [PATCH 43/88] refactor(tasks): preserve nonzero page contract through storage --- core/continuum-kernel/src/runtime/tasks.rs | 17 +++++++---------- .../src/runtime/tasks/delivery.rs | 2 +- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 67abdd9bfc..b7c5a5c48e 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -7,6 +7,7 @@ use crate::orm::types::{CollectionSchema, FieldType, SchemaField}; use crate::orm::{adapter::StorageAdapter, entity::OrmEntity, store::OrmStore}; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::num::NonZeroUsize; use std::sync::Arc; use uuid::Uuid; @@ -251,15 +252,12 @@ impl TaskLedger { &self, owner: Uuid, after: Option, - limit: usize, + limit: NonZeroUsize, ) -> Result { - if limit == 0 { - return Err("task reconciliation page must be nonempty".into()); - } let mut query = QueryBuilder::new(TaskFact::COLLECTION) .filter_eq("owner", owner.to_string()) .sort_asc("id") - .limit(limit); + .limit(limit.get()); if let Some(cursor) = after { query = query.filter("id", QueryOperator::Gt(Value::String(cursor.to_string()))); } @@ -268,7 +266,7 @@ impl TaskLedger { .find_matching(query.build()) .await .map_err(|e| e.to_string())?; - let exhausted = rows.len() < limit; + let exhausted = rows.len() < limit.get(); let next = rows.last().map(|(id, _)| *id); let mut ends = Vec::new(); for (id, row) in rows { @@ -314,7 +312,7 @@ mod tests { drop(second); let reopened = TaskLedger::new(adapter).await?; assert_eq!(reopened.pending(task, owner).await?, Some(winner.clone())); - let page = reopened.pending_page(owner, None, 10).await?; + let page = reopened.pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?).await?; assert_eq!(page.ends, vec![(task, winner.clone())]); assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); assert!(reopened.pending(task, Uuid::new_v4()).await.is_err()); @@ -369,7 +367,7 @@ mod tests { // Five facts for this owner, plus the empty last page. This bound also // catches a cursor that fails to advance on an empty-result page. for _ in 0..7 { - let page = ledger.pending_page(owner, after, 1).await?; + let page = ledger.pending_page(owner, after, NonZeroUsize::MIN).await?; found.extend(page.ends); if page.exhausted { exhausted = true; @@ -383,7 +381,6 @@ mod tests { found, vec![(pending, TaskEnd::Done(TaskOutput::Json(Value::Null)))] ); - assert!(ledger.pending_page(owner, None, 0).await.is_err()); Ok(()) } use crate::orm::gated_adapter::GatedAdapter; @@ -423,7 +420,7 @@ mod tests { assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); assert_eq!(reopened.pending(task, owner).await?, None); assert!(reopened - .pending_page(owner, None, 10) + .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) .await? .ends .is_empty()); diff --git a/core/continuum-kernel/src/runtime/tasks/delivery.rs b/core/continuum-kernel/src/runtime/tasks/delivery.rs index 6ad9819af2..177506ca0e 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery.rs @@ -66,7 +66,7 @@ impl TaskLedger { sink: &S, ) -> Result> { let page = self - .pending_page(owner, after, limit.get()) + .pending_page(owner, after, limit) .await .map_err(DeliveryError::Read)?; if !page.ends.is_empty() { From 0a76c6d869eee2c39e7fe07e62e14276b039c190 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 07:16:34 -0500 Subject: [PATCH 44/88] fix(tasks): acknowledge only checkpointed perception receipts --- .../persona_workspace/own_speech_persisted.rs | 3 ++ .../persona_workspace/task_consumption.rs | 7 ++-- .../tests/task_consumption.rs | 34 ++++++++++++++-- .../cognition/working_memory/task_results.rs | 8 +++- .../src/runtime/tasks/delivery.rs | 23 ++++++++--- .../src/runtime/tasks/delivery/tests.rs | 40 ++++++++++++++++++- .../src/modules/cognition/task_delivery.rs | 4 +- 7 files changed, 101 insertions(+), 18 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index a74f9054ee..b7ada036a7 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -47,12 +47,14 @@ pub struct VolatileReceipt { owner: Uuid, incarnation: Uuid, consumed_tasks: Vec, + perceived_tasks: std::collections::BTreeSet, } impl VolatileReceipt { pub fn owner(&self) -> Uuid { self.owner } pub fn incarnation(&self) -> Uuid { self.incarnation } pub fn consumed_tasks(&self) -> &[Uuid] { &self.consumed_tasks } + pub fn perceived_tasks(&self) -> &std::collections::BTreeSet { &self.perceived_tasks } } /// Persist the volatile tier — atomic tmp+rename so a crash mid-write never @@ -94,6 +96,7 @@ pub(super) fn save_volatile( owner: persona_id, incarnation: wm.incarnation(), consumed_tasks: snapshot.task_results.consumed_ids(), + perceived_tasks: snapshot.task_results.perceived_ids(), }; let task_publication = snapshot.task_results.publication(); let persisted = PersistedVolatile { diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 8021c3ee10..d0f810cb94 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -156,9 +156,10 @@ pub enum TaskSinkError { impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { type Error = TaskSinkError; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + let offered: std::collections::BTreeSet<_> = ends.iter().map(|(task, _)| *task).collect(); let ends = ends.to_vec(); - self.commit(move |registry| registry.consume_task_ends(owner, ends)).await?; - Ok(()) + let receipt = self.commit(move |registry| registry.consume_task_ends(owner, ends)).await?; + Ok(receipt.perceived_tasks().intersection(&offered).copied().collect()) } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 842e4f42ce..9096b6d617 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -180,7 +180,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( } #[tokio::test] -async fn ledger_ack_follows_resident_commit_and_restart_keeps_wake_without_handle( +async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( ) -> Result<(), Box> { use continuum_kernel::runtime::tasks::{TaskLedger, TaskOutput}; let home = tempfile::tempdir()?; @@ -217,14 +217,15 @@ async fn ledger_ack_follows_resident_commit_and_restart_keeps_wake_without_handl .deliver_page(owner, None, limit, &sink) .await? .acknowledged, - 1 + 0 ); - assert_eq!(ledger.pending(task, owner).await?, None); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); let reopened = TaskLedger::new(adapter).await?; let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert_eq!(restored.pending_task_wakes(), vec![task]); - assert_eq!(reopened.terminal(task, owner).await?, Some(end)); + assert_eq!(reopened.terminal(task, owner).await?, Some(end.clone())); + registry.register_from_cfg(cfg_for(owner))?; assert_eq!( reopened .deliver_page(owner, None, limit, &sink) @@ -233,6 +234,31 @@ async fn ledger_ack_follows_resident_commit_and_restart_keeps_wake_without_handl 0 ); assert_eq!(restored.pending_task_wakes(), vec![task]); + assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + use continuum_context::{source::Source, view::View}; + let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; + let (view, _) = View::::start( + Vec::new(), &[&source as &dyn Source<_>], |claims| claims.iter().map(|claim| claim.full_chars).collect() + )?; + let receipt = crate::cognition::render_receipt::RenderReceipt { + owner, incarnation: memory.incarnation(), request: "served-task-result".into(), view: view.receipt(), + }; + std::fs::create_dir(&obstruction)?; + assert!(sink.record_rendered(receipt.clone()).await.is_err()); + assert!(reopened.deliver_page(owner, None, limit, &sink).await.is_err()); + assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); + std::fs::remove_dir(&obstruction)?; + sink.record_rendered(receipt).await?; + // Crash after the perception checkpoint but before ACK: replay uses the + // restored exact receipt, without prompting her again or remembering a handle. + registry.register_from_cfg(cfg_for(owner))?; + assert_eq!(reopened.deliver_page(owner, None, limit, &sink).await?.acknowledged, 1); + assert_eq!(reopened.pending(task, owner).await?, None); + registry.register_from_cfg(cfg_for(owner))?; + assert_eq!(reopened.deliver_page(owner, None, limit, &sink).await?.acknowledged, 0); + assert!(registry.cycles.lock()[&owner].working_memory.pending_task_wakes().is_empty()); + assert_eq!(reopened.terminal(task, owner).await?, Some(end)); Ok(()) } diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs index 6ce226e9d7..fcfbd3fe61 100644 --- a/core/continuum-cognition/src/cognition/working_memory/task_results.rs +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -56,7 +56,8 @@ impl WorkingMemory { /// Stage a terminal reference and its wake obligation atomically. Whole output /// remains in TaskLedger; the fingerprint detects conflicting replay without /// duplicating binary/JSON bodies in every resident checkpoint. The registry must - /// checkpoint this exact state before acknowledging consumption to the ledger. + /// checkpoint this exact state before publishing the wake. Only a later + /// checkpointed perception receipt can authorize ledger acknowledgement. /// A replay is inert, including after its wake has already been admitted. pub fn stage_task_end(&self, task: Uuid, end: TaskEnd) -> Result { self.stage_task_ends(vec![(task, end)]) @@ -171,6 +172,11 @@ impl TaskResults { pub(crate) fn consumed_ids(&self) -> Vec { self.entries.keys().copied().collect() } + + /// Perception in this exact serialized snapshot; filing alone never qualifies. + pub(crate) fn perceived_ids(&self) -> std::collections::BTreeSet { + self.entries.iter().filter_map(|(task, end)| (!end.wake_pending).then_some(*task)).collect() + } } #[cfg(test)] diff --git a/core/continuum-kernel/src/runtime/tasks/delivery.rs b/core/continuum-kernel/src/runtime/tasks/delivery.rs index 177506ca0e..79d04c0c78 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery.rs @@ -1,18 +1,20 @@ //! The shared owner-delivery seam from HER-TASKS T2. Notifications only request a //! reconciliation; durable ownership supplies the results and consumption precedes ACK. use super::{TaskEnd, TaskLedger}; +use std::collections::BTreeSet; use std::num::NonZeroUsize; use uuid::Uuid; /// Implemented by the owner of the recipient's durable state, never by a transient /// workspace or a notification channel. Success means the exact terminal result and -/// its outstanding wake obligation are durable. Replays must deduplicate by task ID. +/// its outstanding wake obligation are durable. Returned IDs attest checkpointed +/// perception, not filing, and must belong to this page. Replays deduplicate by ID. /// Consume the owner page in one commit; per-result checkpoints amplify storage work. #[async_trait::async_trait] pub trait TaskOwnerSink: Send + Sync { type Error: std::error::Error + Send + Sync + 'static; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error>; + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error>; } /// Failure retains its boundary: a sink refusal cannot masquerade as an ACK failure, @@ -21,6 +23,7 @@ pub trait TaskOwnerSink: Send + Sync { pub enum DeliveryError { Read(String), Consume { owner: Uuid, source: E }, + InvalidReceipt { task: Uuid }, Acknowledge { task: Uuid, message: String }, } @@ -34,6 +37,7 @@ impl std::fmt::Display for DeliveryError { Self::Acknowledge { task, message } => { write!(f, "task {task} acknowledgement failed: {message}") } + Self::InvalidReceipt { task } => write!(f, "perception receipt for task {task} is outside the delivered page"), } } } @@ -42,7 +46,7 @@ impl std::error::Error for DeliveryError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Consume { source, .. } => Some(source), - Self::Read(_) | Self::Acknowledge { .. } => None, + Self::Read(_) | Self::Acknowledge { .. } | Self::InvalidReceipt { .. } => None, } } } @@ -69,13 +73,20 @@ impl TaskLedger { .pending_page(owner, after, limit) .await .map_err(DeliveryError::Read)?; - if !page.ends.is_empty() { + let perceived = if page.ends.is_empty() { + BTreeSet::new() + } else { sink.consume(owner, &page.ends) .await - .map_err(|source| DeliveryError::Consume { owner, source })?; + .map_err(|source| DeliveryError::Consume { owner, source })? + }; + let offered: BTreeSet<_> = page.ends.iter().map(|(task, _)| *task).collect(); + // Validate the entire receipt before acknowledging any row. + if let Some(task) = perceived.difference(&offered).next() { + return Err(DeliveryError::InvalidReceipt { task: *task }); } let mut acknowledged = 0; - for (task, _) in page.ends { + for task in perceived { self.acknowledge(task, owner) .await .map_err(|message| DeliveryError::Acknowledge { task, message })?; diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs index c4f96516a3..b68fa7c80c 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -6,6 +6,42 @@ use std::sync::{ Arc, }; +struct PerceptionSink(parking_lot::Mutex>); + +#[async_trait::async_trait] +impl TaskOwnerSink for PerceptionSink { + type Error = std::io::Error; + + async fn consume(&self, _: Uuid, _: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + Ok(self.0.lock().clone()) + } +} + +#[tokio::test] +async fn only_page_scoped_perception_can_ack_and_invalid_batch_has_no_partial_effects( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let first = ledger.accept(owner, "first".into()).await?; + let second = ledger.accept(owner, "second".into()).await?; + ledger.finish(first, owner, TaskEnd::Stopped).await?; + ledger.finish(second, owner, TaskEnd::Lost).await?; + let sink = PerceptionSink(Default::default()); + let limit = NonZeroUsize::new(32).ok_or("invalid fixture page")?; + assert_eq!(ledger.deliver_page(owner, None, limit, &sink).await?.acknowledged, 0); + let foreign = Uuid::new_v4(); + sink.0.lock().extend([first, foreign]); + assert!(matches!(ledger.deliver_page(owner, None, limit, &sink).await, + Err(DeliveryError::InvalidReceipt { task }) if task == foreign)); + assert_eq!(ledger.pending(first, owner).await?, Some(TaskEnd::Stopped)); + sink.0.lock().remove(&foreign); + assert_eq!(ledger.deliver_page(owner, None, limit, &sink).await?.acknowledged, 1); + assert_eq!(ledger.pending(first, owner).await?, None); + assert_eq!(ledger.pending(second, owner).await?, Some(TaskEnd::Lost)); + Ok(()) +} + struct Sink { ledger: Arc, refuse: AtomicBool, @@ -17,7 +53,7 @@ struct Sink { impl TaskOwnerSink for Sink { type Error = std::io::Error; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { for (task, end) in ends { let pending = self .ledger @@ -33,7 +69,7 @@ impl TaskOwnerSink for Sink { self.seen .lock() .extend(ends.iter().map(|(task, end)| (owner, *task, end.clone()))); - Ok(()) + Ok(ends.iter().map(|(task, _)| *task).collect()) } } diff --git a/core/continuum-mind/src/modules/cognition/task_delivery.rs b/core/continuum-mind/src/modules/cognition/task_delivery.rs index e100ffd6d1..7eabd92084 100644 --- a/core/continuum-mind/src/modules/cognition/task_delivery.rs +++ b/core/continuum-mind/src/modules/cognition/task_delivery.rs @@ -88,11 +88,11 @@ mod tests { #[async_trait::async_trait] impl TaskOwnerSink for Sink { type Error = std::io::Error; - async fn consume(&self, owner: Uuid, _: &[(Uuid, TaskEnd)]) -> Result<(), Self::Error> { + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { if owner == self.refused && self.refuse.load(Ordering::SeqCst) { Err(std::io::Error::other("injected owner refusal")) } else { - Ok(()) + Ok(ends.iter().map(|(task, _)| *task).collect()) } } } From 0da6e8e738364ce672f6db7c3618a75d74798304 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 07:18:59 -0500 Subject: [PATCH 45/88] fix(tasks): render durable ends with the shared task line --- .../src/cognition/context_streams/tasks.rs | 40 ++++++++++++++++--- .../tests/task_consumption.rs | 2 +- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs index 10d70a49ab..fd22ea4e3b 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tasks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -35,6 +35,14 @@ pub(crate) struct Tasks<'a> { pub persona: uuid::Uuid, } +fn task_line(task: uuid::Uuid, word: &str, label: Option<&str>) -> String { + let line = format!("{word} task {}", airc_core::shown_id::shown_form(task)); + match label { + Some(label) if !label.is_empty() => format!("{line} {label}"), + _ => line, + } +} + impl Source for Tasks<'_> { fn name(&self) -> &str { "tasks" @@ -47,7 +55,10 @@ impl Source for Tasks<'_> { fn items(&self) -> Vec> { let terminals = self.memory.task_terminals(); let terminal_ids: std::collections::BTreeSet<_> = terminals.iter().map(|end| end.task).collect(); - let tasks: Vec<_> = self.memory.dispatched_snapshot().into_iter() + let dispatched = self.memory.dispatched_snapshot(); + let labels: std::collections::BTreeMap<_, _> = dispatched.iter() + .map(|(task, label, ..)| (*task, label.clone())).collect(); + let tasks: Vec<_> = dispatched.into_iter() .filter(|(task, ..)| !terminal_ids.contains(task)).collect(); if tasks.is_empty() && !terminals.iter().any(|end| end.wake_pending) { return Vec::new(); @@ -65,7 +76,7 @@ impl Source for Tasks<'_> { DispatchStatus::Done => "ok", DispatchStatus::Failed => "failed", }; - let line = format!("{word} task {} {label}", airc_core::shown_id::shown_form(task)); + let line = task_line(task, word, Some(&label)); let whole = if output.is_empty() { line.clone() } else { format!("{line}\n{output}") }; let summary = summarize(&output, Shape::Output).map(|level| ContextMessage::user(format!("{line}\n{level}"))); Item::whole(task_element(self.persona, task, &status), Cause::Root(Origin::ActivityStart), task.to_string(), ContextMessage::user(whole)) @@ -74,15 +85,15 @@ impl Source for Tasks<'_> { })); items.extend(terminals.into_iter().filter(|end| end.wake_pending).map(|end| { let status = match end.state { - TaskEndState::Done => "done", + TaskEndState::Done => "ok", TaskEndState::Failed => "failed", - TaskEndState::TimedOut => "timed out", + TaskEndState::TimedOut => "timed_out", TaskEndState::Stopped => "stopped", TaskEndState::Lost => "lost", }; // This item is the terminal notification, not a projection claiming // to contain the ledger's output. Its identity binds that exact end. - let line = ContextMessage::user(format!("{status} task {}", end.task)); + let line = ContextMessage::user(task_line(end.task, status, labels.get(&end.task).map(String::as_str))); Item::whole(terminal_element(self.persona, end.task, &end.fingerprint), Cause::Root(Origin::ActivityStart), end.task.to_string(), line.clone()) .with_pointer(line) @@ -96,6 +107,25 @@ mod tests { use super::*; use continuum_context::epoch::Block; + #[test] + fn terminal_replaces_dispatch_in_the_same_shape_and_keeps_known_label() { + use continuum_kernel::runtime::tasks::{TaskEnd, TaskOutput}; + let memory = WorkingMemory::new(8); + let persona = uuid::Uuid::new_v4(); + let task = uuid::Uuid::new_v4(); + memory.record_dispatch_event(task, "compile core", "working", DispatchStatus::Running); + memory.stage_task_end(task, TaskEnd::Done(TaskOutput::Json(serde_json::json!({"ok": true})))).expect("fixture terminal"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + let items = Tasks { memory: &memory, persona }.items(); + let expected = format!("ok task {} compile core", airc_core::shown_id::shown_form(task)); + assert_eq!(items.iter().filter(|item| item.full().text == expected).count(), 1); + assert!(items.iter().all(|item| !item.full().text.contains("running task"))); + let restored = WorkingMemory::new(8); + restored.restore(memory.snapshot()); + let expected = format!("ok task {}", airc_core::shown_id::shown_form(task)); + assert!(Tasks { memory: &restored, persona }.items().iter().any(|item| item.full().text == expected)); + } + #[test] fn dispatch_has_one_source_even_when_thoughts_are_present() { let memory = WorkingMemory::new(8); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index 9096b6d617..c5af32654b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -21,7 +21,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( let (view, _) = View::::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { claims.iter().map(|claim| claim.full_chars).collect() })?; - assert!(view.render().any(|message| message.text.contains("timed out task"))); + assert!(view.render().any(|message| message.text.contains("timed_out task"))); let mut receipt = crate::cognition::render_receipt::RenderReceipt { owner, incarnation: memory.incarnation(), request: "submitted-request".to_owned(), view: view.receipt(), }; From 44493e5f1862ed715add6247e5be84e4087c8b25 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 07:26:37 -0500 Subject: [PATCH 46/88] fix(academy): retain complete answers for grade-time lessons --- .../src/cognition/eval/default_eval_set.rs | 7 ------- core/continuum-academy/src/cognition/eval/eval_settle.rs | 2 +- .../src/cognition/eval/eval_task_result.rs | 6 +++--- core/continuum-academy/src/cognition/eval/run_pass.rs | 4 ++-- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/core/continuum-academy/src/cognition/eval/default_eval_set.rs b/core/continuum-academy/src/cognition/eval/default_eval_set.rs index 106cc65114..976b25ee85 100644 --- a/core/continuum-academy/src/cognition/eval/default_eval_set.rs +++ b/core/continuum-academy/src/cognition/eval/default_eval_set.rs @@ -153,13 +153,6 @@ where /// step over — the living persona's lane. pub(super) const EVAL_LANE_BASE_PORT: u16 = 58_200; -/// How much of a graded answer to persist in the result. A coder answer (code + reasoning) -/// fits far under this; the generous bound exists ONLY to cap a pathological loop-to-length -/// generation (which is captured up to here, still a diagnosable signal). The old 200-char -/// cap stored only the preamble and blinded every failure diagnosis + correction-corpus mine. -// context-budget-exempt: observability: how much of an answer is CAPTURED into the run ledger for humans, never text sent to a model -pub(super) const ANSWER_CAPTURE_CHARS: usize = 24_000; - /// Per-task detail retained in the DURABLE run ledger row (`append_progress_ledger`). /// The ledger stored only the summary (score/total), so a detached run's per-task /// verdicts were unrecoverable — a webdev pass/fail could not be glass-boxed after the diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index ec88d8730a..3ed362d654 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -180,7 +180,7 @@ pub(super) async fn run_pass_team( ok, grade, acts, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: m.latency_ms, output_tokens: m.output_tokens, tokens_per_second: m.tokens_per_second(), diff --git a/core/continuum-academy/src/cognition/eval/eval_task_result.rs b/core/continuum-academy/src/cognition/eval/eval_task_result.rs index cc408ec3a1..0712c2a636 100644 --- a/core/continuum-academy/src/cognition/eval/eval_task_result.rs +++ b/core/continuum-academy/src/cognition/eval/eval_task_result.rs @@ -15,9 +15,9 @@ pub struct EvalTaskResult { /// the act budget mid-action — an honest "did not finish", never fabricated). For a /// coder exam the answer IS the code, so this must carry the whole thing: a 200-char /// cap stored only the "Sure, I can help..." preamble and made every failure - /// undiagnosable AND un-minable for a correction corpus (2026-07-21). Bounded by - /// ANSWER_CAPTURE_CHARS against a pathological loop-to-length, which is itself a - /// signal worth capturing up to the cap. + /// undiagnosable AND un-minable for a correction corpus (2026-07-21). Retain the + /// complete answer for the grade-time lesson sink; storage policy cannot cut + /// the evidence before that consumer receives it. pub answer: String, /// Wall-clock latency to SETTLE this task: the summed deliberation-generation /// time across every act→observe tick (the model's own measured request time, diff --git a/core/continuum-academy/src/cognition/eval/run_pass.rs b/core/continuum-academy/src/cognition/eval/run_pass.rs index 24e68cea18..b319af78c1 100644 --- a/core/continuum-academy/src/cognition/eval/run_pass.rs +++ b/core/continuum-academy/src/cognition/eval/run_pass.rs @@ -586,7 +586,7 @@ Fix the workspace and finish — the grade reads th ok: false, grade: format!("infra (DoD could not run, NOT a wrong answer): {reason}"), acts: settled.acts as u32, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: settled.metrics.latency_ms, output_tokens: settled.metrics.output_tokens, tokens_per_second: settled.metrics.tokens_per_second(), @@ -709,7 +709,7 @@ Fix the workspace and finish — the grade reads th ok, grade, acts: total_acts, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: m.latency_ms, output_tokens: m.output_tokens, tokens_per_second: m.tokens_per_second(), From 627d17f1f039bc52013090ceef83bbf8d3212d92 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 07:35:45 -0500 Subject: [PATCH 47/88] fix(tests): remove obsolete Faculty import after canary merge --- .../src/test_env/mind_integration/training_credit/directed.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index f8308553e7..cd5d6b3de0 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -7,7 +7,7 @@ use crate::ai::types::ToolCall; use crate::cognition::act_observe::test_support::{admission, body_with_wm, ScriptedExecutor}; use crate::cognition::act_observe::*; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::workspace::{Faculty, SalienceArbiter, TurnFraming, WorkspaceCycle}; +use crate::cognition::workspace::{SalienceArbiter, TurnFraming, WorkspaceCycle}; // what this catches:41f4e3ef — a directed drive must persist real receipt-linked // progress before settlement; cancellation/rollback cannot lose the last whole From 4656b9ad47294882d636d44870243d59c92f12b9 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 08:46:01 -0500 Subject: [PATCH 48/88] Remove independent heuristic echo clipping and digest truncation --- .../src/ai/heuristic_adapter.rs | 27 +++++-------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/core/continuum-engine/src/ai/heuristic_adapter.rs b/core/continuum-engine/src/ai/heuristic_adapter.rs index e4b0bfdbd6..ccc7dab638 100644 --- a/core/continuum-engine/src/ai/heuristic_adapter.rs +++ b/core/continuum-engine/src/ai/heuristic_adapter.rs @@ -26,7 +26,7 @@ //! //! ### What the response looks like //! -//! `[heuristic:<8-char-hash>] ack: ""` +//! `[heuristic:] ack: ""` //! //! Enough to prove (a) the inference command surface is wired, //! (b) the prompt actually reached the adapter, (c) the response is @@ -69,11 +69,6 @@ pub const HEURISTIC_PROVIDER_ID: &str = "heuristic"; /// adapter handled the request. pub const HEURISTIC_DEFAULT_MODEL: &str = "heuristic-echo-v1"; -/// Echo length cap — last N chars of the most recent user message -/// surfaces in the response. -// context-budget-exempt: a TEST-ONLY canned adapter's echo width (gated behind test-fixtures); never a live bound -const ECHO_CHARS: usize = 200; - /// The adapter struct itself. No mutable state, no clock access, no /// external resources — instances are cheap and interchangeable. /// @@ -226,7 +221,7 @@ impl HeuristicInferenceAdapter { String::new() } - /// Compute a deterministic 8-char hex prefix tying the response + /// Compute a deterministic SHA-256 fingerprint tying the response /// to its inputs. Same canonical inputs → same hash → same /// response text. This is the replay contract. fn determinism_prefix(req: &TextGenerationRequest) -> String { @@ -267,8 +262,7 @@ impl HeuristicInferenceAdapter { } } let digest = hasher.finalize(); - let hex: String = digest.iter().take(4).map(|b| format!("{b:02x}")).collect(); - hex + format!("{digest:x}") } /// Build the response text from the request. Pure function — @@ -287,15 +281,7 @@ impl HeuristicInferenceAdapter { /// algorithms." pub fn build_response_text(req: &TextGenerationRequest) -> String { let prefix = Self::determinism_prefix(req); - let last = Self::last_user_text(&req.messages); - let echoed: String = last - .chars() - .rev() - .take(ECHO_CHARS) - .collect::() - .chars() - .rev() - .collect(); + let echoed = Self::last_user_text(&req.messages); let plain = if echoed.is_empty() { format!("[heuristic:{prefix}] ack: (no user text in prompt)") } else { @@ -622,18 +608,19 @@ mod tests { #[tokio::test] async fn response_echoes_last_user_message_with_heuristic_prefix() { + let latest = format!("keep the beginning {} and the end", "wide unicode 界".repeat(40)); let adapter = HeuristicInferenceAdapter::new(); let resp = adapter .generate_text(req_with(vec![ system_msg("you are nice"), user_msg("first question"), assistant_msg("first answer"), - user_msg("second question — please answer this"), + user_msg(&latest), ])) .await .unwrap(); assert!( - resp.text.contains("second question — please answer this"), + resp.text.contains(&latest), "must echo the LATEST user message, got: {}", resp.text ); From 87d7bbff41c5592317de4375dd7a64f4d8b26b43 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 09:28:01 -0500 Subject: [PATCH 49/88] fix(cognition): use shared gateway admission for responses --- .../src/cognition/generate_response.rs | 136 +----------------- .../src/cognition/generate_response/tests.rs | 125 +--------------- .../GenerateResponseAdmissionPolicy.ts | 9 -- .../cognition/GenerateResponseRequest.ts | 9 +- protocol/typescript/cognition/index.ts | 1 - protocol/typescript/index.ts | 1 - 6 files changed, 4 insertions(+), 277 deletions(-) delete mode 100644 protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts diff --git a/core/continuum-cognition/src/cognition/generate_response.rs b/core/continuum-cognition/src/cognition/generate_response.rs index 17d7d75a39..2337a70b8f 100644 --- a/core/continuum-cognition/src/cognition/generate_response.rs +++ b/core/continuum-cognition/src/cognition/generate_response.rs @@ -1,6 +1,6 @@ //! Rust-owned response-generation prompt assembly and admission. //! -//! Rust owns response admission, the response-generation contract, +//! The shared inference gateway owns admission. This module owns the contract, //! prompt assembly, and the identity-reminder template. Host runtimes //! may be native Rust, game/live loops, AIRC daemons, or wrappers around //! those hosts; none of them own cognition slot coordination for this @@ -39,14 +39,10 @@ use crate::ai::adapter::InferenceDevice; use crate::ai::types::ResponseFormat; use crate::ai::{ChatMessage, MessageContent, TextGenerationRequest, TextGenerationResponse}; -use crate::resources::throughput_class::{ResourceClass, TargetSilicon}; -use crate::inference::resource_admission::{ResourceAdmissionError, ResourceAdmissionGate, ResourceAdmissionGuard, ResourceAdmissionPolicy, ResourceAdmissionRequest}; use crate::cognition::should_respond::AIDecisionContext; -use crate::resources::throughput_lease::ThroughputLeaseRevocationPolicy; use crate::ai::adapter::global_registry; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use std::sync::LazyLock; use std::time::Duration; use ts_rs::TS; @@ -83,28 +79,6 @@ const DEFAULT_GENERATE_TEMPERATURE: f32 = 0.7; /// ceiling before `tokio::time::timeout` returns Err. const DEFAULT_GENERATE_TIMEOUT_MS: u64 = 180_000; -/// Conservative default for local response generation while the -/// substrate-governor bridge becomes the source of these numbers. -const DEFAULT_GENERATE_MAX_CONCURRENCY: usize = 4; - -/// Cost-unit budget paired with [`DEFAULT_GENERATE_MAX_CONCURRENCY`]. -const DEFAULT_GENERATE_MAX_COST_UNITS: u32 = 4; - -/// One response generation claims one local-generation cost unit unless -/// the caller provides a stricter policy. -const DEFAULT_GENERATE_COST_UNITS: u32 = 1; - -/// Lease TTL must outlive the generation timeout so slow-but-valid work -/// is not marked reclaimable before `tokio::time::timeout` fires. -const DEFAULT_GENERATE_LEASE_TTL_PAD_MS: u64 = 5_000; - -static GENERATE_RESPONSE_ADMISSION: LazyLock = - LazyLock::new(ResourceAdmissionGate::new); - -#[cfg(test)] -static GENERATE_RESPONSE_TEST_LOCK: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(())); - // ─── IPC request + response shapes ──────────────────────────────────── /// IPC request: ask the cognition service to assemble a response-prompt @@ -139,55 +113,6 @@ pub struct GenerateResponseRequest { #[ts(optional)] #[ts(optional, type = "number")] pub timeout_ms: Option, - /// Rust-owned admission policy for this generation. When omitted, - /// `evaluate_response` applies the local-generation defaults above. - /// Hosts that know tighter resource limits should pass them here; - /// they should not coordinate slots outside Rust. - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub admission: Option, -} - -/// Per-call local-generation admission policy. This is the contract a -/// host uses to ask Rust for response-generation capacity instead of -/// owning slots itself. -#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq, schemars::JsonSchema)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts" -)] -pub struct GenerateResponseAdmissionPolicy { - pub target_silicon: TargetSilicon, - pub max_concurrency: usize, - pub max_cost_units: u32, - pub cost_units: u32, - #[ts(type = "number")] - pub lease_ttl_ms: u64, -} - -impl GenerateResponseAdmissionPolicy { - fn with_timeout(timeout_ms: u64) -> Self { - Self { - target_silicon: TargetSilicon::UnifiedMemory, - max_concurrency: DEFAULT_GENERATE_MAX_CONCURRENCY, - max_cost_units: DEFAULT_GENERATE_MAX_COST_UNITS, - cost_units: DEFAULT_GENERATE_COST_UNITS, - lease_ttl_ms: timeout_ms.saturating_add(DEFAULT_GENERATE_LEASE_TTL_PAD_MS), - } - } - - fn into_resource_policy(self) -> ResourceAdmissionPolicy { - ResourceAdmissionPolicy { - resource_class: ResourceClass::LocalGeneration, - target_silicon: self.target_silicon, - max_concurrency: self.max_concurrency, - max_cost_units: self.max_cost_units, - cost_units: self.cost_units, - lease_ttl_ms: self.lease_ttl_ms, - revocation_policy: ThroughputLeaseRevocationPolicy::Graceful, - } - } } /// IPC response: generated text plus timing + token telemetry. @@ -228,16 +153,6 @@ pub struct TokenUsage { /// the Rust caller decides policy explicitly. #[derive(Debug, thiserror::Error)] pub enum GenerateResponseError { - /// Rust admission denied this response before inference began. - /// Hosts ask Rust, receive a typed denial, and retry/replan explicitly. - #[error( - "response generation admission denied for persona={persona_id:?} room={room_id:?}: {reason}" - )] - AdmissionDenied { - persona_id: String, - room_id: String, - reason: String, - }, /// The provider registry had no adapter capable of serving this /// model + provider tuple. No alternate runtime is attempted. #[error("no AI adapter available for provider={provider:?} model={model:?}")] @@ -279,7 +194,7 @@ pub async fn evaluate_response( ) -> Result { let start_ms = continuum_base::time::EpochMs::now().millis(); let timeout_ms = request.timeout_ms.unwrap_or(DEFAULT_GENERATE_TIMEOUT_MS); - let _lease = acquire_generate_response_lease(&request, start_ms, timeout_ms)?; + // The llama-server adapter owns admission through the shared turn gateway. // Bind this turn to the persona's ESTABLISHED inference handle (reused across // turns, re-homed if lost — self-healing), bound to the model the engine actually @@ -352,53 +267,6 @@ pub async fn evaluate_response( Ok(result_from_response(response, model, start_ms, end_ms)) } -fn acquire_generate_response_lease( - request: &GenerateResponseRequest, - now_ms: u64, - timeout_ms: u64, -) -> Result { - let policy = request - .admission - .clone() - .unwrap_or_else(|| GenerateResponseAdmissionPolicy::with_timeout(timeout_ms)); - - GENERATE_RESPONSE_ADMISSION - .acquire(ResourceAdmissionRequest { - lease_id: generate_response_lease_id(&request.context, now_ms), - artifact_key: generate_response_artifact_key(&request.context), - holder_id: request.context.persona_id.clone(), - policy: policy.into_resource_policy(), - now_ms, - }) - .map_err(|err| GenerateResponseError::AdmissionDenied { - persona_id: request.context.persona_id.clone(), - room_id: request.context.room_id.clone(), - reason: format_resource_admission_error(err), - }) -} - -fn generate_response_lease_id(context: &AIDecisionContext, now_ms: u64) -> String { - format!( - "cognition/generate-response:{}:{}:{}", - context.room_id, context.persona_id, now_ms - ) -} - -fn generate_response_artifact_key(context: &AIDecisionContext) -> String { - format!( - "cognition/generate-response:{}:{}:{}", - context.room_id, context.persona_id, context.trigger_message.id - ) -} - -fn format_resource_admission_error(err: ResourceAdmissionError) -> String { - match err { - ResourceAdmissionError::InvalidPolicy { reason } - | ResourceAdmissionError::Denied { reason } - | ResourceAdmissionError::Lease { reason } => reason, - } -} - /// Build the `TextGenerationRequest` the adapter consumes. /// Pure: caller passes `request`, `model`, and the start-timestamp so /// tests can assert the request shape without time interference. diff --git a/core/continuum-cognition/src/cognition/generate_response/tests.rs b/core/continuum-cognition/src/cognition/generate_response/tests.rs index e0c2c681c1..446e7c8342 100644 --- a/core/continuum-cognition/src/cognition/generate_response/tests.rs +++ b/core/continuum-cognition/src/cognition/generate_response/tests.rs @@ -418,134 +418,11 @@ fn request_with_overrides( temperature: temp, max_tokens: max, timeout_ms: timeout, - admission: None, } } -fn request_with_admission( - context: AIDecisionContext, - admission: GenerateResponseAdmissionPolicy, -) -> GenerateResponseRequest { - GenerateResponseRequest { - context, - model: None, - temperature: None, - max_tokens: None, - timeout_ms: Some(100), - admission: Some(admission), - } -} - -fn admission( - max_concurrency: usize, - max_cost_units: u32, - cost_units: u32, -) -> GenerateResponseAdmissionPolicy { - GenerateResponseAdmissionPolicy { - target_silicon: TargetSilicon::UnifiedMemory, - max_concurrency, - max_cost_units, - cost_units, - lease_ttl_ms: 1_000, - } -} - -fn reset_generate_response_leases_for_test() { - GENERATE_RESPONSE_ADMISSION.reset_for_test(); -} - -fn lock_generate_response_tests() -> std::sync::MutexGuard<'static, ()> { - GENERATE_RESPONSE_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn active_generate_response_leases_for_test(now_ms: u64) -> usize { - GENERATE_RESPONSE_ADMISSION.active_count_for_test(now_ms) -} - -/// What this catches: response admission is Rust-owned. A successful -/// acquire claims a local-generation lease, and dropping the RAII -/// guard releases it. The same drop path is what runs when -/// `evaluate_response` exits via success, provider error, missing -/// adapter, or timeout. -#[test] -fn rust_admission_guard_releases_local_generation_lease_on_exit() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let request = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(4, 4, 1)); - - { - let _guard = acquire_generate_response_lease(&request, 1_000, 100) - .expect("valid request should acquire a Rust lease"); - assert_eq!(active_generate_response_leases_for_test(1_001), 1); - } - - assert_eq!( - active_generate_response_leases_for_test(1_002), - 0, - "dropping the guard must release the local-generation lease" - ); -} - -/// What this catches: Rust denies over-capacity response generation -/// before any provider call. This is the hard boundary that keeps -/// host wrappers from owning cognition slots. -#[test] -fn rust_admission_denies_concurrency_and_cost_pressure() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let first = request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 4, 1)); - let second = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 4, 1)); - let _held = acquire_generate_response_lease(&first, 2_000, 100) - .expect("first request should fit the policy"); - - let err = acquire_generate_response_lease(&second, 2_001, 100) - .expect_err("second request must be denied by Rust concurrency policy"); - assert!(matches!( - err, - GenerateResponseError::AdmissionDenied { reason, .. } - if reason.contains("max_concurrency=1") - )); - - reset_generate_response_leases_for_test(); - let expensive = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(4, 2, 3)); - let err = acquire_generate_response_lease(&expensive, 3_000, 100) - .expect_err("request whose cost exceeds policy must be denied"); - assert!(matches!( - err, - GenerateResponseError::AdmissionDenied { reason, .. } - if reason.contains("cost_units=3 exceeds max_cost_units=2") - )); -} - -/// What this catches: expired leases are reaped during Rust -/// admission, so a dead holder does not permanently block the -/// local-generation lane. -#[test] -fn rust_admission_reaps_expired_generation_leases() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let request = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 1, 1)); - let guard = acquire_generate_response_lease(&request, 4_000, 100) - .expect("first request should fit the policy"); - std::mem::forget(guard); - - assert_eq!(active_generate_response_leases_for_test(4_001), 1); - let replacement = acquire_generate_response_lease(&request, 5_001, 100) - .expect("expired forgotten lease should be reaped before admission"); - replacement - .release() - .expect("explicit release should return the replacement lease"); - assert_eq!(active_generate_response_leases_for_test(5_002), 0); -} - /// What this catches: defaults — no overrides — produces a -/// TextGenerationRequest with provider="local", model=Qwen-default, +/// TextGenerationRequest routed to the llama-server gateway with an explicit model, /// temperature=0.7, max_tokens=None (the model owns its length), /// response_format=Text, purpose="cognition/generate-response", and /// persona/room attribution carried from the context. Pins the wire diff --git a/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts b/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts deleted file mode 100644 index 94d4506a83..0000000000 --- a/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TargetSilicon } from "./TargetSilicon"; - -/** - * Per-call local-generation admission policy. This is the contract a - * host uses to ask Rust for response-generation capacity instead of - * owning slots itself. - */ -export type GenerateResponseAdmissionPolicy = { targetSilicon: TargetSilicon, maxConcurrency: number, maxCostUnits: number, costUnits: number, leaseTtlMs: number, }; diff --git a/protocol/typescript/cognition/GenerateResponseRequest.ts b/protocol/typescript/cognition/GenerateResponseRequest.ts index d5d22853e3..7f9cc8023b 100644 --- a/protocol/typescript/cognition/GenerateResponseRequest.ts +++ b/protocol/typescript/cognition/GenerateResponseRequest.ts @@ -1,6 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AIDecisionContext } from "./AIDecisionContext"; -import type { GenerateResponseAdmissionPolicy } from "./GenerateResponseAdmissionPolicy"; /** * IPC request: ask the cognition service to assemble a response-prompt @@ -31,10 +30,4 @@ maxTokens?: number, * returning timeout. */ timeoutMs?: number, -/** - * Rust-owned admission policy for this generation. When omitted, - * `evaluate_response` applies the local-generation defaults above. - * Hosts that know tighter resource limits should pass them here; - * they should not coordinate slots outside Rust. - */ -admission?: GenerateResponseAdmissionPolicy, }; +}; diff --git a/protocol/typescript/cognition/index.ts b/protocol/typescript/cognition/index.ts index ebc867f29a..eb209a86f9 100644 --- a/protocol/typescript/cognition/index.ts +++ b/protocol/typescript/cognition/index.ts @@ -59,7 +59,6 @@ export type { GatingRagMetadata } from './GatingRagMetadata'; export type { GatingRecipeStrategy } from './GatingRecipeStrategy'; export type { GatingTriggerMessage } from './GatingTriggerMessage'; export type { GenerateRecipeOrchestratorParams } from './GenerateRecipeOrchestratorParams'; -export type { GenerateResponseAdmissionPolicy } from './GenerateResponseAdmissionPolicy'; export type { GenerateResponseRequest } from './GenerateResponseRequest'; export type { GenerateResponseResult } from './GenerateResponseResult'; export type { GetStateParams } from './GetStateParams'; diff --git a/protocol/typescript/index.ts b/protocol/typescript/index.ts index dc69fc7663..d3c9852758 100644 --- a/protocol/typescript/index.ts +++ b/protocol/typescript/index.ts @@ -53,7 +53,6 @@ export type { GatingRagContext } from './cognition'; export type { GatingRagMetadata } from './cognition'; export type { GatingRecipeStrategy } from './cognition'; export type { GatingTriggerMessage } from './cognition'; -export type { GenerateResponseAdmissionPolicy } from './cognition'; export type { GenerateResponseRequest } from './cognition'; export type { GenerateResponseResult } from './cognition'; export type { HostCapability } from './cognition'; From 17e83266f1867d4a19061d1f374fb11a9eb727bb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 09:35:36 -0500 Subject: [PATCH 50/88] fix(protocol): match executed response binding export --- protocol/typescript/cognition/GenerateResponseRequest.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/protocol/typescript/cognition/GenerateResponseRequest.ts b/protocol/typescript/cognition/GenerateResponseRequest.ts index 7f9cc8023b..12b7961ee1 100644 --- a/protocol/typescript/cognition/GenerateResponseRequest.ts +++ b/protocol/typescript/cognition/GenerateResponseRequest.ts @@ -29,5 +29,4 @@ maxTokens?: number, * Hard cap on how long PR-2's async composer waits before * returning timeout. */ -timeoutMs?: number, -}; +timeoutMs?: number, }; From 8b66ddf8c112131541ca6184d1a6ac6f8a6975f7 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 09:55:45 -0500 Subject: [PATCH 51/88] test(core): remove retired response admission ID declarations --- core/continuum-core/src/test_env/loose_id_guard.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/continuum-core/src/test_env/loose_id_guard.rs b/core/continuum-core/src/test_env/loose_id_guard.rs index affa5b739e..ae3ef7777b 100644 --- a/core/continuum-core/src/test_env/loose_id_guard.rs +++ b/core/continuum-core/src/test_env/loose_id_guard.rs @@ -57,8 +57,6 @@ const LOOSE_IDS: &[LooseId] = &[ LooseId { file: "cognition/eval/eval_task_result.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/eval/fork_eval_cycle_waiting.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/eval/format_exam_lesson.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, - LooseId { file: "cognition/generate_response.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, - LooseId { file: "cognition/generate_response.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/replay.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/should_respond.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/should_respond.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, From 1773b1b9c9308f42c0f32b04613c2a9145715434 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 10:06:22 -0500 Subject: [PATCH 52/88] test(cognition): repeated task receipt cannot acknowledge an end --- .../cognition/persona_workspace/tests/task_consumption.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index c5af32654b..d87fcc6377 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -40,6 +40,13 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( for item in &mut receipt.view.items { item.level = continuum_context::level::Level::Folded; } assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); + for item in &mut receipt.view.items { + let of = item.element.ok_or("terminal receipt lacks element")?; + item.level = continuum_context::level::Level::Repeat { of }; + } + assert!(sink.record_rendered(receipt).await?.is_none()); + assert_eq!(memory.pending_task_wakes(), vec![task], "repeat is not a newly perceived terminal end"); + receipt = exact.clone(); for item in &mut receipt.view.items { item.retired = true; } assert!(sink.record_rendered(receipt).await?.is_none()); assert_eq!(memory.pending_task_wakes(), vec![task]); From 3ad42bf644d29f508d5c819487c1679f711b5a8f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 10:55:24 -0500 Subject: [PATCH 53/88] A checkpoint's context view is derived: one that no longer decodes is dropped with a probe and her next act opens a new epoch, instead of refusing the resident (the 2026-10-31 M5 outage: #5639's new Event.level made every checkpoint undecodable; 32 min with no resident) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/working_memory.rs | 7 +++-- .../cognition/working_memory/derived_view.rs | 29 +++++++++++++++++++ .../cognition/working_memory/tests/trail.rs | 21 ++++++++++++++ 3 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/working_memory/derived_view.rs diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 4704878d98..ecf1588731 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -426,9 +426,9 @@ pub struct VolatileSnapshot { /// for another build: this is the first version, Joel 2026-10-31). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) actions: Vec, - /// Her context view ([`WorkingMemory`]'s `view`). Absent on snapshots written before it, - /// and then her first act after the restore starts a new one. - #[serde(default, skip_serializing_if = "Option::is_none")] + /// Her context view ([`WorkingMemory`]'s `view`), derived: absent, or no longer decodable + /// (`derived_view`), her first act after the restore starts a new one. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "derived_view::or_new_epoch")] pub(crate) context_view: Option, /// Each retained receipt's per-call dependencies ([`WorkingMemory`]'s `receipt_children`), /// so a restart keeps what a restored receipt points at reachable. Empty on snapshots @@ -600,6 +600,7 @@ pub struct WmEntry { } +mod derived_view; mod action_log; mod continuity; mod ledger; diff --git a/core/continuum-cognition/src/cognition/working_memory/derived_view.rs b/core/continuum-cognition/src/cognition/working_memory/derived_view.rs new file mode 100644 index 0000000000..8b5e3c0454 --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_memory/derived_view.rs @@ -0,0 +1,29 @@ +//! A checkpoint's context view is DERIVED: her view is re-rendered at a new epoch from her working +//! memory, so it is a cache of what she last saw, never the record of it. A view that no longer +//! decodes (its shape changed in a later build) is dropped like an absent one, with a probe, and her +//! next act opens a new epoch. It never fails the checkpoint it rides in: on 2026-10-31 a new field on +//! the view's events (#5639) made every resident's checkpoint undecodable and the M5 hosted no one +//! for 32 minutes ("workspace registration failed: missing field `level`"). Nothing old is read here; +//! the stale view is discarded. + +use serde::{Deserialize, Deserializer}; + +use super::ContextView; + +/// `context_view`'s deserializer: the view when it decodes, else none (and a probe saying why). +pub(crate) fn or_new_epoch<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let Some(raw) = Option::::deserialize(deserializer)? else { + return Ok(None); + }; + match serde_json::from_value::(raw) { + Ok(view) => Ok(Some(view)), + Err(error) => { + continuum_base::probe!( + class = "persona.checkpoint.view_dropped", + error = %error, + "a checkpoint's context view no longer decodes (its shape changed); it is derived, so it is dropped and her next act opens a new epoch" + ); + Ok(None) + } + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 470361f018..722baf654c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -289,3 +289,24 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { "no fabricated save age on legacy snapshots: {q:?}" ); } + +// what this catches: a checkpoint whose context view no longer decodes (the view's shape changed in +// a later build) refusing the whole restore. On 2026-10-31 a new field on the view's events made +// every resident's checkpoint undecodable and the M5 hosted no one for 32 minutes. The view is +// derived: it is dropped, her memory restores, and her next act opens a new epoch. +#[test] +fn an_undecodable_view_is_dropped_and_her_memory_still_restores() { + let wm = WorkingMemory::new(8); + wm.record("the build failed on the missing import"); + let mut checkpoint = serde_json::to_value(wm.snapshot()).expect("encode"); + checkpoint["context_view"] = serde_json::json!({ "events": [{ "shape": "from another build" }] }); + let snap: VolatileSnapshot = serde_json::from_value(checkpoint).expect("the checkpoint still decodes"); + assert!(snap.context_view.is_none(), "the stale view is dropped"); + let restored = WorkingMemory::new(8); + restored.restore(snap); + assert!( + restored.recent_entries().iter().any(|entry| entry.text.contains("missing import")), + "her memory survives the dropped view" + ); + assert!(restored.take_view().is_none(), "her next act opens a new epoch"); +} From 4cddddc35aeac4313a18b53f0325425df55c49b2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 10:57:29 -0500 Subject: [PATCH 54/88] The regression test reproduces the outage exactly: a real serialized view with only its level fields removed is dropped, the newest result and settlement restore and survive the next save, and a corrupt authoritative field still refuses (Codex on #5659) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/tests.rs | 54 +++++++++++++++++++ .../cognition/working_memory/tests/trail.rs | 20 ------- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 4155df02a1..ed8e82091d 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -67,6 +67,60 @@ fn her_view_survives_a_restart_in_her_checkpoint() { assert!(restored.take_view().is_none(), "taken once, by the act that resumes it"); } +// what this catches: the 2026-10-31 M5 outage. #5639 added `level` to the view's events, so every +// resident's checkpoint (written by the build before) failed to decode and registration refused all +// four for 32 minutes. A real view with only its `level` fields removed must be dropped (it is +// derived) while everything authoritative restores and saves again; a corrupt AUTHORITATIVE field +// must still refuse (Codex on #5659). +#[test] +fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { + use continuum_context::view::{Claim, View}; + use crate::cognition::working_memory::VolatileSnapshot; + + let memory = WorkingMemory::new(8); + memory.record_receipt("I ran code/list Result: 4 files"); + memory.record_settlement("listed the four files", None); + let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; + let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); + let (view, _) = View::start(Vec::new(), &[&actions as &dyn Source<_>], whole).unwrap(); + memory.keep_view(Some(view)); + let good = serde_json::to_value(memory.snapshot()).expect("encode"); + + // The older build's shape: the same real view, its `level` fields removed and nothing else. + fn strip_levels(value: &mut serde_json::Value) -> usize { + match value { + serde_json::Value::Object(map) => { + let here = usize::from(map.remove("level").is_some()); + here + map.values_mut().map(strip_levels).sum::() + } + serde_json::Value::Array(items) => items.iter_mut().map(strip_levels).sum(), + _ => 0, + } + } + let mut older = good.clone(); + assert!(strip_levels(&mut older["context_view"]) > 0, "the fixture reproduces the missing-level view"); + + let snap: VolatileSnapshot = serde_json::from_value(older).expect("an older view never refuses the checkpoint"); + let restored = WorkingMemory::new(8); + restored.restore(snap); + assert!(restored.take_view().is_none(), "the stale view is dropped: her next act opens a new epoch"); + assert!(restored.has_receipt(), "her newest result survives"); + let settled = |m: &WorkingMemory| m.recent_entries().iter().any(|entry| entry.text.contains("listed the four files")); + assert!(settled(&restored), "her settlement survives"); + + // The next save keeps every authoritative field and carries no view until she renders one. + let saved = serde_json::to_value(restored.snapshot()).expect("encode"); + assert!(saved.get("context_view").is_none()); + let again = WorkingMemory::new(8); + again.restore(serde_json::from_value(saved).expect("the repaired save decodes")); + assert!(again.has_receipt() && settled(&again), "authoritative state survives the repaired save"); + + // A corrupt authoritative field is still refused: only the derived view is forgiven. + let mut corrupt = good; + corrupt["next_action_seq"] = serde_json::json!("not a number"); + assert!(serde_json::from_value::(corrupt).is_err()); +} + // what this catches (Cormac on #5255): a result kept in memory but never saved under a handle // collapsing at a turnover to its one-line ledger head, which nothing can reopen (goal 7). Its // collapsed form is the whole result, so the view can only keep it, never cut it. diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 722baf654c..3f20024dc9 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -290,23 +290,3 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { ); } -// what this catches: a checkpoint whose context view no longer decodes (the view's shape changed in -// a later build) refusing the whole restore. On 2026-10-31 a new field on the view's events made -// every resident's checkpoint undecodable and the M5 hosted no one for 32 minutes. The view is -// derived: it is dropped, her memory restores, and her next act opens a new epoch. -#[test] -fn an_undecodable_view_is_dropped_and_her_memory_still_restores() { - let wm = WorkingMemory::new(8); - wm.record("the build failed on the missing import"); - let mut checkpoint = serde_json::to_value(wm.snapshot()).expect("encode"); - checkpoint["context_view"] = serde_json::json!({ "events": [{ "shape": "from another build" }] }); - let snap: VolatileSnapshot = serde_json::from_value(checkpoint).expect("the checkpoint still decodes"); - assert!(snap.context_view.is_none(), "the stale view is dropped"); - let restored = WorkingMemory::new(8); - restored.restore(snap); - assert!( - restored.recent_entries().iter().any(|entry| entry.text.contains("missing import")), - "her memory survives the dropped view" - ); - assert!(restored.take_view().is_none(), "her next act opens a new epoch"); -} From e6c5d4c694da8b0fd56baccef8a66031cb0c4c16 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 11:05:35 -0500 Subject: [PATCH 55/88] test(cognition): preserve pending task custody across view invalidation --- .../src/cognition/context_streams/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index ed8e82091d..884ef876bf 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -78,6 +78,9 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { use crate::cognition::working_memory::VolatileSnapshot; let memory = WorkingMemory::new(8); + let task = uuid::Uuid::new_v4(); + memory.stage_task_ends(vec![(task, continuum_kernel::runtime::tasks::TaskEnd::Stopped)]) + .expect("stage authoritative terminal"); memory.record_receipt("I ran code/list Result: 4 files"); memory.record_settlement("listed the four files", None); let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; @@ -105,6 +108,8 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { restored.restore(snap); assert!(restored.take_view().is_none(), "the stale view is dropped: her next act opens a new epoch"); assert!(restored.has_receipt(), "her newest result survives"); + assert_eq!(restored.pending_task_wakes(), vec![task], "discarding a view must not acknowledge an end"); + assert_eq!(serde_json::to_value(restored.snapshot()).expect("snapshot")["task_results"], good["task_results"]); let settled = |m: &WorkingMemory| m.recent_entries().iter().any(|entry| entry.text.contains("listed the four files")); assert!(settled(&restored), "her settlement survives"); @@ -112,7 +117,9 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { let saved = serde_json::to_value(restored.snapshot()).expect("encode"); assert!(saved.get("context_view").is_none()); let again = WorkingMemory::new(8); + assert_eq!(saved["task_results"], good["task_results"], "terminal identity and fingerprint survive the next save"); again.restore(serde_json::from_value(saved).expect("the repaired save decodes")); + assert_eq!(again.pending_task_wakes(), vec![task]); assert!(again.has_receipt() && settled(&again), "authoritative state survives the repaired save"); // A corrupt authoritative field is still refused: only the derived view is forgiven. From 79ddda0fc1dbcf0c3a24ae896ff1e8da41207ba3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 11:19:31 -0500 Subject: [PATCH 56/88] Derived view decoded from its exact text (RawValue), never through serde_json::Value: a view's ElementIds are u128, which Value cannot hold, so the Value intermediate refused every VALID view (Codex's executed test on #5659); the test works on JSON text, strips only the level pairs, and now also asserts a valid view is kept Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.toml | 2 +- .../src/cognition/context_streams/tests.rs | 45 ++++++++++--------- .../cognition/working_memory/derived_view.rs | 8 +++- 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 34940c3f8f..34cacbbd57 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -284,7 +284,7 @@ candle-transformers = { version = "0.9" } # Serialization serde = { version = "1", features = ["derive"] } -serde_json = "1" +serde_json = { version = "1", features = ["raw_value"] } # raw_value: a derived field is held as its exact text until decoded, so u128 ids never pass through Value (#5659) # Database rusqlite = { version = "0.38", features = ["bundled"] } diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index ed8e82091d..c64b56f6a4 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -84,23 +84,23 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); let (view, _) = View::start(Vec::new(), &[&actions as &dyn Source<_>], whole).unwrap(); memory.keep_view(Some(view)); - let good = serde_json::to_value(memory.snapshot()).expect("encode"); - - // The older build's shape: the same real view, its `level` fields removed and nothing else. - fn strip_levels(value: &mut serde_json::Value) -> usize { - match value { - serde_json::Value::Object(map) => { - let here = usize::from(map.remove("level").is_some()); - here + map.values_mut().map(strip_levels).sum::() - } - serde_json::Value::Array(items) => items.iter_mut().map(strip_levels).sum(), - _ => 0, + // Text, never `serde_json::Value`: the view's element ids are u128, which a Value cannot hold. + let good = serde_json::to_string(&memory.snapshot()).expect("encode"); + + // The older build's shape: the same real view, its `level` pairs removed and nothing else. + let (head, view_and_rest) = good.split_at(good.find("\"context_view\":").expect("the checkpoint carries her view")); + let mut older_view = view_and_rest.to_owned(); + let mut stripped = 0; + for variant in ["Full", "Summary", "Pointer", "Folded"] { + for pattern in [format!("\"level\":\"{variant}\","), format!(",\"level\":\"{variant}\"")] { + stripped += older_view.matches(pattern.as_str()).count(); + older_view = older_view.replace(pattern.as_str(), ""); } } - let mut older = good.clone(); - assert!(strip_levels(&mut older["context_view"]) > 0, "the fixture reproduces the missing-level view"); + assert!(stripped > 0, "the fixture reproduces the missing-level view"); + let older = format!("{head}{older_view}"); - let snap: VolatileSnapshot = serde_json::from_value(older).expect("an older view never refuses the checkpoint"); + let snap: VolatileSnapshot = serde_json::from_str(&older).expect("an older view never refuses the checkpoint"); let restored = WorkingMemory::new(8); restored.restore(snap); assert!(restored.take_view().is_none(), "the stale view is dropped: her next act opens a new epoch"); @@ -108,17 +108,22 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { let settled = |m: &WorkingMemory| m.recent_entries().iter().any(|entry| entry.text.contains("listed the four files")); assert!(settled(&restored), "her settlement survives"); + // A VALID view (u128 ids and all) still restores whole: the derived decoder is lossless. + let current: VolatileSnapshot = serde_json::from_str(&good).expect("the current view decodes"); + let resumed = WorkingMemory::new(8); + resumed.restore(current); + assert!(resumed.take_view().is_some(), "a view that decodes is kept"); + // The next save keeps every authoritative field and carries no view until she renders one. - let saved = serde_json::to_value(restored.snapshot()).expect("encode"); - assert!(saved.get("context_view").is_none()); + let saved = serde_json::to_string(&restored.snapshot()).expect("encode"); + assert!(!saved.contains("\"context_view\"")); let again = WorkingMemory::new(8); - again.restore(serde_json::from_value(saved).expect("the repaired save decodes")); + again.restore(serde_json::from_str(&saved).expect("the repaired save decodes")); assert!(again.has_receipt() && settled(&again), "authoritative state survives the repaired save"); // A corrupt authoritative field is still refused: only the derived view is forgiven. - let mut corrupt = good; - corrupt["next_action_seq"] = serde_json::json!("not a number"); - assert!(serde_json::from_value::(corrupt).is_err()); + let corrupt = good.replacen("\"next_action_seq\":", "\"next_action_seq\":\"not a number\",\"_was\":", 1); + assert!(serde_json::from_str::(&corrupt).is_err()); } // what this catches (Cormac on #5255): a result kept in memory but never saved under a handle diff --git a/core/continuum-cognition/src/cognition/working_memory/derived_view.rs b/core/continuum-cognition/src/cognition/working_memory/derived_view.rs index 8b5e3c0454..ccc9145480 100644 --- a/core/continuum-cognition/src/cognition/working_memory/derived_view.rs +++ b/core/continuum-cognition/src/cognition/working_memory/derived_view.rs @@ -7,15 +7,19 @@ //! the stale view is discarded. use serde::{Deserialize, Deserializer}; +use serde_json::value::RawValue; use super::ContextView; /// `context_view`'s deserializer: the view when it decodes, else none (and a probe saying why). +/// The view is read as its exact source text first (`RawValue`), never as a `serde_json::Value`: +/// a view's element ids are u128, which a `Value` cannot hold ("number out of range"), so a +/// `Value` intermediate would refuse every valid view (Codex on #5659, executed test). pub(crate) fn or_new_epoch<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { - let Some(raw) = Option::::deserialize(deserializer)? else { + let Some(raw) = Option::>::deserialize(deserializer)? else { return Ok(None); }; - match serde_json::from_value::(raw) { + match serde_json::from_str::(raw.get()) { Ok(view) => Ok(Some(view)), Err(error) => { continuum_base::probe!( From d4aee665e067366d66f177bd87668ed1345134ca Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 18:46:43 -0500 Subject: [PATCH 57/88] fix(tasks): keep acceptance with execution when caller drops --- .../runtime/command_executor/background.rs | 59 +++++++++++++++++-- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index 674719cd9e..db721eb5ef 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -50,12 +50,21 @@ impl CommandExecutor { .await .map_err(DispatchFailure::not_committed)?, ); - let handle = ledger - .accept(owner, command.to_string()) - .await - .map_err(DispatchFailure::not_committed)?; + // The execution task owns persistence too. Dropping the caller while an + // insert is in flight must not strand a committed acceptance without work. + let (accepted, receipt) = tokio::sync::oneshot::channel(); let this = Arc::clone(self); tokio::spawn(async move { + let handle = match ledger.accept(owner, command.to_string()).await { + Ok(handle) => handle, + Err(error) => { + let _ = accepted.send(Err(DispatchFailure::not_committed(error))); + return; + } + }; + // A forgotten receipt does not cancel accepted work; its durable + // terminal remains available to the authenticated owner's replay. + let _ = accepted.send(Ok(handle)); let start = std::time::Instant::now(); // Keep the existing policy and hands admission scopes inside dispatch. // Catch an unwinding handler without detaching a second execution task. @@ -96,7 +105,9 @@ impl CommandExecutor { Some(handle), ); }); - Ok(handle) + receipt.await.map_err(|_| { + DispatchFailure::uncertain("background acceptance owner stopped before reporting".into()) + })? } } @@ -148,6 +159,44 @@ mod tests { } } + #[tokio::test] + async fn dropping_acceptance_waiter_does_not_orphan_execution() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let gate = Arc::new(GatedResult { + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + unwind: false, + }); + let bus = Arc::new(MessageBus::new()); + let mut events = bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_message_bus(bus) + .with_interceptor(gate.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = Uuid::new_v4(); + let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + { + let waiting = executor.dispatch_background("test/result", Value::Null, Some(caller)); + tokio::pin!(waiting); + // On this current-thread runtime the new execution task cannot run + // during poll: abandon its receipt before it starts acceptance. + assert!(futures::poll!(waiting.as_mut()).is_pending()); + } + tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) + .await.map_err(|error| error.to_string())?; + gate.release.notify_one(); + let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) + .await.map_err(|error| error.to_string())? + .map_err(|error| error.to_string())?; + let handle = event.payload["handle"].as_str().ok_or("completion has no task handle")?; + let handle = Uuid::parse_str(handle).map_err(|error| error.to_string())?; + assert!(matches!(ledger.pending(handle, owner).await?, Some(TaskEnd::Done(_)))); + Ok(()) + } + #[tokio::test] async fn terminal_delivery_handles_competing_writers_and_unwinding_handlers( ) -> Result<(), String> { From 12ec595f32b3aa23f5053ff79acba4deb560543e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 19:07:21 -0500 Subject: [PATCH 58/88] fix(tasks): remove unused runtime import after canary merge --- core/continuum-mind/src/modules/cognition.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index cd05c707d6..56270f6650 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -38,7 +38,6 @@ use crate::persona::{ PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord, }; use crate::rag::RagEngine; -use crate::runtime; use crate::runtime::params::Params; use crate::runtime::{ CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule, From ab7dbb699d7bca4660777ca8f9645108b624138b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 21:46:42 -0500 Subject: [PATCH 59/88] Retain shared admission custody across background task persistence --- .../src/runtime/admission_gate.rs | 121 ++++++++++++++++-- .../runtime/command_executor/background.rs | 54 +++++++- core/continuum-kernel/src/runtime/registry.rs | 8 +- 3 files changed, 164 insertions(+), 19 deletions(-) diff --git a/core/continuum-kernel/src/runtime/admission_gate.rs b/core/continuum-kernel/src/runtime/admission_gate.rs index aaa326404b..b9f3985f1f 100644 --- a/core/continuum-kernel/src/runtime/admission_gate.rs +++ b/core/continuum-kernel/src/runtime/admission_gate.rs @@ -20,6 +20,8 @@ //! not fail when the production copy regressed. use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use tokio::sync::Notify; /// High bit. Leaves 63 bits of count, which is not a limit anyone reaches: the count is /// concurrent units of work, bounded by citizens or queue capacity. @@ -28,6 +30,7 @@ const CLOSED: u64 = 1 << 63; /// Admission state for one resource: open/closed plus the in-flight count, in one word. pub struct AdmissionGate { word: AtomicU64, + idle: Notify, } impl AdmissionGate { @@ -36,6 +39,7 @@ impl AdmissionGate { pub const fn new() -> Self { Self { word: AtomicU64::new(0), + idle: Notify::const_new(), } } @@ -66,6 +70,32 @@ impl AdmissionGate { self.admit_hooked(|| {}) } + /// Transfer admission into an owned task without releasing it at the spawn. + pub fn admit_owned(self: &Arc) -> Option { + let permit = self.admit()?; + let gate = Arc::clone(self); + // Transfer the single counted admission to the owned RAII permit. + std::mem::forget(permit); + Some(OwnedPermit { gate }) + } + + /// Close admission and await all existing permits. Cancelling a waiter never + /// reopens the gate or releases another task's custody; another waiter can resume. + pub async fn close_and_wait(&self) { + self.close(); + loop { + let idle = self.idle.notified(); + tokio::pin!(idle); + // Register before checking the count so the final release cannot + // occur between observing work and subscribing to its completion. + idle.as_mut().enable(); + if self.in_flight() == 0 { + return; + } + idle.await; + } + } + /// `admit`, with a hook run between the LOAD and the compare-exchange. /// /// The hook exists so a test can make the CAS genuinely fail. A test that simply @@ -109,16 +139,16 @@ impl AdmissionGate { /// an entry still sitting in the channel, and a drain would then call the module quiet /// while the writer still had work. /// - /// So the contract for this method is narrow and must stay narrow: **it is only - /// correct when a permit was `mem::forget`ed at a hand-off, and it must be called - /// exactly once for each one.** Anywhere both ends are in the same scope, use the + /// The contract is narrow: release exactly one counted admission, either from + /// a permit's Drop or after a permit was forgotten at the log-thread hand-off. + /// Anywhere both ends are in the same scope, use the /// permit and let it drop — a manual decrement has to be repeated at every exit path /// and will be missed at the next one added. /// /// Saturating, so a double release cannot wrap the count into the closed bit and /// reopen a shut gate. A double release is still a bug; this only bounds the damage. pub fn release_one(&self) { - let _ = self + let released = self .word .fetch_update(Ordering::AcqRel, Ordering::Acquire, |cur| { let count = cur & !CLOSED; @@ -130,6 +160,9 @@ impl AdmissionGate { Some((cur & CLOSED) | (count - 1)) } }); + if matches!(released, Ok(previous) if previous & !CLOSED == 1) { + self.idle.notify_waiters(); + } } /// Shut the gate. Returns whether THIS call closed it, so a second caller — a signal @@ -157,9 +190,19 @@ pub struct Permit<'a> { impl Drop for Permit<'_> { fn drop(&mut self) { - // Subtracting 1 from the whole word decrements the low-bit count and cannot reach - // the closed bit, because a permit only exists when the count was at least 1. - self.gate.word.fetch_sub(1, Ordering::AcqRel); + self.gate.release_one(); + } +} + +/// An admitted task's custody, retained through persistence and execution. +#[must_use = "retain the permit until the admitted work and its persistence finish"] +pub struct OwnedPermit { + gate: Arc, +} + +impl Drop for OwnedPermit { + fn drop(&mut self) { + self.gate.release_one(); } } @@ -167,6 +210,42 @@ impl Drop for Permit<'_> { mod tests { use super::*; + #[tokio::test] + async fn cancelling_drain_keeps_admission_closed_and_custody_owned() -> Result<(), String> { + let gate = Arc::new(AdmissionGate::new()); + let permit = gate.admit_owned().ok_or("open gate refused admission")?; + { + let drain = gate.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_pending()); + } + assert!(!gate.is_open()); + assert_eq!(gate.in_flight(), 1); + assert!(gate.admit_owned().is_none()); + let successor = gate.close_and_wait(); + let peer = gate.close_and_wait(); + tokio::pin!(successor, peer); + assert!(futures::poll!(successor.as_mut()).is_pending()); + assert!(futures::poll!(peer.as_mut()).is_pending()); + drop(permit); + assert!(futures::poll!(successor.as_mut()).is_ready()); + assert!(futures::poll!(peer.as_mut()).is_ready()); + assert_eq!(gate.in_flight(), 0); + Ok(()) + } + + #[tokio::test] + async fn release_before_drain_subscription_is_observed() -> Result<(), String> { + let gate = Arc::new(AdmissionGate::new()); + let permit = gate.admit_owned().ok_or("open gate refused admission")?; + gate.close(); + drop(permit); + let drain = gate.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_ready()); + Ok(()) + } + // what this catches: THE RACE, driven through the REAL admit/close rather than a // reimplementation of them. With an open flag and a count as separate atomics this // order was reachable: admit reads OPEN, close lands, drain reads 0 and saves, admit @@ -201,8 +280,15 @@ mod tests { ); assert!(gate.admit().is_none()); drop(permit); - assert_eq!(gate.in_flight(), 0, "the drain's wait ends when the work does"); - assert!(!gate.is_open(), "releasing the last permit must not reopen the gate"); + assert_eq!( + gate.in_flight(), + 0, + "the drain's wait ends when the work does" + ); + assert!( + !gate.is_open(), + "releasing the last permit must not reopen the gate" + ); } // what this catches: the closed bit and the count disturbing each other. They share @@ -217,7 +303,11 @@ mod tests { assert_eq!(gate.in_flight(), 3); drop(b); // one finishes BEFORE the close gate.close(); - assert_eq!(gate.in_flight(), 2, "the close carries what was still running"); + assert_eq!( + gate.in_flight(), + 2, + "the close carries what was still running" + ); drop(a); drop(c); // and the rest finish after it, out of admission order assert_eq!(gate.in_flight(), 0); @@ -232,7 +322,10 @@ mod tests { let gate = AdmissionGate::new(); let _held = gate.admit().expect("open"); assert!(gate.close(), "first close closed it"); - assert!(!gate.close(), "second close must report it was already shut"); + assert!( + !gate.close(), + "second close must report it was already shut" + ); assert_eq!(gate.in_flight(), 1, "and must not disturb the count"); } @@ -320,7 +413,11 @@ mod tests { let gate = AdmissionGate::new(); let permit = gate.admit().expect("open"); std::mem::forget(permit); // handed to another thread - assert_eq!(gate.in_flight(), 1, "the work is still in flight after the hand-off"); + assert_eq!( + gate.in_flight(), + 1, + "the work is still in flight after the hand-off" + ); gate.release_one(); // the holder finished it assert_eq!(gate.in_flight(), 0); } diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index db721eb5ef..59121de218 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -45,6 +45,11 @@ impl CommandExecutor { })?; let owner = caller.peer_id.as_uuid(); let command: CommandUri = command.into(); + // Admission precedes the first storage await. A close either refuses + // this request without effects or sees custody throughout acceptance. + let custody = self.registry.task_admission.admit_owned().ok_or_else(|| { + DispatchFailure::not_committed("runtime is draining background tasks".into()) + })?; let ledger = Arc::clone( self.task_ledger() .await @@ -55,6 +60,7 @@ impl CommandExecutor { let (accepted, receipt) = tokio::sync::oneshot::channel(); let this = Arc::clone(self); tokio::spawn(async move { + let _custody = custody; let handle = match ledger.accept(owner, command.to_string()).await { Ok(handle) => handle, Err(error) => { @@ -106,7 +112,9 @@ impl CommandExecutor { ); }); receipt.await.map_err(|_| { - DispatchFailure::uncertain("background acceptance owner stopped before reporting".into()) + DispatchFailure::uncertain( + "background acceptance owner stopped before reporting".into(), + ) })? } } @@ -129,6 +137,27 @@ mod tests { CommandInterceptor, CommandResult, InterceptorOutcome, MessageBus, ModuleRegistry, }; + #[tokio::test] + async fn closed_runtime_refuses_before_resolving_storage() -> Result<(), String> { + let registry = Arc::new(ModuleRegistry::new()); + registry.task_admission.close(); + // No data module or injected ledger: a request that gets past admission + // would fail at storage resolution with a different error. + let executor = Arc::new(CommandExecutor::new(registry.clone())); + let caller = + CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(Uuid::new_v4())); + let result = executor + .dispatch_background("test/result", Value::Null, Some(caller)) + .await; + let Err(error) = result else { + return Err("closed runtime admitted background work".into()); + }; + assert_eq!(error.message, "runtime is draining background tasks"); + assert_eq!(error.outcome, DispatchOutcome::NotCommitted); + assert_eq!(registry.task_admission.in_flight(), 0); + Ok(()) + } + struct GatedResult { entered: tokio::sync::Notify, release: tokio::sync::Notify, @@ -186,14 +215,29 @@ mod tests { assert!(futures::poll!(waiting.as_mut()).is_pending()); } tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) - .await.map_err(|error| error.to_string())?; + .await + .map_err(|error| error.to_string())?; + assert_eq!(executor.registry.task_admission.in_flight(), 1); + let drain = executor.registry.task_admission.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_pending()); gate.release.notify_one(); let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) - .await.map_err(|error| error.to_string())? + .await + .map_err(|error| error.to_string())? .map_err(|error| error.to_string())?; - let handle = event.payload["handle"].as_str().ok_or("completion has no task handle")?; + let handle = event.payload["handle"] + .as_str() + .ok_or("completion has no task handle")?; let handle = Uuid::parse_str(handle).map_err(|error| error.to_string())?; - assert!(matches!(ledger.pending(handle, owner).await?, Some(TaskEnd::Done(_)))); + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(TaskEnd::Done(_)) + )); + tokio::time::timeout(std::time::Duration::from_secs(5), drain) + .await + .map_err(|error| error.to_string())?; + assert_eq!(executor.registry.task_admission.in_flight(), 0); Ok(()) } diff --git a/core/continuum-kernel/src/runtime/registry.rs b/core/continuum-kernel/src/runtime/registry.rs index cb8ba9e18b..82fb1ff3e3 100644 --- a/core/continuum-kernel/src/runtime/registry.rs +++ b/core/continuum-kernel/src/runtime/registry.rs @@ -15,6 +15,9 @@ use std::any::TypeId; use std::sync::Arc; pub struct ModuleRegistry { + /// Background acceptance, execution and terminal persistence share custody + /// with this runtime's module registry, including across executor instances. + pub(crate) task_admission: Arc, /// Modules by name: "voice" -> Arc modules: DashMap<&'static str, Arc>, @@ -57,6 +60,7 @@ impl Default for ModuleRegistry { impl ModuleRegistry { pub fn new() -> Self { let registry = Self { + task_admission: Arc::new(super::admission_gate::AdmissionGate::new()), modules: DashMap::new(), configs: DashMap::new(), metrics: DashMap::new(), @@ -400,7 +404,8 @@ mod tests { struct StubSpec; impl crate::sdk_codegen::CommandSpec for StubSpec { const NAME: &'static str = "test/stub-descriptor"; - const ACCESS_LEVEL: crate::sdk_codegen::AccessLevel = crate::sdk_codegen::AccessLevel::AiSafe; + const ACCESS_LEVEL: crate::sdk_codegen::AccessLevel = + crate::sdk_codegen::AccessLevel::AiSafe; const WIRE: crate::sdk_codegen::WireShape = crate::sdk_codegen::WireShape::Bare; type Params = StubParams; type Result = StubResult; @@ -547,5 +552,4 @@ mod tests { let found = registry.module_of_type::(); assert!(found.is_some()); } - } From 878e60bf2c31278765ca20012daa9d40408e5450 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 22:07:22 -0500 Subject: [PATCH 60/88] Withhold module shutdown until background custody settles --- .../src/commands/system/shutdown.rs | 2 +- .../runtime/command_executor/background.rs | 3 + core/continuum-kernel/src/runtime/registry.rs | 2 + .../src/runtime/runtime/runtime.rs | 109 +++++++++++++++++- .../src/runtime/runtime/service_profile.rs | 15 ++- ...eipt_survives_every_observer_going_away.rs | 14 ++- protocol/typescript/system/ShutdownReceipt.ts | 6 +- 7 files changed, 140 insertions(+), 11 deletions(-) diff --git a/core/continuum-core/src/commands/system/shutdown.rs b/core/continuum-core/src/commands/system/shutdown.rs index e4cd96af6b..2e1e3798a5 100644 --- a/core/continuum-core/src/commands/system/shutdown.rs +++ b/core/continuum-core/src/commands/system/shutdown.rs @@ -228,7 +228,7 @@ mod tests { #[test] fn commit_requires_same_instance_and_completed_received_receipt() { let current = ShutdownTarget { pid: 42, instance: "first".into() }; - let receipt = ShutdownReceipt { modules: vec![], total_ms: 19 }; + let receipt = ShutdownReceipt { tasks: crate::runtime::DrainOutcome::Drained, modules: vec![], total_ms: 19 }; let mut params = ShutdownCommitParams { target: current.clone(), receipt_sha256: shutdown_receipt_digest(&receipt).unwrap() }; assert!(validate_commit(¶ms, ¤t, None).is_err()); assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_ok()); diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index 59121de218..1fc2b56f75 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -98,6 +98,9 @@ impl CommandExecutor { Ok(winner) => winner, Err(error) => { tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); + this.registry + .task_persistence_failed + .store(true, std::sync::atomic::Ordering::Release); return; } }; diff --git a/core/continuum-kernel/src/runtime/registry.rs b/core/continuum-kernel/src/runtime/registry.rs index 82fb1ff3e3..625a27ffac 100644 --- a/core/continuum-kernel/src/runtime/registry.rs +++ b/core/continuum-kernel/src/runtime/registry.rs @@ -18,6 +18,7 @@ pub struct ModuleRegistry { /// Background acceptance, execution and terminal persistence share custody /// with this runtime's module registry, including across executor instances. pub(crate) task_admission: Arc, + pub(crate) task_persistence_failed: std::sync::atomic::AtomicBool, /// Modules by name: "voice" -> Arc modules: DashMap<&'static str, Arc>, @@ -61,6 +62,7 @@ impl ModuleRegistry { pub fn new() -> Self { let registry = Self { task_admission: Arc::new(super::admission_gate::AdmissionGate::new()), + task_persistence_failed: std::sync::atomic::AtomicBool::new(false), modules: DashMap::new(), configs: DashMap::new(), metrics: DashMap::new(), diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 870e7894f9..14fe6c8d9a 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -1,7 +1,86 @@ use super::*; -impl Runtime { +#[cfg(test)] +mod background_custody_tests { + use super::*; + use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; + use std::sync::atomic::Ordering; + + #[tokio::test(start_paused = true)] + async fn unfinished_custody_withholds_module_stop_and_a_later_drain_can_finish( + ) -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(!receipt.state_is_durable()); + assert!(!receipt.tasks.is_quiet()); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) + } + #[tokio::test] + async fn cancelling_shutdown_wait_does_not_release_task_custody() -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("cancel-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + { + let stop = runtime.shutdown_within(std::time::Duration::from_secs(1)); + tokio::pin!(stop); + assert!(futures::poll!(stop.as_mut()).is_pending()); + } + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert_eq!(runtime.registry.task_admission.in_flight(), 1); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + assert!(runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await + .state_is_durable()); + Ok(()) + } + + #[tokio::test] + async fn failed_terminal_persistence_is_not_a_quiet_runtime() { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("failed-custody-store", Vec::new()); + runtime.register(module.clone()); + // Inject the execution owner's terminal-write failure fact; this tests + // shutdown's consumption of it, not the storage adapter's fault handling. + runtime + .registry + .task_persistence_failed + .store(true, Ordering::Release); + let receipt = runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await; + assert!(!receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(receipt.summary().contains("terminal persistence failed")); + } +} + +impl Runtime { /// `shutdown`, with the per-phase bound passed IN. /// /// A parameter rather than a constant because the TIMEOUT arms could not otherwise be @@ -10,12 +89,30 @@ impl Runtime { /// handling here would have left every one of those tests green — the outcomes were /// described by the suite and never produced by it. Found by IntelMac. pub(super) async fn shutdown_within(&self, per_phase: std::time::Duration) -> ShutdownReceipt { + let started = std::time::Instant::now(); + // The same registry is held by every executor. Close before waiting so + // acceptance cannot race past a zero count. Cancellation leaves it closed. + let tasks = match tokio::time::timeout(per_phase, self.registry.task_admission.close_and_wait()).await { + Err(_) => DrainOutcome::Unknown { + reason: format!("background task custody did not settle within {}ms; modules remain running", per_phase.as_millis()), + }, + Ok(()) if self.registry.task_persistence_failed.load(std::sync::atomic::Ordering::Acquire) => DrainOutcome::Unknown { + reason: "background terminal persistence failed; durable acceptances require reconciliation".into(), + }, + Ok(()) => DrainOutcome::Drained, + }; + if !tasks.is_quiet() { + return ShutdownReceipt { + tasks, + modules: Vec::new(), + total_ms: started.elapsed().as_millis() as u64, + }; + } let modules = self.registry.list_modules(); info!( "Stopping {} modules (drain → save → join, parallel, 2s bound per phase)...", modules.len() ); - let started = std::time::Instant::now(); let futs = modules.iter().filter_map(|name| { self.registry.get_by_name(name).map(|module| { // Deref, not clone: `list_modules` yields `Vec<&'static str>`, so `name` @@ -72,6 +169,7 @@ impl Runtime { }) }); let receipt = ShutdownReceipt { + tasks, modules: futures::future::join_all(futs).await, total_ms: started.elapsed().as_millis() as u64, }; @@ -153,7 +251,6 @@ impl Runtime { ); Ok(()) } - } /// Quarantine threshold for the per-module tick loop. After this many @@ -450,7 +547,11 @@ pub struct ModuleSpec { } impl ModuleSpec { - pub(super) const fn new(name: &'static str, group: ServiceGroup, category: ModuleCategory) -> Self { + pub(super) const fn new( + name: &'static str, + group: ServiceGroup, + category: ModuleCategory, + ) -> Self { Self { name, group, diff --git a/core/continuum-kernel/src/runtime/runtime/service_profile.rs b/core/continuum-kernel/src/runtime/runtime/service_profile.rs index bacdaa94a3..5901b11fd7 100644 --- a/core/continuum-kernel/src/runtime/runtime/service_profile.rs +++ b/core/continuum-kernel/src/runtime/runtime/service_profile.rs @@ -159,6 +159,8 @@ impl ModuleStop { export_to = "../../../protocol/typescript/system/ShutdownReceipt.ts" )] pub struct ShutdownReceipt { + /// Background acceptance and terminal persistence must settle before modules stop. + pub tasks: DrainOutcome, pub modules: Vec, #[ts(type = "number")] pub total_ms: u64, @@ -176,11 +178,17 @@ impl ShutdownReceipt { /// Every module drained, saved, and completed its final shutdown flush. pub fn state_is_durable(&self) -> bool { - self.unsaved().is_empty() + self.tasks.is_quiet() && self.unsaved().is_empty() } /// One line a human can act on, without reading the process's log after it exited. pub fn summary(&self) -> String { + if !self.tasks.is_quiet() { + return format!( + "module shutdown withheld: background task custody {:?}", + self.tasks + ); + } let unsaved = self.unsaved(); if unsaved.is_empty() { return format!( @@ -271,6 +279,7 @@ impl ShutdownOperation { // Publishing an empty receipt says exactly that, rather than leaving // every observer waiting on a broadcast that will never run. let _ = self.result.send_replace(Some(ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 0, })); @@ -298,7 +307,9 @@ pub(super) fn process_shutdown() -> &'static ShutdownOperation { /// /// Delegates to the process's single [`ShutdownOperation`]. See that type for why the /// operation is owned rather than free-standing. -pub fn begin_shutdown(settle: std::time::Duration) -> tokio::sync::watch::Receiver> { +pub fn begin_shutdown( + settle: std::time::Duration, +) -> tokio::sync::watch::Receiver> { process_shutdown().begin(signal_runtime(), settle) } diff --git a/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs b/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs index 53cdc67862..103272840d 100644 --- a/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs +++ b/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs @@ -131,6 +131,7 @@ pub(super) mod conditional_modules_tests { "giving up watching must not end the shutdown" ); let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 3, }; @@ -429,6 +430,7 @@ pub(super) mod conditional_modules_tests { #[test] fn the_summary_names_the_modules_that_did_not_save() { let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: vec![ stop("logger", ModuleStopOutcome::Clean), stop("cognition", ModuleStopOutcome::SaveTimedOut), @@ -452,6 +454,7 @@ pub(super) mod conditional_modules_tests { #[test] fn an_empty_receipt_reports_the_count_it_actually_stopped() { let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 0, }; @@ -548,7 +551,6 @@ pub(super) mod conditional_modules_tests { "{err}" ); } - } /// The mesh states the census reads, as the kernel sees them: through `MeshPresence` /// alone (airc's `AircDiscovery` is the real implementor, above the kernel). @@ -567,11 +569,17 @@ pub(super) mod conditional_modules_tests { } fn healthy() -> Mesh { - Mesh { can_host: true, kind: "healthy" } + Mesh { + can_host: true, + kind: "healthy", + } } fn degraded() -> Mesh { - Mesh { can_host: false, kind: "degraded" } + Mesh { + can_host: false, + kind: "degraded", + } } /// FullCitizen + Healthy → must include persona hosting. diff --git a/protocol/typescript/system/ShutdownReceipt.ts b/protocol/typescript/system/ShutdownReceipt.ts index fd3cb62f47..3682eb2abd 100644 --- a/protocol/typescript/system/ShutdownReceipt.ts +++ b/protocol/typescript/system/ShutdownReceipt.ts @@ -1,4 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DrainOutcome } from "./DrainOutcome"; import type { ModuleStop } from "./ModuleStop"; /** @@ -9,4 +10,7 @@ import type { ModuleStop } from "./ModuleStop"; * 0 whether every module had saved or none had. A stop whose result only exists in the * log of the process that just exited is not a result anybody can act on. */ -export type ShutdownReceipt = { modules: Array, total_ms: number, }; +export type ShutdownReceipt = { /** + * Background acceptance and terminal persistence must settle before modules stop. + */ +tasks: DrainOutcome, modules: Array, total_ms: number, }; From 637f54266435cfd862206b5e8ba04bfef8369381 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 22:17:21 -0500 Subject: [PATCH 61/88] Allow owned shutdown to retry after withheld task custody --- .../src/runtime/runtime/runtime.rs | 36 +++++++++++++++++++ .../src/runtime/runtime/service_profile.rs | 22 ++++++++++-- protocol/typescript/system/ShutdownReceipt.ts | 3 +- 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 14fe6c8d9a..3e442507e5 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -6,6 +6,42 @@ mod background_custody_tests { use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; use std::sync::atomic::Ordering; + #[tokio::test(start_paused = true)] + async fn shutdown_owner_retries_withheld_custody_without_repeating_module_stop( + ) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("retry-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let operation = ShutdownOperation::new(); + let mut first = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + first.changed().await.map_err(|error| error.to_string())?; + let receipt = first + .borrow_and_update() + .clone() + .ok_or("missing withheld receipt")?; + assert!(!receipt.tasks.is_quiet()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + drop(first); + drop(custody); + let mut retry = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + assert!(retry.borrow().is_none()); + retry.changed().await.map_err(|error| error.to_string())?; + let receipt = retry + .borrow_and_update() + .clone() + .ok_or("missing completed receipt")?; + assert!(receipt.state_is_durable()); + let again = operation.begin(Some(runtime), std::time::Duration::ZERO); + assert_eq!(again.borrow().as_ref(), Some(&receipt)); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) + } + #[tokio::test(start_paused = true)] async fn unfinished_custody_withholds_module_stop_and_a_later_drain_can_finish( ) -> Result<(), String> { diff --git a/core/continuum-kernel/src/runtime/runtime/service_profile.rs b/core/continuum-kernel/src/runtime/runtime/service_profile.rs index 5901b11fd7..d60deda5da 100644 --- a/core/continuum-kernel/src/runtime/runtime/service_profile.rs +++ b/core/continuum-kernel/src/runtime/runtime/service_profile.rs @@ -224,14 +224,14 @@ impl ShutdownReceipt { /// tests drift into testing something adjacent. pub(super) struct ShutdownOperation { pub(super) result: tokio::sync::watch::Sender>, - pub(super) started: std::sync::atomic::AtomicBool, + pub(super) started: Arc>, } impl ShutdownOperation { pub(super) fn new() -> Self { Self { result: tokio::sync::watch::channel(None).0, - started: std::sync::atomic::AtomicBool::new(false), + started: Arc::new(parking_lot::Mutex::new(false)), } } @@ -239,6 +239,8 @@ impl ShutdownOperation { /// result. Idempotent: a second caller — a signal racing the stop verb, a retried /// request — joins the first broadcast rather than running `save_state` twice over /// the same state. + /// A custody refusal stops no modules and permits an explicit new attempt; + /// once module shutdown starts its receipt remains the single retained result. /// /// `settle` is how long the citizens' turns may still finish before the modules drain /// (card 32fa22ba): the turns' measured remaining time, never more than this. ZERO = @@ -249,10 +251,16 @@ impl ShutdownOperation { rt: Option>, settle: std::time::Duration, ) -> tokio::sync::watch::Receiver> { - if !self.started.swap(true, std::sync::atomic::Ordering::AcqRel) { + let mut running = self.started.lock(); + if !*running { + *running = true; + // A retry is permitted only after custody withheld every module stop. + // Do not hand its caller the previous attempt's terminal receipt. + self.result.send_replace(None); match rt { Some(rt) => { let tx = self.result.clone(); + let started = Arc::clone(&self.started); // Detached ON PURPOSE: this is the task whose whole point is that no // connection owns it. A socket handler is cancelled when its client // goes away, and a shutdown cancelled after ingress closed leaves the @@ -271,7 +279,15 @@ impl ShutdownOperation { // receipt in precisely the case this design exists for. A later // subscriber would then wait forever on a `None` that never // changes. + // Serialize publication with a new begin: a caller that + // observes the withheld receipt can immediately retry, + // without racing an old publisher over its new attempt. + let mut running = started.lock(); + let withheld = !receipt.tasks.is_quiet(); let _ = tx.send_replace(Some(receipt)); + if withheld { + *running = false; + } }); } None => { diff --git a/protocol/typescript/system/ShutdownReceipt.ts b/protocol/typescript/system/ShutdownReceipt.ts index 3682eb2abd..4b34fae2f2 100644 --- a/protocol/typescript/system/ShutdownReceipt.ts +++ b/protocol/typescript/system/ShutdownReceipt.ts @@ -10,7 +10,8 @@ import type { ModuleStop } from "./ModuleStop"; * 0 whether every module had saved or none had. A stop whose result only exists in the * log of the process that just exited is not a result anybody can act on. */ -export type ShutdownReceipt = { /** +export type ShutdownReceipt = { +/** * Background acceptance and terminal persistence must settle before modules stop. */ tasks: DrainOutcome, modules: Array, total_ms: number, }; From 4f382a9cd68c8dcd91de0ced2dd801290abb05bc Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 22:36:54 -0500 Subject: [PATCH 62/88] Prove shutdown custody across paused acceptance and terminal writes --- .../src/runtime/runtime/runtime.rs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 3e442507e5..c927e25835 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -6,6 +6,66 @@ mod background_custody_tests { use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; use std::sync::atomic::Ordering; + #[tokio::test] + async fn shutdown_waits_for_acceptance_and_terminal_storage_after_receipt_is_forgotten( + ) -> Result<(), String> { + use crate::orm::gated_adapter::GatedAdapter; + use crate::runtime::tasks::TaskLedger; + use crate::runtime::CommandExecutor; + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("storage-boundary", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(GatedAdapter::new(adapter)); + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let mut events = runtime.bus.receiver(); + let owner = uuid::Uuid::new_v4(); + let caller = crate::routing::CallerIdentity::local_persona( + crate::identity::PeerId::from_uuid(owner), + ); + let acceptance = adapter.pause_next_write(); + { + let receipt = executor.dispatch_background( + "test/unhandled", + serde_json::Value::Null, + Some(caller), + ); + tokio::pin!(receipt); + assert!(futures::poll!(receipt.as_mut()).is_pending()); + acceptance.entered.notified().await; + // Drop the actual caller while its durable acceptance write is paused. + } + let shutdown = runtime.shutdown_within(std::time::Duration::from_secs(30)); + tokio::pin!(shutdown); + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + let terminal = adapter.pause_next_write(); + acceptance.release.notify_one(); + terminal.entered.notified().await; + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + terminal.release.notify_one(); + let receipt = shutdown.await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + let completion = events.recv().await.map_err(|error| error.to_string())?; + let task = completion.payload["handle"] + .as_str() + .ok_or("missing completion handle")?; + let task = uuid::Uuid::parse_str(task).map_err(|error| error.to_string())?; + // The command was unhandled, but its failure is durable and deliverable; + // module shutdown cannot overtake either storage boundary. + assert!(matches!( + ledger.pending(task, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Failed { .. }) + )); + Ok(()) + } + #[tokio::test(start_paused = true)] async fn shutdown_owner_retries_withheld_custody_without_repeating_module_stop( ) -> Result<(), String> { From 8176653f6fdc970efa338ea0c075bb7e483462ac Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 22:46:16 -0500 Subject: [PATCH 63/88] Reject process exit while task custody remains unresolved --- .../src/commands/system/shutdown.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/core/continuum-core/src/commands/system/shutdown.rs b/core/continuum-core/src/commands/system/shutdown.rs index 2e1e3798a5..187f00c18c 100644 --- a/core/continuum-core/src/commands/system/shutdown.rs +++ b/core/continuum-core/src/commands/system/shutdown.rs @@ -67,6 +67,11 @@ pub fn shutdown_receipt_digest(receipt: &ShutdownReceipt) -> Result) -> Result<(), crate::sdk_codegen::CommandError> { validate_target(¶ms.target, current)?; + if receipt.is_some_and(|receipt| !receipt.tasks.is_quiet()) { + return Err(crate::sdk_codegen::CommandError::Invalid( + "shutdown withheld while background custody is unresolved; no process exit was committed".into(), + )); + } if receipt.map(shutdown_receipt_digest).transpose()?.as_deref() != Some(params.receipt_sha256.as_str()) { return Err(crate::sdk_codegen::CommandError::Invalid( "shutdown commit requires the completed save receipt from this process".into(), @@ -242,6 +247,23 @@ mod tests { assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_err()); } + #[test] + fn matching_receipt_hash_cannot_authorize_exit_with_unresolved_custody() -> Result<(), crate::sdk_codegen::CommandError> { + let current = ShutdownTarget { pid: 42, instance: "withheld".into() }; + for tasks in [ + crate::runtime::DrainOutcome::Incomplete { in_flight: 1 }, + crate::runtime::DrainOutcome::Unknown { reason: "terminal persistence failed".into() }, + ] { + let receipt = ShutdownReceipt { tasks, modules: Vec::new(), total_ms: 1 }; + let params = ShutdownCommitParams { + target: current.clone(), + receipt_sha256: shutdown_receipt_digest(&receipt)?, + }; + assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_err()); + } + Ok(()) + } + // Exercise the real exit in an isolated test child, never the serving core. // The child must obtain the retained receipt before commit can end it. #[tokio::test] From 15ec55dfe92dd137e7c3849983de05d1befbc906 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 22:58:02 -0500 Subject: [PATCH 64/88] Withhold signal exit until background custody settles --- core/continuum-core/src/main.rs | 109 ++++++++++-------- .../src/runtime/runtime/service_profile.rs | 53 +++++++-- 2 files changed, 106 insertions(+), 56 deletions(-) diff --git a/core/continuum-core/src/main.rs b/core/continuum-core/src/main.rs index 6d7dacee6b..0669a6d0f8 100644 --- a/core/continuum-core/src/main.rs +++ b/core/continuum-core/src/main.rs @@ -75,16 +75,20 @@ fn install_shutdown_handlers() { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { - sig.recv().await; - eprintln!("[continuum-core] SIGTERM — save-and-join broadcast, then exit"); - // The CBAR stop (2026-09-02): every module saves and joins in - // parallel under a bound — replacing a flat 2s sleep during - // which NOTHING saved. Sentinels last (they are children, not - // modules), then the fast _exit that skips llama.cpp's - // double-free-prone static destructors (note above). - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; + while sig.recv().await.is_some() { + eprintln!("[continuum-core] SIGTERM — save-and-join broadcast, then exit"); + // The CBAR stop (2026-09-02): every module saves and joins in + // parallel under a bound — replacing a flat 2s sleep during + // which NOTHING saved. Sentinels last (they are children, not + // modules), then the fast _exit that skips llama.cpp's + // double-free-prone static destructors (note above). + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; + } } }); @@ -93,11 +97,15 @@ fn install_shutdown_handlers() { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) { - sig.recv().await; - eprintln!("[continuum-core] SIGINT — save-and-join broadcast, then exit"); - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; + while sig.recv().await.is_some() { + eprintln!("[continuum-core] SIGINT — save-and-join broadcast, then exit"); + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; + } } }); } @@ -118,43 +126,48 @@ fn install_shutdown_handlers() { let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); let mut ctrl_shutdown = tokio::signal::windows::ctrl_shutdown().ok(); - let close_fut = async { - match ctrl_close.as_mut() { - Some(s) => { - s.recv().await; + loop { + let close_fut = async { + match ctrl_close.as_mut() { + Some(s) => s.recv().await, + None => std::future::pending::>().await, } - None => std::future::pending::<()>().await, - } - }; - let shutdown_fut = async { - match ctrl_shutdown.as_mut() { - Some(s) => { - s.recv().await; + }; + let shutdown_fut = async { + match ctrl_shutdown.as_mut() { + Some(s) => s.recv().await, + None => std::future::pending::>().await, } - None => std::future::pending::<()>().await, + }; + + let signal = tokio::select! { + signal = ctrl_c.recv() => signal, + signal = close_fut => signal, + signal = shutdown_fut => signal, + }; + if signal.is_none() { + eprintln!("[continuum-core] shutdown signal stream closed; listener stopped"); + return; } - }; - - tokio::select! { - _ = ctrl_c.recv() => {} - _ = close_fut => {} - _ = shutdown_fut => {} + eprintln!("[continuum-core] shutdown signal — save-and-join broadcast, then exit"); + // THE SAME BROADCAST THE UNIX ARMS RUN. This arm killed sentinels, slept a + // flat 2 seconds, and `_exit`ed — which is precisely the behaviour the SIGTERM + // arm's own comment says was replaced on 2026-09-02 ("a flat 2s sleep during + // which NOTHING saved"). The unix half was fixed and this half was not, so on + // Windows no module has ever saved on a signal stop: not the citizens' + // workspaces, not the log queue, nothing. The node that runs the citizens is a + // Windows node. + // + // Ordering matches unix deliberately: modules drain and save FIRST, sentinels + // are killed after (they are children, not modules), then the fast `_exit` + // that skips llama.cpp's double-free-prone static destructors. + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; } - eprintln!("[continuum-core] shutdown signal — save-and-join broadcast, then exit"); - // THE SAME BROADCAST THE UNIX ARMS RUN. This arm killed sentinels, slept a - // flat 2 seconds, and `_exit`ed — which is precisely the behaviour the SIGTERM - // arm's own comment says was replaced on 2026-09-02 ("a flat 2s sleep during - // which NOTHING saved"). The unix half was fixed and this half was not, so on - // Windows no module has ever saved on a signal stop: not the citizens' - // workspaces, not the log queue, nothing. The node that runs the citizens is a - // Windows node. - // - // Ordering matches unix deliberately: modules drain and save FIRST, sentinels - // are killed after (they are children, not modules), then the fast `_exit` - // that skips llama.cpp's double-free-prone static destructors. - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; }); } } diff --git a/core/continuum-kernel/src/runtime/runtime/service_profile.rs b/core/continuum-kernel/src/runtime/runtime/service_profile.rs index d60deda5da..5772e980cd 100644 --- a/core/continuum-kernel/src/runtime/runtime/service_profile.rs +++ b/core/continuum-kernel/src/runtime/runtime/service_profile.rs @@ -374,7 +374,7 @@ pub fn signal_runtime() -> Option> { SIGNAL_RUNTIME.get().cloned() } -pub async fn run_signal_shutdown() { +pub async fn run_signal_shutdown() -> Result<(), String> { // Through the SAME idempotent operation the `system/shutdown` verb triggers, so a // signal arriving while the verb is running joins that broadcast instead of starting // a second one over the same state. The bound is deliberately larger than one phase: @@ -384,22 +384,59 @@ pub async fn run_signal_shutdown() { // No settle: a signal's deadline is the supervisor's (launchd's ExitTimeOut, a // console close), not ours to spend waiting on turns. let rx = begin_shutdown(std::time::Duration::ZERO); + await_signal_shutdown(rx).await +} + +async fn await_signal_shutdown( + rx: tokio::sync::watch::Receiver>, +) -> Result<(), String> { match await_shutdown(rx, std::time::Duration::from_secs(8)).await { Some(receipt) => { - // A signal handler cannot return an exit code to anyone, so the receipt's only - // readers are the log and the probe ledger — which is exactly why it is - // written here rather than dropped. `_exit` follows immediately. + // Withheld custody forbids process exit. Keep the signal listener alive + // so a later explicit request can retry the same shutdown owner. + if !receipt.tasks.is_quiet() { + return Err(receipt.summary()); + } if !receipt.state_is_durable() { eprintln!( "[continuum-core] STOPPED WITH UNSAVED STATE: {}", receipt.summary() ); } + Ok(()) } - None => { - eprintln!( - "[continuum-core] shutdown did not finish within 8s — state durability is UNKNOWN" - ); + None => Err("shutdown did not finish within 8s; process exit withheld".into()), + } +} + +#[cfg(test)] +mod signal_custody_tests { + use super::*; + + #[tokio::test(start_paused = true)] + async fn signal_timeout_preserves_owner_and_requires_a_quiet_receipt() { + let (owner, observer) = tokio::sync::watch::channel(None); + assert!(await_signal_shutdown(observer).await.is_err()); + // The timed-out observer must not authorize exit or destroy the retained + // operation. A later signal reads its actual receipt. + for tasks in [ + DrainOutcome::Incomplete { in_flight: 1 }, + DrainOutcome::Unknown { + reason: "terminal persistence failed".into(), + }, + ] { + owner.send_replace(Some(ShutdownReceipt { + tasks, + modules: vec![], + total_ms: 0, + })); + assert!(await_signal_shutdown(owner.subscribe()).await.is_err()); } + owner.send_replace(Some(ShutdownReceipt { + tasks: DrainOutcome::Drained, + modules: vec![], + total_ms: 0, + })); + assert!(await_signal_shutdown(owner.subscribe()).await.is_ok()); } } From 88d7ec315e0631513340c84bfd69550c902f6a06 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 23:16:45 -0500 Subject: [PATCH 65/88] Clarify acceptance custody and shutdown contract --- docs/architecture/HER-TASKS.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/architecture/HER-TASKS.md b/docs/architecture/HER-TASKS.md index 3764b25531..ccfb2be958 100644 --- a/docs/architecture/HER-TASKS.md +++ b/docs/architecture/HER-TASKS.md @@ -115,9 +115,19 @@ once; every kind of task is only its difference. The contract as built (Codex, #5585), which this design adopts: -- **Accept, durably, before spawning.** Starting a task is fallible: acceptance is written to - the ledger (an ORM entity) first, and only an accepted task runs. A refused start is said, never - silently retried in the foreground. +- **Accept, durably, before executing the command.** Starting a task is fallible. The shared + runtime admission gate takes custody before the first storage await. The existing execution + task owns acceptance, execution and terminal persistence; the caller observes its acceptance + receipt. Dropping that observer during a write cannot abandon committed acceptance. Only after + the ledger accepts does the command execute. A refused start is said, never silently retried + in the foreground. +- **Shutdown retains that custody through terminal persistence.** The same runtime gate closes + admission and waits for accepted work before modules drain, save or stop. An observation + deadline or terminal-write failure withholds module shutdown and process exit, with an explicit + nonquiet task receipt. Cancelling an observer never reopens admission. An explicit subsequent + shutdown request rejoins the existing operation or retries its custody-withheld attempt; it + does not create a second shutdown owner. This does not yet establish restart reconciliation or + adoption: the process-incarnation and execution-kind contracts below remain required. - **One terminal outcome, first writer wins.** The ledger stores an immutable terminal receipt (output kept whole, binary and typed handles included, with its effect certainty) before any event is emitted; a late writer can neither replace it nor resurrect delivery. A handler that From fb8f32ac62f62b852982d082367f85dd44dbaec3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 31 Oct 2026 23:47:42 -0500 Subject: [PATCH 66/88] Refuse self-shutdown within admitted task custody --- .../src/runtime/admission_gate.rs | 25 ++++++ .../runtime/command_executor/background.rs | 5 +- .../src/runtime/runtime/runtime.rs | 17 ++++ .../runtime/runtime/self_shutdown_tests.rs | 85 +++++++++++++++++++ .../src/runtime/runtime/service_profile.rs | 5 ++ 5 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs diff --git a/core/continuum-kernel/src/runtime/admission_gate.rs b/core/continuum-kernel/src/runtime/admission_gate.rs index b9f3985f1f..cb036e4b80 100644 --- a/core/continuum-kernel/src/runtime/admission_gate.rs +++ b/core/continuum-kernel/src/runtime/admission_gate.rs @@ -33,7 +33,17 @@ pub struct AdmissionGate { idle: Notify, } +tokio::task_local! { + // Execution context, not a second owner: the RAII permit still owns the count. + static EXECUTING_GATES: Vec>; +} + impl AdmissionGate { + pub(crate) fn held_by_current_task(&self) -> bool { + EXECUTING_GATES + .try_with(|gates| gates.iter().any(|gate| std::ptr::eq(gate.as_ref(), self))) + .is_ok_and(|held| held) + } /// A new, OPEN gate with nothing in flight. `const` so it can be a `static` without /// a lazy initialiser. pub const fn new() -> Self { @@ -200,6 +210,21 @@ pub struct OwnedPermit { gate: Arc, } +impl OwnedPermit { + /// Carry custody through the future and mark its causal scope, so it cannot + /// synchronously shut down the runtime that must wait for this same future. + pub(crate) async fn scope(self, work: F) -> F::Output { + let mut gates = match EXECUTING_GATES.try_with(Clone::clone) { + Ok(gates) => gates, + Err(_) => Vec::new(), // No enclosing admitted execution on this task. + }; + gates.push(Arc::clone(&self.gate)); + let result = EXECUTING_GATES.scope(gates, work).await; + drop(self); + result + } +} + impl Drop for OwnedPermit { fn drop(&mut self) { self.gate.release_one(); diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index 1fc2b56f75..ccf430ae00 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -59,8 +59,7 @@ impl CommandExecutor { // insert is in flight must not strand a committed acceptance without work. let (accepted, receipt) = tokio::sync::oneshot::channel(); let this = Arc::clone(self); - tokio::spawn(async move { - let _custody = custody; + tokio::spawn(custody.scope(async move { let handle = match ledger.accept(owner, command.to_string()).await { Ok(handle) => handle, Err(error) => { @@ -113,7 +112,7 @@ impl CommandExecutor { start.elapsed().as_millis() as u64, Some(handle), ); - }); + })); receipt.await.map_err(|_| { DispatchFailure::uncertain( "background acceptance owner stopped before reporting".into(), diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index c927e25835..b1ea045a71 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -1,5 +1,9 @@ use super::*; +#[cfg(test)] +#[path = "self_shutdown_tests.rs"] +mod self_shutdown_tests; + #[cfg(test)] mod background_custody_tests { use super::*; @@ -184,7 +188,20 @@ impl Runtime { /// were only ever constructed as literals and asserted on. Deleting the timeout /// handling here would have left every one of those tests green — the outcomes were /// described by the suite and never produced by it. Found by IntelMac. + pub(super) fn self_shutdown_refusal(&self) -> Option { + self.registry.task_admission.held_by_current_task().then(|| ShutdownReceipt { + tasks: DrainOutcome::Unknown { + reason: "an admitted task cannot shut down its own runtime; request shutdown outside its execution scope".into(), + }, + modules: Vec::new(), + total_ms: 0, + }) + } + pub(super) async fn shutdown_within(&self, per_phase: std::time::Duration) -> ShutdownReceipt { + if let Some(receipt) = self.self_shutdown_refusal() { + return receipt; + } let started = std::time::Instant::now(); // The same registry is held by every executor. Close before waiting so // acceptance cannot race past a zero count. Cancellation leaves it closed. diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs new file mode 100644 index 0000000000..4debb2a0cc --- /dev/null +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -0,0 +1,85 @@ +use super::*; +use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; +use crate::runtime::{CommandExecutor, CommandInterceptor, InterceptorOutcome}; +use std::sync::atomic::Ordering; + +struct RequestOwnShutdown { + runtime: Arc, + operation: Arc, +} + +#[async_trait::async_trait] +impl CommandInterceptor for RequestOwnShutdown { + fn name(&self) -> &'static str { + "request-own-shutdown" + } + + async fn try_route( + &self, + _: &str, + _: &serde_json::Value, + _: Option<&crate::routing::CallerIdentity>, + ) -> Result { + let direct = self.runtime.shutdown().await; + assert!(!direct.tasks.is_quiet()); + assert!(direct.modules.is_empty()); + let observer = self + .operation + .begin(Some(self.runtime.clone()), Duration::ZERO); + let receipt = observer + .borrow() + .clone() + .ok_or("self-shutdown was not refused immediately")?; + assert!(!receipt.tasks.is_quiet()); + assert!(self.runtime.registry.task_admission.is_open()); + Ok(InterceptorOutcome::Handled(CommandResult::Json( + serde_json::Value::Null, + ))) + } +} + +#[tokio::test] +async fn actual_background_self_shutdown_refuses_before_closing_and_can_finish( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("self-shutdown-store", Vec::new()); + runtime.register(module.clone()); + let operation = Arc::new(ShutdownOperation::new()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()) + .with_message_bus(runtime.bus.clone()) + .with_interceptor(Arc::new(RequestOwnShutdown { + runtime: runtime.clone(), + operation: operation.clone(), + })), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor + .dispatch_background("test/shutdown", serde_json::Value::Null, Some(caller)) + .await + .map_err(|e| e.message)?; + tokio::time::timeout(Duration::from_secs(5), events.recv()) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Done(_)) + )); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(runtime.registry.task_admission.is_open()); + // The refused request did not poison the retained process operation. + let observer = operation.begin(Some(runtime.clone()), Duration::ZERO); + let receipt = await_shutdown(observer, Duration::from_secs(5)) + .await + .ok_or("external shutdown did not finish")?; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} diff --git a/core/continuum-kernel/src/runtime/runtime/service_profile.rs b/core/continuum-kernel/src/runtime/runtime/service_profile.rs index 5772e980cd..f6abede559 100644 --- a/core/continuum-kernel/src/runtime/runtime/service_profile.rs +++ b/core/continuum-kernel/src/runtime/runtime/service_profile.rs @@ -251,6 +251,11 @@ impl ShutdownOperation { rt: Option>, settle: std::time::Duration, ) -> tokio::sync::watch::Receiver> { + // Check before spawning: a spawned shutdown owner no longer carries the + // requesting command's execution scope. Refusal must precede turn settle. + if let Some(receipt) = rt.as_ref().and_then(|rt| rt.self_shutdown_refusal()) { + return tokio::sync::watch::channel(Some(receipt)).1; + } let mut running = self.started.lock(); if !*running { *running = true; From 1b382b8c103a323001cded7149f335d1edfc58e6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 00:06:10 -0500 Subject: [PATCH 67/88] Retain unresolved persistence after execution owner unwinds --- .../continuum-kernel/src/orm/gated_adapter.rs | 10 ++++++- .../runtime/command_executor/background.rs | 26 ++++++++++++++++--- .../src/runtime/runtime/runtime.rs | 2 +- .../runtime/runtime/self_shutdown_tests.rs | 26 +++++++++++++++++++ 4 files changed, 59 insertions(+), 5 deletions(-) diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index f208aeeddd..6b2626d27d 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -32,11 +32,16 @@ pub(crate) struct PausedWrite { pub(crate) struct GatedAdapter { inner: Arc, next: Mutex>, + unwind_next: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false) } + } + + pub(crate) fn unwind_next_write(&self) { + self.unwind_next.store(true, std::sync::atomic::Ordering::SeqCst); } /// Hold the next write at a gate. Only that one write is held. @@ -55,6 +60,9 @@ impl GatedAdapter { &self, write: impl FnOnce(Arc) -> BoxFuture<'static, R> + Send + 'static, ) -> R { + if self.unwind_next.swap(false, std::sync::atomic::Ordering::SeqCst) { + std::panic::resume_unwind(Box::new("injected storage unwind")); + } let gate = self.next.lock().expect("gate lock").take(); // test fixture: a poisoned gate means an earlier test thread panicked let inner = Arc::clone(&self.inner); tokio::spawn(async move { diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index ccf430ae00..aff3576cef 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -7,6 +7,23 @@ use serde_json::Value; use std::sync::Arc; use uuid::Uuid; +// Custody is unresolved until acceptance is refused or a terminal is durable. +// An unexpected unwind/drop in storage must not turn a released permit into a +// successful shutdown. Handler unwinds still produce their ordinary terminal. +struct PersistenceCustody<'a> { + unresolved: &'a std::sync::atomic::AtomicBool, + settled: bool, +} + +impl Drop for PersistenceCustody<'_> { + fn drop(&mut self) { + if !self.settled { + self.unresolved + .store(true, std::sync::atomic::Ordering::Release); + } + } +} + impl CommandExecutor { /// Explicit storage injection for an embedded executor or an isolated fixture. pub fn set_task_ledger(&self, ledger: Arc) -> Result<(), String> { @@ -60,9 +77,14 @@ impl CommandExecutor { let (accepted, receipt) = tokio::sync::oneshot::channel(); let this = Arc::clone(self); tokio::spawn(custody.scope(async move { + let mut persistence = PersistenceCustody { + unresolved: &this.registry.task_persistence_failed, + settled: false, + }; let handle = match ledger.accept(owner, command.to_string()).await { Ok(handle) => handle, Err(error) => { + persistence.settled = true; let _ = accepted.send(Err(DispatchFailure::not_committed(error))); return; } @@ -97,12 +119,10 @@ impl CommandExecutor { Ok(winner) => winner, Err(error) => { tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); - this.registry - .task_persistence_failed - .store(true, std::sync::atomic::Ordering::Release); return; } }; + persistence.settled = true; // A competing supervisor may have persisted a different terminal first. // Every delivery must project that durable winner, never this writer's loser. let outcome = completion(winner); diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index b1ea045a71..42b0fd5643 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -210,7 +210,7 @@ impl Runtime { reason: format!("background task custody did not settle within {}ms; modules remain running", per_phase.as_millis()), }, Ok(()) if self.registry.task_persistence_failed.load(std::sync::atomic::Ordering::Acquire) => DrainOutcome::Unknown { - reason: "background terminal persistence failed; durable acceptances require reconciliation".into(), + reason: "background task persistence did not settle; durable acceptances require reconciliation".into(), }, Ok(()) => DrainOutcome::Drained, }; diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs index 4debb2a0cc..cc74b08ea4 100644 --- a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -83,3 +83,29 @@ async fn actual_background_self_shutdown_refuses_before_closing_and_can_finish( assert_eq!(module.saves.load(Ordering::SeqCst), 1); Ok(()) } + +#[tokio::test] +async fn storage_unwind_cannot_release_custody_as_a_clean_shutdown() -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("storage-unwind", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new(CommandExecutor::new(runtime.registry.clone())); + executor.set_task_ledger(ledger)?; + adapter.unwind_next_write(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( + uuid::Uuid::new_v4(), + )); + let result = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await; + assert!(result.is_err()); + assert_eq!(runtime.registry.task_admission.in_flight(), 0); + let receipt = runtime.shutdown().await; + assert!(!receipt.tasks.is_quiet()); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + Ok(()) +} From bab6c1b5ec779bc3762fc9d4a05d1526d3ed7e5a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 00:18:00 -0500 Subject: [PATCH 68/88] test(tasks): assert unresolved custody outcome instead of stale prose --- core/continuum-kernel/src/runtime/runtime/runtime.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 42b0fd5643..660b59ab3e 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -176,7 +176,8 @@ mod background_custody_tests { .await; assert!(!receipt.state_is_durable()); assert_eq!(module.saves.load(Ordering::SeqCst), 0); - assert!(receipt.summary().contains("terminal persistence failed")); + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); } } From 172bf9d150502cb4a5aead7f6a8af4c9ce658809 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 00:36:34 -0500 Subject: [PATCH 69/88] test(tasks): prove terminal storage unwind withholds completion and shutdown --- .../runtime/runtime/self_shutdown_tests.rs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs index cc74b08ea4..c17f7303a9 100644 --- a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -109,3 +109,67 @@ async fn storage_unwind_cannot_release_custody_as_a_clean_shutdown() -> Result<( assert_eq!(module.saves.load(Ordering::SeqCst), 0); Ok(()) } + +struct FailTerminalWrite(Arc); + +#[async_trait::async_trait] +impl CommandInterceptor for FailTerminalWrite { + fn name(&self) -> &'static str { + "fail-terminal-write" + } + + async fn try_route( + &self, + _: &str, + _: &serde_json::Value, + _: Option<&crate::routing::CallerIdentity>, + ) -> Result { + // Acceptance has already committed. Fail only the terminal write after + // a successful handler result, outside the handler unwind boundary. + self.0.unwind_next_write(); + Ok(InterceptorOutcome::Handled(CommandResult::Json( + serde_json::Value::Null, + ))) + } +} + +#[tokio::test] +async fn terminal_storage_unwind_neither_announces_completion_nor_allows_shutdown( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("terminal-unwind", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()) + .with_message_bus(runtime.bus.clone()) + .with_interceptor(Arc::new(FailTerminalWrite(adapter))), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + tokio::time::timeout( + Duration::from_secs(5), + runtime.registry.task_admission.close_and_wait(), + ) + .await + .map_err(|error| error.to_string())?; + assert_eq!(ledger.pending(handle, owner).await?, None); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + let receipt = runtime.shutdown().await; + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + Ok(()) +} From 18b707be4043f80a59f860ee4e0ec38d524bc346 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 00:56:13 -0500 Subject: [PATCH 70/88] refactor(runtime): consolidate custody tests under one test module --- .../src/runtime/runtime/runtime.rs | 181 +----------------- .../src/runtime/runtime/runtime_tests.rs | 172 +++++++++++++++++ 2 files changed, 174 insertions(+), 179 deletions(-) create mode 100644 core/continuum-kernel/src/runtime/runtime/runtime_tests.rs diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 660b59ab3e..efa92dc1eb 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -1,185 +1,8 @@ use super::*; #[cfg(test)] -#[path = "self_shutdown_tests.rs"] -mod self_shutdown_tests; - -#[cfg(test)] -mod background_custody_tests { - use super::*; - use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; - use std::sync::atomic::Ordering; - - #[tokio::test] - async fn shutdown_waits_for_acceptance_and_terminal_storage_after_receipt_is_forgotten( - ) -> Result<(), String> { - use crate::orm::gated_adapter::GatedAdapter; - use crate::runtime::tasks::TaskLedger; - use crate::runtime::CommandExecutor; - let runtime = Runtime::new(); - let (module, _) = RecordingModule::new("storage-boundary", Vec::new()); - runtime.register(module.clone()); - let (adapter, _directory) = crate::orm::store::fresh_adapter().await; - let adapter = Arc::new(GatedAdapter::new(adapter)); - let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); - let executor = Arc::new( - CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), - ); - executor.set_task_ledger(ledger.clone())?; - let mut events = runtime.bus.receiver(); - let owner = uuid::Uuid::new_v4(); - let caller = crate::routing::CallerIdentity::local_persona( - crate::identity::PeerId::from_uuid(owner), - ); - let acceptance = adapter.pause_next_write(); - { - let receipt = executor.dispatch_background( - "test/unhandled", - serde_json::Value::Null, - Some(caller), - ); - tokio::pin!(receipt); - assert!(futures::poll!(receipt.as_mut()).is_pending()); - acceptance.entered.notified().await; - // Drop the actual caller while its durable acceptance write is paused. - } - let shutdown = runtime.shutdown_within(std::time::Duration::from_secs(30)); - tokio::pin!(shutdown); - assert!(futures::poll!(shutdown.as_mut()).is_pending()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - let terminal = adapter.pause_next_write(); - acceptance.release.notify_one(); - terminal.entered.notified().await; - assert!(futures::poll!(shutdown.as_mut()).is_pending()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - terminal.release.notify_one(); - let receipt = shutdown.await; - assert!(receipt.state_is_durable()); - assert_eq!(module.saves.load(Ordering::SeqCst), 1); - let completion = events.recv().await.map_err(|error| error.to_string())?; - let task = completion.payload["handle"] - .as_str() - .ok_or("missing completion handle")?; - let task = uuid::Uuid::parse_str(task).map_err(|error| error.to_string())?; - // The command was unhandled, but its failure is durable and deliverable; - // module shutdown cannot overtake either storage boundary. - assert!(matches!( - ledger.pending(task, owner).await?, - Some(crate::runtime::tasks::TaskEnd::Failed { .. }) - )); - Ok(()) - } - - #[tokio::test(start_paused = true)] - async fn shutdown_owner_retries_withheld_custody_without_repeating_module_stop( - ) -> Result<(), String> { - let runtime = Arc::new(Runtime::new()); - let (module, _) = RecordingModule::new("retry-custody-store", Vec::new()); - runtime.register(module.clone()); - let custody = runtime - .registry - .task_admission - .admit_owned() - .ok_or("admission refused")?; - let operation = ShutdownOperation::new(); - let mut first = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); - first.changed().await.map_err(|error| error.to_string())?; - let receipt = first - .borrow_and_update() - .clone() - .ok_or("missing withheld receipt")?; - assert!(!receipt.tasks.is_quiet()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - drop(first); - drop(custody); - let mut retry = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); - assert!(retry.borrow().is_none()); - retry.changed().await.map_err(|error| error.to_string())?; - let receipt = retry - .borrow_and_update() - .clone() - .ok_or("missing completed receipt")?; - assert!(receipt.state_is_durable()); - let again = operation.begin(Some(runtime), std::time::Duration::ZERO); - assert_eq!(again.borrow().as_ref(), Some(&receipt)); - assert_eq!(module.saves.load(Ordering::SeqCst), 1); - Ok(()) - } - - #[tokio::test(start_paused = true)] - async fn unfinished_custody_withholds_module_stop_and_a_later_drain_can_finish( - ) -> Result<(), String> { - let runtime = Runtime::new(); - let (module, _) = RecordingModule::new("custody-store", Vec::new()); - runtime.register(module.clone()); - let custody = runtime - .registry - .task_admission - .admit_owned() - .ok_or("admission refused")?; - let receipt = runtime - .shutdown_within(std::time::Duration::from_millis(10)) - .await; - assert!(!receipt.state_is_durable()); - assert!(!receipt.tasks.is_quiet()); - assert!(receipt.modules.is_empty()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - assert!(runtime.registry.task_admission.admit_owned().is_none()); - drop(custody); - let receipt = runtime - .shutdown_within(std::time::Duration::from_millis(10)) - .await; - assert!(receipt.state_is_durable()); - assert_eq!(module.saves.load(Ordering::SeqCst), 1); - Ok(()) - } - - #[tokio::test] - async fn cancelling_shutdown_wait_does_not_release_task_custody() -> Result<(), String> { - let runtime = Runtime::new(); - let (module, _) = RecordingModule::new("cancel-custody-store", Vec::new()); - runtime.register(module.clone()); - let custody = runtime - .registry - .task_admission - .admit_owned() - .ok_or("admission refused")?; - { - let stop = runtime.shutdown_within(std::time::Duration::from_secs(1)); - tokio::pin!(stop); - assert!(futures::poll!(stop.as_mut()).is_pending()); - } - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - assert_eq!(runtime.registry.task_admission.in_flight(), 1); - assert!(runtime.registry.task_admission.admit_owned().is_none()); - drop(custody); - assert!(runtime - .shutdown_within(std::time::Duration::from_secs(1)) - .await - .state_is_durable()); - Ok(()) - } - - #[tokio::test] - async fn failed_terminal_persistence_is_not_a_quiet_runtime() { - let runtime = Runtime::new(); - let (module, _) = RecordingModule::new("failed-custody-store", Vec::new()); - runtime.register(module.clone()); - // Inject the execution owner's terminal-write failure fact; this tests - // shutdown's consumption of it, not the storage adapter's fault handling. - runtime - .registry - .task_persistence_failed - .store(true, Ordering::Release); - let receipt = runtime - .shutdown_within(std::time::Duration::from_secs(1)) - .await; - assert!(!receipt.state_is_durable()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); - assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); - assert!(receipt.modules.is_empty()); - } -} +#[path = "runtime_tests.rs"] +mod tests; impl Runtime { /// `shutdown`, with the per-phase bound passed IN. diff --git a/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs b/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs new file mode 100644 index 0000000000..ba4343e2b9 --- /dev/null +++ b/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs @@ -0,0 +1,172 @@ +#[path = "self_shutdown_tests.rs"] +mod self_shutdown_tests; + +use super::*; +use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; +use std::sync::atomic::Ordering; + +#[tokio::test] +async fn shutdown_waits_for_acceptance_and_terminal_storage_after_receipt_is_forgotten( +) -> Result<(), String> { + use crate::orm::gated_adapter::GatedAdapter; + use crate::runtime::tasks::TaskLedger; + use crate::runtime::CommandExecutor; + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("storage-boundary", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(GatedAdapter::new(adapter)); + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let mut events = runtime.bus.receiver(); + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let acceptance = adapter.pause_next_write(); + { + let receipt = + executor.dispatch_background("test/unhandled", serde_json::Value::Null, Some(caller)); + tokio::pin!(receipt); + assert!(futures::poll!(receipt.as_mut()).is_pending()); + acceptance.entered.notified().await; + // Drop the actual caller while its durable acceptance write is paused. + } + let shutdown = runtime.shutdown_within(std::time::Duration::from_secs(30)); + tokio::pin!(shutdown); + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + let terminal = adapter.pause_next_write(); + acceptance.release.notify_one(); + terminal.entered.notified().await; + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + terminal.release.notify_one(); + let receipt = shutdown.await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + let completion = events.recv().await.map_err(|error| error.to_string())?; + let task = completion.payload["handle"] + .as_str() + .ok_or("missing completion handle")?; + let task = uuid::Uuid::parse_str(task).map_err(|error| error.to_string())?; + // The command was unhandled, but its failure is durable and deliverable; + // module shutdown cannot overtake either storage boundary. + assert!(matches!( + ledger.pending(task, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Failed { .. }) + )); + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn shutdown_owner_retries_withheld_custody_without_repeating_module_stop( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("retry-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let operation = ShutdownOperation::new(); + let mut first = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + first.changed().await.map_err(|error| error.to_string())?; + let receipt = first + .borrow_and_update() + .clone() + .ok_or("missing withheld receipt")?; + assert!(!receipt.tasks.is_quiet()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + drop(first); + drop(custody); + let mut retry = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + assert!(retry.borrow().is_none()); + retry.changed().await.map_err(|error| error.to_string())?; + let receipt = retry + .borrow_and_update() + .clone() + .ok_or("missing completed receipt")?; + assert!(receipt.state_is_durable()); + let again = operation.begin(Some(runtime), std::time::Duration::ZERO); + assert_eq!(again.borrow().as_ref(), Some(&receipt)); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn unfinished_custody_withholds_module_stop_and_a_later_drain_can_finish( +) -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(!receipt.state_is_durable()); + assert!(!receipt.tasks.is_quiet()); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test] +async fn cancelling_shutdown_wait_does_not_release_task_custody() -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("cancel-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + { + let stop = runtime.shutdown_within(std::time::Duration::from_secs(1)); + tokio::pin!(stop); + assert!(futures::poll!(stop.as_mut()).is_pending()); + } + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert_eq!(runtime.registry.task_admission.in_flight(), 1); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + assert!(runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await + .state_is_durable()); + Ok(()) +} + +#[tokio::test] +async fn failed_terminal_persistence_is_not_a_quiet_runtime() { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("failed-custody-store", Vec::new()); + runtime.register(module.clone()); + // Inject the execution owner's terminal-write failure fact; this tests + // shutdown's consumption of it, not the storage adapter's fault handling. + runtime + .registry + .task_persistence_failed + .store(true, Ordering::Release); + let receipt = runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await; + assert!(!receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); +} From b697556a9a1123c9142b857530d8a051db626977 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 01:17:17 -0500 Subject: [PATCH 71/88] refactor(admission): delete unused private resource lease gate --- .../src/inference/resource_admission.rs | 11 +- .../src/inference/resource_admission/gate.rs | 212 ------------------ .../cognition/ResourceAdmissionPolicy.ts | 6 - protocol/typescript/cognition/index.ts | 1 - protocol/typescript/index.ts | 1 - 5 files changed, 1 insertion(+), 230 deletions(-) delete mode 100644 core/continuum-engine/src/inference/resource_admission/gate.rs delete mode 100644 protocol/typescript/cognition/ResourceAdmissionPolicy.ts diff --git a/core/continuum-engine/src/inference/resource_admission.rs b/core/continuum-engine/src/inference/resource_admission.rs index 888f737714..4e9a5afe31 100644 --- a/core/continuum-engine/src/inference/resource_admission.rs +++ b/core/continuum-engine/src/inference/resource_admission.rs @@ -1,18 +1,10 @@ -//! Shared Rust resource admission, and the serving lanes' admission and ledger. -//! -//! This is the small lease gate that every expensive subsystem can use -//! while the substrate governor becomes the process-wide allocator: -//! inference, training, rendering, audio, TTS, STT, classifiers, RAG, -//! and background work. Callers submit typed resource policy; the gate -//! admits or denies before work starts and returns an RAII guard that -//! releases the lease on every exit path. +//! Serving lanes' admission and ledger. //! //! The serving lanes, their permits and the model-call ledger (in-flight gauges, //! prompt samples, measured waits) are serving facts, so they live with the engine; //! the mind's own turn bookkeeping is `cognition::turn_ledger`, which calls down here. -mod gate; mod lanes; mod metrics; mod progress; @@ -20,7 +12,6 @@ mod serving_lane_permit; #[cfg(test)] mod tests; -pub use gate::*; pub use lanes::*; pub use metrics::*; pub use progress::{LaneWait, LaneProgress}; diff --git a/core/continuum-engine/src/inference/resource_admission/gate.rs b/core/continuum-engine/src/inference/resource_admission/gate.rs deleted file mode 100644 index f0675c88e5..0000000000 --- a/core/continuum-engine/src/inference/resource_admission/gate.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! The hard resource-admission gate and its lease-backed guard. - -use crate::resources::throughput_class::{ResourceClass, TargetSilicon}; -use crate::resources::throughput_lease::{ - ThroughputLease, ThroughputLeaseError, ThroughputLeaseRegistry, ThroughputLeaseRevocationPolicy, -}; -use serde::{Deserialize, Serialize}; -use std::sync::{Mutex, MutexGuard}; -use ts_rs::TS; - -#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/ResourceAdmissionPolicy.ts" -)] -pub struct ResourceAdmissionPolicy { - pub resource_class: ResourceClass, - pub target_silicon: TargetSilicon, - pub max_concurrency: usize, - pub max_cost_units: u32, - pub cost_units: u32, - #[ts(type = "number")] - pub lease_ttl_ms: u64, - pub revocation_policy: ThroughputLeaseRevocationPolicy, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ResourceAdmissionRequest { - pub lease_id: String, - pub artifact_key: String, - pub holder_id: String, - pub policy: ResourceAdmissionPolicy, - pub now_ms: u64, -} - -#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] -pub enum ResourceAdmissionError { - #[error("invalid resource admission policy: {reason}")] - InvalidPolicy { reason: String }, - #[error("resource admission denied: {reason}")] - Denied { reason: String }, - #[error("resource lease error: {reason}")] - Lease { reason: String }, -} - -#[derive(Debug, Default)] -pub struct ResourceAdmissionGate { - registry: Mutex, -} - -impl ResourceAdmissionGate { - pub fn new() -> Self { - Self::default() - } - - pub fn acquire( - &'static self, - request: ResourceAdmissionRequest, - ) -> Result { - validate_policy(&request.policy)?; - - let lease = ThroughputLease { - lease_id: request.lease_id.clone(), - artifact_key: request.artifact_key, - resource_class: request.policy.resource_class, - target_silicon: request.policy.target_silicon, - holder_id: request.holder_id, - cost_units: request.policy.cost_units, - acquired_at_ms: request.now_ms, - expires_at_ms: request.now_ms.saturating_add(request.policy.lease_ttl_ms), - revocation_policy: request.policy.revocation_policy, - }; - - let mut registry = self.lock_registry(); - registry.expire(request.now_ms); - let snapshot = registry.snapshot(request.now_ms); - let active_count = snapshot - .active - .iter() - .filter(|lease| lease.target_silicon == request.policy.target_silicon) - .count(); - let active_cost = snapshot - .cost_by_target_silicon - .get(&request.policy.target_silicon) - .copied() - .unwrap_or(0); - - if active_count >= request.policy.max_concurrency { - return Err(ResourceAdmissionError::Denied { - reason: format!( - "resource_class={:?} target_silicon={:?} active_count={} max_concurrency={}", - request.policy.resource_class, - request.policy.target_silicon, - active_count, - request.policy.max_concurrency - ), - }); - } - if active_cost.saturating_add(request.policy.cost_units) > request.policy.max_cost_units { - return Err(ResourceAdmissionError::Denied { - reason: format!( - "resource_class={:?} target_silicon={:?} active_cost={} requested_cost={} max_cost_units={}", - request.policy.resource_class, - request.policy.target_silicon, - active_cost, - request.policy.cost_units, - request.policy.max_cost_units - ), - }); - } - - registry - .acquire(lease, request.now_ms) - .map_err(|err| ResourceAdmissionError::Lease { - reason: format_lease_error(err), - })?; - - Ok(ResourceAdmissionGuard { - gate: self, - lease_id: Some(request.lease_id), - }) - } - - pub(super) fn release(&self, lease_id: &str) -> Result { - self.lock_registry().release(lease_id) - } - - pub(super) fn lock_registry(&self) -> MutexGuard<'_, ThroughputLeaseRegistry> { - self.registry - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - } - - #[cfg(any(test, feature = "test-fixtures"))] - pub fn reset_for_test(&self) { - *self.lock_registry() = ThroughputLeaseRegistry::new(); - } - - #[cfg(any(test, feature = "test-fixtures"))] - pub fn active_count_for_test(&self, now_ms: u64) -> usize { - self.lock_registry().snapshot(now_ms).active.len() - } -} - -#[derive(Debug)] -pub struct ResourceAdmissionGuard { - gate: &'static ResourceAdmissionGate, - lease_id: Option, -} - -impl ResourceAdmissionGuard { - #[cfg(any(test, feature = "test-fixtures"))] - pub fn release(mut self) -> Result { - let lease_id = self - .lease_id - .take() - .expect("resource admission guard must contain a lease id before release"); - self.gate.release(&lease_id) - } -} - -impl Drop for ResourceAdmissionGuard { - fn drop(&mut self) { - let Some(lease_id) = self.lease_id.take() else { - return; - }; - let _ = self.gate.release(&lease_id); - } -} - -pub(super) fn validate_policy(policy: &ResourceAdmissionPolicy) -> Result<(), ResourceAdmissionError> { - if policy.max_concurrency == 0 { - return Err(invalid_policy("max_concurrency must be greater than zero")); - } - if policy.cost_units == 0 { - return Err(invalid_policy("cost_units must be greater than zero")); - } - if policy.max_cost_units == 0 { - return Err(invalid_policy("max_cost_units must be greater than zero")); - } - if policy.cost_units > policy.max_cost_units { - return Err(invalid_policy(format!( - "cost_units={} exceeds max_cost_units={}", - policy.cost_units, policy.max_cost_units - ))); - } - if policy.lease_ttl_ms == 0 { - return Err(invalid_policy("lease_ttl_ms must be greater than zero")); - } - Ok(()) -} - -pub(super) fn invalid_policy(reason: impl Into) -> ResourceAdmissionError { - ResourceAdmissionError::InvalidPolicy { - reason: reason.into(), - } -} - -pub(super) fn format_lease_error(err: ThroughputLeaseError) -> String { - match err { - ThroughputLeaseError::DuplicateLease { lease_id } => { - format!("duplicate lease_id={lease_id}") - } - ThroughputLeaseError::MissingLease { lease_id } => { - format!("missing lease_id={lease_id}") - } - ThroughputLeaseError::ExpiredLease { lease_id } => { - format!("expired lease_id={lease_id}") - } - } -} diff --git a/protocol/typescript/cognition/ResourceAdmissionPolicy.ts b/protocol/typescript/cognition/ResourceAdmissionPolicy.ts deleted file mode 100644 index 2f9a613ace..0000000000 --- a/protocol/typescript/cognition/ResourceAdmissionPolicy.ts +++ /dev/null @@ -1,6 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ResourceClass } from "./ResourceClass"; -import type { TargetSilicon } from "./TargetSilicon"; -import type { ThroughputLeaseRevocationPolicy } from "./ThroughputLeaseRevocationPolicy"; - -export type ResourceAdmissionPolicy = { resourceClass: ResourceClass, targetSilicon: TargetSilicon, maxConcurrency: number, maxCostUnits: number, costUnits: number, leaseTtlMs: number, revocationPolicy: ThroughputLeaseRevocationPolicy, }; diff --git a/protocol/typescript/cognition/index.ts b/protocol/typescript/cognition/index.ts index a27a976f76..c763f2579e 100644 --- a/protocol/typescript/cognition/index.ts +++ b/protocol/typescript/cognition/index.ts @@ -115,7 +115,6 @@ export type { RegisterDomainKeywordsParams } from './RegisterDomainKeywordsParam export type { RegisterDomainKeywordsResult } from './RegisterDomainKeywordsResult'; export type { ResolutionError } from './ResolutionError'; export type { ResolvedModel } from './ResolvedModel'; -export type { ResourceAdmissionPolicy } from './ResourceAdmissionPolicy'; export type { ResourceClass } from './ResourceClass'; export type { ResponseDecision } from './ResponseDecision'; export type { ResponseProposal } from './ResponseProposal'; diff --git a/protocol/typescript/index.ts b/protocol/typescript/index.ts index d27d5f6fd4..66f325a468 100644 --- a/protocol/typescript/index.ts +++ b/protocol/typescript/index.ts @@ -78,7 +78,6 @@ export type { RecipeTurnBatchRequest } from './cognition'; export type { RecipeTurnTrigger } from './cognition'; export type { ResolutionError } from './cognition'; export type { ResolvedModel } from './cognition'; -export type { ResourceAdmissionPolicy } from './cognition'; export type { ResourceClass } from './cognition'; export type { ResponseDecision } from './cognition'; export type { ResponseProposal } from './cognition'; From 467e3d9402046b62df27e309fdc74c7e451bfa95 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 01:56:52 -0500 Subject: [PATCH 72/88] fix(tasks): retain unresolved custody after acceptance storage errors --- .../continuum-kernel/src/orm/gated_adapter.rs | 15 ++++++- .../runtime/command_executor/background.rs | 6 +-- .../runtime/runtime/self_shutdown_tests.rs | 39 +++++++++++++++++++ 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index 6b2626d27d..8760b8a041 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -33,17 +33,22 @@ pub(crate) struct GatedAdapter { inner: Arc, next: Mutex>, unwind_next: std::sync::atomic::AtomicBool, + fail_after_create: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false) } } pub(crate) fn unwind_next_write(&self) { self.unwind_next.store(true, std::sync::atomic::Ordering::SeqCst); } + pub(crate) fn fail_after_next_create(&self) { + self.fail_after_create.store(true, std::sync::atomic::Ordering::SeqCst); + } + /// Hold the next write at a gate. Only that one write is held. pub(crate) fn pause_next_write(&self) -> PausedWrite { let paused = PausedWrite { @@ -96,7 +101,13 @@ impl StorageAdapter for GatedAdapter { Err("the gated fixture does not own its adapter".to_string()) } async fn create(&self, record: DataRecord) -> StorageResult { - self.write(move |a| Box::pin(async move { a.create(record).await })).await + let fail = self.fail_after_create.swap(false, std::sync::atomic::Ordering::SeqCst); + let result = self.write(move |a| Box::pin(async move { a.create(record).await })).await; + if fail && result.success { + StorageResult::err("injected loss of write acknowledgement after commit") + } else { + result + } } async fn read(&self, collection: &str, id: &UUID) -> StorageResult { self.inner.read(collection, id).await diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index aff3576cef..cb534a7607 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -7,7 +7,8 @@ use serde_json::Value; use std::sync::Arc; use uuid::Uuid; -// Custody is unresolved until acceptance is refused or a terminal is durable. +// Custody is unresolved until a terminal is durable. A storage error alone +// cannot certify that acceptance did not commit. // An unexpected unwind/drop in storage must not turn a released permit into a // successful shutdown. Handler unwinds still produce their ordinary terminal. struct PersistenceCustody<'a> { @@ -84,8 +85,7 @@ impl CommandExecutor { let handle = match ledger.accept(owner, command.to_string()).await { Ok(handle) => handle, Err(error) => { - persistence.settled = true; - let _ = accepted.send(Err(DispatchFailure::not_committed(error))); + let _ = accepted.send(Err(DispatchFailure::uncertain(error))); return; } }; diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs index c17f7303a9..29dd0d62e3 100644 --- a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -112,6 +112,45 @@ async fn storage_unwind_cannot_release_custody_as_a_clean_shutdown() -> Result<( struct FailTerminalWrite(Arc); +#[tokio::test] +async fn lost_acceptance_acknowledgement_is_uncertain_and_withholds_shutdown() -> Result<(), String> +{ + use crate::orm::adapter::StorageAdapter; + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("acceptance-ack-loss", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new(CommandExecutor::new(runtime.registry.clone())); + executor.set_task_ledger(ledger)?; + adapter.fail_after_next_create(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( + uuid::Uuid::new_v4(), + )); + let result = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await; + let Err(error) = result else { + return Err("lost acceptance acknowledgement was reported as success".into()); + }; + assert_eq!( + error.outcome, + crate::runtime::command_executor::DispatchOutcome::Uncertain + ); + // The adapter really committed the acceptance before losing its reply. + let count = adapter + .count(crate::orm::query::QueryBuilder::new("kernel_task_facts").build()) + .await; + assert!(count.success); + assert_eq!(count.data, Some(1)); + let receipt = runtime.shutdown().await; + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + Ok(()) +} + #[async_trait::async_trait] impl CommandInterceptor for FailTerminalWrite { fn name(&self) -> &'static str { From a158b65dbe2ea374b38100ecb46d261d805989c5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 01:06:20 -0600 Subject: [PATCH 73/88] fix(tasks): resolve lost acceptance acknowledgement from exact durable fact --- .../runtime/runtime/self_shutdown_tests.rs | 36 ++++++++---------- core/continuum-kernel/src/runtime/tasks.rs | 37 ++++++++++++------- 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs index 29dd0d62e3..85eb0e6f2e 100644 --- a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -113,8 +113,7 @@ async fn storage_unwind_cannot_release_custody_as_a_clean_shutdown() -> Result<( struct FailTerminalWrite(Arc); #[tokio::test] -async fn lost_acceptance_acknowledgement_is_uncertain_and_withholds_shutdown() -> Result<(), String> -{ +async fn verified_acceptance_readback_recovers_lost_acknowledgement() -> Result<(), String> { use crate::orm::adapter::StorageAdapter; let runtime = Arc::new(Runtime::new()); let (module, _) = RecordingModule::new("acceptance-ack-loss", Vec::new()); @@ -123,31 +122,28 @@ async fn lost_acceptance_acknowledgement_is_uncertain_and_withholds_shutdown() - let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); let executor = Arc::new(CommandExecutor::new(runtime.registry.clone())); - executor.set_task_ledger(ledger)?; + executor.set_task_ledger(ledger.clone())?; adapter.fail_after_next_create(); - let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( - uuid::Uuid::new_v4(), - )); - let result = executor + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) - .await; - let Err(error) = result else { - return Err("lost acceptance acknowledgement was reported as success".into()); - }; - assert_eq!( - error.outcome, - crate::runtime::command_executor::DispatchOutcome::Uncertain - ); + .await + .map_err(|error| error.message)?; + let receipt = runtime.shutdown().await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Failed { .. }) + )); // The adapter really committed the acceptance before losing its reply. let count = adapter .count(crate::orm::query::QueryBuilder::new("kernel_task_facts").build()) .await; assert!(count.success); - assert_eq!(count.data, Some(1)); - let receipt = runtime.shutdown().await; - assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); - assert!(receipt.modules.is_empty()); - assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert_eq!(count.data, Some(2)); Ok(()) } diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index b7c5a5c48e..f2f50feba7 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -116,18 +116,27 @@ impl TaskLedger { pub async fn accept(&self, owner: Uuid, command: String) -> Result { let task = Uuid::new_v4(); - self.facts - .save( - task, - &TaskFact { - task, - owner, - fact: Fact::Accepted { command }, - }, - ) - .await - .map_err(|e| e.to_string())?; - Ok(task) + let acceptance = TaskFact { + task, + owner, + fact: Fact::Accepted { command }, + }; + match self.facts.save(task, &acceptance).await { + Ok(()) => Ok(task), + Err(write_error) => { + // A failed acknowledgement does not prove the write failed. + // Resolve this exact attempted acceptance, without a second + // insert or execution owner. Only an identical durable fact + // authorizes execution; absence or read failure stays uncertain. + match self.facts.find_by_id(task).await { + Ok(Some(stored)) if stored == acceptance => Ok(task), + Ok(_) => Err(write_error.to_string()), + Err(read_error) => Err(format!( + "acceptance write failed: {write_error}; readback failed: {read_error}" + )), + } + } + } } async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { @@ -312,7 +321,9 @@ mod tests { drop(second); let reopened = TaskLedger::new(adapter).await?; assert_eq!(reopened.pending(task, owner).await?, Some(winner.clone())); - let page = reopened.pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?).await?; + let page = reopened + .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) + .await?; assert_eq!(page.ends, vec![(task, winner.clone())]); assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); assert!(reopened.pending(task, Uuid::new_v4()).await.is_err()); From 17b72b083188c09bdc6dcaf728b8ffd68307568d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 01:36:54 -0600 Subject: [PATCH 74/88] test(tasks): preserve custody when acceptance readback fails --- .../continuum-kernel/src/orm/gated_adapter.rs | 10 +++- .../runtime/runtime/self_shutdown_tests.rs | 46 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index 8760b8a041..ab15278a51 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -34,11 +34,12 @@ pub(crate) struct GatedAdapter { next: Mutex>, unwind_next: std::sync::atomic::AtomicBool, fail_after_create: std::sync::atomic::AtomicBool, + fail_query: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false) } } pub(crate) fn unwind_next_write(&self) { @@ -49,6 +50,10 @@ impl GatedAdapter { self.fail_after_create.store(true, std::sync::atomic::Ordering::SeqCst); } + pub(crate) fn fail_next_query(&self) { + self.fail_query.store(true, std::sync::atomic::Ordering::SeqCst); + } + /// Hold the next write at a gate. Only that one write is held. pub(crate) fn pause_next_write(&self) -> PausedWrite { let paused = PausedWrite { @@ -113,6 +118,9 @@ impl StorageAdapter for GatedAdapter { self.inner.read(collection, id).await } async fn query(&self, query: StorageQuery) -> StorageResult> { + if self.fail_query.swap(false, std::sync::atomic::Ordering::SeqCst) { + return StorageResult::err("injected query failure"); + } self.inner.query(query).await } async fn query_with_join(&self, query: StorageQuery) -> StorageResult> { diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs index 85eb0e6f2e..7de2e2c3d6 100644 --- a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -147,6 +147,52 @@ async fn verified_acceptance_readback_recovers_lost_acknowledgement() -> Result< Ok(()) } +#[tokio::test] +async fn unreadable_committed_acceptance_retains_custody_without_execution() -> Result<(), String> { + use crate::orm::adapter::StorageAdapter; + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("acceptance-readback-failure", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), + ); + executor.set_task_ledger(ledger)?; + adapter.fail_after_next_create(); + adapter.fail_next_query(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( + uuid::Uuid::new_v4(), + )); + let error = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await + .err() + .ok_or("unverified acceptance incorrectly authorized execution")?; + assert_eq!( + error.outcome, + crate::runtime::command_executor::DispatchOutcome::Uncertain + ); + let receipt = runtime.shutdown().await; + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + // The failed acknowledgement and failed read must not erase the committed + // acceptance, authorize a second insert, or publish a false completion. + let count = adapter + .count(crate::orm::query::QueryBuilder::new("kernel_task_facts").build()) + .await; + assert!(count.success); + assert_eq!(count.data, Some(1)); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + Ok(()) +} + #[async_trait::async_trait] impl CommandInterceptor for FailTerminalWrite { fn name(&self) -> &'static str { From 8ba457c211e4a8bfc165ccc96e78d7d50a2b5544 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 02:06:37 -0600 Subject: [PATCH 75/88] fix(process): refuse indeterminate Windows process observation --- .../src/kill9_windows_tests.rs | 23 +++++++++++++++++- core/continuum-process/src/owned.rs | 24 +++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/core/continuum-process/src/kill9_windows_tests.rs b/core/continuum-process/src/kill9_windows_tests.rs index 7f55852587..d3ff1c8c57 100644 --- a/core/continuum-process/src/kill9_windows_tests.rs +++ b/core/continuum-process/src/kill9_windows_tests.rs @@ -1,4 +1,4 @@ -use super::terminate_windows_handle; +use super::{terminate_windows_handle, windows_handle_has_exited}; use continuum_kernel::system_resources::process_tree::ProcessIdentity; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::process::{Child, Stdio}; @@ -68,3 +68,24 @@ fn live_process_access_denial_remains_a_refusal() -> Result<(), Box Result<(), Box> { + let mut child = waiting_child()?; + // SAFETY: query-only access deliberately omits the right required to wait. + let raw = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, child.id()) }; + let observed = if raw.is_null() { + Err(std::io::Error::last_os_error().to_string()) + } else { + // SAFETY: successful OpenProcess transferred one owned handle. + let handle = unsafe { OwnedHandle::from_raw_handle(raw) }; + windows_handle_has_exited(&handle) + }; + let still_live = child.try_wait()?.is_none(); + drop(child.stdin.take()); + child.wait()?; + assert!(!raw.is_null(), "fixture must acquire a query-only handle"); + assert!(observed.is_err_and(|error| error.contains("WaitForSingleObject"))); + assert!(still_live); + Ok(()) +} diff --git a/core/continuum-process/src/owned.rs b/core/continuum-process/src/owned.rs index 1b5da1167c..9974165949 100644 --- a/core/continuum-process/src/owned.rs +++ b/core/continuum-process/src/owned.rs @@ -105,9 +105,9 @@ pub fn signal_if_same(who: ProcessIdentity) -> Result { #[cfg(windows)] fn signal_windows_identity(who: ProcessIdentity) -> Result { use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; - use windows_sys::Win32::Foundation::{FILETIME, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0}; + use windows_sys::Win32::Foundation::{FILETIME, ERROR_INVALID_PARAMETER}; use windows_sys::Win32::System::Threading::{ - GetProcessTimes, OpenProcess, WaitForSingleObject, + GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, PROCESS_SYNCHRONIZE, }; // Pin the incarnation before inspecting or signalling it: taskkill's PID @@ -134,13 +134,29 @@ fn signal_windows_identity(who: ProcessIdentity) -> Result { let ticks = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime); let started = (ticks / 10_000_000).checked_sub(11_644_473_600) .ok_or("process creation time precedes the Unix epoch")?; - // SAFETY: the owned handle stays open through the nonblocking wait. - if started != who.start_time || unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_OBJECT_0 { + if started != who.start_time || windows_handle_has_exited(&process)? { return Ok(false); } terminate_windows_handle(&process, who) } +// A failed observation is neither a live process nor proof of exit. Keep the +// native error, rather than permitting termination after an indeterminate wait. +#[cfg(windows)] +fn windows_handle_has_exited( + process: &impl std::os::windows::io::AsRawHandle, +) -> Result { + use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + // SAFETY: caller retains the handle throughout this nonblocking wait. + match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } { + WAIT_OBJECT_0 => Ok(true), + WAIT_TIMEOUT => Ok(false), + WAIT_FAILED => Err(format!("WaitForSingleObject: {}", std::io::Error::last_os_error())), + status => Err(format!("unexpected process wait status: {status}")), + } +} + // The caller has verified creation time while holding this handle. Keep the // termination/exit race on that handle, including when signalling fails. #[cfg(windows)] From 318e7742dc4d8a53f11c502af8f651e3c6737d0e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 03:15:58 -0600 Subject: [PATCH 76/88] test(tasks): prove terminal and delivery reply-loss recovery --- core/continuum-kernel/src/runtime/tasks.rs | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index f2f50feba7..6d08afb48f 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -396,6 +396,34 @@ mod tests { } use crate::orm::gated_adapter::GatedAdapter; + #[tokio::test] + async fn lost_terminal_and_delivery_replies_survive_reopen_without_duplicate_facts( + ) -> Result<(), String> { + use crate::orm::adapter::StorageAdapter; + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(GatedAdapter::new(adapter)); + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = ledger.accept(owner, "test/reply-loss".into()).await?; + adapter.fail_after_next_create(); + assert_eq!(ledger.finish(task, owner, TaskEnd::Stopped).await?, TaskEnd::Stopped); + drop(ledger); + let reopened = TaskLedger::new(adapter.clone()).await?; + assert_eq!(reopened.pending(task, owner).await?, Some(TaskEnd::Stopped)); + adapter.fail_after_next_create(); + reopened.acknowledge(task, owner).await?; + drop(reopened); + let reopened = TaskLedger::new(adapter.clone()).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, TaskEnd::Stopped); + reopened.acknowledge(task, owner).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + let count = adapter.count(QueryBuilder::new(TaskFact::COLLECTION).build()).await; + assert!(count.success); + assert_eq!(count.data, Some(3), "one acceptance, one end, one delivery fact"); + Ok(()) + } + async fn notified(signal: &tokio::sync::Notify) -> Result<(), String> { tokio::time::timeout(std::time::Duration::from_secs(5), signal.notified()) .await From 6be362053d6dc269e1c8ecc2bbf6f05b388a2d33 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 17:17:02 -0600 Subject: [PATCH 77/88] feat(tasks): persist executor incarnation with task acceptance --- .../tests/task_consumption.rs | 133 ++++++++++++++---- .../src/runtime/command_executor.rs | 29 +++- .../runtime/command_executor/background.rs | 2 +- core/continuum-kernel/src/runtime/tasks.rs | 124 +++++++++++++--- .../src/runtime/tasks/delivery/tests.rs | 69 +++++++-- .../src/runtime/tasks/execution.rs | 19 +++ .../src/runtime/tasks/output.rs | 18 ++- 7 files changed, 326 insertions(+), 68 deletions(-) create mode 100644 core/continuum-kernel/src/runtime/tasks/execution.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index d87fcc6377..e03d7ddcd9 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -17,27 +17,55 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( registry.consume_task_ends(owner, vec![(task, TaskEnd::TimedOut)])?; let cycle = registry.register_from_cfg(cfg_for(owner))?; let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); - let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; - let (view, _) = View::::start(Vec::new(), &[&source as &dyn Source<_>], |claims| { - claims.iter().map(|claim| claim.full_chars).collect() - })?; - assert!(view.render().any(|message| message.text.contains("timed_out task"))); + let source = crate::cognition::context_streams::tasks::Tasks { + memory: &memory, + persona: owner, + }; + let (view, _) = View::::start( + Vec::new(), + &[&source as &dyn Source<_>], + |claims| claims.iter().map(|claim| claim.full_chars).collect(), + )?; + assert!(view + .render() + .any(|message| message.text.contains("timed_out task"))); let mut receipt = crate::cognition::render_receipt::RenderReceipt { - owner, incarnation: memory.incarnation(), request: "submitted-request".to_owned(), view: view.receipt(), + owner, + incarnation: memory.incarnation(), + request: "submitted-request".to_owned(), + view: view.receipt(), }; let exact = receipt.clone(); let isolated = registry.mind_cycle(&owner).ok_or("private cycle absent")?; - isolated.persist_render_receipts(vec![exact.clone()]).await?; - assert_eq!(memory.pending_task_wakes(), vec![task], "private cycles have no live checkpoint authority"); + isolated + .persist_render_receipts(vec![exact.clone()]) + .await?; + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "private cycles have no live checkpoint authority" + ); let mut foreign = exact.clone(); foreign.incarnation = Uuid::new_v4(); - assert!(matches!(cycle.persist_render_receipts(vec![exact.clone(), foreign]).await, - Err(TaskSinkError::CustodyMismatch { .. }))); - assert_eq!(memory.pending_task_wakes(), vec![task], "validate the whole batch before retirement"); - for item in &mut receipt.view.items { item.element = None; } + assert!(matches!( + cycle + .persist_render_receipts(vec![exact.clone(), foreign]) + .await, + Err(TaskSinkError::CustodyMismatch { .. }) + )); + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "validate the whole batch before retirement" + ); + for item in &mut receipt.view.items { + item.element = None; + } assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); - for item in &mut receipt.view.items { item.level = continuum_context::level::Level::Folded; } + for item in &mut receipt.view.items { + item.level = continuum_context::level::Level::Folded; + } assert!(sink.record_rendered(receipt).await?.is_none()); receipt = exact.clone(); for item in &mut receipt.view.items { @@ -45,15 +73,25 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( item.level = continuum_context::level::Level::Repeat { of }; } assert!(sink.record_rendered(receipt).await?.is_none()); - assert_eq!(memory.pending_task_wakes(), vec![task], "repeat is not a newly perceived terminal end"); + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "repeat is not a newly perceived terminal end" + ); receipt = exact.clone(); - for item in &mut receipt.view.items { item.retired = true; } + for item in &mut receipt.view.items { + item.retired = true; + } assert!(sink.record_rendered(receipt).await?.is_none()); assert_eq!(memory.pending_task_wakes(), vec![task]); let obstruction = volatile_path(owner)?.with_extension("json.tmp"); std::fs::create_dir(&obstruction)?; - assert!(matches!(sink.record_rendered(exact.clone()).await, - Err(TaskSinkError::Consumption(TaskConsumptionError::Checkpoint(_))))); + assert!(matches!( + sink.record_rendered(exact.clone()).await, + Err(TaskSinkError::Consumption( + TaskConsumptionError::Checkpoint(_) + )) + )); assert_eq!(memory.pending_task_wakes(), vec![task]); let before_retry = WorkingMemory::new(8); before_retry.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); @@ -64,13 +102,18 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( let checkpoint = std::fs::read(volatile_path(owner)?)?; assert!(sink.record_rendered(exact.clone()).await?.is_none()); assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); - assert!(source.items().is_empty(), "a consumed end must not leave a standing task banner"); + assert!( + source.items().is_empty(), + "a consumed end must not leave a standing task banner" + ); let restored = WorkingMemory::new(8); restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert!(restored.pending_task_wakes().is_empty()); registry.register_from_cfg(cfg_for(owner))?; - assert!(matches!(cycle.persist_render_receipts(vec![exact.clone()]).await, - Err(TaskSinkError::Consumption(TaskConsumptionError::Replaced(id))) if id == owner)); + assert!( + matches!(cycle.persist_render_receipts(vec![exact.clone()]).await, + Err(TaskSinkError::Consumption(TaskConsumptionError::Replaced(id))) if id == owner) + ); // Retaining a cycle must not retain its registry through a reference cycle. let weak = Arc::downgrade(®istry); drop(sink); @@ -189,7 +232,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( #[tokio::test] async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( ) -> Result<(), Box> { - use continuum_kernel::runtime::tasks::{TaskLedger, TaskOutput}; + use continuum_kernel::runtime::tasks::{TaskExecution, TaskLedger, TaskOutput}; let home = tempfile::tempdir()?; let _native = crate::paths::NativeHomeOverride::install(home.path()); let (adapter, _database) = continuum_kernel::orm::store::fresh_adapter().await; @@ -197,7 +240,13 @@ async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( let registry = Arc::new(PersonaWorkspaceRegistry::new()); let sink = ResidentTaskSink::new(Arc::clone(®istry)); let owner = Uuid::new_v4(); - let task = ledger.accept(owner, "test/result".into()).await?; + let task = ledger + .accept( + owner, + "test/result".into(), + TaskExecution::new_command_executor(), + ) + .await?; let end = TaskEnd::Done(TaskOutput::Json( serde_json::json!({"result":"useful result"}), )); @@ -244,27 +293,53 @@ async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); use continuum_context::{source::Source, view::View}; - let source = crate::cognition::context_streams::tasks::Tasks { memory: &memory, persona: owner }; + let source = crate::cognition::context_streams::tasks::Tasks { + memory: &memory, + persona: owner, + }; let (view, _) = View::::start( - Vec::new(), &[&source as &dyn Source<_>], |claims| claims.iter().map(|claim| claim.full_chars).collect() + Vec::new(), + &[&source as &dyn Source<_>], + |claims| claims.iter().map(|claim| claim.full_chars).collect(), )?; let receipt = crate::cognition::render_receipt::RenderReceipt { - owner, incarnation: memory.incarnation(), request: "served-task-result".into(), view: view.receipt(), + owner, + incarnation: memory.incarnation(), + request: "served-task-result".into(), + view: view.receipt(), }; std::fs::create_dir(&obstruction)?; assert!(sink.record_rendered(receipt.clone()).await.is_err()); - assert!(reopened.deliver_page(owner, None, limit, &sink).await.is_err()); + assert!(reopened + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); std::fs::remove_dir(&obstruction)?; sink.record_rendered(receipt).await?; // Crash after the perception checkpoint but before ACK: replay uses the // restored exact receipt, without prompting her again or remembering a handle. registry.register_from_cfg(cfg_for(owner))?; - assert_eq!(reopened.deliver_page(owner, None, limit, &sink).await?.acknowledged, 1); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); assert_eq!(reopened.pending(task, owner).await?, None); registry.register_from_cfg(cfg_for(owner))?; - assert_eq!(reopened.deliver_page(owner, None, limit, &sink).await?.acknowledged, 0); - assert!(registry.cycles.lock()[&owner].working_memory.pending_task_wakes().is_empty()); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert!(registry.cycles.lock()[&owner] + .working_memory + .pending_task_wakes() + .is_empty()); assert_eq!(reopened.terminal(task, owner).await?, Some(end)); Ok(()) } diff --git a/core/continuum-kernel/src/runtime/command_executor.rs b/core/continuum-kernel/src/runtime/command_executor.rs index a99e594279..bdcaa59ce0 100644 --- a/core/continuum-kernel/src/runtime/command_executor.rs +++ b/core/continuum-kernel/src/runtime/command_executor.rs @@ -81,11 +81,17 @@ pub struct DispatchFailure { impl DispatchFailure { pub(crate) fn not_committed(message: String) -> Self { - Self { outcome: DispatchOutcome::NotCommitted, message } + Self { + outcome: DispatchOutcome::NotCommitted, + message, + } } fn uncertain(message: String) -> Self { - Self { outcome: DispatchOutcome::Uncertain, message } + Self { + outcome: DispatchOutcome::Uncertain, + message, + } } } @@ -168,6 +174,7 @@ pub struct CommandExecutor { /// TS bridge. remote_transport: Arc, task_ledger: tokio::sync::OnceCell>, + task_execution: super::tasks::TaskExecution, } impl CommandExecutor { @@ -179,13 +186,17 @@ impl CommandExecutor { policy: Arc::new(crate::routing::AllowAllPolicy), remote_transport: Arc::new(crate::routing::NotImplementedRemoteTransport), task_ledger: tokio::sync::OnceCell::new(), + task_execution: super::tasks::TaskExecution::new_command_executor(), } } /// The trust this executor's policy resolves for `caller`: the same policy its gate uses /// ([`AuthPolicy::caller_trust`](crate::routing::AuthPolicy::caller_trust)). `None` when the /// policy cannot resolve it, which an owner-only handler treats as a refusal. - pub fn caller_trust(&self, caller: Option<&crate::routing::CallerIdentity>) -> Option { + pub fn caller_trust( + &self, + caller: Option<&crate::routing::CallerIdentity>, + ) -> Option { self.policy.caller_trust(caller) } @@ -394,7 +405,8 @@ impl CommandExecutor { // Around-dispatch concerns (a caller's hands admission, the cognition pulse's work // accounting) are installed by their owners at boot (`dispatch_hook`); one refusal // ends the dispatch with nothing committed. - let scopes = super::dispatch_hook::enter_all(caller).map_err(DispatchFailure::not_committed)?; + let scopes = + super::dispatch_hook::enter_all(caller).map_err(DispatchFailure::not_committed)?; let in_command = scopes.clone(); let decision = route(command); // Local in-process dispatches pass `None` — substrate's own @@ -418,7 +430,9 @@ impl CommandExecutor { // proceeds to transport selection. match verdict { Verdict::Forbidden { reason } => { - return Err(DispatchFailure::not_committed(format!("forbidden: {reason}"))); + return Err(DispatchFailure::not_committed(format!( + "forbidden: {reason}" + ))); } Verdict::Deferred { reason, @@ -593,7 +607,10 @@ impl CommandExecutor { command_name: command.to_string(), duration_ms, success: outcome.is_ok(), - error: outcome.as_ref().err().map(|failure| failure.message.clone()), + error: outcome + .as_ref() + .err() + .map(|failure| failure.message.clone()), handle, result, }; diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index cb534a7607..a464b6b4cc 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -82,7 +82,7 @@ impl CommandExecutor { unresolved: &this.registry.task_persistence_failed, settled: false, }; - let handle = match ledger.accept(owner, command.to_string()).await { + let handle = match ledger.accept(owner, command.to_string(), this.task_execution).await { Ok(handle) => handle, Err(error) => { let _ = accepted.send(Err(DispatchFailure::uncertain(error))); diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 6d08afb48f..e338481c96 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -13,6 +13,8 @@ use uuid::Uuid; mod output; pub use output::TaskOutput; +mod execution; +pub use execution::TaskExecution; mod delivery; pub use delivery::{DeliveryError, DeliveryPage, TaskOwnerSink}; @@ -53,7 +55,10 @@ impl TaskEnd { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] enum Fact { - Accepted { command: String }, + Accepted { + command: String, + execution: TaskExecution, + }, Ended(TaskEnd), Delivered, } @@ -114,12 +119,17 @@ impl TaskLedger { }) } - pub async fn accept(&self, owner: Uuid, command: String) -> Result { + pub async fn accept( + &self, + owner: Uuid, + command: String, + execution: TaskExecution, + ) -> Result { let task = Uuid::new_v4(); let acceptance = TaskFact { task, owner, - fact: Fact::Accepted { command }, + fact: Fact::Accepted { command, execution }, }; match self.facts.save(task, &acceptance).await { Ok(()) => Ok(task), @@ -139,7 +149,9 @@ impl TaskLedger { } } - async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + /// Recover the exact execution owner without guessing from a forgotten handle + /// or a process snapshot. Only the recipient may inspect this registration. + pub async fn execution(&self, task: Uuid, owner: Uuid) -> Result { match self .facts .find_by_id(task) @@ -149,12 +161,16 @@ impl TaskLedger { Some(TaskFact { task: stored_task, owner: stored, - fact: Fact::Accepted { .. }, - }) if stored == owner && stored_task == task => Ok(()), + fact: Fact::Accepted { execution, .. }, + }) if stored == owner && stored_task == task => Ok(execution), _ => Err("task is absent or belongs to another owner".into()), } } + async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + self.execution(task, owner).await.map(|_| ()) + } + /// Only a supervisor that has observed execution ending calls this. A cancellation /// request alone is not an end. Competing endings return the durable winner. pub async fn finish(&self, task: Uuid, owner: Uuid, end: TaskEnd) -> Result { @@ -303,13 +319,39 @@ impl TaskLedger { mod tests { use super::*; + #[tokio::test] + async fn accepted_execution_survives_reopen_and_is_not_replaced_by_new_executor( + ) -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let execution = TaskExecution::new_command_executor(); + let task = ledger.accept(owner, "code/shell".into(), execution).await?; + drop(ledger); + let replacement = TaskExecution::new_command_executor(); + assert_ne!(execution, replacement); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.execution(task, owner).await?, execution); + assert!(reopened.execution(task, Uuid::new_v4()).await.is_err()); + assert_eq!(reopened.pending(task, owner).await?, None); + // An old incarnation is unresolved, not automatically Lost at reopen. + assert_eq!(reopened.terminal(task, owner).await?, None); + Ok(()) + } + #[tokio::test] async fn concurrent_ends_survive_reopen_and_delivery_retry() -> Result<(), String> { let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let first = TaskLedger::new(adapter.clone()).await?; let second = TaskLedger::new(adapter.clone()).await?; let owner = Uuid::new_v4(); - let task = first.accept(owner, "code/shell".into()).await?; + let task = first + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; assert!(first.acknowledge(task, owner).await.is_err()); let (a, b) = tokio::join!( first.finish(task, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))), @@ -338,7 +380,13 @@ mod tests { let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let ledger = TaskLedger::new(adapter).await?; let owner = Uuid::new_v4(); - let task = ledger.accept(owner, "code/shell".into()).await?; + let task = ledger + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(task, owner, TaskEnd::Stopped).await?; ledger .facts @@ -363,14 +411,32 @@ mod tests { let ledger = TaskLedger::new(adapter).await?; let owner = Uuid::new_v4(); let foreign = Uuid::new_v4(); - let consumed = ledger.accept(owner, "consumed".into()).await?; + let consumed = ledger + .accept( + owner, + "consumed".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(consumed, owner, TaskEnd::Stopped).await?; ledger.acknowledge(consumed, owner).await?; - let pending = ledger.accept(owner, "pending".into()).await?; + let pending = ledger + .accept( + owner, + "pending".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger .finish(pending, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))) .await?; - let other = ledger.accept(foreign, "other".into()).await?; + let other = ledger + .accept( + foreign, + "other".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(other, foreign, TaskEnd::Stopped).await?; let mut after = None; let mut found = Vec::new(); @@ -404,9 +470,18 @@ mod tests { let adapter = Arc::new(GatedAdapter::new(adapter)); let ledger = TaskLedger::new(adapter.clone()).await?; let owner = Uuid::new_v4(); - let task = ledger.accept(owner, "test/reply-loss".into()).await?; + let task = ledger + .accept( + owner, + "test/reply-loss".into(), + TaskExecution::new_command_executor(), + ) + .await?; adapter.fail_after_next_create(); - assert_eq!(ledger.finish(task, owner, TaskEnd::Stopped).await?, TaskEnd::Stopped); + assert_eq!( + ledger.finish(task, owner, TaskEnd::Stopped).await?, + TaskEnd::Stopped + ); drop(ledger); let reopened = TaskLedger::new(adapter.clone()).await?; assert_eq!(reopened.pending(task, owner).await?, Some(TaskEnd::Stopped)); @@ -415,12 +490,21 @@ mod tests { drop(reopened); let reopened = TaskLedger::new(adapter.clone()).await?; assert_eq!(reopened.pending(task, owner).await?, None); - assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, TaskEnd::Stopped); + assert_eq!( + reopened.finish(task, owner, TaskEnd::Lost).await?, + TaskEnd::Stopped + ); reopened.acknowledge(task, owner).await?; assert_eq!(reopened.pending(task, owner).await?, None); - let count = adapter.count(QueryBuilder::new(TaskFact::COLLECTION).build()).await; + let count = adapter + .count(QueryBuilder::new(TaskFact::COLLECTION).build()) + .await; assert!(count.success); - assert_eq!(count.data, Some(3), "one acceptance, one end, one delivery fact"); + assert_eq!( + count.data, + Some(3), + "one acceptance, one end, one delivery fact" + ); Ok(()) } @@ -438,7 +522,13 @@ mod tests { let delayed = Arc::new(TaskLedger::new(gated.clone()).await?); let current = TaskLedger::new(adapter.clone()).await?; let owner = Uuid::new_v4(); - let task = current.accept(owner, "code/shell".into()).await?; + let task = current + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; let pause = gated.pause_next_write(); let writer = tokio::spawn(async move { delayed.finish(task, owner, TaskEnd::Lost).await }); notified(&pause.entered).await?; diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs index b68fa7c80c..bd62bf52d4 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -1,6 +1,7 @@ //! The delivery boundary cannot acknowledge an unconsumed terminal result. #![cfg(test)] use super::*; +use crate::runtime::tasks::TaskExecution; use std::sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, @@ -23,20 +24,42 @@ async fn only_page_scoped_perception_can_ack_and_invalid_batch_has_no_partial_ef let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let ledger = TaskLedger::new(adapter).await?; let owner = Uuid::new_v4(); - let first = ledger.accept(owner, "first".into()).await?; - let second = ledger.accept(owner, "second".into()).await?; + let first = ledger + .accept(owner, "first".into(), TaskExecution::new_command_executor()) + .await?; + let second = ledger + .accept( + owner, + "second".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(first, owner, TaskEnd::Stopped).await?; ledger.finish(second, owner, TaskEnd::Lost).await?; let sink = PerceptionSink(Default::default()); let limit = NonZeroUsize::new(32).ok_or("invalid fixture page")?; - assert_eq!(ledger.deliver_page(owner, None, limit, &sink).await?.acknowledged, 0); + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); let foreign = Uuid::new_v4(); sink.0.lock().extend([first, foreign]); - assert!(matches!(ledger.deliver_page(owner, None, limit, &sink).await, - Err(DeliveryError::InvalidReceipt { task }) if task == foreign)); + assert!( + matches!(ledger.deliver_page(owner, None, limit, &sink).await, + Err(DeliveryError::InvalidReceipt { task }) if task == foreign) + ); assert_eq!(ledger.pending(first, owner).await?, Some(TaskEnd::Stopped)); sink.0.lock().remove(&foreign); - assert_eq!(ledger.deliver_page(owner, None, limit, &sink).await?.acknowledged, 1); + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); assert_eq!(ledger.pending(first, owner).await?, None); assert_eq!(ledger.pending(second, owner).await?, Some(TaskEnd::Lost)); Ok(()) @@ -53,7 +76,11 @@ struct Sink { impl TaskOwnerSink for Sink { type Error = std::io::Error; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { for (task, end) in ends { let pending = self .ledger @@ -79,7 +106,9 @@ async fn refused_consumption_remains_pending_and_replay_needs_no_registered_hand let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); let owner = Uuid::new_v4(); - let task = ledger.accept(owner, "build".into()).await?; + let task = ledger + .accept(owner, "build".into(), TaskExecution::new_command_executor()) + .await?; ledger.finish(task, owner, TaskEnd::Stopped).await?; let sink = Sink { ledger: ledger.clone(), @@ -122,8 +151,16 @@ async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( let ledger = Arc::new(TaskLedger::new(adapter).await?); let owner = Uuid::new_v4(); let foreign = Uuid::new_v4(); - let mine = ledger.accept(owner, "mine".into()).await?; - let theirs = ledger.accept(foreign, "theirs".into()).await?; + let mine = ledger + .accept(owner, "mine".into(), TaskExecution::new_command_executor()) + .await?; + let theirs = ledger + .accept( + foreign, + "theirs".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(mine, owner, TaskEnd::Lost).await?; ledger.finish(theirs, foreign, TaskEnd::Stopped).await?; let sink = Sink { @@ -166,8 +203,16 @@ async fn one_owner_page_is_consumed_once_before_its_acknowledgements( let (adapter, _directory) = crate::orm::store::fresh_adapter().await; let ledger = Arc::new(TaskLedger::new(adapter).await?); let owner = Uuid::new_v4(); - let first = ledger.accept(owner, "first".into()).await?; - let second = ledger.accept(owner, "second".into()).await?; + let first = ledger + .accept(owner, "first".into(), TaskExecution::new_command_executor()) + .await?; + let second = ledger + .accept( + owner, + "second".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger.finish(first, owner, TaskEnd::Stopped).await?; ledger.finish(second, owner, TaskEnd::Lost).await?; let sink = Sink { diff --git a/core/continuum-kernel/src/runtime/tasks/execution.rs b/core/continuum-kernel/src/runtime/tasks/execution.rs new file mode 100644 index 0000000000..80fe35c142 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/execution.rs @@ -0,0 +1,19 @@ +//! Durable identity of the execution owner, distinct from the result recipient. +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// A command executor instance owns its in-process dispatch until quiescence. +/// This is not a PID: a replacement executor gets a new incarnation even in the +/// same process. Absence from a process snapshot does not prove this owner ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TaskExecution { + CommandExecutor { incarnation: Uuid }, +} + +impl TaskExecution { + pub fn new_command_executor() -> Self { + Self::CommandExecutor { + incarnation: Uuid::new_v4(), + } + } +} diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs index 178c94870c..82b3f42b2c 100644 --- a/core/continuum-kernel/src/runtime/tasks/output.rs +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -40,7 +40,7 @@ impl From for CommandResult { #[cfg(test)] mod tests { use super::*; - use crate::runtime::tasks::{TaskEnd, TaskLedger}; + use crate::runtime::tasks::{TaskEnd, TaskExecution, TaskLedger}; use uuid::Uuid; #[tokio::test] @@ -60,8 +60,20 @@ mod tests { "producer::Result", ))?; assert!(matches!(&handle, TaskOutput::Handle(_))); - let binary_task = ledger.accept(owner, "producer/binary".into()).await?; - let handle_task = ledger.accept(owner, "producer/handle".into()).await?; + let binary_task = ledger + .accept( + owner, + "producer/binary".into(), + TaskExecution::new_command_executor(), + ) + .await?; + let handle_task = ledger + .accept( + owner, + "producer/handle".into(), + TaskExecution::new_command_executor(), + ) + .await?; ledger .finish(binary_task, owner, TaskEnd::Done(binary.clone())) .await?; From bed869002ee5d24ddf417119cd67db4f64aa0e74 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 17:40:31 -0600 Subject: [PATCH 78/88] refactor(cognition): share registered owner checkpoint boundary --- .../src/cognition/persona_workspace.rs | 4 +- .../persona_workspace/owner_checkpoint.rs | 46 +++++++++ .../persona_workspace/task_consumption.rs | 99 ++++++++++--------- .../tests/task_consumption.rs | 20 ++-- 4 files changed, 113 insertions(+), 56 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index 68523b7229..b36f58d898 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -29,13 +29,13 @@ use uuid::Uuid; use crate::identity::{PeerId, PersonaRef}; use super::deferred_faculty::DeferredFaculty; -use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalEmbedder}; use super::llm_deliberation_faculty::LlmDeliberationFaculty; use super::rag_source_faculty::{RagSourceFaculty, SaliencePolicy}; use super::recall_faculty::RecallFaculty; use super::working_memory::WorkingMemory; use super::workspace::{ActingBody, Faculty, SituationFocusArbiter, WorkspaceCycle}; use crate::ai::adapter::AIProviderAdapter; +use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalEmbedder}; use crate::cognition::admission_state::AdmissionState; use crate::cognition::rag_budget::RagSource; @@ -58,6 +58,8 @@ mod acting_hands; pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; +mod owner_checkpoint; +pub use owner_checkpoint::OwnerCheckpointError; mod task_consumption; pub use task_consumption::{ResidentTaskSink, TaskConsumptionError, TaskSinkError}; mod own_speech_persisted; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs b/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs new file mode 100644 index 0000000000..a5b225fc3b --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs @@ -0,0 +1,46 @@ +//! One resident-state commit boundary, shared by task delivery and perception. +//! The payload owner stages typed state; this owner supplies admission, replacement +//! exclusion, the existing checkpoint writer and publication after persistence. +use super::*; + +#[derive(Debug, thiserror::Error)] +pub enum OwnerCheckpointError { + #[error("resident checkpoint admission is closed")] + Stopped, + #[error("owner {0} is not a registered resident")] + Absent(Uuid), + #[error("owner checkpoint failed: {0}")] + Checkpoint(#[from] std::io::Error), +} + +impl PersonaWorkspaceRegistry { + /// Commit through the registered resident's existing snapshot and writer. + /// A stage must validate its complete input before mutation. An IO failure may + /// leave staged memory, so replay must be idempotent and must checkpoint again. + /// Staging alone never authorizes an acknowledgement or publishes a wake. + /// + /// Payloads, source cursors and wake obligations must all be part of this same + /// saved snapshot. This boundary cannot make an external/in-memory queue durable. + /// Incarnation-sensitive callers validate their expected incarnation in `stage`, + /// while replacement is excluded. Do not call registry operations from `stage`. + pub fn commit_owner_state>( + &self, + owner: Uuid, + stage: impl FnOnce(&WorkingMemory) -> Result<(), E>, + ) -> Result { + let stopped = self.checkpoint_stopped.lock(); + if *stopped { + return Err(OwnerCheckpointError::Stopped.into()); + } + let _assembly = self.assembly.lock(); + let memory = self + .cycles + .lock() + .get(&owner) + .map(|resident| Arc::clone(&resident.working_memory)) + .ok_or_else(|| E::from(OwnerCheckpointError::Absent(owner)))?; + stage(&memory)?; + save_volatile(owner, SaveReason::Periodic, None, &memory) + .map_err(|error| E::from(OwnerCheckpointError::Checkpoint(error))) + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index d0f810cb94..7466a7a529 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -5,16 +5,12 @@ use continuum_kernel::runtime::tasks::TaskEnd; #[derive(Debug, thiserror::Error)] pub enum TaskConsumptionError { - #[error("resident checkpoint admission is closed")] - Stopped, - #[error("task owner {0} is not a registered resident")] - Absent(Uuid), + #[error(transparent)] + Owner(#[from] OwnerCheckpointError), #[error("task read receipt belongs to a replaced memory incarnation for {0}")] Replaced(Uuid), #[error(transparent)] Receipt(#[from] super::super::working_memory::TaskReceiptError), - #[error("task consumption checkpoint failed: {0}")] - Checkpoint(#[from] std::io::Error), } impl PersonaWorkspaceRegistry { @@ -27,23 +23,42 @@ impl PersonaWorkspaceRegistry { receipt: &crate::cognition::render_receipt::RenderReceipt, ) -> Result, TaskConsumptionError> { use continuum_context::level::Level; - let memory = self.cycles.lock().get(&receipt.owner) + let memory = self + .cycles + .lock() + .get(&receipt.owner) .map(|resident| Arc::clone(&resident.working_memory)) - .ok_or(TaskConsumptionError::Absent(receipt.owner))?; + .ok_or(OwnerCheckpointError::Absent(receipt.owner))?; if memory.incarnation() != receipt.incarnation { return Err(TaskConsumptionError::Replaced(receipt.owner)); } - let shown: std::collections::BTreeSet<_> = receipt.view.items.iter() - .filter(|item| !item.retired && matches!(item.level, Level::Full | Level::Summary | Level::Pointer)) - .filter_map(|item| item.element).collect(); - let tasks: Vec<_> = memory.task_terminals().into_iter().filter(|end| end.wake_pending).filter(|end| { - shown.contains(&crate::cognition::context_streams::tasks::terminal_element( - receipt.owner, end.task, &end.fingerprint)) - }).map(|end| end.task).collect(); + let shown: std::collections::BTreeSet<_> = receipt + .view + .items + .iter() + .filter(|item| { + !item.retired && matches!(item.level, Level::Full | Level::Summary | Level::Pointer) + }) + .filter_map(|item| item.element) + .collect(); + let tasks: Vec<_> = memory + .task_terminals() + .into_iter() + .filter(|end| end.wake_pending) + .filter(|end| { + shown.contains(&crate::cognition::context_streams::tasks::terminal_element( + receipt.owner, + end.task, + &end.fingerprint, + )) + }) + .map(|end| end.task) + .collect(); if tasks.is_empty() { return Ok(None); } - self.record_task_reads(receipt.owner, receipt.incarnation, &tasks).map(Some) + self.record_task_reads(receipt.owner, receipt.incarnation, &tasks) + .map(Some) } /// Success receipts exactly the snapshot containing this end and its wake @@ -55,7 +70,7 @@ impl PersonaWorkspaceRegistry { owner: Uuid, ends: Vec<(Uuid, TaskEnd)>, ) -> Result { - self.commit_task_state(owner, |memory| { + self.commit_owner_state(owner, |memory| { memory.stage_task_ends(ends)?; Ok(()) }) @@ -69,7 +84,7 @@ impl PersonaWorkspaceRegistry { incarnation: Uuid, tasks: &[Uuid], ) -> Result { - self.commit_task_state(owner, |memory| { + self.commit_owner_state(owner, |memory| { if memory.incarnation() != incarnation { return Err(TaskConsumptionError::Replaced(owner)); } @@ -77,29 +92,6 @@ impl PersonaWorkspaceRegistry { Ok(()) }) } - - /// One admission and persistence owner for task arrivals and rendered reads. - fn commit_task_state( - &self, - owner: Uuid, - stage: impl FnOnce( - &super::super::working_memory::WorkingMemory, - ) -> Result<(), TaskConsumptionError>, - ) -> Result { - let stopped = self.checkpoint_stopped.lock(); - if *stopped { - return Err(TaskConsumptionError::Stopped); - } - let _assembly = self.assembly.lock(); - let memory = self - .cycles - .lock() - .get(&owner) - .map(|resident| Arc::clone(&resident.working_memory)) - .ok_or(TaskConsumptionError::Absent(owner))?; - stage(&memory)?; - Ok(save_volatile(owner, SaveReason::Periodic, None, &memory)?) - } } /// Async adapter for the registered owner. Filesystem work runs on a blocking @@ -118,13 +110,15 @@ impl ResidentTaskSink { &self, receipt: crate::cognition::render_receipt::RenderReceipt, ) -> Result, TaskSinkError> { - self.commit(move |registry| registry.record_rendered_tasks(&receipt)).await + self.commit(move |registry| registry.record_rendered_tasks(&receipt)) + .await } async fn commit( &self, operation: impl FnOnce(&PersonaWorkspaceRegistry) -> Result - + Send + 'static, + + Send + + 'static, ) -> Result { let registry = Arc::clone(&self.0); // Carry the existing test filesystem scope onto the blocking worker. @@ -136,7 +130,8 @@ impl ResidentTaskSink { .as_deref() .map(crate::paths::NativeHomeOverride::install); operation(®istry) - }).await??) + }) + .await??) } } @@ -156,10 +151,20 @@ pub enum TaskSinkError { impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { type Error = TaskSinkError; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { let offered: std::collections::BTreeSet<_> = ends.iter().map(|(task, _)| *task).collect(); let ends = ends.to_vec(); - let receipt = self.commit(move |registry| registry.consume_task_ends(owner, ends)).await?; - Ok(receipt.perceived_tasks().intersection(&offered).copied().collect()) + let receipt = self + .commit(move |registry| registry.consume_task_ends(owner, ends)) + .await?; + Ok(receipt + .perceived_tasks() + .intersection(&offered) + .copied() + .collect()) } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index e03d7ddcd9..f9f1db3f0b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -88,9 +88,9 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( std::fs::create_dir(&obstruction)?; assert!(matches!( sink.record_rendered(exact.clone()).await, - Err(TaskSinkError::Consumption( - TaskConsumptionError::Checkpoint(_) - )) + Err(TaskSinkError::Consumption(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + ))) )); assert_eq!(memory.pending_task_wakes(), vec![task]); let before_retry = WorkingMemory::new(8); @@ -165,7 +165,7 @@ async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( let owner = Uuid::new_v4(); let task = Uuid::new_v4(); assert!( - matches!(registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Absent(id)) if id == owner) + matches!(registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Owner(OwnerCheckpointError::Absent(id))) if id == owner) ); registry.register_from_cfg(cfg_for(owner))?; registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; @@ -182,7 +182,7 @@ async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( let before = std::fs::read(&path)?; assert!(matches!( registry.consume_task_ends(owner, vec![(Uuid::new_v4(), TaskEnd::Lost)]), - Err(TaskConsumptionError::Stopped) + Err(TaskConsumptionError::Owner(OwnerCheckpointError::Stopped)) )); assert_eq!(std::fs::read(&path)?, before); Ok(()) @@ -208,7 +208,9 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( std::fs::create_dir(&obstruction)?; assert!(matches!( registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), - Err(TaskConsumptionError::Checkpoint(_)) + Err(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + )) )); assert_eq!(std::fs::read(&path)?, before); let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); @@ -400,7 +402,9 @@ async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( std::fs::create_dir(&obstruction)?; assert!(matches!( registry.record_task_reads(owner, current.incarnation(), &[task]), - Err(TaskConsumptionError::Checkpoint(_)) + Err(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + )) )); assert_eq!(current.pending_task_wakes(), vec![task]); std::fs::remove_dir(&obstruction)?; @@ -460,7 +464,7 @@ async fn served_read_arriving_after_shutdown_preserves_restart_delivery( let before = std::fs::read(&path)?; assert!(matches!( registry.record_task_reads(owner, memory.incarnation(), &[task]), - Err(TaskConsumptionError::Stopped) + Err(TaskConsumptionError::Owner(OwnerCheckpointError::Stopped)) )); assert_eq!(std::fs::read(&path)?, before); let restored = WorkingMemory::new(8); From 5caa7f9936674d2af08a85640c4b1af33ec1ce47 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 17:59:24 -0600 Subject: [PATCH 79/88] fix(mind): bind replay sweep fixtures to executor incarnation --- .../src/modules/cognition/task_delivery.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/core/continuum-mind/src/modules/cognition/task_delivery.rs b/core/continuum-mind/src/modules/cognition/task_delivery.rs index 7eabd92084..3901d42536 100644 --- a/core/continuum-mind/src/modules/cognition/task_delivery.rs +++ b/core/continuum-mind/src/modules/cognition/task_delivery.rs @@ -76,7 +76,7 @@ impl CognitionModule { #[cfg(test)] mod tests { use super::*; - use continuum_kernel::runtime::tasks::TaskEnd; + use continuum_kernel::runtime::tasks::{TaskEnd, TaskExecution}; use std::sync::atomic::{AtomicBool, Ordering}; // Scheduling fixture only; real durable consumption is tested by cognition's @@ -88,7 +88,11 @@ mod tests { #[async_trait::async_trait] impl TaskOwnerSink for Sink { type Error = std::io::Error; - async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { if owner == self.refused && self.refuse.load(Ordering::SeqCst) { Err(std::io::Error::other("injected owner refusal")) } else { @@ -104,9 +108,10 @@ mod tests { let ledger = TaskLedger::new(adapter).await?; let refused = Uuid::new_v4(); let healthy = Uuid::new_v4(); - let blocked = ledger.accept(refused, "blocked".into()).await?; - let ready = ledger.accept(healthy, "ready".into()).await?; - let running = ledger.accept(healthy, "running".into()).await?; + let execution = TaskExecution::new_command_executor(); + let blocked = ledger.accept(refused, "blocked".into(), execution).await?; + let ready = ledger.accept(healthy, "ready".into(), execution).await?; + let running = ledger.accept(healthy, "running".into(), execution).await?; ledger.finish(blocked, refused, TaskEnd::Stopped).await?; ledger.finish(ready, healthy, TaskEnd::Stopped).await?; let sink = Sink { From fca4dd4271375dcabb47d6bddf2aef1fda2d4973 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:11:46 -0600 Subject: [PATCH 80/88] test(custody): carry durability faults into checkpoint workers --- .../persona_workspace/task_consumption.rs | 11 ++- .../src/durable/fault_injection.rs | 67 +++++++++++++++---- 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs index 7466a7a529..8e5048a72e 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -124,12 +124,21 @@ impl ResidentTaskSink { // Carry the existing test filesystem scope onto the blocking worker. #[cfg(test)] let test_home = crate::paths::NativeHomeOverride::current(); + #[cfg(test)] + let fence_fault = continuum_host::durable::fault_injection::FenceFault::capture(); Ok(tokio::task::spawn_blocking(move || { #[cfg(test)] let _native = test_home .as_deref() .map(crate::paths::NativeHomeOverride::install); - operation(®istry) + #[cfg(test)] + { + fence_fault.run(|| operation(®istry)) + } + #[cfg(not(test))] + { + operation(®istry) + } }) .await??) } diff --git a/core/continuum-host/src/durable/fault_injection.rs b/core/continuum-host/src/durable/fault_injection.rs index e36e17b34e..5b6b34f692 100644 --- a/core/continuum-host/src/durable/fault_injection.rs +++ b/core/continuum-host/src/durable/fault_injection.rs @@ -1,6 +1,4 @@ -//! Injected faults for tests of code that fences through [`super::fence`]. -//! Compiled only for tests and the `test-fixtures` feature, never into a release binary. - +//! Test-only durability faults, explicitly carried across blocking-worker boundaries. use std::cell::Cell; thread_local! { @@ -11,15 +9,60 @@ pub(super) fn fence_fails() -> bool { FAIL_FENCE.with(Cell::get) } -/// Runs `f` with every durability fence on this thread failing, then restores. -pub fn with_failed_fence(f: impl FnOnce()) { - struct Reset; - impl Drop for Reset { - fn drop(&mut self) { - FAIL_FENCE.with(|fail| fail.set(false)); +/// Captured fixture state. Capturing alone does not affect another thread. +#[derive(Clone, Copy)] +pub struct FenceFault(bool); + +impl FenceFault { + pub fn capture() -> Self { + Self(fence_fails()) + } + + /// Install this fixture only for the operation and restore the previous state, + /// including on unwind. Nested fixture scopes cannot clear an outer fault. + pub fn run(self, operation: impl FnOnce() -> R) -> R { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + FAIL_FENCE.with(|fault| fault.set(self.0)); + } } + let previous = FAIL_FENCE.with(|fault| fault.replace(self.0)); + let _reset = Reset(previous); + operation() + } +} + +pub fn with_failed_fence(operation: impl FnOnce() -> R) -> R { + FenceFault(true).run(operation) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_scope_restores_the_outer_fault() { + assert!(!fence_fails()); + with_failed_fence(|| { + with_failed_fence(|| assert!(fence_fails())); + assert!(fence_fails()); + }); + assert!(!fence_fails()); + } + + #[test] + fn captured_fault_is_explicit_and_scoped_on_worker() -> Result<(), String> { + let captured = with_failed_fence(FenceFault::capture); + let worker = std::thread::spawn(move || { + assert!(!fence_fails()); + captured.run(|| assert!(fence_fails())); + assert!(!fence_fails()); + }); + worker + .join() + .map_err(|_| "fault fixture worker panicked".to_string())?; + assert!(!fence_fails()); + Ok(()) } - FAIL_FENCE.with(|fail| fail.set(true)); - let _reset = Reset; - f(); } From 7182603bf02c5478260a91ddc9a4b42a72929f75 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:23:33 -0600 Subject: [PATCH 81/88] refactor(custody): move checkpoints and adoption into personas disk class --- .../src/cognition/persona_workspace.rs | 1 + .../persona_workspace/checkpoint_adoption.rs | 132 ++++++----------- .../persona_workspace/checkpoint_storage.rs | 50 +++++++ .../persona_workspace/own_speech_persisted.rs | 88 ++++++----- ..._told_when_her_hands_move_and_only_then.rs | 2 +- .../tests/task_consumption.rs | 31 ++-- .../src/durable/fault_injection.rs | 21 +++ core/continuum-host/src/durable/staging.rs | 55 ++++++- core/continuum-host/src/durable/tests.rs | 19 +++ .../disk_reporters/class_writer.rs | 137 ++++++++++++++---- 10 files changed, 359 insertions(+), 177 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index b36f58d898..277f381224 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -42,6 +42,7 @@ use crate::cognition::rag_budget::RagSource; /// Explicit offline adoption of a selected legacy checkpoint; shares this /// owner's schema, native path, and cross-process checkpoint exclusion. pub mod checkpoint_adoption; +mod checkpoint_storage; mod act_output; mod rehome; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index cccb5ab3ba..06d5e966cd 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -5,11 +5,10 @@ //! caller's offline check, and never claims the selected snapshot was flushed //! at shutdown or authenticated to a process lifetime. -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; +use std::fs::{self, File}; +use std::io::{self, Read}; use std::path::{Path, PathBuf}; -use fs2::FileExt; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use uuid::Uuid; @@ -263,90 +262,48 @@ fn exists(path: &Path) -> io::Result { /// Same file lock used by save, load and adoption. Callers keep the returned /// handle alive until their complete file operation ends. Readers wait rather /// than interpreting another owner's work as an absent checkpoint. -pub(super) fn lock_checkpoint(path: &Path, wait: bool) -> io::Result { - let parent = path - .parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "checkpoint has no parent"))?; - fs::create_dir_all(parent)?; - let lock_path = parent.join(".volatile.lock"); - match fs::symlink_metadata(&lock_path) { - Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "checkpoint lock is not a regular file", - )); - } - Ok(_) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(lock_path)?; - if wait { - FileExt::lock_exclusive(&file)?; - } else { - FileExt::try_lock_exclusive(&file)?; - } - Ok(file) +pub(super) fn lock_checkpoint( + path: &Path, + wait: bool, +) -> io::Result { + super::checkpoint_storage::for_path(path)?.lock(Path::new(".volatile.lock"), wait) } -pub(super) fn sync_parent(path: &Path) -> io::Result<()> { - // POSIX directory durability. Windows file contents are flushed below; - // this receipt does not promise power-loss directory-journal guarantees. - #[cfg(unix)] - File::open( - path.parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no parent"))?, - )? - .sync_all()?; - #[cfg(not(unix))] - let _ = path; - Ok(()) +fn relative<'a>( + writer: &continuum_kernel::system_resources::disk_reporters::ClassWriter, + path: &'a Path, +) -> io::Result { + let checkpoint = writer.path(Path::new("volatile.json"))?; + let parent = checkpoint + .parent() + .ok_or_else(|| io::Error::other("checkpoint has no parent"))?; + path.strip_prefix(parent) + .map(Path::to_path_buf) + .map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidInput, + "adoption evidence is outside owner class", + ) + }) } -fn preserve(path: &Path, bytes: &[u8]) -> Result<(), AdoptionError> { - if exists(path)? { - return if read_bounded(path)? == bytes { - // A previous publication may have reached its final name before - // parent sync failed; equality alone does not complete that step. - sync_parent(path)?; - Ok(()) - } else { - Err(AdoptionError::EvidenceConflict(path.display().to_string())) - }; - } - let parent = path - .parent() - .ok_or_else(|| invalid("evidence has no parent"))?; - let temporary = parent.join(format!(".preserve-{}.tmp", Uuid::new_v4())); - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&temporary)?; - file.write_all(bytes)?; - file.sync_all()?; - drop(file); - // Publish a complete inode without overwriting existing evidence. Unlike a - // direct create+write, an interrupted write never occupies the final name. - // Both paths are on the same filesystem. Unsupported hard links are an IO - // refusal, not a fallback to a partially visible or destructive write. - let published = fs::hard_link(&temporary, path); - match published { - Ok(()) => {} +fn preserve( + writer: &continuum_kernel::system_resources::disk_reporters::ClassWriter, + path: &Path, + bytes: &[u8], +) -> Result<(), AdoptionError> { + let name = relative(writer, path)?; + match writer.publish_new(&name, bytes) { + Ok(()) => Ok(()), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { if read_bounded(path)? != bytes { return Err(AdoptionError::EvidenceConflict(path.display().to_string())); } + writer.fence_existing(&name)?; + Ok(()) } - Err(error) => return Err(error.into()), + Err(error) => Err(error.into()), } - fs::remove_file(&temporary)?; - sync_parent(path)?; - Ok(()) } /// Adopt the selected bytes under the checkpoint owner's exclusion. The @@ -371,7 +328,8 @@ pub fn adopt( "plan paths no longer match declared identity and native destination", )); } - let _lock = lock_checkpoint(&destination, false)?; + let writer = super::checkpoint_storage::for_path(&destination)?; + let _lock = writer.lock(Path::new(".volatile.lock"), false)?; ensure_offline()?; let encoded_plan = serde_json::to_vec(plan).map_err(|error| invalid(error.to_string()))?; let parent = destination @@ -425,10 +383,10 @@ pub fn adopt( { // Complete a previous rename's directory durability step before // acknowledging recovery, even if its first attempt failed here. - sync_parent(&destination)?; + writer.fence_existing(Path::new("volatile.json"))?; let encoded_receipt = serde_json::to_vec(&receipt).map_err(|error| invalid(error.to_string()))?; - preserve(&receipt_path, &encoded_receipt)?; + preserve(&writer, &receipt_path, &encoded_receipt)?; receipt.already_applied = true; return Ok(receipt); } @@ -439,24 +397,23 @@ pub fn adopt( if current_destination != plan.prior_destination { return Err(AdoptionError::DestinationChanged); } - fs::create_dir_all(&evidence)?; // Archives before intent: a visible plan always has complete preserved // inputs. Partial files are a refusal on retry, never silently overwritten. - preserve(&archive, &source_bytes)?; + preserve(&writer, &archive, &source_bytes)?; if let Some(expected) = &plan.prior_destination { let (current, bytes) = selection(&destination)?; if ¤t != expected { return Err(AdoptionError::DestinationChanged); } - preserve(&prior, &bytes)?; + preserve(&writer, &prior, &bytes)?; } - preserve(&intent, &encoded_plan)?; + preserve(&writer, &intent, &encoded_plan)?; // Separate inode from immutable evidence, so future in-place writes to the // live file cannot alter the source archive. // One staged payload per explicit plan: repeated offline/precondition // refusals reuse its verified bytes instead of accumulating full copies. let staged = evidence.join("staged.json"); - preserve(&staged, &source_bytes)?; + preserve(&writer, &staged, &source_bytes)?; ensure_offline()?; if selection(&plan.source.path)?.0 != plan.source { return Err(AdoptionError::SourceChanged); @@ -464,8 +421,7 @@ pub fn adopt( if optional_selection(&destination)? != plan.prior_destination { return Err(AdoptionError::DestinationChanged); } - fs::rename(&staged, &destination)?; - sync_parent(&destination)?; + writer.replace(Path::new("volatile.json"), &source_bytes)?; let published = optional_selection(&destination)?; if published .as_ref() @@ -477,6 +433,6 @@ pub fn adopt( } let encoded_receipt = serde_json::to_vec(&receipt).map_err(|error| invalid(error.to_string()))?; - preserve(&receipt_path, &encoded_receipt)?; + preserve(&writer, &receipt_path, &encoded_receipt)?; Ok(receipt) } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs new file mode 100644 index 0000000000..ac82dd95ea --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs @@ -0,0 +1,50 @@ +//! Checkpoint paths, locks and writes share the personas disk-class owner. +use continuum_kernel::system_resources::disk_reporters::ClassWriter; +use std::{ + io, + path::{Path, PathBuf}, +}; +use uuid::Uuid; + +pub(super) fn writer(owner: Uuid) -> io::Result { + #[cfg(not(any(test, feature = "test-fixtures")))] + let class = ClassWriter::of("personas")?; + // Explicit test layout, from the same class catalog as boot. Resolve on this + // thread so NativeHomeOverride and blocking-worker fixture custody agree. + #[cfg(any(test, feature = "test-fixtures"))] + let class = { + let native = crate::paths::home_dir() + .ok_or_else(|| io::Error::other("fixture has no native home"))?; + let home = crate::paths::continuum_home().map_err(io::Error::other)?; + continuum_kernel::system_resources::disk_reporters::standard_tracked_dirs(&native, &home) + .into_iter() + .find(|class| class.class() == "personas") + .ok_or_else(|| io::Error::other("fixture catalog has no personas class"))? + .writer() + }; + Ok(class.owned_by(owner)) +} + +pub(super) fn path(owner: Uuid) -> io::Result { + writer(owner)?.path(Path::new("volatile.json")) +} + +pub(super) fn for_path(path: &Path) -> io::Result { + let owner = path + .parent() + .and_then(Path::file_name) + .and_then(|s| s.to_str()) + .and_then(|s| Uuid::parse_str(s).ok()) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "checkpoint has no typed owner") + })?; + let writer = writer(owner)?; + if std::path::absolute(path)? != std::path::absolute(writer.path(Path::new("volatile.json"))?)? + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "checkpoint is outside its owner class", + )); + } + Ok(writer) +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index b7ada036a7..c8dd19b0dd 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -28,16 +28,7 @@ impl OwnSpeechPersisted { } pub(super) fn volatile_path(persona_id: Uuid) -> std::io::Result { - let home = crate::paths::home_dir().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::NotFound, - "cannot resolve persistent home directory", - ) - })?; - Ok(home - .join(".continuum/personas") - .join(persona_id.to_string()) - .join("volatile.json")) + checkpoint_storage::path(persona_id) } /// Proof returned only after the exact snapshot is synced and renamed. The registry @@ -51,10 +42,18 @@ pub struct VolatileReceipt { } impl VolatileReceipt { - pub fn owner(&self) -> Uuid { self.owner } - pub fn incarnation(&self) -> Uuid { self.incarnation } - pub fn consumed_tasks(&self) -> &[Uuid] { &self.consumed_tasks } - pub fn perceived_tasks(&self) -> &std::collections::BTreeSet { &self.perceived_tasks } + pub fn owner(&self) -> Uuid { + self.owner + } + pub fn incarnation(&self) -> Uuid { + self.incarnation + } + pub fn consumed_tasks(&self) -> &[Uuid] { + &self.consumed_tasks + } + pub fn perceived_tasks(&self) -> &std::collections::BTreeSet { + &self.perceived_tasks + } } /// Persist the volatile tier — atomic tmp+rename so a crash mid-write never @@ -66,8 +65,8 @@ pub(super) fn save_volatile( staged_deadline: Option, wm: &super::super::working_memory::WorkingMemory, ) -> std::io::Result { - let path = volatile_path(persona_id)?; - let _checkpoint_lock = checkpoint_adoption::lock_checkpoint(&path, true)?; + let writer = checkpoint_storage::writer(persona_id)?; + let _checkpoint_lock = writer.lock(std::path::Path::new(".volatile.lock"), true)?; let mut snapshot = wm.snapshot(); // THE HANDOFF (card 49b5e806): composed from what her turns already stamped (rooting, // work/note, the seam walk) plus the two things only the seam knows — what tears this @@ -101,21 +100,16 @@ pub(super) fn save_volatile( let task_publication = snapshot.task_results.publication(); let persisted = PersistedVolatile { wm: snapshot, - own_speech: OwnSpeechPersisted::ByRoom(super::super::deliberation_budget::own_speech_by_room( - crate::identity::PeerId::from_uuid(persona_id), - )), + own_speech: OwnSpeechPersisted::ByRoom( + super::super::deliberation_budget::own_speech_by_room( + crate::identity::PeerId::from_uuid(persona_id), + ), + ), }; - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("json.tmp"); - use std::io::Write; - let mut file = std::fs::File::create(&tmp)?; - file.write_all(&serde_json::to_vec(&persisted)?)?; - file.sync_all()?; - drop(file); - std::fs::rename(&tmp, &path)?; - checkpoint_adoption::sync_parent(&path)?; + writer.replace( + std::path::Path::new("volatile.json"), + &serde_json::to_vec(&persisted)?, + )?; wm.publish_task_checkpoint(task_publication); Ok(receipt) } @@ -134,14 +128,19 @@ pub(super) fn save_volatile( pub(crate) fn persisted_result_handles( persona_id: Uuid, ) -> std::io::Result>> { - result_handles_at(&volatile_path(persona_id)?) + let path = volatile_path(persona_id)?; + let _lock = checkpoint_adoption::lock_checkpoint(&path, true)?; + result_handles_at(&path) } /// [`persisted_result_handles`] for the checkpoint at `path` (the filesystem seam). pub(super) fn result_handles_at( path: &std::path::Path, ) -> std::io::Result>> { - type Cached = (std::time::SystemTime, std::sync::Arc>); + type Cached = ( + std::time::SystemTime, + std::sync::Arc>, + ); static CACHE: std::sync::OnceLock< parking_lot::Mutex>, > = std::sync::OnceLock::new(); @@ -163,16 +162,33 @@ pub(super) fn result_handles_at( .map(|persisted| persisted.wm.reachable_handles()) .unwrap_or_default(), ); - cache.lock().insert(path.to_path_buf(), (modified, std::sync::Arc::clone(&handles))); + cache.lock().insert( + path.to_path_buf(), + (modified, std::sync::Arc::clone(&handles)), + ); Ok(handles) } pub(super) fn load_volatile(persona_id: Uuid) -> std::io::Result> { - load_volatile_at(&volatile_path(persona_id)?) + let path = volatile_path(persona_id)?; + let _lock = checkpoint_adoption::lock_checkpoint(&path, true)?; + if !path.try_exists()? { + let native = crate::paths::home_dir() + .ok_or_else(|| std::io::Error::other("cannot inspect prior checkpoint location"))?; + let previous = native + .join(".continuum/personas") + .join(persona_id.to_string()) + .join("volatile.json"); + if previous != path && previous.try_exists()? { + return Err(std::io::Error::other(format!("checkpoint exists at {}; explicit offline checkpoint adoption is required before using {}", previous.display(), path.display()))); + } + } + load_volatile_at(&path) } -pub(super) fn load_volatile_at(path: &std::path::Path) -> std::io::Result> { - let _lock = checkpoint_adoption::lock_checkpoint(path, true)?; +pub(super) fn load_volatile_at( + path: &std::path::Path, +) -> std::io::Result> { let bytes = match std::fs::read(path) { Ok(bytes) => bytes, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 42cfe573b9..fb451caa14 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -725,7 +725,7 @@ use super::*; std::fs::create_dir_all(path.parent().unwrap()).unwrap(); // Deterministic on Unix and Windows: a directory cannot be overwritten // by the temporary checkpoint file, regardless of user permissions. - std::fs::create_dir(path.with_extension("json.tmp")).unwrap(); + let _fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); let outcomes = registry.flush_volatile_all(); assert_eq!(outcomes.len(), 2); assert!(outcomes diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index f9f1db3f0b..f10ce7edd9 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -84,8 +84,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( } assert!(sink.record_rendered(receipt).await?.is_none()); assert_eq!(memory.pending_task_wakes(), vec![task]); - let obstruction = volatile_path(owner)?.with_extension("json.tmp"); - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); assert!(matches!( sink.record_rendered(exact.clone()).await, Err(TaskSinkError::Consumption(TaskConsumptionError::Owner( @@ -96,7 +95,7 @@ async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( let before_retry = WorkingMemory::new(8); before_retry.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); assert_eq!(before_retry.pending_task_wakes(), vec![task]); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); cycle.persist_render_receipts(vec![exact.clone()]).await?; assert!(memory.pending_task_wakes().is_empty()); let checkpoint = std::fs::read(volatile_path(owner)?)?; @@ -202,10 +201,9 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( } let path = volatile_path(owner)?; let before = std::fs::read(&path)?; - // A directory at the writer's temp-file path forces a real filesystem refusal. + // The shared durability fault refuses placement before replacing the checkpoint. // The existing committed checkpoint is never removed or replaced by the test. - let obstruction = path.with_extension("json.tmp"); - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); assert!(matches!( registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Owner( @@ -216,7 +214,7 @@ async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert!(memory.pending_task_wakes().is_empty()); assert!(memory.stage_task_reads(&[task]).is_err()); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); // The ordinary checkpoint owner also publishes a staged end after IO recovers. for (_, result) in registry.flush_volatile_all() { result?; @@ -262,14 +260,13 @@ async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( registry.register_from_cfg(cfg_for(owner))?; let checkpoint = volatile_path(owner)?; std::fs::create_dir_all(checkpoint.parent().ok_or("checkpoint parent absent")?)?; - let obstruction = checkpoint.with_extension("json.tmp"); - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); assert!(ledger .deliver_page(owner, None, limit, &sink) .await .is_err()); assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); assert_eq!( ledger .deliver_page(owner, None, limit, &sink) @@ -310,14 +307,14 @@ async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( request: "served-task-result".into(), view: view.receipt(), }; - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); assert!(sink.record_rendered(receipt.clone()).await.is_err()); assert!(reopened .deliver_page(owner, None, limit, &sink) .await .is_err()); assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); sink.record_rendered(receipt).await?; // Crash after the perception checkpoint but before ACK: replay uses the // restored exact receipt, without prompting her again or remembering a handle. @@ -358,8 +355,7 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); assert!(memory.stage_task_reads(&[task])?); - let obstruction = volatile_path(owner)?.with_extension("json.tmp"); - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); let failed = registry.flush_volatile_all(); assert_eq!(failed.len(), 1); assert!(failed[0].1.is_err()); @@ -371,7 +367,7 @@ async fn failed_read_checkpoint_keeps_wake_pending_until_retry( !memory.stage_task_reads(&[task])?, "already staged is not durable success" ); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); for (_, result) in registry.flush_volatile_all() { result?; } @@ -398,8 +394,7 @@ async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( matches!(registry.record_task_reads(owner, accepted.incarnation(), &[task]), Err(TaskConsumptionError::Replaced(id)) if id == owner) ); assert_eq!(current.pending_task_wakes(), vec![task]); - let obstruction = volatile_path(owner)?.with_extension("json.tmp"); - std::fs::create_dir(&obstruction)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); assert!(matches!( registry.record_task_reads(owner, current.incarnation(), &[task]), Err(TaskConsumptionError::Owner( @@ -407,7 +402,7 @@ async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( )) )); assert_eq!(current.pending_task_wakes(), vec![task]); - std::fs::remove_dir(&obstruction)?; + drop(fence_fault); registry.record_task_reads(owner, current.incarnation(), &[task])?; assert!(current.pending_task_wakes().is_empty()); let restored = WorkingMemory::new(8); diff --git a/core/continuum-host/src/durable/fault_injection.rs b/core/continuum-host/src/durable/fault_injection.rs index 5b6b34f692..8e1ab3f5d2 100644 --- a/core/continuum-host/src/durable/fault_injection.rs +++ b/core/continuum-host/src/durable/fault_injection.rs @@ -9,6 +9,27 @@ pub(super) fn fence_fails() -> bool { FAIL_FENCE.with(Cell::get) } +/// Thread-bound fault scope; an async fixture must stay on its current-thread runtime. +pub struct FailedFenceScope { + previous: bool, + thread_bound: std::marker::PhantomData>, +} + +impl FailedFenceScope { + pub fn enter() -> Self { + Self { + previous: FAIL_FENCE.with(|fault| fault.replace(true)), + thread_bound: std::marker::PhantomData, + } + } +} + +impl Drop for FailedFenceScope { + fn drop(&mut self) { + FAIL_FENCE.with(|fault| fault.set(self.previous)); + } +} + /// Captured fixture state. Capturing alone does not affect another thread. #[derive(Clone, Copy)] pub struct FenceFault(bool); diff --git a/core/continuum-host/src/durable/staging.rs b/core/continuum-host/src/durable/staging.rs index 4dcd0a6dd0..a212893c82 100644 --- a/core/continuum-host/src/durable/staging.rs +++ b/core/continuum-host/src/durable/staging.rs @@ -38,7 +38,11 @@ impl Staging { pub fn new(dir: &Dir) -> io::Result { let dir = dir.try_clone()?; loop { - let name = format!(".{}-{}.staging", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)); + let name = format!( + ".{}-{}.staging", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + ); match dir.open_with(&name, OpenOptions::new().write(true).create_new(true)) { Ok(file) => return Ok(Staging { dir, name, file }), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, @@ -64,6 +68,10 @@ impl Staging { /// Sync and move over `name` in the same directory, replacing what is there. pub fn replace(self, name: &Path) -> io::Result<()> { + #[cfg(any(test, feature = "test-fixtures"))] + if super::fault_injection::fence_fails() { + return Err(io::Error::other("injected durability fence failure")); + } self.file.sync_all()?; self.dir.rename(&self.name, &self.dir, name)?; super::os::sync_placed(&self.dir, name) @@ -72,6 +80,10 @@ impl Staging { /// Sync and publish at `name` in the same directory: `AlreadyExists` if it is taken (a racing /// identical publisher calls [`fence_existing`] on it), never an overwrite. pub fn publish_new(self, name: &Path) -> io::Result<()> { + #[cfg(any(test, feature = "test-fixtures"))] + if super::fault_injection::fence_fails() { + return Err(io::Error::other("injected durability fence failure")); + } self.file.sync_all()?; self.dir.hard_link(&self.name, &self.dir, name)?; super::os::sync_placed(&self.dir, name) @@ -91,7 +103,8 @@ impl Drop for Staging { /// Complete the durability fence of `name` in `dir`, a name another publisher created and may not /// have synced yet, so a reader never trusts an unfenced name. pub fn fence_existing(dir: &Dir, name: &Path) -> io::Result<()> { - dir.open_with(name, OpenOptions::new().read(true).write(true))?.sync_all()?; + dir.open_with(name, OpenOptions::new().read(true).write(true))? + .sync_all()?; super::os::sync_placed(dir, name) } @@ -104,9 +117,19 @@ pub struct Lock { /// Lock `name` in `dir` exclusively, waiting for a holder when `wait`, else refusing with /// `WouldBlock`. pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { - let file = dir.open_with(name, OpenOptions::new().read(true).write(true).create(true).truncate(false))?; + let file = dir.open_with( + name, + OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false), + )?; if !file.metadata()?.is_file() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("lock {} is not a regular file", name.display()))); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("lock {} is not a regular file", name.display()), + )); } let file = file.into_std(); if wait { @@ -114,7 +137,9 @@ pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { } else { match file.try_lock() { Ok(()) => {} - Err(TryLockError::WouldBlock) => return Err(io::Error::from(io::ErrorKind::WouldBlock)), + Err(TryLockError::WouldBlock) => { + return Err(io::Error::from(io::ErrorKind::WouldBlock)) + } Err(TryLockError::Error(error)) => return Err(error), } } @@ -124,12 +149,26 @@ pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { /// Lock the file at `path` (its directory opened and held). pub fn lock_path(path: &Path, wait: bool) -> io::Result { let (dir, name) = split(path)?; - lock(&Dir::open_ambient_dir(dir, cap_std::ambient_authority())?, Path::new(name), wait) + lock( + &Dir::open_ambient_dir(dir, cap_std::ambient_authority())?, + Path::new(name), + wait, + ) } fn split(path: &Path) -> io::Result<(&Path, &std::ffi::OsStr)> { match (path.parent(), path.file_name()) { - (Some(dir), Some(name)) => Ok((if dir.as_os_str().is_empty() { Path::new(".") } else { dir }, name)), - _ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file in a directory", path.display()))), + (Some(dir), Some(name)) => Ok(( + if dir.as_os_str().is_empty() { + Path::new(".") + } else { + dir + }, + name, + )), + _ => Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file in a directory", path.display()), + )), } } diff --git a/core/continuum-host/src/durable/tests.rs b/core/continuum-host/src/durable/tests.rs index e0b63a19b2..c2f1c0825c 100644 --- a/core/continuum-host/src/durable/tests.rs +++ b/core/continuum-host/src/durable/tests.rs @@ -92,3 +92,22 @@ fn a_held_lock_refuses_a_second_holder() { // between fork and exec (O_CLOEXEC releases it at exec), so "free" is "free once that ends". lock_path(&path, true).expect("free again"); } + +// The managed class path uses Staging, not the legacy path-based fence helper. +#[test] +fn staged_replacement_fault_preserves_old_bytes_and_retry_succeeds() -> io::Result<()> { + let root = tempfile::tempdir()?; + let path = root.path().join("state"); + std::fs::write(&path, b"old")?; + let replace = || -> io::Result<()> { + let mut stage = Staging::new_in(root.path())?; + stage.write_all(b"new")?; + stage.replace(Path::new("state")) + }; + assert!(fault_injection::with_failed_fence(replace).is_err()); + assert_eq!(std::fs::read(&path)?, b"old"); + assert_eq!(std::fs::read_dir(root.path())?.count(), 1); + replace()?; + assert_eq!(std::fs::read(path)?, b"new"); + Ok(()) +} diff --git a/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs b/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs index ebf8d9d828..71f4161622 100644 --- a/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs +++ b/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs @@ -30,7 +30,10 @@ pub struct ClassWriter { impl TrackedDir { pub fn writer(self: &Arc) -> ClassWriter { - ClassWriter { dir: Arc::clone(self), scope: PathBuf::new() } + ClassWriter { + dir: Arc::clone(self), + scope: PathBuf::new(), + } } } @@ -56,7 +59,10 @@ impl ClassWriter { /// a citizen's. The one place an owner's directory name is formed; a caller names only its /// file. pub fn owned_by(&self, owner: uuid::Uuid) -> Self { - ClassWriter { dir: Arc::clone(&self.dir), scope: self.scope.join(owner.to_string()) } + ClassWriter { + dir: Arc::clone(&self.dir), + scope: self.scope.join(owner.to_string()), + } } /// This scope's directory, held open (created on first use). @@ -67,8 +73,18 @@ impl ClassWriter { /// `relative`'s directory, held open, and its file name. fn held_parent<'a>(&self, relative: &'a Path) -> io::Result<(confine::Dir, &'a Path)> { let relative = confine::plain(relative)?; - let name = relative.file_name().map(Path::new).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file", relative.display())))?; - let dirs = relative.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file", relative.display())))?; + let name = relative.file_name().map(Path::new).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file", relative.display()), + ) + })?; + let dirs = relative.parent().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file", relative.display()), + ) + })?; Ok((confine::subdir(&self.held()?, dirs)?, name)) } @@ -80,7 +96,11 @@ impl ClassWriter { for entry in self.held()?.entries()? { let entry = entry?; if entry.file_type()?.is_dir() { - if let Some(owner) = entry.file_name().to_str().and_then(|name| uuid::Uuid::parse_str(name).ok()) { + if let Some(owner) = entry + .file_name() + .to_str() + .and_then(|name| uuid::Uuid::parse_str(name).ok()) + { owners.push(owner); } } @@ -93,7 +113,11 @@ impl ClassWriter { /// type: refused unless it is plain names. Writes never go through it; they go through the /// held directory. pub fn path(&self, relative: &Path) -> io::Result { - Ok(self.dir.path().join(&self.scope).join(confine::plain(relative)?)) + Ok(self + .dir + .path() + .join(&self.scope) + .join(confine::plain(relative)?)) } /// Replace a file whole: a reader sees the old bytes or the new ones, never half, and the @@ -105,6 +129,12 @@ impl ClassWriter { staging.replace(name) } + /// Finish the durability fence of an existing class-owned publication. + pub fn fence_existing(&self, relative: &Path) -> io::Result<()> { + let (dir, name) = self.held_parent(relative)?; + durable::fence_existing(&dir, name) + } + /// Publish an immutable file once: `AlreadyExists` if the name is taken, never an overwrite. /// A caller that may be replaying compares what is there. pub fn publish_new(&self, relative: &Path, bytes: &[u8]) -> io::Result<()> { @@ -117,7 +147,9 @@ impl ClassWriter { /// Open a file to append to (a log, a capture stream), creating it on first use. pub fn append(&self, relative: &Path) -> io::Result { let (dir, name) = self.held_parent(relative)?; - Ok(dir.open_with(name, confine::OpenOptions::new().create(true).append(true))?.into_std()) + Ok(dir + .open_with(name, confine::OpenOptions::new().create(true).append(true))? + .into_std()) } /// Lock `relative` exclusively (a lock file in the class), waiting for a holder when `wait`, @@ -144,7 +176,10 @@ mod tests { fn a_path_outside_the_class_is_refused() { let (_root, writer) = class(); for escape in ["", "/etc/passwd", "../sibling", "a/../../b", "./a"] { - assert!(writer.path(Path::new(escape)).is_err(), "{escape:?} must be refused"); + assert!( + writer.path(Path::new(escape)).is_err(), + "{escape:?} must be refused" + ); } assert!(writer.path(Path::new("peers/a/emission.json")).is_ok()); } @@ -159,10 +194,22 @@ mod tests { writer.replace(name, b"two").expect("second"); let path = writer.path(name).expect("path"); assert_eq!(std::fs::read(&path).expect("read"), b"two"); - let left: Vec<_> = std::fs::read_dir(path.parent().expect("parent")).expect("dir").collect(); + let left: Vec<_> = std::fs::read_dir(path.parent().expect("parent")) + .expect("dir") + .collect(); assert_eq!(left.len(), 1, "no staging file left beside it"); - assert_eq!(writer.publish_new(name, b"three").expect_err("taken").kind(), io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read(&path).expect("read"), b"two", "a refused publish changed nothing"); + assert_eq!( + writer + .publish_new(name, b"three") + .expect_err("taken") + .kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!( + std::fs::read(&path).expect("read"), + b"two", + "a refused publish changed nothing" + ); } // what this catches: an owner's file landing outside its owner's directory, or a caller @@ -172,17 +219,35 @@ mod tests { let (_root, writer) = class(); let owner = uuid::Uuid::from_u128(7); let mine = writer.owned_by(owner); - mine.replace(Path::new("emission.json"), b"{}").expect("write"); + mine.replace(Path::new("emission.json"), b"{}") + .expect("write"); assert_eq!( mine.path(Path::new("emission.json")).expect("path"), - writer.path(Path::new(&owner.to_string())).expect("owner dir").join("emission.json") + writer + .path(Path::new(&owner.to_string())) + .expect("owner dir") + .join("emission.json") + ); + assert!( + mine.path(Path::new("../other")).is_err(), + "an owner cannot reach a sibling" ); - assert!(mine.path(Path::new("../other")).is_err(), "an owner cannot reach a sibling"); // The mirror: the owners read back are exactly those written, and a stray file is not one. - writer.owned_by(uuid::Uuid::from_u128(3)).replace(Path::new("demand.json"), b"{}").expect("second owner"); - writer.replace(Path::new("README"), b"not an owner").expect("stray"); - assert_eq!(writer.owners().expect("owners"), vec![uuid::Uuid::from_u128(3), owner]); - assert_eq!(class().1.owners().expect("empty class"), Vec::::new()); + writer + .owned_by(uuid::Uuid::from_u128(3)) + .replace(Path::new("demand.json"), b"{}") + .expect("second owner"); + writer + .replace(Path::new("README"), b"not an owner") + .expect("stray"); + assert_eq!( + writer.owners().expect("owners"), + vec![uuid::Uuid::from_u128(3), owner] + ); + assert_eq!( + class().1.owners().expect("empty class"), + Vec::::new() + ); } // what this catches: a symlink inside the class sending a write outside the measured root @@ -193,30 +258,50 @@ mod tests { fn a_redirect_inside_the_class_writes_nothing_outside_it() { let (root, writer) = class(); let outside = tempfile::tempdir().expect("outside"); - writer.replace(Path::new("seed"), b"x").expect("the class root exists"); - std::os::unix::fs::symlink(outside.path(), root.path().join("class/away")).expect("dir link"); - assert!(writer.replace(Path::new("away/state.json"), b"leak").is_err()); + writer + .replace(Path::new("seed"), b"x") + .expect("the class root exists"); + std::os::unix::fs::symlink(outside.path(), root.path().join("class/away")) + .expect("dir link"); + assert!(writer + .replace(Path::new("away/state.json"), b"leak") + .is_err()); assert!(writer.append(Path::new("away/log")).is_err()); assert!(writer.lock(Path::new("away/.lock"), false).is_err()); std::fs::write(outside.path().join("target"), b"").expect("target"); - std::os::unix::fs::symlink(outside.path().join("target"), root.path().join("class/file-link")).expect("file link"); + std::os::unix::fs::symlink( + outside.path().join("target"), + root.path().join("class/file-link"), + ) + .expect("file link"); assert!(writer.append(Path::new("file-link")).is_err()); - assert_eq!(std::fs::read_dir(outside.path()).expect("outside").count(), 1, "nothing written outside the class"); + assert_eq!( + std::fs::read_dir(outside.path()).expect("outside").count(), + 1, + "nothing written outside the class" + ); } // what this catches: a writer that guesses a directory when its class is not registered. #[test] fn an_unregistered_class_has_no_writer() { - assert_eq!(ClassWriter::of("no-such-class").err().map(|e| e.kind()), Some(io::ErrorKind::NotFound)); + assert_eq!( + ClassWriter::of("no-such-class").err().map(|e| e.kind()), + Some(io::ErrorKind::NotFound) + ); } // what this catches: two holders of one lock at once. #[test] fn a_held_lock_refuses_a_second_holder() { let (_root, writer) = class(); - let held = writer.lock(Path::new("p/.volatile.lock"), false).expect("first"); + let held = writer + .lock(Path::new("p/.volatile.lock"), false) + .expect("first"); assert!(writer.lock(Path::new("p/.volatile.lock"), false).is_err()); drop(held); - writer.lock(Path::new("p/.volatile.lock"), false).expect("free again"); + writer + .lock(Path::new("p/.volatile.lock"), false) + .expect("free again"); } } From eae44a500e61158703e4a3a1ea31454b94786539 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:35:15 -0600 Subject: [PATCH 82/88] fix(cognition): resolve checkpoint custody and carry seam fault fixtures --- .../persona_workspace/checkpoint_adoption.rs | 27 +++------------- .../persona_workspace/checkpoint_storage.rs | 32 ++++++++++++++++++- .../root_acting_workspace.rs | 7 +++- ..._told_when_her_hands_move_and_only_then.rs | 2 +- 4 files changed, 42 insertions(+), 26 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index 06d5e966cd..2af0047c0d 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -5,6 +5,7 @@ //! caller's offline check, and never claims the selected snapshot was flushed //! at shutdown or authenticated to a process lifetime. +use super::checkpoint_storage::resolved_path; use std::fs::{self, File}; use std::io::{self, Read}; use std::path::{Path, PathBuf}; @@ -187,27 +188,6 @@ fn optional_selection(path: &Path) -> Result, Adopti } } -fn resolved_path(path: &Path) -> Result { - match fs::symlink_metadata(path) { - Ok(metadata) => { - if metadata.file_type().is_symlink() { - return Err(invalid( - "symbolic checkpoint/evidence paths are not accepted", - )); - } - Ok(fs::canonicalize(path)?) - } - Err(error) if error.kind() == io::ErrorKind::NotFound => { - let parent = path.parent().ok_or_else(|| invalid("path has no parent"))?; - let name = path - .file_name() - .ok_or_else(|| invalid("path has no filename"))?; - Ok(resolved_path(parent)?.join(name)) - } - Err(error) => Err(error.into()), - } -} - fn source_path(path: &Path, persona: Uuid) -> Result { if persona.is_nil() { return Err(invalid("an explicit non-nil persona UUID is required")); @@ -273,11 +253,12 @@ fn relative<'a>( writer: &continuum_kernel::system_resources::disk_reporters::ClassWriter, path: &'a Path, ) -> io::Result { - let checkpoint = writer.path(Path::new("volatile.json"))?; + let checkpoint = resolved_path(&writer.path(Path::new("volatile.json"))?)?; let parent = checkpoint .parent() .ok_or_else(|| io::Error::other("checkpoint has no parent"))?; - path.strip_prefix(parent) + resolved_path(path)? + .strip_prefix(parent) .map(Path::to_path_buf) .map_err(|_| { io::Error::new( diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs index ac82dd95ea..89585c625b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs @@ -39,7 +39,10 @@ pub(super) fn for_path(path: &Path) -> io::Result { io::Error::new(io::ErrorKind::InvalidInput, "checkpoint has no typed owner") })?; let writer = writer(owner)?; - if std::path::absolute(path)? != std::path::absolute(writer.path(Path::new("volatile.json"))?)? + if resolved_path(&std::path::absolute(path)?)? + != resolved_path(&std::path::absolute( + writer.path(Path::new("volatile.json"))?, + )?)? { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -48,3 +51,30 @@ pub(super) fn for_path(path: &Path) -> io::Result { } Ok(writer) } + +/// Resolve existing ancestors before comparing class custody. Temporary homes on +/// macOS may use /var while canonical paths use /private/var. The ClassWriter +/// still owns confinement and the actual held-directory write. +pub(super) fn resolved_path(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) => { + if metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "symbolic checkpoint/evidence paths are not accepted", + )); + } + std::fs::canonicalize(path) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let parent = path + .parent() + .ok_or_else(|| io::Error::other("path has no parent"))?; + let name = path + .file_name() + .ok_or_else(|| io::Error::other("path has no filename"))?; + Ok(resolved_path(parent)?.join(name)) + } + Err(error) => Err(error), + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index 3860ddc828..de2398b66a 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -438,6 +438,8 @@ impl PersonaWorkspaceRegistry { let test_home = crate::paths::NativeHomeOverride::current(); #[cfg(test)] let test_home = &test_home; + #[cfg(test)] + let fence_fault = continuum_host::durable::fault_injection::FenceFault::capture(); let results: Vec<(Uuid, std::io::Result)> = std::thread::scope(|scope| { let handles: Vec<_> = residents .into_iter() @@ -447,7 +449,10 @@ impl PersonaWorkspaceRegistry { let _home = test_home .as_deref() .map(crate::paths::NativeHomeOverride::install); - save_one(id, memory) + #[cfg(test)] + { fence_fault.run(|| save_one(id, memory)) } + #[cfg(not(test))] + { save_one(id, memory) } }); (id, handle) }) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index fb451caa14..5e6f0d1649 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -725,7 +725,7 @@ use super::*; std::fs::create_dir_all(path.parent().unwrap()).unwrap(); // Deterministic on Unix and Windows: a directory cannot be overwritten // by the temporary checkpoint file, regardless of user permissions. - let _fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + std::fs::create_dir(&path).expect("test: obstruct only the failed resident checkpoint"); let outcomes = registry.flush_volatile_all(); assert_eq!(outcomes.len(), 2); assert!(outcomes From 325b05105b38b78c29cdefeffa26f26d57180614 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:51:32 -0600 Subject: [PATCH 83/88] fix(stage): stamp provenance from the owned run and inputs --- .../src/cognition/deferred_faculty.rs | 14 ++----- .../src/runtime/stage/runner.rs | 15 +++++-- .../src/runtime/stage/stage.rs | 7 ++-- .../src/runtime/stage/tests.rs | 42 ++++++++----------- 4 files changed, 38 insertions(+), 40 deletions(-) diff --git a/core/continuum-cognition/src/cognition/deferred_faculty.rs b/core/continuum-cognition/src/cognition/deferred_faculty.rs index 92317c809b..819f3ea1ec 100644 --- a/core/continuum-cognition/src/cognition/deferred_faculty.rs +++ b/core/continuum-cognition/src/cognition/deferred_faculty.rs @@ -40,7 +40,7 @@ use std::sync::Arc; use async_trait::async_trait; use continuum_kernel::runtime::stage::{ - Cost, ExecutionCost, InputRevision, MindId, Provenance, Ran, ResidencyCost, RunOutcome, Stage, + Cost, ExecutionCost, InputRevision, MindId, Ran, ResidencyCost, RunOutcome, Stage, StageContext, StageId, StageIncarnation, StageRunner, TopicName, Triggers, }; use uuid::Uuid; @@ -97,9 +97,9 @@ impl Stage for FacultyStage { async fn run( &self, - ctx: &StageContext, + _ctx: &StageContext, ws: &Workspace, - revisions: &[InputRevision], + _revisions: &[InputRevision], ) -> RunOutcome> { let finding = self.inner.contribute(ws).await.map(|mut c| { // Stamp with the cycle it reasoned against AND the room it reasoned about: the late @@ -112,13 +112,7 @@ impl Stage for FacultyStage { contribution: c, } }); - RunOutcome::Produced(vec![( - finding, - Provenance { - by: ctx.run, - from: revisions.to_vec(), - }, - )]) + RunOutcome::Produced(vec![finding]) } } diff --git a/core/continuum-kernel/src/runtime/stage/runner.rs b/core/continuum-kernel/src/runtime/stage/runner.rs index 68a67a03d5..751269e784 100644 --- a/core/continuum-kernel/src/runtime/stage/runner.rs +++ b/core/continuum-kernel/src/runtime/stage/runner.rs @@ -120,7 +120,7 @@ impl Shared { Ok(outcome) => { self.panics.store(0, Ordering::Release); match outcome { - RunOutcome::Produced(outputs) => self.publish(outputs), + RunOutcome::Produced(outputs) => self.publish(outputs, run, revisions), RunOutcome::Idle => Ran::Idle, RunOutcome::Stopped(receipt) => Ran::Stopped(receipt), RunOutcome::Dispatched => { @@ -140,9 +140,18 @@ impl Shared { } /// Publish each output under the compare-and-set, atomically with making it visible. - fn publish(&self, outputs: Vec<(S::Output, Provenance)>) -> Ran { + fn publish( + &self, + outputs: Vec, + run: RunId, + revisions: &[InputRevision], + ) -> Ran { let (mut accepted, mut refused) = (Vec::new(), 0); - for (output, provenance) in outputs { + for output in outputs { + let provenance = Provenance { + by: run, + from: revisions.to_vec(), + }; self.published.send_if_modified(|state| { let fresh = state.publication.try_publish(&provenance.from) == Published::Accepted; if fresh { diff --git a/core/continuum-kernel/src/runtime/stage/stage.rs b/core/continuum-kernel/src/runtime/stage/stage.rs index 0a50ec936e..72f3576eb4 100644 --- a/core/continuum-kernel/src/runtime/stage/stage.rs +++ b/core/continuum-kernel/src/runtime/stage/stage.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use super::control::{ControlRequest, StopReceipt}; use super::cost::Cost; use super::identity::{RunId, StageId}; -use super::topic::{InputRevision, Provenance}; +use super::topic::InputRevision; use super::triggers::Triggers; /// What the substrate hands a run: its identity and the control requests it checks at its yield @@ -26,8 +26,9 @@ impl StageContext { /// What one run produced. #[derive(Debug)] pub enum RunOutcome { - /// Outputs to publish under the publication rule, each with its provenance. - Produced(Vec<(O, Provenance)>), + /// Outputs to publish. The runner stamps the actual run and submitted inputs; + /// a stage cannot substitute provenance. + Produced(Vec), /// Work handed to the task owner; its completion re-triggers the stage. Dispatched, /// Nothing to do for these inputs. diff --git a/core/continuum-kernel/src/runtime/stage/tests.rs b/core/continuum-kernel/src/runtime/stage/tests.rs index 3452c3cd01..ba1785ef29 100644 --- a/core/continuum-kernel/src/runtime/stage/tests.rs +++ b/core/continuum-kernel/src/runtime/stage/tests.rs @@ -139,13 +139,7 @@ impl Stage for Counting { } } } - RunOutcome::Produced(vec![( - input.len() as u64, - Provenance { - by: ctx.run, - from: input.to_vec(), - }, - )]) + RunOutcome::Produced(vec![input.len() as u64]) } } @@ -162,13 +156,7 @@ async fn a_stage_honours_control_with_the_receipt_that_proves_it() { let (tx, rx) = tokio::sync::watch::channel(ControlRequest::Continue); let ctx = StageContext { run, control: rx }; match Counting.run(&ctx, &(), &input).await { - RunOutcome::Produced(out) => assert_eq!( - out[0].1, - Provenance { - by: run, - from: input.to_vec() - } - ), + RunOutcome::Produced(out) => assert_eq!(out, vec![1]), other => panic!("left alone it completes: {other:?}"), // test: the assertion failing loudly } tx.send(ControlRequest::Yield) @@ -214,18 +202,12 @@ impl Stage for Echo { } async fn run( &self, - ctx: &StageContext, + _ctx: &StageContext, input: &i64, - revisions: &[InputRevision], + _revisions: &[InputRevision], ) -> RunOutcome { assert!(*input >= 0, "test: a negative input panics the run"); // test: the deliberate panic under test - RunOutcome::Produced(vec![( - *input, - Provenance { - by: ctx.run, - from: revisions.to_vec(), - }, - )]) + RunOutcome::Produced(vec![*input]) } } @@ -300,7 +282,19 @@ async fn an_inline_run_publishes_under_the_same_rule() { refused: 0 } ); - assert_eq!(runner.latest().map(|o| o.output), Some(4)); + let published = runner.latest().expect("test: inline output was published"); + assert_eq!(published.output, 4); + assert_eq!( + published.provenance, + Provenance { + by: RunId { + incarnation: incarnation(1), + seq: 1 + }, + from: vec![rev("numbers", 4)], + }, + "the runner stamps its own run and inputs even when the stage ignores them" + ); assert_eq!( runner.run_inline(&2, &[rev("numbers", 2)]).await, Ran::Produced { From 20cd74301c435cd3d164281fcf25a5b94ecd992d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 19:10:57 -0600 Subject: [PATCH 84/88] fix(stage): avoid shadowing the publication test helper --- core/continuum-kernel/src/runtime/stage/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/continuum-kernel/src/runtime/stage/tests.rs b/core/continuum-kernel/src/runtime/stage/tests.rs index ba1785ef29..bbfd1c1e6d 100644 --- a/core/continuum-kernel/src/runtime/stage/tests.rs +++ b/core/continuum-kernel/src/runtime/stage/tests.rs @@ -282,10 +282,10 @@ async fn an_inline_run_publishes_under_the_same_rule() { refused: 0 } ); - let published = runner.latest().expect("test: inline output was published"); - assert_eq!(published.output, 4); + let inline_output = runner.latest().expect("test: inline output was published"); + assert_eq!(inline_output.output, 4); assert_eq!( - published.provenance, + inline_output.provenance, Provenance { by: RunId { incarnation: incarnation(1), From fd63f4a8bf14790faf6a21a4e5eeaa557d5f0806 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:45:14 -0600 Subject: [PATCH 85/88] fix(tasks): fence terminal publication to accepted execution incarnation --- .../tests/task_consumption.rs | 9 +- .../runtime/command_executor/background.rs | 11 +- core/continuum-kernel/src/runtime/tasks.rs | 146 ++++++++++++++++-- .../src/runtime/tasks/delivery/tests.rs | 63 +++++++- .../src/runtime/tasks/output.rs | 14 +- .../src/modules/cognition/task_delivery.rs | 27 +++- 6 files changed, 241 insertions(+), 29 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs index f10ce7edd9..f79cf578f4 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -250,7 +250,14 @@ async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( let end = TaskEnd::Done(TaskOutput::Json( serde_json::json!({"result":"useful result"}), )); - ledger.finish(task, owner, end.clone()).await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + end.clone(), + ) + .await?; let limit = std::num::NonZeroUsize::new(32).ok_or("invalid fixture page")?; assert!(ledger .deliver_page(owner, None, limit, &sink) diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs index a464b6b4cc..f2fc777d12 100644 --- a/core/continuum-kernel/src/runtime/command_executor/background.rs +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -115,7 +115,7 @@ impl CommandExecutor { outcome: error.outcome, }, }; - let winner = match ledger.finish(handle, owner, end).await { + let winner = match ledger.finish(handle, owner, this.task_execution, end).await { Ok(winner) => winner, Err(error) => { tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); @@ -303,7 +303,14 @@ mod tests { outcome: DispatchOutcome::Uncertain, }; if !unwind { - ledger.finish(task, owner, winner.clone()).await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + winner.clone(), + ) + .await?; } gate.release.notify_one(); let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index e338481c96..28c3ed9d7a 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -173,8 +173,16 @@ impl TaskLedger { /// Only a supervisor that has observed execution ending calls this. A cancellation /// request alone is not an end. Competing endings return the durable winner. - pub async fn finish(&self, task: Uuid, owner: Uuid, end: TaskEnd) -> Result { - self.authorize(task, owner).await?; + pub async fn finish( + &self, + task: Uuid, + owner: Uuid, + execution: TaskExecution, + end: TaskEnd, + ) -> Result { + if self.execution(task, owner).await? != execution { + return Err("task completion belongs to a different execution incarnation".into()); + } let id = Uuid::new_v5(&task, b"terminal"); let row = TaskFact { task, @@ -336,6 +344,27 @@ mod tests { assert_eq!(reopened.pending(task, owner).await?, None); // An old incarnation is unresolved, not automatically Lost at reopen. assert_eq!(reopened.terminal(task, owner).await?, None); + assert!(reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await + .is_err()); + assert_eq!(reopened.terminal(task, owner).await?, None); + // Late evidence from the accepted incarnation remains valid after reopen. + assert_eq!( + reopened + .finish(task, owner, execution, TaskEnd::Stopped) + .await?, + TaskEnd::Stopped + ); + // Even after a terminal exists, a replacement cannot claim its completion. + assert!(reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await + .is_err()); + assert_eq!( + reopened.terminal(task, owner).await?, + Some(TaskEnd::Stopped) + ); Ok(()) } @@ -354,8 +383,18 @@ mod tests { .await?; assert!(first.acknowledge(task, owner).await.is_err()); let (a, b) = tokio::join!( - first.finish(task, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))), - second.finish(task, owner, TaskEnd::Stopped), + first.finish( + task, + owner, + first.execution(task, owner).await?, + TaskEnd::Done(TaskOutput::Json(Value::Null)) + ), + second.finish( + task, + owner, + second.execution(task, owner).await?, + TaskEnd::Stopped + ), ); let winner = a?; assert_eq!(winner, b?); @@ -367,7 +406,17 @@ mod tests { .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) .await?; assert_eq!(page.ends, vec![(task, winner.clone())]); - assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); + assert_eq!( + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, + winner + ); assert!(reopened.pending(task, Uuid::new_v4()).await.is_err()); reopened.acknowledge(task, owner).await?; reopened.acknowledge(task, owner).await?; @@ -387,7 +436,14 @@ mod tests { TaskExecution::new_command_executor(), ) .await?; - ledger.finish(task, owner, TaskEnd::Stopped).await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped, + ) + .await?; ledger .facts .save( @@ -418,7 +474,14 @@ mod tests { TaskExecution::new_command_executor(), ) .await?; - ledger.finish(consumed, owner, TaskEnd::Stopped).await?; + ledger + .finish( + consumed, + owner, + ledger.execution(consumed, owner).await?, + TaskEnd::Stopped, + ) + .await?; ledger.acknowledge(consumed, owner).await?; let pending = ledger .accept( @@ -428,7 +491,12 @@ mod tests { ) .await?; ledger - .finish(pending, owner, TaskEnd::Done(TaskOutput::Json(Value::Null))) + .finish( + pending, + owner, + ledger.execution(pending, owner).await?, + TaskEnd::Done(TaskOutput::Json(Value::Null)), + ) .await?; let other = ledger .accept( @@ -437,7 +505,14 @@ mod tests { TaskExecution::new_command_executor(), ) .await?; - ledger.finish(other, foreign, TaskEnd::Stopped).await?; + ledger + .finish( + other, + foreign, + ledger.execution(other, foreign).await?, + TaskEnd::Stopped, + ) + .await?; let mut after = None; let mut found = Vec::new(); let mut exhausted = false; @@ -479,7 +554,14 @@ mod tests { .await?; adapter.fail_after_next_create(); assert_eq!( - ledger.finish(task, owner, TaskEnd::Stopped).await?, + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped + ) + .await?, TaskEnd::Stopped ); drop(ledger); @@ -491,7 +573,14 @@ mod tests { let reopened = TaskLedger::new(adapter.clone()).await?; assert_eq!(reopened.pending(task, owner).await?, None); assert_eq!( - reopened.finish(task, owner, TaskEnd::Lost).await?, + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, TaskEnd::Stopped ); reopened.acknowledge(task, owner).await?; @@ -530,7 +619,16 @@ mod tests { ) .await?; let pause = gated.pause_next_write(); - let writer = tokio::spawn(async move { delayed.finish(task, owner, TaskEnd::Lost).await }); + let writer = tokio::spawn(async move { + delayed + .finish( + task, + owner, + delayed.execution(task, owner).await?, + TaskEnd::Lost, + ) + .await + }); notified(&pause.entered).await?; writer.abort(); assert!(matches!(writer.await, Err(error) if error.is_cancelled())); @@ -538,7 +636,17 @@ mod tests { // The competing supervisor observed the actual execution ending. Its result // reaches the sink while the abandoned storage operation is still pending. let winner = TaskEnd::Done(TaskOutput::Json(serde_json::json!({"saved": true}))); - assert_eq!(current.finish(task, owner, winner.clone()).await?, winner); + assert_eq!( + current + .finish( + task, + owner, + current.execution(task, owner).await?, + winner.clone() + ) + .await?, + winner + ); assert_eq!(current.pending(task, owner).await?, Some(winner.clone())); current.acknowledge(task, owner).await?; pause.release.notify_one(); @@ -546,7 +654,17 @@ mod tests { drop(current); let reopened = TaskLedger::new(adapter).await?; - assert_eq!(reopened.finish(task, owner, TaskEnd::Lost).await?, winner); + assert_eq!( + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, + winner + ); assert_eq!(reopened.pending(task, owner).await?, None); assert!(reopened .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs index bd62bf52d4..d7b4197fbc 100644 --- a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -34,8 +34,22 @@ async fn only_page_scoped_perception_can_ack_and_invalid_batch_has_no_partial_ef TaskExecution::new_command_executor(), ) .await?; - ledger.finish(first, owner, TaskEnd::Stopped).await?; - ledger.finish(second, owner, TaskEnd::Lost).await?; + ledger + .finish( + first, + owner, + ledger.execution(first, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + second, + owner, + ledger.execution(second, owner).await?, + TaskEnd::Lost, + ) + .await?; let sink = PerceptionSink(Default::default()); let limit = NonZeroUsize::new(32).ok_or("invalid fixture page")?; assert_eq!( @@ -109,7 +123,14 @@ async fn refused_consumption_remains_pending_and_replay_needs_no_registered_hand let task = ledger .accept(owner, "build".into(), TaskExecution::new_command_executor()) .await?; - ledger.finish(task, owner, TaskEnd::Stopped).await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped, + ) + .await?; let sink = Sink { ledger: ledger.clone(), refuse: AtomicBool::new(true), @@ -161,8 +182,22 @@ async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( TaskExecution::new_command_executor(), ) .await?; - ledger.finish(mine, owner, TaskEnd::Lost).await?; - ledger.finish(theirs, foreign, TaskEnd::Stopped).await?; + ledger + .finish( + mine, + owner, + ledger.execution(mine, owner).await?, + TaskEnd::Lost, + ) + .await?; + ledger + .finish( + theirs, + foreign, + ledger.execution(theirs, foreign).await?, + TaskEnd::Stopped, + ) + .await?; let sink = Sink { ledger: ledger.clone(), refuse: AtomicBool::new(false), @@ -213,8 +248,22 @@ async fn one_owner_page_is_consumed_once_before_its_acknowledgements( TaskExecution::new_command_executor(), ) .await?; - ledger.finish(first, owner, TaskEnd::Stopped).await?; - ledger.finish(second, owner, TaskEnd::Lost).await?; + ledger + .finish( + first, + owner, + ledger.execution(first, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + second, + owner, + ledger.execution(second, owner).await?, + TaskEnd::Lost, + ) + .await?; let sink = Sink { ledger: ledger.clone(), refuse: AtomicBool::new(false), diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs index 82b3f42b2c..066d31f3bb 100644 --- a/core/continuum-kernel/src/runtime/tasks/output.rs +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -75,10 +75,20 @@ mod tests { ) .await?; ledger - .finish(binary_task, owner, TaskEnd::Done(binary.clone())) + .finish( + binary_task, + owner, + ledger.execution(binary_task, owner).await?, + TaskEnd::Done(binary.clone()), + ) .await?; ledger - .finish(handle_task, owner, TaskEnd::Done(handle.clone())) + .finish( + handle_task, + owner, + ledger.execution(handle_task, owner).await?, + TaskEnd::Done(handle.clone()), + ) .await?; ledger.acknowledge(binary_task, owner).await?; assert_eq!(ledger.pending(binary_task, owner).await?, None); diff --git a/core/continuum-mind/src/modules/cognition/task_delivery.rs b/core/continuum-mind/src/modules/cognition/task_delivery.rs index 3901d42536..de275a2302 100644 --- a/core/continuum-mind/src/modules/cognition/task_delivery.rs +++ b/core/continuum-mind/src/modules/cognition/task_delivery.rs @@ -112,8 +112,22 @@ mod tests { let blocked = ledger.accept(refused, "blocked".into(), execution).await?; let ready = ledger.accept(healthy, "ready".into(), execution).await?; let running = ledger.accept(healthy, "running".into(), execution).await?; - ledger.finish(blocked, refused, TaskEnd::Stopped).await?; - ledger.finish(ready, healthy, TaskEnd::Stopped).await?; + ledger + .finish( + blocked, + refused, + ledger.execution(blocked, refused).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + ready, + healthy, + ledger.execution(ready, healthy).await?, + TaskEnd::Stopped, + ) + .await?; let sink = Sink { refused, refuse: AtomicBool::new(true), @@ -132,7 +146,14 @@ mod tests { Some(TaskEnd::Stopped) ); // End an already-scanned acceptance. Fresh sweeps must find it. - ledger.finish(running, healthy, TaskEnd::Lost).await?; + ledger + .finish( + running, + healthy, + ledger.execution(running, healthy).await?, + TaskEnd::Lost, + ) + .await?; sink.refuse.store(false, Ordering::SeqCst); for _ in 0..16 { sweep From e86d69a1876563bbb1f76ace8f0de7b7d0c779cf Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 21:34:41 -0600 Subject: [PATCH 86/88] fix(tasks): expose typed execution mismatch for completion reconciliation --- core/continuum-kernel/src/runtime/tasks.rs | 58 ++++++++++++++----- .../src/runtime/tasks/execution.rs | 25 ++++++++ 2 files changed, 68 insertions(+), 15 deletions(-) diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 28c3ed9d7a..6556f8954d 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -14,7 +14,7 @@ use uuid::Uuid; mod output; pub use output::TaskOutput; mod execution; -pub use execution::TaskExecution; +pub use execution::{FinishError, TaskExecution}; mod delivery; pub use delivery::{DeliveryError, DeliveryPage, TaskOwnerSink}; @@ -179,9 +179,17 @@ impl TaskLedger { owner: Uuid, execution: TaskExecution, end: TaskEnd, - ) -> Result { - if self.execution(task, owner).await? != execution { - return Err("task completion belongs to a different execution incarnation".into()); + ) -> Result { + let accepted = self + .execution(task, owner) + .await + .map_err(FinishError::Authorization)?; + if accepted != execution { + return Err(FinishError::ExecutionMismatch { + task, + accepted, + offered: execution, + }); } let id = Uuid::new_v5(&task, b"terminal"); let row = TaskFact { @@ -191,14 +199,19 @@ impl TaskLedger { }; match self.facts.save(id, &row).await { Ok(()) => Ok(end), - Err(write_error) => match self.facts.find_by_id(id).await.map_err(|e| e.to_string())? { + Err(write_error) => match self + .facts + .find_by_id(id) + .await + .map_err(|e| FinishError::Persistence(e.to_string()))? + { Some(TaskFact { task: stored_task, owner: stored_owner, fact: Fact::Ended(winner), }) if stored_task == task && stored_owner == owner => Ok(winner), // Never reinterpret an arbitrary store failure as a successful completion. - _ => Err(write_error.to_string()), + _ => Err(FinishError::Persistence(write_error.to_string())), }, } } @@ -344,10 +357,16 @@ mod tests { assert_eq!(reopened.pending(task, owner).await?, None); // An old incarnation is unresolved, not automatically Lost at reopen. assert_eq!(reopened.terminal(task, owner).await?, None); - assert!(reopened - .finish(task, owner, replacement, TaskEnd::Lost) - .await - .is_err()); + assert_eq!( + reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await, + Err(FinishError::ExecutionMismatch { + task, + accepted: execution, + offered: replacement + }) + ); assert_eq!(reopened.terminal(task, owner).await?, None); // Late evidence from the accepted incarnation remains valid after reopen. assert_eq!( @@ -357,10 +376,16 @@ mod tests { TaskEnd::Stopped ); // Even after a terminal exists, a replacement cannot claim its completion. - assert!(reopened - .finish(task, owner, replacement, TaskEnd::Lost) - .await - .is_err()); + assert_eq!( + reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await, + Err(FinishError::ExecutionMismatch { + task, + accepted: execution, + offered: replacement + }) + ); assert_eq!( reopened.terminal(task, owner).await?, Some(TaskEnd::Stopped) @@ -624,7 +649,10 @@ mod tests { .finish( task, owner, - delayed.execution(task, owner).await?, + delayed + .execution(task, owner) + .await + .map_err(FinishError::Authorization)?, TaskEnd::Lost, ) .await diff --git a/core/continuum-kernel/src/runtime/tasks/execution.rs b/core/continuum-kernel/src/runtime/tasks/execution.rs index 80fe35c142..aec960e0c1 100644 --- a/core/continuum-kernel/src/runtime/tasks/execution.rs +++ b/core/continuum-kernel/src/runtime/tasks/execution.rs @@ -17,3 +17,28 @@ impl TaskExecution { } } } + +/// A refused terminal publication, distinct from a completed task's outcome. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum FinishError { + #[error("task completion authorization failed: {0}")] + Authorization(String), + #[error( + "task {task} completion execution mismatch: accepted {accepted:?}, offered {offered:?}" + )] + ExecutionMismatch { + task: Uuid, + accepted: TaskExecution, + offered: TaskExecution, + }, + #[error("task terminal persistence failed: {0}")] + Persistence(String), +} + +// Command/test boundaries that expose textual errors can render the typed refusal; +// reconciliation inside the task owner matches FinishError directly. +impl From for String { + fn from(error: FinishError) -> Self { + error.to_string() + } +} From ba87a218f2b6fbe30f84e410b3260fc4229fafec Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 21:44:55 -0600 Subject: [PATCH 87/88] fix(tasks): distinguish unreadable acceptance from authorization refusal --- .../continuum-kernel/src/orm/gated_adapter.rs | 10 +++- core/continuum-kernel/src/runtime/tasks.rs | 54 ++++++++++++++----- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index fc622754bb..765c48f8e5 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -35,11 +35,12 @@ pub(crate) struct GatedAdapter { unwind_next: std::sync::atomic::AtomicBool, fail_after_create: std::sync::atomic::AtomicBool, fail_query: std::sync::atomic::AtomicBool, + fail_read: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false), fail_read: std::sync::atomic::AtomicBool::new(false) } } pub(crate) fn unwind_next_write(&self) { @@ -50,6 +51,10 @@ impl GatedAdapter { self.fail_after_create.store(true, std::sync::atomic::Ordering::SeqCst); } + pub(crate) fn fail_next_read(&self) { + self.fail_read.store(true, std::sync::atomic::Ordering::SeqCst); + } + pub(crate) fn fail_next_query(&self) { self.fail_query.store(true, std::sync::atomic::Ordering::SeqCst); } @@ -115,6 +120,9 @@ impl StorageAdapter for GatedAdapter { } } async fn read(&self, collection: &str, id: &UUID) -> StorageResult { + if self.fail_read.swap(false, std::sync::atomic::Ordering::SeqCst) { + return StorageResult::err("injected acceptance read failure"); + } self.inner.read(collection, id).await } async fn query(&self, query: StorageQuery) -> StorageResult> { diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 6556f8954d..320d06a672 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -151,24 +151,29 @@ impl TaskLedger { /// Recover the exact execution owner without guessing from a forgotten handle /// or a process snapshot. Only the recipient may inspect this registration. - pub async fn execution(&self, task: Uuid, owner: Uuid) -> Result { + pub async fn execution(&self, task: Uuid, owner: Uuid) -> Result { match self .facts .find_by_id(task) .await - .map_err(|e| e.to_string())? + .map_err(|e| FinishError::Persistence(e.to_string()))? { Some(TaskFact { task: stored_task, owner: stored, fact: Fact::Accepted { execution, .. }, }) if stored == owner && stored_task == task => Ok(execution), - _ => Err("task is absent or belongs to another owner".into()), + _ => Err(FinishError::Authorization( + "task is absent or belongs to another owner".into(), + )), } } async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { - self.execution(task, owner).await.map(|_| ()) + self.execution(task, owner) + .await + .map(|_| ()) + .map_err(String::from) } /// Only a supervisor that has observed execution ending calls this. A cancellation @@ -180,10 +185,7 @@ impl TaskLedger { execution: TaskExecution, end: TaskEnd, ) -> Result { - let accepted = self - .execution(task, owner) - .await - .map_err(FinishError::Authorization)?; + let accepted = self.execution(task, owner).await?; if accepted != execution { return Err(FinishError::ExecutionMismatch { task, @@ -562,6 +564,37 @@ mod tests { } use crate::orm::gated_adapter::GatedAdapter; + #[tokio::test] + async fn unreadable_acceptance_is_not_an_authorization_refusal() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let gated = Arc::new(GatedAdapter::new(adapter)); + let ledger = TaskLedger::new(gated.clone()).await?; + let owner = Uuid::new_v4(); + let execution = TaskExecution::new_command_executor(); + let task = ledger.accept(owner, "code/shell".into(), execution).await?; + gated.fail_next_read(); + assert!(matches!( + ledger + .finish(task, owner, execution, TaskEnd::Stopped) + .await, + Err(FinishError::Persistence(_)) + )); + assert_eq!(ledger.terminal(task, owner).await?, None); + assert!(matches!( + ledger + .finish(task, Uuid::new_v4(), execution, TaskEnd::Stopped) + .await, + Err(FinishError::Authorization(_)) + )); + assert_eq!( + ledger + .finish(task, owner, execution, TaskEnd::Stopped) + .await?, + TaskEnd::Stopped + ); + Ok(()) + } + #[tokio::test] async fn lost_terminal_and_delivery_replies_survive_reopen_without_duplicate_facts( ) -> Result<(), String> { @@ -649,10 +682,7 @@ mod tests { .finish( task, owner, - delayed - .execution(task, owner) - .await - .map_err(FinishError::Authorization)?, + delayed.execution(task, owner).await?, TaskEnd::Lost, ) .await From 5f4a450ae965bb105c7871c48c3d834fff7d91da Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 22:04:49 -0600 Subject: [PATCH 88/88] test(tasks): inject acceptance failure through query owner --- core/continuum-kernel/src/orm/gated_adapter.rs | 10 +--------- core/continuum-kernel/src/runtime/tasks.rs | 2 +- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index 765c48f8e5..fc622754bb 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -35,12 +35,11 @@ pub(crate) struct GatedAdapter { unwind_next: std::sync::atomic::AtomicBool, fail_after_create: std::sync::atomic::AtomicBool, fail_query: std::sync::atomic::AtomicBool, - fail_read: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false), fail_read: std::sync::atomic::AtomicBool::new(false) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false) } } pub(crate) fn unwind_next_write(&self) { @@ -51,10 +50,6 @@ impl GatedAdapter { self.fail_after_create.store(true, std::sync::atomic::Ordering::SeqCst); } - pub(crate) fn fail_next_read(&self) { - self.fail_read.store(true, std::sync::atomic::Ordering::SeqCst); - } - pub(crate) fn fail_next_query(&self) { self.fail_query.store(true, std::sync::atomic::Ordering::SeqCst); } @@ -120,9 +115,6 @@ impl StorageAdapter for GatedAdapter { } } async fn read(&self, collection: &str, id: &UUID) -> StorageResult { - if self.fail_read.swap(false, std::sync::atomic::Ordering::SeqCst) { - return StorageResult::err("injected acceptance read failure"); - } self.inner.read(collection, id).await } async fn query(&self, query: StorageQuery) -> StorageResult> { diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs index 320d06a672..357a928547 100644 --- a/core/continuum-kernel/src/runtime/tasks.rs +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -572,7 +572,7 @@ mod tests { let owner = Uuid::new_v4(); let execution = TaskExecution::new_command_executor(); let task = ledger.accept(owner, "code/shell".into(), execution).await?; - gated.fail_next_read(); + gated.fail_next_query(); assert!(matches!( ledger .finish(task, owner, execution, TaskEnd::Stopped)