diff --git a/Cargo.lock b/Cargo.lock index 4057b775f2..92d34b3e8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2761,6 +2761,7 @@ dependencies = [ "continuum-memory", "continuum-perception", "continuum-positron", + "continuum-process", "dashmap", "dirs 5.0.1", "fs2", @@ -2787,7 +2788,6 @@ dependencies = [ "tracing", "ts-rs 12.0.1", "uuid", - "continuum-process", ] [[package]] @@ -3023,6 +3023,7 @@ dependencies = [ "continuum-orm-derive", "continuum-perception", "continuum-positron", + "continuum-process", "continuum-sentinel", "continuum-service", "continuum-serving", @@ -3093,7 +3094,6 @@ dependencies = [ "wide", "windows-sys 0.60.2", "zip 0.6.6", - "continuum-process", ] [[package]] @@ -3147,7 +3147,6 @@ dependencies = [ name = "continuum-engine" version = "0.1.0" dependencies = [ - "continuum-process", "airc-core", "airc-lib", "airc-protocol", @@ -3162,6 +3161,7 @@ dependencies = [ "continuum-cli-lifecycle", "continuum-host", "continuum-kernel", + "continuum-process", "continuum-service", "continuum-tool-protocol", "dashmap", @@ -3246,6 +3246,7 @@ dependencies = [ "continuum-engine", "continuum-host", "continuum-kernel", + "continuum-process", "dashmap", "futures", "inventory", @@ -3261,7 +3262,6 @@ dependencies = [ "tracing", "ts-rs 12.0.1", "uuid", - "continuum-process", ] [[package]] @@ -3284,6 +3284,7 @@ dependencies = [ "continuum-engine", "continuum-kernel", "continuum-mind", + "continuum-process", "continuum-service", "dashmap", "futures", @@ -3298,7 +3299,6 @@ dependencies = [ "tracing", "ts-rs 12.0.1", "uuid", - "continuum-process", ] [[package]] @@ -3322,7 +3322,6 @@ dependencies = [ name = "continuum-hands" version = "0.1.0" dependencies = [ - "continuum-process", "airc-core", "airc-lib", "airc-work", @@ -3331,6 +3330,7 @@ dependencies = [ "continuum-engine", "continuum-git", "continuum-kernel", + "continuum-process", "dashmap", "futures", "ignore", @@ -3522,6 +3522,7 @@ dependencies = [ "continuum-memory", "continuum-perception", "continuum-positron", + "continuum-process", "continuum-rooms", "continuum-store", "continuum-text-analysis", @@ -3550,7 +3551,6 @@ dependencies = [ "tracing", "ts-rs 12.0.1", "uuid", - "continuum-process", ] [[package]] @@ -3675,12 +3675,12 @@ dependencies = [ name = "continuum-sentinel" version = "0.1.0" dependencies = [ - "continuum-process", "async-trait", "chrono", "continuum-base", "continuum-engine", "continuum-kernel", + "continuum-process", "dashmap", "futures", "futures-util", diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 99d4c371fd..fcc6ece6ef 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -14,12 +14,14 @@ use crate::cognition::working_memory::WorkingMemory; pub(crate) struct Actions<'a> { pub memory: &'a WorkingMemory, + /// Whose spill directory a stored whole is read from (`load`). + pub persona: uuid::Uuid, } impl Actions<'_> { fn standing(key: &str, text: String) -> Item { let message = ContextMessage::user(text); - Item { key: key.to_owned(), full: message.clone(), summary: None, pointer: Some(message) } + Item { key: key.to_owned(), full: message.clone(), summary: None, pointer: Some(message), stored: None } } } @@ -64,7 +66,8 @@ impl Source for Actions<'_> { return vec![banner, Self::standing("none", none)]; } let mut items = vec![banner]; - items.extend(acts.into_iter().map(|(seq, full, summary, pointer)| Item { + items.extend(acts.into_iter().map(|(seq, full, summary, pointer, stored)| Item { + stored: stored.map(|(chars, handle)| continuum_context::source::StoredWhole { chars, handle }), key: seq.to_string(), full: ContextMessage::user(full), summary: summary.map(ContextMessage::user), @@ -73,6 +76,19 @@ impl Source for Actions<'_> { items } + /// A whole her working memory evicted from RAM (storage, never visibility: FOCUS-CONTRACT + /// rule 7), read back from its spill file when her view grants it whole, labelled as it + /// read resident. `None` (the resident pointer renders) when the file is gone or unreadable. + fn load(&self, item: &Item) -> Option { + 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()))) + } + /// Once she has acted, the void said earlier in this epoch is superseded, never edited: /// her view reads as the timeline it is (the statement was true when it was made). fn retired(&self) -> Vec> { diff --git a/core/continuum-cognition/src/cognition/context_streams/blocks.rs b/core/continuum-cognition/src/cognition/context_streams/blocks.rs index 2917cf45b4..2d04d54ece 100644 --- a/core/continuum-cognition/src/cognition/context_streams/blocks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/blocks.rs @@ -56,7 +56,7 @@ impl Source for Grounding { // reopen it by, so collapsed it is still its truthful minimum, never a one-liner. let full = self.render(self.text.clone()); let pointer = self.render(self.minimum.clone()); - return vec![Item { key: "block".to_owned(), full, summary: None, pointer: Some(pointer) }]; + return vec![Item { key: "block".to_owned(), full, summary: None, pointer: Some(pointer), stored: None }]; } let whole = self.at(|unit| &unit.content); let summary = self.units.iter().any(|unit| unit.summary.is_some()).then(|| { @@ -69,7 +69,8 @@ impl Source for Grounding { key: "block".to_owned(), full: self.render(whole), summary: summary.map(|summary| self.render(summary)), - pointer: Some(pointer.map_or_else(|| self.render(self.minimum.clone()), |pointer| self.render(pointer))), // map_or_else: units with no coarser level keep the block's truthful minimum + pointer: Some(pointer.map_or_else(|| self.render(self.minimum.clone()), |pointer| self.render(pointer))), // map_or_else: units with no coarser level keep the block's truthful minimum, + stored: None, }] } } diff --git a/core/continuum-cognition/src/cognition/context_streams/conversation.rs b/core/continuum-cognition/src/cognition/context_streams/conversation.rs index 05dca3d1cb..e6183e7f8c 100644 --- a/core/continuum-cognition/src/cognition/context_streams/conversation.rs +++ b/core/continuum-cognition/src/cognition/context_streams/conversation.rs @@ -42,6 +42,7 @@ impl Source for Conversation { // itself, so an update too large to show is never unknown. summary: None, pointer: turn.pointer.clone().map(|text| ContextMessage { role: turn.role, text }), + stored: None, }) .collect() } diff --git a/core/continuum-cognition/src/cognition/context_streams/mod.rs b/core/continuum-cognition/src/cognition/context_streams/mod.rs index dd373c99ed..0b5f597a9d 100644 --- a/core/continuum-cognition/src/cognition/context_streams/mod.rs +++ b/core/continuum-cognition/src/cognition/context_streams/mod.rs @@ -30,9 +30,9 @@ pub(crate) struct MemoryStreams<'a> { } impl<'a> MemoryStreams<'a> { - pub fn of(memory: &'a WorkingMemory) -> Self { + pub fn of(memory: &'a WorkingMemory, persona: uuid::Uuid) -> Self { Self { - actions: actions::Actions { memory }, + actions: actions::Actions { memory, persona }, thoughts: thoughts::Thoughts { memory }, open_views: open_views::OpenViews { memory }, notices: notices::Notices { memory }, diff --git a/core/continuum-cognition/src/cognition/context_streams/notices.rs b/core/continuum-cognition/src/cognition/context_streams/notices.rs index 4e80900718..55e158486f 100644 --- a/core/continuum-cognition/src/cognition/context_streams/notices.rs +++ b/core/continuum-cognition/src/cognition/context_streams/notices.rs @@ -17,7 +17,7 @@ pub(crate) struct Notices<'a> { /// A notice is required input: collapsed, it is still itself, so no grant can drop it. fn required(key: String, text: String) -> Item { let message = ContextMessage::user(text); - Item { key, full: message.clone(), summary: None, pointer: Some(message) } + Item { key, full: message.clone(), summary: None, pointer: Some(message), stored: None } } impl Source for Notices<'_> { diff --git a/core/continuum-cognition/src/cognition/context_streams/open_views.rs b/core/continuum-cognition/src/cognition/context_streams/open_views.rs index 32830e6d8d..2f6e4adf02 100644 --- a/core/continuum-cognition/src/cognition/context_streams/open_views.rs +++ b/core/continuum-cognition/src/cognition/context_streams/open_views.rs @@ -17,7 +17,7 @@ pub(crate) struct OpenViews<'a> { /// turn (Benchy, the M5, 2026-10-17), so collapsed it is still itself. fn required(key: String, text: String) -> Item { let message = ContextMessage::user(text); - Item { key, full: message.clone(), summary: None, pointer: Some(message) } + Item { key, full: message.clone(), summary: None, pointer: Some(message), stored: None } } impl Source for OpenViews<'_> { diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index cc5c45ba45..5eabe5b129 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -9,7 +9,7 @@ use super::notices::Notices; use crate::cognition::working_memory::WorkingMemory; fn rendered(memory: &WorkingMemory) -> String { - Actions { memory }.items().iter().map(|item| item.full.text.clone()).collect::>().join("\n") + Actions { memory, persona: uuid::Uuid::nil() }.items().iter().map(|item| item.full.text.clone()).collect::>().join("\n") } // what this catches: her action stream going silent or lying about her acts, the three @@ -53,7 +53,7 @@ fn her_view_survives_a_restart_in_her_checkpoint() { let memory = WorkingMemory::new(8); memory.record_receipt("I ran code/list Result: 4 files"); memory.record_settlement("listed", None); - let actions = Actions { memory: &memory }; + 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(); let rendered = |view: &View| view.render().map(|m| m.text.clone()).collect::>(); @@ -76,11 +76,42 @@ fn an_unsaved_result_never_collapses_to_a_line_nothing_reopens() { memory.record_receipt("I ran code/shell(cat Cargo.toml) Result: [package] name = \"x\""); memory.record_settlement("read the manifest", None); let (acts, _) = memory.action_renderings(); - let (_, full, _, pointer) = acts.last().expect("the act is on record"); + let (_, full, _, pointer, stored) = acts.last().expect("the act is on record"); + assert!(stored.is_none(), "an unsaved result is resident: nothing to load"); assert!(full.contains("name = \"x\""), "{full}"); assert_eq!(pointer, full, "an unsaved result's pointer is the result itself"); } +// what this catches (FOCUS-CONTRACT rule 7, FLOW §2d): RAM storage deciding what she sees. A +// result's body evicted from RAM for its handle left only its pointer in her view, so the RAM +// bound was a visibility bound. Evicted, it is priced at its whole (`stored`) and loaded back +// whole when the allocation grants it, labelled exactly as it read resident. +#[test] +fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { + let persona = uuid::Uuid::new_v4(); + let memory = WorkingMemory::new(8); + let body = "a line of the evicted result\n".repeat(400); + let pin = crate::cognition::tool_executor::spill::LivePin::new(); + memory.record_receipt_typed(&[], &body, None, pin.retain(persona, &body)); + 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); + 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"); + assert_eq!(full, pointer, "what stays resident is its pointer"); + assert_eq!(chars, resident_whole.chars().count(), "priced at exactly the whole it rendered"); + let source = super::actions::Actions { memory: &memory, persona }; + let item = continuum_context::source::Source::items(&source) + .into_iter() + .find(|item| item.key == seq.to_string()) + .expect("test: the act's item"); + assert_eq!(continuum_context::source::whole_chars(&item), chars); + let whole = continuum_context::source::whole(&source, item); + assert_eq!(whole.text, resident_whole, "loaded back whole, exactly as it read resident"); +} + // what this catches: her substrate's notices re-rendered as new text on every act. They were one // block after her view, ~3.6k chars re-prefilled per act though almost none of it changed // (Benchy and Aiko on the M5, 2026-10-24). As items, an act with the same notices appends diff --git a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs index 2c0e4e3645..8a8ace1f05 100644 --- a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs +++ b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs @@ -39,7 +39,7 @@ impl Source for Thoughts<'_> { let banner = ContextMessage::user( "My own recent thoughts (working memory, my interior state, not a message from anyone):".to_owned(), ); - let mut items = vec![Item { key: "banner".to_owned(), full: banner.clone(), summary: None, pointer: Some(banner) }]; + let mut items = vec![Item { key: "banner".to_owned(), full: banner.clone(), summary: None, pointer: Some(banner), stored: None }]; items.extend(thoughts.into_iter().map(|text| { // Keyed by what it says: a thought, once recorded, does not change, and neither may // its rendering. Full is the whole thought; how much of her thoughts she reads is the @@ -52,12 +52,13 @@ impl Source for Thoughts<'_> { full: ContextMessage::user(format!("- {text}")), summary: None, pointer: Some(ContextMessage::user(format!("- {}", collapse_thought(&text, POINTER_KEEP)))), + stored: None, } })); // Fresh each event, newest last; one item, so a status change appends one line set. items.extend(dispatched.map(|text| { let message = ContextMessage::user(text); - Item { key: "dispatched".to_owned(), full: message.clone(), summary: None, pointer: Some(message) } + Item { key: "dispatched".to_owned(), full: message.clone(), summary: None, pointer: Some(message), stored: None } })); items } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 2b6552b0d1..f5ac14990a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -462,11 +462,6 @@ impl LlmDeliberationFaculty { /// so an act that really needs more room earns it back within a turn. const COMPLETION_COLD_PRIOR_TOKENS: u32 = crate::inference::planning::MIN_SERVE_CTX; - /// The action result's share of the window before its tail is DEMOTED to ordinary - /// history. Same denominator as the room payload for the same reason: no single - /// required item may claim more than a quarter of the window, because the moment one - /// does, every other required item is competing for what is left and the turn refuses. - const RESULT_SHARE_DENOM: u32 = 4; /// The most an ACT turn may generate — a RUNAWAY bound, not a budget. /// Measured acts that COMMITTED a tool call ran 4,188–9,818 tokens on the 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 5c09e6736b..f33acc0f6c 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 @@ -57,14 +57,21 @@ impl LlmDeliberationFaculty { /// weighs her reply also decides, once, how much of her context she reads. pub(in super::super) fn view_claims(&self, streams: &Streams) -> Vec { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); Self::view_sources(streams, memory_streams.as_ref()) .into_iter() .map(|source| { let items = source.items(); let cost = |message: &ContextMessage| Self::message_cost(&message.to_chat()); let floor: usize = items.iter().map(|item| item.pointer.as_ref().map_or(0, cost)).sum(); // map_or: an item that leaves when collapsed costs nothing - let want: usize = items.iter().map(|item| cost(&item.full)).sum(); + // An item's WHOLE level, stored or resident (`whole_chars`): a body evicted from RAM + // is priced from its measured size, never as the pointer resident in its place, + // or the allocation would never grant room to see it (FOCUS-CONTRACT rule 7). + let whole = |item: &continuum_context::source::Item| { + let extra = continuum_context::source::whole_chars(item).saturating_sub(item.full.text.chars().count()); + cost(&item.full) + extra / continuum_base::token_estimate::GUARD_CHARS_PER_TOKEN + }; + let want: usize = items.iter().map(whole).sum(); crate::cognition::rag_budget::RagSourceBudget { source_id: format!("{VIEW_CLAIM}{}", source.name()), priority: source.priority(), @@ -192,7 +199,7 @@ impl LlmDeliberationFaculty { /// caller to size). fn advance_view(&self, streams: &Streams) -> (Vec, bool) { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); let sources = Self::view_sources(streams, memory_streams.as_ref()); let mut held = self.context_view.lock(); // A restart resumes the view her checkpoint kept, the same bytes the engine's saved @@ -242,7 +249,7 @@ impl LlmDeliberationFaculty { /// the caller re-checks the result in tokens). `None` when there is no unsent act to redo. fn admit_view(&self, streams: &Streams, view_tokens: usize, budget_tokens: usize) -> Option> { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); let sources = Self::view_sources(streams, memory_streams.as_ref()); let mut held = self.context_view.lock(); let view = held.as_mut()?; @@ -271,7 +278,7 @@ impl LlmDeliberationFaculty { /// Whether her view, started now under `allocate`'s grants, would show her more than it holds. fn view_would_restore(&self, streams: &Streams, allocate: impl FnOnce(&[Claim]) -> Vec) -> Result { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); let sources = Self::view_sources(streams, memory_streams.as_ref()); self.context_view.lock().as_ref().map_or(Ok(false), |view| view.start_would_restore(&sources, allocate)) // map_or: no view yet holds nothing to restore } @@ -283,7 +290,7 @@ impl LlmDeliberationFaculty { allocate: impl FnOnce(&[Claim]) -> Vec, ) -> Result, continuum_context::view::GrantMismatch> { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); let mut sources = Self::view_sources(streams, memory_streams.as_ref()); sources.retain(|source| !shed.contains(&source.name())); let mut held = self.context_view.lock(); @@ -336,7 +343,7 @@ impl LlmDeliberationFaculty { #[cfg(any(test, feature = "test-fixtures"))] pub(in super::super) fn whole_view(&self, streams: &Streams) -> Vec { let memory = self.working_memory.as_deref(); - let memory_streams = memory.map(MemoryStreams::of); + let memory_streams = memory.map(|memory| MemoryStreams::of(memory, self.persona_id)); let sources = Self::view_sources(streams, memory_streams.as_ref()); let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); match View::start(Vec::new(), &sources, whole) { 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 587eb9505b..e745f691f2 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 @@ -60,7 +60,7 @@ fn two_acts_and_a_turnover(conversation_first: bool) -> (usize, usize, usize) { let memory = WorkingMemory::new(8); memory.record_receipt("I ran code/list Result: 4 files"); memory.record_settlement("listed", None); - let memory_streams = MemoryStreams::of(&memory); + let memory_streams = MemoryStreams::of(&memory, uuid::Uuid::nil()); let first = streams(0, "RECALL: the repro lives in tests/"); let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); let (mut view, _) = View::start(Vec::new(), &ordered(&first, &memory_streams, conversation_first), whole) @@ -96,7 +96,7 @@ fn two_acts_and_a_turnover(conversation_first: bool) -> (usize, usize, usize) { #[test] fn consecutive_acts_share_the_whole_view_and_a_turnover_keeps_the_settled_front() { let memory = WorkingMemory::new(8); - let memory_streams = MemoryStreams::of(&memory); + let memory_streams = MemoryStreams::of(&memory, uuid::Uuid::nil()); let now = streams(0, "RECALL: one"); let names: Vec<&str> = LlmDeliberationFaculty::view_sources(&now, Some(&memory_streams)).iter().map(|s| s.name()).collect(); 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 24e0d17749..084a964ae0 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 @@ -294,10 +294,10 @@ impl LlmDeliberationFaculty { // only a truncation notice. Oversized output paging belongs to the // existing spill/tool-output producer, never to a generic byte reducer. input.update(b"active_result"); - let (latest_result, demoted_result) = match self.working_memory.as_ref() { - None => (Vec::new(), None), + let latest_result = match self.working_memory.as_ref() { + None => Vec::new(), Some(wm) => match wm.active_action_full() { - None => (Vec::new(), None), + None => Vec::new(), Some((seq, full)) => { let message = wm.full_result_message(seq, &full); // Provenance remains part of request identity. Typed calls and @@ -305,10 +305,11 @@ impl LlmDeliberationFaculty { field(&mut input, message.as_bytes()); let observations = wm.active_action_observations(seq); let calls = wm.active_action_native_calls(seq); - let (mut group, tail) = if calls.is_empty() { - // Legacy receipts have no native IDs to echo. - let (head, tail) = self.split_action_result(message); - (vec![head], tail) + let mut group = if calls.is_empty() { + // Legacy receipts have no native IDs to echo. Whole: the one allocation + // reduces it by level when it alone exceeds her window + // (`fit_newest_result`), never a head cut here (FOCUS-CONTRACT rule 4). + vec![ChatMessage::text("user", message)] } else { let results: Vec<_> = observations.iter().map(|o| o.output.result.clone()).collect(); for observation in &observations { @@ -329,7 +330,7 @@ impl LlmDeliberationFaculty { parts.push(crate::ai::types::ContentPart::Text { text: wm.result_label(seq) }); } // This entire required group survives fitting or faults together. - (vec![calls, results], None) + vec![calls, results] }; if let Some(visual) = visual.filter(|v| v.seq == seq && !observations.is_empty()) { // Legacy checkpoints can still own pixels without original @@ -350,7 +351,7 @@ impl LlmDeliberationFaculty { result.content = crate::ai::types::MessageContent::Parts(parts); } } - (group, tail) + group } }, }; @@ -367,10 +368,6 @@ impl LlmDeliberationFaculty { stimulus = Some(ChatMessage::text("user", ws.world_state.clone())); } input.update([(!latest_result.is_empty()) as u8]); - let mut messages = messages; - // The action result's demoted TAIL rides in ordinary history, after prior history: - // without this it would be silently dropped. - messages.extend(demoted_result); let action_statement = self .working_memory .as_ref() @@ -394,105 +391,4 @@ impl LlmDeliberationFaculty { action_statement, } } - - /// Split this turn's room updates into the part that is REQUIRED and the part - /// that merely wants to be there. Nothing is discarded. - /// - /// Room updates are required input — `required_tokens` counts them and - /// `fit_messages` never drops them — so an unbounded room is a citizen who can - /// no longer think. But simply CUTTING the excess would be worse than the bug: - /// a task, a correction, or an instruction that arrived earlier in the batch - /// would be deleted before she ever read it, and she would have no way to know - /// something was taken. - /// - /// So the overflow is DEMOTED, not dropped. The newest share stays required; the - /// older remainder is returned to be appended to ordinary history, where it is - /// still shown whenever the window has room and is trimmed by the existing - /// front-drop only under real pressure — the same treatment every other past - /// message gets. The information survives; only its claim on the required budget - /// does not. - /// - /// Returns `(required_newest, demoted_older)`, both chronological. - /// Split the action result into the REQUIRED head and a DEMOTED tail. - /// - /// The result of the citizen's last act is required input — she cannot reason about - /// what her hands just did if it is dropped — and it was also UNBOUNDED. A single - /// `code/read` or `code/shell` output therefore claimed the whole window as - /// irreducible payload, and `fit_messages` refused the turn, and she went mute while - /// holding her card. - /// - /// Measured 2026-09-10 on a 23,040-token lane: `required_payload = 18,629` against - /// `after_reserves = 15,688`, over by 2,941, with `grounding_tokens = 113` proving - /// grounding innocent and `received = 2` proving it was ONE enormous message. 836 - /// consecutive refusals, zero acts, zero inference, for the whole of a benchmark - /// round. The build had already bounded room updates (#3947) and stopped grounding - /// vetoing the turn (#3954) — this was the same class, one field over. - /// - /// The code here used to say oversized output "belongs to the existing - /// spill/tool-output producer, never to a generic byte reducer". That is a good rule - /// about WHO SHOULD SHRINK IT, and it was enforced nowhere: nothing checked that the - /// producer had, so an unspilled result walked straight into required input. - /// - /// DEMOTED, never discarded (Joel, 2026-09-09: "maybe trim clipped or killed - /// important information the persona needed to complete things"). The head stays - /// required so the act's outcome — status, error, the first lines that say what - /// happened — is always in front of her; the tail becomes ordinary history, still - /// rendered whenever the window allows, and still re-readable through its spill - /// handle. A cut on a CHAR boundary would split a UTF-8 sequence, so the split walks - /// to a line boundary and says how much moved. - pub(in super::super) fn split_action_result(&self, message: String) -> (ChatMessage, Option) { - let window = self.working_window() as usize; - let cap = window / Self::RESULT_SHARE_DENOM as usize; - let whole = ChatMessage::text("user", message.clone()); - if Self::messages_cost(std::slice::from_ref(&whole)) <= cap { - return (whole, None); - } - // WHICH HALF IS REQUIRED IS DECIDED BY WIRE ORDER, not by preference. - // - // History renders BEFORE the required slot (`prompt.history.extend(latest_result)` - // appends the required part last). So keeping the HEAD required would place the - // result's beginning AFTER its middle on the wire — she would read it backwards. - // Keeping the TAIL required puts the demoted beginning in history and the ending - // in the required slot, which is the original order, and it keeps the payload - // ending byte-for-byte where the existing wire test expects it. - // - // Walk lines from the END while the tail still fits its share. - let lines: Vec<&str> = message.split_inclusive('\n').collect(); - let mut take = 0usize; - let mut tail = String::new(); - for line in lines.iter().rev() { - let candidate = format!("{line}{tail}"); - let cost = Self::messages_cost(std::slice::from_ref(&ChatMessage::text( - "user", - candidate.clone(), - ))); - // The LAST line is always required even if it alone exceeds the share: a - // required slot holding none of her result tells her nothing about what her - // hands just did, and a genuinely impossible payload is the existing capacity - // fault's job to report honestly. - if take == 0 || cost <= cap { - tail = candidate; - take += 1; - } else { - break; - } - } - if take >= lines.len() { - return (whole, None); - } - let head: String = lines[..lines.len() - take].concat(); - let head_msg = ChatMessage::text("user", head); - let tail_msg = ChatMessage::text("user", tail); - continuum_base::probe!( - class = "delib.action_result.demoted", - persona = %self.persona_name, - window = window, - cap = cap, - required_tokens = Self::messages_cost(std::slice::from_ref(&tail_msg)), - demoted_tokens = Self::messages_cost(std::slice::from_ref(&head_msg)), - "the action result exceeded its share of the window — its ending stays REQUIRED and the earlier part was demoted to ordinary history, still rendered when the window allows and still re-readable via its spill handle. Nothing was discarded: an unbounded required result is what makes one big tool output a mute citizen." - ); - (tail_msg, Some(head_msg)) - } - } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs index 2504cf3ba5..2632a895c6 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs @@ -418,6 +418,9 @@ pub struct DeliberationPromptView { /// Her newest result's estimated tokens as this view carries it (`RequiredParts::latest_result`): /// what a refusal's excess is charged to when it refits her (`verdict/newest_refit.rs`). pub newest_result_tokens: usize, + /// The one allocation this view was fitted under, for the call's capture (FOCUS-CONTRACT + /// rule 8). `None` when no allocation ran (a fault before the plan). + pub allocation: Option, /// Her hands as the one allocation bought them (`tools_epoch.rs`): the request sends /// exactly this, never a second selection. pub tools: crate::cognition::tool_surface::SelectedSurface<'static>, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs index 18a92b212f..697701f07b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs @@ -219,11 +219,13 @@ impl LlmDeliberationFaculty { .map(|claim| claim.floor_tokens as usize) .sum(); let irreducible_room = after_reserves.saturating_sub(view_floor); + // Her view already carries every block that rides the conversation. Measured BEFORE her + // newest result is fitted: demand is the sum of wants (FOCUS-CONTRACT rule 5), so a result + // shown at a smaller level still asks for its whole, or the window never grows for it. + let unfitted_message_tokens = all_messages.tokens(); // Her newest result alone over what the window leaves it is shown at a smaller level // with its handle, never dropped (goal 7); one that fits is untouched. let newest_result_reduced = self.fit_newest_result(&mut all_messages, irreducible_room); - // Her view already carries every block that rides the conversation. - let unfitted_message_tokens = all_messages.tokens(); // KEEP THE OVERFLOW. This used to be one chained `saturating_sub` ending in // `- all_messages.required_tokens()`, and the saturation is where the diagnosis // died: "over by 31,000" and "exactly at the line" both arrive as `0`, so the one @@ -425,6 +427,20 @@ impl LlmDeliberationFaculty { source })); let plan = crate::cognition::rag_budget::flex_allocate(context_window, &claims); + let allocation = Some(crate::ai::provenance::AllocationReceipt { + window: context_window, + revision: env!("CONTINUUM_BUILD_GIT_SHA").to_owned(), + claims: claims + .iter() + .map(|claim| crate::ai::provenance::ClaimGrant { + source: claim.source_id.clone(), + priority: claim.priority, + floor: claim.floor_tokens, + want: claim.max_tokens, + grant: plan.granted(&claim.source_id), + }) + .collect(), + }); let tools_grant = calibration.prompt_budget(plan.granted(FLEX_TOOLS) as usize); let (selected, tools_refusal) = self.granted_tools(ws, tools, tools_grant); let budget_floor = crate::cognition::rag_budget::turn_need(&claims).saturating_sub(claims.iter().find(|c| c.source_id == FLEX_REPLY).map_or(0, |c| c.floor_tokens)).saturating_add(reply_need); @@ -764,6 +780,7 @@ impl LlmDeliberationFaculty { segments, newest_result_reduced, newest_result_tokens, + allocation, tools: selected.into_owned(), tools_grant, } 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 13cca5e89b..61935600bb 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -127,6 +127,8 @@ impl LlmDeliberationFaculty { binding: &ModelBinding, context_window: u32, mut request: TextGenerationRequest, + // The allocation her prompt was fitted under: the receipt carries it with the capture. + allocation: Option, receipts: &mut Vec, ) -> Option> { // Identity belongs to the submitted adapter request. Provider response IDs @@ -297,7 +299,8 @@ impl LlmDeliberationFaculty { ), } .with_capture(completed.as_deref()) - .with_genes(genes), + .with_genes(genes) + .with_allocation(allocation), ); Some(gen_result) } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs index a9c30ca813..eeb31beda1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs @@ -27,7 +27,7 @@ impl Source for Stream { fn items(&self) -> Vec> { self.items .iter() - .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(format!("[{key} collapsed]")) }) + .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(format!("[{key} collapsed]")), stored: None }) .collect() } } 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 9ce406b74f..411b50bc22 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 @@ -2,82 +2,22 @@ use super::*; -fn faculty_with_window(window: u32) -> LlmDeliberationFaculty { - LlmDeliberationFaculty::new( - Uuid::new_v4(), - "Sahar", - "You are Sahar.", - Arc::new(HeuristicInferenceAdapter::new()), - ) - .with_context_window(window) -} - -// what this catches: the live 2026-09-10 mute, and it is the THIRD instance of -// one class. A `code/read` / `code/shell` output goes in as REQUIRED input, and -// it was unbounded — so one big result claimed the whole window and -// `fit_messages` refused every turn. Measured: required_payload 18,629 against -// after_reserves 15,688 on a 23,040 lane, grounding only 113 (innocent), -// received = 2 (ONE enormous message), 836 consecutive refusals, zero acts for -// a whole benchmark round. -#[test] -fn an_oversized_result_is_split_not_swallowed_whole() { - let faculty = faculty_with_window(4_096); - let huge: String = (0..4_000) - .map(|i| { - format!( - "line {i} of a very large tool result -" - ) - }) - .collect(); - // (required, demoted) = (the result's ENDING, its earlier part). The ending - // is what stays required so the wire reads in the original order — see - // `split_action_result` for why history's position decides this. - let (required, demoted) = faculty.split_action_result(huge.clone()); - let demoted = demoted.expect("an oversized result must yield a demoted part"); - - let cap = 4_096 / LlmDeliberationFaculty::RESULT_SHARE_DENOM as usize; - let required_cost = - LlmDeliberationFaculty::messages_cost(std::slice::from_ref(&required)); - assert!( - required_cost <= cap, - "the required part must fit its share: {required_cost} > {cap}" - ); - - // NOTHING IS DISCARDED. Head + tail reconstitute the original exactly — - // the property that separates demotion from truncation, and the one Joel - // asked for by name after the first cut of #3947 dropped instead of demoted. - let rebuilt = format!("{}{}", demoted.content_text(), required.content_text()); - assert_eq!( - rebuilt, huge, - "demoted + required must reconstitute the result byte-for-byte" - ); -} - -// what this catches: THE WIRING, which the three unit tests above cannot see. -// They call `split_action_result` directly, so they stay green even when the -// production build site stops calling it — verified by mutation, and that is -// exactly the blind source-assertion mistake made earlier the same night. This -// one goes through `prompt_view`, the real path, and fails the moment the -// result is required whole again. +// what this catches: the live 2026-09-10 mute (a `code/read` result several times the window +// required whole: 836 consecutive refusals) WITHOUT its old cure, a head cut by a window share +// (`split_action_result`, deleted with RESULT_SHARE_DENOM: FOCUS-CONTRACT rule 4, a result is +// reduced by LEVEL in the one allocation, never cut). A legacy result (no native call ids) with +// a saved handle goes through the real `prompt_view`: never refused, and what she reads names the +// handle she can read the whole through. Native results are covered below (Aris). #[tokio::test] -async fn a_huge_result_does_not_fault_the_turn_on_the_real_path() { +async fn a_huge_legacy_result_arrives_reduced_with_its_handle_never_refused() { + use crate::ai::types::ResultCustody; use crate::cognition::working_memory::WorkingMemory; let window = 8_192u32; let wm = Arc::new(WorkingMemory::new(8)); wm.set_served_window(window); - // A tool result several times the whole window — an ordinary `code/read` - // of a large file. - let huge: String = (0..6_000) - .map(|i| { - format!( - "line {i} of a very large tool result -" - ) - }) - .collect(); - wm.record_receipt(&huge); + 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() }); let faculty = LlmDeliberationFaculty::new( Uuid::new_v4(), @@ -88,87 +28,11 @@ async fn a_huge_result_does_not_fault_the_turn_on_the_real_path() { .with_context_window(window) .with_working_memory(Arc::clone(&wm)); - let ws = Workspace::new("what did that produce?"); - let view = faculty.prompt_view(&ws); - assert!( - view.capacity_error.is_none(), - "one big tool result must not refuse the turn — she holds her card while refusing, so this strands a benchmark round: {:?}", - view.capacity_error - ); - assert!( - !view.messages.is_empty(), - "and she must still be given her result to reason about" - ); -} - -// what this catches: a result that FITS must be left completely alone. A split -// that fires unconditionally would push every ordinary tool result into history -// and cost the citizen the outcome of her own act on the very next turn. -#[test] -fn a_result_that_fits_is_untouched() { - let faculty = faculty_with_window(32_768); - let small = "ok: wrote 3 lines -" - .to_string(); - let (required, demoted) = faculty.split_action_result(small.clone()); - assert!(demoted.is_none(), "a small result has nothing to demote"); - assert_eq!(required.content_text(), small); -} - -// what this catches: the head must never be empty. If the FIRST line alone -// exceeds the share, it is still required — a citizen handed a demotion notice -// and none of her own result cannot reason about what her hands just did, and -// the honest failure for a genuinely impossible payload is the existing -// capacity fault, not a silently empty head. -#[test] -fn the_first_line_is_required_even_when_it_alone_exceeds_the_share() { - let faculty = faculty_with_window(1_024); - let one_giant_line = format!( - "{} -", - "x".repeat(20_000) - ); - let (required, demoted) = faculty.split_action_result(one_giant_line.clone()); - assert!( - !required.content_text().is_empty(), - "the required part is never empty — she must see what her act produced" - ); - let rebuilt = format!( - "{}{}", - demoted - .as_ref() - .map(|d| d.content_text()) - .unwrap_or_default(), - required.content_text() - ); - assert_eq!(rebuilt, one_giant_line, "still nothing discarded"); -} - -// what this catches: UTF-8 safety. Splitting on a byte or char budget can cut a -// multi-byte sequence in half; line granularity cannot. A panic here would take -// down the cognition cycle on any result containing non-ASCII — which is most -// of them, since the results carry the citizens' own prose. -#[test] -fn splitting_never_cuts_a_multibyte_sequence() { - let faculty = faculty_with_window(2_048); - let multibyte: String = (0..2_000) - .map(|i| { - format!( - "строка {i} — ✅ 日本語テキスト -" - ) - }) - .collect(); - let (required, demoted) = faculty.split_action_result(multibyte.clone()); - let rebuilt = format!( - "{}{}", - demoted - .as_ref() - .map(|d| d.content_text()) - .unwrap_or_default(), - required.content_text() - ); - assert_eq!(rebuilt, multibyte, "multibyte content survives the split"); + let view = faculty.prompt_view(&Workspace::new("what did that produce?")); + assert!(view.capacity_error.is_none(), "one big result must not refuse the turn: {:?}", view.capacity_error); + let sent: String = view.messages.iter().map(|m| m.content_text()).collect(); + assert!(sent.contains("legacy-evidence"), "she reads it at a level that names its handle"); + assert!(sent.len() < huge.len(), "reduced, not sent whole into a window it is several times"); } /// Her NEWEST result over her window (prompt/newest_result.rs): Aris on the M5, 2026-10-26. 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 9aa4ecd68c..32831ef572 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 @@ -27,7 +27,8 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { "src/lib.rs:42: concrete_review_target\n{{\"payload\":\"{}\"}}\nclaimable_now: 29\ntotal_on_board: 43", "x".repeat(window as usize * 2), ); - wm.record_receipt(&result); + // saved, as the act path saves every result too large to keep in RAM (`spill`) + wm.record_receipt_typed(&[], &result, None, crate::ai::types::ResultCustody::Whole { handle: "wire-evidence".into() }); let faculty = LlmDeliberationFaculty::new(persona, "Ivar", "You are Ivar.", adapter.clone()) .with_context_window(window) @@ -148,49 +149,20 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { .messages .iter() .any(|message| message.content_text().contains(stimulus))); - // WHAT IS GUARANTEED ON THE WIRE CHANGED HERE, deliberately. - // - // This used to assert the ENTIRE action result arrived byte-for-byte, - // because the result was REQUIRED input and required input is never - // dropped. That is precisely what muted citizens: one `code/read` of a - // large file claimed the whole window as irreducible payload and - // `fit_messages` refused every turn — measured 2026-09-10, required 18,629 - // against 15,688 available, 836 consecutive refusals, zero acts for an - // entire benchmark round while she held the card. - // - // Now the result is capped at its share and the earlier part is DEMOTED to - // ordinary history: rendered whenever the window allows, evicted by the - // normal front-drop when it does not, and always re-readable through its - // spill handle. So the honest guarantee is: - // - // - the result's ENDING is always on the wire (it stays required), and - // - nothing is DISCARDED at the split — `split_action_result` is pinned - // byte-exact by `an_oversized_result_is_split_not_swallowed_whole`. - // - // A 16k-token single line on a 32k window cannot be both demoted and - // retained; asserting otherwise would just be asserting the mute back. - let wire_text: String = request - .messages - .iter() - .map(|message| message.content_text().to_string()) - .collect(); + // WHAT IS GUARANTEED ON THE WIRE (FOCUS-CONTRACT rule 4). The 2026-09-10 mute (one + // `code/read` required whole, 836 refusals) was first cured by a head cut at a window + // share (`split_action_result`); that cut is gone. Her newest result is reduced by LEVEL + // in the one allocation: whole when it fits, else its summary or pointer, which names + // the handle the whole is read through. Either way it is the last thing she reads. let ending = result .rsplit_once('\n') .map(|(_, last)| last) .filter(|last| !last.is_empty()) .unwrap_or(result.as_str()); + let last = request.messages.last().expect("test: a request has messages").content_text(); assert!( - request - .messages - .last() - .unwrap() - .content_text() - .ends_with(ending), - "the result's ENDING is the last thing she reads — she must always see what her own act produced, never only a footer" - ); - assert!( - wire_text.contains(ending), - "and it is genuinely on the wire, not merely implied" + last.ends_with(ending) || last.contains("wire-evidence"), + "her newest result is the last thing she reads, whole or at a level naming its handle" ); // The held card's context reaches her in the assembled-context message after her @@ -321,9 +293,14 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { let mut ws = if oversized_part == 0 { Workspace::new(&oversized) } else if oversized_part == 1 { - wm.record_receipt(&format!( - "{oversized}\nclaimable_now: 29\ntotal_on_board: 43" - )); + // saved, as the act path saves every result too large to keep whole: with its handle + // she reads it at a level, never a refusal (FOCUS-CONTRACT rule 4) + wm.record_receipt_typed( + &[], + &format!("{oversized}\nclaimable_now: 29\ntotal_on_board: 43"), + None, + crate::ai::types::ResultCustody::Whole { handle: "capacity-evidence".into() }, + ); let mut ws = Workspace::new(""); ws.turns.clear(); ws.self_initiated = true; @@ -365,9 +342,9 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { .with_context_window(window) .with_working_memory(wm) .with_working_set(registry.clone()); - // Parts 3-4 shed their standing grounding (#3954), part 1 caps its oversized - // action result and demotes the rest, and part 2's room update is a turn of her - // view that collapses to its handle (`chat/history`) — all four now THINK + // Parts 3-4 shed their standing grounding (#3954), part 1's oversized saved + // result arrives at a level naming its handle, and part 2's room update is a turn + // of her view that collapses to its handle (`chat/history`) — all four now THINK // instead of refusing. What still faults is the genuinely irreducible payload: // the stimulus (part 0), the question she is answering. let bounded_case = oversized_part != 0; 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 0471ca7809..480078dab8 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 @@ -437,6 +437,17 @@ async fn provider_context_feedback_faults_when_required_input_cannot_fit() { outcome.receipts[0].outcome, crate::ai::provenance::GenerationOutcome::Faulted { .. } )); + // ...and it names the allocation its prompt was fitted under (FOCUS-CONTRACT rule 8): a + // lived call that can't say which attention decision shaped it gives a learned focus policy + // nothing to learn from. Every claim's grant is within what it asked for. + let allocation = outcome.receipts[0].allocation.as_ref().expect("the call names its allocation"); + assert_eq!(allocation.window, window, "the window the one allocation ran over"); + assert!(!allocation.claims.is_empty()); + assert!( + allocation.claims.iter().all(|c| c.grant <= c.want.max(c.floor)), + "no claim granted past its want: {:?}", + allocation.claims + ); ws.now_ms = Some(180_000); // Clock and diagnostic churn do not replace the pending work. wm.record_fact("The provider refused the previous prompt; the artifact remains pending."); ws.turns.push(BurstTurn::perception( 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 0d872c94d0..6c0da5af2b 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 @@ -307,7 +307,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, receipts) + .generate_for_workspace(ws, &binding, fit_window, request, view.allocation.clone(), receipts) .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/persona_workspace/default_workspace_capacity.rs b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs index 5866653374..6ed4d6b6c0 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 @@ -315,9 +315,10 @@ pub(super) fn assemble_workspace_cycle( // turns record nothing). Built HERE (before recall) so recall can share it in and // suppress an engram the recency channel already carries — see below. // Depth comes from the BUDGET, never a constant: the count sibling of the per-step size - // bound, off the same live window. See `ContextBudget::working_memory_steps`. + // bound, a ratio of two window fractions and so the same on every window: no live window is + // read to build it. See `ContextBudget::WORKING_MEMORY_STEPS`. let working_memory = Arc::new(WorkingMemory::new( - crate::cognition::context_budget::ContextBudget::live_or_floor().working_memory_steps(), + crate::cognition::context_budget::ContextBudget::WORKING_MEMORY_STEPS, )); // Persistence belongs to resident registration, independently of whether // recall runs inline or deferred. Constructing a fork grants no disk access. @@ -329,6 +330,13 @@ pub(super) fn assemble_workspace_cycle( // only a real failure (BigMama's live receipt on the 5090, card df0035bf). The pin // holds them live until `restore` below publishes the memory's own set. let restore_pin = persisted.wm.retain_handleless(cfg.persona_id); + // Results the old window share evicted carry no stored size: price each from its saved + // output, so her view can show it whole again (FOCUS-CONTRACT rule 7). + let persona = cfg.persona_id; + persisted.wm.price_evicted_wholes(|handle| { + let path = crate::cognition::tool_executor::spill::resolve(persona, handle).ok()?; + std::fs::read_to_string(path).ok().map(|body| body.trim().chars().count()) + }); // The previous life's handoff re-seeds this one: her ledger and card are known at // the NEXT seam too, without a wall read (card 49b5e806). if let Some(handoff) = persisted.wm.handoff.as_ref() { 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 9e06fa88fe..b778f624fc 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,7 +191,7 @@ use super::*; { let memory = WorkingMemory::new(8); memory.set_served_window(16_384); - let cap = memory.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; 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 { diff --git a/core/continuum-cognition/src/cognition/resident_service.rs b/core/continuum-cognition/src/cognition/resident_service.rs index a1b2967a7f..92f8b3da72 100644 --- a/core/continuum-cognition/src/cognition/resident_service.rs +++ b/core/continuum-cognition/src/cognition/resident_service.rs @@ -120,6 +120,7 @@ mod tests { capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, } } diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 381eeef95d..5f4601e048 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -48,7 +48,7 @@ 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 +// `ContextBudget::WORKING_MEMORY_STEPS` — the COUNT sibling of the per-step SIZE bound // right below, derived from the same calibrated fractions. // // It used to be `DEFAULT_WORKING_MEMORY_CAPACITY = 3`, the one bare number left behind when @@ -522,6 +522,22 @@ impl VolatileSnapshot { pin } + /// Price the whole of every result an earlier life evicted before `stored_chars` was kept: + /// its body left RAM for its handle by the old window share (Aiko on the M5, 2026-10-29), + /// so its whole had no price and showed at pointer level. `whole_of` measures the saved + /// output a handle names (`None`: not saved or unreadable, which stays a pointer, honestly). + /// Once per restore, before the mind acts, so no read happens under an inference grant. + pub fn price_evicted_wholes(&mut self, whole_of: impl Fn(&str) -> Option) { + if self.actions.is_empty() { + self.actions = self.action_records(); + } + for record in self.actions.iter_mut().filter(|r| r.result.is_none() && r.stored_chars.is_none()) { + if let Some(handle) = record.handle.as_deref() { + record.stored_chars = whole_of(handle); + } + } + } + /// 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 @@ -541,6 +557,7 @@ impl VolatileSnapshot { handle: None, written_pointer: None, summary: None, + stored_chars: None, }; let mut records: BTreeMap = BTreeMap::new(); let mut unkeyed = 0usize; @@ -700,6 +717,8 @@ mod perception; 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; 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 f3ce1c40d0..5e8990ac72 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -41,6 +41,12 @@ pub(crate) struct ActionRecord { /// Kept after the result collapses, so what she read stays addressable. #[serde(default, skip_serializing_if = "Option::is_none")] pub summary: Option, + /// The whole result's length once its body left RAM for its handle: what her view prices the + /// whole level at without reading it (`continuum_context::StoredWhole`). Eviction is storage, + /// never visibility (FOCUS-CONTRACT rule 7). `None` while resident, and for records evicted + /// 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, } impl ActionRecord { @@ -149,6 +155,7 @@ impl ActionLog { continue; } total -= record.result_chars(); + record.stored_chars = record.result.as_ref().map(|result| result.chars().count()); record.result = None; } Collapsed { total } diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 44219f0692..a40b0abcde 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -307,10 +307,10 @@ 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); - // Against the REAL window only; an unknown one folds nothing (the rule lives in - // `collapse_results_over_cap`): a floor here folded results the served window holds, - // cap 1,536 measured at restore on the 5090, card df0035bf. - self.collapse_results_over_cap(); + // 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(); 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 f7dd6ba215..5bd6fe9dea 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -334,6 +334,7 @@ impl WorkingMemory { result: Some(tail), handle, written_pointer: None, + stored_chars: None, }, budget.receipt_archive_chars(), ); @@ -347,7 +348,8 @@ impl WorkingMemory { // 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. - self.collapse_results_over_cap(); + // Now a storage budget (FOCUS rule 7): bodies leave RAM, never her view. + self.evict_resident_results(); // 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 dbdb8f105d..ccd313e9cd 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -2,6 +2,18 @@ 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)>); + impl WorkingMemory { /// Typed snapshot of the window, oldest → newest — the kind-aware sibling /// of [`Self::recent`] for consumers that render BY KIND (the steps-taken @@ -219,7 +231,11 @@ impl WorkingMemory { /// else what its pointer says; the pointer names the handle that reopens it, or is the /// ledger line when nothing was saved. The act still in flight is not among them (it /// rides whole as the newest message of the turn); the flag says whether there is one. - pub(crate) fn action_renderings(&self) -> (Vec<(u64, String, Option, String)>, bool) { + /// 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`). + pub(crate) fn action_renderings(&self) -> (Vec, bool) { let active = self.in_flight_action_seq(); let actions = self.actions.lock(); let in_flight = active.is_some_and(|seq| actions.get(seq).is_some()); @@ -241,14 +257,29 @@ impl WorkingMemory { // Unsaved and off the ledger: what it was, which never collapses anyway. (None, None, None) => format!("[action #{}] {}", record.seq, record.operation), }; + let stored = match (&record.result, &record.handle, record.stored_chars) { + (None, Some(handle), Some(chars)) => { + let label = format!("[result {attribution}{workspace}] ").chars().count(); + Some((label + chars, handle.clone())) + } + _ => None, + }; let full = whole.unwrap_or_else(|| pointer.clone()); let summary = record.summary.as_deref().map(|summary| format!("[result {attribution}{workspace} — summary; expand with tool/output] {summary}")); - (record.seq, full, summary, pointer) + (record.seq, full, summary, pointer, stored) }) .collect(); (renderings, in_flight) } + /// The label an act's whole carries in her view (`[result #n; …] `), for a stored whole + /// loaded back from its handle, so it reads exactly as it did resident. + pub(crate) fn action_whole_label(&self, seq: u64) -> Option { + let actions = self.actions.lock(); + let record = actions.get(seq)?; + Some(format!("[result {}{}] ", ResultAttribution::of(record), workspace_label(record.scope.as_deref()))) + } + pub fn recent_results_messages(&self) -> Vec { self.recent_results_with_pointers().into_iter().map(|(body, _)| body).collect() } @@ -277,8 +308,8 @@ 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 SIZE is bounded at - // receipt by the window share (`collapse_results_over_cap`), never by a count here. + // 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. // 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. @@ -387,57 +418,42 @@ impl WorkingMemory { crate::cognition::tool_executor::spill::publish_live_handles(self.instance, handles); } - /// 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 - /// next tick). The boundary lets the repeat-perception guard distinguish a spin - /// (identical call re-issued WITHIN one settling, before any answer) from a - /// 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. - /// Enforce the recent-results char cap by COLLAPSING oldest entries to queryable - /// pointers (spill handle when the body is on disk; identity otherwise). Called at every - /// RECEIPT and at settlement, against a known window only. Hysteresis: nothing moves - /// until the share is exceeded, then the oldest collapse down to HALF the share, so the - /// prompt head is byte-stable between two bursts (a pop_front per act rotated the head - /// and re-prefilled everything after it on a KV that cannot shift, 2026-08-24; a - /// settlement-only cap let a coding turn hold 1.09M chars of results, 2026-10-16). The - /// newest result always stays; an unsaved result stays whole. - /// - /// COLLAPSE IN CHUNKS (2026-09-13, the KV divergence audit): over 55 consecutive - /// captured turns, the FIRST block to differ from the previous prompt was the oldest - /// surviving `[result #n]` in 28 of them — evicting one entry per settle rotated the - /// prompt's head by one entry EVERY turn. Collapsing to HALF the cap in one jump keeps - /// the surviving head byte-identical for ~cap/2 chars of new results; the prefix reuse - /// those turns get is worth more than the half-cap of oldest tails they briefly forgo - /// (the pointers keep them queryable). Same law as `fit_messages`' chunked window start. - pub(super) fn collapse_results_over_cap(&self) { - // Against a KNOWN window only, for every caller (receipt, settlement, restore): an - // unknown budget's results share is the MIN_SERVE_CTX floor (`recent_results_chars`), - // and the window can be unknown at any of them — before serving is ready at restore, - // or when a lane relaunches between the prompt and the tool's return (no loadout to - // pin). Folding against the floor collapses results her real window holds; the next - // call with a known window collapses for real (Cormac on #5112). - let budget = self.budget(); - if !budget.is_known() { - return; - } - let cap = budget.recent_results_chars(); - let total = self.actions.lock().collapse_over(cap).total; + /// 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 > cap { + if total > budget { continuum_base::probe!( - class = "wm.results.unsaved_over_share", + class = "wm.results.unsaved_over_storage", total = %total, - cap = %cap, - "results whose save failed are kept whole over the results share" + 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 + /// next tick). The boundary lets the repeat-perception guard distinguish a spin + /// (identical call re-issued WITHIN one settling, before any answer) from a + /// 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.collapse_results_over_cap(); + 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/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 221c2bc6e1..41f34d02b5 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,7 +10,7 @@ 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 = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; // 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 { @@ -58,7 +58,7 @@ 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 = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; 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")); @@ -85,7 +85,7 @@ 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 = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; 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))); 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 7f77f65516..bd9779eb92 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -57,7 +57,7 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ 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(results.budget().recent_results_chars())); + let body_a = format!("task-a-only {}", "a".repeat(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); results.record_receipt_typed(&[], &body_a, None, saved("scope-a-output")); let original = results.last_action_full(); results.set_scope(Some("task-b".into())); @@ -118,7 +118,7 @@ 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 = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; wm.record_receipt_typed(&[], &"a".repeat(cap / 2), None, saved(&handle)); assert!(live(&file), "referenced by the ring"); for _ in 0..4 { @@ -166,7 +166,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 = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; 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)); @@ -273,20 +273,20 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { assert!(!crate::cognition::tool_executor::spill::is_live(&file), "released with the mind"); } -// what this catches (BigMama's live receipt of #4963 on the 5090, card df0035bf): restore -// collapsing against the FLOOR budget. Restore runs before the served window is known, so -// its budget is the floor (a 1,536-char share measured there) and it folded results her -// real window holds. With no window yet, restore keeps the ring as saved; once a window is -// set, the same snapshot collapses against it. +// 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. #[test] -fn restore_collapses_only_against_a_known_window() { +fn restore_bounds_results_by_storage_never_by_window() { + let budget = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; let source = WorkingMemory::new(8); source.set_served_window(65_536); - let share = source.budget().recent_results_chars(); for i in 0..4 { source.record_receipt_typed( &[], - &format!("r{i} {}", "w".repeat(share / 3)), + &format!("r{i} {}", "w".repeat(budget / 3)), None, saved(&format!("restore-{i}")), ); @@ -295,18 +295,14 @@ fn restore_collapses_only_against_a_known_window() { let entries = |wm: &WorkingMemory| { wm.recent_results_messages().iter().filter(|m| m.starts_with("[result ")).count() }; - - // The source settles against its own window as it records, so the count to keep is - // what it held, not how many were recorded. let held = entries(&source); let unknown = WorkingMemory::new(8); unknown.restore(snapshot.clone()); - assert_eq!(entries(&unknown), held, "no window yet: nothing folds against the floor"); - - let known = WorkingMemory::new(8); - known.set_served_window(16_384); - known.restore(snapshot); - assert!(entries(&known) < held, "a known smaller window collapses on restore"); + assert_eq!(entries(&unknown), held, "no window yet: the storage budget alone bounds it"); + 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 @@ -318,7 +314,7 @@ fn restore_collapses_only_against_a_known_window() { fn the_ring_holds_its_share_at_every_receipt_and_evicts_in_bursts() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let share = wm.budget().recent_results_chars(); + 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() @@ -350,7 +346,7 @@ fn the_ring_holds_its_share_at_every_receipt_and_evicts_in_bursts() { fn an_unsaved_result_keeps_its_bytes_through_settlement_and_restore() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = wm.budget().recent_results_chars(); + let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; let unsaved = format!("UNSAVED {}", "u".repeat(cap / 2)); wm.record_receipt_typed(&[], &unsaved, None, crate::ai::types::ResultCustody::Unsaved); for _ in 0..4 { @@ -368,3 +364,35 @@ fn an_unsaved_result_keeps_its_bytes_through_settlement_and_restore() { restored.restore(wm.snapshot()); assert!(whole(&restored), "and through restore"); } + +// what this catches (Fable on #5573; Aiko on the M5, 2026-10-29): results an earlier life evicted +// by the old window share carry a handle but no stored size, so after a deploy her view priced +// their whole at nothing and showed them as pointers forever. A restore prices each from its +// saved output; one whose output can't be read stays a pointer, never a guessed size. +#[test] +fn a_restore_prices_a_legacy_evicted_result_from_its_saved_output() { + let wm = WorkingMemory::new(8); + let persona = Uuid::new_v4(); + let pin = crate::cognition::tool_executor::spill::LivePin::new(); + let body = "a line of the saved output\n".repeat(50); + 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); + let mut snapshot = wm.snapshot(); + snapshot.actions = snapshot.action_records(); + // the shape the old share left: body gone, handle kept, no stored size + let legacy: Vec<_> = snapshot.actions.iter_mut().filter(|r| r.result.is_none()).map(|r| { + r.stored_chars = None; + r.handle.clone().expect("test: saved") + }).collect(); + assert_eq!(legacy.len(), 2, "two evicted, the newest resident"); + let measured = body.trim().chars().count(); + snapshot.price_evicted_wholes(|handle| (handle == legacy[0]).then_some(measured)); + let restored = WorkingMemory::new(8); + restored.restore(snapshot); + let (acts, _) = restored.action_renderings(); + let label = restored.action_whole_label(acts[0].0).expect("test: a label").chars().count(); + assert_eq!(acts[0].4.as_ref().map(|(chars, _)| *chars), Some(label + measured), "priced from its saved output, label included"); + assert_eq!(acts[1].4, None, "an output that can't be read stays a pointer"); +} 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 064ff93be4..8e864490f9 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -205,7 +205,7 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { // Actual settlement 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(restored.budget().recent_results_chars())); + record_saved(&restored, &"x".repeat(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); } restored.record_settlement("reported", None); assert!(restored.recent_results_messages().join("\n").contains( 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..266d941e3e 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -27,7 +27,7 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { // 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 = wm.budget().recent_results_chars(); + 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); for _ in 0..8 { diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index 37a292db72..d11a403d34 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -642,6 +642,7 @@ capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, }; let served = || GenerationOutcome::Served { model: "m".into(), provider: "p".into(), provider_request_id: None }; let faulted = || GenerationOutcome::Faulted { detail: "lane refused".into(), model: None, provider: None }; diff --git a/core/continuum-context/examples/replay.rs b/core/continuum-context/examples/replay.rs index 647ca04f78..295a77f4f9 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -121,7 +121,7 @@ impl Source for Captured { fn item(key: String, text: String) -> Item { let pointer: String = text.lines().next().unwrap_or_default().chars().take(185).collect(); let pointer = if pointer.len() < text.len() { pointer } else { text.clone() }; - Item { key, pointer: Some(pointer), summary: None, full: text } + Item { key, pointer: Some(pointer), summary: None, full: text, stored: None } } /// The one allocation, modelled: every source gets its floor, then the rest of `budget` diff --git a/core/continuum-context/examples/replay/append.rs b/core/continuum-context/examples/replay/append.rs index 96402db41d..174482cb2c 100644 --- a/core/continuum-context/examples/replay/append.rs +++ b/core/continuum-context/examples/replay/append.rs @@ -254,10 +254,10 @@ pub fn replay(label: &str, cuts: &[Cut], window: usize, share: usize, (chars_per } None => shown.answered().to_owned(), }; - looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full }); + looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full, stored: None }); } for full in extra_pages { - looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full }); + looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full, stored: None }); } previous_sent = Some(&cut.sent); previous_rendered = Some(rendered); diff --git a/core/continuum-context/examples/replay/sediment.rs b/core/continuum-context/examples/replay/sediment.rs index 0efd072696..ca3824adb6 100644 --- a/core/continuum-context/examples/replay/sediment.rs +++ b/core/continuum-context/examples/replay/sediment.rs @@ -171,7 +171,7 @@ mod tests { let items = sizes .iter() .enumerate() - .map(|(n, size)| Item { key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")) }) + .map(|(n, size)| Item { key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")), stored: None }) .collect(); Captured { name: name.to_owned(), items } } diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index d8a633f8dd..fa5c90f157 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -23,12 +23,28 @@ pub struct Item { /// item leaves the view entirely once collapsed (a conversation turn whose room history /// holds it, where a one-line pointer would cost about what the turn does). pub pointer: Option, + /// The whole is stored, not resident: `full` then holds what is in memory (its pointer or + /// summary) and the view prices the whole level from `stored.chars` without reading it. + /// Only an item the allocation grants WHOLE is loaded, once per render, through the + /// render's loader. Residency is not visibility: evicting a body from RAM never changes + /// what she can see (Cormac's proposal, FLOW plan §2d; the RAM storage budget is by bytes, + /// from governed RAM, never from the window). + pub stored: Option, +} + +/// Where a non-resident whole lives and what it costs, measured when it was stored. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredWhole { + /// The whole's exact size in chars, known at spill time: the allocation's price for it. + pub chars: usize, + /// The handle the render's loader opens (a spill path, a result id). + pub handle: String, } impl Item { /// An item that is resident whole, with no coarser levels yet. pub fn whole(key: impl Into, full: T) -> Self { - Self { key: key.into(), full, summary: None, pointer: None } + Self { key: key.into(), full, summary: None, pointer: None, stored: None } } } @@ -60,5 +76,22 @@ pub trait Source { Vec::new() } + /// Load the whole of one of this source's stored items (its `stored` handle), called only + /// for an item the allocation granted WHOLE. The default stores nothing; a source that + /// spills bodies (her results) overrides it. `None` renders what is resident. + fn load(&self, _item: &Item) -> Option { + None + } } +/// What an item's whole level costs: its stored size when the whole is not resident, else +/// the resident text's size. The allocation prices from this and never reads a stored body. +pub fn whole_chars(item: &Item) -> usize { + item.stored.as_ref().map_or_else(|| item.full.chars(), |stored| stored.chars) // map_or_else: a resident item is priced by its own text +} + +/// The item at its whole level: a stored body loaded through its source, else what is resident. +pub fn whole(source: &(impl Source + ?Sized), item: Item) -> T { + let loaded = item.stored.as_ref().and_then(|_| source.load(&item)); + loaded.unwrap_or(item.full) // unwrap_or: an unloadable body renders its resident level (pointer or summary), never nothing +} diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index 5966a3b1cb..4dc338d6a9 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -131,7 +131,7 @@ fn levels(items: &[Item], grant: usize) -> Vec { // its size fits the spare plus that pointer, and what it leaves is spare + pointer - size. // An item smaller than its own pointer gives the difference back instead of losing it. let pointer = pointer_chars(item); - let full = item.full.chars(); + let full = crate::source::whole_chars(item); let summary = item.summary.as_ref().map(Block::chars); let afford = |size: usize, spare: usize| size <= spare + pointer; if ceiling == Level::Full && afford(full, spare) { @@ -169,8 +169,8 @@ fn claim(source: &dyn Source, items: &[Item]) -> Claim { source: source.name().to_owned(), priority: source.priority(), pointer_chars: items.iter().map(pointer_chars).sum(), - full_chars: items.iter().map(|item| item.full.chars()).sum(), - newest_chars: items.last().map_or(0, |item| item.full.chars()), // map_or: a source with no items has no newest end + full_chars: items.iter().map(crate::source::whole_chars).sum(), + newest_chars: items.last().map_or(0, crate::source::whole_chars), // map_or: a source with no items has no newest end } } @@ -276,7 +276,7 @@ impl View { let id = key(source.name(), &item.key); 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(item.full), + Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => { view.summarized.insert(id.clone()); item.summary @@ -351,12 +351,12 @@ impl View { // 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 oversized = limit.is_some_and(|(_, oversized)| item.full.chars() > oversized); + let oversized = limit.is_some_and(|(_, oversized)| crate::source::whole_chars(&item) > oversized); let level = if self.collapsed.contains(&id) { Level::Pointer } else if self.summarized.contains(&id) { Level::Summary - } else if self.epoch.holds(&id) || item.pointer.is_none() || !oversized || fits(item.full.chars()) { + } else if self.epoch.holds(&id) || item.pointer.is_none() || !oversized || fits(crate::source::whole_chars(&item)) { Level::Full } else if item.summary.as_ref().is_some_and(|summary| fits(summary.chars())) { self.summarized.insert(id.clone()); @@ -366,7 +366,7 @@ impl View { Level::Pointer }; let text = match level { - Level::Full => Some(item.full), + Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => item.summary.or(item.pointer), Level::Pointer => item.pointer, }; diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index ab543724b6..a99dff30f4 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -36,13 +36,14 @@ impl Source for Fake { full: text.clone(), summary: None, pointer: Some(format!("[{key}: {} chars, reopen by key]", text.len())), + stored: None, }) .collect() } fn retired(&self) -> Vec> { self.retired .iter() - .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(text.clone()) }) + .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(text.clone()), stored: None }) .collect() } } @@ -179,7 +180,7 @@ fn an_item_without_a_pointer_leaves_the_view_when_collapsed() { 1 } fn items(&self) -> Vec> { - self.0.iter().map(|t| Item { key: (*t).to_owned(), full: (*t).to_owned(), summary: None, pointer: None }).collect() + self.0.iter().map(|t| Item { key: (*t).to_owned(), full: (*t).to_owned(), summary: None, pointer: None, stored: None }).collect() } } let mut turns = Turns(vec!["one", "two", "three"]); @@ -248,6 +249,7 @@ impl Source for Leveled { full: full.clone(), summary: summary.clone(), pointer: Some(format!("[{key}]")), + stored: None, }) .collect() } @@ -367,3 +369,53 @@ fn a_start_with_room_restores_what_a_squeezed_start_collapsed() -> Result<(), Gr assert_eq!(view.start_would_restore(&[&actions], |_| vec![]), Err(GrantMismatch { claims: 1, grants: 0 })); Ok(()) } + +/// A source whose newest body was evicted from RAM: resident it holds only its pointer, the +/// whole is stored and loads through `Source::load`. +struct Spilled { + body: String, +} + +impl Source for Spilled { + fn name(&self) -> &str { + "results" + } + fn priority(&self) -> u8 { + 5 + } + fn items(&self) -> Vec> { + let pointer = "[result #3341: saved, reopen by its handle]".to_owned(); + vec![ + Item { key: "3340".to_owned(), full: "an older result".to_owned(), summary: None, pointer: Some("[result #3340]".to_owned()), stored: None }, + Item { + key: "3341".to_owned(), + full: pointer.clone(), + summary: None, + pointer: Some(pointer), + stored: Some(crate::source::StoredWhole { chars: self.body.chars(), handle: "spill/3341".to_owned() }), + }, + ] + } + fn load(&self, item: &Item) -> Option { + (item.stored.as_ref()?.handle == "spill/3341").then(|| self.body.clone()) + } +} + +// what this catches: a body evicted from RAM priced and rendered as its resident pointer, so +// storage decided what she saw (FOCUS-CONTRACT rule 7; on the M5 2026-10-29 working memory +// deleted result bodies by a window share while the window had room for them). Its claim +// prices the WHOLE (full_chars and the newest end), and a grant that holds it renders the +// loaded body, not the pointer. +#[test] +fn an_evicted_body_is_priced_whole_and_rendered_whole_when_granted() -> Result<(), GrantMismatch> { + let body = "line of her newest result\n".repeat(200); + let spilled = Spilled { body: body.clone() }; + let claims = claims(&[&spilled]); + assert_eq!(claims[0].newest_chars, body.chars(), "the newest end is her whole result"); + assert_eq!(claims[0].full_chars, body.chars() + "an older result".to_owned().chars()); + let (view, _) = View::start(Vec::new(), &[&spilled], all_full)?; + assert!(rendered(&view).contains(&body), "granted whole, it renders the loaded body"); + let (tight, _) = View::start(Vec::new(), &[&spilled], |claims: &[Claim]| claims.iter().map(|c| c.pointer_chars).collect())?; + assert!(!rendered(&tight).contains(&body) && rendered(&tight).contains("reopen by its handle"), "granted only its floor, it is its pointer"); + Ok(()) +} 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 0f92ca8306..4199e3c55a 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 @@ -285,7 +285,7 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { refit: roomy.refit, system: String::new(), input_identity: [0; 32], estimated_prompt_tokens: estimate, completion_reserve: 0, capacity_error: None, budget_fault: None, protocol_error: None, segments: Vec::new(), - newest_result_reduced: false, newest_result_tokens: 0, + newest_result_reduced: false, newest_result_tokens: 0, allocation: None, messages: roomy.messages, tools: crate::cognition::tool_surface::SelectedSurface::none(), tools_grant: 0, }; let corrected = faculty.refit_rejected_prompt(snapshot, estimate as u32 + 1, estimate as u32, 0).unwrap(); diff --git a/core/continuum-dreaming/src/modules/dataset/candidate.rs b/core/continuum-dreaming/src/modules/dataset/candidate.rs index 4822594b6d..2c4b3551b7 100644 --- a/core/continuum-dreaming/src/modules/dataset/candidate.rs +++ b/core/continuum-dreaming/src/modules/dataset/candidate.rs @@ -246,6 +246,7 @@ mod tests { capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, }; serde_json::from_value(json!({ "submissionId": id, diff --git a/core/continuum-engine/src/ai/provenance.rs b/core/continuum-engine/src/ai/provenance.rs index 8fceb48b24..29cb5cd487 100644 --- a/core/continuum-engine/src/ai/provenance.rs +++ b/core/continuum-engine/src/ai/provenance.rs @@ -60,6 +60,34 @@ pub struct GenerationReceipt { /// before this field read as empty. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub gene_scales: Vec, + /// The one allocation her prompt was fitted under (FOCUS-CONTRACT rule 8): with `capture`, + /// a lived call names the attention decision that shaped what she saw, so an outcome can be + /// attributed to it and the call replayed under another policy. `None` for calls no view + /// allocated, and for rows written before this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub allocation: Option, +} + +/// The allocation a call's prompt was fitted under: the window it ran over, the build that +/// allocated it, and each claim's floor, want and grant, in tokens of that allocation. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AllocationReceipt { + pub window: u32, + /// The build that ran the allocator: its policy revision until the policy has its own. + pub revision: String, + pub claims: Vec, +} + +/// One claim of an allocation: what it could not go below, what it wanted whole, and what it got. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimGrant { + pub source: String, + pub priority: u8, + pub floor: u32, + pub want: u32, + pub grant: u32, } /// The genes a request actually runs with, and their scales: every requested adapter at a @@ -138,6 +166,7 @@ impl GenerationReceipt { capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, } } @@ -147,6 +176,12 @@ impl GenerationReceipt { self } + /// Attach the allocation the call's prompt was fitted under ([`AllocationReceipt`]). + pub fn with_allocation(mut self, allocation: Option) -> Self { + self.allocation = allocation; + self + } + /// Attach the capture cursor the call was recorded under. pub fn with_capture(mut self, cursor: Option<&str>) -> Self { self.capture = cursor.filter(|c| !c.is_empty()).map(str::to_owned); @@ -166,6 +201,7 @@ impl GenerationReceipt { capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, } } diff --git a/core/continuum-mind/src/persona/training_producer.rs b/core/continuum-mind/src/persona/training_producer.rs index a4d81d5ad8..16dba54946 100644 --- a/core/continuum-mind/src/persona/training_producer.rs +++ b/core/continuum-mind/src/persona/training_producer.rs @@ -96,6 +96,7 @@ pub mod test_support { capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, } } diff --git a/core/continuum-mind/src/persona/training_producer/tests/part_2.rs b/core/continuum-mind/src/persona/training_producer/tests/part_2.rs index 655c031829..84eab7e75a 100644 --- a/core/continuum-mind/src/persona/training_producer/tests/part_2.rs +++ b/core/continuum-mind/src/persona/training_producer/tests/part_2.rs @@ -284,6 +284,7 @@ use super::*; capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, }); receipts.push(receipt("failed-after-serving")); let homogeneous = served_provenance(&receipts).unwrap(); @@ -299,6 +300,7 @@ use super::*; capture: None, genes: Vec::new(), gene_scales: Vec::new(), + allocation: None, }); assert!(served_provenance(&receipts).is_none()); let last = receipts.last_mut().unwrap(); diff --git a/core/continuum-prompt/src/context_budget.rs b/core/continuum-prompt/src/context_budget.rs index 9513532465..2efccafa0c 100644 --- a/core/continuum-prompt/src/context_budget.rs +++ b/core/continuum-prompt/src/context_budget.rs @@ -380,9 +380,9 @@ fn working_window_when(served: u32, serving: bool) -> u32 { /// /// Long-horizon agentic work is exactly the case a 3-deep scratchpad cannot serve. /// [[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]] - pub fn working_memory_steps(&self) -> usize { - (TRAIL_HEAD_DENOM / TRAIL_TOTAL_DENOM).max(1) - } + /// Window-independent by construction, so it needs no budget instance: a resident's + /// memory is built before (and outlives) any one served window. + pub const WORKING_MEMORY_STEPS: usize = if TRAIL_HEAD_DENOM / TRAIL_TOTAL_DENOM > 1 { TRAIL_HEAD_DENOM / TRAIL_TOTAL_DENOM } else { 1 }; /// The result of her most recent act: WHOLE, up to the window she is served. It used to be /// a quarter of a prefill-bounded total (later floored at an eighth of the window), so her @@ -419,7 +419,7 @@ fn working_window_when(served: u32, serving: bool) -> u32 { /// acts on a 16k lane and hundreds on a big one. /// /// Unknown window → the `MIN_SERVE_CTX` floor share, not "no bound": this bounds a - /// STORED buffer, and (per [`Self::working_memory_steps`]'s precedent) an unbounded + /// STORED buffer, and (per [`Self::WORKING_MEMORY_STEPS`]'s precedent) an unbounded /// buffer is not an honest no-bound — it is a leak. pub fn receipt_archive_chars(&self) -> usize { match self.total_chars { @@ -590,35 +590,11 @@ mod tests { // without the other, this test says so. #[test] fn working_memory_depth_is_derived_from_the_budget_not_a_constant() { - let small = ContextBudget::from_window(4_096); - let lane = ContextBudget::from_window(16_384); - let huge = ContextBudget::from_window(1_000_000); - - assert_eq!( - lane.working_memory_steps(), - TRAIL_HEAD_DENOM / TRAIL_TOTAL_DENOM - ); - assert_eq!( - small.working_memory_steps(), - lane.working_memory_steps(), - "depth is a RATIO of two window fractions, so it does not shrink on a small lane" - ); - assert_eq!( - huge.working_memory_steps(), - lane.working_memory_steps(), - "nor grow on a huge one — a bigger window buys richer steps, not more of them" - ); + assert_eq!(ContextBudget::WORKING_MEMORY_STEPS, TRAIL_HEAD_DENOM / TRAIL_TOTAL_DENOM); assert!( - lane.working_memory_steps() > 3, + ContextBudget::WORKING_MEMORY_STEPS > 3, "must be deeper than the 3-step scratchpad that lost 19 of 21 steps" ); - // An unknown window must still yield a USABLE depth. Unlike a char bound, an - // unbounded COUNT is not "no bound" — it is an unbounded buffer, so the honest - // answer here is the derived ratio, not usize::MAX. - assert_eq!( - ContextBudget::unknown().working_memory_steps(), - lane.working_memory_steps() - ); } #[test]