From 6dcdb53992ebedf8c234001337a3c1d4e9eeb569 Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 22:54:55 -0500 Subject: [PATCH 01/11] WIP (not pushed): working memory sizes from the one owner, WorkingMemoryFaculty deleted, arbiter forwards every bid (card c537d687) Open before push: observation.rs:358 intent_label (Fable: drop the because-clause, annotate open views with call_line); vitals_emitter.rs:94 .min(100) and llm_deliberation_faculty.rs:716 OpenOptions are flagged because this branch touches those files (literal edits); full cognition/mind suites not yet run after the arbiter change. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/apply.rs | 55 ++--- .../src/cognition/act_observe/mod.rs | 38 ++- .../src/cognition/act_observe/observation.rs | 19 +- .../src/cognition/act_observe/settle/tests.rs | 2 +- .../src/cognition/act_observe/tests/apply.rs | 18 +- .../src/cognition/act_observe/tests/chain.rs | 6 +- .../src/cognition/act_observe/tests/credit.rs | 5 - .../src/cognition/act_observe/tests/drive.rs | 31 +-- .../act_observe/tests/investigation.rs | 23 +- .../src/cognition/context_streams/tests.rs | 2 - .../src/cognition/deliberation_prompt.rs | 4 +- .../src/cognition/llm_deliberation_faculty.rs | 2 +- .../prompt/messages.rs | 7 +- .../an_action_result_cannot_mute_a_citizen.rs | 2 - .../tests/prompt_shaping/reply_reserve.rs | 1 - .../tests/prompt_shaping/turn_window.rs | 19 +- .../tests/verdicts/act_verdicts.rs | 2 +- .../tests/verdicts/capacity_and_wire.rs | 3 - .../src/cognition/persona_workspace.rs | 2 +- .../default_workspace_capacity.rs | 28 +-- ...ins_admitted_periodic_writer_before_ack.rs | 2 - ..._told_when_her_hands_move_and_only_then.rs | 1 - .../src/cognition/rag_source_faculty/tests.rs | 3 +- ...d_in_action_recall_informs_the_decision.rs | 1 - .../src/cognition/request_replay.rs | 1 - .../src/cognition/should_respond_module.rs | 1 - .../src/cognition/working_memory.rs | 66 +++--- .../cognition/working_memory/action_log.rs | 37 +-- .../cognition/working_memory/continuity.rs | 34 +-- .../src/cognition/working_memory/faculty.rs | 219 ------------------ .../src/cognition/working_memory/ledger.rs | 87 ++----- .../cognition/working_memory/perception.rs | 36 ++- .../working_memory/tests/action_log.rs | 43 ++-- .../cognition/working_memory/tests/actions.rs | 70 +++--- .../cognition/working_memory/tests/custody.rs | 24 -- .../cognition/working_memory/tests/faculty.rs | 88 ------- .../src/cognition/working_memory/tests/mod.rs | 1 - .../working_memory/tests/open_views.rs | 2 - .../working_memory/tests/provenance.rs | 57 ++--- .../cognition/working_memory/tests/trail.rs | 39 +--- .../src/cognition/workspace/arbiter.rs | 46 +--- .../src/cognition/workspace/cause.rs | 2 +- .../src/cognition/workspace/tests.rs | 90 ++++--- .../cognition/workspace/workspace_cycle.rs | 9 +- .../cognition/workspace/workspace_cycle_2.rs | 3 +- core/continuum-core/src/ipc/vitals_emitter.rs | 1 - .../mind_integration/bound_card_activity.rs | 4 +- .../mind_integration/hands_isolation.rs | 3 +- .../registry/deliberation/prompt_shaping.rs | 2 - .../registry/deliberation/verdicts.rs | 2 - .../test_env/mind_integration/remote_lane.rs | 1 - .../training_credit/directed.rs | 5 +- .../src/persona/obligation/recover.rs | 1 - .../src/persona/service_loop/tests/part_4.rs | 4 - .../supervisor/materialize_adapters.rs | 1 - .../src/persona/wake_backlog.rs | 4 +- 56 files changed, 349 insertions(+), 910 deletions(-) delete mode 100644 core/continuum-cognition/src/cognition/working_memory/faculty.rs delete mode 100644 core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 4d2f92d2ec..4fc665ee61 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -143,15 +143,6 @@ pub async fn apply_act( // Call history is not a cache-validity proof. Reads can change, failures can // recover, and earlier results may no longer fit the prompt. Execute through // the owning command; authorization and operation-specific idempotency stay there. - // EVERY re-injection bound in this act comes from her LIVE served window, never a - // constant — an unknown window folds NOTHING rather than inventing a number - // ([[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]]). - // WM clips inside its OWN record path (it owns its truncation), so it needs the live - // window too — pushed from here, the seam that has the cycle. Re-pushed every act so a - // lane relaunch at a different `-c` is picked up without a restart. - if let Some((_, w)) = cycle.model_loadout() { - body.working_memory.set_served_window(w); - } let ctx = crate::cognition::tool_executor::ToolExecutionContext { persona_id: body.persona_id, persona_name: body.persona_name.clone(), @@ -398,14 +389,14 @@ pub async fn apply_act( // handle and the executor decodes it once from the full value. if verdict.running() { if let Some(handle) = projected.and_then(|v| v.dispatch_handle) { + // Her command whole, as she wrote it: this label is what her view shows for the + // handle, and a cut command reads as a different one. let label: String = call .input .get("command") .and_then(|v| v.as_str()) .unwrap_or(call.name.as_str()) // label only — the handle is the key - .chars() - .take(80) - .collect(); + .to_owned(); body.working_memory.record_dispatch_event( handle, &format!("{}: {label}", call.name), @@ -471,19 +462,7 @@ pub async fn apply_act( // The human OBJECT of the act: the first extracted path (reads, // writes, edits), else the shell command head, else empty — // honest-thin, never dumped raw JSON args. - let summary = obs - .output - .paths - .first() - .map(|p| p.display().to_string()) - .or_else(|| { - obs.call - .input - .get("command") - .and_then(|c| c.as_str()) - .map(|c| c.chars().take(80).collect::()) - }) - .unwrap_or_default(); + let summary = act_object(obs); let update = crate::cognition::mind_events::PersonaActUpdate { act_id: Uuid::new_v4(), room_id, @@ -532,19 +511,7 @@ pub async fn apply_act( lines.push(crate::cognition::presence_glyph::said_line(said.trim())); } lines.extend(acts.iter().map(|obs| { - let object = obs - .output - .paths - .first() - .map(|p| p.display().to_string()) - .or_else(|| { - obs.call - .input - .get("command") - .and_then(|c| c.as_str()) - .map(|c| c.chars().take(80).collect::()) - }) - .unwrap_or_default(); + let object = act_object(obs); crate::cognition::presence_glyph::act_line( &obs.call.name, &object, @@ -836,3 +803,15 @@ mod tests { ); } } + +/// The human object of an act, for the clients' act line and presence glyph: its first extracted +/// path (a read, a write, an edit), else its shell command, else empty, never raw JSON arguments. +/// Whole: how much of it a client shows is that client's rendering, not a cut made here. +fn act_object(obs: &Observation) -> String { + obs.output + .paths + .first() + .map(|p| p.display().to_string()) + .or_else(|| obs.call.input.get("command").and_then(|c| c.as_str()).map(str::to_owned)) + .unwrap_or_default() // unwrap_or_default: an act with no path and no command has no object +} diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index cdd63e740d..15cc663c56 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -76,7 +76,7 @@ pub mod test_support { } /// Body that shares a specific working-memory buffer — so a test can wire the - /// SAME buffer into a `WorkingMemoryFaculty` on the cycle and watch the + /// SAME buffer into her view's sources and watch the /// perception of the persona's own hands flow act→memory→next-tick perception /// (the proprioception channel that replaced the deleted world-state fold). pub fn body_with_wm( @@ -335,7 +335,7 @@ pub mod test_support { /// canonical act→observe arc the driver exists to run. /// /// It perceives its own hands through the working-memory proprioception channel - /// (the `WorkingMemoryFaculty` stamps each act `[action #n]`), NOT the deleted + /// (her trail stamps each act `[action #n]`), NOT the deleted /// world-state fold. It remembers the highest action stamp it has already spoken /// about (`responded_through`) so that across SEPARATE concerns — where the /// volatile buffer still carries the prior concern's action — it re-awakens and @@ -345,14 +345,46 @@ pub mod test_support { pub struct ActThenSpeak { pub responded_through: std::sync::atomic::AtomicU64, pub admission_open: Option>, + /// The working memory her view reads, when the test wires one (`perceived_with`). + pub memory: Option>, } impl ActThenSpeak { pub fn new() -> Self { Self { responded_through: std::sync::atomic::AtomicU64::new(0), admission_open: None, + memory: None, } } + + /// Perceive her own acts the way her view gives them, from `memory`. + pub fn with_memory(mut self, memory: Arc) -> Self { + self.memory = Some(memory); + self + } + } + + /// What a fixture deliberation perceives, as production's does: the broadcast, plus (when + /// wired) what her view gives her from working memory, which is her settled acts' results + /// (the actions source), the newest result riding whole after her view, and her trail. + pub fn perceived_with(ws: &Workspace, memory: Option<&crate::cognition::working_memory::WorkingMemory>) -> String { + let mut perceived = ws.perceived(); + if let Some(memory) = memory { + let (acts, _) = memory.action_renderings(); + for act in acts { + perceived.push('\n'); + perceived.push_str(&act.full); + } + if let Some(newest) = memory.pinned_active_result_block() { + perceived.push('\n'); + perceived.push_str(&newest); + } + for line in memory.recent() { + perceived.push('\n'); + perceived.push_str(&line); + } + } + perceived } /// Highest `[action #N]` stamp present in the assembled perception, 0 if none. pub fn latest_action_seq(perceived: &str) -> u64 { @@ -380,7 +412,7 @@ pub mod test_support { } use std::sync::atomic::Ordering; - let latest = latest_action_seq(&ws.perceived()); + let latest = latest_action_seq(&perceived_with(ws, self.memory.as_deref())); if latest > self.responded_through.load(Ordering::Relaxed) { self.responded_through.store(latest, Ordering::Relaxed); Some(Contribution::verdict( diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index ee549c78c6..6088445bc6 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -263,8 +263,14 @@ impl Observation { /// #205 KV-stability invariant. `intent` is batch-level (one per `apply_act` /// call, shared by every act in the batch), so it is passed rather than /// stored per-`Observation`. + /// The call as she made it, `name(args)`: its arguments by shape, never by size + /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part + /// and its ledger line. + pub(crate) fn call_line(&self) -> String { + format!("{}({})", self.call.name, render_call_args(&self.call.input)) + } + pub fn render_recency(&self, intent: &str) -> String { - let args = render_call_args(&self.call.input); // The intent rides the result as a ONE-LINE reason, its first line: a shape rule, // never a size, and never the whole monologue. // Measured 2026-09-04: one result header carried 2,902 chars of intent @@ -276,13 +282,7 @@ impl Observation { } else { format!(" because {}", intent_label(intent)) }; - format!( - "{}({}){}\nResult:\n{}\n\n", - self.call.name, - args, - because, - self.body_text().trim(), - ) + format!("{}{}\nResult:\n{}\n\n", self.call_line(), because, self.body_text().trim()) } /// This act as one part of a batch receipt's summary level: the recency header (its name and @@ -290,11 +290,10 @@ impl Observation { /// summary reads what the receipt shows her, never the executor's serialized JSON, where a /// read's numbered lines are escaped and no code level is found (Codex on #5424). pub(crate) fn render_summary_part(&self, level: impl Fn(&str) -> Option) -> String { - let args = render_call_args(&self.call.input); let body = self.body_text(); let body = body.trim(); let shown = level(body).unwrap_or_else(|| body.to_owned()); // unwrap_or: a body with no smaller level is its own summary - format!("{}({})\nResult:\n{}\n\n", self.call.name, args, shown) + format!("{}\nResult:\n{}\n\n", self.call_line(), shown) } /// The RECALL-channel rendering: the COLLAPSED reference the Episodic engram diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 1a6c487a32..17ef06bb10 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -242,7 +242,7 @@ std::future::pending().await } } - let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc], Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc], Arc::new(SalienceArbiter)); let mut conversation = ScriptedConversation::new(); conversation.prime().await.unwrap(); // unwrap: test fixture let room = crate::identity::ActivityRoom::from_uuid(uuid::Uuid::new_v4()).unwrap(); // unwrap: a fresh uuid is a valid room diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs index a2814d7589..04347369f2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs @@ -36,7 +36,7 @@ async fn a_batch_whose_effect_mark_is_refused_never_reaches_the_executor() { result_content: "4\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused)))); let outcome = apply_act(&cycle, &[tool_call()], "check the math", Uuid::new_v4(), &chain, None, None).await; @@ -69,7 +69,7 @@ async fn a_sentinel_only_batch_is_no_effect_and_takes_no_mark() { seen_context: Arc::new(Mutex::new(None)), result_content: "reported".into(), }); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused)))); let cut = ToolCall { @@ -95,7 +95,7 @@ async fn apply_act_scopes_to_the_room_and_observes_the_result() { result_content: "4\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); @@ -235,7 +235,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() { let exec = Arc::new(FoldedRunningExecutor { handle }); let the_body = body(exec.clone(), admission()); let wm = the_body.working_memory.clone(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(the_body); let call = ToolCall { @@ -292,7 +292,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() { // live in the faculty now lives here (the faculty only emits the Act verdict). #[tokio::test] async fn apply_act_without_hands_abstains() { - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)); assert!( matches!( apply_act( @@ -317,7 +317,7 @@ async fn apply_act_without_hands_abstains() { #[tokio::test] async fn apply_act_abstains_when_the_hand_fails() { let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(FailingExecutor), adm.clone())); assert!( matches!( @@ -394,21 +394,21 @@ async fn an_acts_calls_carry_the_generation_that_issued_them() { ]; let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) }; - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(exec.clone()), admission())); let stamped = apply_act(&cycle, &two_submits, "submit both", Uuid::new_v4(), &ActChain::new(), None, Some("gen-1".into())).await; assert!(matches!(stamped, ActOutcome::Acted { .. }), "{stamped:?}"); assert_eq!(seen_of(&exec), vec![Some("gen-1".to_string()); 2], "one act, one issuing generation, every call"); let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) }; - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(Arc::new(exec.clone()), admission())); let unstamped = apply_act(&cycle, &[tool_call()], "no generation", Uuid::new_v4(), &ActChain::new(), None, None).await; assert!(matches!(unstamped, ActOutcome::Acted { .. }), "{unstamped:?}"); assert_eq!(seen_of(&exec), vec![None], "no generation, no stamp"); let plain = Arc::new(RecordingExecutor { seen_context: Arc::new(Mutex::new(None)), result_content: "ok".into() }); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8).with_acting(body(plain, admission())); + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)).with_acting(body(plain, admission())); let acted = apply_act(&cycle, &[tool_call()], "cannot stamp", Uuid::new_v4(), &ActChain::new(), None, Some("gen-2".into())).await; assert!(matches!(acted, ActOutcome::Acted { .. }), "hands that cannot stamp still act: {acted:?}"); } diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs index 3d053b847f..ef5b0296f5 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs @@ -22,7 +22,7 @@ async fn a_settle_chain_links_each_act_caused_by_its_predecessor() { result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); let chain = ActChain::new(); @@ -80,7 +80,7 @@ async fn a_chain_rooted_in_its_trigger_links_the_first_act_to_what_caused_the_tu result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let room = Uuid::new_v4(); @@ -114,7 +114,7 @@ async fn an_unrooted_chain_leaves_its_first_act_honestly_unlinked() { result_content: "ok\n".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let chain = ActChain::rooted_in(&crate::cognition::workspace::Cause::Ambient); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs index 689aeeb1ed..145842b41e 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs @@ -3,14 +3,12 @@ use super::*; use crate::cognition::workspace::TurnFraming; use crate::cognition::workspace::WorkspaceCycle; -use crate::cognition::workspace::Faculty; use crate::cognition::workspace::SalienceArbiter; use crate::ai::types::ToolCall; use uuid::Uuid; use std::sync::Arc; use std::sync::Mutex; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; // what this catches: c5910be2 — an ordinary room drive could not see coaching // until it settled. Inject through the conversation DURING a real tool action, @@ -114,7 +112,6 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { .with_request_recorder(Arc::clone(&recorded)), ); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); let adm = admission(); let body = body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm)); let persona = body.persona_id; @@ -135,11 +132,9 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { }]); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm)) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body); let task = "Review the original src/lib.rs change and report a reproducible defect."; diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 5d5999546d..23a3f44e65 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -3,7 +3,6 @@ use super::*; use crate::ai::types::ToolCall; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; use crate::cognition::workspace::Contribution; use crate::cognition::workspace::Decision; use crate::cognition::workspace::Faculty; @@ -60,11 +59,9 @@ async fn drive_to_settle_acts_then_settles_on_speak() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(ActThenSpeak::new()), + Arc::new(ActThenSpeak::new().with_memory(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -84,7 +81,7 @@ async fn drive_to_settle_acts_then_settles_on_speak() { // Refusal after a real act retains its observed work and cannot replay input. #[tokio::test] async fn acted_then_capacity_refused_retains_work_without_replay() { - struct ActThenRefuse; + struct ActThenRefuse(Arc); #[async_trait] impl Faculty for ActThenRefuse { fn id(&self) -> FacultyId { @@ -94,7 +91,7 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { true } async fn contribute(&self, ws: &Workspace) -> Option { - if latest_action_seq(&ws.perceived()) > 0 { + if latest_action_seq(&crate::cognition::act_observe::test_support::perceived_with(ws, Some(&self.0))) > 0 { Some(Contribution::prompt_capacity_refused( crate::cognition::workspace::PromptCapacityError { required_tokens: 8192, @@ -117,11 +114,9 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { let exec = Arc::new(ScriptedExecutor::new(["real observed result"])); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm.clone())), - Arc::new(ActThenRefuse), + Arc::new(ActThenRefuse(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), wm)); let outcome = drive_to_settle(&cycle, "perform the task", 8, TurnFraming::ambient()).await; @@ -165,7 +160,7 @@ async fn capacity_refusal_leaves_the_driver_once_with_typed_custody() { } } let faculty = Arc::new(Refusing(std::sync::atomic::AtomicUsize::new(0))); - let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter), 8); + let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter)); let outcome = drive_to_settle(&cycle, "keep the complete input", 8, TurnFraming::ambient()).await; assert_eq!(faculty.0.load(std::sync::atomic::Ordering::SeqCst), 1); @@ -201,11 +196,9 @@ async fn a_zero_change_speak_reperceives_up_to_the_narration_budget_when_the_wor }); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::clone(&speaker) as Arc, ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm))); @@ -248,11 +241,9 @@ async fn an_ordinary_turn_still_settles_on_the_first_speak() { }); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::clone(&speaker) as Arc, ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm))); @@ -326,7 +317,6 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body(exec.clone(), adm.clone())); @@ -361,7 +351,6 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body(exec2, admission())); let ambient = drive_to_settle(&cycle2, "look around", 20, TurnFraming::ambient()).await; @@ -392,7 +381,6 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(the_body); drive_to_settle( @@ -433,7 +421,6 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { ticks: Mutex::new(0), })], Arc::new(SalienceArbiter), - 8, ) .with_acting(body2); drive_to_settle(&cycle2, "look around", 6, TurnFraming::ambient()).await; @@ -456,7 +443,7 @@ async fn drive_to_settle_returns_unsettled_act_when_budget_exhausted() { result_content: "...".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let outcome = drive_to_settle(&cycle, "go", 2, TurnFraming::ambient()).await; @@ -491,7 +478,7 @@ async fn repeated_calls_respect_the_callers_budget() { ), ] { let exec = Arc::new(ScriptedExecutor::new(results)); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let outcome = drive_to_settle(&cycle, "go", 6, TurnFraming::ambient()).await; assert_eq!(outcome.acts, expected_acts); @@ -508,7 +495,7 @@ async fn fixed_point_requires_available_finished_result_evidence() { use super::super::perception::batch_evidence; use crate::sdk_codegen::{ActVerdict, ToolVerdict}; let exec = Arc::new(ScriptedExecutor::new(["result"])); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec, admission())); let mut call = tool_call(); let mut acts = acts_of(apply_act( @@ -549,7 +536,7 @@ async fn settle_step_defers_the_act_without_executing_when_may_act_is_false() { result_content: "...".into(), }); let adm = admission(); - let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(vec![Arc::new(AlwaysAct)], Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), adm.clone())); let (deferred, _, _) = settle_step( diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs index fea5a8df86..9c988f5e5a 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs @@ -16,7 +16,6 @@ use async_trait::async_trait; use std::sync::Arc; use std::sync::Mutex; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; /// A deliberation faculty that is a small *investigator*: its next move is a /// pure function of what it has DISCOVERED so far (the observations folded @@ -27,7 +26,7 @@ use crate::cognition::working_memory::WorkingMemoryFaculty; /// accumulated MEMORY CONTENT, which is the whole point: the hands change /// the mind. (A test stand-in for the model, exactly like `ActThenSpeak`; /// it proves the cycle's cross-tick plumbing, not production cognition.) -struct Investigator; +struct Investigator(Arc); #[async_trait] impl Faculty for Investigator { fn id(&self) -> FacultyId { @@ -41,7 +40,7 @@ impl Faculty for Investigator { // working-memory render of its own recent acts (proprioception), // where each act-observation head carries the executor's result tokens // (ENTRY=…/CALLS=…). Not the raw burst, not the deleted fold. - let perceived = ws.perceived(); + let perceived = crate::cognition::act_observe::test_support::perceived_with(ws, Some(&self.0)); let after = |key: &str| -> Option { perceived .split(key) @@ -105,11 +104,9 @@ async fn the_hands_change_the_mind_across_a_multi_act_investigation() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(Investigator), + Arc::new(Investigator(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -186,7 +183,7 @@ async fn repeated_reads_and_scoped_discovery_reach_the_executor() { "old", "edited", "new", "missing", "available", "schema one", "schema two", "tree one", "tree two", ]).with_error_at(4)); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body(exec.clone(), admission())); let room = Uuid::new_v4(); let chain = ActChain::new(); @@ -216,7 +213,7 @@ async fn repeated_reads_and_scoped_discovery_reach_the_executor() { async fn repeated_request_keeps_current_room_and_returns_fresh_evidence() { let exec = Arc::new(ScriptedExecutor::new(["room-a content", "room-b content"])); let wm = Arc::new(WorkingMemory::new(3)); - let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8) + let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)) .with_acting(body_with_wm(exec.clone(), admission(), wm.clone())); let rooms = [Uuid::new_v4(), Uuid::new_v4()]; for (i, room) in rooms.into_iter().enumerate() { @@ -267,11 +264,9 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let wm = Arc::new(WorkingMemory::new(3)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(ActThenSpeak::new()), + Arc::new(ActThenSpeak::new().with_memory(Arc::clone(&wm))), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), adm.clone(), Arc::clone(&wm))); @@ -344,7 +339,6 @@ async fn spoken_narrated_action_records_unfulfilled_promise() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(promise)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step( @@ -367,7 +361,6 @@ async fn spoken_narrated_action_records_unfulfilled_promise() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText("the answer is 4, plainly.")) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step( @@ -411,7 +404,6 @@ async fn a_near_identical_copy_of_a_peers_line_is_a_pass_not_a_post() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(peer_line)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step(&cycle, burst(), true, TurnFraming::ambient(), Situation::FreshContext, &ActChain::new()).await; @@ -426,7 +418,6 @@ async fn a_near_identical_copy_of_a_peers_line_is_a_pass_not_a_post() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText(own)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step(&cycle2, burst(), true, TurnFraming::ambient(), Situation::FreshContext, &ActChain::new()).await; @@ -459,7 +450,6 @@ async fn fenced_content_over_unkept_promises_records_unverified_artifact() { let cycle = WorkspaceCycle::new( vec![Arc::new(SpeaksText(confabulated)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), Arc::clone(&wm))); let (step, _, _) = settle_step( @@ -488,7 +478,6 @@ async fn fenced_content_over_unkept_promises_records_unverified_artifact() { let cycle2 = WorkspaceCycle::new( vec![Arc::new(SpeaksText(confabulated)) as Arc], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec2, admission(), Arc::clone(&wm2))); let (step2, _, _) = settle_step( diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index a946bb53ca..aa4e1bfb6b 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -162,9 +162,7 @@ fn a_thought_renders_the_same_whatever_the_served_window() { let render = |memory: &WorkingMemory| { Thoughts { memory, persona: uuid::Uuid::nil() }.items().into_iter().map(|item| item.full().text.clone()).collect::>() }; - memory.set_served_window(32_768); let narrow = render(&memory); - memory.set_served_window(131_072); assert_eq!(render(&memory), narrow, "the window changed and the thought's rendering did not"); } diff --git a/core/continuum-cognition/src/cognition/deliberation_prompt.rs b/core/continuum-cognition/src/cognition/deliberation_prompt.rs index 5cf69a1cf8..b929aa921d 100644 --- a/core/continuum-cognition/src/cognition/deliberation_prompt.rs +++ b/core/continuum-cognition/src/cognition/deliberation_prompt.rs @@ -147,7 +147,6 @@ pub(super) enum PromptChurn { /// The churn class of a grounding block, by the source id it renders under. pub(super) fn churn_of(faculty: &str) -> PromptChurn { - use crate::cognition::working_memory::WM_FACULTY_ID; use crate::cognition::workspace::FacultyId; use crate::cognition::faculty_ids::{ ACTIVE_WORK, AIRC, AWARENESS, ENGRAMS, MEDIA_PERCEPTION, MISSION, ROOM_BOARD, @@ -166,7 +165,7 @@ pub(super) fn churn_of(faculty: &str) -> PromptChurn { | WALL | ACTIVE_WORK => PromptChurn::Board, ROOM_BOARD => PromptChurn::Claims, - ENGRAMS | AIRC | WM_FACULTY_ID => PromptChurn::Turn, + ENGRAMS | AIRC => PromptChurn::Turn, // The strip changes with every event in any of her rooms: turn churn, after the // standing and board blocks, so her awareness never displaces the cached prefix. AWARENESS => PromptChurn::Turn, @@ -954,7 +953,6 @@ mod tests { let mut live = vec!["room-kanban", "room-wall", "roster", "active-work"]; live.sort_by(|a, b| stable_prefix_order(a, b)); assert_eq!(live, ["active-work", "room-wall", "roster", "room-kanban"]); - assert_eq!(churn_of("working-memory"), PromptChurn::Turn); assert_eq!(churn_of("engrams"), PromptChurn::Turn); assert_eq!(churn_of("media-perception"), PromptChurn::Standing); } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 9d6a932a44..55e4ee28f9 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -195,7 +195,7 @@ pub struct LlmDeliberationFaculty { /// Where this faculty records its chain-of-thought after a verdict, so the /// persona can resume its train of thought next turn (the /// [`WorkingMemory`](crate::cognition::working_memory::WorkingMemory) - /// `WorkingMemoryFaculty` reads). `None` → reasoning is dropped (the prior + /// her view's thoughts source reads). `None` → reasoning is dropped (the prior /// behavior). Only the suppressed-thinking default makes `reasoning` empty, so /// this self-activates exactly when thinking is on. working_memory: Option>, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs index f330599492..b56b6cccb1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs @@ -213,8 +213,8 @@ impl LlmDeliberationFaculty { // today: the working-memory faculty). // PINNED just-executed result (#392, run-18057-f1). The full result of the act // she just ran is appended DIRECTLY from the shared working-memory buffer as the - // newest trailing turn — deliberately NOT routed as a faculty bid. As part of the - // working-memory contribution at `WORKING_MEMORY_SALIENCE` it competed in + // newest trailing turn — deliberately NOT routed as a faculty bid. As part of a + // working-memory faculty's bid (that faculty is deleted) it competed in // `arbiter.focus()` top-k and was evicted whole under capacity pressure, so the // persona generated blind to her own grep/read output (the 0-byte SWE-bench patch). // Reading it here puts no attention pass between the hands and the mind. @@ -246,12 +246,11 @@ impl LlmDeliberationFaculty { // between acts (`deliberation_prompt::stable_prefix_order`). Outside the view a block // sat behind it, and every act's append landed before it and re-sent it: on the M5 // (2026-10-21 19:56Z) Aris re-prefilled 49k chars from `[workspace-map]` on. Her - // working-memory bid is not one of them: her thoughts and actions are their own streams. + // thoughts and actions are not among them: they are their own streams in her view. let mut pieces: Vec<&Contribution> = ws .broadcast .iter() .filter(|c| c.decision.is_none() && c.fault.is_none() && c.trailing) - .filter(|c| c.faculty.as_str() != crate::cognition::working_memory::WM_FACULTY_ID) .filter(|c| !c.content.trim().is_empty()) .collect(); pieces.sort_by(|a, b| deliberation_prompt::stable_prefix_order(a.faculty.as_str(), b.faculty.as_str())); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs index 411b50bc22..953427498a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs @@ -15,7 +15,6 @@ async fn a_huge_legacy_result_arrives_reduced_with_its_handle_never_refused() { let window = 8_192u32; let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let huge: String = (0..6_000).map(|i| format!("line {i} of a very large tool result\n")).collect(); wm.record_receipt_typed(&[], &huge, None, ResultCustody::Whole { handle: "legacy-evidence".into() }); @@ -84,7 +83,6 @@ mod the_newest_result_over_her_window { /// The same, served at `window`. fn faculty_at(content: &str, adapter: Arc, window: u32) -> LlmDeliberationFaculty { let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let room = Uuid::new_v4(); let call = ToolCall { id: "call-aris".into(), name: "work/submission".into(), input: json!({ "include_staged_evidence": true }) }; wm.record_native_action_statement("Reading the staged evidence for my submission.", room, std::slice::from_ref(&call)); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs index dcea4123ea..d9babd71c6 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs @@ -774,7 +774,6 @@ fn a_budget_too_small_for_even_one_unit_emits_no_header_at_all() { #[test] fn the_results_ring_renders_before_churning_grounding() { let wm = Arc::new(crate::cognition::working_memory::WorkingMemory::new(3)); - wm.set_served_window(32_768); let custody = |h: &str| crate::ai::types::ResultCustody::Whole { handle: h.into() }; wm.record_receipt_typed(&[], "RING-ENTRY older result", None, custody("1111111111111111")); wm.record_receipt_typed(&[], "the newest result", None, custody("2222222222222222")); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs index eeff1a31f8..3c228b28d9 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs @@ -6,8 +6,8 @@ use super::*; // recorded no-deliverable facts. Fit the actual projection after that eviction. #[tokio::test] async fn substrate_notices_survive_attention_and_history_pressure_once() { - use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; - use crate::cognition::workspace::{Arbiter, Faculty, FocusContext, SalienceArbiter, Situation}; + use crate::cognition::working_memory::WorkingMemory; + use crate::cognition::workspace::{Arbiter, FocusContext, SalienceArbiter, Situation}; let wm = Arc::new(WorkingMemory::new(8)); wm.record("weighing the next step"); wm.record_fact("[no-deliverable] No workspace change yet."); @@ -26,23 +26,18 @@ async fn substrate_notices_survive_attention_and_history_pressure_once() { Uuid::new_v4(), "T", "You are T.", Arc::new(HeuristicInferenceAdapter::new()), ).with_working_memory(Arc::clone(&wm)); let mut ws = Workspace::new("continue the existing task"); - let memory = WorkingMemoryFaculty::new(Arc::clone(&wm)).contribute(&ws).await.unwrap(); - assert!(!memory.content.contains("[no-deliverable]"), "notices have one projection"); - let mut bids: Vec<_> = (0..6).map(|i| Contribution::context( + let bids: Vec<_> = (0..6).map(|i| Contribution::context( FacultyId::Custom(format!("source-{i}")), "standing context", 0.9, "fixture", )).collect(); - bids.push(memory.clone()); - ws.broadcast = SalienceArbiter.focus(bids, 6, &FocusContext { + ws.broadcast = SalienceArbiter.focus(bids, &FocusContext { world_state: &ws.world_state, situation: Situation::PostAction, }); - assert!(!ws.broadcast.iter().any(|c| c.faculty == memory.faculty)); // Her notices ride her view as a required source (`context_streams::notices`): the // allocation grants their floor before anything optional, and the final fit never cuts // her view. So through the production path, at every window from 256 tokens (too small) to roomy, // a prompt that would be sent carries each notice exactly once, and a window that // cannot hold them says so instead of sending a prompt without them. - for keep_memory in [false, true] { - if keep_memory { ws.broadcast.push(memory.clone()); } + { let (mut sent, mut refused) = (0, 0); for window in (256u32..=65_536).step_by(2_048) { let view = faculty.prompt_view_within(&ws, window); @@ -71,10 +66,9 @@ async fn substrate_notices_survive_attention_and_history_pressure_once() { wm.end_of_work_turn(); assert!(wm.notice_details().is_empty(), "detail and reference share expiry"); assert!(!wm.notices().iter().any(|notice| notice.contains("work/get"))); - // A notice-only memory has no optional thought bid at all. + // A notice-only memory still fits: its notices are her view's required source. let only = Arc::new(WorkingMemory::new(8)); only.record_fact("[no-deliverable] No workspace change yet."); - assert!(WorkingMemoryFaculty::new(Arc::clone(&only)).contribute(&ws).await.is_none()); let faculty = LlmDeliberationFaculty::new( Uuid::new_v4(), "T", "You are T.", Arc::new(HeuristicInferenceAdapter::new()), ).with_working_memory(only); @@ -153,7 +147,6 @@ async fn own_history_preserves_corrections_at_each_inference_step() { let persona = Uuid::new_v4(); let calls = Arc::new(Mutex::new(Vec::new())); let wm = Arc::new(WorkingMemory::new(16)); - wm.set_served_window(32_768); let faculty = LlmDeliberationFaculty::new( persona, "Anwen", diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs index 5424a15045..f3fa0313e7 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs @@ -465,7 +465,7 @@ async fn directed_turn_withholds_the_silence_escape() { // "This message names you". Exercise the real framing -> cycle -> // prompt seam on both admission and act-result re-perception. let identity = PersonaIdentity::new(faculty.persona_id, "Kimi"); - let cycle = WorkspaceCycle::new(vec![], Arc::new(SalienceArbiter), 4); + let cycle = WorkspaceCycle::new(vec![], Arc::new(SalienceArbiter)); for (text, human, expected_attention, expected_class) in [ ( "Joel here — which card do you hold?", diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs index ec262ad005..0e3b3edc39 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs @@ -22,7 +22,6 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { None, )])); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let result = format!( "src/lib.rs:42: concrete_review_target\n{{\"payload\":\"{}\"}}\nclaimable_now: 29\ntotal_on_board: 43", "x".repeat(window as usize * 2), @@ -218,7 +217,6 @@ async fn an_8192_window_keeps_required_content_under_a_large_measured_need() { let need = reg.need_of(persona).expect("measured"); assert!(need.total() > window, "the fixture's need exceeds the whole seat"); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let result = format!("src/schema.rs:7: accounts_table_defined\n{}", "column detail ".repeat(40)); wm.record_receipt(&result); let adapter = Arc::new(ScriptedAdapter::new(vec![make_response( @@ -286,7 +284,6 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { )); let registry = WorkingSetRegistry::new(); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let oversized = "payload ".repeat(window as usize); let mut ws = if oversized_part == 0 { Workspace::new(&oversized) diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index ef9c8369a0..ef1bc389fb 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -33,7 +33,7 @@ use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalE use super::llm_deliberation_faculty::LlmDeliberationFaculty; use super::rag_source_faculty::{RagSourceFaculty, SaliencePolicy}; use super::recall_faculty::RecallFaculty; -use super::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use super::working_memory::WorkingMemory; use super::workspace::{ActingBody, Faculty, SituationFocusArbiter, WorkspaceCycle}; use crate::ai::adapter::AIProviderAdapter; use crate::cognition::admission_state::AdmissionState; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs index 7da34b6291..696807d25c 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs @@ -1,10 +1,5 @@ use super::*; -/// Default bounded workspace capacity — the finite attention "spotlight". Enough -/// for recall + world-model + affect + roster context to coexist; the arbiter -/// keeps it bounded so cost stays O(capacity) no matter how many faculties bid. -pub const DEFAULT_WORKSPACE_CAPACITY: usize = 6; - /// Everything needed to assemble one persona's continuous mind. The `admission` /// is the persona's UNIFIED hippocampus (shared with the admission pipeline and /// spanning all the persona's rooms); the `adapter` is the shared model backend, @@ -22,8 +17,6 @@ pub struct PersonaBrainConfig { pub system_prompt: String, pub admission: Arc, pub adapter: Arc, - /// Bounded workspace capacity; `None` → [`DEFAULT_WORKSPACE_CAPACITY`]. - pub capacity: Option, /// Grounding RagSources lifted into perception-tier faculties via /// [`RagSourceFaculty`] (the migration bridge — see its module doc). Each is /// paired with a [`SaliencePolicy`]: roster + doctrine are `StandingFraming` @@ -308,8 +301,8 @@ pub(super) fn assemble_workspace_cycle( }); // Working memory: the persona's recent chain-of-thought AND the head of what its // hands just did, carried forward across turns. The deliberator WRITES its - // reasoning here after each verdict; the perception-tier `WorkingMemoryFaculty` - // (pushed below) READS it into the next tick — so the persona resumes its train of + // reasoning here after each verdict; her view's thoughts and actions sources READ it + // into the next tick — so the persona resumes its train of // thought instead of re-deriving it cold. Volatile scratchpad, distinct from the // long-term engram store; self-activates only when thinking is enabled (suppressed // turns record nothing). Built HERE (before recall) so recall can share it in and @@ -427,13 +420,6 @@ pub(super) fn assemble_workspace_cycle( faculties.push(Arc::new(recall)); } - // The perception-tier reader of the working memory built above: each tick it bids - // the recent reasoning + act heads into the workspace so the deliberator conditions - // on them. (The buffer itself is created before recall so recall can share it in.) - faculties.push(Arc::new(WorkingMemoryFaculty::new(Arc::clone( - &working_memory, - )))); - // Bridge each grounding source into a perception-tier faculty under its // salience policy. Standing-framing (roster, doctrine) bids at a high floor so // the top-k arbiter never evicts the room's rules under attention pressure. @@ -561,13 +547,9 @@ pub(super) fn assemble_workspace_cycle( let cycle = WorkspaceCycle::new( faculties, - // Situation-aware focuser: on every act→observe re-perception (`PostAction`) - // it drops the standing SOCIAL re-grounding so the tool result + working - // memory + recall own the window — the persona goes lean and code-first while - // heads-down, and fuller-grounded on a fresh ask. This is the wire behind - // "straightforward for whatever their current state requires." + // Situation-aware focuser: every bid is forwarded, ordered by salience; how much + // of each she sees is her view's one allocation. Arc::new(SituationFocusArbiter::new()), - cfg.capacity.unwrap_or(DEFAULT_WORKSPACE_CAPACITY), ) .with_genome(genome) .with_decoding(decoding) @@ -591,7 +573,7 @@ pub(super) fn assemble_workspace_cycle( persona_name: persona_name_for_body, executor, admission: admission_for_body, - // Same buffer the perception-tier WorkingMemoryFaculty reads — the + // Same buffer her view's sources read — the // organism records each act here so the mind perceives its own hands // next tick (proprioception), even when the result is a dedup no-op in // long-term memory and thinking is suppressed. diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs index b49dc23bc8..59670f2fa5 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs @@ -136,7 +136,6 @@ use super::*; system_prompt: "You are Ivar, an engineer on the grid.".to_string(), admission: seed_admission(1_000_000_000), adapter: Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -411,7 +410,6 @@ use super::*; let cycle = WorkspaceCycle::new( faculties, Arc::new(SalienceArbiter), - DEFAULT_WORKSPACE_CAPACITY, ) .with_capture(sink.clone()); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 7af2838e13..ec36aff556 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -190,7 +190,6 @@ use super::*; // of a mind with no live working memory still protects it (Astra on acdfb010a). { let memory = WorkingMemory::new(8); - memory.set_served_window(16_384); let cap = 8_192; // a test body size; a shed below it collapses the older ones let saved = |handle: &str| crate::ai::types::ResultCustody::Whole { handle: handle.into() }; memory.record_receipt_typed(&[], &"c".repeat(cap / 2), None, saved("c011a75ed0000001")); diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs index 0aa0823870..aed446f872 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -514,7 +514,7 @@ ), Arc::new(SeesDoctrine), ]; - let ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 6) + let ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .run("is anyone going to merge this?") .await; @@ -621,7 +621,6 @@ let _ = WorkspaceCycle::new( faculties, Arc::new(SalienceArbiter), - DEFAULT_CAPACITY_FOR_TEST, ) .with_capture(sink.clone()) .run("anything urgent?") diff --git a/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs b/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs index 4309878d5c..24fda93939 100644 --- a/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs @@ -18,7 +18,6 @@ use super::*; let ws = WorkspaceCycle::new( faculties, Arc::new(super::super::super::workspace::SalienceArbiter), - 5, ) .with_capture(Arc::new(PrintingSink)) .run("teammate asks: where did we land on the deploy?") diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index 854a71a458..468128513b 100644 --- a/core/continuum-cognition/src/cognition/request_replay.rs +++ b/core/continuum-cognition/src/cognition/request_replay.rs @@ -484,7 +484,6 @@ mod tests { // A diagnostic changes only named historical pointers, never tool protocol or settings. let mut diagnostic = request.clone(); let wm = crate::cognition::working_memory::WorkingMemory::new(8); - wm.set_served_window(16_384); wm.record_receipt_typed(&[], "historical result", Some(room), crate::ai::types::ResultCustody::Whole { handle: "0123abcd".into() }); wm.record_receipt("current result"); diff --git a/core/continuum-cognition/src/cognition/should_respond_module.rs b/core/continuum-cognition/src/cognition/should_respond_module.rs index 5047fd3bad..a1e299c4dc 100644 --- a/core/continuum-cognition/src/cognition/should_respond_module.rs +++ b/core/continuum-cognition/src/cognition/should_respond_module.rs @@ -171,7 +171,6 @@ mod tests { system_prompt: "You are Ivar, an engineer on the grid.".to_string(), admission: seed_admission(1_000_000_000), adapter: Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 1962dff658..99026b550b 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -24,8 +24,8 @@ //! //! ## How it wires into the Workspace brain //! -//! - [`WorkingMemoryFaculty`] is a PERCEPTION-tier faculty: each tick it bids the -//! recent reasoning into the workspace so the phase-2 deliberator conditions on it. +//! - Her view's sources (`context_streams`: thoughts, actions) read it each act, so the +//! deliberator perceives her recent reasoning and her own acts as items of her view. //! - The deliberation faculty WRITES its reasoning here after producing a verdict //! (the thing that thinks records its thinking). Read at phase 1, written at phase //! 2 → next tick reads the updated buffer. That's the rolling working memory. @@ -38,14 +38,12 @@ //! helps, remember what you reasoned." No config flag needed. use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use uuid::Uuid; -use async_trait::async_trait; use parking_lot::Mutex; -use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; // How many recent steps to carry forward is NOT a constant. It is // `ContextBudget::WORKING_MEMORY_STEPS` — the COUNT sibling of the per-step SIZE bound @@ -76,10 +74,6 @@ use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; /// carrying two opposite meanings in one prompt. One token, one meaning. pub const WM_SETTLEMENT_PREFIX: &str = "[answered]"; -/// The faculty's bid salience. Same tier as retrieved grounding -/// (`RETRIEVED_SALIENCE` = 0.5): useful context that informs the decision but must -/// not outrank standing framing (roster/doctrine, 0.9) or a strong recall hit. -const WORKING_MEMORY_SALIENCE: f32 = 0.5; // The trail-head and latest-action bounds are NOT constants. They are fractions of this // mind's LIVE served context window, owned by `ContextBudget` — see @@ -92,7 +86,6 @@ use crate::cognition::act_observe::Observation; /// Her context view, the type her working memory checkpoints. pub(crate) type ContextView = continuum_context::view::View; -use crate::cognition::context_budget::ContextBudget; /// Clip a full action-result body to [`WM_ACTION_FULL_MAX_CHARS`] for prompt inclusion. /// Returns the body unchanged when it fits; otherwise a `char`-boundary-safe head plus @@ -115,10 +108,6 @@ pub fn collapse_thought(text: &str, keep: usize) -> String { format!("[{} earlier chars — my full thought, collapsed] …{tail}", total - keep) } -/// Max distinct dispatched (background) handles tracked at once. A persona with more than -/// this many sentinels/compiles/debuggers in flight is unusual; past the cap the -/// oldest-updated finished handle is evicted first (a still-running one is never dropped). -const MAX_DISPATCHED: usize = 16; /// Borrowed provenance already carried by the result ring. Displaying a result /// in another activity must not erase where it came from or which operation ran. @@ -202,14 +191,6 @@ struct DispatchedAction { seq: u64, } -/// A bounded, rolling buffer of the persona's recent reasoning. Cheap to clone the -/// `Arc`; shared between the writer (deliberation faculty) and the reader -/// (`WorkingMemoryFaculty`). `parking_lot::Mutex` — no poisoning, and every access -/// is a quick sync snapshot/push with no `.await` held across the lock. -/// The working-memory faculty's canonical id — the ONE string the contribution -/// carries and every consumer (stability ordering in the deliberation tail, -/// capture tooling) matches on. -pub(crate) const WM_FACULTY_ID: &str = "working-memory"; /// A keyed working-memory fact with a lifetime in work turns. #[derive(Debug, Clone)] @@ -220,6 +201,10 @@ struct TurnPinnedFact { detail: Option, } +/// A bounded, rolling buffer of the persona's recent reasoning. Cheap to clone the `Arc`; +/// written by the deliberation faculty and read by her view's sources (`context_streams`). +/// `parking_lot::Mutex` — no poisoning, and every access is a quick sync snapshot/push with no +/// `.await` held across the lock. #[derive(Debug)] pub struct WorkingMemory { /// Process-unique construction ordinal. It keys this mind's set of live spill handles @@ -249,7 +234,6 @@ pub struct WorkingMemory { /// bound below. `0` = not yet known (cold boot / mid-relaunch), which means NO clipping: /// the deliberation guard still trims the assembled prompt to the real `n_ctx`, so an /// unknown window must never be replaced with an invented one. - served_window: AtomicU32, entries: Mutex>, /// The acting root her receipts are stamped with (set at the work-turn /// rooting seam, cleared on restore). See [`WmEntry::scope`]. @@ -270,7 +254,7 @@ pub struct WorkingMemory { /// SAME recency channel as `last_action`, but keyed so concurrent sentinels/compiles/ /// debuggers stream in without clobbering each other. Fed by the completion/progress /// listener (`record_dispatch_event`); surfaced by the faculty so the mind perceives - /// "what I sent away, and where it's at" each heartbeat. Bounded by `MAX_DISPATCHED`. + /// "what I sent away, and where it's at" each heartbeat. A finished handle retires once she has answered a prompt that showed its end. dispatched: Mutex>, /// Monotonic stamp applied to ACTION entries. Two reasons: (1) it makes each /// recorded action a DISTINCT string even when the persona repeats the identical @@ -600,7 +584,7 @@ impl VolatileSnapshot { /// Every saved result this checkpoint still reaches; the persisted twin of what working /// memory publishes live, through the same log and the same rule. pub(crate) fn reachable_handles(&self) -> HashSet { - let log = action_log::ActionLog::from_records(self.action_records(), usize::MAX); + let log = action_log::ActionLog::from_records(self.action_records()); reachable_handles(log.receipt_keys(), &self.receipt_children, &self.open_views) } @@ -711,14 +695,11 @@ pub struct WmEntry { mod action_log; mod continuity; -mod faculty; mod ledger; mod perception; mod residency; pub use action_log::ActOutputRefusal; -pub use faculty::WorkingMemoryFaculty; -pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; pub(crate) use residency::{ResidentResults, ShedCandidate}; @@ -731,3 +712,32 @@ impl Drop for WorkingMemory { #[cfg(test)] mod tests; + +/// Background commands she sent away (sentinels, compiles, debuggers), streaming their +/// status back by handle: what is outstanding and what just finished, so she can pass a +/// handle to a follow-up command. `None` when nothing was dispatched. +pub(crate) fn render_dispatched(dispatched: &[(Uuid, String, String, DispatchStatus)]) -> Option { + if dispatched.is_empty() { + return None; + } + let lines = dispatched + .iter() + .map(|(h, label, latest, status)| { + let hs = h.to_string(); + let short = hs.get(..8).unwrap_or(hs.as_str()); + let tag = match status { + DispatchStatus::Running => "running", + DispatchStatus::Done => "done", + DispatchStatus::Failed => "failed", + }; + let tail = if latest.is_empty() { + String::new() + } else { + format!(": {latest}") + }; + format!("- #{short} {label} [{tag}]{tail}") + }) + .collect::>() + .join("\n"); + Some(format!("Commands you dispatched (background, by handle):\n{lines}")) +} diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index e37245f979..ad4d5af2ec 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -98,18 +98,17 @@ pub(super) struct ActionLog { } impl ActionLog { - /// A log from records in any order, bounded to `archive_chars` like a live one. - pub fn from_records(mut records: Vec, archive_chars: usize) -> Self { + /// A log from records in any order. Nothing here bounds it: a record keeps its line and its + /// handle for as long as her mind lives, and its body's RAM is the one memory owner's to + /// shed (`residency`), never a character cap. + pub fn from_records(mut records: Vec) -> Self { records.sort_by_key(|record| record.seq); records.dedup_by_key(|record| record.seq); - let mut log = Self { records: records.into() }; - log.prune(archive_chars); - log + Self { records: records.into() } } - pub fn push(&mut self, record: ActionRecord, archive_chars: usize) { + pub fn push(&mut self, record: ActionRecord) { self.records.push_back(record); - self.prune(archive_chars); } pub fn get(&self, seq: u64) -> Option<&ActionRecord> { @@ -139,22 +138,6 @@ impl ActionLog { pointers } - /// The newest ledger lines that fit `archive_chars`, oldest first; at least the newest. - pub fn archive(&self, archive_chars: usize) -> Vec<(&ActionRecord, &str)> { - let mut used = 0usize; - let mut kept: Vec<(&ActionRecord, &str)> = Vec::new(); - for (record, head) in self.records.iter().rev().filter_map(|r| r.head.as_deref().map(|h| (r, h))) { - let cost = head.chars().count() + 1; - if !kept.is_empty() && used + cost > archive_chars { - break; - } - used += cost; - kept.push((record, head)); - } - kept.reverse(); - kept - } - /// Every receipt whose dependencies must stay reachable: each retained result's key and /// every handle a record names. A body moved to its handle exists only on disk, so its /// handle is live for as long as its record is, however many pointers are newer. @@ -214,12 +197,4 @@ impl ActionLog { Collapsed { total } } - /// Drop the records nothing can reach any more: past the ledger's share, no body in RAM, - /// and no handle to reload one from. A record naming a handle stays, since its whole is - /// reachable through her view (`StoredWhole`) for as long as the record is. - fn prune(&mut self, archive_chars: usize) { - let keep: HashSet = self.archive(archive_chars).into_iter().map(|(record, _)| record.seq).collect(); - self.records - .retain(|record| record.result.is_some() || record.handle.is_some() || keep.contains(&record.seq)); - } } diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 1947e8cbea..4e6cc7460c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -183,12 +183,13 @@ impl WorkingMemory { // The log, projected into the wire shape older builds read (see // `VolatileSnapshot::action_records`), under one lock so a concurrent collapse // cannot move a record between the projections. - let archive_chars = self.budget().receipt_archive_chars(); let last_action = self.last_action.lock().clone(); let (archive, recent_results, result_scopes, pointers, records) = { let actions = self.actions.lock(); - let archive: Vec<(Option, String)> = - actions.archive(archive_chars).into_iter().map(|(r, head)| (r.room, head.to_owned())).collect(); + let archive: Vec<(Option, String)> = actions + .records() + .filter_map(|record| record.head.as_ref().map(|head| (record.room, head.clone()))) + .collect(); let recent_results: Vec<(u64, Option, String, String, Option)> = actions .retained() .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) @@ -298,11 +299,9 @@ impl WorkingMemory { e.pop_front(); } } - // Same re-clamp contract as `entries`: the log bounds itself to THIS life's share, and - // the collapse below folds results a bigger-window life held into pointers, never a - // silent deletion. - *self.actions.lock() = - action_log::ActionLog::from_records(records, self.budget().receipt_archive_chars()); + // The log is restored whole: what of its bodies stays in RAM is the one memory owner's + // to shed (`residency`), never a share of this life's window. + *self.actions.lock() = action_log::ActionLog::from_records(records); *self.last_action.lock() = snap.last_action; *self.receipt_children.lock() = snap.receipt_children; *self.view.lock() = snap.context_view; @@ -398,7 +397,6 @@ impl WorkingMemory { // hers to decide. let current = env!("CONTINUUM_BUILD_GIT_SHA"); if !snap.build_sha.is_empty() && snap.build_sha != current { - let short = |s: &str| s.chars().take(9).collect::(); // Same lifetime as [resumed]: the rebuild is news at the wake, not a // standing condition — after two turns her receipts on THIS build exist. self.pin_fact_for_turns("rebuilt", &format!( @@ -408,8 +406,8 @@ impl WorkingMemory { not re-read to check. Only the TOOLS may behave differently now: a tool that \ failed before may work on this build, worth re-trying rather than concluding \ from memory.", - short(&snap.build_sha), - short(current), + snap.build_sha, + current, ), 2); } } @@ -437,7 +435,9 @@ impl WorkingMemory { /// never inferred from an owner field — an expired claim still names its last holder, /// and a card in Review is absent from her live claims for a reason that is not a lapse. pub fn note_claim_gone(&self, card: uuid::Uuid, verdict: ClaimGone) { - let id8: String = card.simple().to_string().chars().take(8).collect(); + // Ids whole, as the verbs that take them read them: a prefix is a cut, and the board + // resolves either form (`continuum_base::id_resolve`). + let id = card.simple(); let edge = |ms: Option| { ms.and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64)) .map(|t| format!(" (lease edge {}Z)", t.format("%H:%M"))) @@ -448,26 +448,26 @@ impl WorkingMemory { // Each sentence is what the board SHOWS NOW — never a story about how it got // there (the wake did not watch the lease lapse or the transfer happen). ClaimGone::HeldBy { peer, expires_at_ms } => format!( - "[claim] card {id8} is NO LONGER YOURS: your checkpoint had you working it, and \ + "[claim] card {id} is NO LONGER YOURS: your checkpoint had you working it, and \ the board now shows {} holding it{}. {untouched} Do not resume as its holder — \ work/get {card} shows its state; take it back with work/claim only when it \ reads claimable.", - peer.simple().to_string().chars().take(8).collect::(), + peer.simple(), edge(expires_at_ms), ), ClaimGone::Lapsed { expired_at_ms } => format!( - "[claim] card {id8} is NO LONGER YOURS: your checkpoint had you working it, and \ + "[claim] card {id} is NO LONGER YOURS: your checkpoint had you working it, and \ the board now shows it unheld — the last lease on it ran out{} and nobody holds \ it. {untouched} work/claim {card} takes it back, then continue from your ledger.", edge(expired_at_ms), ), ClaimGone::MovedOn { state } => format!( - "[claim] card {id8} is no longer in your hands: the board now shows it in {state} \ + "[claim] card {id} is no longer in your hands: the board now shows it in {state} \ — that is the card's life advancing, not a lapse. {untouched} Nothing to \ re-claim; work/get {card} shows where it stands." ), ClaimGone::Unknown => format!( - "[claim] your checkpoint had you working card {id8}, but no board you stand in \ + "[claim] your checkpoint had you working card {id}, but no board you stand in \ shows it now, so nothing can be said about who holds it. {untouched} \ work/get {card} before assuming it is yours or free." ), diff --git a/core/continuum-cognition/src/cognition/working_memory/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/faculty.rs deleted file mode 100644 index 899f17bd41..0000000000 --- a/core/continuum-cognition/src/cognition/working_memory/faculty.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! The `Faculty` that bids working memory into the workspace. - -use super::*; - -/// Render the already-budgeted trail in order. A later settlement may correct -/// or repeat an earlier report; similarity cannot replace that event's content. -fn render_trail(recent: &[String]) -> String { - let mut out = String::new(); - for entry in recent { - if !out.is_empty() { - out.push('\n'); - } - out.push_str("- "); - out.push_str(entry); - } - out -} - -/// Background commands she sent away (sentinels, compiles, debuggers), streaming their -/// status back by handle: what is outstanding and what just finished, so she can pass a -/// handle to a follow-up command. `None` when nothing was dispatched. -pub(crate) fn render_dispatched(dispatched: &[(Uuid, String, String, DispatchStatus)]) -> Option { - if dispatched.is_empty() { - return None; - } - let lines = dispatched - .iter() - .map(|(h, label, latest, status)| { - let hs = h.to_string(); - let short = hs.get(..8).unwrap_or(hs.as_str()); - let tag = match status { - DispatchStatus::Running => "running", - DispatchStatus::Done => "done", - DispatchStatus::Failed => "failed", - }; - let tail = if latest.is_empty() { - String::new() - } else { - format!(": {latest}") - }; - format!("- #{short} {label} [{tag}]{tail}") - }) - .collect::>() - .join("\n"); - Some(format!("Commands you dispatched (background, by handle):\n{lines}")) -} - -/// Perception-tier faculty that bids the persona's recent reasoning into the -/// workspace — so the deliberator can resume its own train of thought rather than -/// re-deriving it cold each turn. Abstains when there's nothing recorded (first -/// turns, or thinking suppressed). -pub struct WorkingMemoryFaculty { - memory: Arc, -} - -impl WorkingMemoryFaculty { - pub fn new(memory: Arc) -> Self { - Self { memory } - } - - fn faculty_id() -> FacultyId { - FacultyId::Custom(WM_FACULTY_ID.to_string()) - } -} - -#[async_trait] -impl Faculty for WorkingMemoryFaculty { - fn id(&self) -> FacultyId { - Self::faculty_id() - } - - // Perception tier (default): reacts to the raw world-state, bidding the recent - // reasoning into phase 1 so the deliberator conditions on it in phase 2. - async fn contribute(&self, ws: &Workspace) -> Option { - let mut entries = self.memory.recent_entries(); - // Public action statements use their room-scoped assistant projection, - // never the optional interior-thought bid. Facts use the required notice projection. - entries.retain(|entry| !matches!(entry.kind, WmKind::ActionStatement { .. } | WmKind::Fact)); - let dispatched = self.memory.dispatched_snapshot(); - if entries.is_empty() && dispatched.is_empty() { - return None; - } - // Render BY KIND (the recent_entries contract; PERCEPTION-FACTS.md). - // Substrate Facts ([resumed]/[context]/[repetition]…) are the SYSTEM's - // second-person notices posted into her window — NOT her thoughts. - // Glass-boxed 2026-08-01 (#264 fourth finding): lumping them into the - // "my interior state" block made the model resolve the voice conflict - // by converting the notice to first person and SPEAKING it — 2f50b223 - // posted "My session was interrupted under a minute ago and my memory - // restored; nothing was in flight" verbatim into the room, a - // scaffold-echo of the [resumed] briefing. Same bug class as the - // second-person header this comment block's sibling above fixed - // (#264 third finding): provenance framing must match the voice. - // Each entry CLIPPED to the same head bound receipts already use — - // measured 2026-08-24: ONE unclipped reasoning trace (a 16k-token - // think emission) made this block 70,086 chars (~20k tokens), the - // single dominant mass of an 85k prompt. The full text stays in the - // entry (the pinned path and recall read it); only the TRAIL RENDER - // is bounded, with the collapse idiom naming what was elided. - // A WORK turn perceives its own recent past compactly: the newest few - // reasonings/receipts in full and the older ones as one count line — - // collapsed, not clipped. Measured 2026-09-05: this block was 14–23 KB of - // a ~22k-token prompt on every act, with zero KV reuse; a card's work turn - // needs what she just did, not the morning. - let mut collapsed_older = 0usize; - if ws.workspace_deliverable { - const WORK_TURN_RECENT_KEEP: usize = 3; - let non_fact: Vec = entries - .iter() - .enumerate() - .filter(|(_, e)| !matches!(e.kind, WmKind::Fact)) - .map(|(i, _)| i) - .collect(); - if non_fact.len() > WORK_TURN_RECENT_KEEP { - let drop: std::collections::HashSet = non_fact - [..non_fact.len() - WORK_TURN_RECENT_KEEP] - .iter() - .copied() - .collect(); - collapsed_older = drop.len(); - entries = entries - .into_iter() - .enumerate() - .filter(|(i, _)| !drop.contains(i)) - .map(|(_, e)| e) - .collect(); - } - } - // Per-entry head in a WORK turn: 1,500 chars — past that a work act's - // reasoning is history, not state. - let head = if ws.workspace_deliverable { - self.memory.budget().trail_head_chars().min(1_500) - } else { - self.memory.budget().trail_head_chars() - }; - // A THOUGHT keeps its end (its decision); a receipt or settlement keeps its - // head, where its identity is (`[action #N]` and what was done). - let clip = |e: &WmEntry| -> String { - if matches!(e.kind, WmKind::Thought) { - return collapse_thought(&e.text, head); - } - let t = e.text.as_str(); - if t.chars().count() <= head { - t.to_string() - } else { - let kept: String = t.chars().take(head).collect(); - format!("{kept} …[{} more chars — my full thought, collapsed]", t.chars().count() - head) - } - }; - let recent: Vec = entries - .iter() - .map(clip) - .collect(); - // Render oldest-first, newest-LAST: position alone carries recency (the last - // line is the most recent thought), the universal chat-history convention. - // - // We deliberately do NOT prefix each trace with a relative "(turn -N)" label. - // That offset rewrites every act (what was -1 becomes -2 when a new trace - // appends), mutating the whole block from its first byte. Combined with this - // whole contribution now rendering as a TRAILING turn nearest generation - // (`Contribution::trailing`, #205) rather than inside the system message, the - // append-only formatting finally pays off: a settle-act appends its one new - // trace to the very end of the token stream, so the entire system prefix AND - // the prior conversation keep their KV cache and only the new tail re-prefills. - // (Before #205 this block sat in the system message, so appending a trace - // shifted every conversation token after it — the append-only property was - // defeated by position and ~4000 tokens re-prefilled per act.) Each trace - // already carries its own stable absolute marker (e.g. "[action #41]"); - // recency needs no per-act-mutating annotation. - let n = recent.len(); - let mut sections: Vec = Vec::new(); - // The append-only reasoning/action trail (may be empty if the only live content - // is dispatched background work). - if !recent.is_empty() { - sections.push(format!( - // First person, explicitly not-a-message (glass-boxed 2026-07-31, - // #264 third finding): this block rides a `user`-role turn, and the - // old second-person header — "Your recent thoughts and actions" — - // parsed as a PEER addressing her. Asha opened turn after turn with - // "Thank you for the summary of recent actions and thoughts", - // politely replying to her own interoception. Self-knowledge must - // never be phrased in another's voice. - "My own recent thoughts and actions (working memory — this is my \ - interior state, not a message from anyone):\n{}", - format!("{}{}", render_trail(&recent), if collapsed_older > 0 { format!("\n[{collapsed_older} earlier acts this session, collapsed — their receipts are still in my memory]") } else { String::new() }) - )); - } - // The FULL result of the most recent act is NO LONGER emitted here. It is the - // load-bearing content for the mind to act on what its hands fetched, and as part - // of THIS 0.5-salience bid it rode `arbiter.focus()` top-k and was silently evicted - // under capacity pressure (the run-18057-f1 0-byte patch). It is now PINNED by the - // message builder as its own durable trailing turn — see - // [`WorkingMemory::active_action_full`] and [`WorkingMemory::full_result_message`] - // — so no attention pass can drop it. - // This contribution keeps only the append-only trail + dispatched status, - // which are proprioceptive summary, not the just-fetched result. - // Substrate notices are projected by PerceptionFact independently of this bid. - // Background commands the mind sent away — sentinels, compiles, debuggers — - // streaming their status back by handle. The mind sees what's outstanding and what - // just finished, and can pass a handle to a follow-up command (cancel/query). Fresh - // each event, so it trails the stable prefix like the full-result block. - sections.extend(render_dispatched(&dispatched)); - Some( - Contribution::context( - Self::faculty_id(), - sections.join("\n\n"), - WORKING_MEMORY_SALIENCE, - format!( - "working memory: {n} trace(s), {} dispatched", - dispatched.len() - ), - ) - // Proprioception that grows each act — renders as a trailing turn nearest - // generation, never in the system message, so the KV prefix stays stable - // across a settle-act (#205). See [`Contribution::trailing`]. - .trailing(), - ) - } -} diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 253e6b9c94..f34c3bebdd 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -55,7 +55,6 @@ impl WorkingMemory { pinned: Mutex::new(Vec::new()), ended_pins: Mutex::new(Vec::new()), restored_acting_card: Mutex::new(None), - served_window: AtomicU32::new(0), entries: Mutex::new(VecDeque::new()), scope: Mutex::new(None), pending_emissions: Mutex::new(Vec::new()), @@ -100,26 +99,6 @@ impl WorkingMemory { .map(|e| e.peak_tokens).max().unwrap_or(0) } - /// Adopt the LIVE served context window (tokens) as the basis for every re-injection - /// bound. Pushed from the act→observe seam (`act_observe/apply.rs`) off the workspace - /// cycle's model binding, every act. Before the first act, or when the cycle carries - /// no loadout, [`Self::budget`] reads the serving truth instead of answering "no bound". - pub fn set_served_window(&self, tokens: u32) { - self.served_window.store(tokens, Ordering::Relaxed); - } - - /// The re-injection budget for this mind right now. Unknown window ⇒ no bounds. - pub fn budget(&self) -> ContextBudget { - match self.served_window.load(Ordering::Relaxed) { - // No pin yet (before the first act, or a cycle with no loadout): the serving - // truth, never "no bound". This arm was `ContextBudget::unknown()`. - 0 => ContextBudget::live(), - // The ring is STATE, not this turn's prompt: one audience for every turn, so its - // share is stable and it collapses only in bursts (see `from_window_for`). - w => ContextBudget::from_window_for(w, crate::inference::prefill_rate::Audience::Unattended), - } - } - /// Record a fingerprint (tool name + args) of the action the hands just took, and return /// how many times THIS exact call now appears in the recent window (including this one). /// `≥ 2` means the mind is re-issuing an identical call — proprioception the act→observe @@ -320,16 +299,18 @@ impl WorkingMemory { } // The record and the active slot publish together, so a concurrent publisher // cannot prune a not-yet-visible receipt. - let budget = self.budget(); let mut actions = self.actions.lock(); - *self.last_action.lock() = Some((seq, a.to_string())); + let previous = self.last_action.lock().replace((seq, a.to_string())); + if let Some((answered_since, _)) = previous { + self.retire_perceived_dispatches(answered_since); + } actions.push( action_log::ActionRecord { seq, room, scope: scope.clone(), operation: label, - head: Some(archive_head(seq, a, &acts, budget.trail_head_chars())), + head: Some(ledger_line(seq, a, &acts)), summary: result_summary(&tail, &acts), result: Some(tail), handle, @@ -337,18 +318,16 @@ impl WorkingMemory { stored_chars: None, received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, - budget.receipt_archive_chars(), ); } // No size cap here: the body stays in RAM until the one memory owner sheds // (`residency`). A cap at receipt was a hand-rigged number (`RESULTS_RESIDENT_CHARS`, // 1 << 20 chars) deciding what RAM could hold; the pressure monitor measures it. - // Head into the rolling recency trail: proprioception ("I did #n X") + the - // repeat-break signal. Truncation lives HERE now (one place), so callers pass the - // full result and never pre-truncate. Append-only + `#seq`-stamped keeps the + // Into the rolling recency trail: proprioception ("I did #n X") + the repeat-break + // signal, as the act's ledger line, never a cut of its result (goal 7: the result stays + // whole in its record and her view levels it). Append-only + `#seq`-stamped keeps the // trail's KV-cache prefix byte-stable across a settle-act. - let head: String = a.chars().take(self.budget().trail_head_chars()).collect(); - let text = format!("[action #{seq}] {head}"); + let text = ledger_line(seq, a, &acts); // Her tool head learns from every call, and a verb she found is loaded into the tail. let verbs: Vec = acts.iter().map(|act| act.call.name.clone()).collect(); let found = super::super::tool_head::found_by_finder(acts.iter().map(|act| &act.call)); @@ -387,11 +366,6 @@ impl WorkingMemory { self.instance } - pub fn receipt_archive(&self) -> Vec<(Option, String)> { - let archive_chars = self.budget().receipt_archive_chars(); - self.actions.lock().archive(archive_chars).into_iter().map(|(record, head)| (record.room, head.to_owned())).collect() - } - /// The TYPED acts still in the recency window, oldest → newest — the parallel /// channel to [`recent`](Self::recent)'s rendered strings. A consumer that used /// to grep the receipt prose for a verb / a path (`mutated_workspace`, @@ -424,47 +398,24 @@ impl WorkingMemory { } -/// An act's ledger line, `[action #n] ...`. COMPACT from the TYPED channel when there is one -/// (CAUSAL-MEMORY-GRAPH.md slice B): `name(args)` per call, never the receipt's first line, -/// which drags the full `because ` clause (~250 chars) and starved a 1,808-act -/// citizen down to 1-2 visible acts (measured live 2026-08-15). The reasoning lives in the -/// act's engram, reachable through the CausedBy edge. A legacy text receipt (no typed acts) -/// keeps its first line, cut to the trail head's share. -fn archive_head(seq: u64, result: &str, acts: &[Observation], trail_head_chars: usize) -> String { +/// An act's ledger line, `[action #n] ...`, one rendering for her trail and her record. COMPACT +/// from the TYPED channel when there is one (CAUSAL-MEMORY-GRAPH.md slice B): `name(args)` per +/// call, never the receipt's first line, which drags the full `because ` clause (~250 +/// chars) and starved a 1,808-act citizen down to 1-2 visible acts (measured live 2026-08-15). Its +/// arguments render by shape, never by size (`Observation::call_line`): a single-line value +/// whole, a body by its reference, so a value she reads is exactly what she sent or plainly not it +/// (card d624a9a1). A text receipt with no typed call renders whole: nothing here cuts. +fn ledger_line(seq: u64, result: &str, acts: &[Observation]) -> String { if acts.is_empty() { - let head: String = result.lines().take(1).flat_map(str::chars).take(trail_head_chars).collect(); - return format!("[action #{seq}] {head}"); + return format!("[action #{seq}] {}", result.trim()); } let calls: Vec = acts .iter() - .map(|o| format!("{}({})", o.call.name, call_args(&o.call.input, trail_head_chars))) + .map(Observation::call_line) .collect(); format!("[action #{seq}] {}", calls.join("; ")) } -/// One call's arguments for its ledger line, with no value ever cut (card d624a9a1). The line -/// cut the JSON at 48 chars, so `{"file_path":"/home/resident/.continuum/citizens/pe` read as a -/// real path: a 1.5B resident copied it, was refused three times, and looped (IntelMac, -/// 2026-10-22; goal 7). A string value longer than `value_chars`, or spanning lines (a write's -/// body), becomes an explicit `` marker; every other value renders whole. So a value -/// she reads is either exactly what she sent or plainly not it, never a plausible prefix. -pub(super) fn call_args(input: &serde_json::Value, value_chars: usize) -> String { - fn shown(value: &serde_json::Value, value_chars: usize) -> serde_json::Value { - use serde_json::Value; - match value { - Value::String(text) if text.contains('\n') || text.chars().count() > value_chars => { - Value::String(format!("<{} chars>", text.chars().count())) - } - Value::Array(items) => Value::Array(items.iter().map(|item| shown(item, value_chars)).collect()), - Value::Object(fields) => { - Value::Object(fields.iter().map(|(key, item)| (key.clone(), shown(item, value_chars))).collect()) - } - other => other.clone(), - } - } - shown(input, value_chars).to_string() -} - /// One operation's summary level by its typed verb (`continuum_context::levels`): a read's /// outline, else (and for any other output) its head and tail. `None` when the text is its own /// best summary. The one owner of that choice, for a receipt in the ring and for the newest diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index b170280cd7..60f219c143 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -173,9 +173,9 @@ impl WorkingMemory { /// The FULL result of the just-executed act, ready to render as a **pinned** /// trailing prompt block — the run-18057-f1 fix. /// - /// This block used to live INSIDE the working-memory faculty's single - /// [`Contribution`](crate::cognition::workspace::Contribution) at - /// `WORKING_MEMORY_SALIENCE` (0.5). That bid competes in `arbiter.focus()` + /// This block used to live INSIDE a working-memory faculty's single + /// [`Contribution`](crate::cognition::workspace::Contribution) bid (deleted with that + /// faculty, card c537d687). That bid competed in `arbiter.focus()` /// top-k, so under capacity pressure the whole contribution — the just-fetched /// grep/read result included — was truncated, and the persona generated blind /// to what her own hands had returned (the 0-byte SWE-bench patch). The message @@ -189,9 +189,6 @@ impl WorkingMemory { /// would add nothing. pub fn pinned_active_result_block(&self) -> Option { let (seq, full) = self.active_action_full()?; - if full.chars().count() <= self.budget().trail_head_chars() { - return None; - } // Shown as the producer handed it over: whole, or its handle. A consumer never // re-cuts (CONTENT-TRAVELS-BY-HANDLE.md, forbidden moves). Some(self.full_result_message(seq, &full)) @@ -353,8 +350,9 @@ impl WorkingMemory { /// `Done`/`Failed` marks it. The mind perceives outstanding + freshly-finished handles /// via the faculty next heartbeat, so it can act on a result the moment it lands /// without ever blocking. `label` is set once (first event) and preserved across - /// updates. Bounded by `MAX_DISPATCHED` — a finished handle is evicted before a - /// running one when over cap ([[act-results-need-a-recency-channel-not-semantic-recall]]). + /// updates. A finished handle retires once she has answered a prompt that showed its end + /// ([`Self::retire_perceived_dispatches`]); a running one never does + /// ([[act-results-need-a-recency-channel-not-semantic-recall]]). pub fn record_dispatch_event( &self, handle: Uuid, @@ -373,17 +371,17 @@ impl WorkingMemory { entry.latest = content.trim().to_string(); entry.status = status; entry.seq = seq; - if m.len() > MAX_DISPATCHED { - // Evict the oldest-updated FINISHED handle; never drop one still running. - if let Some(victim) = m - .iter() - .filter(|(_, a)| a.status != DispatchStatus::Running) - .min_by_key(|(_, a)| a.seq) - .map(|(h, _)| *h) - { - m.remove(&victim); - } - } + } + + /// Retire every finished handle whose end she has perceived: one whose terminal event is + /// older than `answered_since`, the sequence of an act recorded before the act now being + /// recorded. That act's prompt was built after it, and her view renders every dispatched + /// handle, so the end was in a prompt she answered. Acts and dispatch events share one + /// sequence, so this is an ordering, never a count; a running handle never retires. + pub(super) fn retire_perceived_dispatches(&self, answered_since: u64) { + self.dispatched + .lock() + .retain(|_, action| action.status == DispatchStatus::Running || action.seq >= answered_since); } /// The label of a dispatched handle THIS persona owns, or `None` if the handle isn't diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 4521544006..48b9426212 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs @@ -1,6 +1,11 @@ #![cfg(test)] use super::*; +/// Her ledger lines in order, with the room each act was for: every record's line. +fn ledger(wm: &WorkingMemory) -> Vec<(Option, String)> { + wm.actions.lock().records().filter_map(|record| record.head.clone().map(|head| (record.room, head))).collect() +} + // what this catches: one act kept as three copies that disagree. The results ring, the // steps ledger and the collapsed-pointer index each evicted on their own rule, so an act // could be a full result in one, gone from another and a pointer in the third. Here every @@ -9,7 +14,6 @@ use super::*; #[test] fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; // A short first line per result: that line is the ledger's, the body the ring's. wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); @@ -18,8 +22,8 @@ fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { } wm.record_settlement("done", None); shed(&wm, cap / 2); - let ledger: Vec = wm.receipt_archive().into_iter().map(|(_, head)| head).collect(); - assert!(ledger.first().is_some_and(|head| head.starts_with("[action #1]")), "{ledger:?}"); + let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); + assert!(lines.first().is_some_and(|head| head.starts_with("[action #1]")), "{lines:?}"); let ring = wm.recent_results_messages().join("\n"); assert!(ring.contains("[result #1; room unrecorded; operation unrecorded; output handle: tool/output first-handle — collapsed]"), "{ring}"); assert!(!ring.contains(&"a".repeat(cap / 2)), "its whole result left the ring"); @@ -39,10 +43,9 @@ fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { let reachable = legacy.reachable_handles(); assert!(reachable.contains("h7") && reachable.contains("h8"), "{reachable:?}"); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.restore(legacy); - let ledger: Vec = wm.receipt_archive().into_iter().map(|(_, head)| head).collect(); - assert_eq!(ledger, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); + let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); + assert_eq!(lines, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); let ring = wm.recent_results_messages().join("\n"); // Its pointer keeps the exact text the older build wrote: operation and all. assert!(ring.contains("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]"), "{ring}"); @@ -56,7 +59,6 @@ fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { #[test] fn a_restart_keeps_every_act_as_she_read_it() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.set_scope(Some("/work/foo".into())); let room = Uuid::new_v4(); let cap = 2 * BODY; @@ -71,14 +73,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { let pointers = |memory: &WorkingMemory| -> Vec { memory.recent_results_messages().into_iter().filter(|m| m.starts_with("Older results")).collect() }; - let (index, ledger) = (pointers(&wm), wm.receipt_archive()); + let (index, lines) = (pointers(&wm), ledger(&wm)); assert!(index.join("\n").contains("workspace foo — collapsed]"), "precondition: a collapsed pointer with its workspace: {index:?}"); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.set_scope(Some("/work/foo".into())); restored.restore(wm.snapshot()); assert_eq!(pointers(&restored), index); - assert_eq!(restored.receipt_archive(), ledger); + assert_eq!(ledger(&restored), lines); } // what this catches: a rollback to the build before the log restoring her blank. The @@ -86,7 +87,6 @@ fn a_restart_keeps_every_act_as_she_read_it() { #[test] fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); for act in 2..=5 { @@ -103,19 +103,18 @@ fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { // what this catches (card d624a9a1): an act's line cutting an argument mid-value. A cut path // reads as a real one, and a small model copies it and loops (IntelMac 2026-10-22: a cut -// '.../citizens/pe' became three refused reads). Short values render whole, a long or -// multi-line string becomes an explicit size marker, and no rendered value is a cut prefix of -// what was sent. +// '.../citizens/pe' became three refused reads). Her recorded line shows a single-line value +// whole however long, a multi-line body by its reference, and never a cut prefix of either. #[test] fn an_acts_arguments_are_whole_or_plainly_elided_never_cut() { let path = "/home/resident/.continuum/citizens/peers/cf6b4df6-ab13-4fd8-81fb-bcb115215468/workspace/src/ipc/mod.rs"; let body = "fn main() {}\n".repeat(200); - let args = serde_json::json!({"file_path": path, "content": body, "lines": [1, 40], "nested": {"mode": "append"}}); - let line = crate::cognition::working_memory::ledger::call_args(&args, path.chars().count()); - assert!(line.contains(path), "a path within the budget renders whole: {line}"); - assert!(line.contains(&format!("<{} chars>", body.chars().count())), "a multi-line body is a marker: {line}"); - assert!(line.contains("[1,40]") && line.contains("\"mode\":\"append\""), "{line}"); - let tight = crate::cognition::working_memory::ledger::call_args(&args, 10); - assert!(tight.contains(&format!("<{} chars>", path.chars().count())), "a path over budget is a marker, not a prefix: {tight}"); - assert!(!tight.contains("/home/resident/"), "no prefix of the path survives: {tight}"); + let mut act = crate::cognition::act_observe::test_support::act("code/write", Some(path)); + act.call.input = serde_json::json!({"file_path": path, "content": body, "lines": [1, 40]}); + let wm = WorkingMemory::new(8); + wm.record_receipt_typed(&[act], "wrote", None, crate::ai::types::ResultCustody::Unsaved); + let (_, line) = ledger(&wm).pop().expect("test: the act's line"); + assert!(line.contains(path), "a path renders whole however long: {line}"); + assert!(!line.contains("fn main() {}"), "a multi-line body is referenced, not repeated: {line}"); + assert!(line.contains("[1,40]"), "{line}"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index c8c475bba7..792b13ed68 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -7,13 +7,11 @@ use super::*; // replaces the prior. This is why a persona reading a 130-line file can now answer about // the whole file instead of looping on the doc-comment head. #[tokio::test] -async fn latest_action_returns_full_result_trail_keeps_head() { +async fn latest_action_returns_full_result_trail_keeps_its_call_line() { let wm = Arc::new(WorkingMemory::new(8)); - // Truncation bounds are fractions of a LIVE window now; an unknown-window memory - // is unbounded by contract, so a clipping test must declare the window it measures. - wm.set_served_window(16_384); - let big = format!("line0\n{}", "x".repeat(5_000)); // > WM_ACTION_HEAD_CHARS - wm.record_receipt(&big); + let big = format!("line0\n{}", "x".repeat(5_000)); + let read = crate::cognition::act_observe::test_support::act("code/read", Some("src/a.rs")); + wm.record_receipt_typed(&[read], &big, None, crate::ai::types::ResultCustody::Unsaved); // The full result is available whole. let (seq, full) = wm.last_action_full().expect("latest act kept"); @@ -23,14 +21,10 @@ async fn latest_action_returns_full_result_trail_keeps_head() { "the mind gets the WHOLE result, not a truncated stub" ); - // The rolling trail carries only the head (KV-stable proprioception). + // The rolling trail carries the act's call line, never a cut of its result: what she did, + // stable across acts (KV-stable proprioception); the result is whole in its record. let trail = wm.recent(); - assert_eq!(trail.len(), 1); - assert!(trail[0].starts_with("[action #1]")); - assert!( - trail[0].chars().count() < big.chars().count(), - "trail entry is head-truncated, not the whole result" - ); + assert_eq!(trail, ["[action #1] code/read(file_path=src/a.rs)"]); // The full result is PINNED by the message builder (#392) as its own durable // trailing block — it is no longer part of the evictable faculty bid. @@ -59,8 +53,8 @@ async fn latest_action_returns_full_result_trail_keeps_head() { #[tokio::test] async fn the_pinned_result_is_what_the_producer_handed_over_never_re_cut() { let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(16_384); - let over_share = "z".repeat(wm.budget().latest_action_chars() + 4_000); + // Larger than any share of any served window a working memory used to cut to. + let over_share = "z".repeat(1 << 20); wm.record_receipt(&over_share); let pinned = wm .pinned_active_result_block() @@ -78,20 +72,12 @@ async fn full_result_drops_out_after_the_persona_settles_but_a_new_act_reactivat let wm = Arc::new(WorkingMemory::new(8)); // Truncation bounds are fractions of a LIVE window now; an unknown-window memory // is unbounded by contract, so a clipping test must declare the window it measures. - wm.set_served_window(16_384); let dump = format!("code/tree result\n{}", "n".repeat(3_000)); // > WM_ACTION_HEAD_CHARS wm.record_receipt(&dump); - // The proprioceptive trail head lives in the faculty contribution; the FULL result - // is the PINNED block the message builder appends (#392). This test spans both. - let faculty_trail = |wm: Arc| async move { - WorkingMemoryFaculty::new(wm) - .contribute(&Workspace::new("tick")) - .await - .expect("bids") - .content - .clone() - }; + // The proprioceptive trail line lives in her trail; the FULL result is the PINNED block + // the message builder appends (#392). This test spans both. + let trail = |wm: &WorkingMemory| wm.recent().join("\n"); // Active (acted, not yet spoken): the full result is present in the pinned block. assert!( @@ -112,7 +98,7 @@ async fn full_result_drops_out_after_the_persona_settles_but_a_new_act_reactivat "after settling, the 2k-token dump stops riding along the prompt (#139/#165)" ); assert!( - faculty_trail(wm.clone()).await.contains("[action #1]"), + trail(&wm).contains("[action #1]"), "but the proprioceptive trail head survives — the mind still knows it acted" ); @@ -175,13 +161,8 @@ async fn dispatched_commands_stream_back_by_handle() { assert_eq!(c.3, DispatchStatus::Done); assert_eq!(c.2, "0 errors, 0 warnings"); - // The faculty surfaces both dispatched handles to the mind. - let rendered = WorkingMemoryFaculty::new(wm.clone()) - .contribute(&Workspace::new("a fresh burst")) - .await - .expect("bids when dispatched work exists") - .content - .clone(); + // Her view's thoughts source surfaces both dispatched handles through this rendering. + let rendered = render_dispatched(&wm.dispatched_snapshot()).expect("dispatched work renders"); assert!( rendered.contains("Commands you dispatched"), "the mind sees its sentinels" @@ -196,6 +177,27 @@ async fn dispatched_commands_stream_back_by_handle() { ); } +// what this catches: a finished background handle held forever (the old 16-handle cap only +// evicted past a count) or dropped before she could see how it ended. It retires once she has +// answered a prompt built after its end (an act recorded after the act that followed it); a +// running handle never retires, however many acts pass. +#[test] +fn a_finished_dispatch_retires_once_she_has_answered_a_prompt_that_showed_its_end() { + let wm = WorkingMemory::new(8); + let (compile, sentinel) = (Uuid::from_u128(1), Uuid::from_u128(2)); + wm.record_dispatch_event(sentinel, "research task", "searching…", DispatchStatus::Running); + wm.record_dispatch_event(compile, "compile core", "0 errors", DispatchStatus::Done); + let handles = |wm: &WorkingMemory| wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect::>(); + wm.record_receipt("an act whose prompt may predate the compile's end"); + assert_eq!(handles(&wm).len(), 2, "the next act's prompt may not have shown it yet"); + wm.record_receipt("an act whose prompt was built after the compile ended"); + assert_eq!(handles(&wm), vec![sentinel], "its end was in a prompt she answered"); + for _ in 0..20 { + wm.record_receipt("more acts"); + } + assert_eq!(handles(&wm), vec![sentinel], "a running handle never retires"); +} + // what this catches: record/recent round-trips, blank reasoning is ignored, and // the buffer ROLLS at capacity (oldest dropped) — it's a scratchpad, not a log. #[test] diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index 55f8dd8d55..b96d895566 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -1,20 +1,6 @@ #![cfg(test)] use super::*; -/// what this catches: a mind with no pin yet answering "no bound" on its own. `budget()` -/// fell to `ContextBudget::unknown()` whenever `set_served_window` had not run (before -/// the first act after a restore, or a cycle with no loadout), and an unknown budget is -/// usize::MAX on every bound. A fresh mind answers what the serving truth answers. -#[test] -fn a_fresh_mind_budgets_against_the_serving_truth_not_an_unset_pin() { - let wm = WorkingMemory::new(8); - let live = ContextBudget::live(); - assert_eq!(wm.budget().is_known(), live.is_known()); - assert_eq!(wm.budget().recent_results_chars(), live.recent_results_chars()); - wm.set_served_window(16_384); - assert!(wm.budget().is_known(), "a pinned window is a known budget"); -} - // what this catches: her collapsed thought keeping the re-orientation and losing // the decision (Kimi, 2026-10-04: "keep the end"). The decision survives, the // marker still names the collapse for the framing-echo detector, short thoughts @@ -55,7 +41,6 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ // Result custody must obey the same scope even after entry-trail eviction, // a shed's collapse and checkpoint restoration. Storage remains intact. let results = WorkingMemory::new(2); - results.set_served_window(16_384); results.set_scope(Some("task-a".into())); let body_a = format!("task-a-only {}", "a".repeat(BODY)); results.record_receipt_typed(&[], &body_a, None, saved("scope-a-output")); @@ -118,7 +103,6 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { let file = std::path::PathBuf::from(format!("/spill/p/{handle}.log")); let live = |p: &std::path::Path| crate::cognition::tool_executor::spill::is_live(p); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[], &"a".repeat(cap / 2), None, saved(&handle)); assert!(live(&file), "referenced by the ring"); @@ -145,7 +129,6 @@ fn a_moved_body_s_handle_stays_live_behind_any_number_of_newer_pointers() { let handle = || format!("{:016x}", Uuid::new_v4().as_u128() as u64); let live = |h: &str| crate::cognition::tool_executor::spill::is_live(&std::path::PathBuf::from(format!("/spill/p/{h}.log"))); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let first = handle(); wm.record_receipt_typed(&[], &"f".repeat(BODY), None, saved(&first)); for _ in 0..30 { @@ -215,7 +198,6 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { }; let (receipt, children) = (id(), [id(), id()]); let wm = WorkingMemory::new(2); // two entries: the third receipt rolls the first out - wm.set_served_window(16_384); let cap = 2 * BODY; wm.record_receipt_typed(&[act(&children[0]), act(&children[1])], &"r".repeat(cap / 2), None, saved(&receipt)); for _ in 0..3 { @@ -314,7 +296,6 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { }; let file = std::path::PathBuf::from(format!("/spill/p/{call_handle}.log")); let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); wm.record_receipt_typed(&[act], "read it", None, ResultCustody::Unsaved); assert!( crate::cognition::tool_executor::spill::is_live(&file), @@ -332,7 +313,6 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { #[test] fn restore_keeps_every_resident_body_whatever_the_window() { let source = WorkingMemory::new(8); - source.set_served_window(65_536); for i in 0..4 { source.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(64 * BODY)), None, saved(&format!("restore-{i}"))); } @@ -346,7 +326,6 @@ fn restore_keeps_every_resident_body_whatever_the_window() { assert_eq!(entries(&unknown), held, "no window yet: nothing moves at restore"); assert_eq!(unknown.resident_result_bytes(), source.resident_result_bytes(), "every body restored resident"); let small = WorkingMemory::new(8); - small.set_served_window(16_384); small.restore(snapshot); assert_eq!(entries(&small), held, "a small window changes nothing her view is offered"); } @@ -358,7 +337,6 @@ fn restore_keeps_every_resident_body_whatever_the_window() { #[test] fn results_are_never_evicted_at_receipt_however_large_the_ring() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let chunk = 64 * BODY; for i in 0..40 { wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("ring-{i}"))); @@ -379,7 +357,6 @@ fn results_are_never_evicted_at_receipt_however_large_the_ring() { #[test] fn an_unsaved_result_keeps_its_bytes_through_a_shed_and_restore() { let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let cap = 2 * BODY; let unsaved = format!("UNSAVED {}", "u".repeat(cap / 2)); wm.record_receipt_typed(&[], &unsaved, None, crate::ai::types::ResultCustody::Unsaved); @@ -395,7 +372,6 @@ fn an_unsaved_result_keeps_its_bytes_through_a_shed_and_restore() { "the saved ones around it collapsed" ); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.restore(wm.snapshot()); assert!(whole(&restored), "and through restore"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs deleted file mode 100644 index 4456239a57..0000000000 --- a/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs +++ /dev/null @@ -1,88 +0,0 @@ -#![cfg(test)] -use super::*; - -// what this catches: the faculty ABSTAINS with no recorded reasoning (first -// turns / suppressed thinking) — it never bids empty noise into the workspace. -#[tokio::test] -async fn faculty_abstains_when_empty() { - let wm = Arc::new(WorkingMemory::new(3)); - let faculty = WorkingMemoryFaculty::new(wm); - let ws = Workspace::new("a fresh burst"); - assert!(faculty.contribute(&ws).await.is_none()); -} - -// what this catches: once reasoning is recorded, the faculty bids it as -// context at the working-memory salience tier — the reasoning the deliberator -// will see next tick. Newest is rendered LAST (positional recency). -#[tokio::test] -async fn faculty_bids_recent_reasoning_as_context() { - let wm = Arc::new(WorkingMemory::new(3)); - wm.record("I should check the room roster first."); - wm.record("Now I will read the latest message."); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let ws = Workspace::new("a fresh burst"); - let c = faculty.contribute(&ws).await.expect("bids when non-empty"); - assert_eq!(c.faculty, FacultyId::Custom("working-memory".to_string())); - assert!((c.salience - WORKING_MEMORY_SALIENCE).abs() < f32::EPSILON); - assert!(c.content.contains("check the room roster")); - // newest trace is LAST (position carries recency, no relative label). - let oldest_at = c.content.find("room roster").unwrap(); - let newest_at = c.content.find("latest message").unwrap(); - assert!(newest_at > oldest_at, "newest trace rendered last"); - assert!(c.decision.is_none(), "perception bid carries no decision"); -} - -// what this catches: the KV-cache-locality invariant this formatter exists to -// hold — appending a new trace must NOT rewrite the rendering of prior traces. -// (The old "(turn -N)" relative label broke this: every prior entry's offset -// shifted on each append, mutating the whole block from its first byte and -// forcing a full re-prefill of the dynamic tail every settle-act.) -#[tokio::test] -async fn prior_traces_render_byte_identical_after_append() { - let wm = Arc::new(WorkingMemory::new(8)); - wm.record("first"); - wm.record("second"); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let ws = Workspace::new("burst"); - let before = faculty.contribute(&ws).await.unwrap().content; - wm.record("third"); - let after = faculty.contribute(&ws).await.unwrap().content; - // the older render is a strict PREFIX of the newer one — pure append. - assert!( - after.starts_with(&before), - "appending a trace must leave prior traces byte-identical (cacheable prefix);\n before={before:?}\n after={after:?}" - ); -} - -// what this catches: #205 — the working-memory faculty's contribution is marked -// TRAILING, so the deliberation faculty renders it nearest generation as a -// conversation turn (not in the system message). That is what keeps the cacheable -// system prefix byte-stable across a settle-act instead of re-prefilling the whole -// tail. The proprioceptive content (its own thinking + the [action #n] receipt -// trail) is unchanged — only WHERE it lands moved. regression for #205 -#[tokio::test] -async fn working_memory_contribution_is_marked_trailing() { - let wm = Arc::new(WorkingMemory::new(8)); - wm.record("I should write the login form first, then style it."); - wm.record_receipt("I ran code/write({\"file_path\":\"login.html\"}) Result: ok, 812 bytes"); - let faculty = WorkingMemoryFaculty::new(Arc::clone(&wm)); - let c = faculty - .contribute(&Workspace::new("build a login form")) - .await - .expect("recent content → a contribution"); - assert!( - c.trailing, - "working-memory proprioception must render nearest generation, not in the system prefix (#205)" - ); - // Content is unchanged by the move — the mind still perceives its own hands. - assert!( - c.content.contains("write the login form first"), - "the reasoning trail survives: {}", - c.content - ); - assert!( - c.content.contains("[action #1]"), - "the action receipt survives — this faculty IS the proprioception channel: {}", - c.content - ); -} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index b834ea390b..856fa8a36d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -4,7 +4,6 @@ use super::*; mod action_log; mod actions; mod custody; -mod faculty; mod open_views; mod pins; mod provenance; diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs index 5c27bcb02d..a14f5f4616 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs @@ -62,7 +62,6 @@ fn record(wm: &WorkingMemory, act: Observation) { #[test] fn a_view_keeps_pre_read_intent_without_claiming_it_is_understanding() { let wm = WorkingMemory::new(3); - wm.set_served_window(46_848); record(&wm, read(1, 498, 498, None)); wm.annotate_open_views("each rule is a module with a predicate over SourceFile, registered in scan()"); let block = wm.open_views_block().expect("an open view renders"); @@ -152,7 +151,6 @@ fn a_view_in_a_checkout_her_hands_left_is_retired_from_her_view() { use continuum_context::view::{Claim, View}; let wm = WorkingMemory::new(3); - wm.set_served_window(46_848); wm.set_scope(Some("/checkouts/a".into())); record(&wm, read(1, 40, 498, None)); let views = crate::cognition::context_streams::open_views::OpenViews { memory: &wm, persona: uuid::Uuid::nil() }; diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 536ceedf1d..58c026d2b8 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -41,9 +41,10 @@ fn typed_receipt_threads_the_act_by_field_and_keeps_text_byte_stable() { legacy.record_receipt(rendered); assert_eq!( typed.recent(), - legacy.recent(), - "the rendered receipt text is byte-identical to the legacy string path (#205)" + ["[action #1] code/search(query=needle)"], + "the trail line is the act's call, stable however its result reads (#205)" ); + assert_eq!(typed.last_action_full().map(|(_, full)| full), Some(rendered.trim().to_owned()), "the result is whole in its record"); let active = typed .active_act() @@ -146,7 +147,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { status: ActStatus::Executed, }; let wm = WorkingMemory::new(8); - wm.set_served_window(16_384); let room_a = Uuid::new_v4(); let room_b = Uuid::new_v4(); wm.record_receipt_typed( @@ -194,7 +194,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { "the existing checkpoint tuple format must remain compatible" ); let restored = WorkingMemory::new(8); - restored.set_served_window(16_384); restored.restore(serde_json::from_value(encoded).expect("test: recorded snapshot decodes")); assert_eq!(restored.recent_results_messages(), messages); assert_eq!( @@ -220,7 +219,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { .map(|line| format!("{line}: complete source line with enough context to exceed the old per-entry share\n")) .collect::(); let memory = WorkingMemory::new(8); - memory.set_served_window(16_384); let mut read_observation = observation("read-274", "code/read", Some("read-274-output")); read_observation.output.result.content = read.clone(); memory.record_receipt_typed(&[read_observation], &read, Some(room_a), saved("read-274-output")); @@ -245,7 +243,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { memory.record_settlement("work remains on this card", None); assert_whole_or_handle(&memory); let restarted = WorkingMemory::new(8); - restarted.set_served_window(16_384); restarted.restore(memory.snapshot()); assert_whole_or_handle(&restarted); } @@ -274,48 +271,30 @@ fn legacy_full_result_without_metadata_stays_explicitly_unattributed() { // to empty via `#[serde(default)]` (the same contract as saved_at_ms/build_sha). // A grid-sync peer or a pre-deploy snapshot must never wedge the mind on restore. #[test] -// what this catches: the #414 deprivation regressing — receipts must survive -// the shared ring's churn via the receipts-only archive, the archive must stay -// within its window-derived CHAR share (never a bare count, never unbounded), -// and it must round-trip the volatile snapshot exactly as the ring does. The -// measured failure: a 2,863-act citizen whose window showed ONE act read her -// own starved history as "I have nothing to contribute". -fn receipt_archive_survives_ring_churn_and_roundtrips_the_snapshot() { +// what this catches: the #414 deprivation regressing — her acts must survive the shared ring's +// churn, every one of them kept in her record (no character share cuts the oldest: what of +// their bodies stays in RAM is the one memory owner's to shed), and the record must round-trip +// the volatile snapshot. The measured failure: a 2,863-act citizen whose window showed ONE act +// read her own starved history as "I have nothing to contribute". +fn her_acts_survive_ring_churn_and_roundtrip_the_snapshot() { let wm = WorkingMemory::new(2); - wm.set_served_window(16_384); + let lines = |wm: &WorkingMemory| -> Vec { wm.actions.lock().records().filter_map(|record| record.head.clone()).collect() }; wm.record_receipt("I ran code/shell(ls) Result: ok"); for i in 0..10 { wm.record_fact(&format!("chatty fact {i}")); } - assert!( - !wm.has_receipt(), - "precondition: the ring entry must age out under churn" - ); - let archive = wm.receipt_archive(); - assert_eq!(archive.len(), 1, "the archive must survive the churn"); - assert!(archive[0].1.contains("code/shell(ls)")); - - // Char-bound eviction: flood with receipts; the archive keeps its - // NEWEST within the share and never grows unbounded. + assert!(!wm.has_receipt(), "precondition: the ring entry must age out under churn"); + assert_eq!(lines(&wm).len(), 1, "her act survives the churn"); + assert!(lines(&wm)[0].contains("code/shell(ls)")); for i in 0..2000 { wm.record_receipt(&format!("I ran code/read(f{i}) Result: ok")); } - let archive = wm.receipt_archive(); - let cap = wm.budget().receipt_archive_chars(); - let total: usize = archive.iter().map(|(_, h)| h.chars().count() + 1).sum(); - assert!(total <= cap, "archive exceeded its share: {total} > {cap}"); - assert!( - archive.last().unwrap().1.contains("f1999"), - "eviction must drop oldest, keep newest: {:?}", - archive.last() - ); - - // Snapshot round-trip: the archive persists like the ring. - let snap = wm.snapshot(); + let kept = lines(&wm); + assert_eq!(kept.len(), 2001, "every act is kept, oldest first"); + assert!(kept.last().is_some_and(|line| line.contains("f1999")), "{:?}", kept.last()); let fresh = WorkingMemory::new(2); - fresh.set_served_window(16_384); - fresh.restore(snap); - assert_eq!(fresh.receipt_archive(), archive); + fresh.restore(wm.snapshot()); + assert_eq!(lines(&fresh), kept); } #[test] diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 18128e6eb7..83b2c3aaa7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -12,7 +12,6 @@ use super::*; fn recent_results_survive_subsequent_acts_and_stay_bounded() { let wm = WorkingMemory::new(8); // A known window, as the act→observe seam pins it before any receipt in production. - wm.set_served_window(16_384); record_saved(&wm, "[action] code/run(sol.rs) error[E0601]: `main` function not found"); record_saved(&wm, "[action] code/list() sol.rs sol2.rs"); record_saved(&wm, "[action] code/tree() workspace/"); @@ -55,18 +54,17 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { ); } -// what this catches: e731576c — actual settlement records must reach the -// memory contribution even when a one-word correction resembles an older -// answer, or a later answer repeats the original state. -#[tokio::test] -async fn settlement_trail_preserves_corrections_and_later_repeated_reports() { +// what this catches: e731576c — actual settlement records must be kept, in order and whole, +// even when a one-word correction resembles an older answer, or a later answer repeats the +// original state. +#[test] +fn settlement_trail_preserves_corrections_and_later_repeated_reports() { let passed = "I verified the candidate build and all regression tests passed \ after checking the shared workspace changes against the review requirements."; let failed = "I verified the candidate build and all regression tests failed \ after checking the shared workspace changes against the review requirements."; assert!(super::super::super::deliberation_budget::near_identical_substantial(passed, failed)); - let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); + let wm = WorkingMemory::new(8); wm.record_settlement(passed, None); wm.record_receipt("code/read found the regression"); wm.record_settlement(failed, None); @@ -81,27 +79,10 @@ async fn settlement_trail_preserves_corrections_and_later_repeated_reports() { &WmKind::Settlement ] ); - assert!(entries - .iter() - .all(|entry| entry.text.chars().count() <= wm.budget().trail_head_chars())); - let expected: Vec<_> = entries - .iter() - .map(|entry| format!("- {}", entry.text)) - .collect(); - let contribution = WorkingMemoryFaculty::new(wm) - .contribute(&Workspace::new("What changed in the latest review?")) - .await - .expect("test: recorded working memory contributes"); - let actual: Vec<_> = contribution - .content - .lines() - .filter(|line| line.starts_with("- ")) - .collect(); - assert_eq!( - actual, expected, - "the rendered trail must preserve every recorded entry in order" - ); - assert!(!contribution.content.contains("not re-shown")); + let texts: Vec<&str> = entries.iter().map(|entry| entry.text.as_str()).collect(); + assert!(texts[0].ends_with(passed), "the first report, whole: {}", texts[0]); + assert!(texts[2].ends_with(failed), "the correction, whole, though it resembles the first: {}", texts[2]); + assert!(texts[3].ends_with(passed), "the later repeat, kept as its own entry: {}", texts[3]); } // what this catches: loop-awareness — `note_action_fingerprint` counts repeats of the diff --git a/core/continuum-cognition/src/cognition/workspace/arbiter.rs b/core/continuum-cognition/src/cognition/workspace/arbiter.rs index b054daaf48..c43f9c231b 100644 --- a/core/continuum-cognition/src/cognition/workspace/arbiter.rs +++ b/core/continuum-cognition/src/cognition/workspace/arbiter.rs @@ -11,18 +11,14 @@ use super::*; /// intelligence lives in the faculties (and, later, a learned focuser); the /// arbiter only integrates and focuses it. pub trait Arbiter: Send + Sync { - /// Focus `candidates` down to what should enter the bounded workspace for - /// THIS tick's `ctx`. INPUT-side attention only — curates the context the - /// model attends to, never the model's output. - fn focus( - &self, - candidates: Vec, - capacity: usize, - ctx: &FocusContext<'_>, - ) -> Vec; + /// Order `candidates` for THIS tick's `ctx`. INPUT-side attention only — curates the + /// context the model attends to, never the model's output. It never cuts by a count: + /// every bid is forwarded, and how much of each she sees is her view's one allocation + /// (MIND-CONTEXT, ONE-BUDGET; a top-k spotlight was a cut outside it). + fn focus(&self, candidates: Vec, ctx: &FocusContext<'_>) -> Vec; } -/// Top-k by ML salience within the workspace's bounded capacity. +/// Every bid, ordered by ML salience. /// /// This is the **bootstrap** policy: pure exploitation, attention at temperature /// 0 — the highest-salience bids always win. It is *greedy*, so on its own it @@ -40,18 +36,8 @@ impl Arbiter for SalienceArbiter { /// Blind top-k by ML salience — ignores the situation (`_ctx`). It is the /// floor (outlier A): every richer, situation-aware focuser must beat THIS on /// the scoreboard to earn its latency. - fn focus( - &self, - mut candidates: Vec, - capacity: usize, - _ctx: &FocusContext<'_>, - ) -> Vec { - candidates.sort_by(|a, b| { - b.salience - .partial_cmp(&a.salience) - .unwrap_or(std::cmp::Ordering::Equal) - }); - candidates.truncate(capacity); + fn focus(&self, mut candidates: Vec, _ctx: &FocusContext<'_>) -> Vec { + candidates.sort_by(|a, b| b.salience.total_cmp(&a.salience)); candidates } } @@ -100,12 +86,7 @@ impl Default for SituationFocusArbiter { } impl Arbiter for SituationFocusArbiter { - fn focus( - &self, - candidates: Vec, - capacity: usize, - ctx: &FocusContext<'_>, - ) -> Vec { + fn focus(&self, candidates: Vec, ctx: &FocusContext<'_>) -> Vec { // `stable` MUST NOT DECIDE ATTENTION — its own contract says so. // // [`Contribution::stable`] is documented as "a SERIALIZATION-order property, @@ -135,7 +116,7 @@ impl Arbiter for SituationFocusArbiter { // Situation-weighted budgets per #167) — never a serialization flag borrowed as // an attention verdict. let _ = ctx.situation; - self.inner.focus(candidates, capacity, ctx) + self.inner.focus(candidates, ctx) } } @@ -216,8 +197,8 @@ pub struct ActingBody { /// (proprioception). Distinct from `admission` (long-term, content-deduped): an /// act must be perceptible NEXT tick even when its result is a dedup no-op in /// long-term memory, so the mind sees its own hands and doesn't re-issue the - /// identical act blind. Shared `Arc` with the perception-tier - /// [`WorkingMemoryFaculty`] (one buffer, written here, read there). + /// identical act blind. Shared `Arc` with her view's sources (`context_streams`: one + /// buffer, written here, read there). pub working_memory: Arc, } @@ -228,9 +209,6 @@ pub struct ActingBody { pub struct WorkspaceCycle { pub(super) faculties: Vec>, pub(super) arbiter: Arc, - /// Bound on how many contributions can hold the workspace at once — the - /// finite "spotlight" of attention. - pub(super) capacity: usize, /// Replay/logging seam — every tick is recorded here. Default `Noop` /// (zero hot-path cost); swap in a recording sink to make the mind a /// glass box for debugging, tuning, and test benches. diff --git a/core/continuum-cognition/src/cognition/workspace/cause.rs b/core/continuum-cognition/src/cognition/workspace/cause.rs index d5e1a6040b..5fba59edb3 100644 --- a/core/continuum-cognition/src/cognition/workspace/cause.rs +++ b/core/continuum-cognition/src/cognition/workspace/cause.rs @@ -555,7 +555,7 @@ impl Workspace { /// every context contribution that won attention this tick, newline-joined. /// This is where the persona reads what its perception faculties surfaced — /// roster/doctrine grounding, recall hits, and (the proprioception channel) - /// the `WorkingMemoryFaculty`'s render of its own recent acts. A deliberation + /// her view's render of its own recent acts. A deliberation /// faculty scans THIS, not the raw `world_state` burst — the burst is the /// stimulus, the broadcast is what the mind actually knows going into the /// decision. (Replaces the deleted eval-only `[you just acted]` world-state diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index d11a403d34..c6ac3969e6 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -1,9 +1,9 @@ #![cfg(test)] // what this catches: PROVENANCE BEING FILTERED BY ATTENTION. Card 0d51573a. - // `ws.broadcast` is the FOCUSED set — SalienceArbiter truncates to capacity — so - // deriving receipts from it silently drops the generations of any faculty that - // lost the attention competition. Astra found that in my first implementation, + // `ws.broadcast` is the FOCUSED set, so deriving receipts from it would drop the + // generations of any faculty attention dropped (the arbiter cut by a count until card + // c537d687; it forwards every bid now, and receipts must still not depend on it). Astra found that in my first implementation, // which flat_mapped broadcast; my previous test could not catch it because it // hand-assembled `ws.broadcast` and never ran the arbiter at all. // @@ -23,17 +23,8 @@ Arc::new(FixedFaculty(loud)), Arc::new(FixedFaculty(quiet)), ]; - // capacity 1 — one of the two bids MUST be truncated. - let ws = cycle(faculties, 1).run("burst").await; - - // POSITIVE CONTROL: the truncation really happened. Without this the receipt - // assertion below would pass just as well on a cycle that kept both bids, - // and would be asserting nothing about attention. - assert_eq!( - ws.broadcast.len(), - 1, - "capacity 1 must drop one bid — otherwise this test never exercises truncation" - ); + let ws = cycle(faculties).run("burst").await; + assert_eq!(ws.broadcast.len(), 2, "attention forwards every bid"); let ids: Vec<&str> = ws .generation_receipts() @@ -41,8 +32,8 @@ .collect(); assert!( ids.contains(&"req-quiet"), - "the TRUNCATED faculty's receipt must survive — provenance is not subject \ - to attention; got {ids:?}" + "the quieter faculty's receipt survives — provenance is not subject to \ + attention; got {ids:?}" ); assert!( ids.contains(&"req-loud"), @@ -175,8 +166,8 @@ } } - fn cycle(faculties: Vec>, capacity: usize) -> WorkspaceCycle { - WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), capacity) + fn cycle(faculties: Vec>) -> WorkspaceCycle { + WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) } // what this catches: the cycle's genome page-in/page-out round-trips through the @@ -186,7 +177,7 @@ // would measure the same genome and every lift would read as zero. #[test] fn genome_page_in_and_out_round_trips() { - let c = cycle(vec![], 4); + let c = cycle(vec![]); assert!( c.genome().is_empty(), "a fresh cycle starts on the base model" @@ -215,7 +206,7 @@ // the tile's Act corner would never light while she runs tools. #[test] fn acting_lights_only_the_act_axis_on_the_compass() { - let c = cycle(vec![], 4); + let c = cycle(vec![]); assert_eq!( c.faculty_pulse().levels(), [0, 0, 0, 0], @@ -245,7 +236,7 @@ Arc::new(HeuristicInferenceAdapter::new()); // The handle the faculty would hold; the cycle shares the SAME Arc. let handle = model_binding(Arc::clone(&adapter), None, 4096); - let c = cycle(vec![], 4).with_model_binding(Arc::clone(&handle)); + let c = cycle(vec![]).with_model_binding(Arc::clone(&handle)); // Baseline: what boot bound. assert_eq!(handle.load().context_window, 4096); @@ -274,7 +265,7 @@ // A cycle that shared no binding in (no deliberation faculty) must not // panic on re-home — it has nothing to rebind. - let bare = cycle(vec![], 4); + let bare = cycle(vec![]); bare.rebind_model(ModelBinding { adapter, model: Some("whatever".to_string()), @@ -305,7 +296,7 @@ // Boot shape: binding with NO explicit model (the live upstart path). let handle = model_binding(Arc::clone(&adapter), None, 20_224); - let c = cycle(vec![], 4).with_model_binding(handle); + let c = cycle(vec![]).with_model_binding(handle); let (model, ctx) = c.model_loadout().expect("a bound cycle reports a loadout"); assert_eq!( model.as_deref(), @@ -324,7 +315,7 @@ assert_eq!(model.as_deref(), Some("qwen-coder-14b")); // No binding at all (no deliberation faculty) → no loadout, honest-absent. - assert!(cycle(vec![], 4).model_loadout().is_none()); + assert!(cycle(vec![]).model_loadout().is_none()); } // what this catches: every finding is stamped with the cycle it was computed @@ -348,7 +339,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let c = cycle(faculties, 4); + let c = cycle(faculties); // First tick → CycleId(1); both the perception (Recall) and deliberation // (verdict) findings must carry it. @@ -397,7 +388,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let c = cycle(faculties, 4); + let c = cycle(faculties); let ws = Workspace::new("teammate: the deploy is red, what happened?"); // isolate recall: exactly one bid, its engram content, a real timing. @@ -448,7 +439,7 @@ // the highest-salience faculty bids win the bounded workspace. This is the // ML-integration replacement for calculate_priority's hand-weights. #[tokio::test] - async fn arbiter_selects_top_k_by_ml_salience() { + async fn arbiter_forwards_every_bid_highest_salience_first() { let faculties: Vec> = vec![ Arc::new(FixedFaculty(Contribution::context( FacultyId::Recall, @@ -469,10 +460,9 @@ "some arousal", ))), ]; - let ws = cycle(faculties, 2).run("the consolidated thread").await; - assert_eq!(ws.broadcast.len(), 2, "bounded capacity"); - assert_eq!(ws.broadcast[0].content, "high", "highest ML salience wins"); - assert_eq!(ws.broadcast[1].content, "mid"); + let ws = cycle(faculties).run("the consolidated thread").await; + let order: Vec<&str> = ws.broadcast.iter().map(|c| c.content.as_str()).collect(); + assert_eq!(order, ["high", "mid", "low"], "every bid, highest ML salience first: the view sizes each"); } // what this catches: ACTING-ORGANISM step 1 — the mind can express "I want to @@ -498,7 +488,7 @@ 0.95, "the model emitted a tool call", )))]; - let ws = cycle(faculties, 4).run("peer: does your sum work?").await; + let ws = cycle(faculties).run("peer: does your sum work?").await; match ws.decision() { Some(Decision::Act { calls, intent }) => { assert_eq!(calls.as_slice(), std::slice::from_ref(&call)); @@ -538,11 +528,11 @@ "actionable", ))), ]; - let ws = cycle(faculties, 1).run("burst").await; - assert_eq!(ws.broadcast.len(), 1); + let ws = cycle(faculties).run("burst").await; + assert_eq!(ws.broadcast.len(), 2); assert!( ws.broadcast[0].content.contains("peer persona"), - "the relevant peer-persona content wins on salience, not the human's rank" + "the relevant peer-persona content leads on salience, not the human's rank" ); } @@ -566,7 +556,7 @@ "high epistemic value — no one raised it", ))), ]; - let ws = cycle(faculties, 5).run("coordination thread").await; + let ws = cycle(faculties).run("coordination thread").await; match ws.decision() { Some(Decision::RaiseUnprompted { text }) => { assert_eq!(text, "blocker on the deploy") @@ -587,7 +577,7 @@ "nothing worth adding", ))), ]; - let ws = cycle(faculties, 5).run("idle chatter").await; + let ws = cycle(faculties).run("idle chatter").await; assert_eq!( ws.broadcast.len(), 1, @@ -615,7 +605,7 @@ "model 'X' is not the active served model (serving: 'Y')", ))), ]; - let ws = cycle(faculties, 5).run("swept to an unhosted model").await; + let ws = cycle(faculties).run("swept to an unhosted model").await; // The fault is readable and names the cause verbatim… assert_eq!( ws.deliberation_fault(), @@ -653,12 +643,12 @@ context.receipts = vec![receipt("other-faculty", served())]; let faculties: Vec> = vec![Arc::new(FixedFaculty(verdict)), Arc::new(FixedFaculty(context))]; - let ws = cycle(faculties, 5).run("decide").await; + let ws = cycle(faculties).run("decide").await; assert_eq!(ws.decision_generation().as_deref(), Some("decided")); let mut all_faulted = Contribution::verdict(Decision::Speak { text: "x".into() }, 0.8, "faulted"); all_faulted.receipts = vec![receipt("only-fault", faulted())]; - let ws = cycle(vec![Arc::new(FixedFaculty(all_faulted))], 5).run("decide").await; + let ws = cycle(vec![Arc::new(FixedFaculty(all_faulted))]).run("decide").await; assert_eq!(ws.decision_generation(), None, "a decision with no served generation carries none"); } @@ -674,7 +664,7 @@ 0.8, "caught up on the backlog", )))]; - let ws = cycle(faculties, 5).run(consolidated).await; + let ws = cycle(faculties).run(consolidated).await; assert!(ws.world_state.contains("many events, one unit")); assert!(matches!(ws.decision(), Some(Decision::Speak { .. }))); } @@ -710,8 +700,8 @@ "high value", ))), ]; - // capacity 1 → only the winner is broadcast, but the trace keeps both. - let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 1) + // Every bid is broadcast, and the trace keeps every bid with its salience. + let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .with_capture(sink.clone()) .run("thread") .await; @@ -720,7 +710,7 @@ assert_eq!(traces.len(), 1, "one tick recorded"); let t = &traces[0]; assert_eq!(t.bids.len(), 2, "trace keeps ALL bids — winner AND loser"); - assert_eq!(t.broadcast.len(), 1, "only the winner held attention"); + assert_eq!(t.broadcast.len(), 2, "attention forwards every bid"); assert!( t.bids.iter().any(|b| b.content == "loser bid"), "the loser bid + its salience + reasoning are replayable for debugging" @@ -750,7 +740,7 @@ // Phase 2 (deliberation): reacts to the assembled broadcast. Arc::new(ConditionalDeliberation), ]; - let ws = cycle(faculties, 5).run("what's the status?").await; + let ws = cycle(faculties).run("what's the status?").await; match ws.decision() { Some(Decision::Speak { text }) => assert!( text.contains("deploy pipeline is red"), @@ -778,7 +768,7 @@ ))), Arc::new(ConditionalDeliberation), ]; - let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter), 5) + let _ws = WorkspaceCycle::new(faculties, Arc::new(SalienceArbiter)) .with_capture(sink.clone()) .run("status?") .await; @@ -839,7 +829,7 @@ ))), Arc::new(CountingDeliberation(calls.clone())), ]; - let _ws = cycle(faculties, 5).run("burst").await; + let _ws = cycle(faculties).run("burst").await; assert_eq!( calls.load(std::sync::atomic::Ordering::SeqCst), 1, @@ -887,11 +877,10 @@ ); let candidates = vec![roster, doctrine, result.clone(), recall.clone()]; - // Fresh ask: fuller grounding — everything within capacity survives, exactly - // like the blind salience floor. + // Fresh ask: fuller grounding — every bid survives, exactly like the blind + // salience floor. let fresh = arbiter.focus( candidates.clone(), - 10, &FocusContext { world_state: "ask", situation: Situation::FreshContext, @@ -923,7 +912,6 @@ // "salience still governs which contributions are included and truncated". let post = arbiter.focus( candidates, - 10, &FocusContext { world_state: "result", situation: Situation::PostAction, diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs index c6a7e808da..88efb143b2 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs @@ -1,15 +1,10 @@ use super::*; impl WorkspaceCycle { - pub fn new( - faculties: Vec>, - arbiter: Arc, - capacity: usize, - ) -> Self { + pub fn new(faculties: Vec>, arbiter: Arc) -> Self { Self { faculties, arbiter, - capacity: capacity.max(1), capture: Arc::new(NoopWorkspaceCaptureSink), acting: None, genome: empty_genome(), @@ -436,7 +431,7 @@ impl WorkspaceCycle { /// /// This is what makes "pull relevant memory, *then* decide" real: the decider /// is never blind to recall. Still one tick over the consolidated burst, still - /// `O(capacity)` for the bounded context — no per-event slowdown. + /// `O(bids)` for the context — no per-event slowdown. /// TEST-ONLY ambient shorthand: the burst names its room (a raw string /// converts with [`ActivityRoom::test_room`](crate::identity::ActivityRoom::test_room) /// under `#[cfg(test)]`), so even faculty-isolation ticks run in a diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs index f9b4860180..e90724718e 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs @@ -148,7 +148,7 @@ impl WorkspaceCycle { }; let focused = self .arbiter - .focus(context_bids.clone(), self.capacity, &focus_ctx); + .focus(context_bids.clone(), &focus_ctx); // Bids-vs-focused receipt at the attention seam. Together with // `delib.context.render` (received-vs-rendered) this closes the glass box // over a surfaced finding's whole path: faculty bid → attention → @@ -157,7 +157,6 @@ impl WorkspaceCycle { // dark (#130). continuum_base::probe!( class = "workspace.attention.focus", - capacity = self.capacity, // The situation that drove this focus — the stat that makes context // control learnable: a focuser policy (this bootstrap, or a later // learned one) is a function of situation → dropped grounding, and the diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 5aed0ece2c..71a8d1a42b 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -354,7 +354,6 @@ mod tests { RecallMetadataRegistry::new(), ))), adapter: std::sync::Arc::new(HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs index b0be45c91b..f693d83332 100644 --- a/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs +++ b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use crate::cognition::act_observe::test_support::{admission, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{settle_step, ActChain}; -use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{ ActingBody, SalienceArbiter, Situation, TurnFraming, WorkspaceCycle, }; @@ -108,11 +108,9 @@ async fn bound_card_activity_is_shared_by_perception_and_execution() { let cycle = WorkspaceCycle::new( vec![ Arc::new(board), - Arc::new(WorkingMemoryFaculty::new(wm.clone())), Arc::new(ActThenSpeak::new()), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(Arc::new(ActingBody { persona_id: persona, diff --git a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs index f1eb854e02..06b67aaa04 100644 --- a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs +++ b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs @@ -259,7 +259,7 @@ async fn a_claims_hands_are_its_own_and_her_default_hands_never_move() { card_staging::stage_for_card(home.path(), persona, &gym_card).await, card_staging::Staging::Ready { path: workspace.clone() }, ); - let cycle = WorkspaceCycle::new(vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), 4) + let cycle = WorkspaceCycle::new(vec![], Arc::new(crate::cognition::workspace::SalienceArbiter)) .with_acting(Arc::new(ActingBody { persona_id: persona, persona_name: live.persona_name.clone(), executor: live.executor.clone(), working_memory: live.working_memory.clone(), @@ -440,7 +440,6 @@ fn a_handless_cycle_yields_no_hands() { let cycle = crate::cognition::workspace::WorkspaceCycle::new( vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), - 4, ); assert!(ActingHands::of(&cycle).is_none()); } diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs index 4199e3c55a..3b0dc9d978 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs @@ -29,7 +29,6 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { // shape: `code/search` returned the `_sympify` location she must edit next. Large // enough to clear the trail-head threshold so the pinned block surfaces. let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(16_384); let needle = "sympy/core/expr.py:123: return self == sympify(other) # _sympify HERE"; let grep_result = format!( "code/search matches:\n{needle}\n{}", @@ -265,7 +264,6 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { // (a burst to pointers once the share is exceeded), so the window is sized to // hold this 16.8k-char inventory beside the next batch; a smaller window would // collapse it at the batch's receipt, which is the other mechanism, not this one. - wm.set_served_window(65_536); let pin = crate::cognition::tool_executor::spill::LivePin::new(); let custody = pin.retain(persona, &inventory); let handle = custody.handle().expect("saved inventory").to_owned(); diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs index 6115de0c6b..a9e3d814fd 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs @@ -22,7 +22,6 @@ async fn a_writing_turn_after_a_cut_gets_its_reply_on_a_46848_window() { let cut = reg.record_emission_in_memory(persona, 5_404, 0, EmissionStop::CutMidAnswer, 4); assert_eq!(cut.peak_tokens, 10_808, "a cut mid-answer records the answer at double"); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); let adapter = Arc::new(ScriptedAdapter::new(vec![make_response(FinishReason::Stop, "PASS", None)])); let faculty = LlmDeliberationFaculty::new(persona, "Benchy", "You are Benchy.", adapter.clone()) .with_context_window(window) @@ -281,7 +280,6 @@ async fn standing_activity_grounding_survives_history_on_the_wire() { None, )])); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(window); wm.record_receipt("latest complete tool receipt"); // Optional history does not outrank the reply reserve. Give this // established citizen measured emissions so the large source diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 00cfa5d2a4..791db51f43 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -125,7 +125,6 @@ fn cfg_for(persona_id: uuid::Uuid, name: &str) -> crate::cognition::persona_work system_prompt: format!("You are {name}, an engineer on the grid."), admission: crate::cognition::act_observe::test_support::admission(), adapter: std::sync::Arc::new(crate::ai::HeuristicInferenceAdapter::new()), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index 1031377d0b..f8308553e7 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -6,7 +6,7 @@ use std::sync::Mutex; use crate::ai::types::ToolCall; use crate::cognition::act_observe::test_support::{admission, body_with_wm, ScriptedExecutor}; use crate::cognition::act_observe::*; -use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{Faculty, SalienceArbiter, TurnFraming, WorkspaceCycle}; // what this catches:41f4e3ef — a directed drive must persist real receipt-linked @@ -40,7 +40,6 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { ]); hands.pause_before = Some((5, Arc::clone(&entered), release)); let wm = Arc::new(WorkingMemory::new(8)); - wm.set_served_window(32_768); let body = body_with_wm(Arc::new(hands), admission(), Arc::clone(&wm)); let persona = body.persona_id; let responses = (0..5) @@ -85,11 +84,9 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { }]); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(wm)) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body); let card = Uuid::new_v4(); diff --git a/core/continuum-mind/src/persona/obligation/recover.rs b/core/continuum-mind/src/persona/obligation/recover.rs index 38f7532b81..bc4a92a83f 100644 --- a/core/continuum-mind/src/persona/obligation/recover.rs +++ b/core/continuum-mind/src/persona/obligation/recover.rs @@ -160,7 +160,6 @@ mod tests { crate::cognition::recall_metadata::RecallMetadataRegistry::new(), ))), adapter: Arc::new(adapter), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: Some(Arc::new(crate::cognition::act_observe::test_support::ScriptedExecutor::new(["ok"]))), diff --git a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs index e73a19b372..1b54668fa1 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs @@ -105,7 +105,6 @@ use super::*; system_prompt: "You are Paige.".to_string(), admission, adapter: Arc::new(HeuristicInferenceAdapter::new().with_canned_response("PASS: done")), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -205,7 +204,6 @@ use super::*; HeuristicInferenceAdapter::new() .with_canned_response("The tests failed after the latest change."), ), - capacity: None, grounding_sources: Vec::new(), embedder: None, tool_executor: None, @@ -304,7 +302,6 @@ use super::*; let cycle = crate::cognition::workspace::WorkspaceCycle::new( vec![], Arc::new(crate::cognition::workspace::SalienceArbiter), - 4, ); let mut unavailable = current.clone(); unavailable.card_id = airc_lib::WorkCardId::new(); @@ -508,7 +505,6 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( adapter: Arc::new( HeuristicInferenceAdapter::new().with_canned_response("PASS: nothing calls me right now"), ), - capacity: None, grounding_sources: Vec::new(), embedder: None, // Her hands: an initiative turn is offered only to a mind that can act. diff --git a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs index f169349223..4be441b1f4 100644 --- a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs +++ b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs @@ -468,7 +468,6 @@ pub async fn materialize_adapters( system_prompt: system_prompt.to_string(), admission: cognition.admission.clone(), adapter: adapter.clone(), - capacity: None, // S1: the node's recipe registry, so this citizen's tool surface follows // the room she acts in (its recipe's affordances), not a global list. experience: crate::experience::source::node_experience_source(), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 33c139d025..df2a8498b3 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -626,7 +626,7 @@ mod tests { async fn starved_priority_input_survives_until_dispatch_without_replaying_actions() { use crate::cognition::act_observe::test_support::{admission, body_with_wm, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{drive_to_settle_with_input, SettleStep}; - use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; + use crate::cognition::working_memory::WorkingMemory; use crate::cognition::workspace::{Burst, Faculty, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; use std::sync::{Arc, Mutex}; use crate::cognition::conversation::scripted_conversation::ScriptedConversation; @@ -643,11 +643,9 @@ mod tests { let wm = Arc::new(WorkingMemory::new(8)); let cycle = WorkspaceCycle::new( vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, Arc::new(faculty), ], Arc::new(SalienceArbiter), - 8, ) .with_acting(body_with_wm(exec.clone(), admission(), wm)); let original = IncomingMessage { From 91202b8125bee12b7a884746992897ce6592ace6 Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 23:44:07 -0500 Subject: [PATCH 02/11] WM slice: drop the because-clause from results (Fable approved); open views carry her whole intent as their optional level; remove the dead capacity test constant Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/apply.rs | 2 +- .../src/cognition/act_observe/mod.rs | 2 +- .../src/cognition/act_observe/observation.rs | 44 +++---------------- .../an_action_result_cannot_mute_a_citizen.rs | 2 +- .../src/cognition/rag_source_faculty/tests.rs | 3 -- .../src/cognition/working_memory/ledger.rs | 7 +-- .../cognition/working_memory/tests/actions.rs | 2 +- 7 files changed, 15 insertions(+), 47 deletions(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 4fc665ee61..de57d37edb 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -417,7 +417,7 @@ pub async fn apply_act( }, status: ActStatus::Executed, }; - observation.push_str(&obs.render_recency(intent)); + observation.push_str(&obs.render_recency()); recall_observation.push_str(&obs.render_recall(intent)); // (The canvas feed publishes at the tool-executor seam, PRE-fold — a // flood-sized ObserveResult here is already a spilled preview that no diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index 15cc663c56..2f5652cc7e 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -32,7 +32,7 @@ mod perception; mod recency; mod observation; -pub use observation::{extract_paths, intent_label, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; +pub use observation::{extract_paths, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; mod types; pub use types::{SettleOutcome, SettleStep}; diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index 6088445bc6..497ea39db0 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -257,12 +257,6 @@ impl Observation { self.output.verdict.failed() || self.output.result.is_error == Some(true) } - /// The RECENCY-channel rendering: the FULL trace working memory keeps so the - /// mind can act on what it just fetched. Byte-identical to the old inline - /// `apply.rs` block (`{name}({args}){because}\nResult:\n{bounded}\n\n`) — the - /// #205 KV-stability invariant. `intent` is batch-level (one per `apply_act` - /// call, shared by every act in the batch), so it is passed rather than - /// stored per-`Observation`. /// The call as she made it, `name(args)`: its arguments by shape, never by size /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part /// and its ledger line. @@ -270,19 +264,13 @@ impl Observation { format!("{}({})", self.call.name, render_call_args(&self.call.input)) } - pub fn render_recency(&self, intent: &str) -> String { - // The intent rides the result as a ONE-LINE reason, its first line: a shape rule, - // never a size, and never the whole monologue. - // Measured 2026-09-04: one result header carried 2,902 chars of intent - // ("Let me get oriented…") ahead of 790 chars of actual output; across a - // turn, 6.1k of 20.6k result chars were intent echo. The output is what - // she must read; the reason is a label. - let because = if intent.trim().is_empty() { - String::new() - } else { - format!(" because {}", intent_label(intent)) - }; - format!("{}{}\nResult:\n{}\n\n", self.call_line(), because, self.body_text().trim()) + /// The RECENCY-channel rendering: the FULL trace working memory keeps so the mind can act on + /// what it just fetched, `{call}\nResult:\n{body}\n\n`, stable across acts (the #205 + /// KV-stability invariant). + pub fn render_recency(&self) -> String { + // No reason clause: her intent reaches her whole as her own thought, and #5611's causes + // link each result to its act, so a result carries its call and its output only. + format!("{}\nResult:\n{}\n\n", self.call_line(), self.body_text().trim()) } /// This act as one part of a batch receipt's summary level: the recency header (its name and @@ -350,27 +338,9 @@ pub fn extract_paths(input: &serde_json::Value) -> Vec { out } -/// Clip an act's intent to a one-line reason of at most `max_chars` characters -/// (first line, head-trimmed with an ellipsis). Pure; used by the recency render. -/// The intent's label on a result: its first line. A shape rule, never a size: the rest of what she -/// thought is her own message, already in her view. -pub fn intent_label(intent: &str) -> String { - intent.trim().lines().next().map_or_else(String::new, |first| first.trim().to_string()) // an empty intent labels nothing -} - #[cfg(test)] mod tests { - // what this catches: the monologue riding every result (2,902 chars of intent ahead of 790 - // chars of output, measured 2026-09-04). The label is the first line, by shape, never a size. - #[test] - fn intent_on_a_result_is_its_first_line() { - let long = "Let me get oriented properly this time. I've been confusing myself with stale context and the board says otherwise.\nSecond line never rides."; - let label = super::intent_label(long); - assert!(label.starts_with("Let me get oriented") && !label.contains("Second line"), "{label:?}"); - assert_eq!(super::intent_label("read the card"), "read the card"); - assert_eq!(super::intent_label(" "), ""); - } use super::*; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs index 953427498a..16c05717fe 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs @@ -98,7 +98,7 @@ mod the_newest_result_over_her_window { }, status: ActStatus::Executed, }; - let rendered = observation.render_recency(""); + let rendered = observation.render_recency(); wm.record_receipt_typed(&[observation], &rendered, Some(room), ResultCustody::Whole { handle: HANDLE.into() }); LlmDeliberationFaculty::new(Uuid::new_v4(), "Aris", "You are Aris.", adapter) .with_context_window(window) diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs index aed446f872..c5cf0706fe 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -636,6 +636,3 @@ ); } - /// The production default capacity (mirror of persona_workspace's constant) so - /// the canary tests the realistic configuration, not a contrived one. - const DEFAULT_CAPACITY_FOR_TEST: usize = 6; diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f34c3bebdd..6e0606db7a 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -222,13 +222,14 @@ impl WorkingMemory { } /// Attach her stated reasoning for the act just recorded to the open views it touched, - /// so each view carries what she understood, not only how far she read. The note is the - /// intent's label, its first line: the same shape rule a result's header uses, never a size. + /// so each view carries what she intended, not only how far she read. Whole, never a first + /// line: it is an optional level of the open-views source, which her view sizes and drops + /// before the cursor (`planning_detail_yields_to_cursor_and_returns_when_granted`). pub fn annotate_open_views(&self, intent: &str) { let Some(seq) = self.next_action_seq.load(Ordering::Relaxed).checked_sub(1) else { return; }; - self.open_views.lock().annotate(seq, &crate::cognition::act_observe::intent_label(intent)); + self.open_views.lock().annotate(seq, intent); } pub(crate) fn record_receipt_measured( diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index 792b13ed68..e6de9b4686 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -384,7 +384,7 @@ fn a_batch_receipts_summary_keeps_every_operation() { let summary_of = |acts: Vec| { let wm = WorkingMemory::new(8); // The receipt as production renders it: each act's recency rendering, in order. - let rendered: String = acts.iter().map(|a| a.render_recency("")).collect(); + let rendered: String = acts.iter().map(|a| a.render_recency()).collect(); wm.record_receipt_typed(&acts, &rendered, None, Default::default()); let actions = wm.actions.lock(); actions.records().last().and_then(|record| record.summary.clone()) From 8c01588f174ff923a526f4e895f58da9de84695a Mon Sep 17 00:00:00 2001 From: joelteply Date: Fri, 30 Oct 2026 23:45:34 -0500 Subject: [PATCH 03/11] WM slice: vitals gauge percentage saturates without a literal clamp; revert the doc-only touch of llm_deliberation_faculty.rs (its disk writer awaits the class handle) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/llm_deliberation_faculty.rs | 2 +- core/continuum-core/src/ipc/vitals_emitter.rs | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 55e4ee28f9..9d6a932a44 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -195,7 +195,7 @@ pub struct LlmDeliberationFaculty { /// Where this faculty records its chain-of-thought after a verdict, so the /// persona can resume its train of thought next turn (the /// [`WorkingMemory`](crate::cognition::working_memory::WorkingMemory) - /// her view's thoughts source reads). `None` → reasoning is dropped (the prior + /// `WorkingMemoryFaculty` reads). `None` → reasoning is dropped (the prior /// behavior). Only the suppressed-thinking default makes `reasoning` empty, so /// this self-activates exactly when thinking is on. working_memory: Option>, diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 71a8d1a42b..9ac00fcf79 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -90,8 +90,13 @@ const TPS_FULL_SCALE: u64 = 40; /// Prefill/ingest t/s that reads as pegged (M-series ingest ~300-800). const PFX_FULL_SCALE: u64 = 800; +/// `v` as a share of a full scale, in percent. Past the full scale it reads as full, and an +/// empty scale reads as nothing for nothing and full for anything. fn pct_usize(v: usize, full: usize) -> u8 { - (v.saturating_mul(100) / full.max(1)).min(100) as u8 + if v >= full { + return if v == 0 { 0 } else { 100 }; + } + (v.saturating_mul(100) / full) as u8 // v < full, so the share is below 100 and fits a u8 } /// One tick's radiated readouts from `registry` — the SAMPLE half of the From 9cd28b1dcf771045c91998a39e9b05117e067ee0 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:24:06 -0500 Subject: [PATCH 04/11] WM slice: no backwards compatibility (Joel 2026-10-31: 'This is the first version'). The checkpoint carries her actions in one shape: receipt_heads, receipt_head_rooms, recent_results, result_scopes and evicted_pointers (the previous build's projection) are deleted with the legacy restore path and written_pointer; checkpoint adoption validates the records; the tests of rollback and pre-records restores are deleted Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../persona_workspace/checkpoint_adoption.rs | 12 +-- .../src/cognition/working_memory.rs | 101 +----------------- .../cognition/working_memory/action_log.rs | 4 - .../cognition/working_memory/continuity.rs | 30 +----- .../src/cognition/working_memory/ledger.rs | 1 - .../cognition/working_memory/perception.rs | 2 - .../working_memory/tests/action_log.rs | 42 -------- .../cognition/working_memory/tests/actions.rs | 2 +- .../cognition/working_memory/tests/custody.rs | 39 +++---- .../working_memory/tests/provenance.rs | 19 ---- .../cognition/working_memory/tests/trail.rs | 5 - .../src/persona/wake_backlog.rs | 4 +- 12 files changed, 35 insertions(+), 226 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index cccb5ab3ba..4b5c1b46ac 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -130,18 +130,18 @@ fn summary(bytes: &[u8]) -> Result { .as_ref() .is_some_and(|(seq, _)| *seq == 0 || *seq >= wm.next_action_seq) || wm - .recent_results + .action_records() .iter() - .any(|(seq, _, _, _, _)| *seq == 0 || *seq >= wm.next_action_seq) + .any(|record| record.seq == 0 || record.seq >= wm.next_action_seq) { return Err(invalid("receipt sequence must precede next_action_seq")); } let mut previous = None; - for (seq, _, _, _, _) in &wm.recent_results { - if previous.is_some_and(|old| old >= *seq) { + for record in wm.action_records() { + if previous.is_some_and(|old| old >= record.seq) { return Err(invalid("result receipt sequences must strictly increase")); } - previous = Some(*seq); + previous = Some(record.seq); } let utterances = match &persisted.own_speech { OwnSpeechPersisted::ByRoom(rooms) => { @@ -160,7 +160,7 @@ fn summary(bytes: &[u8]) -> Result { saved_at_ms: wm.saved_at_ms, next_action_seq: wm.next_action_seq, entries: wm.entries.len(), - result_receipts: wm.recent_results.len(), + result_receipts: wm.action_records().iter().filter(|record| record.result.is_some()).count(), own_utterances: utterances, unscoped_own_utterances: match &persisted.own_speech { OwnSpeechPersisted::ByRoom(_) => 0, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 99026b550b..de18895a62 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -149,10 +149,7 @@ impl<'a> ResultAttribution<'a> { /// The line a collapsed result leaves: what it was, and the handle that reopens it. fn collapsed_pointer(record: &action_log::ActionRecord) -> String { - match &record.written_pointer { - Some(pointer) => pointer.clone(), - None => format!("[result {}{} — collapsed]", ResultAttribution::of(record), workspace_label(record.scope.as_deref())), - } + format!("[result {}{} — collapsed]", ResultAttribution::of(record), workspace_label(record.scope.as_deref())) } /// Recognize ONLY the standalone pointer representation emitted by this owner. @@ -430,43 +427,14 @@ pub struct VolatileSnapshot { /// then says nothing rather than guessing a change it cannot see (#165). #[serde(default)] pub build_sha: String, - /// The proprioception receipt archive (#414) — act-history head lines that must - /// survive a reboot exactly as the ring entries do (the counter already did; a - /// counter without its lines is the deprivation this field exists to end). Empty - /// on snapshots written before this field (serde default): restore starts the - /// archive fresh and the ledger's counter-only arm stays honest about the gap. - #[serde(default)] - pub receipt_heads: Vec, - /// Room tags parallel to `receipt_heads`, index-aligned (slice B). A - /// SEPARATE defaulted field — not a tuple — so snapshots written before - /// scoping still deserialize; restore pads missing tags with `None` - /// (honest "unscoped", never a guessed room). - #[serde(default)] - pub receipt_head_rooms: Vec>, - /// Recent act result TAILS `(seq, room, tail)` — the cross-turn feedback - /// channel (2026-08-16). Defaulted so pre-field snapshots deserialize; - /// restore then starts the buffer fresh. - #[serde(default)] - pub recent_results: Vec<(u64, Option, String, String, Option)>, - /// Additive attribution preserves the existing receipt tuple wire format. Missing - /// legacy attribution is unknown, never inferred from a room or the current root. - #[serde(default)] - pub result_scopes: BTreeMap, /// Her state at the seam — the whole held card, her ledger, what was staged, what tore /// the life (card 49b5e806, Kimi 2026-09-26). Stamped by `save_volatile`, which knows /// whose memory this is and why it is being written; rendered FIRST on wake. `None` on /// snapshots from before this field and for a citizen at home with nothing to hand. #[serde(default)] pub handoff: Option, - /// The collapsed results' pointers, each with the handle it reopens: what a result - /// leaves when it collapses out of the ring is HOW she reaches it again, so it survives - /// a restart exactly as the ring does (Astra on #4963: a read collapsed at settlement - /// lost its only handle on restart). Empty on snapshots written before this field. - #[serde(default)] - pub evicted_pointers: Vec<(String, String)>, - /// Her actions, whole ([`action_log`]): what a restore reads. The ring, archive and - /// pointer fields above are the same acts in the shape the previous build reads, kept - /// so a rollback still restores her. Empty on snapshots written before it. + /// Her actions, whole ([`action_log`]): what a restore reads, the one shape (no projection + /// for another build: this is the first version, Joel 2026-10-31). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) actions: Vec, /// Her context view ([`WorkingMemory`]'s `view`). Absent on snapshots written before it, @@ -522,63 +490,9 @@ impl VolatileSnapshot { } } - /// Her actions as records: the records it carries, or, for a checkpoint written before - /// them, the ring, archive and pointer index read back into records. Those older lines - /// are keyed by the `#n` this owner wrote at their head (one with none is dropped and - /// counted), and an older pointer keeps the exact text it was written with, since its - /// operation and workspace are not stored apart from it. + /// Her actions as records, as the checkpoint carries them. pub(crate) fn action_records(&self) -> Vec { - if !self.actions.is_empty() { - return self.actions.clone(); - } - let blank = |seq: u64, room: Option| action_log::ActionRecord { - seq, - room, - scope: None, - operation: "unrecorded".into(), - head: None, - result: None, - handle: None, - written_pointer: None, - summary: None, - stored_chars: None, - received_ms: None, - }; - let mut records: BTreeMap = BTreeMap::new(); - let mut unkeyed = 0usize; - for (seq, room, result, operation, handle) in &self.recent_results { - let record = records.entry(*seq).or_insert_with(|| blank(*seq, *room)); - record.scope = self.result_scopes.get(seq).cloned(); - record.operation = operation.clone(); - record.result = Some(result.clone()); - record.handle = handle.clone(); - } - let mut rooms = self.receipt_head_rooms.iter(); - for head in &self.receipt_heads { - let room = rooms.next().copied().flatten(); - let Some(seq) = written_seq(head, "[action #") else { - unkeyed += 1; - continue; - }; - records.entry(seq).or_insert_with(|| blank(seq, room)).head = Some(head.clone()); - } - for (pointer, handle) in &self.evicted_pointers { - let Some(seq) = written_seq(pointer, "[result #") else { - unkeyed += 1; - continue; - }; - let record = records.entry(seq).or_insert_with(|| blank(seq, None)); - record.handle.get_or_insert_with(|| handle.clone()); - record.written_pointer = Some(pointer.clone()); - } - if unkeyed > 0 { - continuum_base::probe!( - class = "wm.actions.unkeyed_on_restore", - unkeyed = %unkeyed, - "checkpoint lines without an action number were dropped on restore" - ); - } - records.into_values().collect() + self.actions.clone() } /// Every saved result this checkpoint still reaches; the persisted twin of what working @@ -614,11 +528,6 @@ impl VolatileSnapshot { } } -/// The `#n` this owner wrote right after `prefix` at the head of a line. -fn written_seq(line: &str, prefix: &str) -> Option { - let digits: String = line.strip_prefix(prefix)?.chars().take_while(char::is_ascii_digit).collect(); - digits.parse().ok() -} /// "; workspace " for a result recorded under a root; empty for one recorded before. fn workspace_label(root: Option<&str>) -> String { diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index ad4d5af2ec..997b49585c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -48,10 +48,6 @@ pub(crate) struct ActionRecord { /// The saved whole; `None` when the save failed, and then the result never collapses /// (nothing else holds its bytes). pub handle: Option, - /// The pointer exactly as a build before the records wrote it, restored from its - /// checkpoint: its operation and workspace live only in that text. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub written_pointer: Option, /// The result's summary level (`continuum_context::levels`): a numbered read's outline, /// else an output's head and tail; what her view gives it when it cannot keep it whole. /// Kept after the result collapses, so what she read stays addressable. diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 4e6cc7460c..1ef0c4c2dc 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -180,41 +180,14 @@ impl WorkingMemory { } (entries, authored) }; - // The log, projected into the wire shape older builds read (see - // `VolatileSnapshot::action_records`), under one lock so a concurrent collapse - // cannot move a record between the projections. let last_action = self.last_action.lock().clone(); - let (archive, recent_results, result_scopes, pointers, records) = { - let actions = self.actions.lock(); - let archive: Vec<(Option, String)> = actions - .records() - .filter_map(|record| record.head.as_ref().map(|head| (record.room, head.clone()))) - .collect(); - let recent_results: Vec<(u64, Option, String, String, Option)> = actions - .retained() - .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) - .collect(); - let result_scopes: BTreeMap = actions - .retained() - .filter_map(|r| r.scope.clone().map(|scope| (r.seq, scope))) - .collect(); - let pointers: Vec<(String, String)> = actions - .indexed_pointers() - .into_iter() - .filter_map(|r| r.handle.clone().map(|handle| (super::collapsed_pointer(r), handle))) - .collect(); - (archive, recent_results, result_scopes, pointers, actions.records().cloned().collect()) - }; + let records: Vec = self.actions.lock().records().cloned().collect(); VolatileSnapshot { pending_emissions: self.pending_emissions.lock().clone(), entries, action_statements, last_action, action_fps: self.action_fps.lock().iter().cloned().collect(), - receipt_heads: archive.iter().map(|(_, head)| head.clone()).collect(), - receipt_head_rooms: archive.iter().map(|(room, _)| *room).collect(), - recent_results, - result_scopes, next_action_seq: self.next_action_seq.load(Ordering::Relaxed), saved_at_ms: continuum_base::time::EpochMs::now().millis(), build_sha: env!("CONTINUUM_BUILD_GIT_SHA").to_string(), @@ -229,7 +202,6 @@ impl WorkingMemory { .filter(|d| d.status == DispatchStatus::Running) .map(|d| d.label.clone()) .collect(), - evicted_pointers: pointers, actions: records, context_view: self.view.lock().clone(), receipt_children: self.receipt_children.lock().clone(), diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 6e0606db7a..890bf869f2 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -315,7 +315,6 @@ impl WorkingMemory { summary: result_summary(&tail, &acts), result: Some(tail), handle, - written_pointer: None, stored_chars: None, received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 60f219c143..9723b13fef 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -255,8 +255,6 @@ impl WorkingMemory { let workspace = workspace_label(record.scope.as_deref()); let whole = record.result.as_deref().map(|result| format!("[result {attribution}{workspace}] {result}")); let pointer = match (&record.handle, &whole, &record.head) { - // An older build's pointer, as it was written (its operation lives there). - (Some(_), _, _) if record.written_pointer.is_some() => record.written_pointer.clone().into_iter().collect(), (Some(_), _, _) => format!("[result {attribution}{workspace} — collapsed; query tool/output to expand]"), // Retained but never saved: no handle could reopen a collapsed line, so it stays // whole (goal 7: the full result stays reachable; Cormac on #5255). diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 48b9426212..34a462b411 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs @@ -29,29 +29,6 @@ fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { assert!(!ring.contains(&"a".repeat(cap / 2)), "its whole result left the ring"); } -// what this catches: a checkpoint from the build before the log losing what a collapsed -// result reopens. Its pointer lines and ledger lines carry no seq column; the #n the old -// owner wrote keys them, and the pointer's saved whole stays reachable for the spill guard. -#[test] -fn a_checkpoint_from_before_the_log_restores_its_pointers_and_ledger() { - let mut legacy = WorkingMemory::new(8).snapshot(); - legacy.receipt_heads = vec!["[action #7] code/read(\"a.rs\")".into(), "[action #8] code/shell(\"ls\")".into()]; - legacy.receipt_head_rooms = vec![None, None]; - legacy.recent_results = vec![(8, None, "a.rs\nb.rs".into(), "code/shell".into(), Some("h8".into()))]; - legacy.evicted_pointers = vec![("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]".into(), "h7".into())]; - legacy.next_action_seq = 9; - let reachable = legacy.reachable_handles(); - assert!(reachable.contains("h7") && reachable.contains("h8"), "{reachable:?}"); - let wm = WorkingMemory::new(8); - wm.restore(legacy); - let lines: Vec = ledger(&wm).into_iter().map(|(_, head)| head).collect(); - assert_eq!(lines, ["[action #7] code/read(\"a.rs\")", "[action #8] code/shell(\"ls\")"]); - let ring = wm.recent_results_messages().join("\n"); - // Its pointer keeps the exact text the older build wrote: operation and all. - assert!(ring.contains("[result #7; room unrecorded; operation code/read; output handle: tool/output h7 — collapsed]"), "{ring}"); - assert!(ring.contains("a.rs\nb.rs"), "{ring}"); -} - // what this catches: a restart changing what she reads of her own acts (Cormac on #5254: a // collapsed pointer re-rendered as "operation unrecorded" with no workspace, because the // checkpoint kept a pointer only as text). Every record is checkpointed whole, so her ring @@ -82,25 +59,6 @@ fn a_restart_keeps_every_act_as_she_read_it() { assert_eq!(ledger(&restored), lines); } -// what this catches: a rollback to the build before the log restoring her blank. The -// checkpoint keeps the wire shape that build reads beside the records it now restores from. -#[test] -fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { - let wm = WorkingMemory::new(8); - let cap = 2 * BODY; - wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); - for act in 2..=5 { - record_saved(&wm, &format!("act {act}\n{}", "s".repeat(cap / 2))); - } - wm.record_settlement("done", None); - shed(&wm, cap / 2); - let snap = wm.snapshot(); - assert!(snap.receipt_heads.first().is_some_and(|head| head.starts_with("[action #1]"))); - assert_eq!(snap.evicted_pointers.first().map(|(_, handle)| handle.as_str()), Some("first-handle")); - assert_eq!(snap.recent_results.last().map(|(seq, ..)| *seq), Some(5)); - assert_eq!(snap.actions.len(), 5); -} - // what this catches (card d624a9a1): an act's line cutting an argument mid-value. A cut path // reads as a real one, and a small model copies it and loops (IntelMac 2026-10-22: a cut // '.../citizens/pe' became three refused reads). Her recorded line shows a single-line value diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index e6de9b4686..d5e6f3db96 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -32,7 +32,7 @@ async fn latest_action_returns_full_result_trail_keeps_its_call_line() { .pinned_active_result_block() .expect("the whole result is pinned for the mind"); assert!( - pinned.contains("Full result of your most recent action (#1; room unrecorded; operation unrecorded):"), + pinned.contains("Full result of your most recent action (#1; room unrecorded; operation code/read):"), "the whole result reaches the mind" ); assert!( diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index b96d895566..6dba2bf0a5 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -60,23 +60,16 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ results.record_settlement("reported", None); shed(&results, 0); let snapshot = results.snapshot(); - assert!(!snapshot.evicted_pointers.is_empty(), "fixture exercises the collapsed ring"); - let mut encoded = serde_json::to_value(&snapshot).expect("snapshot serializes"); + assert!(snapshot.action_records().iter().any(|r| r.result.is_none() && r.handle.is_some()), "fixture exercises a collapsed result"); + let encoded = serde_json::to_value(&snapshot).expect("snapshot serializes"); let restored = WorkingMemory::new(2); restored.restore(serde_json::from_value(encoded.clone()).expect("snapshot round trip")); let shown = restored.recent_results_messages().join("\n"); restored.set_scope(Some("task-b".into())); assert!(shown.contains("scope-a-output") && restored.recent_results_messages().join("\n") == shown, "{shown}"); - assert_eq!(restored.snapshot().evicted_pointers, snapshot.evicted_pointers, "pointers retain custody"); - // Pre-attribution snapshots stay explicitly unknown, not falsely assigned - // to the restoring root or hidden based on missing bounded entry metadata. - encoded.as_object_mut().unwrap().remove("result_scopes"); - let legacy = WorkingMemory::new(2); - legacy.restore(serde_json::from_value(encoded).expect("legacy snapshot")); - legacy.set_scope(Some("task-b".into())); - assert!(legacy.recent_results_messages().join("\n").contains("scope-a-output")); + assert_eq!(restored.snapshot().action_records(), snapshot.action_records(), "collapsed results retain custody"); // Receipt publication, pruning and snapshots share custody: a concurrent - // checkpoint must never downgrade a known-root result to legacy unknown. + // checkpoint must never lose a result's root. let concurrent = WorkingMemory::new(2); concurrent.set_scope(Some("writer-root".into())); std::thread::scope(|threads| { @@ -86,9 +79,8 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ for _ in 0..128 { concurrent.publish_live_handles(); let snapshot = concurrent.snapshot(); - for seq in snapshot.recent_results.iter().map(|r| r.0) - .chain(snapshot.last_action.iter().map(|r| r.0)) { - assert_eq!(snapshot.result_scopes.get(&seq).map(String::as_str), Some("writer-root")); + for record in snapshot.action_records().iter().filter(|r| r.result.is_some()) { + assert_eq!(record.scope.as_deref(), Some("writer-root")); } } }); @@ -245,16 +237,26 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { let _ = std::fs::remove_dir_all(&root); } -// what this catches (Codex on #4987): a legacy receipt with no handle files its children +// what this catches (Codex on #4987): a receipt with no handle (its save failed) files its children // under `seq:N`; restore saves it and it takes a handle, so the children must move to that // key or the next publish prunes them as belonging to no receipt. #[test] -fn a_restored_legacy_receipt_keeps_its_children_under_its_new_handle() { +fn a_restored_handleless_receipt_keeps_its_children_under_its_new_handle() { let child = format!("{:016x}", Uuid::new_v4().as_u128() as u64); let mut snapshot = WorkingMemory::new(8).snapshot(); - snapshot.recent_results.push((7, None, "a legacy receipt".into(), "code/read".into(), None)); + snapshot.actions.push(crate::cognition::working_memory::action_log::ActionRecord { + seq: 7, + room: None, + scope: None, + operation: "code/read".into(), + head: None, + result: Some("a receipt whose save failed".into()), + handle: None, + summary: None, + stored_chars: None, + received_ms: None, + }); snapshot.receipt_children.insert(receipt_key(7, None), vec![child.clone()]); - snapshot.actions = snapshot.action_records(); // what retain_handleless does first let unsaved = snapshot.unsaved_receipts(); let handle = format!("{:016x}", Uuid::new_v4().as_u128() as u64); snapshot.actions[0].handle = Some(handle.clone()); // what a successful save sets @@ -346,7 +348,6 @@ fn results_are_never_evicted_at_receipt_however_large_the_ring() { } assert!(wm.resident_result_bytes() >= 40 * chunk as u64, "all 40 bodies resident: {}", wm.resident_result_bytes()); let snapshot = wm.snapshot(); - assert!(snapshot.evicted_pointers.is_empty(), "nothing collapsed to a pointer"); assert!(snapshot.actions.iter().all(|record| record.result.is_some()), "every record holds its body"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 58c026d2b8..6358c7db5e 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -247,25 +247,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { assert_whole_or_handle(&restarted); } -// e731: pre-result-ring snapshots have a full body but no room/operation -// attribution. Rendering must expose that absence instead of inventing it. -#[test] -fn legacy_full_result_without_metadata_stays_explicitly_unattributed() { - let wm = WorkingMemory::new(8); - wm.record_receipt("legacy body"); - let mut snapshot = wm.snapshot(); - snapshot.recent_results.clear(); - let restored = WorkingMemory::new(8); - restored.restore(snapshot); - let (seq, full) = restored - .active_action_full() - .expect("test: legacy body restored"); - assert_eq!( - restored.full_result_message(seq, &full), - "Full result of your most recent action (#1; room unrecorded; operation unrecorded):\nlegacy body" - ); -} - // what this catches (Step 3 back-compat): an OLD volatile.json — written before // the WmEntry.acts field existed — restores WITHOUT panic, the `acts` defaulting // to empty via `#[serde(default)]` (the same contract as saved_at_ms/build_sha). diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 83b2c3aaa7..c0f1c27d7f 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -267,12 +267,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { interrupted_dispatches: Vec::new(), build_sha: String::new(), // pre-field snapshot: no rebuild guessed either acting_card: None, - receipt_heads: Vec::new(), - receipt_head_rooms: Vec::new(), // pre-archive snapshot: ledger's counter-only arm covers it - recent_results: Vec::new(), - result_scopes: Default::default(), handoff: None, - evicted_pointers: Vec::new(), actions: Vec::new(), context_view: None, receipt_children: Default::default(), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index df2a8498b3..a347c40809 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -634,13 +634,13 @@ mod tests { use std::sync::atomic::{AtomicBool, Ordering}; let gate = Arc::new(AtomicBool::new(false)); - let mut faculty = ActThenSpeak::new(); + let wm = Arc::new(WorkingMemory::new(8)); + let mut faculty = ActThenSpeak::new().with_memory(Arc::clone(&wm)); faculty.admission_open = Some(Arc::clone(&gate)); let exec = Arc::new(RecordingExecutor { seen_context: Arc::new(Mutex::new(None)), result_content: "4".into(), }); - let wm = Arc::new(WorkingMemory::new(8)); let cycle = WorkspaceCycle::new( vec![ Arc::new(faculty), From 61e6b550e33d41823ebd9e3d2f146dc6f51bf616 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:36:35 -0500 Subject: [PATCH 05/11] WM slice: observation::call_args, the one argument renderer (Observation::call_line uses it; #5635's status line will) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/observation.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index 497ea39db0..ba7cc4fd82 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -226,6 +226,14 @@ impl ActOutcome { } } +/// A call's arguments as she reads them, by shape and never by size: a single-line value whole, +/// a multi-line value (a file's body, a heredoc) by its reference, so one line stays one line. +/// The one argument renderer (`Observation::call_line`, and a result's status line in +/// `tool_executor::answer`). +pub(crate) fn call_args(input: &serde_json::Value) -> String { + render_call_args(input) +} + impl Observation { /// Execution alone is not success: projected running/failed/undecodable /// results do not establish an effect. Legacy unprojected commands retain @@ -261,7 +269,7 @@ impl Observation { /// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part /// and its ledger line. pub(crate) fn call_line(&self) -> String { - format!("{}({})", self.call.name, render_call_args(&self.call.input)) + format!("{}({})", self.call.name, call_args(&self.call.input)) } /// The RECENCY-channel rendering: the FULL trace working memory keeps so the mind can act on From 895e6e72732014a669a55521f0faab59d61c7e40 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:47:49 -0500 Subject: [PATCH 06/11] WM slice: the provenance test stops asserting the old checkpoint tuple format Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/working_memory/tests/provenance.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 6358c7db5e..ca60a60915 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -185,14 +185,6 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { ); let encoded = serde_json::to_value(wm.snapshot()).expect("test: snapshot serializes"); - assert_eq!( - encoded["recent_results"][0] - .as_array() - .expect("test: persisted result tuple") - .len(), - 5, - "the existing checkpoint tuple format must remain compatible" - ); let restored = WorkingMemory::new(8); restored.restore(serde_json::from_value(encoded).expect("test: recorded snapshot decodes")); assert_eq!(restored.recent_results_messages(), messages); From 39ed38fdfeaf8ea31700e0a5750cef5f3c3d1804 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 00:52:12 -0500 Subject: [PATCH 07/11] WM slice: recent_results stays until checkpoint adoption moves onto its disk class handle (card 2b326931); adoption untouched Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../persona_workspace/checkpoint_adoption.rs | 12 ++++++------ .../src/cognition/working_memory.rs | 6 ++++++ .../src/cognition/working_memory/continuity.rs | 10 +++++++++- .../src/cognition/working_memory/tests/trail.rs | 1 + 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index 4b5c1b46ac..cccb5ab3ba 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -130,18 +130,18 @@ fn summary(bytes: &[u8]) -> Result { .as_ref() .is_some_and(|(seq, _)| *seq == 0 || *seq >= wm.next_action_seq) || wm - .action_records() + .recent_results .iter() - .any(|record| record.seq == 0 || record.seq >= wm.next_action_seq) + .any(|(seq, _, _, _, _)| *seq == 0 || *seq >= wm.next_action_seq) { return Err(invalid("receipt sequence must precede next_action_seq")); } let mut previous = None; - for record in wm.action_records() { - if previous.is_some_and(|old| old >= record.seq) { + for (seq, _, _, _, _) in &wm.recent_results { + if previous.is_some_and(|old| old >= *seq) { return Err(invalid("result receipt sequences must strictly increase")); } - previous = Some(record.seq); + previous = Some(*seq); } let utterances = match &persisted.own_speech { OwnSpeechPersisted::ByRoom(rooms) => { @@ -160,7 +160,7 @@ fn summary(bytes: &[u8]) -> Result { saved_at_ms: wm.saved_at_ms, next_action_seq: wm.next_action_seq, entries: wm.entries.len(), - result_receipts: wm.action_records().iter().filter(|record| record.result.is_some()).count(), + result_receipts: wm.recent_results.len(), own_utterances: utterances, unscoped_own_utterances: match &persisted.own_speech { OwnSpeechPersisted::ByRoom(_) => 0, diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index de18895a62..4db6a404ad 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -427,6 +427,12 @@ pub struct VolatileSnapshot { /// then says nothing rather than guessing a change it cannot see (#165). #[serde(default)] pub build_sha: String, + /// Retained results `(seq, room, result, operation, handle)`, read only by checkpoint + /// adoption's validation (`persona_workspace::checkpoint_adoption`). It goes when adoption's + /// writes move onto their disk class handle (ONE-BUDGET row 5, card 2b326931; then adoption reads + /// `actions`): the one shape is `actions`. + #[serde(default)] + pub recent_results: Vec<(u64, Option, String, String, Option)>, /// Her state at the seam — the whole held card, her ledger, what was staged, what tore /// the life (card 49b5e806, Kimi 2026-09-26). Stamped by `save_volatile`, which knows /// whose memory this is and why it is being written; rendered FIRST on wake. `None` on diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 1ef0c4c2dc..e37fdbba32 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -181,13 +181,21 @@ impl WorkingMemory { (entries, authored) }; let last_action = self.last_action.lock().clone(); - let records: Vec = self.actions.lock().records().cloned().collect(); + let (records, recent_results) = { + let actions = self.actions.lock(); + let recent_results: Vec<(u64, Option, String, String, Option)> = actions + .retained() + .filter_map(|r| r.result.clone().map(|result| (r.seq, r.room, result, r.operation.clone(), r.handle.clone()))) + .collect(); + (actions.records().cloned().collect::>(), recent_results) + }; VolatileSnapshot { pending_emissions: self.pending_emissions.lock().clone(), entries, action_statements, last_action, action_fps: self.action_fps.lock().iter().cloned().collect(), + recent_results, next_action_seq: self.next_action_seq.load(Ordering::Relaxed), saved_at_ms: continuum_base::time::EpochMs::now().millis(), build_sha: env!("CONTINUUM_BUILD_GIT_SHA").to_string(), diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index c0f1c27d7f..849cf8218c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -262,6 +262,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { action_statements: Vec::new(), last_action: None, action_fps: Vec::new(), + recent_results: Vec::new(), next_action_seq: 1, saved_at_ms: 0, // pre-field snapshot: no save time guessed interrupted_dispatches: Vec::new(), From d94939b24c230df623a6e7591950216b9833b49a Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 01:09:56 -0500 Subject: [PATCH 08/11] WM slice: no retirement by order (Codex on #5637). A finished dispatch stays until the submitted render receipt acknowledges it; an act recorded later proves nothing about an optional source being sent. retire_perceived_dispatches is deleted; the 16-handle cap stays gone Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/working_memory.rs | 2 +- .../src/cognition/working_memory/ledger.rs | 5 +---- .../cognition/working_memory/perception.rs | 16 +++------------- .../cognition/working_memory/tests/actions.rs | 19 ++++++++----------- 4 files changed, 13 insertions(+), 29 deletions(-) diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 4db6a404ad..3df55a262d 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -251,7 +251,7 @@ pub struct WorkingMemory { /// SAME recency channel as `last_action`, but keyed so concurrent sentinels/compiles/ /// debuggers stream in without clobbering each other. Fed by the completion/progress /// listener (`record_dispatch_event`); surfaced by the faculty so the mind perceives - /// "what I sent away, and where it's at" each heartbeat. A finished handle retires once she has answered a prompt that showed its end. + /// "what I sent away, and where it's at" each heartbeat. A finished handle stays until a submitted render receipt shows its end reached her. dispatched: Mutex>, /// Monotonic stamp applied to ACTION entries. Two reasons: (1) it makes each /// recorded action a DISTINCT string even when the persona repeats the identical diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 890bf869f2..a6c4f54e54 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -301,10 +301,7 @@ impl WorkingMemory { // The record and the active slot publish together, so a concurrent publisher // cannot prune a not-yet-visible receipt. let mut actions = self.actions.lock(); - let previous = self.last_action.lock().replace((seq, a.to_string())); - if let Some((answered_since, _)) = previous { - self.retire_perceived_dispatches(answered_since); - } + *self.last_action.lock() = Some((seq, a.to_string())); actions.push( action_log::ActionRecord { seq, diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 9723b13fef..8db4716ce0 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -348,8 +348,9 @@ impl WorkingMemory { /// `Done`/`Failed` marks it. The mind perceives outstanding + freshly-finished handles /// via the faculty next heartbeat, so it can act on a result the moment it lands /// without ever blocking. `label` is set once (first event) and preserved across - /// updates. A finished handle retires once she has answered a prompt that showed its end - /// ([`Self::retire_perceived_dispatches`]); a running one never does + /// updates. A finished handle stays until a submitted render receipt shows its end reached + /// her (HER-TASKS' acknowledge point, the render receipt in progress); until that exists + /// nothing retires one, so an end she has not perceived is never dropped (Codex on #5637) /// ([[act-results-need-a-recency-channel-not-semantic-recall]]). pub fn record_dispatch_event( &self, @@ -371,17 +372,6 @@ impl WorkingMemory { entry.seq = seq; } - /// Retire every finished handle whose end she has perceived: one whose terminal event is - /// older than `answered_since`, the sequence of an act recorded before the act now being - /// recorded. That act's prompt was built after it, and her view renders every dispatched - /// handle, so the end was in a prompt she answered. Acts and dispatch events share one - /// sequence, so this is an ordering, never a count; a running handle never retires. - pub(super) fn retire_perceived_dispatches(&self, answered_since: u64) { - self.dispatched - .lock() - .retain(|_, action| action.status == DispatchStatus::Running || action.seq >= answered_since); - } - /// The label of a dispatched handle THIS persona owns, or `None` if the handle isn't /// ours (never dispatched here, or already evicted). The async-dispatch listener uses /// it to claim ONLY its own completions off the shared `command:completed` bus — other diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index d5e6f3db96..1970810ef4 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -177,25 +177,22 @@ async fn dispatched_commands_stream_back_by_handle() { ); } -// what this catches: a finished background handle held forever (the old 16-handle cap only -// evicted past a count) or dropped before she could see how it ended. It retires once she has -// answered a prompt built after its end (an act recorded after the act that followed it); a -// running handle never retires, however many acts pass. +// what this catches: a finished background handle dropped before a submitted prompt showed her +// its end. An act recorded later proves nothing about an optional source being allocated (Codex +// on #5637), so nothing retires a handle until the render receipt acknowledges it: the old +// 16-handle count evicted finished ends she may never have seen. #[test] -fn a_finished_dispatch_retires_once_she_has_answered_a_prompt_that_showed_its_end() { +fn a_finished_dispatch_stays_until_a_receipt_acknowledges_it() { let wm = WorkingMemory::new(8); let (compile, sentinel) = (Uuid::from_u128(1), Uuid::from_u128(2)); wm.record_dispatch_event(sentinel, "research task", "searching…", DispatchStatus::Running); wm.record_dispatch_event(compile, "compile core", "0 errors", DispatchStatus::Done); - let handles = |wm: &WorkingMemory| wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect::>(); - wm.record_receipt("an act whose prompt may predate the compile's end"); - assert_eq!(handles(&wm).len(), 2, "the next act's prompt may not have shown it yet"); - wm.record_receipt("an act whose prompt was built after the compile ended"); - assert_eq!(handles(&wm), vec![sentinel], "its end was in a prompt she answered"); for _ in 0..20 { wm.record_receipt("more acts"); } - assert_eq!(handles(&wm), vec![sentinel], "a running handle never retires"); + let mut handles: Vec = wm.dispatched_snapshot().into_iter().map(|(h, ..)| h).collect(); + handles.sort(); + assert_eq!(handles, vec![compile, sentinel], "acts alone never retire a finished end, and a running one stays"); } // what this catches: record/recent round-trips, blank reasoning is ignored, and From aae0f503fac4de8e3c18db6b83231b0479614976 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 02:24:50 -0500 Subject: [PATCH 09/11] WM slice: drop the Faculty import the deleted faculty left unused (warning ratchet 14 -> 13) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/test_env/mind_integration/training_credit/directed.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index f8308553e7..cd5d6b3de0 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -7,7 +7,7 @@ use crate::ai::types::ToolCall; use crate::cognition::act_observe::test_support::{admission, body_with_wm, ScriptedExecutor}; use crate::cognition::act_observe::*; use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::workspace::{Faculty, SalienceArbiter, TurnFraming, WorkspaceCycle}; +use crate::cognition::workspace::{SalienceArbiter, TurnFraming, WorkspaceCycle}; // what this catches:41f4e3ef — a directed drive must persist real receipt-linked // progress before settlement; cancellation/rollback cannot lose the last whole From d69f8f30646f1f43dd1c6a06441edcc37ea468a9 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 03:01:57 -0500 Subject: [PATCH 10/11] WM slice: a record's line and summary stay in the memory owner's account (Codex on #5637) ActionRecord::resident_bytes charged only the resident body, but a ledger line renders a single-line argument whole and outlives every shed, so a large write's payload stayed in RAM outside the account after its body was reported shed. resident_bytes now charges every text the record owns (line, summary, body); body_bytes is what a shed releases, and shed candidates and collapse_over count it. The reporter's pinned charge (resident - movable) thus carries the lines, with no cap and no clip. Regression: a_whole_single_line_argument_stays_in_the_memory_owners_account_after_a_shed (a 64 KiB single-line content argument; a shed releases exactly its body, the line stays charged through a checkpoint roundtrip, the handle reachable). Mutation-proved: charging the body alone fails it. Reporter and trail fixtures add the pinned line bytes. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../tests/mind_results_reporter.rs | 28 +++++++++++++------ .../cognition/working_memory/action_log.rs | 23 +++++++++++---- .../src/cognition/working_memory/residency.rs | 6 ++-- .../working_memory/tests/action_log.rs | 27 ++++++++++++++++++ .../src/cognition/working_memory/tests/mod.rs | 5 ++++ .../cognition/working_memory/tests/trail.rs | 5 ++-- 6 files changed, 74 insertions(+), 20 deletions(-) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs index 7b783fcea1..bc69d458b4 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -38,6 +38,16 @@ fn saved(handle: &str) -> ResultCustody { } } +/// The bytes no shed releases: every record's ledger line and summary across `minds`. The memory +/// owner charges them as pinned (Codex on #5637), and they stay constant through every shed. +fn lines(minds: &Minds) -> u64 { + minds + .iter() + .flat_map(|(_, memory)| memory.snapshot().actions) + .map(|r| [r.head, r.summary].into_iter().flatten().map(|t| t.len() as u64).sum::()) + .sum() +} + /// Which of a mind's results are resident, by the name each body starts with. fn resident(memory: &WorkingMemory) -> Vec { memory @@ -70,12 +80,12 @@ fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { let minds: Minds = vec![(pa, Arc::clone(&a)), (pb, Arc::clone(&b))]; let proven = Mutex::new(ProvenCopies::default()); let total = resident_bytes(&minds); - assert_eq!(total, 7 * BODY as u64, "precondition: every body resident"); + assert_eq!(total, 7 * BODY as u64 + lines(&minds), "precondition: every body resident"); shed_to(&minds, total - 2 * BODY as u64, &proven); assert_eq!( resident_bytes(&minds), - 5 * BODY as u64, + 5 * BODY as u64 + lines(&minds), "exactly down to the allocation" ); assert_eq!(resident(&a), ["a2", "a3"], "a1 was the oldest received"); @@ -159,7 +169,7 @@ fn a_copy_that_cannot_reproduce_the_body_keeps_it_resident() { ["c1", "c2", "c3", "c5"], "unprovable copies keep their bodies; c4 moved" ); - assert_eq!(resident_bytes(&minds), 4 * BODY as u64); + assert_eq!(resident_bytes(&minds), 4 * BODY as u64 + lines(&minds)); } // what this catches (Cormac on #5595): `budget()` touching the filesystem. The monitor calls it @@ -179,11 +189,11 @@ fn budget_answers_from_the_proof_cache_without_the_filesystem() { let unproven = budget_of(&minds, &proven); assert_eq!( (unproven.min_bytes, unproven.max_bytes), - (4 * BODY as u64, 4 * BODY as u64), + (4 * BODY as u64 + lines(&minds), 4 * BODY as u64 + lines(&minds)), "nothing proven: all pinned" ); - shed_to(&minds, 3 * BODY as u64, &proven); + shed_to(&minds, 3 * BODY as u64 + lines(&minds), &proven); assert_eq!( resident(&memory), ["d2", "d3", "d4"], @@ -197,15 +207,15 @@ fn budget_answers_from_the_proof_cache_without_the_filesystem() { .to_owned(); std::fs::remove_dir_all(&dir).expect("test: remove the spill dir"); let cached = budget_of(&minds, &proven); - assert_eq!(cached.max_bytes, 3 * BODY as u64); + assert_eq!(cached.max_bytes, 3 * BODY as u64 + lines(&minds)); assert_eq!( - cached.min_bytes, BODY as u64, + cached.min_bytes, BODY as u64 + lines(&minds), "d2 and d3 proven from the cache; only the newest pinned" ); } // what this catches: the memory owner reading a wrong total, so it sheds too little or too -// much. `report()` is the sum of resident body BYTES across every mind (not characters: a +// much. `report()` is the sum of every record's BYTES across every mind (bodies, lines, summaries) (not characters: a // multi-byte body counts its bytes), and moves with every receipt and shed. #[test] fn report_sums_resident_bytes_across_minds() { @@ -224,7 +234,7 @@ fn report_sums_resident_bytes_across_minds() { b.record_receipt_typed(&[], &wide, None, saved("b1")); assert_eq!( resident_bytes(&minds), - 2 * BODY as u64 + wide.len() as u64, + 2 * BODY as u64 + wide.len() as u64 + lines(&minds), "bytes, not chars" ); assert_eq!( 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 997b49585c..759f25b8f1 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -74,9 +74,20 @@ impl ActionRecord { super::receipt_key(self.seq, self.handle.as_deref()) } - /// The RAM its resident body holds, in bytes: what the memory owner accounts, never a - /// character count (that is `stored_chars`, the view's price). + /// The RAM this record holds, in bytes: every text it owns (its ledger line, its summary and + /// its body while resident), so a line or summary that outlives a shed stays in the memory + /// owner's account as pinned charge (Codex on #5637). Never a character count (that is + /// `stored_chars`, the view's price). pub fn resident_bytes(&self) -> u64 { + [&self.head, &self.summary, &self.result] + .into_iter() + .map(|text| text.as_ref().map_or(0, |text| text.len() as u64)) + .sum() + } + + /// The bytes a shed releases: its resident body. The line and the summary stay with the + /// record for as long as her mind lives. + pub fn body_bytes(&self) -> u64 { self.result.as_ref().map_or(0, |result| result.len() as u64) } } @@ -145,7 +156,7 @@ impl ActionLog { .collect() } - /// The RAM every resident body holds, in bytes. + /// The RAM every record holds, in bytes: bodies, lines and summaries. pub fn resident_bytes(&self) -> u64 { self.records.iter().map(ActionRecord::resident_bytes).sum() } @@ -166,7 +177,7 @@ impl ActionLog { } /// Move the oldest evictable bodies to their handles until at most `budget` bytes stay - /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view + /// resident, counting every record's line and summary (which no shed releases). Each keeps its measured length (`stored_chars`) and its handle, so her view /// still prices and reloads its whole. Exactly to the budget: the memory owner decides /// when, so there is no hysteresis here. pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str) -> bool) -> Collapsed { @@ -179,14 +190,14 @@ impl ActionLog { self.evictable(saved) .take_while(|record| { let take = over > 0; - over = over.saturating_sub(record.resident_bytes()); + over = over.saturating_sub(record.body_bytes()); take }) .map(|record| record.seq) .collect() }; for record in self.records.iter_mut().filter(|record| chosen.contains(&record.seq)) { - total -= record.resident_bytes(); + total -= record.body_bytes(); record.stored_chars = record.result.as_ref().map(|result| result.chars().count()); record.result = None; } diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs index 80aa89067b..4975d3bf3c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/residency.rs +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -24,7 +24,7 @@ pub(crate) struct ShedCandidate { /// One mind's resident result bodies, read under her lock with no filesystem access. #[derive(Debug, Clone)] pub(crate) struct ResidentResults { - /// Bytes of every resident body. + /// Bytes of every record: resident bodies, plus the lines and summaries no shed releases. pub resident_bytes: u64, /// Saved bodies other than the newest, oldest first: what a shed may move once each /// candidate's output is vouched for. @@ -32,7 +32,7 @@ pub(crate) struct ResidentResults { } impl WorkingMemory { - /// The RAM her resident result bodies hold, in bytes. Cheap: one pass, no allocation. + /// The RAM her action records hold, in bytes: bodies, lines and summaries. Cheap: one pass, no allocation. pub(crate) fn resident_result_bytes(&self) -> u64 { self.actions.lock().resident_bytes() } @@ -48,7 +48,7 @@ impl WorkingMemory { received_ms: record.received_ms, seq: record.seq, handle: record.handle.clone()?, - bytes: record.resident_bytes(), + bytes: record.body_bytes(), }) }) .collect(); 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 34a462b411..60b53380da 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 @@ -76,3 +76,30 @@ fn an_acts_arguments_are_whole_or_plainly_elided_never_cut() { assert!(!line.contains("fn main() {}"), "a multi-line body is referenced, not repeated: {line}"); assert!(line.contains("[1,40]"), "{line}"); } + +// what this catches (Codex on #5637): a ledger line outside the memory owner's account. A +// single-line argument renders whole in her line however long, and the line outlives every +// shed, so an account of bodies alone reported a write's bytes shed while its payload stayed +// in RAM in the line. Every byte a record keeps is charged; a shed releases its body and the +// line stays as pinned charge, through a checkpoint roundtrip with its handle reachable. +#[test] +fn a_whole_single_line_argument_stays_in_the_memory_owners_account_after_a_shed() { + let payload = "x".repeat(16 * BODY); + let mut act = crate::cognition::act_observe::test_support::act("code/write", Some("/w/a.txt")); + act.call.input = serde_json::json!({"file_path": "/w/a.txt", "content": payload}); + let wm = WorkingMemory::new(8); + wm.record_receipt_typed(&[act], &"wrote\n".repeat(BODY), None, saved("write-handle")); + record_saved(&wm, "newest"); + let before = wm.resident_results(); + let write = before.candidates.iter().find(|c| c.handle == "write-handle").expect("test: the write is sheddable"); + assert!(before.resident_bytes >= payload.len() as u64 + write.bytes, "line and body both charged: {before:?}"); + shed(&wm, 0); + let after = wm.resident_results(); + assert!(after.candidates.iter().all(|c| c.handle != "write-handle"), "its body moved to its handle"); + assert!(after.resident_bytes >= payload.len() as u64, "the line is still charged: {after:?}"); + assert_eq!(before.resident_bytes - after.resident_bytes, write.bytes, "a shed releases exactly its body"); + let restored = WorkingMemory::new(8); + restored.restore(wm.snapshot()); + assert_eq!(restored.resident_results().resident_bytes, after.resident_bytes, "the charge survives a restart"); + assert!(restored.actions.lock().records().any(|r| r.handle.as_deref() == Some("write-handle")), "its handle is reachable"); +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index 856fa8a36d..3647726cab 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -25,6 +25,11 @@ fn record_saved(wm: &WorkingMemory, text: &str) { /// size is the test's choice; production has no such number (the memory owner sheds). const BODY: usize = 4_096; +/// The bytes no shed releases: her records' ledger lines and summaries, charged as pinned. +fn line_bytes(wm: &WorkingMemory) -> usize { + wm.actions.lock().records().map(|r| (r.resident_bytes() - r.body_bytes()) as usize).sum() +} + /// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, /// with every handle's saved output vouched for. fn shed(wm: &WorkingMemory, budget: usize) { 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 849cf8218c..470361f018 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -26,7 +26,8 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { for _ in 0..8 { record_saved(&wm, &"x".repeat(unit)); } - shed(&wm, 4 * unit); + let pinned = line_bytes(&wm); + shed(&wm, 4 * unit + pinned); let messages = wm.recent_results_messages(); let kept: Vec<&String> = messages.iter().filter(|m| m.starts_with("[result ")).collect(); assert!(!kept.is_empty(), "the newest results stay"); @@ -39,7 +40,7 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { !messages.join("\n").contains("E0601"), "the oldest collapse to pointers once shed — bounded, not immortal" ); - assert!(wm.resident_result_bytes() <= 4 * unit as u64, "down to the allocation: {}", wm.resident_result_bytes()); + assert!(wm.resident_result_bytes() <= (4 * unit + pinned) as u64, "down to the allocation: {}", wm.resident_result_bytes()); // Between sheds the ring only appends: receipts and settles move nothing, so the head // stays byte-identical (the KV divergence audit, 2026-09-13). let head_after_collapse = wm.recent_results_messages().get(1).cloned(); From 67cf48cb02c128e5087eb2a74da79e6e15ae9b2e Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 03:56:47 -0500 Subject: [PATCH 11/11] WM slice: drop the Faculty import wake_backlog's test no longer uses (a test-profile warning the lib ratchet does not count) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- core/continuum-mind/src/persona/wake_backlog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index a347c40809..6b77a393d0 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -627,7 +627,7 @@ mod tests { use crate::cognition::act_observe::test_support::{admission, body_with_wm, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{drive_to_settle_with_input, SettleStep}; use crate::cognition::working_memory::WorkingMemory; - use crate::cognition::workspace::{Burst, Faculty, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; + use crate::cognition::workspace::{Burst, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; use std::sync::{Arc, Mutex}; use crate::cognition::conversation::scripted_conversation::ScriptedConversation; use crate::cognition::conversation::{IncomingMessage, PersonaConversation};