diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index fcc6ece6ef..913e5d1cc5 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -83,10 +83,8 @@ impl Source for Actions<'_> { let stored = item.stored.as_ref()?; let seq: u64 = item.key.parse().ok()?; let label = self.memory.action_whole_label(seq)?; - let path = crate::cognition::tool_executor::spill::resolve(self.persona, &stored.handle).ok()?; - let body = std::fs::read_to_string(path).ok()?; - // the record keeps its result trimmed (`record_receipt_inner`); loaded back, it reads the same - Some(ContextMessage::user(format!("{label}{}", body.trim()))) + let body = crate::cognition::tool_executor::spill::saved_whole(self.persona, &stored.handle).ok()?; + Some(ContextMessage::user(format!("{label}{body}"))) } /// Once she has acted, the void said earlier in this epoch is superseded, never edited: diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 5eabe5b129..62b64ce156 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -96,7 +96,7 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); - memory.evict_resident_results_over(1); + memory.evict_resident_results_over(1, &|_, _| true); let (acts, _) = memory.action_renderings(); let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); let (chars, _) = stored.expect("evicted to its handle and priced"); diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index 57658e32a1..ece912881f 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -58,4 +58,6 @@ pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; mod own_speech_persisted; +mod mind_results_reporter; +pub use mind_results_reporter::MindResultsReporter; pub(crate) use own_speech_persisted::*; 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 6ed4d6b6c0..7da34b6291 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 @@ -653,8 +653,9 @@ pub struct PersonaWorkspaceRegistry { /// crosses between her public and private turns except what she publishes. It is never in /// `cycles`, so the volatile checkpoint never writes it to disk in plaintext (until her /// sealed store exists, a restart forgets her private scratchpad, which is the honest cost). - /// Lock order: `cycles`, then `templates`, then `mind_cycles`. - pub(super) mind_cycles: Mutex>>, + /// Lock order: `cycles`, then `templates`, then `mind_cycles`. Its working memory is held + /// beside it so the memory owner accounts and sheds her private results too. + pub(super) mind_cycles: Mutex>, } pub(super) struct ResidentWorkspace { diff --git a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs new file mode 100644 index 0000000000..e4409817f3 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs @@ -0,0 +1,364 @@ +//! The one memory owner's view of every mind's resident result bodies. +//! +//! A result's body stays in RAM until the memory pressure monitor says shed: RAM decides, not +//! a number (Joel, 2026-10-29; it replaced `RESULTS_RESIDENT_CHARS = 1 << 20`, a cap per mind +//! at receipt). This reporter is the only thing that moves a body to its handle in production +//! (`WorkingMemory::evict_resident_results_over`). It sheds oldest-first across every resident +//! mind, public and private, and never moves a mind's newest result or a body whose saved copy +//! is not PROVEN to load back to it (the last copy). +//! +//! Accounting is BYTES of resident bodies (`String::len`), never characters: characters are +//! the view's price (`stored_chars`). Each record owns its body (no shared backing), so the sum +//! over records is the RAM they hold; a working memory reached twice is counted once. +//! +//! Proof, once per saved copy, never under a mind's lock and never in `budget()`: at shed time +//! each candidate's body is copied out (the lock held only for the copy) and compared with what +//! its saved copy loads back to through the spill owner's one read (`spill::reproduces`, the +//! same text her view's `load` renders). A proven `(persona, handle)` is cached: the output is +//! content-addressed and live-protected while a record names it, so the proof holds. Only +//! proven bodies are planned and moved; an unproven one counts as pinned. +//! +//! NOT FULL GOVERNOR COVERAGE: the shed target is the host's RAM overrun past this priority's +//! gate (`over_gate`). Pressure raised by swap activity alone, with RAM use under the gate, +//! makes `over_gate` return 0 and sheds nothing here. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use parking_lot::Mutex; + +use continuum_kernel::system_resources::{ + MemoryBudgetSpec, MemoryPriority, MemoryReporter, ModuleMemoryReport, PressureLevel, + PressureSnapshot, +}; +use tokio::sync::watch; +use uuid::Uuid; + +use super::PersonaWorkspaceRegistry; +use crate::cognition::tool_executor::spill; +use crate::cognition::working_memory::{ResidentResults, ShedCandidate, WorkingMemory}; + +const NAME: &str = "mind_results"; + +/// Her results are working state for her current task ("active persona state"), not an idle +/// cache: `Interactive`. Its gate (0.80) is where the monitor's Warning starts, so a shed gives +/// up only the overrun past it, not every movable body at the first Warning as `Background`'s +/// 0.60 gate would. +const PRIORITY: MemoryPriority = MemoryPriority::Interactive; + +/// Why a body stays resident through a shed: it is the last copy of what she read. +#[derive(Debug)] +pub(crate) enum LastCopy { + /// Its saved copy could not be read back (no such handle, no file, no permission, not text). + Unreadable(std::io::Error), + /// Its saved copy reads back, but not to this body. + Mismatch, +} + +impl LastCopy { + pub(crate) fn reason(&self) -> &'static str { + match self { + Self::Unreadable(_) => "unreadable", + Self::Mismatch => "mismatch", + } + } + + fn probe(&self, persona: Uuid, handle: &str) { + let detail = match self { + Self::Unreadable(error) => error.to_string(), + Self::Mismatch => "its saved copy does not load back to the resident body".to_owned(), + }; + continuum_base::probe!( + class = "wm.results.last_copy_kept", + persona_id = %persona, + handle = %handle, + reason = self.reason(), + detail = %detail, + "a resident result stays through a shed: its saved copy cannot reproduce it" + ); + } +} + +/// Prove `candidate`'s saved copy loads back to exactly its resident body. `None` when the +/// record moved on since it was read (nothing to prove). Reads the file with no lock held. +pub(crate) fn prove( + persona: Uuid, + memory: &WorkingMemory, + candidate: &ShedCandidate, +) -> Option> { + let body = memory.resident_body(candidate.seq, &candidate.handle)?; + Some(match spill::reproduces(persona, &candidate.handle, &body) { + Ok(true) => Ok(()), + Ok(false) => Err(LastCopy::Mismatch), + Err(error) => Err(LastCopy::Unreadable(error)), + }) +} + +/// The saved copies proven to reproduce their resident bodies, per `(persona, handle)`. Pruned +/// at every shed to the candidates that still exist, so it never outgrows what is resident. +#[derive(Debug, Default)] +pub(crate) struct ProvenCopies(HashSet<(Uuid, String)>); + +impl ProvenCopies { + pub(crate) fn contains(&self, persona: Uuid, handle: &str) -> bool { + self.0.contains(&(persona, handle.to_owned())) + } +} + +/// The resident minds the reporter accounts: `(persona, working memory)`, each memory once. +pub(crate) type Minds = Vec<(Uuid, Arc)>; + +impl PersonaWorkspaceRegistry { + /// Every resident mind's working memory: her live cycle's and her private mind cycle's. + /// Each lock is taken and released on its own, never nested. + pub(crate) fn resident_working_memories(&self) -> Minds { + let mut minds: Minds = self + .cycles + .lock() + .iter() + .map(|(id, entry)| (*id, Arc::clone(&entry.working_memory))) + .collect(); + minds.extend( + self.mind_cycles + .lock() + .iter() + .map(|(id, entry)| (*id, Arc::clone(&entry.working_memory))), + ); + let mut seen = std::collections::HashSet::new(); + minds.retain(|(_, memory)| seen.insert(Arc::as_ptr(memory))); + minds + } +} + +/// The bytes every mind's resident result bodies hold. +pub(crate) fn resident_bytes(minds: &Minds) -> u64 { + minds + .iter() + .map(|(_, memory)| memory.resident_result_bytes()) + .sum() +} + +/// What this consumer gives up: how far the host's used RAM stands past the line the monitor +/// declares this priority sheds at (`MemoryPriority::pressure_gate`). Both numbers are the +/// monitor's own; nothing here is a ratio of ours. `0` before the first poll (no total yet). +pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { + let used = snapshot + .total_bytes + .saturating_sub(snapshot.available_bytes); + let gate = (snapshot.total_bytes as f64 * PRIORITY.pressure_gate()) as u64; + used.saturating_sub(gate) +} + +/// One mind's resident result bodies: what a shed may move (saved, not the newest, and its +/// copy proven) and what it may not. +#[derive(Debug, Clone)] +pub(crate) struct Residency { + pub resident_bytes: u64, + /// The newest result, every unsaved body, and every body whose copy is not proven yet. + pub pinned_bytes: u64, + /// Proven candidates, oldest first. + pub evictable: Vec, +} + +/// `memory`'s residency against the proofs in hand: memory only, no filesystem access. +pub(crate) fn residency(persona: Uuid, memory: &WorkingMemory, proven: &ProvenCopies) -> Residency { + let ResidentResults { + resident_bytes, + candidates, + } = memory.resident_results(); + let evictable: Vec = candidates + .into_iter() + .filter(|candidate| proven.contains(persona, &candidate.handle)) + .collect(); + let movable: u64 = evictable.iter().map(|candidate| candidate.bytes).sum(); + Residency { + resident_bytes, + pinned_bytes: resident_bytes - movable, + evictable, + } +} + +/// What the reporter declares: everything resident preferred, the unprovable floor as minimum. +/// Reads the proof cache only: the monitor calls this under its reporters lock. +pub(crate) fn budget_of(minds: &Minds, proven: &Mutex) -> MemoryBudgetSpec { + let proven = proven.lock(); + let (resident, pinned) = + minds + .iter() + .fold((0u64, 0u64), |(resident, pinned), (persona, memory)| { + let mind = residency(*persona, memory, &proven); + (resident + mind.resident_bytes, pinned + mind.pinned_bytes) + }); + MemoryBudgetSpec { + name: NAME.to_string(), + priority: PRIORITY, + min_bytes: pinned, + preferred_bytes: resident, + max_bytes: resident, + } +} + +/// Per mind, the candidates to move so the total comes down to `allocation`, the oldest +/// received across every mind first. +pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec> { + let total: u64 = minds.iter().map(|mind| mind.resident_bytes).sum(); + let mut chosen = vec![HashSet::new(); minds.len()]; + if total > allocation { + let mut candidates: Vec<(Option, u64, usize, u64)> = minds + .iter() + .enumerate() + .flat_map(|(index, mind)| { + mind.evictable + .iter() + .map(move |c| (c.received_ms, c.seq, index, c.bytes)) + }) + .collect(); + candidates.sort_unstable(); + let mut need = total - allocation; + for (_, seq, index, bytes) in candidates { + if need == 0 { + break; + } + chosen[index].insert(seq); + need = need.saturating_sub(bytes); + } + } + chosen +} + +/// Prove every saved candidate not proven yet, each with no lock held across its read; a copy +/// that cannot reproduce its body stays unproven and says why (`LastCopy`). Then forget proofs +/// for handles no longer resident anywhere. +fn prove_candidates(minds: &Minds, proven: &Mutex) { + let mut resident: HashSet<(Uuid, String)> = HashSet::new(); + for (persona, memory) in minds { + for candidate in memory.resident_results().candidates { + let key = (*persona, candidate.handle.clone()); + if !proven.lock().0.contains(&key) { + match prove(*persona, memory, &candidate) { + Some(Ok(())) => { + proven.lock().0.insert(key.clone()); + } + Some(Err(last_copy)) => last_copy.probe(*persona, &candidate.handle), + None => {} + } + } + resident.insert(key); + } + } + proven.lock().0.retain(|key| resident.contains(key)); +} + +/// Shed every mind's resident bodies down to `allocation` bytes in total, oldest first, moving +/// only bodies whose saved copy is proven to load back to them. +pub(crate) fn shed_to(minds: &Minds, allocation: u64, proven: &Mutex) { + prove_candidates(minds, proven); + let residencies: Vec = { + let proven = proven.lock(); + minds + .iter() + .map(|(persona, memory)| residency(*persona, memory, &proven)) + .collect() + }; + let plans = plan_shed(&residencies, allocation); + for (((_, memory), mind), chosen) in minds.iter().zip(&residencies).zip(plans) { + if chosen.is_empty() { + continue; + } + let handles: HashMap = mind + .evictable + .iter() + .filter(|candidate| chosen.contains(&candidate.seq)) + .map(|candidate| (candidate.seq, candidate.handle.as_str())) + .collect(); + let movable: u64 = mind + .evictable + .iter() + .filter(|c| handles.contains_key(&c.seq)) + .map(|c| c.bytes) + .sum(); + // Under her lock: only a planned record still naming its proven handle. + memory.evict_resident_results_over( + mind.resident_bytes.saturating_sub(movable), + &|seq, handle| { + handles + .get(&seq) + .is_some_and(|proven_handle| *proven_handle == handle) + }, + ); + } +} + +/// The `MemoryReporter` for every mind's resident result bodies. Registered once at boot +/// beside the persona registry (`persona_registry_modules`). +pub struct MindResultsReporter { + registry: Arc, + /// The monitor's published snapshot: `shed_load` runs right after it is published, so this + /// is the poll that decided to shed. + pressure: watch::Receiver, + /// Saved copies proven at shed time; `budget()` reads only this. + proven: Mutex, +} + +impl MindResultsReporter { + pub fn new( + registry: Arc, + pressure: watch::Receiver, + ) -> Self { + Self { + registry, + pressure, + proven: Mutex::new(ProvenCopies::default()), + } + } +} + +impl MemoryReporter for MindResultsReporter { + fn name(&self) -> &'static str { + NAME + } + + /// It wants to keep everything it holds (`preferred = max = resident`); its floor is what no + /// shed may move yet: each mind's newest result, every unsaved body, and every body whose + /// copy is not proven. No filesystem access: proofs are made at shed time and cached. + fn budget(&self) -> MemoryBudgetSpec { + budget_of(&self.registry.resident_working_memories(), &self.proven) + } + + fn report(&self) -> ModuleMemoryReport { + let minds = self.registry.resident_working_memories(); + let bytes = resident_bytes(&minds); + ModuleMemoryReport { + name: NAME.to_string(), + bytes, + detail: format!( + "{} minds, {} KiB of resident result bodies", + minds.len(), + bytes / 1024 + ), + can_shed: true, + } + } + + fn can_shed(&self) -> bool { + true + } + + fn shed_load(&self, level: PressureLevel) { + let over = over_gate(&self.pressure.borrow()); + if over == 0 { + return; + } + let minds = self.registry.resident_working_memories(); + let before = resident_bytes(&minds); + shed_to(&minds, before.saturating_sub(over), &self.proven); + continuum_base::probe!( + class = "wm.results.shed", + level = %level, + over_gate = %over, + before = %before, + after = %resident_bytes(&minds), + "the memory owner moved the oldest resident results to their handles" + ); + } +} 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 052b4479a7..a08a874fdd 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 @@ -169,22 +169,24 @@ impl PersonaWorkspaceRegistry { /// private turns at the next turn boundary. `None` when she has no live cycle or template. pub fn mind_cycle(&self, persona_id: &Uuid) -> Option> { let live = self.get(persona_id)?; - let cached = self.mind_cycles.lock().get(persona_id).cloned(); + let cached = self.mind_cycles.lock().get(persona_id).map(|entry| Arc::clone(&entry.cycle)); let mind = match cached { Some(mind) => mind, None => { let _assembly = self.assembly.lock(); // Bound to its own statement: a guard in an `if let` scrutinee would live into // the `else` and deadlock on the insert below (non-reentrant lock). - let built_meanwhile = self.mind_cycles.lock().get(persona_id).cloned(); + let built_meanwhile = self.mind_cycles.lock().get(persona_id).map(|entry| Arc::clone(&entry.cycle)); if let Some(mind) = built_meanwhile { mind } else { let mut cfg = self.templates.lock().get(persona_id)?.clone(); cfg.defer_recall = false; - let (cycle, _working_memory) = assemble_workspace_cycle(cfg, None, Capture::Withheld); + let (cycle, working_memory) = assemble_workspace_cycle(cfg, None, Capture::Withheld); let cycle = Arc::new(cycle); - self.mind_cycles.lock().insert(*persona_id, Arc::clone(&cycle)); + self.mind_cycles + .lock() + .insert(*persona_id, ResidentWorkspace { cycle: Arc::clone(&cycle), working_memory }); cycle } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs index 9e657b1452..2219479f21 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs @@ -15,6 +15,7 @@ use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; mod she_is_told_when_her_hands_move_and_only_then; +mod mind_results_reporter; mod final_checkpoint_drains_admitted_periodic_writer_before_ack; use final_checkpoint_drains_admitted_periodic_writer_before_ack::*; mod gated_grounding; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs new file mode 100644 index 0000000000..7b783fcea1 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -0,0 +1,259 @@ +#![cfg(test)] +use std::sync::Arc; + +use uuid::Uuid; + +use crate::ai::types::ResultCustody; +use crate::cognition::persona_workspace::mind_results_reporter::{ + budget_of, over_gate, prove, resident_bytes, shed_to, LastCopy, Minds, ProvenCopies, +}; +use crate::cognition::tool_executor::spill::{self, LivePin}; +use crate::cognition::working_memory::WorkingMemory; +use parking_lot::Mutex; + +/// A test body's size in bytes; production has no such number (the memory owner sheds). +const BODY: usize = 1_000; + +fn body(name: &str) -> String { + format!("{name}{}", "b".repeat(BODY - name.len())) +} + +fn receipt(memory: &WorkingMemory, name: &str, custody: ResultCustody) { + memory.record_receipt_typed(&[], &body(name), None, custody); + // Distinct receipt times, so "oldest across minds" is the order they were received in. + std::thread::sleep(std::time::Duration::from_millis(2)); +} + +/// Record `name` saved for real through the spill owner; its handle. +fn kept(memory: &WorkingMemory, persona: Uuid, pin: &LivePin, name: &str) -> String { + let custody = pin.retain(persona, &body(name)); + let handle = custody.handle().expect("test: saved").to_owned(); + receipt(memory, name, custody); + handle +} + +fn saved(handle: &str) -> ResultCustody { + ResultCustody::Whole { + handle: handle.into(), + } +} + +/// Which of a mind's results are resident, by the name each body starts with. +fn resident(memory: &WorkingMemory) -> Vec { + memory + .snapshot() + .actions + .iter() + .filter_map(|r| r.result.as_ref().map(|body| body[..2].to_owned())) + .collect() +} + +// what this catches: a shed that moves the wrong bodies. It must take the OLDEST received +// across every mind (not each mind's oldest in turn), stop at the allocation, and never move a +// mind's newest result or an unsaved one. A moved body keeps its handle and its measured +// length, and its saved copy loads back to exactly what she read. +#[test] +fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { + let (pa, pb) = (Uuid::new_v4(), Uuid::new_v4()); + let pin = LivePin::new(); + let (a, b) = ( + Arc::new(WorkingMemory::new(8)), + Arc::new(WorkingMemory::new(8)), + ); + kept(&a, pa, &pin, "a1"); + receipt(&b, "b1", ResultCustody::Unsaved); + let b2 = kept(&b, pb, &pin, "b2"); + kept(&b, pb, &pin, "b3"); + kept(&a, pa, &pin, "a2"); + kept(&b, pb, &pin, "b4"); + kept(&a, pa, &pin, "a3"); + let minds: Minds = vec![(pa, Arc::clone(&a)), (pb, Arc::clone(&b))]; + let proven = Mutex::new(ProvenCopies::default()); + let total = resident_bytes(&minds); + assert_eq!(total, 7 * BODY as u64, "precondition: every body resident"); + + shed_to(&minds, total - 2 * BODY as u64, &proven); + assert_eq!( + resident_bytes(&minds), + 5 * BODY as u64, + "exactly down to the allocation" + ); + assert_eq!(resident(&a), ["a2", "a3"], "a1 was the oldest received"); + assert_eq!( + resident(&b), + ["b1", "b3", "b4"], + "b2 was next, before a2, though a2 is a's oldest left" + ); + let moved = b + .snapshot() + .actions + .into_iter() + .find(|r| r.handle.as_deref() == Some(b2.as_str())) + .expect("test: b2 kept its record"); + assert_eq!( + moved.stored_chars, + Some(BODY), + "a moved body keeps its measured length" + ); + assert_eq!( + spill::saved_whole(pb, &b2).expect("test: b2 loads"), + body("b2"), + "and loads back to what she read" + ); + + shed_to(&minds, 0, &proven); + assert_eq!(resident(&a), ["a3"], "a's newest stays"); + assert_eq!( + resident(&b), + ["b1", "b4"], + "unsaved and newest stay through any shed" + ); +} + +// what this catches (Codex and Cormac on #5595): a saved copy counted as safe because its FILE +// EXISTS. A file that is there but does not load back to the body (wrong content, a truncated +// write), or is gone, is not a copy: moving the body would lose the last one, and her view's +// load would render a pointer. Real files through the spill owner, never an injected verdict. +#[test] +fn a_copy_that_cannot_reproduce_the_body_keeps_it_resident() { + let persona = Uuid::new_v4(); + let pin = LivePin::new(); + let memory = Arc::new(WorkingMemory::new(8)); + let wrong = kept(&memory, persona, &pin, "c1"); + let truncated = kept(&memory, persona, &pin, "c2"); + let gone = kept(&memory, persona, &pin, "c3"); + kept(&memory, persona, &pin, "c4"); + kept(&memory, persona, &pin, "c5"); + let path = |handle: &str| spill::resolve(persona, handle).expect("test: path"); + std::fs::write(path(&wrong), "not what she read").expect("test: overwrite"); + std::fs::write(path(&truncated), &body("c2")[..BODY / 2]).expect("test: truncated write"); + std::fs::remove_file(path(&gone)).expect("test: remove"); + + let candidates = memory.resident_results().candidates; + let verdict = |handle: &str| { + let candidate = candidates + .iter() + .find(|c| c.handle == handle) + .expect("test: a candidate"); + prove(persona, &memory, candidate).expect("test: still resident") + }; + assert!( + matches!(verdict(&truncated), Err(LastCopy::Mismatch)), + "a truncated copy is a mismatch" + ); + assert_eq!( + verdict(&truncated).err().map(|e| e.reason()), + Some("mismatch"), + "the wm.results.last_copy_kept probe's reason" + ); + assert!(matches!(verdict(&wrong), Err(LastCopy::Mismatch))); + assert!( + matches!(verdict(&gone), Err(LastCopy::Unreadable(_))), + "a missing copy is unreadable" + ); + + let minds: Minds = vec![(persona, Arc::clone(&memory))]; + shed_to(&minds, 0, &Mutex::new(ProvenCopies::default())); + assert_eq!( + resident(&memory), + ["c1", "c2", "c3", "c5"], + "unprovable copies keep their bodies; c4 moved" + ); + assert_eq!(resident_bytes(&minds), 4 * BODY as u64); +} + +// what this catches (Cormac on #5595): `budget()` touching the filesystem. The monitor calls it +// under its reporters lock on every snapshot, so a stat per resident record ran inside the +// monitor. Proofs are made at shed time and cached; with the spill directory gone, budget() +// answers the same from the cache, and an unproven body counts as pinned. +#[test] +fn budget_answers_from_the_proof_cache_without_the_filesystem() { + let persona = Uuid::new_v4(); + let pin = LivePin::new(); + let memory = Arc::new(WorkingMemory::new(8)); + for name in ["d1", "d2", "d3", "d4"] { + kept(&memory, persona, &pin, name); + } + let minds: Minds = vec![(persona, Arc::clone(&memory))]; + let proven = Mutex::new(ProvenCopies::default()); + let unproven = budget_of(&minds, &proven); + assert_eq!( + (unproven.min_bytes, unproven.max_bytes), + (4 * BODY as u64, 4 * BODY as u64), + "nothing proven: all pinned" + ); + + shed_to(&minds, 3 * BODY as u64, &proven); + assert_eq!( + resident(&memory), + ["d2", "d3", "d4"], + "the oldest moved once proven" + ); + let handle = memory.resident_results().candidates[0].handle.clone(); + let dir = spill::resolve(persona, &handle) + .expect("test: path") + .parent() + .expect("test: dir") + .to_owned(); + std::fs::remove_dir_all(&dir).expect("test: remove the spill dir"); + let cached = budget_of(&minds, &proven); + assert_eq!(cached.max_bytes, 3 * BODY as u64); + assert_eq!( + cached.min_bytes, BODY as u64, + "d2 and d3 proven from the cache; only the newest pinned" + ); +} + +// what this catches: the memory owner reading a wrong total, so it sheds too little or too +// much. `report()` is the sum of resident body BYTES across every mind (not characters: a +// multi-byte body counts its bytes), and moves with every receipt and shed. +#[test] +fn report_sums_resident_bytes_across_minds() { + let (a, b) = ( + Arc::new(WorkingMemory::new(8)), + Arc::new(WorkingMemory::new(8)), + ); + let minds: Minds = vec![ + (Uuid::new_v4(), Arc::clone(&a)), + (Uuid::new_v4(), Arc::clone(&b)), + ]; + assert_eq!(resident_bytes(&minds), 0); + receipt(&a, "a1", saved("a1")); + receipt(&a, "a2", saved("a2")); + let wide = "é".repeat(BODY); + b.record_receipt_typed(&[], &wide, None, saved("b1")); + assert_eq!( + resident_bytes(&minds), + 2 * BODY as u64 + wide.len() as u64, + "bytes, not chars" + ); + assert_eq!( + resident_bytes(&minds), + a.resident_result_bytes() + b.resident_result_bytes() + ); +} + +// what this catches: a shed target of our own invention. The bytes shed are how far the host's +// used RAM stands past the monitor's own gate for this priority; nothing before the first poll. +#[test] +fn the_shed_target_is_the_hosts_overrun_past_the_monitors_gate() { + use continuum_kernel::system_resources::{MemoryPriority, PressureSnapshot}; + assert_eq!( + over_gate(&PressureSnapshot::default()), + 0, + "no poll yet: nothing to shed" + ); + let total = 100 * 1024 * 1024 * 1024u64; + let gate = (total as f64 * MemoryPriority::Interactive.pressure_gate()) as u64; + let snapshot = |used: u64| PressureSnapshot { + total_bytes: total, + available_bytes: total - used, + ..Default::default() + }; + assert_eq!(over_gate(&snapshot(gate)), 0, "at the gate: nothing"); + assert_eq!( + over_gate(&snapshot(gate + 5 * BODY as u64)), + 5 * BODY as u64, + "past it: exactly the overrun" + ); +} 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 b778f624fc..7af2838e13 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 @@ -191,13 +191,14 @@ use super::*; { let memory = WorkingMemory::new(8); memory.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + 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")); for _ in 0..4 { memory.record_receipt_typed(&[], &"s".repeat(cap / 2), None, saved("5000000000000002")); } memory.record_settlement("done", None); + memory.evict_resident_results_over(0, &|_, _| true); let persisted = PersistedVolatile { wm: memory.snapshot(), own_speech: OwnSpeechPersisted::ByRoom(Vec::new()), diff --git a/core/continuum-cognition/src/cognition/tool_executor/spill.rs b/core/continuum-cognition/src/cognition/tool_executor/spill.rs index d3fb04d9ad..27fb521633 100644 --- a/core/continuum-cognition/src/cognition/tool_executor/spill.rs +++ b/core/continuum-cognition/src/cognition/tool_executor/spill.rs @@ -326,6 +326,21 @@ pub fn resolve(persona_id: Uuid, handle: &str) -> std::io::Result { resolve_in(&spill_root()?, persona_id, handle) } +/// THE read of a saved result as her view loads it back: the saved output, trimmed as the +/// record keeps its result (`record_receipt_inner`). Her view's `load` and the memory owner's +/// proof ([`reproduces`]) both read through here, so "verified" means "loads back to this text". +pub fn saved_whole(persona_id: Uuid, handle: &str) -> std::io::Result { + let text = fs::read_to_string(resolve(persona_id, handle)?)?; + Ok(text.trim().to_owned()) +} + +/// Whether `persona_id`'s saved output for `handle` loads back ([`saved_whole`]) to exactly +/// `body`: the proof that the copy can stand in for a body leaving RAM. `Err` when it cannot be +/// read back at all. +pub fn reproduces(persona_id: Uuid, handle: &str, body: &str) -> std::io::Result { + Ok(saved_whole(persona_id, handle)? == body) +} + // ── root-injected cores (the filesystem seam; unit-tested against a tempdir so // tests never pollute ~/.continuum — the isolation lesson of task #7) ────── diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 5f4601e048..3aefa0de79 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -558,6 +558,7 @@ impl VolatileSnapshot { written_pointer: None, summary: None, stored_chars: None, + received_ms: None, }; let mut records: BTreeMap = BTreeMap::new(); let mut unkeyed = 0usize; @@ -713,12 +714,12 @@ mod continuity; mod faculty; mod ledger; mod perception; +mod residency; pub use faculty::WorkingMemoryFaculty; pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; -#[cfg(test)] -pub(crate) use perception::RESULTS_RESIDENT_CHARS; +pub(crate) use residency::{ResidentResults, ShedCandidate}; impl Drop for WorkingMemory { /// A mind that is gone points at nothing: its saved results may be evicted again. 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 5e8990ac72..e91fdf3793 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -11,8 +11,9 @@ use std::collections::{HashSet, VecDeque}; use uuid::Uuid; -/// How many collapsed results keep their pointer (and their saved whole) reachable. The -/// bound the collapsed-pointer index already had; the ledger line outlives it. +/// How many collapsed results the legacy results ring lists as pointer lines (and the +/// checkpoint's rollback shape carries). A rendering count only: every record that names a +/// handle keeps it live and stays in the log (`receipt_keys`, `prune`). const POINTER_INDEX: usize = 12; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -47,6 +48,12 @@ pub(crate) struct ActionRecord { /// before this was kept (their whole then has no price: they show at pointer level). #[serde(default, skip_serializing_if = "Option::is_none")] pub stored_chars: Option, + /// When the result was received (ms since the Unix epoch): the one clock that orders every + /// mind's resident results oldest-first when the memory owner sheds across minds. `None` + /// for a record from a build before this was kept, which sheds first (it is older than any + /// result received since). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub received_ms: Option, } impl ActionRecord { @@ -56,15 +63,17 @@ impl ActionRecord { super::receipt_key(self.seq, self.handle.as_deref()) } - fn result_chars(&self) -> usize { - self.result.as_ref().map_or(0, |result| result.chars().count() + 1) + /// The RAM its resident body holds, in bytes: what the memory owner accounts, never a + /// character count (that is `stored_chars`, the view's price). + pub fn resident_bytes(&self) -> u64 { + self.result.as_ref().map_or(0, |result| result.len() as u64) } } /// What a collapse left behind. pub(super) struct Collapsed { - /// Characters still retained in full. - pub total: usize, + /// Bytes still resident. + pub total: u64, } #[derive(Debug, Default)] @@ -132,45 +141,70 @@ impl ActionLog { } /// Every receipt whose dependencies must stay reachable: each retained result's key and - /// each indexed pointer's handle. + /// 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. pub fn receipt_keys(&self) -> HashSet { - self.retained().chain(self.indexed_pointers()).map(ActionRecord::receipt_key).collect() + self.records + .iter() + .filter(|record| record.result.is_some() || record.handle.is_some()) + .map(ActionRecord::receipt_key) + .collect() + } + + /// The RAM every resident body holds, in bytes. + pub fn resident_bytes(&self) -> u64 { + self.records.iter().map(ActionRecord::resident_bytes).sum() + } + + /// The records a shed may move to their handles, oldest first: resident, saved, not the + /// newest result, and vouched for by `saved(seq, handle)` (its saved copy was proven to load + /// back to this body). Everything else is the last copy of what she read, so it stays. + pub fn evictable<'a>( + &'a self, + saved: &'a dyn Fn(u64, &str) -> bool, + ) -> impl Iterator + 'a { + let newest = self.retained().last().map(|record| record.seq); + self.records.iter().filter(move |record| { + record.result.is_some() + && Some(record.seq) != newest + && record.handle.as_deref().is_some_and(|handle| saved(record.seq, handle)) + }) } - /// Collapse the oldest saved results to their handles once the retained results exceed - /// `cap`, down to half of it, so the head of what she reads stays byte-stable between two - /// bursts. The newest result always stays, and an unsaved one stays whole. - pub fn collapse_over(&mut self, cap: usize) -> Collapsed { - let mut total: usize = self.records.iter().map(ActionRecord::result_chars).sum(); - if total <= cap { + /// Move the oldest evictable bodies to their handles until at most `budget` bytes stay + /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view + /// still prices and reloads its whole. Exactly to the budget: the memory owner decides + /// when, so there is no hysteresis here. + pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str) -> bool) -> Collapsed { + let mut total = self.resident_bytes(); + if total <= budget { return Collapsed { total }; } - let target = cap / 2; - let newest = self.retained().last().map(|record| record.seq); - for record in self.records.iter_mut() { - if total <= target { - break; - } - if record.result.is_none() || record.handle.is_none() || Some(record.seq) == newest { - continue; - } - total -= record.result_chars(); + let chosen: HashSet = { + let mut over = total - budget; + self.evictable(saved) + .take_while(|record| { + let take = over > 0; + over = over.saturating_sub(record.resident_bytes()); + take + }) + .map(|record| record.seq) + .collect() + }; + for record in self.records.iter_mut().filter(|record| chosen.contains(&record.seq)) { + total -= record.resident_bytes(); record.stored_chars = record.result.as_ref().map(|result| result.chars().count()); record.result = None; } Collapsed { total } } - /// Drop the records nothing shows any more: past the ledger's share, collapsed, and - /// no longer indexed as a pointer. + /// 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) - .chain(self.indexed_pointers()) - .map(|record| record.seq) - .collect(); - self.records.retain(|record| record.result.is_some() || keep.contains(&record.seq)); + 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 a40b0abcde..1947e8cbea 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -307,10 +307,9 @@ impl WorkingMemory { *self.receipt_children.lock() = snap.receipt_children; *self.view.lock() = snap.context_view; *self.open_views.lock() = super::super::open_views::OpenViews::from_saved(snap.open_views); - // Restored bodies are bound by the storage budget, never the window: a floor here once - // folded results the served window held (cap 1,536 at restore on the 5090, card - // df0035bf), and now nothing about the window decides what she sees (FLOW §2d). - self.evict_resident_results(); + // Restored bodies stay resident until the memory owner sheds: neither the window (a + // floor here once folded what the served window held, card df0035bf; FLOW §2d) nor a + // size cap decides at restore. self.publish_live_handles(); { let mut f = self.action_fps.lock(); diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 5bd6fe9dea..253e6b9c94 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -295,8 +295,8 @@ impl WorkingMemory { // wall_source.rs 25+ times in four hours and landed no edit because every earlier // read reached her next turn as its last ~2,100 chars (Joel: "the clipping I've // yelled about for months"). The producer already fitted it (whole, or its - // handle: `spill::LivePin::whole_or_handle`); the budget decides how many of these units - // fit (`recent_results_chars`) and the rest collapse to pointers at settlement. + // handle: `spill::LivePin::whole_or_handle`); her view decides how much of each she + // sees, and the memory owner's shed alone moves a body to its handle (`residency`). { let tail = a.to_string(); // A receipt can contain several operations. Retain their typed names @@ -335,21 +335,14 @@ impl WorkingMemory { handle, written_pointer: None, stored_chars: None, + received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, budget.receipt_archive_chars(), ); } - // The ring's share is enforced HERE, at every receipt, with hysteresis: nothing - // moves until the share is exceeded, then the oldest collapse to pointers down to - // half of it, so the prefix ahead of the newest entries is byte-stable for the whole - // run between two bursts. History: eviction on every act past ~3 (2026-08-24) rotated - // the head each act, and on a KV that cannot shift (`kv_shiftable = Some(false)`, - // "cache_reuse is not supported by this context") re-prefilled everything after it; - // the cap was then moved to settlement only. A coding turn is 100+ acts between - // settlements: on the M5 (2026-10-16) the rings persisted at 213 results / 686k - // chars, 155 / 1.09M, 123 / 442k, 49 / 138k, and fit_messages was the only bound. - // Now a storage budget (FOCUS rule 7): bodies leave RAM, never her view. - self.evict_resident_results(); + // 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 diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index ccd313e9cd..8ea1ce91ce 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -2,14 +2,6 @@ use super::*; -/// The RAM her results' bodies may hold, in characters: a storage budget, not a view size -/// (FOCUS-CONTRACT rule 7). Past it the oldest saved bodies move to their handles on disk and -/// stay visible at every level. -// derived-or-floor: floor. Storage only: past it a body is one local file read away when her view -// grants it whole. About 2 MiB per mind at the 2-byte char upper bound, sized above the largest -// ring measured (1.09M chars on a coding turn, 2026-10-16), so eviction is rare. -pub(crate) const RESULTS_RESIDENT_CHARS: usize = 1 << 20; - /// One act as her view renders it: seq, full, summary, pointer, and its stored whole (rendered /// chars, handle) when its body is not resident. pub(crate) type ActRendering = (u64, String, Option, String, Option<(usize, String)>); @@ -233,8 +225,8 @@ impl WorkingMemory { /// rides whole as the newest message of the turn); the flag says whether there is one. /// Each act as her view's actions source renders it: (seq, full, summary, pointer, stored). /// `stored` is the whole's rendered length and handle once its body left RAM for its - /// handle (`evict_resident_results`): `full` is then the pointer, and the view prices and - /// loads the whole through the source (`continuum_context::StoredWhole`). + /// handle (`evict_resident_results_over`, the memory owner's shed): `full` is then the + /// pointer, and the view prices and loads the whole through the source (`continuum_context::StoredWhole`). pub(crate) fn action_renderings(&self) -> (Vec, bool) { let active = self.in_flight_action_seq(); let actions = self.actions.lock(); @@ -308,11 +300,11 @@ impl WorkingMemory { "Recent results of your own actions (oldest first; #n matches the action ledger):" .to_string(), None, )); - // Every eligible result rides as a message of its own: the ring's RAM is bounded at - // receipt by its storage budget (`evict_resident_results`), never by a count here. + // Every eligible result rides as a message of its own: the ring's RAM is bounded by the + // one memory owner's shed (`residency`), never by a count here. // A count fold ("newest 16 as messages, the rest as index lines", 2026-10-16) rotated // the head on EVERY act, which on a KV that cannot shift re-prefilled everything - // after it; the chars cap with hysteresis rotates once per burst. + // after it; a shed happens only when RAM is short, so between sheds the ring appends. out.extend(actions.retained().filter(eligible).filter_map(|record| { let result = record.result.as_deref()?; let attribution = ResultAttribution::of(record); @@ -418,31 +410,6 @@ impl WorkingMemory { crate::cognition::tool_executor::spill::publish_live_handles(self.instance, handles); } - /// Bound the RAM her results' bodies hold (FOCUS-CONTRACT rule 7: a storage budget, never - /// what she sees). Past [`RESULTS_RESIDENT_CHARS`] the oldest saved bodies leave RAM for their - /// handles, down to half of it (hysteresis: nothing moves until the budget is passed). Each - /// keeps its measured length, so her view still prices its whole level and loads it when - /// the allocation grants it (`continuum_context::StoredWhole`, the actions source's `load`). - /// The newest result always stays; an unsaved result stays whole (no handle could reload - /// it). The window plays no part: it once did (`recent_results_chars`), and then this - /// decided what she read before her view saw her claims (FLOW §2d). - pub(super) fn evict_resident_results(&self) { - self.evict_resident_results_over(RESULTS_RESIDENT_CHARS); - } - - pub(crate) fn evict_resident_results_over(&self, budget: usize) { - let total = self.actions.lock().collapse_over(budget).total; - self.publish_live_handles(); - if total > budget { - continuum_base::probe!( - class = "wm.results.unsaved_over_storage", - total = %total, - budget = %budget, - "results whose save failed stay resident over the storage budget" - ); - } - } - /// Record that the persona SETTLED — produced an utterance and closed the current /// concern. Pushes a [`WM_SETTLEMENT_PREFIX`]-marked boundary into the same rolling /// buffer (honest proprioception: "I already answered X", perceivable by the mind @@ -451,9 +418,6 @@ impl WorkingMemory { /// legitimate re-use of the same tool for a genuinely NEW concern after an answer. /// Blank is ignored. Oldest ages out past capacity, same rolling scratchpad. pub fn record_settlement(&self, answer_head: &str, room: Option) { - // Deferred ring hygiene: the settle just closed, the next prompt - // re-prefills regardless — collapse over-cap results NOW, never mid-settle. - self.evict_resident_results(); let a = answer_head.trim(); let scope = self.scope.lock().clone(); // Existing authored-settlement boundary, not proof the task was completed. diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs new file mode 100644 index 0000000000..80aa89067b --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -0,0 +1,94 @@ +//! What of her results' bodies stays in RAM: the one memory owner decides. +//! +//! A result's body stays resident until the memory pressure monitor asks the mind-results +//! reporter to shed (`persona_workspace::mind_results_reporter`), never by a size cap at +//! receipt or restore: RAM decides, not a number (Joel, 2026-10-29). A shed moves the oldest +//! saved bodies to their handles; each keeps its measured length, so her view still prices its +//! whole level and loads it when the allocation grants it (FOCUS-CONTRACT rule 7, +//! `continuum_context::StoredWhole`). The newest result always stays, and so does any body +//! whose saved output is not there to reload: it is the last copy. + +use super::*; + +/// One resident body a shed may move to its handle, if its saved output is there to reload +/// (the caller checks that outside her lock). +#[derive(Debug, Clone)] +pub(crate) struct ShedCandidate { + /// When it was received; `None` (an older build's record) sheds first. + pub received_ms: Option, + pub seq: u64, + pub handle: String, + pub bytes: u64, +} + +/// One mind's resident result bodies, read under her lock with no filesystem access. +#[derive(Debug, Clone)] +pub(crate) struct ResidentResults { + /// Bytes of every resident body. + pub resident_bytes: u64, + /// Saved bodies other than the newest, oldest first: what a shed may move once each + /// candidate's output is vouched for. + pub candidates: Vec, +} + +impl WorkingMemory { + /// The RAM her resident result bodies hold, in bytes. Cheap: one pass, no allocation. + pub(crate) fn resident_result_bytes(&self) -> u64 { + self.actions.lock().resident_bytes() + } + + /// Her resident bodies and the saved ones a shed could move. Only memory is read under the + /// lock: whether each handle's output is there is the caller's check, made after it drops. + pub(crate) fn resident_results(&self) -> ResidentResults { + let actions = self.actions.lock(); + let candidates = actions + .evictable(&|_, _| true) + .filter_map(|record| { + Some(ShedCandidate { + received_ms: record.received_ms, + seq: record.seq, + handle: record.handle.clone()?, + bytes: record.resident_bytes(), + }) + }) + .collect(); + ResidentResults { + resident_bytes: actions.resident_bytes(), + candidates, + } + } + + /// A copy of one resident body, if its record still names `handle`: what the memory owner + /// proves its saved copy against, outside the lock (the lock is held only for the copy). + pub(crate) fn resident_body(&self, seq: u64, handle: &str) -> Option { + let actions = self.actions.lock(); + let record = actions.get(seq)?; + if record.handle.as_deref() != Some(handle) { + return None; + } + record.result.clone() + } + + /// THE eviction verb: move the oldest saved bodies to their handles until at most `budget` + /// bytes stay resident. Only the memory owner's shed calls it in production, with + /// `saved(seq, handle)` answering from the copies it proved outside the lock, so a record + /// that changed since (a different handle, or gone) is not moved. No filesystem access + /// happens under the lock. The newest stays, and + /// past the budget after that the overrun is reported, never forced. + pub(crate) fn evict_resident_results_over( + &self, + budget: u64, + saved: &dyn Fn(u64, &str) -> bool, + ) { + let total = self.actions.lock().collapse_over(budget, saved).total; + self.publish_live_handles(); + if total > budget { + continuum_base::probe!( + class = "wm.results.last_copies_over_allocation", + total = %total, + budget = %budget, + "results with no saved output to reload stay resident over the shed's allocation" + ); + } + } +} 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 41f34d02b5..4521544006 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 @@ -10,13 +10,14 @@ use super::*; 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 = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + 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")); 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 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 ring = wm.recent_results_messages().join("\n"); @@ -58,12 +59,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { wm.set_served_window(16_384); wm.set_scope(Some("/work/foo".into())); let room = Uuid::new_v4(); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), Some(room), saved("first-handle")); for act in 2..=5 { wm.record_receipt_typed(&[], &format!("act {act}\n{}", "s".repeat(cap / 2)), Some(room), saved("ring-test")); } wm.record_settlement("done", None); + shed(&wm, cap / 2); // The pointer index and the ledger. (Which act counts as in flight after a restore is // the restore's own rule, unchanged here, so the retained results are not compared.) let pointers = |memory: &WorkingMemory| -> Vec { @@ -85,12 +87,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + 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")); 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 bd9779eb92..52f119b7ca 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -53,11 +53,11 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ "{back:?}" ); // Result custody must obey the same scope even after entry-trail eviction, - // settlement collapse and checkpoint restoration. Storage remains intact. + // 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(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); + let body_a = format!("task-a-only {}", "a".repeat(BODY)); results.record_receipt_typed(&[], &body_a, None, saved("scope-a-output")); let original = results.last_action_full(); results.set_scope(Some("task-b".into())); @@ -73,6 +73,7 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ assert!(results.active_action_full().is_none(), "B stays stored but inactive in A"); results.set_scope(Some("task-b".into())); 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"); @@ -118,13 +119,14 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { 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 = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[], &"a".repeat(cap / 2), None, saved(&handle)); assert!(live(&file), "referenced by the ring"); for _ in 0..4 { record_saved(&wm, &"s".repeat(cap / 2)); } wm.record_settlement("done", None); + shed(&wm, cap / 2); assert!( wm.recent_results_messages().join("\n").contains(&format!("{handle} — collapsed")), "it collapsed to a pointer" @@ -134,6 +136,54 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { assert!(!live(&file), "released when the mind drops"); } +// what this catches: a body moved to disk losing its last copy. Liveness (and the log itself) +// once covered only the newest 12 collapsed pointers (`POINTER_INDEX`), so a shed that moved +// many bodies left the older handles evictable under disk pressure while her view still priced +// their wholes. Every record that names a handle keeps it live, however many pointers are newer. +#[test] +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 { + record_receipt_with(&wm, &handle()); + } + shed(&wm, 0); + for _ in 0..30 { + record_receipt_with(&wm, &handle()); + } + shed(&wm, 0); + assert!(live(&first), "the oldest moved body's handle is still protected"); + let (acts, _) = wm.action_renderings(); + let oldest = acts.first().expect("test: the first act"); + assert_eq!(oldest.4.as_ref().map(|(_, h)| h.as_str()), Some(first.as_str()), "its record stays, priced and reloadable"); + drop(wm); + assert!(!live(&first), "released when the mind drops"); +} + +fn record_receipt_with(wm: &WorkingMemory, handle: &str) { + wm.record_receipt_typed(&[], &format!("{handle} {}", "s".repeat(BODY)), None, saved(handle)); +} + +// what this catches: a shed moving a record it never checked. The memory owner vouches for each +// saved output outside her lock, then evicts by `(seq, handle)`; a record that no longer names +// the vouched handle stays resident. +#[test] +fn a_shed_moves_only_the_records_it_vouched_for() { + let wm = WorkingMemory::new(8); + wm.record_receipt_typed(&[], &"a".repeat(BODY), None, saved("vouched-a")); + wm.record_receipt_typed(&[], &"b".repeat(BODY), None, saved("vouched-b")); + wm.record_receipt_typed(&[], "newest", None, saved("vouched-c")); + let seq_of = |h: &str| wm.snapshot().actions.iter().find(|r| r.handle.as_deref() == Some(h)).map(|r| r.seq).expect("test: seq"); + let (a, b) = (seq_of("vouched-a"), seq_of("vouched-b")); + wm.evict_resident_results_over(0, &|seq, handle| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); + let resident: Vec<_> = wm.snapshot().actions.into_iter().filter(|r| r.result.is_some()).filter_map(|r| r.handle).collect(); + assert_eq!(resident, ["vouched-a", "vouched-c"], "a changed since it was vouched for; only b moved"); +} + // what this catches (Codex on #4987): per-call results reachable only while the ENTRY that // carried their acts survives. Entries roll over at capacity while the receipt that points // at those results stays in the ring, then collapses to a pointer, then is checkpointed and @@ -166,7 +216,7 @@ 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 = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + 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 { record_saved(&wm, &"s".repeat(cap / 2)); @@ -175,6 +225,7 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { assert!(children.iter().all(|c| live(c)), "the receipt still holds its children"); wm.record_settlement("done", None); + shed(&wm, cap / 2); assert!(wm.recent_results_messages().join("\n").contains(&format!("{receipt} — collapsed")), "collapsed to a pointer"); assert!(live(&receipt) && children.iter().all(|c| live(c)), "the pointer holds the receipt and its children"); @@ -274,22 +325,16 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { } // what this catches (BigMama's live receipt of #4963 on the 5090, card df0035bf; FLOW §2d): -// restore folding what she sees by a window. Restore once collapsed against the floor budget -// before her window was known (a 1,536-char share), and later against the window itself. The -// ring's bound is now a storage budget (`RESULTS_RESIDENT_CHARS`): the window plays no part, so -// restoring with no window or a small one keeps exactly what the snapshot held. +// restore folding what she sees by a window or a size. Restore once collapsed against the floor +// budget before her window was known (a 1,536-char share), later against the window itself, and +// then against a size cap of ours (`RESULTS_RESIDENT_CHARS`). Only the memory owner sheds now, so +// restoring with no window or a small one keeps every body the snapshot held resident. #[test] -fn restore_bounds_results_by_storage_never_by_window() { - let budget = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; +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(budget / 3)), - None, - saved(&format!("restore-{i}")), - ); + source.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(64 * BODY)), None, saved(&format!("restore-{i}"))); } let snapshot = source.snapshot(); let entries = |wm: &WorkingMemory| { @@ -298,63 +343,53 @@ fn restore_bounds_results_by_storage_never_by_window() { let held = entries(&source); let unknown = WorkingMemory::new(8); unknown.restore(snapshot.clone()); - assert_eq!(entries(&unknown), held, "no window yet: the storage budget alone bounds it"); + 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"); } -// what this catches: the ring growing without bound between settlements. The share was -// enforced at settlement only, and a coding turn is 100+ acts between settlements (the M5, -// 2026-10-16: 1.09M chars of results persisted for one mind). At every receipt the ring is -// within its share, the newest result is whole, and eviction is a BURST with hysteresis: -// between bursts the ring only appends, so the prefix ahead of it stays byte-stable. +// what this catches: a size cap of ours deciding what RAM holds (`RESULTS_RESIDENT_CHARS = +// 1 << 20` evicted every mind's oldest bodies at receipt, settlement and restore; Joel +// 2026-10-29: no hand-rigged constants). However large the ring grows, receipts and +// settlements move nothing to its handle: only the memory owner's shed does. #[test] -fn the_ring_holds_its_share_at_every_receipt_and_evicts_in_bursts() { +fn results_are_never_evicted_at_receipt_however_large_the_ring() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let share = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; - let chunk = share / 5; - let rendered = |wm: &WorkingMemory| -> Vec { - wm.recent_results_messages().into_iter().filter(|m| m.starts_with("[result ")).collect() - }; - let mut bursts = 0; - let mut head: Option = None; + let chunk = 64 * BODY; for i in 0..40 { - wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("burst-{i}"))); - let ring = rendered(&wm); - let chars: usize = ring.iter().map(|m| m.chars().count()).sum(); - assert!(chars <= share + 2_048, "receipt {i}: {chars} rendered chars over the {share} share"); - let now = ring.first().cloned(); - if head.is_some() && now != head { - bursts += 1; + wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("ring-{i}"))); + if i % 10 == 9 { + wm.record_settlement("a burst done", None); } - head = now; } - assert!(bursts >= 1, "the share was exceeded, so at least one burst evicted"); - assert!(bursts < 20, "a burst with hysteresis, not a rotation on every act: {bursts} bursts in 40 receipts"); - let newest = wm.snapshot().recent_results.last().map(|r| r.2.clone()).unwrap_or_default(); - assert!(newest.starts_with("r39 ") && newest.len() > chunk, "the newest result is held whole"); + 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"); } // what this catches: an unsaved result dropped at collapse (Astra on #4963 at 4840af859: // a pointer saying "never saved" documents the loss instead of preventing it). Its save -// failed, so nothing else holds its bytes: it stays WHOLE through settlement and restore -// while the saved results around it collapse to pointers. +// failed, so nothing else holds its bytes: it stays WHOLE through a shed and restore while +// the saved results around it collapse to pointers. #[test] -fn an_unsaved_result_keeps_its_bytes_through_settlement_and_restore() { +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 = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; let unsaved = format!("UNSAVED {}", "u".repeat(cap / 2)); wm.record_receipt_typed(&[], &unsaved, None, crate::ai::types::ResultCustody::Unsaved); for _ in 0..4 { record_saved(&wm, &"s".repeat(cap / 2)); } wm.record_settlement("done", None); + shed(&wm, cap / 2); let whole = |m: &WorkingMemory| m.recent_results_messages().iter().any(|r| r.ends_with(&unsaved)); - assert!(whole(&wm), "kept whole through settlement"); + assert!(whole(&wm), "kept whole through the shed"); assert!( wm.recent_results_messages().join("\n").contains("ring-test — collapsed"), "the saved ones around it collapsed" @@ -378,7 +413,7 @@ fn a_restore_prices_a_legacy_evicted_result_from_its_saved_output() { wm.record_receipt_typed(&[], &body, None, pin.retain(persona, &body)); wm.record_receipt_typed(&[], "a result whose output is gone", None, pin.retain(persona, "a result whose output is gone")); wm.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); - wm.evict_resident_results_over(1); + shed(&wm, 1); let mut snapshot = wm.snapshot(); snapshot.actions = snapshot.action_records(); // the shape the old share left: body gone, handle kept, no stored size 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 6ddc61bcf7..b834ea390b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -21,3 +21,13 @@ fn saved(handle: &str) -> crate::ai::types::ResultCustody { fn record_saved(wm: &WorkingMemory, text: &str) { wm.record_receipt_typed(&[], text, None, saved("ring-test")); } + +/// A test body's size in bytes: big enough that a shed below a few of them is visible. The +/// size is the test's choice; production has no such number (the memory owner sheds). +const BODY: usize = 4_096; + +/// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, +/// with every handle's saved output vouched for. +fn shed(wm: &WorkingMemory, budget: usize) { + wm.evict_resident_results_over(budget as u64, &|_, _| true); +} 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 8e864490f9..536ceedf1d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -202,12 +202,13 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { wm.full_result_message(seq, &full) ); - // Actual settlement collapses old results; its pointers must still tell + // A shed collapses old results; its pointers must still tell // the mind which activity and operation the retained handle belongs to. for _ in 0..4 { - record_saved(&restored, &"x".repeat(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); + record_saved(&restored, &"x".repeat(BODY)); } restored.record_settlement("reported", None); + shed(&restored, 0); assert!(restored.recent_results_messages().join("\n").contains( &format!("[result #1; room {room_a}; operation code/search, code/read; output handle: tool/output search-output — collapsed]") )); 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 266d941e3e..18128e6eb7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -11,8 +11,7 @@ use super::*; #[test] fn recent_results_survive_subsequent_acts_and_stay_bounded() { let wm = WorkingMemory::new(8); - // A known window: the receipt-time collapse folds nothing against an unknown one - // (the act→observe seam pins the served window before any receipt in production). + // 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"); @@ -22,17 +21,13 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { block.contains("E0601"), "the compile error must survive later trivial acts: {block}" ); - // PREMISE (2026-10-16, the third premise): the share is enforced at EVERY receipt, - // in a BURST with hysteresis. 2026-08-24 moved it to settlement because per-act - // eviction rotated the head on every act; a coding turn then held 100+ results - // between settlements (the M5: 1.09M chars persisted for one mind). So: flooding - // past the share collapses the OLDEST to pointers once, down to half the share… - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; - // Whole results an eighth of the share each, so several fit and the collapse is visible. - let unit = (cap / 8).max(1); + // A shed (only the memory owner's, under pressure) collapses the OLDEST to pointers, + // and every result still shown is shown whole. + let unit = BODY; for _ in 0..8 { record_saved(&wm, &"x".repeat(unit)); } + shed(&wm, 4 * unit); let messages = wm.recent_results_messages(); let kept: Vec<&String> = messages.iter().filter(|m| m.starts_with("[result ")).collect(); assert!(!kept.is_empty(), "the newest results stay"); @@ -43,18 +38,11 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { assert!(messages.iter().any(|m| m.contains("collapsed")), "the rest are pointers"); assert!( !messages.join("\n").contains("E0601"), - "the oldest collapse to pointers once the share is exceeded — bounded, not immortal" - ); - // …in ONE CHUNK: the collapse lands at half the cap so the surviving head - // stays byte-identical across the next receipts and settles (the KV divergence - // audit, 2026-09-13: the oldest surviving result was the first differing block in - // 28 of 55 consecutive turns under one-entry-per-settle eviction). - let total: usize = kept.len() * unit; - assert!( - total <= cap / 2 + unit, - "an over-cap collapse lands at half the cap, not at the cap: {total} > {}", - cap / 2 + "the oldest collapse to pointers once shed — bounded, not immortal" ); + assert!(wm.resident_result_bytes() <= 4 * unit as u64, "down to the allocation: {}", wm.resident_result_bytes()); + // Between sheds the ring only appends: receipts and settles move nothing, so the head + // stays byte-identical (the KV divergence audit, 2026-09-13). let head_after_collapse = wm.recent_results_messages().get(1).cloned(); record_saved(&wm, "[action] code/read(a.rs) fine"); wm.record_settlement("one", None); @@ -63,7 +51,7 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { assert_eq!( wm.recent_results_messages().get(1).cloned(), head_after_collapse, - "the ledger head is byte-stable across receipts and settles that fit under the cap" + "the ledger head is byte-stable across receipts and settles between sheds" ); } diff --git a/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs b/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs index 46d9a6d29a..c741aedb7f 100644 --- a/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs +++ b/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs @@ -98,6 +98,12 @@ pub(super) fn register_persona_registry_modules( crate::cognition::channel_substrate::global_channel_digest_buffer(), ), ); + // Every mind's resident result bodies answer to the one memory owner: they stay in RAM + // until the monitor sheds, never a size cap of ours (Joel, 2026-10-29). + pressure_monitor.add_reporter(Arc::new(crate::cognition::persona_workspace::MindResultsReporter::new( + crate::cognition::persona_workspace::global(), + pressure_monitor.subscribe(), + ))); // The dream/consolidation region goes LIVE (#145 slice B): per live persona, // on a material-driven cadence (dreams only when undigested episodic // experience accrues, `CadenceHint::Sleep` otherwise), it distills episodic