diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index 86bfebcdfb..8fe8764dbc 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -14,13 +14,15 @@ pub(super) async fn eval_settle( let delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: prompt.to_string(), tokens: 0, metadata: serde_json::json!({ "peer_id": "peer", "occurred_at_ms": EVAL_EPOCH_MS }), }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let burst = crate::cognition::workspace::Burst::from_turns( room, diff --git a/core/continuum-academy/src/cognition/eval/run_pass.rs b/core/continuum-academy/src/cognition/eval/run_pass.rs index 248f837b94..36d1e4082d 100644 --- a/core/continuum-academy/src/cognition/eval/run_pass.rs +++ b/core/continuum-academy/src/cognition/eval/run_pass.rs @@ -205,6 +205,9 @@ pub(super) async fn run_pass( let task_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: framed_prompt, tokens: 0, metadata: serde_json::json!({ @@ -214,7 +217,6 @@ pub(super) async fn run_pass( }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; // own_peer/agent_name attribute the persona's OWN past posts; a single-task // exam has none, so they're inert here (the item's peer_id "peer" ≠ ""). @@ -400,6 +402,9 @@ pub(super) async fn run_pass( let nudge_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!( "You did not answer. This is a GRADED exam question and you must answer it \ now — do NOT reply PASS or stay silent. Provide your complete solution:\n\n{}", @@ -410,7 +415,6 @@ pub(super) async fn run_pass( }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let nudge_burst = crate::cognition::workspace::Burst::from_turns( room, @@ -519,6 +523,9 @@ pub(super) async fn run_pass( let red_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!( "You settled, but the task's definition-of-done currently FAILS. Its output ends: @@ -531,7 +538,6 @@ Fix the workspace and finish — the grade reads th }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let red_burst = crate::cognition::workspace::Burst::from_turns( room, diff --git a/core/continuum-academy/src/cognition/eval/warm_gate.rs b/core/continuum-academy/src/cognition/eval/warm_gate.rs index 53f1a61975..7995ea34fc 100644 --- a/core/continuum-academy/src/cognition/eval/warm_gate.rs +++ b/core/continuum-academy/src/cognition/eval/warm_gate.rs @@ -9,13 +9,15 @@ pub(super) async fn warm_gate(cycle: &crate::cognition::workspace::WorkspaceCycl let probe_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: "ready check".to_string(), tokens: 0, metadata: serde_json::json!({ "peer_id": "peer", "occurred_at_ms": EVAL_EPOCH_MS }), }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let mut warm = false; for _ in 0..15u32 { diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index 49b3a77b9e..41f88bf154 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -437,7 +437,7 @@ pub async fn apply_act( }, status: ActStatus::Executed, }; - observation.push_str(&obs.render_recency(intent, &budget)); + observation.push_str(&obs.render_recency(intent)); 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/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs index cf35f4d70b..331ed6720d 100644 --- a/core/continuum-cognition/src/cognition/act_observe/observation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/observation.rs @@ -22,7 +22,6 @@ use serde::{Deserialize, Serialize}; use ts_rs::TS; use crate::ai::types::{ToolCall, ToolResult}; -use crate::cognition::context_budget::ContextBudget; use super::recency::{ humanize_result_content, render_act_for_recall, @@ -264,15 +263,10 @@ 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`. - pub fn render_recency(&self, intent: &str, budget: &ContextBudget) -> String { - Self::render_recency_impl(self, intent, budget) - } - - fn render_recency_impl(&self, intent: &str, budget: &ContextBudget) -> String { - let fold = Some(budget.echoed_arg_chars()); - let args = summarize_args_for_recency(&self.call.input, fold); + pub fn render_recency(&self, intent: &str) -> String { + let args = summarize_args_for_recency(&self.call.input); // The intent rides the result as a ONE-LINE reason, clipped to the same - // window-relative echo budget the args get — never the whole monologue. + // fixed echo bound the args get (ECHOED_ARG_CHARS) — 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 @@ -280,7 +274,7 @@ impl Observation { let because = if intent.trim().is_empty() { String::new() } else { - format!(" because {}", clip_intent(intent, budget.echoed_arg_chars())) + format!(" because {}", clip_intent(intent, super::recency::ECHOED_ARG_CHARS)) }; format!( "{}({}){}\nResult:\n{}\n\n", @@ -295,8 +289,8 @@ impl Observation { /// args, the same fold) over its HUMANIZED body at `level` (its summary, else whole), so a /// 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, budget: &ContextBudget, level: impl Fn(&str) -> Option) -> String { - let args = summarize_args_for_recency(&self.call.input, Some(budget.echoed_arg_chars())); + pub(crate) fn render_summary_part(&self, level: impl Fn(&str) -> Option) -> String { + let args = summarize_args_for_recency(&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 diff --git a/core/continuum-cognition/src/cognition/act_observe/recency.rs b/core/continuum-cognition/src/cognition/act_observe/recency.rs index f076cb6ee8..645e3d3403 100644 --- a/core/continuum-cognition/src/cognition/act_observe/recency.rs +++ b/core/continuum-cognition/src/cognition/act_observe/recency.rs @@ -77,6 +77,13 @@ pub(super) fn humanize_result_content(raw: &str) -> String { } } +/// How much of one argument she wrote is echoed back in its result's header, and of the +/// intent line beside it. A rule for showing her own words, which her tool call already +/// carries whole, never a share of the window: the recall sibling below is a constant for +/// the same reason. It was a fixed 600 before it became `ContextBudget::echoed_arg_chars` +/// (a 64th of the window, a second budget her view's allocation never saw). +pub(super) const ECHOED_ARG_CHARS: usize = 600; + /// Collapse tool ARGS for the RECENCY channel (working memory). /// /// The recall path has collapsed big args since it was written — `summarize_args_for_recall` @@ -90,18 +97,11 @@ pub(super) fn humanize_result_content(raw: &str) -> String { /// into working memory as ARGS, ahead of the `EDIT REFUSED` result carrying the diagnostic she /// needed. On a 16k-token lane there is no room left for the diagnosis to survive. /// -/// Deliberately MUCH more generous than the recall bound (600 vs 80 chars): recency is shown -/// once and she may genuinely need to see the edit she just issued. Only a pathological -/// whole-file paste collapses. -/// -/// `budget` is `None` when the live window is UNKNOWN (no model binding). Then nothing folds. -/// An unknown window must never become an invented one — that is how a guess turns into a -/// clamp that outlives the guess. -pub(super) fn summarize_args_for_recency( - args: &serde_json::Value, - budget: Option, -) -> String { - let fold_at = budget.unwrap_or(usize::MAX); +/// Deliberately MUCH more generous than the recall bound ([`ECHOED_ARG_CHARS`] vs 80 chars): +/// recency is shown once and she may genuinely need to see the edit she just issued. Only a +/// pathological whole-file paste collapses. +pub(super) fn summarize_args_for_recency(args: &serde_json::Value) -> String { + let fold_at = ECHOED_ARG_CHARS; match args { serde_json::Value::Object(map) => map .iter() @@ -211,7 +211,6 @@ pub(super) fn render_act_for_recall( #[cfg(test)] mod tests { - use crate::cognition::context_budget::ContextBudget; use crate::sdk_codegen::{ActVerdict, ToolVerdict}; /// The two pre-#4352 states this file used to take as a bare bool. const OK_V: ActVerdict = ActVerdict::Declared(ToolVerdict::Succeeded); @@ -372,10 +371,7 @@ mod tests { fn a_whole_file_arg_is_not_echoed_back_ahead_of_the_result() { let whole_file = "x = 1\n".repeat(4000); // ~24k chars, a real source file let args = serde_json::json!({ "file_path": "sympy/core/basic.py", "content": whole_file }); - let rendered = summarize_args_for_recency( - &args, - Some(ContextBudget::from_window(16_384).echoed_arg_chars()), - ); + let rendered = summarize_args_for_recency(&args); assert!( rendered.chars().count() < 400, "a whole-file arg must collapse, not flood: {} chars", @@ -396,10 +392,7 @@ mod tests { "file_path": "a.py", "new_content": "def f():\n return refine_arg(x)\n" }); - let kept = summarize_args_for_recency( - &small, - Some(ContextBudget::from_window(16_384).echoed_arg_chars()), - ); + let kept = summarize_args_for_recency(&small); assert!( kept.contains("refine_arg"), "an ordinary edit stays visible verbatim: {kept}" diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs index 997fc5882b..5d5fb59b36 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs @@ -173,11 +173,9 @@ pub async fn settle_step( // read the typed acts (verb + paths) off these entries, not receipt prose, // so they survive the seam-5 live-drift the `I ran …` scans died on. let pre_settle = body.working_memory.recent_entries(); - let head: String = text - .chars() - .take(body.working_memory.budget().trail_head_chars()) - .collect(); - body.working_memory.record_settlement(&head, Some(ws.activity_room_id)); + // Whole: what of it her trail shows is the trail's levels in her view's one + // allocation, never a head cut at a window share here (FLOW §2d). + body.working_memory.record_settlement(&text, Some(ws.activity_room_id)); // Unfulfilled-promise backstop (#122): a Speak that NARRATES action // (first-person intent + fence) which nothing lifted/executed — // reaching this arm means no format recognized it — leaves her diff --git a/core/continuum-cognition/src/cognition/cached_source.rs b/core/continuum-cognition/src/cognition/cached_source.rs index e950d3b746..c493ad38c2 100644 --- a/core/continuum-cognition/src/cognition/cached_source.rs +++ b/core/continuum-cognition/src/cognition/cached_source.rs @@ -17,8 +17,7 @@ //! event, workspace-map until one of the persona's own write receipts. The owner //! who constructs the wrap holds a [`DirtyHandle`] and connects it to that event; //! `deliver` never re-fetches on the compose path unless dirty (or the cache -//! genuinely cannot answer: different room, or a bigger budget could yield more -//! from a source that truncated). No benchmark/drive mode — an exam composes fast +//! genuinely cannot answer: a different room). No benchmark/drive mode — an exam composes fast //! because nothing it depends on changes, a live room gets the same win because //! rosters and doctrine barely change there either. //! @@ -31,9 +30,7 @@ use std::sync::Arc; use async_trait::async_trait; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagSource}; /// The invalidation lever the OWNER wires to the source's change event. /// Cloneable and cheap; `mark()` from any thread/task. @@ -107,14 +104,12 @@ impl CachedRagSource { /// Can `cached` answer THIS call without a fetch? /// /// - Same room (a projection is room-scoped state). - /// - It fits the budget (`tokens_used <= budget`). - /// - It is COMPLETE (`!truncated`) **or** the budget hasn't grown past what - /// it was able to spend — a truncated delivery under a bigger budget - /// could legitimately yield more, so it re-fetches. - fn answers(cached: &CachedDelivery, room: Option, budget: u32) -> bool { + /// - Not invalidated (the caller checks `dirty` before asking). + /// + /// A source is never handed a size, so a delivery is not budget-shaped and + /// `truncated` is the source's own fetch limit: neither changes the answer. + fn answers(cached: &CachedDelivery, room: Option) -> bool { cached.room == room - && cached.delivery.tokens_used <= budget - && (!cached.delivery.truncated || budget <= cached.delivery.tokens_used) } } @@ -132,25 +127,12 @@ impl RagSource for CachedRagSource { self.inner.expand_command() } - fn floor_tokens(&self) -> u32 { - self.inner.floor_tokens() - } - - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - self.inner.budget_claim(window, headroom) - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { let room = ctx.airc_room.as_ref().map(|r| r.as_uuid()); let mut guard = self.last_good.lock().await; if !self.dirty.load(Ordering::SeqCst) { if let Some(cached) = guard.as_ref() { - if Self::answers(cached, room, budget) { + if Self::answers(cached, room) { return cached.delivery.clone(); } } @@ -159,7 +141,7 @@ impl RagSource for CachedRagSource { // an event landing mid-fetch must not be lost (swap-then-check would // serve a projection already known stale). self.dirty.store(false, Ordering::SeqCst); - let delivery = self.inner.deliver(ctx, budget, resolution).await; + let delivery = self.inner.deliver(ctx).await; *guard = Some(CachedDelivery { delivery: delivery.clone(), room, @@ -187,27 +169,17 @@ mod tests { fn expand_command(&self) -> Option<&'static str> { None } - fn floor_tokens(&self) -> u32 { - 1 - } - async fn deliver( - &self, - _ctx: &RagContext, - _budget: u32, - _resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, _ctx: &RagContext) -> RagDelivery { let n = self.fetches.fetch_add(1, Ordering::SeqCst) + 1; - RagDelivery { - source_id: "counting".to_string(), - items: vec![crate::cognition::rag_budget::RagItem { - content: format!("fetch #{n}"), - tokens: 4, - metadata: serde_json::json!({}), - }], - tokens_used: 4, - truncated: false, - resolution_used: ResolutionPreference::Raw, - } + RagDelivery::of( + "counting", + vec![crate::cognition::rag_budget::RagItem::whole( + "counting", + format!("fetch #{n}"), + serde_json::json!({}), + )], + false, + ) } } @@ -225,7 +197,7 @@ mod tests { let ctx = RagContext::for_persona(me, 0); for _ in 0..5 { - let d = cached.deliver(&ctx, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&ctx).await; assert_eq!( d.items[0].content, "fetch #1", "unchanged world → cached projection" @@ -238,7 +210,7 @@ mod tests { ); dirty.mark(); - let d = cached.deliver(&ctx, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&ctx).await; assert_eq!( d.items[0].content, "fetch #2", "dirty → exactly one refetch" @@ -247,7 +219,7 @@ mod tests { // A DIFFERENT room must not see this room's projection (exam-bleed class). let other = RagContext::for_persona_in_room(me, 0, uuid::Uuid::new_v4()); - let d = cached.deliver(&other, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&other).await; assert_eq!( d.items[0].content, "fetch #3", "room switch → fresh fetch, never bleed" diff --git a/core/continuum-cognition/src/cognition/channel_digest.rs b/core/continuum-cognition/src/cognition/channel_digest.rs index 31c895aa81..2ba3a18e8b 100644 --- a/core/continuum-cognition/src/cognition/channel_digest.rs +++ b/core/continuum-cognition/src/cognition/channel_digest.rs @@ -408,8 +408,8 @@ mod tests { "first sight splits one page back — the seed the caller then persists" ); - // Now the DELIVERY step marks what she was shown as read — what - // `AircRagSource::deliver` does with the packed read-through lamport. The + // Now her read receipt marks what a sent prompt showed her as read — what + // `AircRagSource::mark_read` does after the deliberation faculty sends. The // seed bounds the page; the advance consumes it. Both halves are needed, // and together the room goes QUIET with nothing new. Before the fix, the // whole transcript came back as unread on every single turn forever. diff --git a/core/continuum-cognition/src/cognition/context_budget.rs b/core/continuum-cognition/src/cognition/context_budget.rs index 95180b48eb..7758c66098 100644 --- a/core/continuum-cognition/src/cognition/context_budget.rs +++ b/core/continuum-cognition/src/cognition/context_budget.rs @@ -116,6 +116,26 @@ impl ContextBudget { } } + /// The window her prompt is fitted to: the knee the dyno measured in her own traffic, never + /// above the served slot. Stable by construction: it does not move with load, so it never + /// turns an epoch over mid-flight. + /// + /// Why a token count from the dyno and not a rate: the knee is where a smaller window's + /// turnovers start to cost more than the smaller context saves, and it is counted in + /// tokens of her own requests, so it does not depend on how fast the engine is. A rate + /// does, and moves with load. Deriving the window from the live prefill-rate EMA + /// (f45f090a6, M5 2026-10-28) moved it 48k -> 40k -> 32k as contention lowered the rate, + /// refused Aris twice at 32k and turned epochs over 74 times in 37 minutes. Rolled back. + /// + /// Measured 2026-10-28 (continuum-context replay --append-tail over all four residents' + /// captures, `~/.continuum/evidence/2026-10-28-working-window/`): at 48k, prefill per + /// request fell ~3x (Benchy 110 -> 41 s, Aiko 81 -> 24, Aris 113 -> 33, Atlas 94 -> 20) + /// with zero handles dropped; 32k doubled turnovers. Re-measure by rerunning the replay; + /// the act inspector tracking the knee continuously is the next step. + pub fn working_window(served: u32) -> u32 { + Self::working_window_when(served, crate::inference::llama_server::current_serving().active_model.is_some()) + } + /// The served window only — the KV-capacity reading, for seams that must not be /// prefill-bounded (a test fixture, a capacity report). pub fn from_window_unbounded(context_window: u32) -> Self { @@ -292,8 +312,21 @@ fn prefill_affordable_window_for(served: u32, audience: crate::inference::prefil affordable } -/// Share of the served window recall may spend. See [`ContextBudget::recall_tokens`]. -const RECALL_DENOM: usize = 10; +/// The working window's measured knee, in tokens (see [`Self::working_window`]). +// derived-or-floor: derived — the dyno's knee over the M5 residents' own captures, 2026-10-28 +// (~/.continuum/evidence/2026-10-28-working-window/): 48k cut prefill per request ~3x with +// zero handles dropped; 32k doubled turnovers; 64k kept 1.5-2x more prefill. +const WORKING_WINDOW_TOKENS: u32 = 49_152; + +/// PURE: the working window for a served slot of `served` tokens, when a model is `serving`: the +/// measured knee, never above the slot. With nothing served (a fixture) it is the served window. +fn working_window_when(served: u32, serving: bool) -> u32 { + if served == 0 || !serving { + return served; + } + Self::WORKING_WINDOW_TOKENS.min(served) +} + /// Whether a window is known: every bound below is a real number, not "no bound". pub fn is_known(&self) -> bool { @@ -376,116 +409,6 @@ const RECALL_DENOM: usize = 10; self.fraction(4) } - /// One source's grounding offer, in tokens. Preserve the source bridge's - /// window-relative share (task #124: 4096 on a 16k window), but apply the - /// same measured prefill affordability as recall, tools and working memory. - /// This is an offer ceiling, not a reservation: the existing prompt fitter - /// still allocates the assembled context and preserves complete source units. - /// Grounding and tool-output rendering have separate policy names even though - /// their current shares agree; changing one must not silently change the other. - pub fn grounding_tokens(&self) -> usize { - match self.total_chars { - Some(total) => (total / GUARD_CHARS_PER_TOKEN) / 4, - None => usize::MAX, - } - } - - /// ONE tool's one-line summary in the catalog she is offered. A catalog lists ~100 tools, - /// so an unbounded description per line re-creates the dump this bound exists to prevent — - /// but on a roomy window she can afford a fuller clause per tool, which is real PX. At a - /// 16k lane this is exactly the 96 chars the old constant hard-coded. - pub fn catalog_summary_chars(&self) -> usize { - self.fraction(512) - } - - /// Default CEILING on one response's generated length, in TOKENS (not chars) — the role's - /// fallback budget when it declares none. An eighth of the window: enough that a real - /// answer (a function, a diff, a traceback walk) is never truncated mid-thought, while - /// still leaving the prompt its room. #45's doctrine is that the adapter owns generation - /// length; this is the fallback for a role that says nothing, and like every other bound - /// here it must scale — a `512` default silently truncates every model's answers equally, - /// whether it holds 4k or 1M. - pub fn default_response_tokens(&self) -> u32 { - match self.total_chars { - // total_chars = window * GUARD_CHARS_PER_TOKEN, so /8 in tokens is /(8*ratio) here. - Some(total) => ((total / GUARD_CHARS_PER_TOKEN) / 8).min(u32::MAX as usize) as u32, - None => u32::MAX, - } - } - - /// Tokens recall may spend surfacing past memories. - /// - /// Recall is ONE perception faculty among many (roster, doctrine, working memory) - /// plus the room transcript and the identity prompt — it must never crowd them - /// out. `1/RECALL_DENOM` keeps the live message dominant while still carrying the - /// relevant past, and it SCALES: a 1M-context model gets proportionally more - /// recall instead of a fixed 4k-shaped slice. - /// - /// Moved here 2026-08-20 from `recall_faculty.rs`, where it lived as - /// `RECALL_WINDOW_FRACTION: f32 = 0.10` — a bare float that this module's own - /// guard could not see, because the guard's type list stopped at the integers. - /// Widening it to floats surfaced this on the first run. - pub fn recall_tokens(&self) -> usize { - match self.total_chars { - Some(total) => (total / GUARD_CHARS_PER_TOKEN) / Self::RECALL_DENOM, - None => usize::MAX, - } - } - - /// Share of the window the TOOL MENU may occupy. See [`Self::tool_surface_tokens`]. - const TOOL_SURFACE_DENOM: usize = 4; - - /// The most the offered tool schemas may cost before the surface must narrow to her - /// hands. A menu, not a meal: `1/TOOL_SURFACE_DENOM` of the served window. - /// - /// ## Why a bound existed nowhere, and what it cost - /// - /// `native_tool_specs` is DERIVED — every command marked `NATIVE = true` is offered - /// automatically. That is the right architecture, and it means the surface grows as an - /// unbounded side effect of a flag set in another file (+52 % in two weeks, #460). The - /// per-turn COST was already memoized (`describe_tool_tokens`) and compared against - /// nothing. - /// - /// Measured 2026-09-07 04:1xZ on IntelMac (card e20e064f): a 0.5B citizen on a 32,768 - /// window took 37 schemas ≈ 8,735 tokens — larger than her framing (3,189) and her - /// entire conversation (3,551) combined — for `demand_tokens` 31,895 against 32,768, - /// i.e. 97.3 % of the window consumed before she wrote a token. She published her - /// prompt preamble to the room instead of answering. - /// - /// ## Why `1/4`, calibrated rather than invented - /// - /// Chosen so the lanes where the full surface DEMONSTRABLY works keep it, and only the - /// ones where it crowds out the conversation narrow. Against the same 8,735-token - /// surface: - /// - /// | served window | 1/4 allowance | full surface | - /// |---------------|---------------|--------------| - /// | 50,944 (M5 Ornith lane) | 12,736 | fits — unchanged | - /// | 32,768 (IntelMac 0.5B) | 8,192 | narrows — the measured failure | - /// | 24,832 (5090 per-slot) | 6,208 | narrows | - /// - /// `4` is also the denominator this module already uses for the two other "one big - /// thing may take a quarter" bounds (latest action, rendered tool slice), so the menu - /// is held to the same share as the single largest piece of content beside it. - /// - /// ## What narrowing must NOT mean - /// - /// Not amputation. Trimming the set outright is the #206 cliff — measured 14/14 SWE - /// acts spent on `commands/help` with 0 edits, because a citizen who cannot see a verb - /// and cannot look one up has only the asking-tool left. The narrowed surface is her - /// HANDS, which by construction retain the `commands/` discovery pair, so anything - /// withheld is still exactly one `commands/list` away. Bound the menu; never remove the - /// index. - /// - /// Unknown window folds nothing, per the module's unknown-window contract — an unknown - /// window must never become an invented one. - pub fn tool_surface_tokens(&self) -> usize { - match self.total_chars { - Some(total) => (total / GUARD_CHARS_PER_TOKEN) / Self::TOOL_SURFACE_DENOM, - None => usize::MAX, - } - } - /// Echo of ONE argument value back into the recency channel. The tightest bound, and /// deliberately so: she WROTE these one generation ago, so echoing a whole file's /// `content` back at her buys nothing and costs the window. @@ -610,25 +533,16 @@ mod tests { 1_024 ); - // Card 2bbee27a: grounding previously bypassed this rate ladder and - // offered a quarter of raw KV capacity while the other context sources - // used measured affordability. Exercise those same known/unknown rungs - // at the current 51,712-token geometry and a smaller-than-serve-floor - // window. These are deterministic policy inputs, not hardware receipts. - for (window, rate, expected) in [ - (51_712, MeasuredRate { tps: Some(1_000.0), source: RateSource::Fresh }, 12_928), - (51_712, MeasuredRate::UNKNOWN, crate::inference::prefill_rate::UNMEASURED_FILL_FLOOR_TOKENS / 4), - (256, MeasuredRate::UNKNOWN, 64), - (256, MeasuredRate { tps: Some(12.5), source: RateSource::Stale }, 64), - (0, MeasuredRate { tps: Some(1_000.0), source: RateSource::Fresh }, 0), + // Every rung, known or unknown, stays within the lane at the current geometry and a + // smaller-than-serve-floor window (deterministic policy inputs, not hardware receipts). + for (window, rate) in [ + (51_712, MeasuredRate { tps: Some(1_000.0), source: RateSource::Fresh }), + (51_712, MeasuredRate::UNKNOWN), + (256, MeasuredRate::UNKNOWN), + (256, MeasuredRate { tps: Some(12.5), source: RateSource::Stale }), + (0, MeasuredRate { tps: Some(1_000.0), source: RateSource::Fresh }), ] { - let affordable = ContextBudget::affordable_for_rate(rate, window, Audience::Interactive, None); - assert!(affordable <= window); - if window > 0 { - let budget = ContextBudget::from_window_unbounded(affordable); - assert_eq!(budget.grounding_tokens(), expected as usize); - assert!(budget.grounding_tokens() <= window as usize); - } + assert!(ContextBudget::affordable_for_rate(rate, window, Audience::Interactive, None) <= window); } } @@ -652,51 +566,11 @@ mod tests { assert_eq!(b.latest_action_chars(), 16_384 * GUARD_CHARS_PER_TOKEN); near(b.dispatch_result_chars(), 4_000); // DISPATCH_RESULT_MAX_CHARS near(b.render_slice_chars(), 12_000); // RENDER_BUDGET_CHARS - near(b.catalog_summary_chars(), 96); // SUMMARY_MAX_CHARS // Echoed args share the trail-head fraction (see the module doc's † note — the old // 600 was invented, not tuned, so it is not a calibration target). assert_eq!(b.echoed_arg_chars(), b.trail_head_chars()); } - /// what this catches: the tool-menu bound drifting off the lanes it was calibrated - /// against, in EITHER direction. `TOOL_SURFACE_DENOM` was chosen so the lanes where the - /// full 37-schema surface demonstrably works keep it, and only the ones where it crowds - /// out the conversation narrow — so both halves are asserted. Raising the denominator - /// silently amputates a working lane; lowering it re-admits the failure below. - /// - /// The 8,735 figure is measured, not assumed: IntelMac 2026-09-07, `tools_n=37`, and - /// `llm_deliberation_faculty`'s own comment independently puts 37 schemas at ~8.5k. - /// On that day a 0.5B on a 32,768 window spent it and reached `over_window` 0.973, - /// then published its prompt preamble to the room instead of answering (card e20e064f). - #[test] - fn the_tool_menu_bound_admits_the_lanes_it_was_calibrated_to_admit() { - const MEASURED_37_SCHEMA_SURFACE: usize = 8_735; - - // The M5's Ornith lane carries the full surface today and must keep carrying it — - // this fix must not narrow a lane that was never the problem. - assert!( - ContextBudget::from_window(50_944).tool_surface_tokens() >= MEASURED_37_SCHEMA_SURFACE, - "a 50,944-token lane must still be offered the whole surface" - ); - // The measured failure, and the 5090's per-slot window beside it. - for window in [32_768u32, 24_832] { - assert!( - ContextBudget::from_window(window).tool_surface_tokens() - < MEASURED_37_SCHEMA_SURFACE, - "a {window}-token window cannot afford 37 schemas and must narrow to hands" - ); - } - } - - /// what this catches: an unknown window inventing a tool-menu bound. Same contract as - /// every other bound here — unknown folds NOTHING, because an unknown window that - /// becomes a number is the exact bug this module exists to kill. A narrowing driven by - /// a guessed window would hide verbs from a citizen for no measured reason. - #[test] - fn an_unknown_window_never_narrows_the_tool_menu() { - assert_eq!(ContextBudget::unknown().tool_surface_tokens(), usize::MAX); - } - /// what this catches: the whole point of the module — a big window must actually GET a /// big budget. A regression that re-pins any bound to a constant fails here, because a /// 1M-context lane would keep returning the 16k-lane number. @@ -764,4 +638,16 @@ mod tests { assert_eq!(b.trail_head_chars(), usize::MAX); assert_eq!(b.echoed_arg_chars(), usize::MAX); } + + // what this catches: a working window that moves with load (f45f090a6 shrank it 48k -> + // 32k under contention and refused a resident) or exceeds the slot. With no served model + // (every test) it is the served window, as before. + #[test] + fn the_working_window_is_the_measured_knee_and_never_exceeds_the_slot() { + assert_eq!(ContextBudget::working_window_when(159_232, true), 49_152, "serving a wide slot: the measured knee"); + assert_eq!(ContextBudget::working_window_when(32_768, true), 32_768, "never above the slot"); + assert_eq!(ContextBudget::working_window_when(159_232, false), 159_232, "nothing served (a fixture): the served window"); + assert_eq!(ContextBudget::working_window_when(0, true), 0); + assert_eq!(ContextBudget::working_window(159_232), 159_232, "no served model in a test: the served window"); + } } diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 99d4c371fd..f28282076e 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -19,7 +19,7 @@ pub(crate) struct Actions<'a> { impl Actions<'_> { fn standing(key: &str, text: String) -> Item { let message = ContextMessage::user(text); - Item { key: key.to_owned(), full: message.clone(), summary: None, pointer: Some(message) } + Item { stored: None, key: key.to_owned(), full: message.clone(), summary: None, pointer: Some(message) } } } @@ -65,6 +65,7 @@ impl Source for Actions<'_> { } let mut items = vec![banner]; items.extend(acts.into_iter().map(|(seq, full, summary, pointer)| Item { + stored: None, key: seq.to_string(), full: ContextMessage::user(full), summary: summary.map(ContextMessage::user), diff --git a/core/continuum-cognition/src/cognition/context_streams/blocks.rs b/core/continuum-cognition/src/cognition/context_streams/blocks.rs index 624a1785f0..510a81b587 100644 --- a/core/continuum-cognition/src/cognition/context_streams/blocks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/blocks.rs @@ -1,19 +1,44 @@ //! A standing grounding block (the workspace map, the board, the wall, the roster) as a -//! source of one item: what it says now. A block that changes appends its new version; -//! itemizing a block further (one card, one open view) belongs in its own adapter, which -//! is also where a block gains pointers to collapse to. +//! source of one item: what it says now. A block that changes appends its new version. +//! +//! Its levels come from the source's own units (FLOW-IMPLEMENTATION-PLAN §2d): whole is +//! every unit whole, summary every unit at its summary, pointer every unit at the cheapest +//! level it offers. The block stays one item because each item renders as its own message; +//! choosing a level per unit (keep the best card whole, collapse the rest) waits on merging +//! adjacent items at render. use continuum_context::source::{Item, Source}; +use crate::cognition::rag_budget::RagItem; + use super::{priority, ContextMessage}; pub(crate) struct Grounding { pub faculty: String, /// The whole block. pub text: String, - /// What it guarantees when the window is short: a long list's first units with a line - /// naming what is omitted; an atomic block whole (then the same as `text`). + /// What it guarantees when the window is short, for a block with no units: a long + /// list's first units with a line naming what is omitted; an atomic block whole. pub minimum: String, + /// The source's keyed, levelled units, when it delivered them. + pub units: std::sync::Arc<[RagItem]>, +} + +impl Grounding { + /// A block with no units that is shown whole or not at all (a contract in force). + pub fn atomic(faculty: impl Into, text: impl Into) -> Self { + let text = text.into(); + Self { faculty: faculty.into(), minimum: text.clone(), text, units: std::sync::Arc::from(Vec::new()) } + } + + fn render(&self, body: String) -> ContextMessage { + ContextMessage::user(format!("[{}]\n{body}", self.faculty)) + } + + /// The block with every unit at the level `pick` chooses. + fn at(&self, pick: impl Fn(&RagItem) -> &str) -> String { + self.units.iter().map(pick).collect::>().join("\n") + } } impl Source for Grounding { @@ -26,10 +51,53 @@ impl Source for Grounding { } fn items(&self) -> Vec> { - // A block is what she works from now (her board, her checkout) with no handle to - // reopen it by, so collapsed it is still its truthful minimum, never a one-liner. - let full = ContextMessage::user(format!("[{}]\n{}", self.faculty, self.text)); - let pointer = ContextMessage::user(format!("[{}]\n{}", self.faculty, self.minimum)); - vec![Item { key: "block".to_owned(), full, summary: None, pointer: Some(pointer) }] + if self.units.is_empty() { + // A block is what she works from now (her board, her checkout) with no handle to + // reopen it by, so collapsed it is still its truthful minimum, never a one-liner. + let full = self.render(self.text.clone()); + let pointer = self.render(self.minimum.clone()); + return vec![Item { stored: None, key: "block".to_owned(), full, summary: None, pointer: Some(pointer) }]; + } + let whole = self.at(|unit| &unit.content); + let summary = self.units.iter().any(|unit| unit.summary.is_some()).then(|| { + self.at(|unit| unit.summary.as_deref().unwrap_or(&unit.content)) // a unit with no summary level is its own summary + }); + let pointer = self.at(|unit| unit.pointer.as_deref().or(unit.summary.as_deref()).unwrap_or(&unit.content)); // the cheapest level each unit offers + let summary = summary.filter(|summary| *summary != whole); + let pointer = (pointer != whole).then_some(pointer); + vec![Item { + stored: None, + key: "block".to_owned(), + full: self.render(whole), + summary: summary.map(|summary| self.render(summary)), + pointer: Some(pointer.map_or_else(|| self.render(self.minimum.clone()), |pointer| self.render(pointer))), // map_or_else: units with no coarser level keep the block's truthful minimum + }] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn grounding(units: Vec) -> Grounding { + let text = units.iter().map(|u| u.content.clone()).collect::>().join("\n"); + Grounding { faculty: "room-board".into(), minimum: text.clone(), text, units: units.into() } + } + + // what this catches: a source's levels never reaching her view (the block had only + // whole-or-first-units). Whole is every unit whole, summary every unit's summary, pointer + // every unit at its cheapest level, each smaller than the last. + #[test] + fn a_block_takes_its_levels_from_its_units() { + let card = |id: &str| { + RagItem::whole(id, format!("card {id}: a long description of the work"), serde_json::Value::Null) + .with_summary(format!("card {id}: short")) + .with_pointer(format!("[card {id}]")) + }; + let item = grounding(vec![card("a"), card("b")]).items().remove(0); + let text = |m: &ContextMessage| m.text.clone(); + assert_eq!(text(&item.full), "[room-board]\ncard a: a long description of the work\ncard b: a long description of the work"); + assert_eq!(item.summary.as_ref().map(text).as_deref(), Some("[room-board]\ncard a: short\ncard b: short")); + assert_eq!(item.pointer.as_ref().map(text).as_deref(), Some("[room-board]\n[card a]\n[card b]")); } } diff --git a/core/continuum-cognition/src/cognition/context_streams/conversation.rs b/core/continuum-cognition/src/cognition/context_streams/conversation.rs index e44cc77fbf..157f12878d 100644 --- a/core/continuum-cognition/src/cognition/context_streams/conversation.rs +++ b/core/continuum-cognition/src/cognition/context_streams/conversation.rs @@ -11,6 +11,9 @@ pub(crate) struct Turn { pub key: String, pub role: Role, pub line: String, + /// What remains when collapsing must not drop the turn (the index of messages that + /// reached her room during this turn). `None` for ordinary turns. + pub pointer: Option, } #[derive(Default)] @@ -31,13 +34,15 @@ impl Source for Conversation { self.turns .iter() .map(|turn| Item { + stored: None, key: turn.key.clone(), full: ContextMessage { role: turn.role, text: turn.line.clone() }, // Collapsed, a turn leaves her view: the room's history holds it, and the // `[context]` fact says how many turns the room offered. A one-line pointer would - // weigh about what a short turn does, saving nothing. + // weigh about what a short turn does, saving nothing. The room-update index keeps + // itself, so an update too large to show is never unknown. summary: None, - pointer: None, + pointer: turn.pointer.clone().map(|text| ContextMessage { role: turn.role, text }), }) .collect() } diff --git a/core/continuum-cognition/src/cognition/context_streams/notices.rs b/core/continuum-cognition/src/cognition/context_streams/notices.rs index 4e80900718..c7327a7ddd 100644 --- a/core/continuum-cognition/src/cognition/context_streams/notices.rs +++ b/core/continuum-cognition/src/cognition/context_streams/notices.rs @@ -17,7 +17,7 @@ pub(crate) struct Notices<'a> { /// A notice is required input: collapsed, it is still itself, so no grant can drop it. fn required(key: String, text: String) -> Item { let message = ContextMessage::user(text); - Item { key, full: message.clone(), summary: None, pointer: Some(message) } + Item { stored: None, key, full: message.clone(), summary: None, pointer: Some(message) } } impl Source for Notices<'_> { diff --git a/core/continuum-cognition/src/cognition/context_streams/open_views.rs b/core/continuum-cognition/src/cognition/context_streams/open_views.rs index 32830e6d8d..19def233c9 100644 --- a/core/continuum-cognition/src/cognition/context_streams/open_views.rs +++ b/core/continuum-cognition/src/cognition/context_streams/open_views.rs @@ -17,7 +17,7 @@ pub(crate) struct OpenViews<'a> { /// turn (Benchy, the M5, 2026-10-17), so collapsed it is still itself. fn required(key: String, text: String) -> Item { let message = ContextMessage::user(text); - Item { key, full: message.clone(), summary: None, pointer: Some(message) } + Item { stored: None, key, full: message.clone(), summary: None, pointer: Some(message) } } impl Source for OpenViews<'_> { diff --git a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs index 2c0e4e3645..6ce1e4a378 100644 --- a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs +++ b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs @@ -39,7 +39,7 @@ impl Source for Thoughts<'_> { let banner = ContextMessage::user( "My own recent thoughts (working memory, my interior state, not a message from anyone):".to_owned(), ); - let mut items = vec![Item { key: "banner".to_owned(), full: banner.clone(), summary: None, pointer: Some(banner) }]; + let mut items = vec![Item { stored: None, key: "banner".to_owned(), full: banner.clone(), summary: None, pointer: Some(banner) }]; items.extend(thoughts.into_iter().map(|text| { // Keyed by what it says: a thought, once recorded, does not change, and neither may // its rendering. Full is the whole thought; how much of her thoughts she reads is the @@ -48,6 +48,7 @@ impl Source for Thoughts<'_> { // chars on one act and 1,445 on the next, so every act re-appended every thought // (Benchy on the M5, 2026-10-24 22:3xZ: ~7k chars of unchanged thoughts per act). Item { + stored: None, key: text.clone(), full: ContextMessage::user(format!("- {text}")), summary: None, @@ -57,7 +58,7 @@ impl Source for Thoughts<'_> { // Fresh each event, newest last; one item, so a status change appends one line set. items.extend(dispatched.map(|text| { let message = ContextMessage::user(text); - Item { key: "dispatched".to_owned(), full: message.clone(), summary: None, pointer: Some(message) } + Item { stored: None, key: "dispatched".to_owned(), full: message.clone(), summary: None, pointer: Some(message) } })); items } diff --git a/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs b/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs index d5b9a59698..441b4e34bb 100644 --- a/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs +++ b/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs @@ -41,6 +41,9 @@ pub struct TriggerTurn<'a> { /// Event occurrence time when measured; zero means unknown. Never substitute /// the wake/turn clock for an event timestamp missing from the source. pub occurred_at_ms: u64, + /// The room event the waking message is, when known: her read receipt advances to it + /// once a sent prompt rendered it. + pub source: Option, } /// The shared roster projection's admitted atoms. The legacy source remains @@ -203,6 +206,17 @@ pub fn push_work_board_anchor( turns.push(crate::cognition::workspace::BurstTurn::perception(anchor)); } +/// The room event an airc item is, from the metadata the airc source stamps (`event_id`, +/// `room_id`, `lamport`). `None` for an item without it (a synthesized eval delivery). +fn turn_source(metadata: &serde_json::Value) -> Option { + let id = |key: &str| metadata.get(key).and_then(|v| v.as_str()).and_then(|s| uuid::Uuid::parse_str(s).ok()); + Some(crate::cognition::workspace::TurnSource { + room: id("room_id")?, + event: id("event_id")?, + lamport: metadata.get("lamport").and_then(|v| v.as_u64())?, + }) +} + pub fn build_workspace_turns( deliveries: &[crate::cognition::rag_budget::RagDelivery], own_peer: &str, @@ -238,7 +252,11 @@ pub fn build_workspace_turns( names.get(who_raw).copied().unwrap_or(who_raw) }; let occurred_at_ms = item.metadata.get("occurred_at_ms").and_then(|v| v.as_u64()); - BurstTurn::attributed(is_self, author, item.content.clone(), occurred_at_ms) + let turn = BurstTurn::attributed(is_self, author, item.content.clone(), occurred_at_ms); + match turn_source(&item.metadata) { + Some(source) => turn.from_event(source), + None => turn, + } }) .collect(); @@ -260,12 +278,11 @@ pub fn build_workspace_turns( .get(trigger.peer_id) .copied() .unwrap_or(trigger.peer_id); - turns.push(BurstTurn::attributed( - false, - author, - trigger.content.to_string(), - Some(trigger.occurred_at_ms), - )); + let turn = BurstTurn::attributed(false, author, trigger.content.to_string(), Some(trigger.occurred_at_ms)); + turns.push(match trigger.source { + Some(source) => turn.from_event(source), + None => turn, + }); } } diff --git a/core/continuum-cognition/src/cognition/dispatch_listener.rs b/core/continuum-cognition/src/cognition/dispatch_listener.rs index b68eec0df1..b6f247eda8 100644 --- a/core/continuum-cognition/src/cognition/dispatch_listener.rs +++ b/core/continuum-cognition/src/cognition/dispatch_listener.rs @@ -18,26 +18,13 @@ use crate::cognition::working_memory::{DispatchStatus, WorkingMemory}; use crate::runtime::command_events::{CommandCompletedEvent, COMMAND_COMPLETED_TOPIC}; use crate::runtime::message_bus::MessageBus; -// A dispatched command's result (a compile log, a sentinel's report) is bounded so one huge -// result can't dominate perception; the full text stays recoverable through the command's own -// handle. The bound is a FRACTION OF HER LIVE WINDOW, never a constant — the old -// `DISPATCH_RESULT_MAX_CHARS = 4_000` is exactly the "4k or smaller window" that makes a -// 1M-context model useless. [[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]] -use crate::cognition::context_budget::ContextBudget; - -/// Render a command result Value into the compact text the mind reads. A JSON string is -/// shown bare (no quotes); anything else is compact JSON. Bounded by -/// the live window (`ContextBudget::dispatch_result_chars`). -fn summarize_result(value: &serde_json::Value) -> String { - let raw = match value { +/// Preserve the completion for working memory's source. JSON strings are bare; +/// other values retain their complete compact JSON. The view chooses a level; +/// this transport consumer cannot discard the end of a result before allocation. +fn result_text(value: &serde_json::Value) -> String { + match value { serde_json::Value::String(s) => s.clone(), other => other.to_string(), - }; - let cap = ContextBudget::live().dispatch_result_chars(); - if raw.chars().count() > cap { - raw.chars().take(cap).collect::() + " …[truncated]" - } else { - raw } } @@ -58,7 +45,7 @@ pub fn fold_completion(wm: &WorkingMemory, ev: CommandCompletedEvent) -> bool { let body = ev .result .as_ref() - .map(summarize_result) + .map(result_text) .unwrap_or_else(|| "done".to_string()); (body, DispatchStatus::Done) } else { @@ -99,6 +86,21 @@ pub fn spawn(bus: Arc, working_memory: Arc) { mod tests { use super::*; + #[test] + fn completion_source_keeps_the_terminal_result_before_view_allocation() { + let wm = WorkingMemory::new(8); + let handle = uuid::Uuid::new_v4(); + wm.record_dispatch_event(handle, "compile", "running", DispatchStatus::Running); + let body = format!("{}\nFINAL: compile failed at the changed call site", "診断\n".repeat(100_000)); + assert!(fold_completion(&wm, ev(Some(handle), true, serde_json::json!(body)))); + let snapshot = wm.dispatched_snapshot(); + let result = snapshot.iter().find(|(h, ..)| *h == handle).expect("owned dispatch retained"); + assert_eq!(result.2, body); + assert_eq!(result.3, DispatchStatus::Done); + let structured = serde_json::json!({"output": body, "status": "failed"}); + assert_eq!(serde_json::from_str::(&result_text(&structured)).expect("complete JSON"), structured); + } + fn ev( handle: Option, success: bool, diff --git a/core/continuum-cognition/src/cognition/grounding_invalidation.rs b/core/continuum-cognition/src/cognition/grounding_invalidation.rs index b57232dc82..c251c77afc 100644 --- a/core/continuum-cognition/src/cognition/grounding_invalidation.rs +++ b/core/continuum-cognition/src/cognition/grounding_invalidation.rs @@ -183,9 +183,7 @@ pub fn spawn_publish_invalidator( mod tests { use super::*; use crate::cognition::cached_source::{CachedRagSource, DirtyHandle}; - use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagSource, ResolutionPreference, - }; + use crate::cognition::rag_budget::{RagContext, RagDelivery, RagSource}; use async_trait::async_trait; use std::sync::atomic::{AtomicU32, Ordering}; @@ -201,26 +199,20 @@ mod tests { fn expand_command(&self) -> Option<&'static str> { None } - fn floor_tokens(&self) -> u32 { - 1 - } - async fn deliver( - &self, - _ctx: &RagContext, - _budget: u32, - _resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, _ctx: &RagContext) -> RagDelivery { let n = self.fetches.fetch_add(1, Ordering::SeqCst) + 1; RagDelivery { source_id: "counting".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!("fetch #{n}"), tokens: 4, metadata: serde_json::json!({}), }], tokens_used: 4, truncated: false, - resolution_used: ResolutionPreference::Raw, } } } @@ -285,13 +277,13 @@ mod tests { drop(dirty); // wiring done — cache liveness now keys the listener let ctx = RagContext::for_persona(uuid::Uuid::new_v4(), 0); - let d = cached.deliver(&ctx, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&ctx).await; assert_eq!(d.items[0].content, "fetch #1"); // Read-only completion → cache keeps serving. bus.publish_async_only(COMMAND_COMPLETED_TOPIC, completed("code/read")); tokio::time::sleep(std::time::Duration::from_millis(50)).await; - let d = cached.deliver(&ctx, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&ctx).await; assert_eq!( d.items[0].content, "fetch #1", "read-only completion must not dirty" @@ -302,7 +294,7 @@ mod tests { let mut refetched = false; for _ in 0..100 { tokio::time::sleep(std::time::Duration::from_millis(10)).await; - let d = cached.deliver(&ctx, 100, ResolutionPreference::Raw).await; + let d = cached.deliver(&ctx).await; if d.items[0].content == "fetch #2" { refetched = true; break; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index e8c18c9576..9b88573f8a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -97,6 +97,8 @@ mod admission; pub(crate) mod admission_clock; use self::request::*; mod reply_claim; +mod read_receipt; +pub use read_receipt::ReadReceipt; use self::reply_claim::*; mod verdict; mod tool_surface; @@ -152,6 +154,9 @@ const FLEX_HISTORY: &str = "history"; const FLEX_REPLY: &str = "reply"; +/// Her hands (`prompt/tools_epoch.rs`): floor = the epoch's level or core hands, want = all. +const FLEX_TOOLS: &str = "tools"; + /// The reasoner faculty. Persona-scoped; shared model backend. pub struct LlmDeliberationFaculty { persona_id: Uuid, @@ -185,7 +190,7 @@ pub struct LlmDeliberationFaculty { tools: Vec, /// Her native tool surfaces (the whole registry, her hands, her core hands), built /// once per tool assignment in canonical order; which one a turn sends is - /// [`Self::select_tool_surface`], from the activity and the served window only. + /// the retained tools in [`Self::prompt_view`], selected from the shared allocation. surface: ToolSurface, /// Where this faculty records its chain-of-thought after a verdict, so the /// persona can resume its train of thought next turn (the @@ -199,6 +204,8 @@ pub struct LlmDeliberationFaculty { /// The live spawn path attaches a per-persona JSONL sink. See /// [`prompt_capture`](crate::cognition::prompt_capture). prompt_capture: Option>, + /// Where a sent prompt's read receipt goes (`read_receipt.rs`); `None` marks nothing read. + read_receipt: Option>, /// The persona's paged-in genome — the LoRA layers this faculty injects into /// every generation request ([`GenomeHandle`]). Shared with the owning /// [`WorkspaceCycle`](super::workspace::WorkspaceCycle), which pages skills @@ -232,6 +239,8 @@ pub struct LlmDeliberationFaculty { context_view: parking_lot::Mutex< Option>, >, + /// The tool level her current view epoch chose (`prompt/tools_epoch.rs`). + tools_epoch: parking_lot::Mutex>, /// A measurement fork's (`fork_eval_cycle`): its turns warm their own page, never hers. forked: bool, } @@ -259,10 +268,12 @@ impl LlmDeliberationFaculty { surface: ToolSurface::default(), working_memory: None, prompt_capture: None, + read_receipt: None, genome: empty_genome(), decoding: relaxed_decoding(), working_set: None, context_view: parking_lot::Mutex::new(None), + tools_epoch: parking_lot::Mutex::new(None), forked: false, } } @@ -451,24 +462,6 @@ impl LlmDeliberationFaculty { /// so an act that really needs more room earns it back within a turn. const COMPLETION_COLD_PRIOR_TOKENS: u32 = crate::inference::planning::MIN_SERVE_CTX; - /// The share of the served window the REQUIRED room payload may occupy. - /// - /// Room updates are required input — a citizen must see what was said to her — - /// so `fit_messages` may not drop them the way it drops old history. Unbounded, - /// that makes a BUSY ROOM into a mute citizen: measured 2026-09-09 on BigMama, - /// `delib.turn.demand` reported `conversation_tokens=53522` against a 23,040 - /// window (`over_window=3.14`). The required side then exceeded the whole - /// budget, `grounding_budget` saturated to 0, and `GroundingPlan::minimum` - /// refused 192 of 229 cognition cycles — 84% — with - /// "requires 810 tokens, but only 0 are available". Both live citizens were - /// mute for hours while `serving/status` read `ready: true`. - /// - /// The window is not the fault and raising it does not fix this: the room grows - /// without bound and any fixed window is eventually 3x under. What is bounded - /// here is what the turn REQUIRES; the rest of the room is still reachable - /// through history and recall. - const ROOM_UPDATE_SHARE_DENOM: u32 = 4; - /// The action result's share of the window before its tail is DEMOTED to ordinary /// history. Same denominator as the room payload for the same reason: no single /// required item may claim more than a quarter of the window, because the moment one diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs index 80a8247e59..53ddd854d4 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs @@ -396,7 +396,7 @@ impl LlmDeliberationFaculty { /// on top, the price of keeping it whole.) The reserve must also hold one act's appends, so /// `growing` is at most `available - grounding - per_act` as well, which binds only when an /// act appends more than half of what the growing sources may hold. Before the epoch being -/// replaced appended anything (`None`) the half start stands alone; the replay's half-window +/// replaced appended anything (`None`) the share start (`EPOCH_START_SHARE`) stands alone; the replay's half-window /// start halved turnovers (continuum-context `examples/replay.rs`). /// /// The one allocator spends it: a higher-priority source asks for its whole grant as its @@ -416,7 +416,7 @@ pub(in super::super) fn start_grants( // Characters per allocation token, the ratio each claim was priced at (`view_claims`). let wanted_tokens: u64 = grants.iter().flatten().map(|a| u64::from(a.requested_max)).sum(); let wanted_chars: u64 = claims.iter().zip(&grants).filter(|(_, a)| a.is_some()).map(|(c, _)| c.full_chars as u64).sum(); - let per_act_tokens = appended_per_act.map_or(0, |chars| (chars as u64 * wanted_tokens).div_ceil(wanted_chars.max(1)) as usize); // map_or: no act measured yet reserves the half start alone + let per_act_tokens = appended_per_act.map_or(0, |chars| (chars as u64 * wanted_tokens).div_ceil(wanted_chars.max(1)) as usize); // map_or: no act measured yet reserves the share start alone let lowest = claims.iter().map(|claim| claim.priority).min().unwrap_or(0); // unwrap_or: no claims means nothing to grant let grounding: usize = claims .iter() @@ -431,11 +431,11 @@ pub(in super::super) fn start_grants( // newest end with them. A re-home back into a 160-turn room measured 331,230 tokens // appended in one act against a 20,693 grant, and her view rendered empty // (`provider_context_feedback_bounds_replay_and_scales_next_turn`, 2026-10-23). Such an - // epoch turns over on the next act whatever its start, so it keeps the half start. + // epoch turns over on the next act whatever its start, so it keeps the ordinary start. let growing = if per_act_tokens < growable { - (growable / 2).min(growable - per_act_tokens) + (growable / EPOCH_START_SHARE).min(growable - per_act_tokens) } else { - growable / 2 + growable / EPOCH_START_SHARE }; let start = grounding + growing; let budgets: Vec = claims @@ -468,3 +468,15 @@ pub(in super::super) fn start_grants( #[cfg(test)] mod tests; + +/// The share of what grounding leaves that a new epoch starts her growing sources at; the rest is +/// room to append before the next turnover. A turnover re-prefills the start, and turnovers come +/// once per (window - start) of appends, so prefill per act from turnovers is +/// `start * appended / (window - start)`: a smaller start is cheaper, bounded by what it collapses +/// (which stays reachable through handles). +// derived-or-floor: derived — the dyno over the M5 residents' captures at the 48k working window, +// 2026-10-28 (~/.continuum/evidence/2026-10-28-working-window/, replay --share 2/3/4): a quarter +// start cut prefill per request 10-25% against a half (Benchy 42 -> 34 s, Aiko 25 -> 19, Aris 33 -> 32, +// Atlas 21 -> 17) with fewer turnovers and fewer items collapsed overall. The closed-form optimum +// from her measured expand rate replaces this (FLOW plan §2b). +const EPOCH_START_SHARE: usize = 4; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs index 146b2029cc..587eb9505b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs @@ -8,11 +8,11 @@ use crate::cognition::context_streams::conversation::{Conversation, Turn}; use crate::cognition::context_streams::Role; fn block(faculty: &str, text: &str) -> Grounding { - Grounding { faculty: faculty.to_owned(), text: text.to_owned(), minimum: text.to_owned() } + Grounding::atomic(faculty, text) } fn turn(n: usize) -> Turn { - Turn { key: format!("turn-{n}"), role: Role::User, line: format!("[occurred {n}] Operator: turn {n}") } + Turn { key: format!("turn-{n}"), role: Role::User, line: format!("[occurred {n}] Operator: turn {n}"), pointer: None } } /// One act's sources: a room window of six turns starting at `first_turn`, a settled map, the diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs index aa23103642..948cbc2e6b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs @@ -275,13 +275,11 @@ impl LlmDeliberationFaculty { // 2026-07-20 humaneval fix); her notices ride her view, ahead of all of this. if !prompt.latest_result.is_empty() { prompt.history.extend(prompt.stimulus); - prompt.history.extend(prompt.room_updates); prompt.history.extend(prompt.action_statement); prompt.history.extend(prompt.latest_result); } else { prompt.history.extend(prompt.action_statement); prompt.history.extend(prompt.stimulus); - prompt.history.extend(prompt.room_updates); } Ok(FittedMessages { messages: prompt.history, @@ -335,7 +333,6 @@ impl LlmDeliberationFaculty { stimulus: None, latest_result: required, action_statement: None, - room_updates: Vec::new(), }; let mut fitted = self.fit_messages(prompt, input_budget .saturating_sub(fixed_tokens).saturating_sub(frozen_grounding_tokens))?; 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 05896fa2ad..24e0d17749 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 @@ -100,17 +100,47 @@ impl LlmDeliberationFaculty { stimulus = Some(ChatMessage::text(role, line)); continue; } - let key = match turn.occurred_at_ms { - Some(ms) => format!("{ms}/{}", turn.author), - // An opaque stimulus has no time: its position among the turns is its identity. - None => format!("#{index}"), + // A room turn is its event (unique, and what her read receipt names); a turn without + // one keys by time and author, an opaque stimulus by its position. + let key = match (turn.source, turn.occurred_at_ms) { + (Some(source), _) => source.event.to_string(), + (None, Some(ms)) => format!("{ms}/{}", turn.author), + (None, None) => format!("#{index}"), }; let role = if turn.is_self { crate::cognition::context_streams::Role::Assistant } else { crate::cognition::context_streams::Role::User }; - turns.push(crate::cognition::context_streams::conversation::Turn { key, role, line }); + turns.push(crate::cognition::context_streams::conversation::Turn { key, role, line, pointer: None }); + } + // Messages that reached her room during this turn are conversation too, after the + // burst, keyed by their event: in her view they append like any turn, and one + // already in the burst keeps its place. They rode the fresh tail as required input + // under a quarter-of-the-window share (ROOM_UPDATE_SHARE_DENOM), a second budget. + for update in ws.room_updates.iter() { + let key = update.event_id.to_string(); + if turns.iter().any(|turn| turn.key == key) { + continue; + } + let line = update.render_room_update(); + turns.push(crate::cognition::context_streams::conversation::Turn { key, role: crate::cognition::context_streams::Role::User, line, pointer: None }); + } + // One line after them that never collapses: how many arrived and where the rest + // are. An update her window cannot hold whole then leaves only this, never + // vanishes unknown; a handle per update would put every one in the conversation's + // floor and crowd out the newest (40 handles took its room in the busy-room test). + if let Some(newest) = ws.room_updates.last() { + let line = format!( + "[{} room message(s) arrived during this turn; any not shown above: reread with chat/history]", + ws.room_updates.len() + ); + turns.push(crate::cognition::context_streams::conversation::Turn { + key: format!("room-updates/{}", newest.event_id), + role: crate::cognition::context_streams::Role::User, + pointer: Some(line.clone()), + line, + }); } // What follows the view in this act's prompt: facts, the clock, demoted payloads. let mut messages: Vec = Vec::new(); @@ -238,7 +268,7 @@ impl LlmDeliberationFaculty { }; let text = render(GroundingPiece::whole(c)); let minimum = if c.standing_grounding { render(GroundingPiece::minimum(c)) } else { text.clone() }; - crate::cognition::context_streams::blocks::Grounding { faculty: c.faculty.as_str().to_owned(), text, minimum } + crate::cognition::context_streams::blocks::Grounding { faculty: c.faculty.as_str().to_owned(), text, minimum, units: std::sync::Arc::clone(&c.units) } }) .collect(); let result_pointers = Vec::new(); @@ -337,17 +367,10 @@ impl LlmDeliberationFaculty { stimulus = Some(ChatMessage::text("user", ws.world_state.clone())); } input.update([(!latest_result.is_empty()) as u8]); - // Demoted room updates ride in ordinary history: still shown when the window - // has room, trimmed by the existing front-drop only under pressure. They are - // chronologically newer than prior history, so they append to its end. - let (room_updates, demoted_updates) = self.split_room_updates(ws); let mut messages = messages; - // The action result's demoted TAIL rides the same way, and goes in FIRST: it is - // the outcome of the act that preceded these room updates, so appending it before - // them keeps history in the order it happened. Without this the tail would be - // silently dropped, which is the discarding this whole split exists to avoid. + // The action result's demoted TAIL rides in ordinary history, after prior history: + // without this it would be silently dropped. messages.extend(demoted_result); - messages.extend(demoted_updates); let action_statement = self .working_memory .as_ref() @@ -369,7 +392,6 @@ impl LlmDeliberationFaculty { stimulus, latest_result, action_statement, - room_updates, } } @@ -419,7 +441,7 @@ impl LlmDeliberationFaculty { /// handle. A cut on a CHAR boundary would split a UTF-8 sequence, so the split walks /// to a line boundary and says how much moved. pub(in super::super) fn split_action_result(&self, message: String) -> (ChatMessage, Option) { - let window = self.binding.load().context_window as usize; + let window = self.working_window() as usize; let cap = window / Self::RESULT_SHARE_DENOM as usize; let whole = ChatMessage::text("user", message.clone()); if Self::messages_cost(std::slice::from_ref(&whole)) <= cap { @@ -473,43 +495,4 @@ impl LlmDeliberationFaculty { (tail_msg, Some(head_msg)) } - pub(in super::super) fn split_room_updates(&self, ws: &Workspace) -> (Vec, Vec) { - let window = self.binding.load().context_window as usize; - let cap = window / Self::ROOM_UPDATE_SHARE_DENOM as usize; - let mut required: Vec = Vec::new(); - let mut demoted: Vec = Vec::new(); - let mut used = 0usize; - // Newest first so the REQUIRED half is the freshest room state. - for message in ws.room_updates.iter().rev() { - let rendered = ChatMessage::text("user", message.render_room_update()); - let cost = Self::messages_cost(std::slice::from_ref(&rendered)); - // The newest update is always required, even if it alone exceeds the - // share: one oversized message must not silently demote the very - // stimulus the turn exists to answer. If it genuinely cannot fit, the - // existing capacity fault says so honestly. - if required.is_empty() || used.saturating_add(cost) <= cap { - used += cost; - required.push(rendered); - } else { - demoted.push(rendered); - } - } - required.reverse(); - demoted.reverse(); - if !demoted.is_empty() { - let demoted_tokens = Self::messages_cost(&demoted); - continuum_base::probe!( - class = "delib.room_updates.demoted", - persona = %self.persona_name, - window = window, - cap = cap, - required = required.len(), - required_tokens = used, - demoted = demoted.len(), - demoted_tokens = demoted_tokens, - "required room payload exceeded its share of the window — the newest stay REQUIRED and the older were demoted to ordinary history, which is still rendered when the window allows. Nothing was discarded: an unbounded required payload is what makes a busy room a mute citizen." - ); - } - (required, demoted) - } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs index d2bcf2c58c..ff31145f93 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs @@ -14,4 +14,6 @@ pub(super) mod fit; pub(super) use self::fit::*; mod segments; mod newest_result; +mod tools_epoch; +pub(super) use self::tools_epoch::ToolsEpoch; pub(super) use self::segments::*; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs index 70f5204d0e..bbf62a0afd 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs @@ -56,9 +56,6 @@ impl LlmDeliberationFaculty { .filter(|c| c.decision.is_none() && c.trailing) .map(|c| estimate_guard_tokens(&c.content)) .sum(); - let affordable_tokens = super::super::super::tool_surface::over_affordable_receipt( - &self.persona_name, surface_reason, tool_tokens, framing_tokens, context_window, - ); if budget_tokens == 0 { // Received-vs-rendered receipt even on the zero-budget path — a turn // whose entire context vanished must say so, not render silently empty @@ -78,7 +75,6 @@ impl LlmDeliberationFaculty { tool_tokens, registry_tool_tokens = self.describe_tool_tokens(), surface_reason = ?surface_reason, - affordable_tokens = ?affordable_tokens, received = ws.broadcast.iter().filter(|c| c.decision.is_none() && !c.trailing).count(), rendered = 0usize, dropped = %ws @@ -192,10 +188,8 @@ impl LlmDeliberationFaculty { // Actual selected schemas, not the full registry's withheld cost. tool_tokens, registry_tool_tokens = self.describe_tool_tokens(), - // Which arm selected that surface, and the prompt the lane affords: the two - // numbers a 10k-token surface on a 2.8k-affordable lane is read against. + // Which whole tool level the shared allocation selected. surface_reason = ?surface_reason, - affordable_tokens = ?affordable_tokens, // The pool the budget is subtracted FROM, read from the local that // actually holds it. First written as // `framing + conversation + budget` — a RECONSTRUCTION from the diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/tools_epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/tools_epoch.rs new file mode 100644 index 0000000000..f551421cc7 --- /dev/null +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/tools_epoch.rs @@ -0,0 +1,82 @@ +//! Her hands as one claim in the window's one allocation (FLOW-IMPLEMENTATION-PLAN §2d). +//! +//! The tool schemas sit ahead of every message, so a surface that changes mid-epoch rewrites +//! the whole prompt after the system text. The claim therefore prices like her view: at an +//! epoch's start its floor is her core hands and its want her whole surface (hands plus her +//! learned head, `ToolSurface::claim_with_head`); once the epoch has chosen a level, that level +//! is the claim's target (`min_tokens`), which the allocator gives up only when the window +//! cannot hold it (a relaunch onto a smaller window), and then loudly. The floor stays her +//! core hands: a window that cannot hold those refuses the turn, never sends her handless. +//! Before this the surface was sized against a share of the window outside the allocation +//! (`ContextBudget::tool_surface_tokens`), a second budget the allocation never saw. + +use super::*; +use crate::cognition::tool_surface::SelectedSurface; + +/// The level this epoch of her view chose, in raw (uncalibrated) tokens. +#[derive(Clone, Copy, Debug)] +pub(in super::super) struct ToolsEpoch { + epoch: u64, + tokens: usize, +} + +/// This act's tools claim, in raw tokens. +#[derive(Clone, Copy, Debug)] +pub(in super::super) struct ToolsClaim { + /// Her core hands: granted unconditionally or the turn is refused. + pub(in super::super) floor: usize, + /// The level this epoch chose (her core hands at an epoch's start): held unless the + /// window cannot. + pub(in super::super) level: usize, + /// Her whole surface: what demand records, whatever the grant. + pub(in super::super) want: usize, +} + +impl LlmDeliberationFaculty { + fn view_epoch(&self) -> Option { + self.context_view.lock().as_ref().map(|view| view.epoch_id()) + } + + /// The tools claim. Demand never depends on a grant. + pub(in super::super) fn tools_claim(&self, ws: &Workspace) -> ToolsClaim { + let (core, want) = self.tool_claim_tokens(ws); + let retained = *self.tools_epoch.lock(); + let level = match (retained, self.view_epoch()) { + (Some(kept), Some(epoch)) if kept.epoch == epoch => kept.tokens.max(core), + _ => core, + }; + ToolsClaim { floor: core, level, want: want.max(level) } + } + + /// The surface the allocation's grant buys, or the loud refusal when the window could not + /// grant even the floor (never a silent shrink below her hands). + pub(in super::super) fn granted_tools(&self, ws: &Workspace, claim: ToolsClaim, grant: usize) -> (SelectedSurface<'_>, Option) { + if grant < claim.level { + continuum_base::probe!( + class = "delib.tools.epoch_level_lost", + persona = %self.persona_name, + level = claim.level as u64, + grant = grant as u64, + "the window could not hold the tool level this epoch chose: her hands change mid-epoch and the prompt after the system text re-prefills" + ); + } + match self.select_tool_surface_granted(ws, grant) { + Ok(selected) => (selected, None), + Err(needed) => ( + SelectedSurface::none(), + Some(PromptCapacityError { required_tokens: needed, budget_tokens: grant }), + ), + } + } + + /// After her view is fitted: the level this act sent is the level of the epoch the view is + /// now in, so an epoch this act started keeps it, and the next start chooses again. + pub(in super::super) fn retain_tools(&self, selected: &SelectedSurface<'_>, refused: bool) { + if refused { + return; // a refused turn sent no surface: the epoch keeps the level it had + } + if let Some(epoch) = self.view_epoch() { + *self.tools_epoch.lock() = Some(ToolsEpoch { epoch, tokens: selected.tokens }); + } + } +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs index d1e5bcb9a8..2504cf3ba5 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs @@ -111,7 +111,6 @@ pub struct PromptMessages { pub latest_result: Vec, /// Public action text retains assistant provenance and required-input pricing. pub(in super::super) action_statement: Option, - pub(in super::super) room_updates: Vec, } /// Her OWN most recent move and its outcome, priced — the SUFFIX of the optional history @@ -301,8 +300,6 @@ impl PromptMessages { }; RequiredParts { stimulus: cost(&mut self.stimulus.iter()), - room_updates: cost(&mut self.room_updates.iter()), - room_update_count: self.room_updates.len(), action_statement: cost(&mut self.action_statement.iter()), latest_result: cost(&mut self.latest_result.iter()), latest_result_count: self.latest_result.len(), @@ -319,8 +316,6 @@ impl PromptMessages { #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct RequiredParts { pub stimulus: usize, - pub room_updates: usize, - pub room_update_count: usize, pub action_statement: usize, pub latest_result: usize, pub latest_result_count: usize, @@ -329,7 +324,7 @@ pub struct RequiredParts { impl RequiredParts { pub fn total(&self) -> usize { - self.stimulus + self.room_updates + self.action_statement + self.latest_result + self.grounding + self.stimulus + self.action_statement + self.latest_result + self.grounding } } @@ -423,6 +418,12 @@ pub struct DeliberationPromptView { /// Her newest result's estimated tokens as this view carries it (`RequiredParts::latest_result`): /// what a refusal's excess is charged to when it refits her (`verdict/newest_refit.rs`). pub newest_result_tokens: usize, + /// Her hands as the one allocation bought them (`tools_epoch.rs`): the request sends + /// exactly this, never a second selection. + pub tools: crate::cognition::tool_surface::SelectedSurface<'static>, + /// The raw tokens the allocation granted her hands: a retry on a server that refuses + /// `tail_tools` re-selects at this grant, without her learned head. + pub tools_grant: usize, } impl DeliberationPromptView { diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs index d542e9d645..5c3eb5acdd 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs @@ -24,14 +24,34 @@ impl LlmDeliberationFaculty { self.prompt_view_with_feedback(ws, window, calibration) } + /// The window her prompt is fitted to: the working window + /// ([`crate::cognition::context_budget::ContextBudget::working_window`]), narrowed by the + /// provider's last observation. The binding keeps the served window: serving reads it. pub fn prompt_fit(&self, binding: &ModelBinding) -> (u32, PromptCalibration) { + self.fit_within(binding, crate::cognition::context_budget::ContextBudget::working_window(binding.context_window)) + } + + /// The served window, narrowed the same way: the one rebuild when her required input + /// cannot fit the working window (`verdict/contribute.rs`), so a large required payload is + /// served from the whole slot instead of refused. + pub fn prompt_fit_served(&self, binding: &ModelBinding) -> (u32, PromptCalibration) { + self.fit_within(binding, binding.context_window) + } + + fn fit_within(&self, binding: &ModelBinding, window: u32) -> (u32, PromptCalibration) { let feedback = self.prompt_feedback.load(); feedback.as_ref().filter(|f| f.applies_to(binding)).map_or( - (binding.context_window, PromptCalibration::default()), - |f| (binding.context_window.min(f.available), f.calibration), + (window, PromptCalibration::default()), + |f| (window.min(f.available), f.calibration), ) } + /// The working window for this faculty's current binding: the shares sized from the + /// window (results, room updates, the tool surface) scale with the prompt they live in. + pub(in super::super) fn working_window(&self) -> u32 { + crate::cognition::context_budget::ContextBudget::working_window(self.binding.load().context_window) + } + /// Fixture view against an explicit window, without a prior provider observation. #[cfg(any(test, feature = "test-fixtures"))] pub fn prompt_view_within(&self, ws: &Workspace, context_window: u32) -> DeliberationPromptView { @@ -126,11 +146,9 @@ impl LlmDeliberationFaculty { // here, AND the human-readable tool MENU inside `compose_system` (counted in // `framing_tokens`). Whether that duplication is intended is an open // question, not something this comment should assert either way. - // The SELECTED surface, not the whole registry: `contribute` narrows to her - // hands on a work turn, and subtracting the full registry here trimmed the - // conversation to fit room that was never occupied (card dec1a7ff). One - // decision, made once, consulted by the budget and by the request alike. - let selected = self.select_tool_surface(ws); + // Her hands are a claim in the one allocation below (`tools_epoch.rs`): before it, + // only their floor is irreducible; the surface sent is what the grant buys. + let tools = self.tools_claim(ws); // Which tool categories the bookmarked menu OPENS this turn. Computed ONCE // here from `ws` (NOT from the budgeted `context`, which is not built yet) and @@ -171,11 +189,7 @@ impl LlmDeliberationFaculty { visual, ); all_messages.streams.blocks.extend(contracts.into_iter().map(|contract| { - crate::cognition::context_streams::blocks::Grounding { - faculty: contract.name.to_owned(), - text: contract.body.to_owned(), - minimum: contract.body.to_owned(), - } + crate::cognition::context_streams::blocks::Grounding::atomic(contract.name, contract.body) })); // Her view leads the history: this act appends to it, and everything after it (the // standing grounding, facts, the clock) is this act's fresh tail. @@ -190,7 +204,7 @@ impl LlmDeliberationFaculty { (context_window as usize).saturating_sub(Self::COMPLETION_FLOOR_TOKENS as usize), ) .saturating_sub(framing_tokens) - .saturating_sub(selected.tokens); + .saturating_sub(tools.floor); // Her view's REQUIRED sources (notices, the lines of files she has open) are never shed: // granted their floor first, or kept over their grant (`fit_view`). That floor is // therefore as irreducible as the turn's own input, and what is left for the rest is @@ -230,10 +244,8 @@ impl LlmDeliberationFaculty { payload_overflow, context_window, framing_tokens, - tool_tokens = selected.tokens, + tool_tokens = tools.floor, stimulus_tokens = required.stimulus, - room_update_tokens = required.room_updates, - room_updates = required.room_update_count, action_statement_tokens = required.action_statement, latest_result_tokens = required.latest_result, latest_results = required.latest_result_count, @@ -291,7 +303,7 @@ impl LlmDeliberationFaculty { // allocation as this floor, never pre-charged here. let after_framing = calibration .prompt_budget((context_window as usize).saturating_sub(reply.floor_tokens as usize)) - .saturating_sub(selected.tokens) + .saturating_sub(tools.floor) .saturating_sub(framing_tokens); offered() .find(|c| c.faculty.as_str() == crate::cognition::faculty_ids::ACTIVE_WORK) @@ -335,7 +347,8 @@ impl LlmDeliberationFaculty { }; let history_floor = evidence.tokens.max(quiet_minimum).min(optional_history); let claim = |tokens: usize| calibration.charge(tokens).min(u32::MAX as usize) as u32; - let fixed_cost = claim(framing_tokens.saturating_add(selected.tokens)); + let fixed_cost = claim(framing_tokens); + let tools_floor = claim(tools.floor); let required_cost = claim(required_tokens); let mut reply = reply; // The reply never takes from required content: its floor is what the window leaves @@ -348,7 +361,7 @@ impl LlmDeliberationFaculty { if matches!(self.turn_kind(ws), TurnKind::Act) { reply.max_tokens = reply.max_tokens.max(reply_runaway); } - reply.floor_tokens = reply_need.min(context_window.saturating_sub(fixed_cost.saturating_add(required_cost))); + reply.floor_tokens = reply_need.min(context_window.saturating_sub(fixed_cost.saturating_add(tools_floor).saturating_add(required_cost))); reply.min_tokens = reply.floor_tokens; let fixed_claim = |id: &str, tokens: u32| crate::cognition::rag_budget::RagSourceBudget { source_id: id.to_owned(), @@ -388,6 +401,16 @@ impl LlmDeliberationFaculty { required: false, }, reply, + // Her hands, above grounding (`tools_epoch.rs`): floor = core hands, target = the + // level this epoch chose, want = her whole surface. + crate::cognition::rag_budget::RagSourceBudget { + source_id: FLEX_TOOLS.to_owned(), + priority: 7, + floor_tokens: tools_floor, + min_tokens: claim(tools.level).max(tools_floor), + max_tokens: claim(tools.want).max(tools_floor), + required: true, + }, ]; // Her view's sources, each its own claim (`epoch.rs`): the blocks she works from at // the grounding claim's weight, her conversation, thoughts and results at history's. @@ -398,6 +421,8 @@ impl LlmDeliberationFaculty { source })); let plan = crate::cognition::rag_budget::flex_allocate(context_window, &claims); + let tools_grant = calibration.prompt_budget(plan.granted(FLEX_TOOLS) as usize); + let (selected, tools_refusal) = self.granted_tools(ws, tools, tools_grant); let budget_floor = crate::cognition::rag_budget::turn_need(&claims).saturating_sub(claims.iter().find(|c| c.source_id == FLEX_REPLY).map_or(0, |c| c.floor_tokens)).saturating_add(reply_need); // Whatever no claim took is hers to write with, up to the runaway bound. let reply_grant = plan.granted(FLEX_REPLY); @@ -413,6 +438,8 @@ impl LlmDeliberationFaculty { required_tokens = required_cost, grounding_granted = plan.granted(FLEX_GROUNDING), history_granted = plan.granted(FLEX_HISTORY), + tools_granted = plan.granted(FLEX_TOOLS), + tools_floor, reply_priority = claims[4].priority, reply_floor = claims[4].floor_tokens, reply_wanted = claims[4].max_tokens, @@ -437,7 +464,7 @@ impl LlmDeliberationFaculty { let view_granted: u32 = plan .allocations .iter() - .filter(|a| claims.iter().skip(5).any(|c| c.source_id == a.source_id)) + .filter(|a| claims.iter().skip(6).any(|c| c.source_id == a.source_id)) .map(|a| a.allocated_tokens) .sum(); // What no claim took goes to the reply up to its runaway bound; only the rest is room @@ -451,6 +478,7 @@ impl LlmDeliberationFaculty { // it is ever collapsed. self.fit_view(&mut all_messages, view, &plan, view_room as usize, calibration); self.view_sent(); + self.retain_tools(&selected, tools_refusal.is_some()); // Her view as the allocation sized it: the fit below never cuts it. let view_len = all_messages.grounding_at; @@ -527,6 +555,8 @@ impl LlmDeliberationFaculty { } Err(error) => (FittedMessages::default(), Some(error)), }; + // Her hands not granted even their floor refuse the turn as loudly as her input would. + let capacity_error = tools_refusal.or(capacity_error); // THE FIT'S RECEIPT (card d33e928a, Kimi's finding): whenever the fit dropped // history, say what it dropped and from what budget, and say it loudly when // nothing optional survived — that turn composes with no room at all, operator @@ -701,7 +731,7 @@ impl LlmDeliberationFaculty { messages: &messages, view_len: grounding_at, grounding_len: refit.grounding_len, - framing_grant: fixed_cost, + framing_grant: fixed_cost.saturating_add(plan.granted(FLEX_TOOLS)), required_grant: required_cost, history_grant: plan.granted(FLEX_HISTORY), grounding_grant: plan.granted(FLEX_GROUNDING), @@ -724,6 +754,8 @@ impl LlmDeliberationFaculty { segments, newest_result_reduced, newest_result_tokens, + tools: selected.into_owned(), + tools_grant, } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/read_receipt.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/read_receipt.rs new file mode 100644 index 0000000000..219b4469ca --- /dev/null +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/read_receipt.rs @@ -0,0 +1,57 @@ +//! Her read receipt: after a prompt is sent, the newest room event it actually rendered, per +//! room. Marking read belongs here, not at delivery: delivery is not reading, and only her +//! one view knows which turns she saw (FLOW-IMPLEMENTATION-PLAN §2d). Before this the airc +//! source advanced her cursor while packing, before any prompt existed, so a turn her view +//! then collapsed, or an act that was refused, still marked the room read. + +use super::*; +use crate::cognition::workspace::TurnSource; + +/// Where a sent prompt's read receipt goes (the persona's airc source, through its room cursor). +#[async_trait::async_trait] +pub trait ReadReceipt: Send + Sync { + /// She read `room` through `event` (monotonic: a lower event never rewinds her). + async fn read_through(&self, room: uuid::Uuid, event: uuid::Uuid); +} + +impl LlmDeliberationFaculty { + /// Install the read receipt. Off by default: an eval or replay faculty marks nothing read. + pub fn with_read_receipt(mut self, receipt: Arc) -> Self { + self.read_receipt = Some(receipt); + self + } + + /// The newest event per room that the prompt just sent rendered: her stimulus and every + /// conversation turn her view shows (room updates are conversation turns, keyed by event). + pub(super) fn rendered_through(&self, ws: &Workspace) -> Vec { + let stimulus = ws.turns.iter().rposition(|t| !t.is_self && t.voice == crate::cognition::workspace::TurnVoice::Speech); + let view = self.context_view.lock(); + let shown = |index: usize, source: &TurnSource| { + Some(index) == stimulus || view.as_ref().is_some_and(|v| v.renders("conversation", &source.event.to_string())) + }; + let turns = ws.turns.iter().enumerate().filter_map(|(i, t)| t.source.filter(|s| shown(i, s))); + let updates = ws + .room_updates + .iter() + .map(|m| TurnSource { room: m.room_id, event: m.event_id, lamport: m.lamport }) + .filter(|source| view.as_ref().is_some_and(|v| v.renders("conversation", &source.event.to_string()))); + let mut newest: std::collections::HashMap = std::collections::HashMap::new(); + for source in turns.chain(updates) { + let entry = newest.entry(source.room).or_insert(source); + if source.lamport > entry.lamport { + *entry = source; + } + } + newest.into_values().collect() + } + + /// After a prompt was sent and answered: mark each room read through what it rendered. + pub(super) async fn send_read_receipt(&self, ws: &Workspace) { + let Some(receipt) = self.read_receipt.as_ref() else { + return; + }; + for source in self.rendered_through(ws) { + receipt.read_through(source.room, source.event).await; + } + } +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs index 9f1eb44a19..03e9d4e410 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs @@ -155,7 +155,7 @@ fn an_initiative_turn_takes_a_work_turns_hands_and_act_kind() { initiative.initiative = true; assert!(!initiative.workspace_deliverable, "an initiative is not a deliverable turn"); assert_eq!(faculty.turn_kind(&initiative), faculty.turn_kind(&work), "the act allowance"); - let (i, w) = (faculty.select_tool_surface(&initiative), faculty.select_tool_surface(&work)); + let (i, w) = (faculty.prompt_view(&initiative).tools, faculty.prompt_view(&work).tools); assert_eq!((i.reason, i.specs), (w.reason, w.specs), "one surface for every kind of turn"); } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs index a9c30ca813..3933813ecf 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs @@ -27,7 +27,7 @@ impl Source for Stream { fn items(&self) -> Vec> { self.items .iter() - .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(format!("[{key} collapsed]")) }) + .map(|(key, text)| Item { stored: None, key: key.clone(), full: text.clone(), summary: None, pointer: Some(format!("[{key} collapsed]")) }) .collect() } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs index 9c34330648..9ce406b74f 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 @@ -236,7 +236,7 @@ mod the_newest_result_over_her_window { }, status: ActStatus::Executed, }; - let rendered = observation.render_recency("", &wm.budget()); + 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/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs index 481bdb2d78..7c82023b7b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs @@ -32,7 +32,6 @@ fn a_binding_fill_budget_keeps_her_own_last_move_and_its_result() { history: history.clone(), stimulus: None, latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }; // The run that must survive: her act, its result, and the ask that opened them. @@ -107,7 +106,6 @@ fn the_recent_move_protection_states_its_own_limits() { history, stimulus: None, latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }; // A MULTI-TOOL CHAIN LONGER THAN THE SCAN BOUND. Protected as a suffix, and diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs index b9d527829e..d403cad82b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs @@ -123,7 +123,6 @@ fn fit_receipt_names_what_it_dropped_and_when_it_emptied_the_history() { history, stimulus: Some(stimulus.clone()), latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }; let required = prompt(Vec::new()).required_tokens(); let total: usize = history.iter().map(LlmDeliberationFaculty::message_cost).sum(); @@ -186,7 +185,6 @@ fn fit_front_advances_in_quanta_not_per_act() { history: msgs[..n].to_vec(), stimulus: None, latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }, budget, ) @@ -238,7 +236,6 @@ fn fit_front_advances_in_quanta_not_per_act() { history: clustered, stimulus: None, latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }, budget, ) @@ -269,7 +266,6 @@ fn fit_front_advances_in_quanta_not_per_act() { ], stimulus: None, latest_result: Vec::new(), action_statement: None, - room_updates: Vec::new(), }; let ambient_cost = LlmDeliberationFaculty::message_cost(ambient().history.last().unwrap()); @@ -296,18 +292,17 @@ fn the_pinned_result_rides_last_and_nothing_rides_after_the_ask() { history: vec![ChatMessage::text("user", "[work turn] fix the bug")], stimulus: Some(ChatMessage::text("user", "the ask")), latest_result: result.then(|| ChatMessage::text("user", "Full result of your most recent action")).into_iter().collect(), action_statement: None, - room_updates: vec![ChatMessage::text("user", "[Room message received during this turn] hi")], }; let order = |result: bool| -> Vec { faculty.fit_messages(prompt(result), 100_000).expect("test: fits").messages.iter() .map(|m| m.content_text().lines().next().unwrap_or("").to_string()).collect() }; assert_eq!(order(true), vec![ - "[work turn] fix the bug", "the ask", "[Room message received during this turn] hi", + "[work turn] fix the bug", "the ask", "Full result of your most recent action", ]); assert_eq!(order(false), vec![ - "[work turn] fix the bug", "the ask", "[Room message received during this turn] hi", + "[work turn] fix the bug", "the ask", ]); } @@ -325,7 +320,7 @@ fn continuity_followup_keeps_completed_action_evidence() { streams: Default::default(), result_pointers: Vec::new(), input_identity: [0; 32], grounding_tokens: 0, grounding_at: 0, - history, stimulus: None, latest_result: Vec::new(), action_statement: None, room_updates: Vec::new(), + history, stimulus: None, latest_result: Vec::new(), action_statement: None, }; assert!(prompt.recent_move_evidence().tokens >= expected, "a new follow-up cannot make the preceding action and result disposable"); @@ -345,7 +340,7 @@ fn continuity_insufficient_capacity_refuses_instead_of_dropping_evidence() { ChatMessage::text("assistant", "calling code/write: completed.py ".repeat(30)), ChatMessage::text("user", "Full result of code/write: file written successfully."), ], - stimulus: None, latest_result: Vec::new(), action_statement: None, room_updates: Vec::new(), + stimulus: None, latest_result: Vec::new(), action_statement: None, }; let insufficient = prompt.recent_move_evidence().tokens - 1; assert!(faculty.fit_messages(prompt, insufficient).is_err(), @@ -364,3 +359,41 @@ fn a_binding_without_a_model_name_carries_the_adapters_served_model() { assert_eq!(faculty.binding.load().model.as_deref(), Some(served.as_str()), "a bound faculty always names the model it is bound to"); } + +// what this catches: her hands re-sized every act (a surface that moves mid-epoch rewrites the +// whole prompt after the system text), or sized outside the one allocation. Her first view +// buys her whole hands from an ample grant; the next act's claim keeps that level as its +// target with her core hands as the only floor, and the request carries exactly the +// selection the allocation bought. +#[test] +fn an_epoch_keeps_the_tool_level_its_allocation_bought() { + let raw: Vec = ["code/read", "work/state", "chat/send", "commands/list", "room/join", "code/git/status", "work/submit", "web/fetch"] + .iter() + .map(|n| NativeToolSpec { + name: (*n).to_string(), + description: format!("{n}: does what its name says"), + input_schema: crate::ai::types::ToolInputSchema { + schema_type: "object".to_string(), + properties: serde_json::json!({}), + required: None, + definitions: None, + }, + }) + .collect(); + let adapter: Arc = Arc::new(HeuristicInferenceAdapter::new()); + let faculty = LlmDeliberationFaculty::new(Uuid::new_v4(), "Asha", "You are Asha.", adapter).with_tools(raw); + let ws = Workspace::new("what changed on the board?"); + let first = faculty.prompt_view_within(&ws, 200_000); + assert!(first.capacity_error.is_none(), "{:?}", first.capacity_error); + let claim = faculty.tools_claim(&ws); + assert!(claim.floor < claim.want, "core hands are smaller than her whole hands: {claim:?}"); + assert_eq!(first.tools.tokens, claim.want, "an ample grant buys her whole surface"); + assert_eq!(claim.level, first.tools.tokens, "the epoch keeps the level it chose as its target"); + assert!(first.tools_grant >= first.tools.tokens, "the selection stays within its grant"); + let second = faculty.prompt_view_within(&ws, 200_000); + assert_eq!( + serde_json::to_string(&second.tools.specs).expect("schemas"), + serde_json::to_string(&first.tools.specs).expect("schemas"), + "the same epoch sends byte-identical schemas" + ); +} 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 89e00aa1e9..f95e22826f 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 @@ -92,9 +92,6 @@ async fn substrate_notices_survive_attention_and_history_pressure_once() { // against a 23,040 window, 192 of 229 cognition cycles refused (84%), both // citizens mute for hours while serving reported ready. // -// Mutation check: delete the cap in `bounded_room_updates` (collect every -// update instead) and this goes RED with a capacity_error — which is exactly -// the production symptom. #[tokio::test] async fn a_busy_room_cannot_make_a_citizen_mute() { let adapter: Arc = Arc::new(HeuristicInferenceAdapter::new()); @@ -129,37 +126,14 @@ async fn a_busy_room_cannot_make_a_citizen_mute() { view.capacity_error ); - // The NEWEST updates stay REQUIRED; the older ones are DEMOTED, not - // deleted. Joel, 2026-09-09: "maybe trim clipped or killed important - // information the persona needed to complete things" — a task or a - // correction that arrived earlier in the batch must not vanish before - // she reads it, so the overflow rides in ordinary history instead. - let (required, demoted) = faculty.split_room_updates(&ws); - assert!(!required.is_empty(), "the newest update is always required"); + // Every update is a conversation turn of her view keyed by its event, so the room + // cannot inflate the required input at all (it was required under a quarter-window + // share); the newest reaches the prompt whole. + let text: Vec = view.messages.iter().map(|m| m.content_text().to_string()).collect(); + assert!(text.iter().any(|t| t.contains("update 39")), "the newest update reaches her prompt"); assert!( - !demoted.is_empty(), - "an over-share payload must actually be demoted" - ); - assert_eq!( - required.len() + demoted.len(), - 40, - "every update survives somewhere — demotion must not DELETE" - ); - assert!( - required - .last() - .expect("required is non-empty") - .content_text() - .contains("update 39"), - "the NEWEST update must stay required" - ); - assert!( - demoted - .first() - .expect("demoted is non-empty") - .content_text() - .contains("update 0"), - "the OLDEST update is the one demoted, and it is still present" + !view.messages.last().is_some_and(|m| m.content_text().contains("[Room message received during this turn")), + "room updates ride her view, not the required tail" ); } 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 c0f43d62cb..7e2abecf2e 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 @@ -213,7 +213,7 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { crate::cognition::tool_surface::tool_surface_tokens_of(request.tools.as_ref().unwrap()); assert_eq!( schema_tokens, - faculty.select_tool_surface(&ws).tokens + faculty.prompt_view(&ws).tools.tokens ); let wire_tokens = LlmDeliberationFaculty::framing_cost(request.system_prompt.as_ref().unwrap()) @@ -304,11 +304,11 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { let window = 8192u32; for oversized_part in 0..5 { let persona = Uuid::new_v4(); - // Parts 0-2 must never reach the adapter, so an EMPTY script proves it. - // Parts 3-4 shed their enrichment and go on to think, so they need a real - // response — reaching the model is the outcome those cases assert. + // Part 0 (the oversized stimulus) must never reach the adapter, so an EMPTY script + // proves it. Parts 1-4 bound, shed or collapse and go on to think, so they need a + // real response — reaching the model is the outcome those cases assert. let adapter = Arc::new(ScriptedAdapter::new( - if oversized_part >= 3 || oversized_part == 1 { + if oversized_part != 0 { vec![make_response(FinishReason::Stop, "PASS", None)] } else { vec![] @@ -365,15 +365,20 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { .with_context_window(window) .with_working_memory(wm) .with_working_set(registry.clone()); - // Parts 3-4 shed their standing grounding (#3954) and part 1 caps its - // oversized action result and demotes the rest — all three now THINK - // instead of refusing. What still faults is a genuinely irreducible - // payload: the stimulus (part 0) and a room update (part 2), neither of - // which any bound may drop without answering a question she was never - // shown. - let bounded_case = oversized_part >= 3 || oversized_part == 1; + // Parts 3-4 shed their standing grounding (#3954), part 1 caps its oversized + // action result and demotes the rest, and part 2's room update is a turn of her + // view that collapses to its handle (`chat/history`) — all four now THINK + // instead of refusing. What still faults is the genuinely irreducible payload: + // the stimulus (part 0), the question she is answering. + let bounded_case = oversized_part != 0; let grounding_case = bounded_case; let view = faculty.prompt_view(&ws); + if oversized_part == 2 { + assert!( + view.messages.iter().any(|m| m.content_text().contains("reread with chat/history")), + "an oversized room update is never unknown: the index names where it is" + ); + } if grounding_case { assert!( view.capacity_error.is_none(), @@ -581,7 +586,7 @@ async fn a_refused_tail_rebuilds_her_request_without_it_once() { let rebuilt = &seen[1]; assert!(rebuilt.tail_tools.is_none(), "the rebuilt request carries no tail"); let offered: Vec<&str> = rebuilt.tools.iter().flatten().map(|tool| tool.name.as_str()).collect(); - let activity = faculty.select_activity_surface(&ws); + let activity = faculty.tool_surface().select_granted(&ws.room_affordances, faculty.prompt_view(&ws).tools_grant).expect("activity fits granted tools"); let expected: Vec<&str> = activity.specs.iter().flat_map(|specs| specs.iter()).map(|tool| tool.name.as_str()).collect(); assert!(!offered.is_empty() && offered == expected, "she is offered exactly her activity's surface: {offered:?}"); if refusals == 1 { diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs index f0f9bd921d..0471ca7809 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs @@ -65,7 +65,7 @@ async fn live_window_reductions_bound_actual_requests_and_persist() { let schemas = crate::cognition::tool_surface::tool_surface_tokens_of( request.tools.as_ref().expect("native tools retained"), ); - assert_eq!(schemas, faculty.select_tool_surface(&ws).tokens); + assert_eq!(schemas, faculty.prompt_view(&ws).tools.tokens); assert_eq!(request.max_tokens, Some(expected_view.completion_reserve)); let cost = LlmDeliberationFaculty::framing_cost( request.system_prompt.as_deref().expect("system framing"), diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs index 9eb03d5cc1..d1df36d585 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs @@ -61,7 +61,7 @@ impl LlmDeliberationFaculty { /// reserves the head the next epoch would hold, so a turnover can adopt it and the shadow /// receipt (`delib.tool_head.epoch`) measures it. It changes what is SENT only on a server /// that takes `tail_tools`, where a verb outside the head stays callable. - fn with_learned_head<'a>(&'a self, selected: SelectedSurface<'a>, ws: &Workspace) -> SelectedSurface<'a> { + fn with_learned_head<'a>(&'a self, selected: SelectedSurface<'a>, ws: &Workspace, budget: usize) -> SelectedSurface<'a> { let Some(memory) = self.working_memory.as_deref() else { return selected; }; @@ -69,7 +69,6 @@ impl LlmDeliberationFaculty { return selected; }; let binding = self.binding.load(); - let budget = super::super::context_budget::ContextBudget::from_window_unbounded(binding.context_window).tool_surface_tokens(); let head = memory.tool_head(); let next = head.next( ws.now_ms.map_or_else(continuum_base::time::EpochMs::now, continuum_base::time::EpochMs::from_millis), // map_or_else: a workspace that carries no clock reading decides at now @@ -92,36 +91,21 @@ impl LlmDeliberationFaculty { &self.surface } - /// The tool surface THIS turn sends, what it COSTS, and WHY, decided once and consulted - /// by both the budget and the request (card dec1a7ff: when the accounting priced the - /// registry while the request sent hands, the conversation was trimmed to fit room that - /// was never occupied). - /// - /// Its inputs are the activity's declaration and the SERVED window, never the turn: - /// consecutive acts in one activity send byte-identical schemas, so the prefix after the - /// system prompt survives (goal 10; [`crate::cognition::tool_surface`] has the why). - pub fn select_tool_surface(&self, ws: &Workspace) -> SelectedSurface<'_> { - self.with_learned_head(self.select_activity_surface(ws), ws) + /// Whole demand before focus allocation. The epoch owner records this beside + /// the grant; the grant never becomes a demand observation. + pub fn tool_claim_tokens(&self, ws: &Workspace) -> (usize, usize) { + let held = self.working_memory.as_ref().and_then(|wm| wm.tool_head().held()).unwrap_or_default(); // unwrap_or_default: no learned head contributes no extra verbs + self.surface.claim_with_head(&ws.room_affordances, &held) } - /// The activity's own surface, without her learned head: what she is offered when her - /// destination refused the tail (`InferenceError::TailToolsUnreachable`), so every verb she - /// sees is one she can call. - pub(super) fn select_activity_surface(&self, ws: &Workspace) -> SelectedSurface<'_> { - let selected = self.surface.select(&ws.room_affordances, self.binding.load().context_window); - if !ws.room_affordances.is_empty() - && !matches!(selected.reason, SurfaceReason::RoomAffordances | SurfaceReason::NoTools) - { - continuum_base::probe!( - class = "delib.surface.room_affordances_unmatched", - persona = %self.persona_name, - room = %ws.activity_room_id, - declared = ws.room_affordances.len(), - "the room's recipe declares affordances and none names a native verb: \ - the rule binds nothing here; offering her hands instead" - ); - } - selected + /// Called at epoch start with the ONE allocation's tools grant. Retain the + /// returned selection for accounting and the wire until the next epoch. + pub fn select_tool_surface_granted(&self, ws: &Workspace, grant_tokens: usize) -> Result, usize> { + let (_, want) = self.tool_claim_tokens(ws); + let activity = self.surface.select_granted(&ws.room_affordances, grant_tokens)?; + let selected = self.with_learned_head(activity, ws, grant_tokens); + if selected.tokens > grant_tokens { return Err(selected.tokens); } + Ok(selected.with_demand(want)) } /// Her view started a new epoch, the one moment her head may change: her tool head learns @@ -181,7 +165,7 @@ impl LlmDeliberationFaculty { if self.surface.registry().is_empty() { return; // no hands offered — nothing to fit, nothing to warn about } - let window = self.binding.load().context_window; + let window = self.working_window(); let needed = self.min_window_for_agentic_surface(); if window >= needed { return; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index e44d32a6f2..0d872c94d0 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -144,6 +144,23 @@ impl LlmDeliberationFaculty { return Some(Contribution::deliberation_fault(fault.clone())); } if let Some(error) = view.capacity_error { + // Required input past the WORKING window is served from the whole slot, once, + // never refused while the slot has room (`ContextBudget::working_window`). + let (served_fit, served_calibration) = self.prompt_fit_served(&binding); + if served_fit > fit_window { + continuum_base::probe!( + class = "delib.prompt.working_window_exceeded", + persona = %self.persona_name, + required_tokens = error.required_tokens, + working_window = fit_window, + served_window = served_fit, + "required input exceeds the working window: this act is fitted to the served window instead" + ); + fit_window = served_fit; + calibration = served_calibration; + view = self.prompt_view_with_visual_feedback(ws, fit_window, calibration, visual.as_ref()); + continue; + } continuum_base::probe!( class = "delib.prompt.capacity", persona = %self.persona_name, @@ -206,14 +223,19 @@ impl LlmDeliberationFaculty { // the structured-turns refactor that fixes the echo loop. // A verb not on her native surface still DISPATCHES: `act_observe` resolves any // call by name, and the system prompt's menu plus `commands/help` reach it. - // WHICH surface she is offered is a question about her ACTIVITY and the served - // window, never about this turn: the schemas sit right after the system prompt, - // so a surface that moves between acts re-prefills everything after it (goal 10; - // `cognition::tool_surface` has the measurement). The decision lives in - // [`Self::select_tool_surface`] so the budget in `prompt_view_within` reaches the - // SAME answer (card dec1a7ff). + // The view retains the tool level bought by the shared allocation for this epoch. + // Send that same selection so accounting, wire bytes and prefix reuse agree. if request_template.is_none() { - let mut selected = if tail_refused { self.select_activity_surface(ws) } else { self.select_tool_surface(ws) }; + // What her view's allocation bought; a server that refuses `tail_tools` gets the + // activity surface at the same grant, without her learned head. + let mut selected = if tail_refused { + match self.surface.select_granted(&ws.room_affordances, view.tools_grant) { + Ok(activity) => activity.into_owned(), + Err(_) => view.tools.clone(), // unreachable in practice: the view ran this same activity selection at this grant and it succeeded + } + } else { + view.tools.clone() + }; // Verbs she loaded into the tail ride beside the head, callable natively. let tail = std::mem::take(&mut selected.tail); if selected.reason == SurfaceReason::CoreHandsForWindow { @@ -228,11 +250,10 @@ impl LlmDeliberationFaculty { hands = self.surface.hands().len() as u64, surface_tokens = selected.tokens as u64, withheld_tokens = selected.demand_tokens().saturating_sub(selected.tokens) as u64, - budget_tokens = super::super::super::context_budget::ContextBudget::from_window_unbounded(served) - .tool_surface_tokens() as u64, + budget_tokens = view.tools_grant as u64, context_window = served, - "her extended hands exceed the served window's tool share: \ - offering her core hands; the discovery pair still reaches the rest" + "her one allocation granted her core hands, not her extended ones: \ + the discovery pair still reaches the rest" ); } // Selection and budget accounting borrow the cached schemas. Only the @@ -391,6 +412,8 @@ impl LlmDeliberationFaculty { } } }; + // Sent and answered: she read what this prompt rendered (read_receipt.rs), never before. + self.send_read_receipt(ws).await; let messages = &view.messages; let lifecycle_recorded = self .prompt_capture diff --git a/core/continuum-cognition/src/cognition/persona_tools.rs b/core/continuum-cognition/src/cognition/persona_tools.rs index f1b3cee772..94795f0130 100644 --- a/core/continuum-cognition/src/cognition/persona_tools.rs +++ b/core/continuum-cognition/src/cognition/persona_tools.rs @@ -36,12 +36,6 @@ use serde_json::json; use std::collections::BTreeMap; use std::fmt::Write as _; -// The per-tool catalog-summary bound is a fraction of her LIVE window -// (`ContextBudget::catalog_summary_chars`), never a constant: a catalog lists ~100 tools, so -// an unbounded line re-creates the dump — but a roomy window can afford a fuller clause per -// tool, and that is real PX. The full call format still arrives via `TOOL_HELP_NAME`. -// [[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]] -use crate::cognition::context_budget::ContextBudget; /// The persona's tool surface: every command it is AUTHORIZED to run at `trust`, /// projected to a tool spec. **Offer == authorized, by construction** — a persona @@ -117,59 +111,6 @@ pub fn descriptor_to_tool_spec(d: &CommandDescriptor) -> NativeToolSpec { // data-driven projection of the registry (NOT output puppeteering): same single // source of truth as [`authorized_tool_specs`], just a leaner representation. -/// One compact catalog line: a tool's name, a one-line summary, and the category -/// it groups under (the first path segment, via [`extract_category`]). -#[derive(Debug, Clone)] -pub struct ToolCatalogEntry { - pub name: String, - pub summary: String, - pub category: String, -} - -/// The persona's tool catalog at `trust`: the same authorized set as -/// [`authorized_tool_specs`], projected to compact [`ToolCatalogEntry`] lines -/// (name + one-line summary + category) instead of full schemas. This is what the -/// persona browses; the full call format for any one tool comes from -/// [`TOOL_HELP_NAME`] on demand. -pub fn authorized_tool_catalog(trust: TrustLevel) -> Vec { - command_registry_live() - .iter() - .filter(|d| is_command_authorized(d.name, trust)) - .map(|d| ToolCatalogEntry { - name: d.name.to_string(), - summary: tool_summary(d), - category: extract_category(d.name).to_string(), - }) - .collect() -} - -/// A tool's one-line summary for the catalog: the first sentence / first line of -/// its declared description, bounded by the live window's catalog share. Falls back to the -/// param-type handle when the command declares no description (same fallback as -/// [`descriptor_to_tool_spec`], kept consistent). -fn tool_summary(d: &CommandDescriptor) -> String { - let raw = if d.description.is_empty() { - format!("params: {}", d.params.name) - } else { - // First line, then first sentence within it — whichever ends sooner. - let first_line = d.description.lines().next().unwrap_or("").trim(); // unwrap_or: an empty description has no first line; the summary is empty - match first_line.find(". ") { - Some(i) => first_line[..i].to_string(), - None => first_line.trim_end_matches('.').to_string(), - } - }; - let raw = raw.split_whitespace().collect::>().join(" "); - // `live_or_floor`, not `live`: the catalog is assembled BEFORE the prompt guard, so an - // unbounded summary here yields a menu that cannot fit rather than one trimmed later. - let cap = ContextBudget::live_or_floor().catalog_summary_chars(); - if raw.chars().count() <= cap { - raw - } else { - let truncated: String = raw.chars().take(cap.saturating_sub(1)).collect(); - format!("{}…", truncated.trim_end()) - } -} - /// Render the persona's tool surface as a NAMED CATALOG GROUPED BY CATEGORY — one /// line per category listing the verb of every tool it holds (`code: run, read, /// edit, write, search, …`), NOT each tool's full schema. 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 bd826e615c..5866653374 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 @@ -110,6 +110,10 @@ pub struct PersonaBrainConfig { /// page per room and never queue behind the living mind's act, since it acts beside /// her (`slots::PageKey::Fork`). `false` for every resident. pub forked: bool, + /// Where her sent prompts' read receipts go: her airc source, which advances her room + /// cursor through what each sent prompt rendered. `None` (a fork, an eval, a harness) + /// marks nothing read. + pub read_receipt: Option>, } /// Whether a grounding source must run synchronously on the inference loop, or @@ -433,15 +437,10 @@ pub(super) fn assemble_workspace_cycle( // synchronous so it's never `None` on the first tick. Eval/harness keep // everything synchronous (`defer_grounding == false`) — their tight settle-loops // never yield to the worker, so deferral there would measure a starved mind. - // Per-source grounding ceiling scales with the LIVE served window (task #50's - // single-sourced `cfg.context_window`), exactly like recall's budget above — - // never a baked constant (task #124). A 128k model lets each source hold its - // full board/map/roster; a tight window shrinks them honestly; the packer keeps - // the total ≤ window. - let grounding_budget = super::super::rag_source_faculty::grounding_budget_for(cfg.context_window); + // No per-source ceiling: each source delivers every item at its levels and her prompt + // view's one allocation decides what she sees (FLOW-IMPLEMENTATION-PLAN §2d). for g in cfg.grounding_sources { let faculty = RagSourceFaculty::new(cfg.persona_id, g.source, g.policy) - .with_budget(grounding_budget) .with_volatile_content(g.volatile_content) // Deferrability is also a LOUDNESS contract, not only a scheduling one // (#3873). ColdStartCritical means "absent here is a wrong turn", so a @@ -509,6 +508,10 @@ pub(super) fn assemble_workspace_cycle( ws }); let mut deliberation = if cfg.forked { deliberation.forked() } else { deliberation }; + // A fork copies the living config but never marks her rooms read: it acts beside her. + if let Some(receipt) = cfg.read_receipt.clone().filter(|_| !cfg.forked) { + deliberation = deliberation.with_read_receipt(receipt); + } if tool_executor.is_some() { // Offer EXACTLY what this persona is authorized to run (offer == // authorized) — never a tool the gate would refuse. A local persona is the 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 6d9f4f0436..b49dc23bc8 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 @@ -151,6 +151,7 @@ use super::*; // benchmark-reproducibility knob set only by the eval fork. suppress_recall: false, forked: false, + read_receipt: None, } } @@ -491,21 +492,12 @@ use super::*; } /// Test/stub source — floorless, so it never encodes a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - async fn deliver( - &self, - _ctx: &crate::cognition::rag_budget::RagContext, - _budget: u32, - resolution: crate::cognition::rag_budget::ResolutionPreference, - ) -> crate::cognition::rag_budget::RagDelivery { + async fn deliver(&self, _ctx: &crate::cognition::rag_budget::RagContext) -> crate::cognition::rag_budget::RagDelivery { crate::cognition::rag_budget::RagDelivery { source_id: "classify-stub".to_string(), items: Vec::new(), tokens_used: 0, truncated: false, - resolution_used: resolution, } } } @@ -574,25 +566,19 @@ use super::*; } /// Test/stub source — floorless, so it never encodes a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - async fn deliver( - &self, - _ctx: &crate::cognition::rag_budget::RagContext, - _budget: u32, - resolution: crate::cognition::rag_budget::ResolutionPreference, - ) -> crate::cognition::rag_budget::RagDelivery { + async fn deliver(&self, _ctx: &crate::cognition::rag_budget::RagContext) -> crate::cognition::rag_budget::RagDelivery { crate::cognition::rag_budget::RagDelivery { source_id: "workspace-map".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!("workspace layout — {HANDS_MARKER}"), tokens: 12, metadata: serde_json::Value::Null, }], tokens_used: 12, truncated: false, - resolution_used: resolution, } } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs index 41a78331ad..7ac03b04cd 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs @@ -65,15 +65,7 @@ use super::*; } /// Test/stub source — floorless, so it never encodes a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - async fn deliver( - &self, - _ctx: &crate::cognition::rag_budget::RagContext, - _budget: u32, - resolution: crate::cognition::rag_budget::ResolutionPreference, - ) -> crate::cognition::rag_budget::RagDelivery { + async fn deliver(&self, _ctx: &crate::cognition::rag_budget::RagContext) -> crate::cognition::rag_budget::RagDelivery { self.entries.fetch_add(1, AtomicOrdering::SeqCst); self.entered.notify_one(); // Park until the test opens the gate. `wait_for` returns immediately @@ -82,13 +74,15 @@ use super::*; crate::cognition::rag_budget::RagDelivery { source_id: "gated-grounding".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: "roster: Ivar [persona], win-claude [claude]".to_string(), tokens: 12, metadata: serde_json::Value::Null, }], tokens_used: 12, truncated: false, - resolution_used: resolution, } } } diff --git a/core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs b/core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs index 8a1d0d12c5..c28e19a601 100644 --- a/core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs +++ b/core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs @@ -206,38 +206,6 @@ pub fn flex_allocate(available: u32, claims: &[RagSourceBudget]) -> FlexAllocati } } -pub(super) fn empty_allocation( - context_window: u32, - reserved: ReservedTokens, - sources: &[RagSourceBudget], - warnings: Vec, - escalation_needed: bool, -) -> BudgetAllocation { - BudgetAllocation { - context_window, - reserved, - available_for_sources: 0, - allocations: sources - .iter() - .map(|s| SourceAllocation { - source_id: s.source_id.to_string(), - allocated_tokens: 0, - requested_floor: s.floor_tokens, - requested_min: s.min_tokens, - requested_max: s.max_tokens, - state: if s.required { - AllocationState::UnderProvisioned - } else { - AllocationState::Dropped - }, - }) - .collect(), - total_allocated: 0, - unallocated: 0, - escalation_needed, - warnings, - } -} //============================================================================= // TEST STUB SOURCE — proves the trait shape compiles + composes @@ -274,52 +242,12 @@ impl RagSource for StubRagSource { None } - /// Test/stub source — floorless, so allocator tests exercise the grow pass - /// rather than accidentally encoding a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - _resolution: ResolutionPreference, - ) -> RagDelivery { - // Defense-in-depth identity check: this source is bound to - // a specific persona at construction; refuse calls from a - // different ctx.persona_id by returning empty (no panics, - // no half-state — graceful degradation). + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + // Defense-in-depth identity check: this source is bound to a specific persona at + // construction; another persona's ctx gets nothing (no panics, no half-state). if ctx.persona_id != self.persona_id { - return RagDelivery { - source_id: self.source_id.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - }; - } - - let mut taken = Vec::new(); - let mut used: u32 = 0; - for item in &self.items { - if used.saturating_add(item.tokens) > budget { - break; - } - used += item.tokens; - taken.push(item.clone()); - } - // Ruling a: no positional cursor — truncation is notice metadata, - // and the next deliver re-derives from scratch (a larger budget - // simply fits more). - let truncated = taken.len() < self.items.len(); - RagDelivery { - source_id: self.source_id.to_string(), - items: taken, - tokens_used: used, - truncated, - resolution_used: ResolutionPreference::Raw, + return RagDelivery::empty(self.source_id); } + RagDelivery::of(self.source_id, self.items.clone(), false) } - } diff --git a/core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs b/core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs index d99323713f..0bfa506b8f 100644 --- a/core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs +++ b/core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs @@ -186,42 +186,6 @@ pub struct RagSourceBudget { pub required: bool, } -impl RagSourceBudget { - /// Existing retrieval appetite, resolved against this turn's capacity. - /// The source owns its atomic floor; the shared allocator still owns fitting. - pub fn retrieval(source_id: &str, floor: u32, window: u32, headroom: u32) -> Self { - let max = (((window as u64) * 6 / 10) as u32).min(headroom); - let floor = floor.min(max); - Self { - source_id: source_id.to_owned(), - priority: 10, - floor_tokens: floor, - min_tokens: COMFORTABLE_SOURCE_TOKENS.min(max).max(floor), - max_tokens: max, - required: false, - } - } - - /// A lightweight source's existing window-relative offer. The denominator - /// belongs to that source's content policy, never to its identifier. - pub fn floorless_share( - source_id: &str, - window: u32, - headroom: u32, - denominator: std::num::NonZeroU32, - ) -> Self { - let mut claim = Self::retrieval(source_id, 0, window, headroom); - claim.min_tokens = 0; - claim.max_tokens = claim.max_tokens.min(window / denominator.get()); - claim - } -} - -/// Existing comfortable retrieval target (not the atomic survival floor). -/// Measured first units are 6..40 tokens; a source can survive below this target. -// context-budget-exempt: a per-source TARGET, capped by the resolved window/headroom -pub(super) const COMFORTABLE_SOURCE_TOKENS: u32 = 500; - /// Per-source outcome. Reported back from the allocator. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SourceAllocation { @@ -257,100 +221,18 @@ pub enum AllocationState { UnderProvisioned, } -/// Reserved tokens — fixed costs that come off the top before any -/// source allocation. `system` is the system prompt + identity -/// header overhead; `completion` is the tokens reserved for the -/// model's output. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub struct ReservedTokens { - pub system: u32, - pub completion: u32, -} - -impl ReservedTokens { - pub fn total(self) -> u32 { - self.system.saturating_add(self.completion) - } - - /// THE window-scaled reservation shape (#424 dedup — this derivation was - /// byte-identical in `unified.rs` and `rag_inspect.rs`; one logical - /// decision lives in one place). Reservations scale as a percentage of - /// the window per [[intent-driven-api-not-hot-patches]]: a 2048-window - /// persona can't reserve a flat 4000 for completion (negative headroom → - /// all sources get 0 → cognition fires with no RAG content → LLM defaults - /// to the grammar-shortest "will_respond=false" attractor), while an - /// M-series 32k persona shouldn't be pinned to Compat-tier crumbs. - /// - /// - system: 10% of window, clamped [128, 512] - /// - completion: 25% of window, clamped [256, 4_000] - /// - /// This is a FALLBACK shape, not a budgeter: the substrate's real - /// budgeter (profile/model-characteristic driven) can override via a - /// richer reservation API. NOTE the 4_000 completion ceiling is the RAG - /// *reservation* only — the generation ceiling itself is deliberately - /// uncapped (`llm_deliberation_faculty::completion_budget_for`, Joel - /// 2026-07-13: stop choking context); whether this reservation should - /// follow it up on large windows is an open budgeting question, not a - /// dedup question. - pub fn scaled_for_window(context_window: u32) -> Self { - Self { - system: (context_window / 10).clamp(128, 512), - completion: (context_window / 4).clamp(256, 4_000), - } - } - - /// Actual tokens left for sources after this reservation. Exhausted capacity - /// is zero, never a fabricated minimum; the allocator reports underprovisioning. - pub fn headroom_within(self, context_window: u32) -> u32 { - context_window.saturating_sub(self.total()) - } -} - -/// Full allocation result. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct BudgetAllocation { - pub context_window: u32, - pub reserved: ReservedTokens, - pub available_for_sources: u32, - pub allocations: Vec, - pub total_allocated: u32, - pub unallocated: u32, - /// True if any required source ended up `UnderProvisioned`. - /// Caller MUST handle this — escalate to operator, request - /// lower-resolution content from sources, or switch models. - pub escalation_needed: bool, - /// Warnings collected during allocation — non-fatal but - /// surfaced for operator visibility (e.g., "floors exceeded - /// available budget; dropped required=false sources"). - pub warnings: Vec, -} - //============================================================================= // SOURCE-OWNED DELIVERY (the no-clipping mechanism) //============================================================================= -/// What "resolution" of content the allocator wants from a source. -/// The source delivers at the resolution that fits its budget; -/// compression is a substrate-side fallback, never a clip. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ResolutionPreference { - /// Verbatim, full fidelity. L1 raw — recent messages, current - /// engrams in their original form. - Raw, - /// L2-style outlined gist. Used when raw doesn't fit but the - /// source has a compressed form available. - Compressed, - /// Single-sentence digest per item. - Summarized, - /// Metadata-only ("3 engrams from coding session, gist available - /// on demand via cursor"). Last resort before drop. - Placeholder, -} - /// One delivered item — already a complete atomic unit by the /// source's definition. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct RagItem { + /// Stable for the item's life within its source (a card id, a post id, a peer id, an + /// engram id): what her view keys the item by, so it appends only when this item + /// changes. Empty in captures written before keys. + #[serde(default)] + pub key: String, /// Ready-to-include text. The source has serialized, formatted, /// and verified structural completeness. Allocator concatenates /// directly into the prompt. @@ -361,27 +243,64 @@ pub struct RagItem { /// content hash. Lets prompt assembly + sentinel verifiers /// trace what made it in. pub metadata: serde_json::Value, + /// A coarser level between whole and pointer (a post's category and first line, a + /// memory's gist), the view's choice when the whole does not fit (FLOW plan §2d). + /// Absent in captures written before levels. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// What the item is and how to reopen it (an id and the verb): its cost once collapsed. + /// `None` when a collapsed item leaves her view entirely. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pointer: Option, +} + +impl RagItem { + /// An item at its whole level, priced by the one estimator, with no coarser levels yet. + pub fn whole(key: impl Into, content: impl Into, metadata: serde_json::Value) -> Self { + let content = content.into(); + let tokens = continuum_base::token_estimate::estimate_prompt_tokens(&content); + Self { key: key.into(), content, tokens, metadata, summary: None, pointer: None } + } + + /// With a summary level. + pub fn with_summary(mut self, summary: impl Into) -> Self { + self.summary = Some(summary.into()); + self + } + + /// With a pointer level. + pub fn with_pointer(mut self, pointer: impl Into) -> Self { + self.pointer = Some(pointer.into()); + self + } } /// What a source returns when asked to deliver. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct RagDelivery { pub source_id: String, - /// Items already pre-validated as complete atomic units. Never - /// partial. Sum of `items[i].tokens` <= the budget the source - /// was given. + /// Every item the source holds, each a complete unit at its levels. Never partial and + /// never sized: the one allocation in her prompt view chooses each item's level. pub items: Vec, /// Actual tokens consumed across all items. pub tokens_used: u32, - /// True → the source has more than it delivered; the remainder reaches - /// the reader through the source's `expand_command` (whole-or-handle). - /// No production allocator resumes a position today — truncation is - /// notice metadata, not a resumable handle (ruling a; card e049aa82). + /// True → the source holds more than it delivered (a room's scrollback beyond its + /// fetch); the rest reaches the reader through the source's `expand_command`. Never a + /// budget cut: sources no longer take one. pub truncated: bool, - /// What resolution the source actually used. May differ from - /// the requested resolution if the source's content can't fit - /// at the requested resolution. - pub resolution_used: ResolutionPreference, +} + +impl RagDelivery { + /// Every item a source holds, `tokens_used` summed from them. + pub fn of(source_id: &str, items: Vec, truncated: bool) -> Self { + let tokens_used = items.iter().fold(0u32, |sum, item| sum.saturating_add(item.tokens)); + Self { source_id: source_id.to_owned(), items, tokens_used, truncated } + } + + /// A source with nothing to say this turn. + pub fn empty(source_id: &str) -> Self { + Self::of(source_id, Vec::new(), false) + } } /// Deserializes both wire forms of a delivered RAG pack. Current captures carry @@ -404,7 +323,6 @@ impl<'de> Deserialize<'de> for RagDelivery { tokens_used: u32, /// Current form; absent on pre-ruling-a lines. truncated: Option, - resolution_used: ResolutionPreference, /// Legacy form; never emitted today — read only for old JSONL. continuation: Option, } @@ -422,7 +340,6 @@ impl<'de> Deserialize<'de> for RagDelivery { items: w.items, tokens_used: w.tokens_used, truncated, - resolution_used: w.resolution_used, }) } } @@ -476,193 +393,16 @@ pub trait RagSource: Send + Sync { /// the same forcing function as persona's `room_board_source::RoomBoardReader::peer_names`. fn expand_command(&self) -> Option<&'static str>; - /// The cost, in tokens, of the SMALLEST COMPLETE STATEMENT this source can - /// make — its first atomic unit, not its comfortable size. - /// - /// This is the allocator's floor for the source, and the allocator's rule - /// for a floor that doesn't fit is to drop the source ENTIRELY. So this - /// number decides, alone, whether a citizen under budget pressure hears - /// anything at all from this source. - /// - /// ### The defect this exists to kill (measured 2026-08-06) - /// - /// Every source was assigned a hardcoded floor of **500** tokens by - /// `unified.rs`, a number unrelated to any of them. Their real first units, - /// measured off a live prompt: room 6, board 26, workspace-map 32, - /// recall 40 — about **104 tokens for one complete unit from all six**. - /// On a node whose grounding budget measured 0..214, every source was - /// dropped on 100% of turns (137 of 137 for one citizen, 132 of 132 for - /// another) while asking for 12-80x more than it needed to say something - /// true. That is what made grounding all-or-nothing instead of degrading: - /// a source that could have delivered a complete 26-token headline was - /// never asked for it. + /// Every item this source holds, each at its levels (whole, `summary`, `pointer`). A + /// source never takes a size: the one allocation in her prompt view decides which level + /// each item gets (FLOW-IMPLEMENTATION-PLAN §2d). Before this each source was handed its + /// own budget (a quarter of the window per grounding faculty, a second flexbox in + /// `compose_for_turn`) and cut or head-trimmed to it before the view ever saw it. /// - /// So: answer with what your FIRST unit actually costs. Not what you'd - /// like. `0` is legitimate and means "I have no floor — give me whatever is - /// left over" (the lightweight roster/doctrine shape). There is no default - /// impl on purpose: a default would let a new source silently inherit - /// someone else's appetite, which is exactly how the 500 got everywhere. - fn floor_tokens(&self) -> u32; - - /// Declare this source's appetite independently of its name or decoration. - /// This is input to the existing allocator, not a second allocation path. - fn budget_claim(&self, window: u32, headroom: u32) -> RagSourceBudget { - RagSourceBudget::retrieval(self.source_id(), self.floor_tokens(), window, headroom) - } - - /// Deliver as many complete atomic units as fit within `budget`. - /// The source decides what counts as complete; allocator only - /// trusts that `delivery.tokens_used <= budget`. - /// - /// `ctx` carries the per-call substrate context (persona scope, - /// timing, room handle). Sources MUST validate that - /// `ctx.persona_id == self.persona_id` if they're bound to a + /// `ctx` carries the per-call substrate context (persona scope, timing, room handle). + /// Sources MUST validate that `ctx.persona_id == self.persona_id` if they're bound to a /// specific persona at construction. - /// - /// If `resolution = Raw` doesn't fit, the source MAY automatically - /// fall back to a lower resolution and report - /// `delivery.resolution_used`. The source decides when fallback - /// is preferable to delivering fewer items at higher resolution. - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery; -} - -//============================================================================= -// ADAPTER TRAIT — POLYMORPHISM RAIL -//============================================================================= -/// The allocation strategy. Ship one heuristic impl -/// (`FlexboxRagBudgetAdapter`); future learnable adapters -/// (`LearnedRagBudgetAdapter` reading telemetry from -/// `MemoryParameterAdapter`) slot in without changing callers per -/// the adapter-first methodology. -pub trait RagBudgetAdapter: Send + Sync { - fn name(&self) -> &'static str; - - /// Allocate tokens to each source. Pure-function — no I/O, no - /// async. Sources are CALLED later with their allocation by - /// the prompt-assembly layer. - /// - /// `ctx` first per the Android Context pattern. Allocators may - /// use it for telemetry stamping, persona-specific tuning (a - /// future `LearnedRagBudgetAdapter` reads per-persona regret - /// signals from `MemoryParameterAdapter`), or for stable - /// deterministic seeds keyed on `(ctx.persona_id, ctx.turn_id)`. - fn allocate( - &self, - ctx: &RagContext, - context_window: u32, - reserved: ReservedTokens, - sources: &[RagSourceBudget], - ) -> BudgetAllocation; -} - -//============================================================================= -// FLEXBOX ADAPTER — THE FIRST CONCRETE IMPL -//============================================================================= -/// CSS-flexbox-inspired allocation. Algorithm (anti-clipping): -/// -/// 1. Reserve system + completion off the top -/// 2. **Floor pass** — allocate `floor_tokens` to every source. -/// Floors are unconditional; if floor totals exceed available, -/// drop required=false sources by priority (lowest first) until -/// required floors fit. If even required floors can't fit, set -/// affected sources to `UnderProvisioned` + flag escalation. -/// 3. **Min pass** — top up to `min_tokens` for sources by priority. -/// If a source can't reach `min_tokens` but is at >= `floor_tokens`, -/// its state is `FloorOnly`. -/// 4. **Grow pass** — distribute remaining tokens by priority weight, -/// capped at `max_tokens` per source. Iterate until no movement -/// (capped sources release tokens to non-capped). -/// 5. Report — each source's state classifies the outcome. -pub struct FlexboxRagBudgetAdapter; - -impl FlexboxRagBudgetAdapter { - pub fn new() -> Self { - Self - } -} - -impl Default for FlexboxRagBudgetAdapter { - fn default() -> Self { - Self::new() - } -} - -impl RagBudgetAdapter for FlexboxRagBudgetAdapter { - fn name(&self) -> &'static str { - "flexbox" - } - - fn allocate( - &self, - _ctx: &RagContext, - context_window: u32, - reserved: ReservedTokens, - sources: &[RagSourceBudget], - ) -> BudgetAllocation { - let available = reserved.headroom_within(context_window); - - if available == 0 { - let warnings = vec![format!( - "reserved tokens ({}) >= context window ({}); no budget for sources", - reserved.total(), - context_window - )]; - return empty_allocation(context_window, reserved, sources, warnings, true); - } - - let FlexAllocation { - allocations, - unallocated, - escalation_needed, - warnings, - } = flex_allocate(available, sources); - let mut total_allocated = 0u32; - for allocation in &allocations { - total_allocated = total_allocated.saturating_add(allocation.allocated_tokens); - // The allocator decided how much of her mind each source gets, and - // until now said NOTHING. So when a grounding block failed to - // appear, "the source abstained" and "the source was granted zero" - // were indistinguishable from outside — which is exactly the - // ambiguity that survived the #331 room fix: gate passing, board - // non-empty, block still absent, no way to tell why. - // - // Emitted per source per allocation: what it ASKED for and what it - // GOT. A source at allocated=0 (or below its own floor) is a - // faculty the persona cannot hear this turn, and that must be a - // readable fact, not an inference. [[observability-as-substrate]] - if allocation.allocated_tokens == 0 - || allocation.allocated_tokens < allocation.requested_floor - { - tracing::info!( - probe_class = "rag.budget.starved", - source = %allocation.source_id, - granted = allocation.allocated_tokens, - floor = allocation.requested_floor, - min = allocation.requested_min, - max = allocation.requested_max, - state = ?allocation.state, - context_window, - "source granted less than its own floor — this faculty is silent this turn" - ); - } - } - - BudgetAllocation { - context_window, - reserved, - available_for_sources: available, - allocations, - total_allocated, - unallocated, - escalation_needed, - warnings, - } - } + async fn deliver(&self, ctx: &RagContext) -> RagDelivery; } /// What [`flex_allocate`] decided: every claim's grant in INPUT order, the tokens no diff --git a/core/continuum-cognition/src/cognition/rag_budget/tests.rs b/core/continuum-cognition/src/cognition/rag_budget/tests.rs index 0abfa55f24..abc47f5ab5 100644 --- a/core/continuum-cognition/src/cognition/rag_budget/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_budget/tests.rs @@ -19,11 +19,12 @@ } } - fn reserved(system: u32, completion: u32) -> ReservedTokens { - ReservedTokens { system, completion } + /// The window less a fixed reservation: what the one allocation is handed. + fn reserved(system: u32, completion: u32) -> u32 { + system.saturating_add(completion) } - fn alloc_for<'a>(result: &'a BudgetAllocation, id: &str) -> &'a SourceAllocation { + fn alloc_for<'a>(result: &'a FlexAllocation, id: &str) -> &'a SourceAllocation { result .allocations .iter() @@ -31,23 +32,9 @@ .unwrap() } - fn ctx() -> RagContext { - RagContext::for_persona( - uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(), - 1_000_000, - ) - } - #[test] fn empty_context_window_under_provisions_required() { - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 500, - reserved(400, 200), - &[budget("conversation", 10, 100, 200, 1000, true)], - ); - assert_eq!(result.available_for_sources, 0); + let result = flex_allocate(500u32.saturating_sub(reserved(400, 200)), &[budget("conversation", 10, 100, 200, 1000, true)]); assert!(result.escalation_needed); assert_eq!( alloc_for(&result, "conversation").state, @@ -57,13 +44,7 @@ #[test] fn single_required_source_satisfied() { - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 10_000, - reserved(500, 2000), - &[budget("conversation", 10, 200, 500, 5000, true)], - ); + let result = flex_allocate(10_000u32.saturating_sub(reserved(500, 2000)), &[budget("conversation", 10, 200, 500, 5000, true)]); let conv = alloc_for(&result, "conversation"); assert!(conv.allocated_tokens >= 500); assert_eq!(conv.state, AllocationState::Satisfied); @@ -72,18 +53,12 @@ #[test] fn priority_distributes_remaining_proportionally() { - let adapter = FlexboxRagBudgetAdapter::new(); // max well above expected share so neither caps before the // priority ratio gets to express. - let result = adapter.allocate( - &ctx(), - 10_000, - reserved(0, 0), - &[ + let result = flex_allocate(10_000u32.saturating_sub(reserved(0, 0)), &[ budget("conversation", 10, 100, 500, 50_000, true), budget("memories", 5, 100, 500, 50_000, true), - ], - ); + ]); let conv = alloc_for(&result, "conversation"); let mem = alloc_for(&result, "memories"); // Both got their mins (500). Remaining 9000 distributed by @@ -98,16 +73,10 @@ #[test] fn optional_source_drops_when_floor_cant_fit() { - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 1_000, - reserved(500, 200), - &[ + let result = flex_allocate(1_000u32.saturating_sub(reserved(500, 200)), &[ budget("conversation", 10, 200, 200, 500, true), budget("artifacts", 3, 200, 200, 500, false), - ], - ); + ]); // Conversation required, gets its 200 floor. Remaining 100 < // artifacts floor 200, so artifacts is Dropped. let conv = alloc_for(&result, "conversation"); @@ -121,16 +90,10 @@ #[test] fn required_under_provisions_when_floor_cant_fit() { - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 300, - reserved(100, 100), - &[ + let result = flex_allocate(300u32.saturating_sub(reserved(100, 100)), &[ budget("conversation", 10, 200, 200, 500, true), budget("memories", 5, 200, 200, 500, true), - ], - ); + ]); // Available = 100; conv floor 200 takes it all; memories floor // 200 can't fit → UnderProvisioned + escalate. assert!(result.escalation_needed); @@ -145,16 +108,10 @@ // Joel's recent-universal floor doctrine: even if min is // squeezed, floor is unconditional. Here floor == min so the // test verifies the floor lands BEFORE the min pass. - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 2_000, - reserved(0, 0), - &[ + let result = flex_allocate(2_000u32.saturating_sub(reserved(0, 0)), &[ budget("conversation", 10, 500, 500, 1000, true), budget("memories", 5, 200, 600, 1500, false), - ], - ); + ]); let conv = alloc_for(&result, "conversation"); let mem = alloc_for(&result, "memories"); assert!(conv.allocated_tokens >= 500); @@ -163,16 +120,10 @@ #[test] fn max_caps_distribution() { - let adapter = FlexboxRagBudgetAdapter::new(); - let result = adapter.allocate( - &ctx(), - 10_000, - reserved(0, 0), - &[ + let result = flex_allocate(10_000u32.saturating_sub(reserved(0, 0)), &[ budget("tiny", 10, 0, 0, 100, false), budget("big", 5, 0, 0, 9_000, false), - ], - ); + ]); let tiny = alloc_for(&result, "tiny"); let big = alloc_for(&result, "big"); assert_eq!(tiny.allocated_tokens, 100); // capped @@ -185,25 +136,14 @@ fn deterministic_priority_tiebreak() { // Two sources at same priority must allocate identically across // runs. Use source_id alpha order. - let adapter = FlexboxRagBudgetAdapter::new(); - let result_a = adapter.allocate( - &ctx(), - 10_000, - reserved(0, 0), - &[ + let result_a = flex_allocate(10_000u32.saturating_sub(reserved(0, 0)), &[ budget("a", 5, 0, 500, 2000, false), budget("b", 5, 0, 500, 2000, false), - ], - ); - let result_b = adapter.allocate( - &ctx(), - 10_000, - reserved(0, 0), - &[ + ]); + let result_b = flex_allocate(10_000u32.saturating_sub(reserved(0, 0)), &[ budget("b", 5, 0, 500, 2000, false), budget("a", 5, 0, 500, 2000, false), - ], - ); + ]); let a_in_a = alloc_for(&result_a, "a").allocated_tokens; let a_in_b = alloc_for(&result_b, "a").allocated_tokens; assert_eq!(a_in_a, a_in_b, "allocation must be input-order-independent"); @@ -211,89 +151,21 @@ // ---- Source trait + stub tests ---- - fn item(text: &str, tokens: u32) -> RagItem { - RagItem { - content: text.to_string(), - tokens, - metadata: serde_json::json!({}), - } - } - fn persona() -> uuid::Uuid { uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap() } + // what this catches: a source sizing itself (FLOW plan §2d). The stub delivers every item + // it holds whatever is large, and refuses another persona's ctx with nothing. #[tokio::test] - async fn stub_source_delivers_what_fits() { - let source = StubRagSource::new( - "stub", - persona(), - vec![item("a", 10), item("b", 20), item("c", 100)], - ); - let delivery = source.deliver(&ctx(), 50, ResolutionPreference::Raw).await; - // a (10) + b (20) = 30 fits, c (100) doesn't. + async fn a_source_delivers_every_item_and_only_to_its_persona() { + let items = vec![RagItem::whole("a", "a", serde_json::json!({})), RagItem::whole("huge", "x".repeat(40_000), serde_json::json!({}))]; + let source = StubRagSource::new("stub", persona(), items); + let delivery = source.deliver(&RagContext::for_persona(persona(), 1_000_000)).await; assert_eq!(delivery.items.len(), 2); - assert_eq!(delivery.tokens_used, 30); - assert!(delivery.truncated); - } - - #[tokio::test] - async fn stub_source_truncation_flag_and_fresh_rederive() { - // Ruling a: no resumable handle — the flag says "more exists", - // and the next deliver re-derives from scratch, so a larger - // budget simply fits more. - let source = StubRagSource::new( - "stub", - persona(), - vec![item("a", 10), item("b", 10), item("c", 10), item("d", 10)], - ); - let first = source.deliver(&ctx(), 20, ResolutionPreference::Raw).await; - assert_eq!(first.items.len(), 2); - assert!(first.truncated, "two items left undelivered"); - - // Fresh re-derive with a budget that fits everything. - let second = source.deliver(&ctx(), 100, ResolutionPreference::Raw).await; - assert_eq!(second.items.len(), 4); - assert!(!second.truncated); - } - - #[tokio::test] - async fn stub_source_not_truncated_when_all_fit() { - let source = StubRagSource::new("stub", persona(), vec![item("a", 10)]); - let first = source.deliver(&ctx(), 100, ResolutionPreference::Raw).await; - assert_eq!(first.items.len(), 1); - assert!(!first.truncated, "everything fit — nothing omitted"); - } - - #[tokio::test] - async fn stub_source_never_partial_includes() { - // The no-clipping invariant: even with budget mid-item, the - // source skips the over-budget item rather than partial-include. - let source = StubRagSource::new("stub", persona(), vec![item("huge", 500)]); - let delivery = source.deliver(&ctx(), 100, ResolutionPreference::Raw).await; - assert_eq!(delivery.items.len(), 0); - assert_eq!(delivery.tokens_used, 0); - // Truncated set because the item still exists, just didn't - // fit at this budget. - assert!(delivery.truncated); - } - - - - #[tokio::test] - async fn stub_source_refuses_wrong_persona_ctx() { - // The defense-in-depth check: source bound to persona A, - // called with ctx for persona B — must return empty rather - // than serve B's caller with A's content. - let pax = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000abc").unwrap(); + assert!(!delivery.truncated); let maya = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000def").unwrap(); - let pax_source = StubRagSource::new("stub", pax, vec![item("a", 10)]); - let maya_ctx = RagContext::for_persona(maya, 1_000_000); - let delivery = pax_source - .deliver(&maya_ctx, 100, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 0); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); + assert!(source.deliver(&RagContext::for_persona(maya, 1_000_000)).await.items.is_empty()); } // what this catches (#338, measured live 2026-08-06): a source being dropped @@ -313,7 +185,6 @@ // sizes, every source still speaks. Floor is survival; min is appetite. #[test] fn sources_survive_at_their_first_unit_when_budget_wont_fit_their_appetite() { - let adapter = FlexboxRagBudgetAdapter::new(); // Real measured first units; 500 is the comfortable target each would // like. Total floors = 104, total appetites = 2000. let sources = [ @@ -324,15 +195,7 @@ ]; // 214 tokens — the live starved budget. Fits all four floors (104), // fits not even ONE comfortable size. - let alloc = adapter.allocate( - &RagContext::for_persona(uuid::Uuid::nil(), 0), - 214, - ReservedTokens { - system: 0, - completion: 0, - }, - &sources, - ); + let alloc = flex_allocate(214, &sources); for (i, s) in sources.iter().enumerate() { assert!( alloc.allocations[i].allocated_tokens >= s.floor_tokens, @@ -350,43 +213,6 @@ } } - /// What this catches: the window-scaled reservation stays ONE derivation - /// with the documented shape — a second hand-copied variant (the exact - /// duplication this replaced across unified.rs / rag_inspect.rs) shows up - /// as a drift here. Exhausted windows must not fabricate source capacity - /// (card 2bbee27a); construction and allocation share the same headroom. - #[test] - fn reserved_tokens_scaled_shape_is_the_one_derivation() { - // Compat-tier 2048: percentages, floors active. - let small = ReservedTokens::scaled_for_window(2048); - assert_eq!(small.system, 204); // 10%, inside [128, 512] - assert_eq!(small.completion, 512); // 25%, inside [256, 4_000] - assert_eq!(small.headroom_within(2048), 2048 - 204 - 512); - - // M-series 32k: both ceilings engage. - let big = ReservedTokens::scaled_for_window(32_768); - assert_eq!(big.system, 512); - assert_eq!(big.completion, 4_000); - assert_eq!(big.headroom_within(32_768), 32_768 - 4_512); - - // Reservations exhaust the window: report no capacity rather than 512 - // tokens that the lane cannot hold. - let tiny = ReservedTokens::scaled_for_window(256); - assert_eq!((tiny.system, tiny.completion), (128, 256)); - assert_eq!(tiny.headroom_within(256), 0); - for window in [0, 256, 384, 400, 512, 2_048, 51_712] { - let reserved = ReservedTokens::scaled_for_window(window); - let allocation = FlexboxRagBudgetAdapter::new().allocate( - &RagContext::for_persona(uuid::Uuid::nil(), 0), - window, - reserved, - &[], - ); - assert_eq!(reserved.headroom_within(window), allocation.available_for_sources); - assert!(allocation.available_for_sources <= window); - } - } - // what this catches: a lane need learned from the GRANT, which the flexbox grows to any // window, so the need tracked the window and refused every extra lane (the M5, 10-18). #[test] diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty.rs b/core/continuum-cognition/src/cognition/rag_source_faculty.rs index c4e4dbc6c8..5d06807afe 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty.rs @@ -56,20 +56,7 @@ use async_trait::async_trait; use uuid::Uuid; use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; -use crate::cognition::rag_budget::{RagContext, RagSource, ResolutionPreference}; - -/// Resolve a source offer through the same measured affordability owner as -/// recall, tools and working memory. The serving minimum is not permission to -/// exceed a caller's actual window. Explicit fixture budgets remain available -/// through `with_budget`; final assembly still owns total prompt fitting. -/// A zero window grants zero, rather than inventing serving capacity. The -/// constructor's legacy default passes the declared serving minimum explicitly; -/// production assembly passes its resolved model window. -pub fn grounding_budget_for(served_window: u32) -> u32 { - super::context_budget::ContextBudget::from_window(served_window) - .grounding_tokens() - .min(served_window as usize) as u32 -} +use crate::cognition::rag_budget::{RagContext, RagSource}; /// Salience floor for **standing framing** (roster, doctrine) — always-present /// structural context, like the system prompt. This ranks above retrieved @@ -140,7 +127,6 @@ pub struct RagSourceFaculty { stable: bool, /// Importance survives moving volatile grounding out of the system prefix. standing_grounding: bool, - budget: u32, clock: Clock, /// `true` when the assembler registered this grounding as /// [`Deferrability::ColdStartCritical`] — meaning its absence is a WRONG turn, @@ -200,10 +186,6 @@ impl RagSourceFaculty { // follows content stability. stable, standing_grounding: matches!(policy, SaliencePolicy::StandingFraming), - // Floor default (derived from the substrate serving floor, not a magic - // number). Production overrides via `with_budget(grounding_budget_for( - // cfg.context_window))` so the ceiling tracks the LIVE served window. - budget: grounding_budget_for(crate::inference::planning::MIN_SERVE_CTX), clock: wall_clock(), // Not cold-start-critical until the assembler says so. The safe // direction for a LOUDNESS contract is the opposite of the safe @@ -226,12 +208,6 @@ impl RagSourceFaculty { self } - /// Override the per-tick token budget handed to the source. - pub fn with_budget(mut self, budget: u32) -> Self { - self.budget = budget; - self - } - /// Framing whose content mutates per turn: demote OUT of the stable tier /// while keeping the StandingFraming salience floor (see `stable` field doc). pub fn with_volatile_content(mut self, volatile: bool) -> Self { @@ -373,10 +349,10 @@ impl Faculty for RagSourceFaculty { crate::cognition::rag_budget::RagRoomScope::Activity => ws.activity_room_id, }; let ctx = RagContext::for_persona_in_room(self.persona_id, now, room); - let delivery = self - .source - .deliver(&ctx, self.budget, ResolutionPreference::Raw) - .await; + // Every item the source holds, at its levels: her view's one allocation decides + // what of it she sees (FLOW-IMPLEMENTATION-PLAN §2d). Each faculty was handed a + // quarter of the window to cut to, seven of them about 7/4 of it. + let delivery = self.source.deliver(&ctx).await; // Empty delivery → abstain (the source had nothing, or degraded to empty // per the good-citizen doctrine). No empty bid clutters the workspace. An @@ -410,6 +386,7 @@ impl Faculty for RagSourceFaculty { let c = Contribution::context(self.faculty_id.clone(), content, self.salience, reasoning) .with_parts(units) + .with_units(delivery.items) .with_expand_command(self.source.expand_command()) // A continuation means the SOURCE stopped short of its own list; the // packer's notice must say so (card e049aa82: nothing resumes cursors). 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 e9fa66b50b..0aa0823870 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -1,6 +1,6 @@ #![cfg(test)] use super::*; - use crate::cognition::rag_budget::{ RagDelivery, RagItem, ResolutionPreference}; + use crate::cognition::rag_budget::{RagDelivery, RagItem}; use std::sync::Mutex; fn persona() -> Uuid { @@ -14,7 +14,6 @@ items: Vec, seen_persona: Mutex>, seen_room: Mutex>, - seen_budget: Mutex>, } impl StubSource { @@ -22,6 +21,9 @@ let items = contents .iter() .map(|c| RagItem { + key: String::new(), + summary: None, + pointer: None, content: c.to_string(), tokens: continuum_base::token_estimate::estimate_prompt_tokens(c), metadata: serde_json::json!({}), @@ -32,7 +34,6 @@ items, seen_persona: Mutex::new(None), seen_room: Mutex::new(None), - seen_budget: Mutex::new(None), } } } @@ -48,17 +49,8 @@ None } - /// Test/stub source — floorless, so it never encodes a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - *self.seen_budget.lock().unwrap() = Some(budget); + /// Test/stub source. + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { *self.seen_persona.lock().unwrap() = Some(ctx.persona_id); *self.seen_room.lock().unwrap() = ctx.airc_room.map(|room| room.as_uuid()); let tokens_used = self.items.iter().map(|i| i.tokens).sum(); @@ -67,7 +59,6 @@ items: self.items.clone(), tokens_used, truncated: false, - resolution_used: resolution, } } } @@ -538,13 +529,9 @@ // what this catches: the salience POLICY — standing framing (roster/doctrine) // bids HIGHER than retrieved grounding, so the floor exists. This is the - // ordering is a preference, not required placement. Card 2bbee27a also pins - // the production budget bridge at tiny/zero windows and explicit overrides. + // ordering is a preference, not required placement. #[tokio::test] async fn standing_framing_outbids_retrieved() { - assert_eq!(grounding_budget_for(0), 0); - let small = grounding_budget_for(256); - assert_eq!(small, 64, "a serving floor must not enlarge a known tiny window"); let framing_source = Arc::new(StubSource::new("room-doctrine", &["respond sparingly"])); let retrieved_source = Arc::new(StubSource::new("conversation", &["someone said hi"])); let framing = RagSourceFaculty::new( @@ -552,20 +539,16 @@ framing_source.clone(), SaliencePolicy::StandingFraming, ) - .with_budget(small) .with_clock(Arc::new(|| 1)); let retrieved = RagSourceFaculty::new( persona(), retrieved_source.clone(), SaliencePolicy::Retrieved, ) - .with_budget(small / 2) .with_clock(Arc::new(|| 1)); let f = framing.contribute(&Workspace::new("q")).await.unwrap(); let r = retrieved.contribute(&Workspace::new("q")).await.unwrap(); - assert_eq!(*framing_source.seen_budget.lock().unwrap(), Some(small)); - assert_eq!(*retrieved_source.seen_budget.lock().unwrap(), Some(small / 2)); assert!( f.salience > r.salience, "standing framing must out-bid retrieved (floor): framing={} retrieved={}", diff --git a/core/continuum-cognition/src/cognition/recall_faculty.rs b/core/continuum-cognition/src/cognition/recall_faculty.rs index e979aad692..a8fbba85e8 100644 --- a/core/continuum-cognition/src/cognition/recall_faculty.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty.rs @@ -48,9 +48,8 @@ use crate::cognition::admission_state::AdmissionState; use crate::cognition::engram::{Engram, EngramOrigin}; /// Hard safety ceiling on memories surfaced per tick, regardless of model size — -/// the [`RecallBudget`] picks the ACTUAL count (smaller) within this. `with_limit` -/// can lower it for tests/bench. Generous: the budget, not this, is the real -/// limiter on a live persona. +/// [`recall_count_for_window`] picks the ACTUAL count (smaller) within this. +/// `with_limit` can lower it for tests/bench. const DEFAULT_RECALL_LIMIT: usize = 16; /// How many consecutive turns the sticky recall rendering may hold its bytes @@ -88,46 +87,6 @@ fn recall_count_for_window(context_window: u32) -> usize { } } -/// The per-tick recall budget: how many memories may surface, the closest-match -/// floor below which a candidate is dropped as topically-irrelevant noise, and the -/// token ceiling recall may not exceed in the served window. Derived from the -/// model's served capability — a small model is not buried under memory it cannot -/// hold, and recall never eats the window. See [`recall_count_for_window`], -/// [`RECALL_RELEVANCE_FLOOR`], [`ContextBudget::recall_tokens`]. -struct RecallBudget { - max_count: usize, - token_ceiling: usize, -} - -impl RecallBudget { - fn for_window(context_window: u32) -> Self { - let token_ceiling = if context_window == 0 { - usize::MAX // window unknown → don't token-gate (count + floor still apply) - } else { - crate::cognition::context_budget::ContextBudget::from_window(context_window) - .recall_tokens() - .max(MIN_RECALL_TOKENS) - }; - Self { - max_count: recall_count_for_window(context_window), - token_ceiling, - } - } -} - -/// Floor on the recall token ceiling so even a tiny served window fits at least a -/// memory or two — below this, recall would be silently empty. -// context-budget-exempt: a FLOOR under the recall allocation — it only ever raises a budget, never caps one, so a big window is never clamped by it -const MIN_RECALL_TOKENS: usize = 256; - -/// Cheap token estimate for one surfaced memory: the body plus the `- …\n` list -/// framing (padded generously — the score annotation it once covered is no longer -/// model-visible), at the ~4-chars-per-token rule of thumb. Used only to keep -/// recall within its window budget — an estimate, not a tokenizer. -fn estimate_recall_tokens(content: &str) -> usize { - continuum_base::token_estimate::estimate_prompt_tokens(content) as usize + 6 -} - /// When relevance re-ranking is active, over-fetch this many × the surface limit /// as candidates, then narrow by relevance. Over-fetch so a topically-relevant /// but lower-salience memory can still enter the running and win the re-rank. @@ -240,7 +199,7 @@ pub struct RecallFaculty { /// the rent ledger attributed warm KV breaks to, with staleness bounded at /// [`RECALL_STICKY_TURNS`] turns and a new TOP memory always fresh. Tiny: /// N-rooms entries of a few KB each, per persona. - sticky: parking_lot::Mutex, String, u8)>>, + sticky: parking_lot::Mutex, String, std::sync::Arc<[crate::cognition::rag_budget::RagItem]>, u8)>>, } impl RecallFaculty { @@ -388,8 +347,10 @@ impl Faculty for RecallFaculty { // (context window). Computed BEFORE the fetch so the over-fetch covers the // budget's count, not a flat constant — a cloud-class window can surface // more than the historical 5, a tight 4B fewer. - let budget = RecallBudget::for_window(self.context_window); - let surface_count = budget.max_count.min(self.limit); + // How many memories, by the served model's capability (its cognitive load, measured); + // never how many tokens: her view's one allocation prices the block and picks its + // level (FLOW-IMPLEMENTATION-PLAN §2d), where a window share cut it before. + let surface_count = recall_count_for_window(self.context_window).min(self.limit); // Fetch candidates WITHOUT recording hits — we record the hit on what we // actually SURFACE (below), not on candidates that lose the re-rank. @@ -505,7 +466,6 @@ impl Faculty for RecallFaculty { // high-salience nag can rank above a genuinely relevant memory under the // blend, and we want to skip the nag and keep scanning for the relevant one. let mut surfaced: Vec<(f32, Engram, f32, f32)> = Vec::with_capacity(surface_count); - let mut used_tokens = 0usize; for (blended, engram, salience, passes_gate, attention_bid) in scored.into_iter() { if surfaced.len() >= surface_count { break; @@ -526,13 +486,6 @@ impl Faculty for RecallFaculty { { continue; } - let est = estimate_recall_tokens(&engram.content); - // Always admit the first qualifying memory (don't starve recall on a - // tiny window); after that, stop before the token ceiling is breached. - if !surfaced.is_empty() && used_tokens + est > budget.token_ceiling { - break; - } - used_tokens += est; surfaced.push((blended, engram, salience, attention_bid)); } @@ -690,7 +643,7 @@ impl Faculty for RecallFaculty { // tunable ("tune it as we go"). { let mut sticky = self.sticky.lock(); - if let Some((prev_ids, prev_content, remaining)) = sticky.get_mut(&ws.room_id) { + if let Some((prev_ids, prev_content, prev_units, remaining)) = sticky.get_mut(&ws.room_id) { let set_equal = *prev_ids == surfaced_ids; let top_already_cached = surfaced_ids .first() @@ -714,17 +667,25 @@ impl Faculty for RecallFaculty { top_salience, reasoning, ) + .with_units(prev_units.to_vec()) .trailing(), ); } } } let now_ms = (self.clock)(); - let lines = scored + let rendered: Vec<(&Engram, String)> = scored .iter() - .map(|(_, engram, _, _)| render_memory_line(engram, self.persona_id, now_ms)) - .collect::>() - .join("\n"); + .map(|(_, engram, _, _)| (engram, render_memory_line(engram, self.persona_id, now_ms))) + .collect(); + let lines = rendered.iter().map(|(_, line)| line.as_str()).collect::>().join("\n"); + // Each memory a unit at its levels, so her view can show the block at gists or + // handles when it cannot hold every memory whole; the frame stays whole. + let units: Vec = std::iter::once( + crate::cognition::rag_budget::RagItem::whole("frame", RECALL_MEMORY_FRAME, serde_json::Value::Null), + ) + .chain(rendered.iter().map(|(engram, line)| memory_unit(engram, line))) + .collect(); // Label the section AS memory, inline, so a transcript-trained model reads the // lines below as RECOLLECTION — "I remember/recall that …" — not as statements // about the present. Glass-boxed 2026-07-14 (Joel, "in prose/rag form engrams @@ -734,9 +695,10 @@ impl Faculty for RecallFaculty { // prefix per line already marks WHO/WHEN; this frames the whole block so the // pastness is unmissable. Not a directive about what to do — just what this IS. let content = format!("{RECALL_MEMORY_FRAME}\n{lines}"); + let units: std::sync::Arc<[crate::cognition::rag_budget::RagItem]> = units.into(); self.sticky.lock().insert( ws.room_id, - (surfaced_ids, content.clone(), RECALL_STICKY_TURNS), + (surfaced_ids, content.clone(), std::sync::Arc::clone(&units), RECALL_STICKY_TURNS), ); let reasoning = format!( "recalled {} memor{} ({}) — salience-uplifted, loop closed", @@ -751,6 +713,7 @@ impl Faculty for RecallFaculty { Some( Contribution::context(FacultyId::Recall, content, top_salience, reasoning) + .with_units(units.to_vec()) // TRAILING, not stable: recall is re-scored EVERY turn (salience × // recency, new engrams admitted between turns), so its block churns // mid-list — measured 2026-09-01 as the system prompt mutating at @@ -823,6 +786,18 @@ fn provenance_prefix(engram: &Engram, persona_id: Uuid, now_ms: u64) -> String { /// peer's first-person message verbatim as her own. Quote marks are the /// strongest structural signal a transcript-trained model has that words belong /// to someone else. +/// One memory as a unit: its rendered line whole, its first sentence when shorter, and a +/// handle she reopens through `cognition/recall`. +fn memory_unit(engram: &Engram, line: &str) -> crate::cognition::rag_budget::RagItem { + let id = engram.id.to_string(); + let unit = crate::cognition::rag_budget::RagItem::whole(id.clone(), line, serde_json::json!({ "engram_id": id })) + .with_pointer(format!("- [memory {} — cognition/recall]", airc_core::shown_id::shown_form(engram.id))); + match line.find(". ").map(|end| &line[..=end]) { + Some(gist) if gist.len() < line.len() => unit.with_summary(gist), + _ => unit, + } +} + fn render_memory_line(engram: &Engram, persona_id: Uuid, now_ms: u64) -> String { let prefix = provenance_prefix(engram, persona_id, now_ms); let heard = matches!( diff --git a/core/continuum-cognition/src/cognition/should_respond_module.rs b/core/continuum-cognition/src/cognition/should_respond_module.rs index 1aaaca56de..5047fd3bad 100644 --- a/core/continuum-cognition/src/cognition/should_respond_module.rs +++ b/core/continuum-cognition/src/cognition/should_respond_module.rs @@ -182,6 +182,7 @@ mod tests { defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }) .expect("test: resident checkpoint is readable"); registry diff --git a/core/continuum-cognition/src/cognition/tool_surface.rs b/core/continuum-cognition/src/cognition/tool_surface.rs index d33a6b2e70..0a8c4cab8a 100644 --- a/core/continuum-cognition/src/cognition/tool_surface.rs +++ b/core/continuum-cognition/src/cognition/tool_surface.rs @@ -18,10 +18,9 @@ //! //! # What decides it now //! -//! Two inputs, both of which change only where her prompt turns over anyway: -//! - the ACTIVITY: the verbs or subtrees (`code/**`) its recipe declares, else her hands; -//! - the SERVED window (a startup fact; a relaunch drops the KV regardless): whether her -//! extended hands fit its tool share, else her core hands. +//! The activity declares the desired verbs or subtrees (code/**), else her hands. +//! The shared prompt allocation grants a token budget; this owner selects a whole level. +//! The faculty retains that level for the epoch so subsequent acts keep stable schemas. //! //! The order is canonical (by command name), fixed at [`ToolSurface::build`]. Nothing here //! takes fewer abilities: the system prompt's menu lists every category, `commands/help` @@ -47,7 +46,7 @@ pub enum SurfaceReason { NoTools, /// Her hands: the working set of an activity that declares none (the ordinary room). Hands, - /// The served window's tool share cannot hold her extended hands (the web, push and + /// The shared allocation grant cannot hold her extended hands (the web, push and /// PR, rooms and chat, her focus verbs), so her core hands go out. The one arm that is a /// truncation, so the one whose demand exceeds what it sends. CoreHandsForWindow, @@ -90,6 +89,51 @@ pub struct ToolSurface { } impl ToolSurface { + /// Prices for the one allocation, independent of its eventual grant. Explicit + /// activity recipes are indivisible: silently replacing their verbs changes + /// what the activity can do. Ordinary hands have the core as their floor. + pub fn claim_tokens(&self, declared: &[String]) -> (usize, usize) { + match self.declared(declared) { + Some(offer) => (offer.tokens, offer.tokens), + None => (self.core.tokens, self.hands.tokens), + } + } + + /// Full activity surface plus the retained learned verbs, counted as a union. + /// No grant is an input: focus cannot teach the serving planner its own cap. + pub fn claim_with_head(&self, declared: &[String], held: &[String]) -> (usize, usize) { + let (floor, _) = self.claim_tokens(declared); + let recipe = self.declared(declared); + let base = recipe.as_ref().map_or(&self.hands.specs, |offer| &offer.specs); + let wanted: Vec<_> = self.names.iter().zip(&self.registry.specs) + .filter(|(name, spec)| held.contains(name) || base.iter().any(|b| b.name == spec.name)) + .map(|(_, spec)| spec.clone()).collect(); + (floor, tool_surface_tokens_of(&wanted)) + } + + /// Select a whole schema level from an allocation grant, never a window share. + /// `Err(floor)` reports capacity instead of emitting schemas beyond the grant. + /// The epoch owner retains this selection until the next epoch boundary. + pub fn select_granted(&self, declared: &[String], grant_tokens: usize) -> Result, usize> { + if self.registry.specs.is_empty() { + return Ok(SelectedSurface::borrowed(&[], 0, SurfaceReason::NoTools, 0)); + } + if let Some(offer) = self.declared(declared) { + let tokens = offer.tokens; + if tokens > grant_tokens { return Err(tokens); } + return Ok(SelectedSurface { + specs: Some(Cow::Owned(offer.specs)), tokens, + reason: SurfaceReason::RoomAffordances, demand: tokens, tail: Vec::new(), + }); + } + if self.core.tokens > grant_tokens { return Err(self.core.tokens); } + if self.hands.tokens <= grant_tokens { + Ok(SelectedSurface::borrowed(&self.hands.specs, self.hands.tokens, SurfaceReason::Hands, self.hands.tokens)) + } else { + Ok(SelectedSurface::borrowed(&self.core.specs, self.core.tokens, SurfaceReason::CoreHandsForWindow, self.hands.tokens)) + } + } + /// Build every surface from the native registry, sorted by command name so the bytes /// on the wire never depend on registration order, then renamed into the model's dialect. pub fn build(mut raw: Vec, to_wire: impl Fn(NativeToolSpec) -> NativeToolSpec) -> Self { @@ -128,34 +172,6 @@ impl ToolSurface { self.hands.tokens } - /// The surface for an activity that declares `declared` on a lane serving - /// `served_window` tokens. Nothing about the turn is an input, so two acts in the same - /// activity on the same lane offer the same bytes. - pub fn select(&self, declared: &[String], served_window: u32) -> SelectedSurface<'_> { - if self.registry.specs.is_empty() { - return SelectedSurface::borrowed(&[], 0, SurfaceReason::NoTools, 0); - } - if let Some(offer) = self.declared(declared) { - let tokens = offer.tokens; - return SelectedSurface { - specs: Some(Cow::Owned(offer.specs)), - tokens, - reason: SurfaceReason::RoomAffordances, - demand: tokens, - tail: Vec::new(), - }; - } - // The SERVED window, never the prefill-affordable one: the schemas sit in the cached - // prefix, so they are prefilled once per epoch, not once per act, and pricing them - // against this turn's measured rate is what made the surface move. - let share = super::context_budget::ContextBudget::from_window_unbounded(served_window).tool_surface_tokens(); - if self.hands.tokens <= share { - SelectedSurface::borrowed(&self.hands.specs, self.hands.tokens, SurfaceReason::Hands, self.hands.tokens) - } else { - SelectedSurface::borrowed(&self.core.specs, self.core.tokens, SurfaceReason::CoreHandsForWindow, self.hands.tokens) - } - } - /// Every native verb as the learned head chooses from it: its canonical name, its /// description, and what its schema costs on the wire. pub fn vocabulary(&self) -> Result { @@ -231,6 +247,7 @@ fn declares(pattern: &str, name: &str) -> bool { /// /// One decision, consulted by both the budget math and the request builder, so the two can /// never disagree about what is on the wire (card dec1a7ff). +#[derive(Debug, Clone)] pub struct SelectedSurface<'a> { /// Exactly what goes into the request. `None` only when there are no tools. Borrowed /// from the built surfaces, owned only when an activity's declaration selected it. @@ -258,6 +275,28 @@ impl<'a> SelectedSurface<'a> { self.demand } + /// The same selection, owning its schemas: what a prompt view carries to its request, so + /// the request sends exactly what the allocation bought (one decision, card dec1a7ff). + pub fn into_owned(self) -> SelectedSurface<'static> { + SelectedSurface { + specs: self.specs.map(|specs| Cow::Owned(specs.into_owned())), + tokens: self.tokens, + reason: self.reason, + demand: self.demand, + tail: self.tail, + } + } + + /// No surface: a turn refused for capacity before it could be offered one. + pub fn none() -> Self { + Self::borrowed(&[], 0, SurfaceReason::NoTools, 0) + } + + pub(crate) fn with_demand(mut self, demand: usize) -> Self { + self.demand = demand; + self + } + /// Charge the budget at least `reserve_tokens` for this surface: the next epoch's head, /// which a turnover in this act would adopt, is larger than this one. pub fn reserving(mut self, reserve_tokens: usize) -> Self { @@ -323,38 +362,44 @@ pub fn tool_surface_tokens_of(specs: &[NativeToolSpec]) -> usize { .sum() } -/// The prompt this lane affords (served window bounded by prefill t/s x TTFT), read beside -/// what the tool surface and framing cost. Emits `delib.tool_surface.over_affordable` when -/// they alone exceed it. Observation only: nothing here changes what is sent (card 3026b83e, -/// step 1). Returns the affordable token count for the turn's receipt. -pub(crate) fn over_affordable_receipt( - persona: &str, - surface_reason: SurfaceReason, - tool_tokens: usize, - framing_tokens: usize, - context_window: u32, -) -> Option { - let affordable_tokens = - super::context_budget::ContextBudget::from_window(context_window).affordable_tokens(); - if let Some(affordable) = affordable_tokens.filter(|a| framing_tokens + tool_tokens > *a) { - continuum_base::probe!( - class = "delib.tool_surface.over_affordable", - persona = %persona, - surface_reason = ?surface_reason, - tool_tokens, - framing_tokens, - affordable_tokens = affordable, - context_window, - "the tool surface and framing alone cost more than the prompt this lane can prefill inside its TTFT budget" - ); - } - affordable_tokens -} - #[cfg(test)] mod tests { use super::*; + #[test] + fn focus_grants_change_the_tool_level_without_changing_full_demand() { + let surface = built(REGISTRY.iter().copied()); + let (floor, want) = surface.claim_tokens(&[]); + assert!(floor > 0 && floor < want); + let focused = surface.select_granted(&[], want).expect("whole hands fit"); + let reduced = surface.select_granted(&[], floor).expect("core hands fit"); + assert_eq!(focused.demand_tokens(), want); + assert_eq!(reduced.demand_tokens(), want); + assert_eq!((focused.tokens, reduced.tokens), (want, floor)); + assert_eq!(surface.select_granted(&[], floor - 1).err(), Some(floor)); + let again = surface.select_granted(&[], want).expect("same grant fits"); + assert_eq!(serde_json::to_string(&focused.specs).expect("schemas"), + serde_json::to_string(&again.specs).expect("schemas"), "same epoch inputs keep prefix bytes"); + let declared = vec!["code/**".to_string()]; + let (floor, want) = surface.claim_tokens(&declared); + assert_eq!(floor, want, "an explicit recipe is indivisible"); + assert_eq!(surface.select_granted(&declared, floor - 1).err(), Some(floor)); + assert_eq!(surface.select_granted(&declared, want).expect("recipe fits").demand_tokens(), want); + } + + #[test] + fn learned_want_is_a_union_not_the_granted_head_size() { + let surface = built(REGISTRY.iter().copied()); + let (floor, want) = surface.claim_with_head(&[], &[]); + assert_eq!(surface.claim_with_head(&[], &["code/read".into()]), (floor, want)); + let held = vec!["activity/archive".into()]; + let (_, extended) = surface.claim_with_head(&[], &held); + assert_eq!(extended, want + tool_surface_tokens_of(&[spec("activity/archive")])); + assert_eq!(surface.claim_with_head(&[], &[held[0].clone(), held[0].clone()]), (floor, extended)); + let selected = surface.select_granted(&[], floor).expect("core fits").with_demand(extended); + assert_eq!((selected.tokens, selected.demand_tokens()), (floor, extended)); + } + fn spec(name: &str) -> NativeToolSpec { NativeToolSpec { name: name.to_string(), @@ -385,14 +430,14 @@ mod tests { // must depend on the activity and the served window alone, in one canonical order: the // same inputs give the same schemas whatever order the registry was assembled in. #[test] - fn the_same_activity_and_window_give_the_same_bytes_in_canonical_order() { + fn the_same_activity_and_grant_give_the_same_bytes_in_canonical_order() { let forward = built(REGISTRY.iter().copied()); let backward = built(REGISTRY.iter().rev().copied()); for declared in [Vec::new(), vec!["code/**".to_string()]] { - for window in [0, 8_192, 87_296] { - let (a, b) = (forward.select(&declared, window), backward.select(&declared, window)); + for window in [forward.claim_tokens(&declared).0, forward.claim_tokens(&declared).1] { + let (a, b) = (forward.select_granted(&declared, window).expect("grant fits"), backward.select_granted(&declared, window).expect("grant fits")); assert_eq!((a.reason, wire(&a)), (b.reason, wire(&b)), "declared {declared:?}, window {window}"); - assert_eq!(wire(&a), wire(&forward.select(&declared, window)), "a second act is identical"); + assert_eq!(wire(&a), wire(&forward.select_granted(&declared, window).expect("grant fits")), "a second act is identical"); } } let names: Vec<&str> = forward.hands().iter().map(|s| s.name.as_str()).collect(); @@ -408,31 +453,31 @@ mod tests { #[test] fn a_declared_subtree_selects_that_subtree_with_her_discovery_and_focus_verbs() { let surface = built(REGISTRY.iter().copied()); - let selected = surface.select(&["code/**".to_string()], 87_296); + let selected = surface.select_granted(&["code/**".to_string()], 87_296).expect("recipe fits"); assert_eq!(selected.reason, SurfaceReason::RoomAffordances); let names: Vec<&str> = selected.specs.as_deref().into_iter().flatten().map(|s| s.name.as_str()).collect(); assert_eq!( names, ["code/edit", "code/git/apply", "code/read", "commands/help", "commands/list", "focus/continue"] ); - let unmatched = surface.select(&["mail/send".to_string()], 87_296); + let unmatched = surface.select_granted(&["mail/send".to_string()], 87_296).expect("hands fit"); assert_eq!(unmatched.reason, SurfaceReason::Hands, "a rule binding nothing offers her hands, never nothing"); } // what this catches: a window too small for her extended hands sending nothing, or // reporting the core it sent as all she wanted (the demand probe would hide the pressure). #[test] - fn a_window_too_small_for_her_extended_hands_sends_her_core_and_demands_the_whole() { + fn a_small_grant_sends_core_hands_and_demands_the_whole() { let surface = built(REGISTRY.iter().copied()); - let roomy = surface.select(&[], 87_296); + let roomy = surface.select_granted(&[], surface.hands_tokens()).expect("hands fit"); assert_eq!((roomy.reason, roomy.demand_tokens()), (SurfaceReason::Hands, roomy.tokens)); - let tight = surface.select(&[], 512); + let tight = surface.select_granted(&[], surface.claim_tokens(&[]).0).expect("core fits"); assert_eq!(tight.reason, SurfaceReason::CoreHandsForWindow); assert_eq!(tight.demand_tokens(), surface.hands_tokens()); assert!(tight.tokens < tight.demand_tokens()); let names: Vec<&str> = tight.specs.as_deref().into_iter().flatten().map(|s| s.name.as_str()).collect(); assert!(names.contains(&"commands/list") && !names.contains(&"web/fetch"), "{names:?}"); - assert_eq!(surface.select(&[], 0).reason, SurfaceReason::Hands, "an unknown window is never an invented one"); + assert_eq!(surface.select_granted(&[], 0).err(), Some(surface.claim_tokens(&[]).0), "zero grant cannot buy core hands"); } // what this catches: the learned head sending verbs out of canonical order (two acts in one diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f378e933cf..20fbbe6427 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -497,7 +497,7 @@ fn result_summary(result: &str, acts: &[Observation], budget: &crate::cognition: many => { // Each part is the act as the receipt shows it (its header over its humanized body), // at its own level: the same seam the single-act branch reads through `result`. - let parts: String = many.iter().map(|act| act.render_summary_part(budget, |body| level(body, Some(act)))).collect(); + let parts: String = many.iter().map(|act| act.render_summary_part(|body| level(body, Some(act)))).collect(); (parts.chars().count() * LEVEL_RATIO <= result.chars().count()).then_some(parts) } } 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 3e407b7b37..c8c475bba7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -382,7 +382,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("", &wm.budget())).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()) diff --git a/core/continuum-cognition/src/cognition/workspace/edit.rs b/core/continuum-cognition/src/cognition/workspace/edit.rs index 49e895dcac..ea2990c3eb 100644 --- a/core/continuum-cognition/src/cognition/workspace/edit.rs +++ b/core/continuum-cognition/src/cognition/workspace/edit.rs @@ -374,6 +374,11 @@ pub struct Contribution { /// because the source did not report one ("whole or handle": a cut the reader /// cannot see is a silent clip, PERSONA-COGNITION-PIPELINE.md §3). pub source_truncated: bool, + /// The source's own items, each with its stable key and levels (whole, summary, + /// pointer), when it delivered some: her view prices and collapses them one by one + /// (`context_streams::blocks`), so the one allocation chooses per card, per post, per + /// member instead of whole-block-or-minimum. Shared, never copied per reader. + pub units: std::sync::Arc<[crate::cognition::rag_budget::RagItem]>, } impl Contribution { @@ -395,6 +400,7 @@ impl Contribution { parts: vec![content.clone()], expand_command: None, source_truncated: false, + units: std::sync::Arc::from(Vec::new()), content, salience: salience.clamp(0.0, 1.0), reasoning: reasoning.into(), @@ -420,6 +426,12 @@ impl Contribution { /// the assembly path never has to special-case "divisible but with nothing /// to divide". `content` is left untouched — it remains the whole, and is /// what renders whenever the whole fits. + /// The source's keyed, levelled items (see [`Contribution::units`]). + pub fn with_units(mut self, units: Vec) -> Self { + self.units = units.into(); + self + } + pub fn with_parts(mut self, parts: Vec) -> Self { if !parts.is_empty() { self.parts = parts; @@ -462,6 +474,7 @@ impl Contribution { parts: vec![content.clone()], expand_command: None, source_truncated: false, + units: std::sync::Arc::from(Vec::new()), content, salience: salience.clamp(0.0, 1.0), reasoning: reasoning.into(), @@ -511,6 +524,7 @@ impl Contribution { parts: vec![error.clone()], expand_command: None, source_truncated: false, + units: std::sync::Arc::from(Vec::new()), content: error.clone(), salience: 1.0, reasoning: "deliberation inference failed".to_string(), @@ -614,9 +628,27 @@ pub struct BurstTurn { pub occurred_at_ms: Option, /// Speech, or something the system told her. See [`TurnVoice`]. pub voice: TurnVoice, + /// The airc event this turn is, when it came from a room: what keys it in her view and + /// what her read receipt advances to once a sent prompt rendered it. `None` for opaque, + /// eval and perception turns. + pub source: Option, +} + +/// The room event a turn came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TurnSource { + pub room: uuid::Uuid, + pub event: uuid::Uuid, + pub lamport: u64, } impl BurstTurn { + /// This turn is the room event `source`. + pub fn from_event(mut self, source: TurnSource) -> Self { + self.source = Some(source); + self + } + /// An attributed turn — the live/eval path that knows WHO spoke and WHEN. pub fn attributed( is_self: bool, @@ -630,6 +662,7 @@ impl BurstTurn { content: content.into(), occurred_at_ms, voice: TurnVoice::Speech, + source: None, } } @@ -646,6 +679,7 @@ impl BurstTurn { content: content.into(), occurred_at_ms: None, voice: TurnVoice::Speech, + source: None, } } @@ -659,6 +693,7 @@ impl BurstTurn { pub fn perception(content: impl Into) -> Self { Self { voice: TurnVoice::Perception, + source: None, ..Self::opaque(content) } } diff --git a/core/continuum-cognition/src/cognition/workspace_capture.rs b/core/continuum-cognition/src/cognition/workspace_capture.rs index f4678b65a5..7b80f70ad9 100644 --- a/core/continuum-cognition/src/cognition/workspace_capture.rs +++ b/core/continuum-cognition/src/cognition/workspace_capture.rs @@ -262,6 +262,7 @@ mod tests { parts: Vec::new(), expand_command: None, source_truncated: false, + units: std::sync::Arc::from(Vec::new()), }; let verdict = Contribution { faculty: FacultyId::Deliberation, @@ -285,6 +286,7 @@ mod tests { parts: Vec::new(), expand_command: None, source_truncated: false, + units: std::sync::Arc::from(Vec::new()), }; let trace = WorkspaceTrace { cycle: crate::cognition::workspace::CycleId::UNSTAMPED, diff --git a/core/continuum-context/examples/replay.rs b/core/continuum-context/examples/replay.rs index 647ca04f78..5d9659fe68 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -121,7 +121,7 @@ impl Source for Captured { fn item(key: String, text: String) -> Item { let pointer: String = text.lines().next().unwrap_or_default().chars().take(185).collect(); let pointer = if pointer.len() < text.len() { pointer } else { text.clone() }; - Item { key, pointer: Some(pointer), summary: None, full: text } + Item { stored: None, key, pointer: Some(pointer), summary: None, full: text } } /// The one allocation, modelled: every source gets its floor, then the rest of `budget` diff --git a/core/continuum-context/examples/replay/append.rs b/core/continuum-context/examples/replay/append.rs index 96402db41d..e61981f004 100644 --- a/core/continuum-context/examples/replay/append.rs +++ b/core/continuum-context/examples/replay/append.rs @@ -254,10 +254,10 @@ pub fn replay(label: &str, cuts: &[Cut], window: usize, share: usize, (chars_per } None => shown.answered().to_owned(), }; - looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full }); + looped.push(Item { stored: None, key: looped.len().to_string(), pointer: None, summary: None, full }); } for full in extra_pages { - looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full }); + looped.push(Item { stored: None, key: looped.len().to_string(), pointer: None, summary: None, full }); } previous_sent = Some(&cut.sent); previous_rendered = Some(rendered); diff --git a/core/continuum-context/examples/replay/sediment.rs b/core/continuum-context/examples/replay/sediment.rs index 0efd072696..5858693dd0 100644 --- a/core/continuum-context/examples/replay/sediment.rs +++ b/core/continuum-context/examples/replay/sediment.rs @@ -171,7 +171,7 @@ mod tests { let items = sizes .iter() .enumerate() - .map(|(n, size)| Item { key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")) }) + .map(|(n, size)| Item { stored: None, key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")) }) .collect(); Captured { name: name.to_owned(), items } } diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index 78d704f353..fa5c90f157 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -23,6 +23,29 @@ pub struct Item { /// item leaves the view entirely once collapsed (a conversation turn whose room history /// holds it, where a one-line pointer would cost about what the turn does). pub pointer: Option, + /// The whole is stored, not resident: `full` then holds what is in memory (its pointer or + /// summary) and the view prices the whole level from `stored.chars` without reading it. + /// Only an item the allocation grants WHOLE is loaded, once per render, through the + /// render's loader. Residency is not visibility: evicting a body from RAM never changes + /// what she can see (Cormac's proposal, FLOW plan §2d; the RAM storage budget is by bytes, + /// from governed RAM, never from the window). + pub stored: Option, +} + +/// Where a non-resident whole lives and what it costs, measured when it was stored. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredWhole { + /// The whole's exact size in chars, known at spill time: the allocation's price for it. + pub chars: usize, + /// The handle the render's loader opens (a spill path, a result id). + pub handle: String, +} + +impl Item { + /// An item that is resident whole, with no coarser levels yet. + pub fn whole(key: impl Into, full: T) -> Self { + Self { key: key.into(), full, summary: None, pointer: None, stored: None } + } } /// A source of a mind's context. @@ -52,4 +75,23 @@ pub trait Source { fn retired(&self) -> Vec> { Vec::new() } + + /// Load the whole of one of this source's stored items (its `stored` handle), called only + /// for an item the allocation granted WHOLE. The default stores nothing; a source that + /// spills bodies (her results) overrides it. `None` renders what is resident. + fn load(&self, _item: &Item) -> Option { + None + } +} + +/// What an item's whole level costs: its stored size when the whole is not resident, else +/// the resident text's size. The allocation prices from this and never reads a stored body. +pub fn whole_chars(item: &Item) -> usize { + item.stored.as_ref().map_or_else(|| item.full.chars(), |stored| stored.chars) // map_or_else: a resident item is priced by its own text +} + +/// The item at its whole level: a stored body loaded through its source, else what is resident. +pub fn whole(source: &(impl Source + ?Sized), item: Item) -> T { + let loaded = item.stored.as_ref().and_then(|_| source.load(&item)); + loaded.unwrap_or(item.full) // unwrap_or: an unloadable body renders its resident level (pointer or summary), never nothing } diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index 44b97961f1..aefb6ddb9b 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -116,7 +116,7 @@ fn levels(items: &[Item], grant: usize) -> Vec { let mut levels = vec![Level::Pointer; items.len()]; let mut ceiling = Level::Full; for (item, level) in items.iter().zip(levels.iter_mut()).rev() { - let full = item.full.chars().saturating_sub(pointer_chars(item)); + let full = crate::source::whole_chars(item).saturating_sub(pointer_chars(item)); let summary = item.summary.as_ref().map(|s| s.chars().saturating_sub(pointer_chars(item))); if ceiling == Level::Full && full <= spare { spare -= full; @@ -153,7 +153,7 @@ fn claim(source: &dyn Source, items: &[Item]) -> Claim { source: source.name().to_owned(), priority: source.priority(), pointer_chars: items.iter().map(pointer_chars).sum(), - full_chars: items.iter().map(|item| item.full.chars()).sum(), + full_chars: items.iter().map(crate::source::whole_chars).sum(), } } @@ -223,8 +223,9 @@ impl View { let mut rendered = Vec::with_capacity(items.len()); for (item, level) in items.into_iter().zip(levels) { let id = key(source.name(), &item.key); + let item_key = item.key.clone(); // its fingerprint after the level consumed it; once per item per start let text = match level { - Level::Full => Some(item.full), + Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => { view.summarized.insert(id.clone()); item.summary @@ -235,7 +236,7 @@ impl View { } }; if let Some(text) = text { - rendered.push((fingerprint(&item.key, &text), text.chars())); + rendered.push((fingerprint(&item_key, &text), text.chars())); view.epoch.observe(id, text); } } @@ -249,6 +250,14 @@ impl View { /// Append what changed in each source since the last act, each item at the rendering its /// epoch start chose. An item first seen mid-epoch arrives in full: the allocator weighs /// it at the next start. + /// Whether her view shows `source`'s item `item` this epoch, whole or as its summary. A + /// collapsed item renders at most its pointer, which is not reading it: the read receipt + /// (her room cursor) only advances through what this answers true for. + pub fn renders(&self, source: &str, item: &str) -> bool { + let id = key(source, item); + self.epoch.holds(&id) && !self.collapsed.contains(&id) + } + pub fn advance(&mut self, sources: &[&dyn Source]) -> Advance { self.act = Some(self.epoch.mark()); self.append(sources, None) @@ -291,12 +300,12 @@ impl View { // new turn), so it always arrives whole: admission never drops what she has // not seen. let fits = |chars: usize| limit.map_or(true, |(limit, _)| self.epoch.chars() + chars <= limit); // map_or: no limit admits every arrival whole - let oversized = limit.is_some_and(|(_, oversized)| item.full.chars() > oversized); + let oversized = limit.is_some_and(|(_, oversized)| crate::source::whole_chars(&item) > oversized); let level = if self.collapsed.contains(&id) { Level::Pointer } else if self.summarized.contains(&id) { Level::Summary - } else if self.epoch.holds(&id) || item.pointer.is_none() || !oversized || fits(item.full.chars()) { + } else if self.epoch.holds(&id) || item.pointer.is_none() || !oversized || fits(crate::source::whole_chars(&item)) { Level::Full } else if item.summary.as_ref().is_some_and(|summary| fits(summary.chars())) { self.summarized.insert(id.clone()); @@ -306,7 +315,7 @@ impl View { Level::Pointer }; let text = match level { - Level::Full => Some(item.full), + Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => item.summary.or(item.pointer), Level::Pointer => item.pointer, }; diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 83ab568f44..5396773c03 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -32,6 +32,7 @@ impl Source for Fake { self.items .iter() .map(|(key, text)| Item { + stored: None, key: key.clone(), full: text.clone(), summary: None, @@ -42,7 +43,7 @@ impl Source for Fake { fn retired(&self) -> Vec> { self.retired .iter() - .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(text.clone()) }) + .map(|(key, text)| Item { stored: None, key: key.clone(), full: text.clone(), summary: None, pointer: Some(text.clone()) }) .collect() } } @@ -179,7 +180,7 @@ fn an_item_without_a_pointer_leaves_the_view_when_collapsed() { 1 } fn items(&self) -> Vec> { - self.0.iter().map(|t| Item { key: (*t).to_owned(), full: (*t).to_owned(), summary: None, pointer: None }).collect() + self.0.iter().map(|t| Item { stored: None, key: (*t).to_owned(), full: (*t).to_owned(), summary: None, pointer: None }).collect() } } let mut turns = Turns(vec!["one", "two", "three"]); @@ -244,6 +245,7 @@ impl Source for Leveled { self.0 .iter() .map(|(key, full, summary)| Item { + stored: None, key: (*key).to_owned(), full: full.clone(), summary: summary.clone(), @@ -325,3 +327,76 @@ fn a_short_item_without_a_summary_stays_whole_under_a_summary_ceiling() -> Resul assert_eq!((start.collapsed, start.summarized), (0, 2)); Ok(()) } + +// what this catches: a read receipt naming a turn she never saw. `renders` answers true only +// for an item her view shows whole (or summarized) this epoch, never for one collapsed to its +// pointer or one the view never held. +#[test] +fn renders_is_true_only_for_what_her_view_shows() -> Result<(), GrantMismatch> { + let mut actions = Fake::new("actions", 1); + actions.push("#1", &"x".repeat(9_000)); + actions.push("#2", "short"); + let pointer = |item: &Item| item.pointer.as_ref().map_or(0, String::len); + let floor: usize = actions.items().iter().map(pointer).sum(); + let (view, _) = View::start(vec![], &[&actions], |_| vec![floor + 10])?; + assert!(!view.renders("actions", "#1"), "collapsed to its pointer: not read"); + assert!(view.renders("actions", "#2"), "whole: read"); + assert!(!view.renders("actions", "#3"), "never held"); + assert!(!view.renders("conversation", "#2"), "another source's key"); + Ok(()) +} + +/// A source whose bodies are spilled: resident as their pointer, whole on disk. +struct Spilled { + bodies: Vec<(String, String)>, + loads: std::cell::Cell, +} + +impl Source for Spilled { + fn name(&self) -> &str { + "results" + } + fn priority(&self) -> u8 { + 1 + } + fn items(&self) -> Vec> { + self.bodies + .iter() + .map(|(key, body)| { + let pointer = format!("[{key}: {} chars stored]", body.len()); + Item { + stored: Some(crate::source::StoredWhole { chars: body.len(), handle: key.clone() }), + key: key.clone(), + full: pointer.clone(), + summary: None, + pointer: Some(pointer), + } + }) + .collect() + } + fn load(&self, item: &Item) -> Option { + self.loads.set(self.loads.get() + 1); + let handle = &item.stored.as_ref()?.handle; + self.bodies.iter().find(|(key, _)| key == handle).map(|(_, body)| body.clone()) + } +} + +// what this catches: residency changing visibility. A stored whole is priced from its measured +// size without a read, and only the item the allocation grants WHOLE is loaded; the one it +// collapses is never read off disk. +#[test] +fn a_stored_whole_is_priced_without_a_read_and_loaded_only_when_granted() -> Result<(), GrantMismatch> { + let spilled = Spilled { + bodies: vec![("#1".into(), "a".repeat(5_000)), ("#2".into(), "b".repeat(800))], + loads: std::cell::Cell::new(0), + }; + let claim = claims(&[&spilled as &dyn Source]); + assert_eq!(claim[0].full_chars, 5_800, "priced from the stored sizes"); + assert_eq!(spilled.loads.get(), 0, "pricing reads nothing"); + let floor = claim[0].pointer_chars; + let (view, _) = View::start(vec![], &[&spilled], |_| vec![floor + 1_000])?; + assert_eq!(spilled.loads.get(), 1, "only the granted whole was loaded"); + assert!(rendered(&view).contains(&"b".repeat(800)), "the newest, granted whole, renders its body"); + assert!(!view.renders("results", "#1") && view.renders("results", "#2")); + Ok(()) +} diff --git a/core/continuum-core/src/commands/tool/output.rs b/core/continuum-core/src/commands/tool/output.rs index c14f20370d..ddd803db6a 100644 --- a/core/continuum-core/src/commands/tool/output.rs +++ b/core/continuum-core/src/commands/tool/output.rs @@ -18,17 +18,17 @@ use crate::cognition::tool_executor::spill; use crate::sdk_codegen::{ActionCommand, CommandError, Ctx}; /// Default context lines around each grep match (like `grep -C2`). -// context-budget-exempt: grep-style -C lines around a match — a display shape; the rendered slice's total size is window-derived (render_slice_chars) +// context-budget-exempt: grep-style -C lines around a match; transport bounds the page, the view bounds perception. const DEFAULT_CONTEXT_LINES: usize = 2; /// Default cap on grep match windows — enough to see the failures, bounded so a /// pattern that matches everything can't re-flood. const DEFAULT_MAX_MATCHES: usize = 50; -// Char budget for the rendered slice — a fraction of the caller's LIVE served window -// (`ContextBudget::render_slice_chars`), kept below the result-fold bound so a normal -// investigation isn't itself re-spilled. Never a constant: the old `RENDER_BUDGET_CHARS = -// 12_000` clipped a 1M-context mind to the same slice as a 16k one. -// [[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]] -use crate::cognition::context_budget::ContextBudget; +/// Maximum encoded body of one saved-output transport page, independent of model context. +/// A provisional 64 KiB I/O bound, not a measured optimum or a perception allowance. +/// The result enters the ordinary action source; only the shared view chooses its level. +/// nextByteOffset keeps every remaining byte reachable. Full response-lifetime RAM custody +/// belongs to the resource daemon and is separate from this per-read bound. +const OUTPUT_TRANSPORT_PAGE_BYTES: usize = 64 * 1024; /// Prebuilt failure-hunting filters, so a persona navigates a flood WITHOUT having to /// know regex — the PX "hit the ground running" affordance for the overwhelming case @@ -119,7 +119,7 @@ pub struct ToolOutputParams { #[ts(optional)] #[ts(type = "number")] pub byte_offset: Option, - /// Requested byte count; a page fits the live render allowance. No bytes are + /// Requested byte count; each encoded transport page is at most 64 KiB. No bytes are /// discarded when this request spans multiple pages: nextByteOffset continues it. #[ts(optional)] #[ts(type = "number")] @@ -231,7 +231,7 @@ impl ActionCommand for ToolOutput { (None, None) => None, }; - let budget = ContextBudget::live().render_slice_chars(); + let budget = OUTPUT_TRANSPORT_PAGE_BYTES; if params.byte_length.is_some() && params.byte_offset.is_none() { return Err(CommandError::Invalid( "byteLength requires byteOffset".into(), @@ -310,6 +310,49 @@ fn read_saved( mod tests { use super::*; + // A transport boundary may split UTF-8, but never discard a byte. This fixture + // spans several production-sized pages and reconstructs the exact saved body. + #[test] + fn transport_pages_reconstruct_the_whole_saved_output() { + use base64::Engine as _; + let dir = tempfile::tempdir().expect("temporary output directory"); + let path = dir.path().join("saved.txt"); + let body = "a🦀é\n".repeat(OUTPUT_TRANSPORT_PAGE_BYTES); + std::fs::write(&path, &body).expect("saved output"); + let mut offset = 0; + let mut actual = Vec::new(); + let mut pages = 0; + loop { + let result = read_saved( + &path, + ToolOutputParams { + handle: "fixture".into(), + byte_offset: Some(offset), + ..Default::default() + }, + None, + OUTPUT_TRANSPORT_PAGE_BYTES, + ).expect("bounded transport page"); + assert!(result.content.len() <= OUTPUT_TRANSPORT_PAGE_BYTES); + actual.extend(if result.encoding == "base64" { + base64::engine::general_purpose::STANDARD.decode(result.content) + .expect("lossless encoded bytes") + } else { + result.content.into_bytes() + }); + pages += 1; + match result.next_byte_offset { + Some(next) => { + assert!(next > offset); + offset = next; + } + None => break, + } + } + assert!(pages > 1); + assert_eq!(actual, body.as_bytes()); + } + // what this catches: name mirrors path so the persona reaches it by the name // she'd guess from the elision marker. #[test] diff --git a/core/continuum-core/src/ipc/prepare_unix_socket_path.rs b/core/continuum-core/src/ipc/prepare_unix_socket_path.rs index 07dac5c4da..02ba6fcc2d 100644 --- a/core/continuum-core/src/ipc/prepare_unix_socket_path.rs +++ b/core/continuum-core/src/ipc/prepare_unix_socket_path.rs @@ -582,8 +582,3 @@ pub(super) fn handle_client( log_debug!("ipc", "server", "Client disconnected: {}", peer_addr); Ok(()) } - -// ============================================================================ -// Server Main Loop -// ============================================================================ -use crate::runtime::ipc_ready::ipc_ready_tx; diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 002fe42cde..5aed0ece2c 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -364,6 +364,7 @@ mod tests { defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }) .expect("test: resident checkpoint is readable"); registry diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/budget.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/budget.rs index 6c589c2fd2..4499383ea3 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/budget.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/budget.rs @@ -6,19 +6,13 @@ use super::*; -/// The smallest 1 KiB-aligned window whose tool share ADMITS her whole hands, and the -/// largest that does not. -/// -/// ASKED of [`ContextBudget`], never re-derived from its denominator: a window constant -/// here would not scale with the share it straddles, and spelling `/ 4` would duplicate -/// `TOOL_SURFACE_DENOM`. The share is the SERVED window's (`from_window_unbounded`): the -/// schemas sit in the cached prefix, so the surface never follows a turn's prefill rate. +/// The first aligned window whose shared allocation admits whole hands, and its predecessor. fn calibrated_windows() -> (u32, u32) { let hands = faculty_with_the_real_registry(1024).tool_surface().hands_tokens(); let admits = (1..=512) .map(|k| k * 1024) .find(|w| { - crate::cognition::context_budget::ContextBudget::from_window_unbounded(*w).tool_surface_tokens() >= hands + faculty_with_the_real_registry(*w).prompt_view(&work_turn()).tools.tokens >= hands }) .expect("some served window admits her hands"); (admits, admits - 1024) @@ -51,7 +45,7 @@ fn a_turn_is_budgeted_for_her_hands_not_for_the_registry() { let (fits, _narrow) = calibrated_windows(); let faculty = faculty_with_the_real_registry(fits); for ws in [work_turn(), Workspace::new("anything open?")] { - let selected = faculty.select_tool_surface(&ws); + let selected = faculty.prompt_view(&ws).tools; assert_eq!(selected.reason, SurfaceReason::Hands); assert_eq!(selected.tokens, faculty.tool_surface().hands_tokens(), "charged for what goes on the wire"); assert!( @@ -72,7 +66,9 @@ fn a_turn_is_budgeted_for_her_hands_not_for_the_registry() { fn a_window_withheld_surface_still_reports_her_whole_hands_as_demand() { let (_fits, narrow) = calibrated_windows(); let faculty = faculty_with_the_real_registry(narrow); - let selected = faculty.select_tool_surface(&Workspace::new("anything open?")); + // Keep the same claims used to calibrate this boundary. An ambient turn has + // different conversation demand and can still afford full hands here. + let selected = faculty.prompt_view(&work_turn()).tools; assert_eq!(selected.reason, SurfaceReason::CoreHandsForWindow, "this window's share cannot hold her hands"); assert!(selected.tokens < faculty.tool_surface().hands_tokens(), "she is SENT her core hands"); assert_eq!( @@ -88,7 +84,7 @@ fn a_window_withheld_surface_still_reports_her_whole_hands_as_demand() { fn an_untruncated_surface_does_not_inflate_demand() { let (fits, _narrow) = calibrated_windows(); let faculty = faculty_with_the_real_registry(fits); - let selected = faculty.select_tool_surface(&work_turn()); + let selected = faculty.prompt_view(&work_turn()).tools; assert_eq!(selected.demand_tokens(), selected.tokens); } @@ -100,7 +96,7 @@ fn the_cost_reported_is_always_the_cost_of_the_surface_reported() { let (fits, narrow) = calibrated_windows(); for (label, window) in [("hands", fits), ("core/window", narrow)] { let faculty = faculty_with_the_real_registry(window); - let selected = faculty.select_tool_surface(&work_turn()); + let selected = faculty.prompt_view(&work_turn()).tools; let specs = selected.specs.as_deref().expect("a tool surface was offered"); assert_eq!( selected.tokens, 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 3e8b5b3fdc..0f92ca8306 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 @@ -286,7 +286,7 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { estimated_prompt_tokens: estimate, completion_reserve: 0, capacity_error: None, budget_fault: None, protocol_error: None, segments: Vec::new(), newest_result_reduced: false, newest_result_tokens: 0, - messages: roomy.messages, + messages: roomy.messages, tools: crate::cognition::tool_surface::SelectedSurface::none(), tools_grant: 0, }; let corrected = faculty.refit_rejected_prompt(snapshot, estimate as u32 + 1, estimate as u32, 0).unwrap(); assert!(corrected.estimated_prompt_tokens < estimate); @@ -781,7 +781,7 @@ fn tool_surface_is_a_category_index_plus_discovery_pair() { "the newest burst line must survive once the budget prices the surface it \ actually sends — if this regresses, the accounting is double-counting the \ withheld registry again (card dec1a7ff); selected={}, estimated={}, reserve={}, capacity={:?}\n{}", - faculty.select_tool_surface(&ws).tokens, + faculty.prompt_view(&ws).tools.tokens, view.estimated_prompt_tokens, view.completion_reserve, view.capacity_error, diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/surface.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/surface.rs index 84606857b5..4c96fa18c9 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/surface.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/surface.rs @@ -34,7 +34,7 @@ async fn consecutive_acts_in_one_activity_send_byte_identical_tool_schemas() { let mut held_review = Workspace::new("review card deec4ac2: is the fix right?"); held_review.workspace_deliverable = true; let wire = |ws: &Workspace| { - let selected = faculty.select_tool_surface(ws); + let selected = faculty.prompt_view(ws).tools; (selected.reason, serde_json::to_string(&selected.specs).expect("specs serialize")) }; let first = wire(&message); @@ -64,7 +64,7 @@ fn a_room_that_declares_affordances_selects_exactly_those_plus_the_discovery_pai let mut ws = Workspace::new("find the docs for this API"); ws.room_affordances = vec!["web/fetch".to_string(), "web/search".to_string()]; - let selected = faculty.select_tool_surface(&ws); + let selected = faculty.prompt_view(&ws).tools; assert_eq!(selected.reason, SurfaceReason::RoomAffordances); let offered = selected.specs.as_deref().expect("a surface was offered"); let surface = faculty.tool_surface(); @@ -102,7 +102,7 @@ fn a_room_that_declares_nothing_offers_her_hands_on_every_turn() { work.workspace_deliverable = true; for ws in [Workspace::new("anything open?"), work] { assert!(ws.room_affordances.is_empty(), "the ordinary room declares none"); - let selected = faculty.select_tool_surface(&ws); + let selected = faculty.prompt_view(&ws).tools; assert_eq!(selected.reason, SurfaceReason::Hands); assert_eq!(selected.specs.as_deref(), Some(faculty.tool_surface().hands())); } @@ -142,7 +142,7 @@ fn a_room_whose_affordances_match_no_native_verb_falls_back_never_to_nothing() { let faculty = faculty_on(65_536); let mut ws = Workspace::new("chase the recruiter"); ws.room_affordances = vec!["mail/send".to_string()]; - let selected = faculty.select_tool_surface(&ws); + let selected = faculty.prompt_view(&ws).tools; assert_eq!(selected.reason, SurfaceReason::Hands, "fell through to her hands"); assert_eq!(selected.specs.as_deref(), Some(faculty.tool_surface().hands())); } 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 e0ae009304..82d6367d53 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 @@ -384,7 +384,7 @@ async fn standing_activity_grounding_survives_history_on_the_wire() { // budget-shed one. let minimum = GroundingPlan::minimum(&ws); let fixed = LlmDeliberationFaculty::framing_cost(&framing.stable) - + faculty.select_tool_surface(&ws).tokens + + faculty.prompt_view(&ws).tools.tokens + minimum.context_reserve() + minimum.trailing_tokens() + unfitted.required_tokens() @@ -515,7 +515,7 @@ async fn standing_activity_grounding_survives_history_on_the_wire() { ); let tools = request.tools.as_ref().expect("actual native surface"); let tool_tokens = crate::cognition::tool_surface::tool_surface_tokens_of(tools); - assert_eq!(tool_tokens, faculty.select_tool_surface(&ws).tokens); + assert_eq!(tool_tokens, faculty.prompt_view(&ws).tools.tokens); let wire = LlmDeliberationFaculty::framing_cost(system) + LlmDeliberationFaculty::messages_cost(&request.messages) + tool_tokens 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 2ca91ce761..1b7504b086 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 @@ -97,5 +97,6 @@ fn cfg_for(persona_id: uuid::Uuid) -> crate::cognition::persona_workspace::Perso defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, } } diff --git a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs index 32173a5590..f771a841aa 100644 --- a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs +++ b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs @@ -189,6 +189,9 @@ crate::action_command! { .messages .iter() .map(|m| crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: m.content.clone(), tokens: 0, metadata: serde_json::json!({ @@ -202,7 +205,6 @@ crate::action_command! { items, tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; // own_peer attributes the persona's OWN past posts (is_self → assistant role); a // command-seeded turn carries only inbound peer messages, so it's inert here but diff --git a/core/continuum-mind/src/modules/persona_rag_inspect.rs b/core/continuum-mind/src/modules/persona_rag_inspect.rs index 2353700408..190caac40d 100644 --- a/core/continuum-mind/src/modules/persona_rag_inspect.rs +++ b/core/continuum-mind/src/modules/persona_rag_inspect.rs @@ -107,14 +107,6 @@ pub struct RagInspectParams { #[serde(skip_serializing_if = "Option::is_none")] #[ts(optional)] #[ts(optional, type = "number")] - pub airc_floor: Option, - #[serde(skip_serializing_if = "Option::is_none")] - #[ts(optional)] - #[ts(optional, type = "number")] - pub airc_max: Option, - #[serde(skip_serializing_if = "Option::is_none")] - #[ts(optional)] - #[ts(optional, type = "number")] pub airc_fetch_limit: Option, /// Optional absolute path for the JSONL capture trace. When set, /// the inspection records the full turn there so other AIs / @@ -140,28 +132,6 @@ pub struct RagInspectParams { pub chain_inference: Option, } -/// One source's allocation outcome — flattened from the library's -/// BudgetAllocation for the wire. -#[derive(Debug, Clone, Serialize, Deserialize, TS)] -#[ts( - export, - export_to = "../../../protocol/typescript/persona/RagInspectAllocation.ts" -)] -#[serde(rename_all = "camelCase")] -pub struct RagInspectAllocation { - pub source_id: String, - #[ts(type = "number")] - pub allocated_tokens: u32, - #[ts(type = "number")] - pub requested_floor: u32, - #[ts(type = "number")] - pub requested_min: u32, - #[ts(type = "number")] - pub requested_max: u32, - /// "satisfied" / "floor_only" / "dropped" / "under_provisioned" - pub state: String, -} - /// One item the source delivered, with the mechanic-grade rationale /// flattened for the wire (content_preview, score, age_s, etc). #[derive(Debug, Clone, Serialize, Deserialize, TS)] @@ -183,9 +153,13 @@ pub struct RagInspectItem { pub lamport: u64, #[ts(type = "number")] pub age_s: u64, + /// The item has a coarser summary level her view can fall back to. + pub has_summary: bool, + /// The item has a pointer level (what it is and how to reopen it). + pub has_pointer: bool, } -/// One source's delivery — its budget, what it served, and the per- +/// One source's delivery — what it served, and the per- /// item rationale. #[derive(Debug, Clone, Serialize, Deserialize, TS)] #[ts( @@ -196,21 +170,18 @@ pub struct RagInspectItem { pub struct RagInspectDelivery { pub source_id: String, #[ts(type = "number")] - pub budget_requested: u32, - #[ts(type = "number")] pub tokens_used: u32, pub has_continuation: bool, pub items: Vec, } -/// Result of `persona/rag-inspect`. Carries the full allocation -/// outcome + per-source deliveries so any AI inspecting the persona +/// Result of `persona/rag-inspect`. Carries the per-source deliveries so any AI inspecting the persona /// can answer the three canonical questions: /// - "Would I respond as it requests at this step?" — full prompt /// reconstructable from `deliveries`; when `chainInference=true`, /// the actual model response is captured in `modelResponse`. -/// - "Which layer is broken?" — per-source `allocations` show state -/// (satisfied / floor_only / dropped / under_provisioned). +/// - "Which layer is broken?" — per-source deliveries and each item's +/// levels (`hasSummary`, `hasPointer`). /// - "Is this contextually relevant?" — per-item score + age + /// peer in the deliveries. #[derive(Debug, Clone, Serialize, Deserialize, TS)] @@ -225,15 +196,6 @@ pub struct RagInspectResult { pub persona_name: String, #[ts(type = "number")] pub context_window: u32, - /// Sum of all source allocations. Useful for "did we leave - /// tokens on the table?" telemetry. - #[ts(type = "number")] - pub total_allocated: u32, - /// True if the allocator reported `escalation_needed` — a - /// required source landed under-provisioned. Callers (AIs) - /// SHOULD flag this in their reasoning. - pub escalation_needed: bool, - pub allocations: Vec, pub deliveries: Vec, /// JSONL trace path (relative or absolute) when `trace_path` /// was set on the request. Other AIs / mechanic-shop tools @@ -279,27 +241,11 @@ pub struct RagInspectModelResponse { impl RagInspectResult { fn from_library(value: RagInspection) -> Self { - let total_allocated = value.allocation.total_allocated; - let escalation_needed = value.allocation.escalation_needed; - let allocations = value - .allocation - .allocations - .into_iter() - .map(|a| RagInspectAllocation { - source_id: a.source_id, - allocated_tokens: a.allocated_tokens, - requested_floor: a.requested_floor, - requested_min: a.requested_min, - requested_max: a.requested_max, - state: allocation_state_to_str(a.state).to_string(), - }) - .collect(); let deliveries = value .deliveries .into_iter() .map(|d| RagInspectDelivery { source_id: d.source_id, - budget_requested: d.budget_requested, tokens_used: d.tokens_used, has_continuation: d.has_continuation, items: d @@ -313,6 +259,8 @@ impl RagInspectResult { peer_id_prefix: i.peer_id_prefix, lamport: i.lamport, age_s: i.age_s, + has_summary: i.has_summary, + has_pointer: i.has_pointer, }) .collect(), }) @@ -331,9 +279,6 @@ impl RagInspectResult { persona_id: value.persona_id, persona_name: value.persona_name, context_window: value.context_window, - total_allocated, - escalation_needed, - allocations, deliveries, trace_path: value .trace_path @@ -344,16 +289,6 @@ impl RagInspectResult { } } -fn allocation_state_to_str(state: crate::cognition::rag_budget::AllocationState) -> &'static str { - use crate::cognition::rag_budget::AllocationState as S; - match state { - S::Satisfied => "satisfied", - S::FloorOnly => "floor_only", - S::Dropped => "dropped", - S::UnderProvisioned => "under_provisioned", - } -} - // ── Module ──────────────────────────────────────────────────────── pub struct PersonaRagInspectModule { @@ -437,12 +372,6 @@ pub(crate) async fn inspect_persona( if let Some(cw) = params.context_window { request.context_window = cw; } - if let Some(floor) = params.airc_floor { - request.airc_floor = floor; - } - if let Some(max) = params.airc_max { - request.airc_max = max; - } if let Some(fetch) = params.airc_fetch_limit { request.airc_fetch_limit = fetch as usize; } @@ -618,8 +547,9 @@ mod tests { assert!(result.unwrap_err().contains("not found in stub resolver")); } + // what this catches: an empty room still reports the airc source's delivery (zero items), not a missing source. #[tokio::test] - async fn known_persona_with_empty_room_returns_zero_items_but_satisfied_allocation() { + async fn known_persona_with_empty_room_delivers_zero_items() { let m = module_with(vec![]); let result = inspect_persona( &m.resolver, @@ -633,13 +563,8 @@ mod tests { .unwrap(); assert_eq!(result.persona_name, "Paige"); assert_eq!(result.persona_id, persona_uuid()); - // Allocator gives the airc source its full max (default 20k); - // delivery is empty since there are no events. - assert!(!result.escalation_needed); - assert_eq!(result.allocations.len(), 1); - assert_eq!(result.allocations[0].source_id, "airc"); - assert_eq!(result.allocations[0].state, "satisfied"); assert_eq!(result.deliveries.len(), 1); + assert_eq!(result.deliveries[0].source_id, "airc"); assert!(result.deliveries[0].items.is_empty()); } diff --git a/core/continuum-mind/src/persona/active_work_source.rs b/core/continuum-mind/src/persona/active_work_source.rs index a78ef2450a..612bce0a25 100644 --- a/core/continuum-mind/src/persona/active_work_source.rs +++ b/core/continuum-mind/src/persona/active_work_source.rs @@ -21,9 +21,7 @@ use airc_lib::{AircError, WorkCard}; use async_trait::async_trait; use serde_json::json; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::ACTIVE_WORK; @@ -45,11 +43,6 @@ pub trait AircWorkReader: Send + Sync { } } -/// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), -/// so every grounding layer's number is in the same unit the replay ledger reports. -/// (Was a private byte-length copy that drifted — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// Persona-bound source reading the persona's own claimed work. pub struct ActiveWorkSource { persona_id: uuid::Uuid, @@ -58,13 +51,12 @@ pub struct ActiveWorkSource { claims_seen: std::sync::Mutex, } -/// One current snapshot plus a coalesced historical notice. Refused transitions -/// must not accumulate card ids/titles under claim churn. The authoritative -/// board owns detail; this source retains only whether reconciliation is due. +/// The last successful snapshot, the baseline a lost claim is diffed against. Every +/// transition is delivered the turn it is seen (nothing is refused for size), so no +/// historical notice is retained: the authoritative board owns detail. #[derive(Default)] struct ClaimsSeen { current: Option>, - loss_notice_pending: bool, } impl ActiveWorkSource { @@ -84,42 +76,34 @@ impl ActiveWorkSource { /// GONE from this read; we do NOT know who holds it now (that would need a /// board read), so the fact says exactly that and points at the board. fn lost_claim_item(card_id: &uuid::Uuid, title: &str) -> RagItem { - let id8: String = card_id.to_string().chars().take(8).collect(); + let id8 = airc_core::shown_id::shown_form(*card_id); let content = format!( "[work] Your claim on card {id8} \"{title}\" is no longer held by you \ (lease expired or released). Do not continue work on it as yours — \ check the board before touching it again." ); - let tokens = estimate_tokens(&content); - RagItem { + // The key is the card: the transition is one fact about one card. The pointer + // keeps the "not yours any more" fact alive once the whole line collapses. + RagItem::whole( + format!("lost:{card_id}"), content, - tokens, - metadata: json!({ + json!({ "fact": "claim_lost", "card_id": card_id.to_string(), }), - } - } - - fn deferred_loss_item() -> RagItem { - let content = - "[work] Earlier claims ended; current ownership, including reacquisitions: work/list." - .to_string(); - RagItem { - tokens: estimate_tokens(&content), - content, - metadata: json!({ "fact": "claim_lost", "coalesced": true }), - } + ) + .with_pointer(format!("[work] claim on card {id8} ended — work/list")) } - fn empty() -> RagDelivery { - RagDelivery { - source_id: ACTIVE_WORK.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - } + /// A rejection fact is keyed by its own text: the ring (`claim_rejections`) hands out + /// lines, not ids, and one line is one rejection for as long as it lives there. + fn rejected_claim_item(line: String) -> RagItem { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + line.hash(&mut hasher); + let key = format!("rejected:{:016x}", hasher.finish()); + RagItem::whole(key, line, json!({ "fact": "claim_rejected" })) + .with_pointer("[work] a claim was rejected — work/list") } } @@ -133,21 +117,10 @@ impl RagSource for ActiveWorkSource { Some("work/list") } - /// One claimed-card line — id, title, state. Same shape and size as the - /// board's per-card line, which measured ~26 tokens live. - fn floor_tokens(&self) -> u32 { - 32 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { // Persona-scoped: a cross-persona ctx gets nothing. if ctx.persona_id != self.persona_id { - return Self::empty(); + return RagDelivery::empty(ACTIVE_WORK); } // One airc call (board-wide, all rooms). Failure is non-fatal — empty @@ -162,30 +135,19 @@ impl RagSource for ActiveWorkSource { persona_id = %self.persona_id, "active_work: active_claims failed — empty delivery, cognition stays up" ); - return Self::empty(); + return RagDelivery::empty(ACTIVE_WORK); } }; - // Reconcile successful observations with source admission atomically. - // Refused losses coalesce into one historical notice, never an unbounded - // queue or a stale assertion about current ownership after reacquisition. - // Source admission is not acknowledgement by the final model consumer. + // Reconcile the successful observation with the baseline: every claim that + // vanished since the last good read is delivered now, as an item. let now: std::collections::HashMap = claims .iter() .map(|c| (c.card_id.as_uuid(), c.title.clone())) .collect(); let mut items: Vec = Vec::new(); - let mut tokens_used: u32 = 0; { let mut seen = self.claims_seen.lock().unwrap_or_else(|p| p.into_inner()); - if seen.loss_notice_pending { - let notice = Self::deferred_loss_item(); - if notice.tokens <= budget { - tokens_used += notice.tokens; - items.push(notice); - seen.loss_notice_pending = false; - } - } let mut lost: Vec<_> = match seen.current.as_ref() { Some(before) => before .iter() @@ -195,18 +157,9 @@ impl RagSource for ActiveWorkSource { // First successful read: no baseline, nothing to lose from. None => Vec::new(), }; - // Stable ordering makes partial admission reproducible; a long - // title cannot prevent a later, smaller notice from fitting. + // Stable ordering keeps the delivery reproducible. lost.sort_unstable_by_key(|(id, _)| *id); - for (card_id, title) in lost { - let item = Self::lost_claim_item(&card_id, &title); - if tokens_used.saturating_add(item.tokens) > budget { - seen.loss_notice_pending = true; - continue; - } - tokens_used += item.tokens; - items.push(item); - } + items.extend(lost.iter().map(|(card_id, title)| Self::lost_claim_item(card_id, title))); seen.current = Some(now); } // Rejected-claim facts (the #159-family sibling of the lost-claim @@ -215,27 +168,20 @@ impl RagSource for ActiveWorkSource { // past the raw receipt's short window — the rejection-amnesia fix // (glass-boxed 2026-08-02: accurate rejection reports for three // turns, then "I've claimed the task" once the receipts scrolled). - for line in crate::persona::claim_rejections::recent(self.persona_id) { - let tokens = estimate_tokens(&line); - if tokens_used.saturating_add(tokens) > budget { - break; - } - tokens_used += tokens; - items.push(RagItem { - content: line, - tokens, - metadata: json!({ "fact": "claim_rejected" }), - }); - } + items.extend( + crate::persona::claim_rejections::recent(self.persona_id) + .into_iter() + .map(Self::rejected_claim_item), + ); if claims.is_empty() && items.is_empty() { - return Self::empty(); + return RagDelivery::empty(ACTIVE_WORK); } // Claim selection is not a receipt that this running turn rebound its hands. // WorkClaim may select/stage another card during a burst, while that burst // retains its admitted workspace. Describe the shared selector's result only. let focus = crate::persona::work_focus::focus_workspace_card(claims.iter()).map(|c| c.card_id); for card in &claims { - let id8: String = card.card_id.as_uuid().to_string().chars().take(8).collect(); + let id8 = airc_core::shown_id::shown_form(card.card_id.as_uuid()); // Human-readable line; structured parts also ride in metadata so // prompt-assembly / verifiers can render without re-parsing. let stance = if claims.len() > 1 { @@ -253,39 +199,28 @@ impl RagSource for ActiveWorkSource { title = card.title, prio = card.priority, ); - let tokens = estimate_tokens(&content); - if tokens_used.saturating_add(tokens) > budget { - // Budget exhausted — a truncated work list is still truthful for - // the cards it names. Atomic unit = one card; no continuation. - break; - } - tokens_used += tokens; - items.push(RagItem { - content, - tokens, - metadata: json!({ - "card_id": card.card_id.as_uuid().to_string(), - "state": format!("{:?}", card.state), - "claim_id": card.claim_id.map(|c| c.as_uuid().to_string()), - }), - }); + items.push( + RagItem::whole( + format!("card:{}", card.card_id.as_uuid()), + content, + json!({ + "card_id": card.card_id.as_uuid().to_string(), + "state": format!("{:?}", card.state), + "claim_id": card.claim_id.map(|c| c.as_uuid().to_string()), + }), + ) + .with_pointer(format!("[card {id8}] you hold it — work/list")), + ); } + let delivery = RagDelivery::of(ACTIVE_WORK, items, false); tracing::debug!( persona_id = %self.persona_id, - budget, - cards = items.len(), - tokens_used, + items = delivery.items.len(), + tokens_used = delivery.tokens_used, "active_work: deliver" ); - - RagDelivery { - source_id: ACTIVE_WORK.to_string(), - items, - tokens_used, - truncated: false, - resolution_used: resolution, - } + delivery } } @@ -391,7 +326,7 @@ mod tests { Ok(vec![in_review, working, selected]), ]); for selected_title in ["Source-hygiene", "New explicit task"] { - let delivery = src.deliver(&ctx(persona), 10_000, ResolutionPreference::Raw).await; + let delivery = src.deliver(&ctx(persona)).await; let selected_lines: Vec<_> = delivery.items.iter() .filter(|item| item.content.contains(" \u{2014} selected claim")) .collect(); @@ -401,7 +336,6 @@ mod tests { !item.content.contains("THIS TURN") && !item.content.contains("not this turn"))); let review = delivery.items.iter().find(|item| item.content.contains("django")).expect("review remains held"); assert!(review.content.ends_with(" \u{2014} held")); - assert!(delivery.tokens_used <= 10_000); } } @@ -422,7 +356,7 @@ mod tests { let src = source(persona, vec![Ok(vec![]), Ok(vec![])]); let delivery = src - .deliver(&ctx(persona), 10_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert_eq!( delivery.items.len(), @@ -436,7 +370,7 @@ mod tests { // Another persona's source never sees it. let src_other = source(other, vec![Ok(vec![])]); let delivery = src_other - .deliver(&ctx(other), 10_000, ResolutionPreference::Raw) + .deliver(&ctx(other)) .await; assert!(delivery.items.is_empty()); } @@ -457,14 +391,14 @@ mod tests { // Read 1: holds the card — normal grounding line, no facts. let d1 = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert_eq!(d1.items.len(), 1); assert!(d1.items[0].metadata.get("fact").is_none()); // Read 2: the card vanished → the transition fact, once, loud. let d2 = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert_eq!(d2.items.len(), 1); assert_eq!(d2.items[0].metadata["fact"], "claim_lost"); @@ -479,96 +413,50 @@ mod tests { // Read 3: baseline adopted — silence, not a nag loop. let d3 = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert!(d3.items.is_empty()); } - // what this catches: refused losses survive as bounded historical notice, - // while current claims remain visible and reacquisition is not revoked. + // what this catches: the old budget-coupled state — every ended claim is delivered + // the turn it is seen, however long its title, with a stable per-card key and a + // pointer; nothing is deferred to a later turn, and another persona's context + // neither sees the facts nor disturbs the baseline. #[tokio::test] - async fn refused_losses_coalesce_without_blocking_current_claims() { + async fn every_lost_claim_is_delivered_at_once_with_keys_and_pointers() { let persona = Uuid::new_v4(); let mut large = card(&"long title ".repeat(100)); let mut small = card("small"); large.card_id = WorkCardId::from_uuid(Uuid::from_u128(1)); small.card_id = WorkCardId::from_uuid(Uuid::from_u128(2)); - let small_cost = - ActiveWorkSource::lost_claim_item(&small.card_id.as_uuid(), &small.title).tokens; let src = source( persona, vec![ Ok(vec![large.clone(), small.clone()]), Ok(vec![]), - Err(()), - Ok(vec![large.clone()]), Ok(vec![large.clone()]), ], ); - let raw = ResolutionPreference::Raw; - src.deliver(&ctx(persona), 10_000, raw).await; - let partial = src.deliver(&ctx(persona), small_cost, raw).await; - assert_eq!(partial.items.len(), 1); - assert_eq!( - partial.items[0].metadata["card_id"], - small.card_id.as_uuid().to_string() - ); - assert_eq!(partial.tokens_used, small_cost); - // Neither a different persona nor a failed read consumes the notice. - assert!(src - .deliver(&ctx(Uuid::new_v4()), 10_000, raw) - .await - .items - .is_empty()); - assert!(src - .deliver(&ctx(persona), 10_000, raw) - .await - .items - .is_empty()); - let regained = src.deliver(&ctx(persona), 10_000, raw).await; - assert_eq!(regained.items.len(), 2); - assert_eq!(regained.items[0].metadata["coalesced"], true); - assert!(regained.items[0].content.contains("Earlier claims ended")); - assert!(regained.items[0].content.contains("work/list")); - assert!(regained.items[0].metadata.get("card_id").is_none()); - assert!( - regained.items[1].metadata.get("fact").is_none(), - "current claim remains visible" - ); - assert_eq!(src.deliver(&ctx(persona), 10_000, raw).await.items.len(), 1); - - // Churn at zero budget retains one current snapshot and a boolean, - // never a growing queue of ended card ids or unrenderable titles. - let mut reads = Vec::new(); - for _ in 0..100 { - reads.push(Ok(vec![card(&"long title ".repeat(100))])); - reads.push(Ok(vec![])); - } - reads.extend([Ok(vec![]), Ok(vec![])]); - let churn = source(persona, reads); - for _ in 0..200 { - assert!(churn.deliver(&ctx(persona), 0, raw).await.items.is_empty()); - } - { - let seen = churn.claims_seen.lock().unwrap(); - assert!(seen.current.as_ref().unwrap().is_empty()); - assert!(seen.loss_notice_pending); - } - let recovered = churn - .deliver(&ctx(persona), churn.floor_tokens(), raw) - .await; + src.deliver(&ctx(persona)).await; + let lost = src.deliver(&ctx(persona)).await; + let keys: Vec<_> = lost.items.iter().map(|i| i.key.clone()).collect(); assert_eq!( - recovered.items.len(), - 1, - "the digest fits the existing source floor" + keys, + [ + format!("lost:{}", large.card_id.as_uuid()), + format!("lost:{}", small.card_id.as_uuid()), + ] ); - assert_eq!(recovered.items[0].metadata["fact"], "claim_lost"); - assert!(churn - .deliver(&ctx(persona), 10_000, raw) - .await - .items - .is_empty()); + assert!(lost.items.iter().all(|i| i.pointer.is_some() && i.metadata["fact"] == "claim_lost")); + assert!(!lost.truncated); + assert!(src.deliver(&ctx(Uuid::new_v4())).await.items.is_empty()); + // Reacquisition: a plain current claim keyed by its card id, no loss fact. + let regained = src.deliver(&ctx(persona)).await; + assert_eq!(regained.items.len(), 1); + assert_eq!(regained.items[0].key, format!("card:{}", large.card_id.as_uuid())); + assert!(regained.items[0].metadata.get("fact").is_none()); } + // what this catches: a DEGRADED read must never fabricate loss — the // baseline survives the error, and the loss fact only fires when a // SUCCESSFUL read actually shows the card gone. @@ -582,11 +470,11 @@ mod tests { ); let _hold = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; // Degraded read: empty delivery, NO loss facts, baseline preserved. let err = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert!( err.items.is_empty(), @@ -594,13 +482,13 @@ mod tests { ); // Recovered read still holding: no facts (nothing was ever lost). let ok = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert_eq!(ok.items.len(), 1); assert!(ok.items[0].metadata.get("fact").is_none()); // NOW it's genuinely gone → the fact fires from the preserved baseline. let lost = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert_eq!(lost.items.len(), 1); assert_eq!(lost.items[0].metadata["fact"], "claim_lost"); @@ -613,7 +501,7 @@ mod tests { let persona = Uuid::new_v4(); let src = source(persona, vec![Ok(vec![])]); let d = src - .deliver(&ctx(persona), 1_000, ResolutionPreference::Raw) + .deliver(&ctx(persona)) .await; assert!( d.items.is_empty(), diff --git a/core/continuum-mind/src/persona/airc_source.rs b/core/continuum-mind/src/persona/airc_source.rs index a63293d1e1..5d994c658a 100644 --- a/core/continuum-mind/src/persona/airc_source.rs +++ b/core/continuum-mind/src/persona/airc_source.rs @@ -36,9 +36,7 @@ use crate::cognition::channel_element::ChannelElement; use crate::cognition::channel_substrate::{ global_channel_digest_buffer, global_channel_digest_builder, }; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::runtime::ready_buffer::ReadyBuffer; use crate::cognition::conversation::transcript_reader::AircTranscriptReader; @@ -51,8 +49,6 @@ const FETCH_LIMIT: usize = 100; /// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), /// shared by every RAG source so the replay ledger's numbers match. (Was a private /// copy — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; -use crate::cognition::token_budget::head_to_tokens; /// Persona-bound source delivering the consolidated channel digest. pub struct AircRagSource { @@ -66,29 +62,11 @@ pub struct AircRagSource { /// persona's airc runtime log holds only events since ITS boot). `Some` in /// production (default); tests without a store see a loud-skip, not a panic. history: Option>, - /// WHERE HER HISTORY STARTS, per room: the event the window's oldest kept line - /// belongs to. Kept across turns so the window's start holds still and jumps in - /// large steps ([`HISTORY_SLACK`]) instead of sliding one event per turn. Measured - /// on the 5090, 2026-10-05 (Cormac's trace): the newest-first fill dropped the - /// oldest line on every room event, so the FIRST history message changed every - /// turn; her hybrid base can only roll back to a saved checkpoint before the first - /// differing token, so each turn re-prefilled 39-59k tokens (20-75 s) and the - /// checkpoint cap then erased even the head's. One anchor per room, in memory. - anchors: std::sync::Mutex>, -} - -/// The oldest kept line of a room's window, as the event it came from. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct HistoryAnchor { - pub event: uuid::Uuid, + /// The digest last delivered per room: what `mark_read` resolves an event id against + /// (airc's cursor wants the event itself, not a bare id). + last_digest: std::sync::Mutex>>, } -/// The share of the window budget left free when the start jumps, so the next turns' -/// new events fit without moving it again. A quarter: the start moves once per ~quarter -/// window of new traffic, and every turn in between extends the cached prefix instead -/// of replacing it. A larger slack buys fewer jumps at the cost of history shown. -pub(crate) const HISTORY_SLACK: f32 = 0.25; - impl AircRagSource { /// Production constructor — shares the process-global digest substrate so every /// persona reuses one element cache + bookmark store + pre-staged buffer. @@ -101,30 +79,10 @@ impl AircRagSource { grounding: DEFAULT_GROUNDING, fetch_limit: FETCH_LIMIT, history: Some(Arc::new(crate::persona::durable_history::ChatStoreHistory)), - anchors: std::sync::Mutex::new(std::collections::HashMap::new()), + last_digest: std::sync::Mutex::new(std::collections::HashMap::new()), } } - /// Floor of tokens any packed turn can occupy (sender prefix + separators - /// alone — a physical minimum, not a policy). Used ONLY to size the - /// candidate window handed to the token packer: `budget / floor` - /// candidates can never under-supply it, so the TOKEN budget — never a - /// message count — is the binding constraint on what the persona sees. - /// The 2026-07-30 glass box: a 5-message grounding pre-trim starved - /// pack_digest into a 3–5-message world view while the L1 budget could - /// hold dozens — the persona then confabulated generic-assistant filler - /// because the actual conversation was invisible (#259). - // context-budget-exempt: a FLOOR under a per-turn allocation — it only ever raises, so a large window is never clamped by it - const MIN_TOKENS_PER_TURN: u32 = 8; - - /// Turns-that-fit grounding: derive the digest's before-bookmark window - /// from the delivery budget. `recipe_floor` (the recipe-defined N, default - /// [`DEFAULT_GROUNDING`]) is the floor; the ceiling bounds the durable - /// top-up fetch, not what the packer may keep. - fn grounding_for_budget(budget: u32, recipe_floor: usize) -> usize { - ((budget / Self::MIN_TOKENS_PER_TURN) as usize).clamp(recipe_floor, 256) - } - /// Synthesize a grounding-only `TranscriptEvent` from a durable transcript /// line. Lamport 0 puts it strictly BEFORE any live event after the split /// sort (which is stable, so hydrated lines keep their chronological input @@ -148,41 +106,13 @@ impl AircRagSource { self } - /// Format a digest into budget-packed `RagItem`s. Walks the window newest-first - /// accumulating tokens until budget, then emits chronological (oldest-first) so - /// the chat template reads turns in order. Each item is tagged `unread` vs - /// grounding so the prompt builder / glass box can tell them apart. - /// - /// BREADTH OVER VERBATIM DEPTH (#128/#146, measured 2026-07-13): the original - /// packer kept WHOLE messages newest-first, so a small budget in a verbose - /// four-persona room held ~2-3 turns TOTAL — the persona's entire perceivable - /// world. Any low-frequency speaker (the operator) was displaced within - /// seconds; the room degenerated into parallel monologues that only rapid-fire - /// exchange survived. A conversation is legible from turn HEADS; it is not - /// legible from two verbatim essays. So each turn now costs at most a - /// per-turn cap (a budget fraction, never a hardcoded model tier) and long - /// turns are head-trimmed with an explicit marker — the same - /// straddling-trim law the prompt fitter applies to messages, one level down. - /// The NEWEST turn is exempt (kept verbatim up to the whole budget): it is - /// what the persona is responding to. - /// Returns the packed items, the tokens they cost, and the READ-THROUGH - /// ELEMENT: the newest element that actually entered her prompt. That last - /// value is what advances her cursor — she is marked read for what she was - /// GIVEN, never for what was merely fetched and then dropped by the budget. - /// - /// The ELEMENT, not a lamport, because airc's `save_runtime_cursor_for_event` - /// wants the source event (it carries the room + kind and emits - /// `SubscriptionAdvanced`). Handing it a bare number would throw that away. - fn pack_digest( - digest: &ChannelDigest, - budget: u32, - working: bool, - anchor: Option, - ) -> (Vec, u32, Option>, Option) { - // Per-turn cap: budget/8 → a useful window holds ~8+ turns; clamped so - // tiny budgets still render a sentence and huge ones don't let one - // essay crowd the window. - let per_turn_cap = (budget / 8).clamp(48, 256); + /// Every unit of a digest, whole, oldest first: the source delivers levels, never a size + /// (FLOW-IMPLEMENTATION-PLAN §2d). Her one allocation in the prompt view decides which + /// turns she sees, and when a start moves. This replaced a per-turn cap, head cuts and an + /// anchored start that sized the conversation against a second budget (the 159k served + /// window) before the view sized it again against hers. Receipt runs still fold to one + /// line per author, and quarantined lines still never enter. + fn digest_items(digest: &ChannelDigest, working: bool) -> Vec { let (units, quarantined) = Self::collapse_work_receipts(digest, working); if quarantined > 0 { continuum_base::probe!( @@ -192,116 +122,42 @@ impl AircRagSource { "transcript lines the speak gate would refuse were kept out of her burst — the contagion carrier (card 169eb543)" ); } - // Cost every unit once, newest-first (the newest is exempt from the per-turn - // cap: it is what she is responding to). `costed` is oldest-first after the - // reverse, parallel to `units`, with None for a unit that has no text. - let mut costed: Vec)>> = Vec::with_capacity(units.len()); - let mut newest_kept = true; - for unit in units.iter().rev() { - let idx = unit.last_idx; - let text: &str = match unit.collapsed.as_deref() { - Some(t) => t, - None => match digest.elements[idx].text() { - Some(t) => t, - None => { - costed.push(None); - continue; - } - }, - }; - let full = estimate_tokens(text); - let cap = if newest_kept { budget } else { per_turn_cap }; - let (cost, trimmed) = if full <= cap { - (full, unit.collapsed.clone()) - } else { - let head = head_to_tokens(text, cap); - let head_cost = estimate_tokens(&head).saturating_add(2); // marker - // The marker SPELLING is shared with the tail-trim site so the two - // cannot drift apart again (card 3833b472). The +2 reserve above is - // left as it was on purpose: `trim_marker_tokens()` measures the real - // cost at 8, so this site under-reserves, but raising it changes how - // many turns fit in every prompt — a packing change that belongs in - // its own card with its own before/after, not smuggled into a - // disclosure fix. - ( - head_cost, - Some(crate::cognition::token_budget::mark_head_kept( - &head, full, - )), - ) - }; - newest_kept = false; - costed.push(Some((cost, trimmed))); - } - costed.reverse(); - // THE START HOLDS STILL. The window is the suffix of units from `start`; its - // cost is the sum from there to the newest. Where the fill would naturally - // begin (newest-first to the budget) is `natural`. The anchor from last turn - // is kept while the suffix from it still fits; when it no longer fits, the - // start jumps FORWARD past `natural` to leave HISTORY_SLACK of the budget - // free, so the next turns' new events fit without moving it again. Every - // turn in between then extends the prefix the engine already holds, instead - // of replacing its first message. The first fill in a room (no anchor yet) - // shows everything the budget holds; the room's second turn then pays one - // jump and holds from there. An anchored event that scrolled out of the - // digest is a jump too. - let suffix_cost = |start: usize| -> u32 { - costed[start..].iter().flatten().map(|(c, _)| *c).fold(0u32, |a, c| a.saturating_add(c)) - }; - let first_start_within = |limit: u32| -> usize { - // the smallest start whose suffix fits `limit`; units.len() = nothing fits - (0..=units.len()).find(|&start| suffix_cost(start) <= limit).unwrap_or(units.len()) // unwrap_or: the empty suffix always fits, so this is never reached - }; - let natural = first_start_within(budget); - // The anchor is the event at the unit's ORDER position (a run's first receipt), - // never its newest: keyed on the newest, an open run at the window's start would - // look scrolled out on every receipt and jump each turn (Cormac on #4806). - let anchored = anchor.and_then(|a| { - units.iter().position(|u| digest.elements[u.order_idx].event_id() == a.event) - }); - let slack_limit = ((budget as f32) * (1.0 - HISTORY_SLACK)) as u32; - let start = match (anchor, anchored) { - // the first fill in this room: everything the budget holds - (None, _) => natural, - // last turn's start still fits: hold it, even if more would fit now - (Some(_), Some(a)) if a >= natural => a, - // it no longer fits, or it scrolled out: jump forward with headroom; never - // past the newest unit, which is always shown - _ => first_start_within(slack_limit).min(units.len().saturating_sub(1)), - }; - let mut keep: Vec<(usize, Option)> = Vec::new(); - let mut tokens_used: u32 = 0; - for (unit, c) in units[start..].iter().zip(&costed[start..]) { - if let Some((cost, trimmed)) = c { - tokens_used = tokens_used.saturating_add(*cost); - keep.push((unit.last_idx, trimmed.clone())); - } - } - let new_anchor = units.get(start).map(|u| HistoryAnchor { event: digest.elements[u.order_idx].event_id() }); - if anchored.is_some_and(|a| a != start) || (anchored.is_none() && anchor.is_some()) { + units + .iter() + .filter(|unit| unit.collapsed.is_some() || digest.elements[unit.last_idx].text().is_some()) + .map(|unit| Self::format_item(&digest.elements[unit.last_idx], unit.last_idx >= digest.unread_start, unit.collapsed.clone())) + .collect() + } + + /// She read the room through `event`: advance her per-room cursor to it, exactly as the + /// human's UI does on mark-read. Called by the deliberation faculty after a prompt that + /// rendered `event` was sent (its read-receipt hook), never at delivery: delivery is not + /// reading, and only the view knows which turns she saw. Monotonic in airc, so a repeat + /// or a lower event never rewinds her. + pub async fn mark_read(&self, room_id: uuid::Uuid, event: uuid::Uuid) { + let element = self + .last_digest + .lock() + .unwrap_or_else(|p| p.into_inner()) // a poisoned map still answers, same policy as every lock in this crate + .get(&room_id) + .and_then(|digest| digest.elements.iter().find(|el| el.event().event_id.as_uuid() == event).cloned()); + let Some(element) = element else { continuum_base::probe!( - class = "perception.history.anchor_moved", - room = %digest.room_id, - from_natural = natural as u64, - start = start as u64, - units = units.len() as u64, - tokens = tokens_used as u64, - budget = budget as u64, - "the start of her history in this room jumped: the prefix the engine held is replaced once, then holds again" + class = "perception.mark_read.unknown_event", + persona = %self.persona_id, + room = %room_id, + "a read receipt named an event the last digest of this room does not hold: the cursor stays" + ); + return; + }; + if let Err(err) = self.reader.advance_read_cursor(self.persona_id, room_id, element.event()).await { + tracing::warn!( + error = %err, + persona_id = %self.persona_id, + room = %room_id, + "airc rag: could not persist the read cursor — she will re-read this page next turn (bounded)" ); } - // `keep` is oldest-first after the reverse, so its LAST entry is the newest - // element that actually fit — how far she genuinely read this turn. - // the newest element that entered her prompt, by the elements' own order (a run's - // line sits at its first receipt but reads through its newest) - let read_through = keep.iter().map(|(idx, _)| *idx).max().map(|idx| digest.elements[idx].clone()); - let items = keep - .into_iter() - .map(|(idx, trimmed)| { - Self::format_item(&digest.elements[idx], idx >= digest.unread_start, trimmed) - }) - .collect(); - (items, tokens_used, read_through, new_anchor) } /// COLLAPSE, DON'T CLIP — work receipts. A working citizen radiates one @@ -452,15 +308,14 @@ impl AircRagSource { fn format_item( element: &Arc, unread: bool, - trimmed: Option, + collapsed: Option, ) -> RagItem { let ev = element.event(); - let text = trimmed.unwrap_or_else(|| element.text().unwrap_or_default().to_string()); - let tokens = estimate_tokens(&text); - RagItem { - content: text, - tokens, - metadata: serde_json::json!({ + let text = collapsed.unwrap_or_else(|| element.text().unwrap_or_default().to_string()); + RagItem::whole( + ev.event_id.as_uuid().to_string(), + text, + serde_json::json!({ "event_id": ev.event_id.as_uuid().to_string(), "room_id": ev.room_id.as_uuid().to_string(), // The LOGICAL author: a chat/send line is attributed to the human/web @@ -477,17 +332,7 @@ impl AircRagSource { // as the item score; without it the inspect layer silently saw 0.0. "score": if unread { 1.0 } else { 0.5 }, }), - } - } - - fn empty(resolution: ResolutionPreference) -> RagDelivery { - RagDelivery { - source_id: AIRC.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: resolution, - } + ) } } @@ -527,22 +372,10 @@ impl RagSource for AircRagSource { Some("collaboration/chat/export") } - /// One conversation turn — a speaker and what they said. The recent-history - /// appetite is much larger and is expressed as `min`, not as this floor; - /// conflating the two is what made every source all-or-nothing. - fn floor_tokens(&self) -> u32 { - 64 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { // Defense in depth: never serve another persona's context. if ctx.persona_id != self.persona_id { - return Self::empty(ResolutionPreference::Placeholder); + return RagDelivery::empty(AIRC); } // Page the TURN's room when the RagContext carries it (#367). Before this, // page_recent always followed the persona's current-room POINTER (her @@ -565,7 +398,7 @@ impl RagSource for AircRagSource { persona_id = %self.persona_id, "airc rag: page_recent failed — empty delivery, cognition stays up" ); - return Self::empty(ResolutionPreference::Placeholder); + return RagDelivery::empty(AIRC); } }; let Some(room_id) = ctx @@ -574,7 +407,7 @@ impl RagSource for AircRagSource { .or_else(|| events.last().map(|e| e.room_id.as_uuid())) else { // No room scope AND no transcript — genuinely nothing to digest. - return Self::empty(ResolutionPreference::Placeholder); + return RagDelivery::empty(AIRC); }; // #249: when the LIVE window is shallower than the grounding target (the @@ -585,10 +418,10 @@ impl RagSource for AircRagSource { // sender (the durable row id is the airc event id for persona lines, but // live events re-mint EventIds across runtimes — content identity is the // honest join). Fetch failure degrades to the shallow window, loudly. - // Turns-that-fit: the budget sizes the candidate window; the packer's - // token walk decides what survives. self.grounding stays only as the - // recipe floor (#259 — kills the 5-message world-view starvation). - let grounding = Self::grounding_for_budget(budget, self.grounding); + // How much history to stage: the recipe's grounding, at least the fetch window. What + // she then SEES of it is her view's decision (FLOW-IMPLEMENTATION-PLAN §2d), never a + // budget here (#259's starvation came from sizing this window by a budget). + let grounding = self.grounding.max(self.fetch_limit); let mut events = events; let live_in_room = events .iter() @@ -647,10 +480,12 @@ impl RagSource for AircRagSource { // the pre-staged path is skipped when we hydrated (the staged digest was // built from the same shallow log); the built-once path below carries the // topped-up window. Region-side hydration is the follow-up slice. + // What a rebuild would hold: the room's events after any durable top-up, up to the + // staging depth. A staged digest is reused only when it holds at least that much, so a + // shallow stage (the region stages the recipe floor) or a top-up forces the rebuild. + let rebuild_holds = events.iter().filter(|e| e.room_id.as_uuid() == room_id).count().min(grounding); let digest = match self.buffer.peek(&(self.persona_id, room_id)) { - // The region pre-stages with the recipe floor; only reuse it when - // it already covers the budget-derived window — else rebuild wide. - Some(d) if live_in_room >= grounding && d.elements.len() >= grounding => d, + Some(d) if d.elements.len() >= rebuild_holds => d, _ => { // The cursor is AIRC's, read per build. A read failure must not mute // her — fall back to 0 (everything unread), which the FIRST_READ_PAGE @@ -678,73 +513,32 @@ impl RagSource for AircRagSource { } }; - let anchor = self.anchors.lock().unwrap_or_else(|p| p.into_inner()).get(&room_id).copied(); // a poisoned map still answers, same policy as every lock in this crate - let (items, tokens_used, read_through, new_anchor) = - Self::pack_digest(&digest, budget, crate::cognition::persona_workspace::acting_root_of(self.persona_id).is_some(), anchor); - if let Some(a) = new_anchor { - self.anchors.lock().unwrap_or_else(|p| p.into_inner()).insert(room_id, a); // a poisoned map still takes the anchor; losing it costs one re-prefill, never a panic - } - // SHE HAS NOW READ THE ROOM — advance her per-room cursor, exactly as the - // human's UI does on nav/mark-read and on navigating away from a room. - // - // THE BUG THIS FIXES: `ChannelBookmarks` is per-(persona, room) and has - // been correct since it was written — but the ONLY production callers of - // `advance` were in `modules/nav.rs`, both keyed on `ctx.user_id`, the - // authenticated HUMAN. A persona never navigates, so her `last_read` stayed - // at 0 forever, and `last_read`'s own doc spells out what 0 means: - // "never read (everything is unread)". Every turn therefore re-delivered - // the ENTIRE paged history as UNREAD, each item at attention score 1.0, - // with an EMPTY grounding split (unread_start == 0) — the digest's - // read/unread structure was built and then never used for a persona. - // - // That is the storm: with nothing ever marked read, no message is ever - // consumed, so two citizens in one room re-excite each other on a window - // that only grows. With the cursor advancing, a wake shows what is NEW - // plus N-before grounding, and a room with nothing new is quiet — the same - // contract every message client has had for thirty years. - // - // Mark-read on DELIVERY, not on reply, because delivery is when she saw - // it — `tip_lamport`'s own doc says "ignore/skip/respond all mark-read". - // Advancing to `read_through` (what was PACKED) rather than the digest tip - // keeps it honest under a tight budget: she is never marked read for a - // message the packer dropped. `advance` is monotonic, so a repeat delivery - // or a late lower lamport can never rewind her. - if let Some(element) = read_through.as_ref() { - if let Err(err) = self - .reader - .advance_read_cursor(self.persona_id, room_id, element.event()) - .await - { - tracing::warn!( - error = %err, - persona_id = %self.persona_id, - room = %room_id, - "airc rag: could not persist the read cursor — she will re-read this \ - page next turn (bounded), never the whole transcript" - ); - } - } + let items = Self::digest_items(&digest, crate::cognition::persona_workspace::acting_root_of(self.persona_id).is_some()); + let tokens_used = items.iter().map(|item| item.tokens).fold(0u32, |a, t| a.saturating_add(t)); + // Kept for `mark_read`: the faculty marks her read after a sent prompt rendered these + // turns, never here (delivery is not reading). + self.last_digest.lock().unwrap_or_else(|p| p.into_inner()).insert(room_id, Arc::clone(&digest)); // a poisoned map still takes the digest; losing it costs one unmarked turn, never a panic tracing::debug!( persona_id = %self.persona_id, room = %room_id, window = digest.elements.len(), - budget, - items_packed = items.len(), + items = items.len(), tokens_used, - "airc_rag: deliver (digest)" + "airc_rag: deliver (digest, every unit whole)" ); - RagDelivery { - source_id: AIRC.to_string(), - items, - tokens_used, - // The digest IS the window. More history = a command (scrollback/search), - // not a budget continuation cursor. - truncated: false, - resolution_used: resolution, - } + // The digest IS the window. More history = a command (scrollback/search), + // not a budget continuation cursor. + RagDelivery::of(AIRC, items, false) } } +#[async_trait::async_trait] +impl crate::cognition::llm_deliberation_faculty::ReadReceipt for AircRagSource { + async fn read_through(&self, room: uuid::Uuid, event: uuid::Uuid) { + self.mark_read(room, event).await; + } +} + #[cfg(test)] mod tests; diff --git a/core/continuum-mind/src/persona/airc_source/tests.rs b/core/continuum-mind/src/persona/airc_source/tests.rs index 0a6a86f968..823958202f 100644 --- a/core/continuum-mind/src/persona/airc_source/tests.rs +++ b/core/continuum-mind/src/persona/airc_source/tests.rs @@ -88,7 +88,7 @@ }); let (source, _) = isolated_source(reader.clone()); source - .deliver(&ctx_in(room), 1_000, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert_eq!( *reader.paged_room.lock().unwrap(), @@ -100,7 +100,7 @@ // pointer-scoped, not accidentally room-pinned. let ctx_no_room = RagContext::for_persona(persona(), 1_000_000); source - .deliver(&ctx_no_room, 1_000, ResolutionPreference::Raw) + .deliver(&ctx_no_room) .await; assert_eq!(*reader.paged_room.lock().unwrap(), Some(None)); } @@ -124,7 +124,7 @@ // Isolated tests exercise the live window; hydration has its own test // (a stub DurableRoomHistory) and stays off here. history: None, - anchors: std::sync::Mutex::new(std::collections::HashMap::new()), + last_digest: std::sync::Mutex::new(std::collections::HashMap::new()), }; (source, buffer) } @@ -164,7 +164,7 @@ ])); let (source, _) = isolated_source(reader); let delivery = source - .deliver(&ctx_in(room), 1_000, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert_eq!(delivery.items.len(), 2); assert_eq!(delivery.items[0].content, "hello"); @@ -182,9 +182,9 @@ // 2026-07-30: Asha's captures showed "[context] you can currently see the // last 3 messages" while her L1 budget could hold dozens — she then looped // generic-assistant filler because the real conversation was invisible). - // Grounding must derive from the TOKEN budget (turns-that-fit), never a - // fixed message count: with every message already read (bookmark at tip), - // a generous budget must still deliver far more than DEFAULT_GROUNDING. + // what this catches: a budget sizing the conversation inside the source (FLOW plan §2d). + // A caught-up persona is still handed the whole staged history, and a tiny budget + // changes nothing: her one view decides what she sees, never a second budget here. #[tokio::test] async fn caught_up_persona_sees_budget_worth_of_history_not_five_messages() { let room = RoomId::new(); @@ -196,69 +196,38 @@ let (source, _) = isolated_source(reader); let delivery = source - .deliver(&ctx_in(room), 4_000, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert!( delivery.items.len() > DEFAULT_GROUNDING, - "a 4k-token budget must widen the window past the {DEFAULT_GROUNDING}-message \ + "the window must reach past the {DEFAULT_GROUNDING}-message \ recipe floor, got {}", delivery.items.len() ); assert_eq!( delivery.items.len(), 20, - "all 20 short turns fit the budget — the packer, not a count, decides" + "all 20 turns are delivered, whatever the budget" ); } - // what this catches: BREADTH OVER VERBATIM DEPTH (#128/#146, measured - // 2026-07-13: live persona prompts held THREE messages total in a busy - // room — the whole perceivable world — so any low-frequency speaker was - // displaced in seconds and the operator went unheard for hours). Long - // turns must render as head-trimmed summaries so a small budget holds - // MANY turns: the oldest (operator) message survives trimmed, the newest - // stays verbatim. Under the old whole-message packer this exact input - // delivered 3 items and the operator message was gone. + // what this catches: a head cut in the source (#128/#146 trimmed long turns to a + // per-turn cap before her view saw them, and NEVER CLIP THE NEWEST END). Every turn + // arrives whole at any budget; how much of the conversation she sees is the view's + // levels, and a turn it cannot fit leaves whole at a start, never as a cut head. #[tokio::test] - async fn small_budget_keeps_many_trimmed_turns_not_three_essays() { + async fn every_turn_arrives_whole_at_any_budget() { let room = RoomId::new(); let long = |tag: &str| format!("{tag}: {}", "lorem ipsum dolor sit amet ".repeat(15)); - let mut events = vec![event_in( - room, - Some(&long("OPERATOR your card is 0b1a6230")), - 1, - )]; - for (i, l) in (2..=5).enumerate() { - events.push(event_in(room, Some(&long(&format!("peer essay {i}"))), l)); - } - events.push(event_in(room, Some(&long("newest peer question")), 6)); - let reader = Arc::new(StubReader::new(events)); - let (source, _) = isolated_source(reader); - let delivery = source - .deliver(&ctx_in(room), 400, ResolutionPreference::Raw) - .await; - - assert!( - delivery.items.len() >= 6, - "breadth: all 6 turns fit a 400-token budget as trimmed heads, got {}", - delivery.items.len() - ); - assert!( - delivery.items[0].content.starts_with("OPERATOR") - && delivery.items[0].content.contains("trimmed"), - "oldest low-frequency speaker survives, trimmed: {:?}", - delivery.items[0].content - ); - let newest = &delivery.items.last().unwrap().content; - assert!( - newest.starts_with("newest peer question") && !newest.contains("trimmed"), - "the turn being responded to stays verbatim: {newest:?}" - ); - assert!( - delivery.tokens_used <= 400, - "budget honored: {}", - delivery.tokens_used - ); + let texts: Vec = std::iter::once(long("OPERATOR your card is 0b1a6230")) + .chain((0..4).map(|i| long(&format!("peer essay {i}")))) + .chain(std::iter::once(long("newest peer question"))) + .collect(); + let events = texts.iter().enumerate().map(|(i, t)| event_in(room, Some(t), i as u64 + 1)).collect(); + let (source, _) = isolated_source(Arc::new(StubReader::new(events))); + let delivery = source.deliver(&ctx_in(room)).await; + let seen: Vec<&str> = delivery.items.iter().map(|i| i.content.as_str()).collect(); + assert_eq!(seen, texts.iter().map(String::as_str).collect::>(), "every turn, whole, in order"); } fn receipt_from(room: RoomId, peer: PeerId, thought: &str, act: &str, lamport: u64) -> TranscriptEvent { @@ -285,93 +254,35 @@ let (source, _) = isolated_source(Arc::new(StubReader::new(Vec::new()))); let render = |events: &Vec| { let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (items, _, read_through, _) = AircRagSource::pack_digest(&digest, 4_000, false, None); - (items.into_iter().map(|i| i.content).collect::>(), read_through.map(|e| e.event().lamport)) + AircRagSource::digest_items(&digest, false).into_iter().map(|i| i.content).collect::>() }; - let (before, read_before) = render(&events); + let before = render(&events); assert_eq!(before.len(), 4, "{before:?}"); assert!(before[1].starts_with("💭 thought two") && before[1].contains("2 act batches"), "the first run, folded, at its start: {:?}", before[1]); assert!(before[3].contains("thought three"), "the run after Kira's line is its own line: {:?}", before[3]); - assert_eq!(read_before, Some(5), "read through the newest receipt"); // Another receipt from Atlas: the open run at the tail grows; nothing before // it changes by a byte. events.push(receipt_from(room, atlas, "thought four", "code/shell cat ✓", 6)); - let (after, read_after) = render(&events); + let after = render(&events); assert_eq!(after.len(), 4); assert_eq!(&after[..3], &before[..3], "every line before the open run is byte-identical"); assert!(after[3].starts_with("💭 thought four") && after[3].contains("2 act batches"), "{:?}", after[3]); - assert_eq!(read_after, Some(6)); } - // what this catches (Cormac on #4806, point 2): in a receipts-only room the window - // starts on an OPEN run; keyed on the run's newest receipt the anchor looked - // scrolled out on every receipt and jumped each turn. Keyed on the run's first - // receipt it holds while the run grows. + // what this catches (Cormac on #4806, point 2): a receipts-only room is one open run + // that grows as one folded line at its first receipt, so the window's head holds. #[test] - fn an_open_run_at_the_window_start_holds_the_anchor_while_it_grows() { + fn an_open_run_at_the_window_start_stays_one_line_while_it_grows() { let room = RoomId::new(); let atlas = PeerId::new(); - let mut events: Vec = (1..=3).map(|l| receipt_from(room, atlas, &format!("thought {l}"), "code/read a ✓", l)).collect(); + let events: Vec = (1..=4).map(|l| receipt_from(room, atlas, &format!("thought {l}"), "code/read a ✓", l)).collect(); let (source, _) = isolated_source(Arc::new(StubReader::new(Vec::new()))); - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (_, _, _, a0) = AircRagSource::pack_digest(&digest, 4_000, false, None); - let a0 = a0.expect("an anchor"); - events.push(receipt_from(room, atlas, "thought 4", "code/read b ✓", 4)); - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (items, _, _, a1) = AircRagSource::pack_digest(&digest, 4_000, false, Some(a0)); - assert_eq!(a1, Some(a0), "the open run grew; its first receipt is still the start"); + let digest = source.builder.build_from_events(persona(), room.as_uuid(), events, 0, 0); + let items = AircRagSource::digest_items(&digest, false); assert_eq!(items.len(), 1); assert!(items[0].content.starts_with("💭 thought 4") && items[0].content.contains("4 act batches"), "{:?}", items[0].content); } - // what this catches (Cormac's 5090 trace, 2026-10-05: 20-75 s of re-prefill per - // turn): the window's START holds still across turns while the suffix from it - // fits, so the first history message is byte-identical turn to turn and the - // engine's prefix survives; when it no longer fits, the start jumps FORWARD with - // HISTORY_SLACK of headroom, once, then holds again. Newest-first filling moved - // it by one line on every room event. - #[test] - fn the_history_start_holds_still_and_jumps_in_blocks() { - let room = RoomId::new(); - let (source, _) = isolated_source(Arc::new(StubReader::new(Vec::new()))); - let line = |l: u64| event_in(room, Some(&format!("peer{l}: line number {l} of the room, said with enough words that each line costs a real share of the window")), l); - let mut events: Vec = (1..=120).map(line).collect(); - let budget = 300; // ~ sixty of these lines: half the room - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - // The first fill in a room shows everything the budget holds. - let (_, tokens0, _, a0) = AircRagSource::pack_digest(&digest, budget, false, None); - let a0 = a0.expect("an anchor"); - assert!(tokens0 <= budget && tokens0 > ((budget as f32) * (1.0 - HISTORY_SLACK)) as u32, "full: {tokens0} of {budget}"); - // One more event: the suffix from that start no longer fits, so the start - // jumps ONCE, forward, with headroom. - events.push(line(121)); - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (items1, tokens1, _, a1) = AircRagSource::pack_digest(&digest, budget, false, Some(a0)); - let a1 = a1.expect("an anchor"); - assert_ne!(a1, a0, "the start jumped"); - assert!(tokens1 <= ((budget as f32) * (1.0 - HISTORY_SLACK)) as u32, "the jump left headroom: {tokens1}"); - let first1 = items1.first().unwrap().content.clone(); - // Several more: the start HOLDS and the first message stays byte-identical; - // the new lines extend the window instead of replacing its head. - events.push(line(122)); - events.push(line(123)); - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (items2, tokens2, _, a2) = AircRagSource::pack_digest(&digest, budget, false, Some(a1)); - assert_eq!(a2, Some(a1), "the start held"); - assert_eq!(items2.first().unwrap().content, first1, "the first history message did not change"); - assert!(tokens2 <= budget && items2.len() == items1.len() + 2, "{} → {}", items1.len(), items2.len()); - // Enough traffic that it cannot hold: one more jump, headroom again, newest shown. - for l in 124..=200 { - events.push(line(l)); - } - let digest = source.builder.build_from_events(persona(), room.as_uuid(), events.clone(), 0, 0); - let (items3, tokens3, _, a3) = AircRagSource::pack_digest(&digest, budget, false, Some(a1)); - let a3 = a3.expect("an anchor"); - assert_ne!(a3, a1); - assert!(tokens3 <= ((budget as f32) * (1.0 - HISTORY_SLACK)) as u32, "{tokens3}"); - assert!(items3.last().unwrap().content.contains("line number 200"), "the newest line is always shown"); - } - // what this catches: THE LOOP WAS THE WINDOW (2026-09-03) — a run of one // author's work receipts collapses to ONE unit (her newest thought + an act // tally) instead of N verbatim "I've been going in circles" lines; a chat @@ -392,7 +303,7 @@ let reader = Arc::new(StubReader::new(events)); let (source, _) = isolated_source(reader); let delivery = source - .deliver(&ctx_in(room), 4_000, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert_eq!( delivery.items.len(), @@ -448,14 +359,14 @@ // and the conversational path (receipts collapsed per author). let digest = source.builder.build_from_events(persona(), room.as_uuid(), events, 0, 0); for working in [false, true] { - let (items, _, _, _) = AircRagSource::pack_digest(&digest, 4_000, working, None); + let items = AircRagSource::digest_items(&digest, working); let seen: Vec<&str> = items.iter().map(|i| i.content.as_str()).collect(); assert_eq!(seen.len(), 2, "working={working}: only the two real lines survive: {seen:?}"); assert!(seen[0].starts_with("Kira:"), "{seen:?}"); assert!(seen[1].starts_with("Atlas:"), "a line DISCUSSING an envelope is speech: {seen:?}"); } // And the live path (the one every turn takes) delivers the same two. - let delivery = source.deliver(&ctx_in(room), 4_000, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx_in(room)).await; assert_eq!(delivery.items.len(), 2, "{:?}", delivery.items.iter().map(|i| &i.content).collect::>()); } @@ -469,7 +380,7 @@ let reader = Arc::new(StubReader::new(vec![event_in(room, Some("hi"), 1)])); let (source, _) = isolated_source(reader); let ctx = RagContext::for_persona(persona(), 1_000_000); // airc_room = None - let delivery = source.deliver(&ctx, 1_000, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx).await; assert_eq!( delivery.items.len(), 1, @@ -484,16 +395,16 @@ let reader = Arc::new(StubReader::new(vec![])); let (source, _) = isolated_source(reader); let ctx = RagContext::for_persona(persona(), 1_000_000); - let delivery = source.deliver(&ctx, 1_000, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx).await; assert!(delivery.items.is_empty()); } // what this catches: a pre-staged digest in the buffer is served WITHOUT // rebuilding (the hot path peeks the region's snapshot). We seed the buffer with // a digest the reader could not have produced, and confirm it's what's served. - // NOTE (#259): reuse now requires the staged digest to COVER the budget-derived - // window — the tiny budget here keeps that window at 1 so the staged snapshot - // qualifies; an under-grounded stage must be rebuilt wide instead (previous test). + // NOTE (#259): reuse requires the staged digest to hold at least what a rebuild would + // (the room's events after any top-up); here both hold one, so the stage is served, + // while an under-grounded stage is rebuilt wide instead (previous test). #[tokio::test] async fn serves_prestaged_digest_without_rebuild() { let room = RoomId::new(); @@ -511,7 +422,7 @@ buffer.publish((persona(), room.as_uuid()), Arc::new(staged)); let delivery = source - .deliver(&ctx_in(room), 8, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert_eq!(delivery.items.len(), 1); assert_eq!( @@ -529,10 +440,9 @@ let mut other = RagContext::for_persona(Uuid::new_v4(), 1_000_000); other.substrate.airc_room = Some(room); let delivery = source - .deliver(&other, 1_000, ResolutionPreference::Raw) + .deliver(&other) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: a reader error degrades to empty (cognition stays up), no @@ -544,31 +454,46 @@ reader.set_fail(true); let (source, _) = isolated_source(reader); let delivery = source - .deliver(&ctx_in(room), 1_000, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; assert!(delivery.items.is_empty()); assert_eq!(delivery.tokens_used, 0); } - // what this catches: budget caps the window — only the newest messages that fit - // are packed, and there is NO continuation cursor (the digest is the unit). + struct CursorReader { + events: Vec, + advanced: Mutex>, + } + #[async_trait] + impl AircTranscriptReader for CursorReader { + async fn page_recent(&self, limit: usize) -> Result, AircError> { + Ok(self.events.iter().take(limit).cloned().collect()) + } + async fn advance_read_cursor(&self, _persona: Uuid, _room: Uuid, event: &TranscriptEvent) -> Result<(), AircError> { + self.advanced.lock().unwrap().push(event.lamport); + Ok(()) + } + } + + // what this catches: delivery marking her read (it did, before any prompt existed, so + // a turn her view collapsed or an act that was refused still marked the room read, and + // running rag_inspect moved a resident's real cursor). Delivery moves nothing; the + // read receipt of a sent prompt moves it to exactly the event named, and an event the + // last digest does not hold moves nothing. #[tokio::test] - async fn budget_caps_window_no_continuation() { + async fn delivery_marks_nothing_read_and_the_receipt_marks_the_named_event() { let room = RoomId::new(); - let reader = Arc::new(StubReader::new(vec![ - event_in(room, Some("aaaaa"), 1), - event_in(room, Some("bbbbb"), 2), - event_in(room, Some("ccccc"), 3), - ])); - let (source, _) = isolated_source(reader); - let delivery = source - .deliver(&ctx_in(room), 4, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 2, "two newest fit budget 4"); - assert!( - !delivery.truncated, - "digest model has no continuation cursor" - ); + let events: Vec = (1..=3).map(|l| event_in(room, Some(&format!("line {l}")), l)).collect(); + let second = events[1].event_id.as_uuid(); + let reader = Arc::new(CursorReader { events, advanced: Mutex::new(Vec::new()) }); + let (source, _) = isolated_source(reader.clone()); + let delivery = source.deliver(&ctx_in(room)).await; + assert_eq!(delivery.items.len(), 3); + assert!(!delivery.truncated, "the digest has no continuation cursor"); + assert!(reader.advanced.lock().unwrap().is_empty(), "delivery is not reading"); + source.mark_read(room.as_uuid(), second).await; + source.mark_read(room.as_uuid(), Uuid::new_v4()).await; + assert_eq!(*reader.advanced.lock().unwrap(), vec![2], "read through exactly what her prompt rendered"); } struct StubHistory { @@ -631,7 +556,7 @@ })); let delivery = source - .deliver(&ctx_in(room), 400, ResolutionPreference::Raw) + .deliver(&ctx_in(room)) .await; let texts: Vec<&str> = delivery.items.iter().map(|i| i.content.as_str()).collect(); assert!( diff --git a/core/continuum-mind/src/persona/awareness_source.rs b/core/continuum-mind/src/persona/awareness_source.rs index d209cc2941..df31cc9802 100644 --- a/core/continuum-mind/src/persona/awareness_source.rs +++ b/core/continuum-mind/src/persona/awareness_source.rs @@ -7,8 +7,7 @@ use std::sync::Arc; use crate::persona::active_work_source::AircWorkReader; -use crate::cognition::rag_budget::{ RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference}; -use crate::persona::viewstate_rag::estimate_tokens; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::AWARENESS; @@ -18,7 +17,7 @@ const HEADING: &str = "Across your activities (loudest first):"; pub struct AwarenessRagSource { persona_id: uuid::Uuid, /// Her own airc handle, for the one fact the strip needs that her region does not - /// hold: whether she holds work. `None` in tests of the fit alone. + /// hold: whether she holds work. `None` when the offer cannot be computed. claims: Option>, } @@ -38,14 +37,23 @@ impl AwarenessRagSource { Self { persona_id, claims } } - /// Lines for the turn: the offer first when it applies (her continuation leads the - /// strip when she has one; the offer stands in its place when she has none). - async fn lines_for_turn(&self, snapshot: &crate::persona::awareness::AwarenessSnapshot, room: Option) -> Vec { - let mut lines = snapshot.render_lines_in(self.persona_id, room); + /// Keyed lines for the turn: the offer first when it applies (her continuation leads + /// the strip when she has one; the offer stands in its place when she has none). A + /// key is the identity of what the line describes, so the view re-appends a line only + /// when its activity's line changes. + async fn lines_for_turn(&self, snapshot: &crate::persona::awareness::AwarenessSnapshot, room: Option) -> Vec<(String, String)> { + // `render_lines_in` emits the continuation (if any) then one line per visible activity. + let mut keys: Vec = Vec::new(); + if snapshot.continuation.is_some() { + keys.push("continuation".to_owned()); + } + keys.extend(snapshot.visible().iter().map(|l| l.activity.to_string())); + let mut lines: Vec<(String, String)> = + keys.into_iter().zip(snapshot.render_lines_in(self.persona_id, room)).collect(); if snapshot.continuation.is_none() { if let Some(reader) = &self.claims { match reader.active_claims().await { - Ok(claims) if !claims.is_empty() => lines.insert(0, offer_line(claims.len())), + Ok(claims) if !claims.is_empty() => lines.insert(0, ("offer".to_owned(), offer_line(claims.len()))), Ok(_) => {} Err(e) => continuum_base::probe!( class = "mind.strip.claims_unreadable", @@ -58,34 +66,6 @@ impl AwarenessRagSource { } lines } - - /// The block, fitted to `budget`: the strip is loudest first, so dropping lines - /// from the END keeps what matters most. `None` = not even the heading and the - /// loudest line fit. - fn fit(lines: &[String], budget: u32) -> Option { - let mut kept: Vec<&str> = Vec::with_capacity(lines.len()); - for line in lines { - kept.push(line); - let text = Self::render(&kept); - if estimate_tokens(&text) > budget { - kept.pop(); - break; - } - } - if kept.is_empty() { - return None; - } - Some(Self::render(&kept)) - } - - fn render(lines: &[&str]) -> String { - let mut out = String::from(HEADING); - for line in lines { - out.push('\n'); - out.push_str(line); - } - out - } } #[async_trait::async_trait] @@ -94,99 +74,47 @@ impl RagSource for AwarenessRagSource { AWARENESS } - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - // Existing strip allowance: one short line per activity, window / 48. - crate::cognition::rag_budget::RagSourceBudget::floorless_share( - self.source_id(), - window, - headroom, - std::num::NonZeroU32::new(48).expect("existing nonzero source share"), - ) - } - fn expand_command(&self) -> Option<&'static str> { // The strip is already her whole awareness, reduced; nothing fuller to expand to. None } - fn floor_tokens(&self) -> u32 { - 0 - } - - async fn deliver(&self, ctx: &RagContext, budget: u32, resolution: ResolutionPreference) -> RagDelivery { - let empty = |res| RagDelivery { - source_id: AWARENESS.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: res, - }; + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { if ctx.persona_id != self.persona_id { - return empty(ResolutionPreference::Placeholder); + return RagDelivery::empty(AWARENESS); } let Some(snapshot) = crate::persona::perception_feed::awareness_of(self.persona_id, ctx.now_ms) else { - return empty(resolution); + return RagDelivery::empty(AWARENESS); }; let lines = self.lines_for_turn(&snapshot, ctx.airc_room.map(|r| r.as_uuid())).await; if lines.is_empty() { - return empty(resolution); + return RagDelivery::empty(AWARENESS); } - let Some(content) = Self::fit(&lines, budget) else { - continuum_base::probe!( - class = "mind.strip.unfit", - persona = %self.persona_id, - budget, - lines = lines.len() as u64, - "the strip's loudest line did not fit the grounding budget — she turns without her awareness" - ); - return empty(resolution); - }; - let tokens = estimate_tokens(&content); + // The heading is its own first item: the lines read as nothing without it. Each + // line follows, loudest first, as its own unit for the view to level. + let meta = serde_json::json!({ + "live_activities": snapshot.load.live_activities, + "unread_total": snapshot.load.unread_total, + }); + let mut items = Vec::with_capacity(lines.len() + 1); + items.push(RagItem::whole("heading", HEADING, meta.clone())); + items.extend(lines.iter().map(|(key, line)| RagItem::whole(key.clone(), line.clone(), meta.clone()))); + let delivery = RagDelivery::of(AWARENESS, items, false); continuum_base::probe!( class = "mind.strip.delivered", persona = %self.persona_id, lines_total = lines.len() as u64, - lines_shown = content.lines().count().saturating_sub(1) as u64, - tokens, - budget, + tokens = delivery.tokens_used, "her awareness strip is in this turn's grounding" ); - RagDelivery { - source_id: AWARENESS.to_string(), - items: vec![RagItem { - content, - tokens, - metadata: serde_json::json!({ - "lines_total": lines.len(), - "live_activities": snapshot.load.live_activities, - "unread_total": snapshot.load.unread_total, - }), - }], - tokens_used: tokens, - truncated: false, - resolution_used: resolution, - } + delivery } - } #[cfg(test)] mod tests { use super::*; - // what this catches: the strip is loudest first, so a budget that holds only part of - // it keeps the HEAD and drops the tail; a budget that holds not even the loudest line - // delivers nothing rather than a torn line. - #[test] - fn a_tight_budget_keeps_the_loudest_lines_and_never_tears_one() { - let lines: Vec = (0..6).map(|i| format!("[line {i}] something that happened in activity {i}")).collect(); - let full = AwarenessRagSource::fit(&lines, 10_000).expect("fits"); - assert_eq!(full.lines().count(), 7, "heading + six lines"); - let some = AwarenessRagSource::fit(&lines, estimate_tokens(&full) - 12).expect("fits a prefix"); - assert!(some.lines().count() < 7 && some.lines().nth(1) == Some(&lines[0][..]), "keeps the head: {some}"); - assert!(AwarenessRagSource::fit(&lines, 1).is_none(), "not even the loudest line: nothing, never a torn line"); - } - // what this catches: the offer names the verb and the count, and is an offer (the // word "writes one" — it never claims to have written anything). #[test] diff --git a/core/continuum-mind/src/persona/engram_source.rs b/core/continuum-mind/src/persona/engram_source.rs deleted file mode 100644 index 997d9e145e..0000000000 --- a/core/continuum-mind/src/persona/engram_source.rs +++ /dev/null @@ -1,478 +0,0 @@ -//! EngramSource — the first concrete `RagSource` implementation. -//! -//! Reads from a per-persona `AdmissionState`'s engram store + the -//! shared `RecallMetadataRegistry`, ranks engrams by salience × -//! recency, packs top-K into `RagItem`s within the budget. Persona- -//! scoped at construction. -//! -//! ### Doctrine alignment -//! -//! Per [[RTOS-brain-no-region-on-hot-path]]: the source's `deliver` -//! does its scoring + selection synchronously inside the call. No -//! I/O, no async wait. The expensive work (admission, decay, -//! consolidation) lives in the hippocampus's own tick — this source -//! just reads pre-staged state. -//! -//! Per the no-clipping doctrine -//! ([[docs/architecture/EVERY-MODEL-INCLUDED-VIA-L1-BUDGET.md]]): -//! atomic unit = one engram. Engrams that don't fit leave the delivery -//! stamped `truncated` — nothing resumes from here (ruling a); the caller -//! re-derives fresh under a bigger budget or drops the source. Mid-engram -//! truncation is structurally impossible. -//! -//! Per [[substrate-is-a-good-citizen-on-the-host]]: the metadata -//! field on every emitted `RagItem` carries provenance — engram_id, -//! kind, admitted_at_ms, score — so prompt assembly + sentinel -//! verifiers + future telemetry can trace what made it in. -//! -//! ### Scoring (slice 10 — simplified Algorithm 1+2) -//! -//! score = 0.6 × salience + 0.4 × recency_normalized -//! -//! - **salience** comes from `RecallMetadata.salience` (admission- -//! time default 0.5; decays per Algorithm 4; uplifts on recall -//! hits per slice 5's `record_recall_hit`). Floored at -//! `SALIENCE_FLOOR` from the anti-amnesia work, so engrams never -//! drop to invisible. -//! - **recency_normalized** is linear over 24h: engrams admitted -//! right now score ~1.0, engrams ≥ 24h old score 0.0. -//! -//! Future slices add: -//! - Algorithm 2 channel-bias (`ctx.airc_room` → boost when engram -//! origin matches the current room) -//! - Algorithm 2 structural relevance (engram graph activation -//! spreading from query embedding) -//! - Algorithm 2 topic similarity (vector cosine vs query -//! embedding once embeddings are wired through `RagContext`) -//! - Compressed resolution (engram summary instead of full content) - -use std::sync::Arc; - -use async_trait::async_trait; - -use crate::cognition::admission_state::AdmissionState; -use crate::cognition::engram::Engram; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; - -/// 24 hours in ms — the normalization window for the recency -/// score. Engrams older than this contribute 0 to the recency -/// component. Tunable via future `MemoryParameterAdapter`. -const RECENCY_WINDOW_MS: u64 = 24 * 60 * 60 * 1000; - -use crate::cognition::faculty_ids::ENGRAMS; - -/// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), -/// shared by every RAG source so the replay ledger's numbers match. (Was a private -/// copy — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - -/// Linear recency over `RECENCY_WINDOW_MS`. Returns 1.0 for -/// engrams admitted right at `now_ms`, 0.0 for engrams admitted -/// ≥ `RECENCY_WINDOW_MS` ago, linearly interpolated between. -fn recency_score(admitted_at_ms: u64, now_ms: u64) -> f32 { - if now_ms <= admitted_at_ms { - return 1.0; - } - let age_ms = now_ms - admitted_at_ms; - if age_ms >= RECENCY_WINDOW_MS { - return 0.0; - } - 1.0 - (age_ms as f32 / RECENCY_WINDOW_MS as f32) -} - -/// The composite score for ranking. 0.6 × salience + 0.4 × recency. -/// Slice 11+ will add channel-bias, structural relevance, topic -/// similarity. -fn composite_score(salience: f32, admitted_at_ms: u64, now_ms: u64) -> f32 { - 0.6 * salience + 0.4 * recency_score(admitted_at_ms, now_ms) -} - -/// Format an engram's content for inclusion in the prompt. Slice 10 -/// uses raw `engram.content`; slice 11+ may prefix with provenance -/// markers depending on the prompt-assembly contract. -fn format_engram_content(engram: &Engram, _resolution: ResolutionPreference) -> String { - engram.content.clone() -} - -/// EngramSource — persona-bound, reads from a shared AdmissionState. -/// -/// Holds an `Arc` so the same admission state is -/// shared with the admission pipeline + future cognition subsystems. -/// The recall metadata comes from `admission_state.recall_metadata()` -/// (a clone of the inner `Arc`). -pub struct EngramSource { - persona_id: uuid::Uuid, - admission_state: Arc, -} - -impl EngramSource { - pub fn new(persona_id: uuid::Uuid, admission_state: Arc) -> Self { - Self { - persona_id, - admission_state, - } - } - - /// Score + sort every engram in the store. Returns - /// `Vec<(score, engram)>` sorted by score descending. Pure - /// function over the admission state at a moment in time. - fn rank_engrams(&self, now_ms: u64) -> Vec<(f32, Engram)> { - let recall_meta = self.admission_state.recall_metadata().clone(); - let count = self.admission_state.engram_count(); - let mut scored: Vec<(f32, Engram)> = Vec::with_capacity(count); - for i in 0..count { - let Some(engram) = self.admission_state.engram_at(i) else { - continue; - }; - let salience = recall_meta - .get(engram.id) - .map(|m| m.salience) - .unwrap_or(0.5); - let score = composite_score(salience, engram.admitted_at_ms, now_ms); - scored.push((score, engram)); - } - // Sort by score descending; stable enough — same-score engrams - // tiebreak on admitted_at_ms descending to favor newer. - scored.sort_by(|a, b| { - b.0.partial_cmp(&a.0) - .unwrap_or(std::cmp::Ordering::Equal) - .then(b.1.admitted_at_ms.cmp(&a.1.admitted_at_ms)) - }); - scored - } - - /// Pack ranked engrams into RagItems within budget starting from - /// the given rank offset. Returns (items, tokens_used, - /// next_rank_or_done). next_rank is `scored.len()` if the - /// source delivered everything; otherwise it's the index of the - /// first engram that didn't fit (cursor for resume). - fn pack_from_rank( - &self, - scored: &[(f32, Engram)], - start_rank: usize, - budget: u32, - resolution: ResolutionPreference, - ) -> (Vec, u32, usize) { - let mut items = Vec::new(); - let mut tokens_used: u32 = 0; - let mut next_rank = start_rank; - for (idx, (score, engram)) in scored.iter().enumerate().skip(start_rank) { - let content = format_engram_content(engram, resolution); - let tokens = estimate_tokens(&content); - if tokens_used.saturating_add(tokens) > budget { - next_rank = idx; - break; - } - tokens_used += tokens; - items.push(RagItem { - content, - tokens, - metadata: serde_json::json!({ - "engram_id": engram.id.to_string(), - "kind": format!("{:?}", engram.kind), - "admitted_at_ms": engram.admitted_at_ms, - "score": score, - }), - }); - next_rank = idx + 1; - } - (items, tokens_used, next_rank) - } - - fn build_delivery( - &self, - items: Vec, - tokens_used: u32, - next_rank: usize, - scored_len: usize, - resolution: ResolutionPreference, - ) -> RagDelivery { - let truncated = next_rank < scored_len; - RagDelivery { - source_id: ENGRAMS.to_string(), - items, - tokens_used, - truncated, - resolution_used: resolution, - } - } -} - -#[async_trait] -impl RagSource for EngramSource { - fn source_id(&self) -> &'static str { - ENGRAMS - } - - fn expand_command(&self) -> Option<&'static str> { - Some("cognition/recall") - } - - /// MEASURED 40 tokens: one recalled engram line. The heavyweight's - /// *comfortable* size is far larger and it still gets that through `min` + - /// the grow pass — this is only what it needs to say ONE true thing. - fn floor_tokens(&self) -> u32 { - 48 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - // Defense-in-depth: refuse calls with the wrong persona ctx. - if ctx.persona_id != self.persona_id { - return RagDelivery { - source_id: ENGRAMS.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - }; - } - let scored = self.rank_engrams(ctx.now_ms); - let scored_len = scored.len(); - let (items, tokens_used, next_rank) = self.pack_from_rank(&scored, 0, budget, resolution); - self.build_delivery(items, tokens_used, next_rank, scored_len, resolution) - } - -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::cognition::admission_state::EngramOriginKind; - use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; - use uuid::Uuid; - - /// Build an AdmissionState wrapped in Arc, with `count` engrams - /// admitted via the raw store accessor + each tracked in the - /// recall metadata registry with a chosen salience. - fn fixture(count: usize, base_now_ms: u64) -> (uuid::Uuid, Arc) { - let persona = Uuid::parse_str("00000000-0000-0000-0000-000000000aaa").unwrap(); - let recall_meta = Arc::new(RecallMetadataRegistry::new()); - let state = Arc::new(AdmissionState::new(recall_meta.clone())); - - // Push N engrams directly. We bypass `admit` (which runs the - // full admission pipeline) to keep the test isolated to the - // source's scoring + packing behavior. - for i in 0..count { - let engram = Engram { - context_id: None, - id: Uuid::new_v4(), - kind: EngramKind::Episodic, - content: format!("engram body number {i}"), - origin: EngramOrigin::Chat(ChatMessageRef { - message_id: Uuid::new_v4(), - room_id: Uuid::new_v4(), - sender_id: Uuid::new_v4(), - posted_at_ms: base_now_ms.saturating_sub((i as u64) * 60_000), - content_hash: format!("hash-{i}"), - }), - recall_keys: Vec::new(), - admitted_at_ms: base_now_ms.saturating_sub((i as u64) * 60_000), - trust_state_at_admission: TrustState::ApprovedPeer, - admission_trace_id: None, - }; - // Test-only access: push through the engram_count-incrementing - // path. We can't easily push directly into the private store, - // so use admit_via_test_pushback (a test-only API) — except - // that doesn't exist. We'll use the admit() pipeline by - // constructing inbox messages... that's too complex for slice - // 10's purposes. - // - // Pragmatic alternative: add a test-only accessor on - // AdmissionState that lets tests push engrams directly. Done - // below — see admission_state.rs:`pub fn _push_for_test_only`. - state.push_for_test(engram.clone()); - recall_meta.admit( - engram.id, - RecallMetadata { - salience: 0.5 + (i as f32 * 0.05).min(0.5), - access_count: 0, - last_accessed_ms: 0, - protected_until_ms: 0, - last_decayed_ms: base_now_ms, - }, - ); - } - // Suppress unused warning — fixture pattern uses kind for future tests. - let _ = EngramOriginKind::Chat; - (persona, state) - } - - fn ctx_for(persona_id: uuid::Uuid, now_ms: u64) -> RagContext { - RagContext::for_persona(persona_id, now_ms) - } - - #[tokio::test] - async fn empty_store_delivers_nothing() { - let (persona, state) = fixture(0, 1_000_000_000); - let source = EngramSource::new(persona, state); - let delivery = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 1000, - ResolutionPreference::Raw, - ) - .await; - assert!(delivery.items.is_empty()); - assert_eq!(delivery.tokens_used, 0); - assert!(!delivery.truncated); - } - - #[tokio::test] - async fn single_engram_delivered_when_fits() { - let (persona, state) = fixture(1, 1_000_000_000); - let source = EngramSource::new(persona, state); - let delivery = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 1000, - ResolutionPreference::Raw, - ) - .await; - assert_eq!(delivery.items.len(), 1); - assert!(delivery.tokens_used > 0); - assert!(!delivery.truncated); - // Metadata carries the engram id. - assert!(delivery.items[0].metadata.get("engram_id").is_some()); - } - - #[tokio::test] - async fn oversized_engram_returns_truncated_with_zero_items() { - let (persona, state) = fixture(1, 1_000_000_000); - let source = EngramSource::new(persona, state); - // Budget of 0 tokens — the (small but nonzero) engram can't - // fit. Source returns 0 items + truncated so the caller sees it - // was cut and re-derives fresh under a bigger budget (ruling a: - // nothing resumes from here). - let delivery = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 0, - ResolutionPreference::Raw, - ) - .await; - assert_eq!(delivery.items.len(), 0); - assert_eq!(delivery.tokens_used, 0); - assert!(delivery.truncated); - } - - #[tokio::test] - async fn multi_engram_ranked_by_salience_descending() { - // 5 engrams with increasing salience (per fixture builder). - // Smallest budget that fits 2 engrams → top 2 by score should - // come out, in descending order. - let (persona, state) = fixture(5, 1_000_000_000); - let source = EngramSource::new(persona, state.clone()); - let delivery = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 100, // enough for a couple - ResolutionPreference::Raw, - ) - .await; - // Score is descending across items. - let scores: Vec = delivery - .items - .iter() - .map(|i| { - i.metadata - .get("score") - .and_then(|s| s.as_f64()) - .unwrap_or(0.0) - }) - .collect(); - for w in scores.windows(2) { - assert!(w[0] >= w[1], "scores not descending: {scores:?}"); - } - assert!(!delivery.items.is_empty()); - } - - #[tokio::test] - async fn truncation_flags_what_the_budget_could_not_fit() { - let (persona, state) = fixture(4, 1_000_000_000); - let source = EngramSource::new(persona, state); - // Budget tight enough to omit engrams — each engram body is ~6 - // tokens, so budget 12 fits only part of the four. Ruling a: no - // resumable handle; the flag says "more exists" and the next - // deliver re-derives from scratch (a larger budget simply fits more). - let first = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 12, - ResolutionPreference::Raw, - ) - .await; - assert!(!first.items.is_empty()); - assert!(first.truncated, "four engrams exist, budget fits fewer"); - - // Fresh re-derive with a budget that fits everything. - let second = source - .deliver( - &ctx_for(persona, 1_000_000_000), - 10_000, - ResolutionPreference::Raw, - ) - .await; - assert_eq!(second.items.len(), 4); - assert!(!second.truncated); - } - - #[tokio::test] - async fn cross_persona_ctx_returns_empty() { - let (persona, state) = fixture(3, 1_000_000_000); - let source = EngramSource::new(persona, state); - let other = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); - let delivery = source - .deliver( - &ctx_for(other, 1_000_000_000), - 1_000, - ResolutionPreference::Raw, - ) - .await; - assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); - } - - - - #[test] - fn recency_score_at_now_is_one() { - assert_eq!(recency_score(1_000_000_000, 1_000_000_000), 1.0); - } - - #[test] - fn recency_score_at_window_or_older_is_zero() { - let now = 24 * 60 * 60 * 1000_u64; - assert_eq!(recency_score(0, now), 0.0); - // older than the window — also 0. - assert_eq!(recency_score(0, now * 2), 0.0); - } - - #[test] - fn recency_score_halfway_is_half() { - let now = 24 * 60 * 60 * 1000_u64; - let half_window_ago = now / 2; - let score = recency_score(half_window_ago, now); - assert!((score - 0.5).abs() < 0.001, "got {score}"); - } - - #[test] - fn composite_score_weights_salience_more() { - // Same recency, higher salience → higher score. - let high = composite_score(1.0, 1_000_000_000, 1_000_000_000); - let low = composite_score(0.0, 1_000_000_000, 1_000_000_000); - assert!(high > low); - // Specifically, weight ratio should be 0.6 : 0.4. - // pure salience 1.0 at recency 1.0 = 0.6 * 1.0 + 0.4 * 1.0 = 1.0 - assert!((high - 1.0).abs() < 0.001); - // pure salience 0.0 at recency 1.0 = 0.0 + 0.4 = 0.4 - assert!((low - 0.4).abs() < 0.001); - } -} diff --git a/core/continuum-mind/src/persona/inference_profile.rs b/core/continuum-mind/src/persona/inference_profile.rs index f9404245f3..5258a2e142 100644 --- a/core/continuum-mind/src/persona/inference_profile.rs +++ b/core/continuum-mind/src/persona/inference_profile.rs @@ -89,36 +89,16 @@ pub struct SamplingProfile { /// sequence frequency, catching gap-separated loops the windowed /// penalty misses (#181). 0.0 = off. llama.cpp-family gateways only. pub frequency_penalty: f32, - /// Maximum tokens to generate per response. Derived from role's - /// `max_response_chars` divided by approximate chars-per-token - /// (typically 4 for English). - pub max_new_tokens: u32, -} - -/// Response-length fallback (tokens) when the role doesn't specify a budget. A ROLE concern, -/// not a model fact — so it lives here, not on `ModelSampling`. -/// -/// DERIVED from the live served window (an eighth of it), never a constant. This was -/// `pub const DEFAULT_MAX_NEW_TOKENS: u32 = 512` — inert today (role-budget wiring is still -/// reserved, see `profile_builder`) but it is the value that gets wired, and 512 tokens -/// truncates a real answer on ANY model. The whole point of a misfit grid is that the machine -/// decides how much room there is, not a literal. -/// [[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]] -pub fn default_max_new_tokens() -> u32 { - crate::cognition::context_budget::ContextBudget::live_or_floor().default_response_tokens() } impl SamplingProfile { - /// Project a persona sampling profile from the model's row-level decode - /// defaults (#76) plus the role's response budget. This is the ONE seam - /// that combines the two sources: model-level knobs (temperature, top-k/p, - /// the #181 anti-loop pair) come from [`ModelSampling`] on the `Model` row; - /// `max_new_tokens` is the role's length budget. Blessed/tuned models carry - /// their own `ModelSampling`; unblessed rows carry the floor. - pub fn from_model( - m: &crate::model_registry::types::ModelSampling, - max_new_tokens: u32, - ) -> Self { + /// Project a persona sampling profile from the model's row-level decode defaults (#76): + /// temperature, top-k/p and the #181 anti-loop pair, from [`ModelSampling`] on the `Model` + /// row. Blessed/tuned models carry their own `ModelSampling`; unblessed rows carry the + /// floor. Reply length is not here: it is the reply's claim in her prompt's one + /// allocation (FLOW-IMPLEMENTATION-PLAN §2d); a window-derived default sat here, read + /// by nothing. + pub fn from_model(m: &crate::model_registry::types::ModelSampling) -> Self { Self { temperature: m.temperature, top_k: m.top_k, @@ -126,7 +106,6 @@ impl SamplingProfile { repeat_penalty: m.repeat_penalty, repeat_last_n: m.repeat_last_n, frequency_penalty: m.frequency_penalty, - max_new_tokens, } } @@ -135,10 +114,7 @@ impl SamplingProfile { /// pair) live in exactly ONE place and can never drift from the Model row's /// default. Suitable when there is no model row (tests, scripted adapters). pub fn chat_defaults() -> Self { - Self::from_model( - &crate::model_registry::types::ModelSampling::default(), - default_max_new_tokens(), - ) + Self::from_model(&crate::model_registry::types::ModelSampling::default()) } } @@ -336,9 +312,6 @@ mod tests { assert_eq!(s.top_k, 40); assert_eq!(s.top_p, 0.95); assert_eq!(s.repeat_penalty, 1.1); - // Derived from the live window now (see `default_max_new_tokens`), so assert the - // relationship rather than a literal that would re-pin the clamp this removed. - assert_eq!(s.max_new_tokens, default_max_new_tokens()); } /// Round-trips through serde without dropping fields. camelCase on diff --git a/core/continuum-mind/src/persona/loop_dedup.rs b/core/continuum-mind/src/persona/loop_dedup.rs index 258f946ad2..6c7d89d34b 100644 --- a/core/continuum-mind/src/persona/loop_dedup.rs +++ b/core/continuum-mind/src/persona/loop_dedup.rs @@ -187,8 +187,10 @@ pub fn dedup_loop_filler(deliveries: &[RagDelivery]) -> Vec { } kept.push(item.clone()); } + let tokens_used = kept.iter().fold(0u32, |sum, item| sum.saturating_add(item.tokens)); out.push(RagDelivery { items: kept, + tokens_used, ..delivery.clone() }); } @@ -248,11 +250,14 @@ pub fn defer_as_loop_filler(incoming: &str, recent: &[String]) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::cognition::rag_budget::{RagDelivery, RagItem, ResolutionPreference}; + use crate::cognition::rag_budget::{RagDelivery, RagItem}; use serde_json::json; fn airc_item(content: &str, peer: &str) -> RagItem { RagItem { + key: String::new(), + summary: None, + pointer: None, content: content.to_string(), tokens: 1, metadata: json!({ "peer_id": peer }), @@ -265,7 +270,6 @@ mod tests { items, tokens_used: 0, truncated: false, - resolution_used: ResolutionPreference::Placeholder, } } @@ -365,11 +369,17 @@ mod tests { d.source_id = "room-doctrine".to_string(); d.items = vec![ RagItem { + key: String::new(), + summary: None, + pointer: None, content: repeated.to_string(), tokens: 1, metadata: json!({}), }, RagItem { + key: String::new(), + summary: None, + pointer: None, content: repeated.to_string(), tokens: 1, metadata: json!({}), diff --git a/core/continuum-mind/src/persona/media_perception_source.rs b/core/continuum-mind/src/persona/media_perception_source.rs index 7225279874..35ab630b91 100644 --- a/core/continuum-mind/src/persona/media_perception_source.rs +++ b/core/continuum-mind/src/persona/media_perception_source.rs @@ -1,13 +1,13 @@ //! `MediaPerceptionSource` — the live-call perception [`RagSource`]. //! //! Wraps a [`PerceptionBuffer`] and delivers the room AS IT IS NOW — who is visible + a -//! description of what they show — as budgeted [`RagItem`]s. Two disciplines, together: +//! description of what they show — as one [`RagItem`] per participant. Two disciplines, together: //! - **NON-BLOCKING**: reads only the cells RESOLVED so far (`current_percepts` → the //! `MediaFrame::*_if_ready` twins). A still-warming participant is simply absent this //! delivery, present the next — the turn NEVER waits ([[command-async-shape-prefer-stream-never-block]]). -//! - **BUDGETED**: perception must NOT dominate. It competes for context with -//! engram/airc/roster through the ONE flexbox allocator, stopping when its allotment is -//! spent ([[perception-feedback-must-not-blow-rag]], [[budget-at-assembly-not-clamp-the-prompt]]). +//! - **LEVELLED, NEVER SIZED**: every resolved participant is delivered with a `summary` +//! and a `pointer`; the ONE allocation in the prompt view decides how much of each +//! survives ([[perception-feedback-must-not-blow-rag]], [[budget-at-assembly-not-clamp-the-prompt]]). //! //! Delivers the TEXT percept (description grounding, available to ANY model). The //! thumbnail image for a native-vision persona rides the separate render seam (#190) off @@ -18,16 +18,16 @@ use std::sync::Arc; use async_trait::async_trait; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::media::{Percept, PerceptionBuffer}; use crate::runtime::SharedCompute; use crate::cognition::faculty_ids::MEDIA_PERCEPTION; -/// A persona's live-call visual perception, delivered as budgeted RAG grounding. +/// The verb that looks at a participant again. +const LOOK_COMMAND: &str = "perception/look"; + +/// A persona's live-call visual perception, delivered as RAG grounding. pub struct MediaPerceptionSource { persona_id: uuid::Uuid, /// The room-as-now frame hold (one latest frame per airc participant). @@ -64,15 +64,16 @@ impl MediaPerceptionSource { ), _ => return None, }; - let tokens = estimate_tokens(&content); - Some(RagItem { - content, - tokens, - metadata: serde_json::json!({ - "participant": p.participant, - "content_hash": p.content_hash, - }), - }) + let metadata = serde_json::json!({ + "participant": p.participant, + "content_hash": p.content_hash, + }); + // Coarser level: who is on the call, without the description. Pointer: how to look again. + Some( + RagItem::whole(p.participant.clone(), content, metadata) + .with_summary(format!("[seeing {}] visible on the call", short(&p.participant))) + .with_pointer(format!("[{} on the call — {LOOK_COMMAND}]", short(&p.participant))), + ) } } @@ -82,16 +83,6 @@ fn short(id: &str) -> &str { &id[..8.min(id.len())] } -fn empty_delivery() -> RagDelivery { - RagDelivery { - source_id: MEDIA_PERCEPTION.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - } -} - #[async_trait] impl RagSource for MediaPerceptionSource { fn source_id(&self) -> &'static str { @@ -99,54 +90,26 @@ impl RagSource for MediaPerceptionSource { } fn expand_command(&self) -> Option<&'static str> { - Some("perception/look") - } - - /// One resolved perception cell — who is visible / what is shown. A single - /// cell is a complete visual fact. - fn floor_tokens(&self) -> u32 { - 48 + Some(LOOK_COMMAND) } - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { // Persona-scoped: a cross-persona ctx gets nothing (defense in depth, same shape as // the roster/airc sources). if ctx.persona_id != self.persona_id { - return empty_delivery(); + return RagDelivery::empty(MEDIA_PERCEPTION); } // NON-BLOCKING read of the room as it is NOW — only cells resolved this tick. - let percepts = self.buffer.current_percepts(&self.compute); - let mut items: Vec = Vec::new(); - let mut tokens_used: u32 = 0; - for p in &percepts { - let Some(item) = Self::make_item(p) else { - continue; - }; - // BUDGET: perception must NOT dominate — stop when the allotment is spent. - // A truncated view is still truthful for the participants it names. - if tokens_used.saturating_add(item.tokens) > budget { - break; - } - tokens_used += item.tokens; - items.push(item); - } - - RagDelivery { - source_id: MEDIA_PERCEPTION.to_string(), - items, - tokens_used, - // Room-as-now, not a paginated history. - truncated: false, - resolution_used: resolution, - } + let items = self + .buffer + .current_percepts(&self.compute) + .iter() + .filter_map(Self::make_item) + .collect(); + // Room-as-now, not a paginated history. + RagDelivery::of(MEDIA_PERCEPTION, items, false) } - } #[cfg(test)] @@ -212,39 +175,31 @@ mod tests { ) } - // what this catches: a resolved percept becomes a budgeted "[seeing …] " grounding - // item; wrong persona gets nothing; a zero budget yields nothing (perception must not - // dominate). The core deliver contract. + // what this catches: a resolved percept becomes one "[seeing …] " item keyed by + // participant with a summary and a pointer; wrong persona gets nothing. The core + // deliver contract. #[tokio::test] - async fn delivers_resolved_percepts_as_budgeted_grounding() { + async fn delivers_resolved_percepts_as_levelled_grounding() { let pid = Uuid::new_v4(); let (src, _compute) = source_with_resolved_alice(pid).await; let ctx = RagContext::for_persona(pid, 0); - let d = src.deliver(&ctx, 10_000, ResolutionPreference::Raw).await; + let d = src.deliver(&ctx).await; assert_eq!(d.items.len(), 1, "one resolved participant → one item"); assert!( d.items[0].content.contains("seeing"), "grounds who is seen: {}", d.items[0].content ); + assert_eq!(d.items[0].key, "alice-peer"); + assert!(d.items[0].summary.as_deref().is_some_and(|s| s.contains("visible on the call"))); + assert!(d.items[0].pointer.as_deref().is_some_and(|p| p.contains("perception/look"))); assert!(d.tokens_used > 0); assert!(!d.truncated, "room-as-now, never paginated"); // Cross-persona → empty (defense in depth). let other = RagContext::for_persona(Uuid::new_v4(), 0); - assert!(src - .deliver(&other, 10_000, ResolutionPreference::Raw) - .await - .items - .is_empty()); - - // Zero budget → nothing (must NOT dominate context). - assert!(src - .deliver(&ctx, 0, ResolutionPreference::Raw) - .await - .items - .is_empty()); + assert!(src.deliver(&other).await.items.is_empty()); } // what this catches: NON-BLOCKING — a participant whose cells haven't resolved yet is @@ -267,7 +222,7 @@ mod tests { // (observe spawns a warm task, but we don't await it — read immediately.) let src = MediaPerceptionSource::new(pid, buffer, compute); let ctx = RagContext::for_persona(pid, 0); - let d = src.deliver(&ctx, 10_000, ResolutionPreference::Raw).await; + let d = src.deliver(&ctx).await; assert!( d.items.is_empty(), "unresolved participant is absent this tick, not awaited" diff --git a/core/continuum-mind/src/persona/mod.rs b/core/continuum-mind/src/persona/mod.rs index 43c3ae7ff4..0c51131bd5 100644 --- a/core/continuum-mind/src/persona/mod.rs +++ b/core/continuum-mind/src/persona/mod.rs @@ -50,7 +50,6 @@ pub mod cognition_pulse; pub mod substrate_governor; pub mod domain_classifier; pub mod durable_history; -pub mod engram_source; pub mod evaluator; pub mod host; pub mod hw_tier_descriptor; diff --git a/core/continuum-mind/src/persona/obligation.rs b/core/continuum-mind/src/persona/obligation.rs index df732261eb..1ff18b53f7 100644 --- a/core/continuum-mind/src/persona/obligation.rs +++ b/core/continuum-mind/src/persona/obligation.rs @@ -1,9 +1,9 @@ //! A persona's obligations: the turns she was admitted into and has not finished (card 920619c5). //! -//! A turn's trigger is marked read when its context is composed (`airc_source` advances the -//! read cursor on delivery), and after a restart `prime()` skips everything already in the -//! room. So a turn the stop cuts loses its trigger for good, which is why the stop waits up -//! to `turn_ingress::TURN_SETTLE_CAP` for turns in flight (enrico 2026-10-26: four stops, +//! A turn's trigger is marked read once a prompt that rendered it was sent and answered (the +//! deliberation faculty's read receipt), and after a restart `prime()` skips everything already +//! in the room. So a turn the stop cuts after that point loses its trigger for good, which is +//! why the stop waits up to `turn_ingress::TURN_SETTLE_CAP` for turns in flight (enrico 2026-10-26: four stops, //! 300 s each, 12 of 14 turns cut anyway). //! //! This module is the durable half of `wake_backlog::PendingInput`'s custody: one row per diff --git a/core/continuum-mind/src/persona/obligation/recover.rs b/core/continuum-mind/src/persona/obligation/recover.rs index 52c47fe2ac..38f7532b81 100644 --- a/core/continuum-mind/src/persona/obligation/recover.rs +++ b/core/continuum-mind/src/persona/obligation/recover.rs @@ -171,6 +171,7 @@ mod tests { defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }; crate::cognition::persona_workspace::global().register_from_cfg(cfg).unwrap() // unwrap: test fixture } diff --git a/core/continuum-mind/src/persona/profile_builder.rs b/core/continuum-mind/src/persona/profile_builder.rs index 3e98c7833b..71a01edbcb 100644 --- a/core/continuum-mind/src/persona/profile_builder.rs +++ b/core/continuum-mind/src/persona/profile_builder.rs @@ -190,10 +190,7 @@ pub fn build_profile( // profile uses the default budget. let chat_template = model.chat_template.clone(); let stop_sequences = model.stop_sequences.clone(); - let sampling = SamplingProfile::from_model( - &model.sampling, - crate::persona::inference_profile::default_max_new_tokens(), - ); + let sampling = SamplingProfile::from_model(&model.sampling); Ok(PersonaInferenceProfile { persona_id, @@ -394,12 +391,6 @@ mod tests { "the row's WIDER anti-loop window overrides the floor — per-model tuning is live" ); assert!((profile.sampling.frequency_penalty - 0.45).abs() < 1e-6); - // max_new_tokens is a ROLE budget, not a model fact — so it's the default, - // NOT carried from ModelSampling (which deliberately has no such field). - assert_eq!( - profile.sampling.max_new_tokens, - crate::persona::inference_profile::default_max_new_tokens() - ); } /// Tier-shaped n_gpu_layers: MSeries+ goes full GPU (-1), Compat diff --git a/core/continuum-mind/src/persona/rag_capture.rs b/core/continuum-mind/src/persona/rag_capture.rs index 1acd591a61..c888c3e574 100644 --- a/core/continuum-mind/src/persona/rag_capture.rs +++ b/core/continuum-mind/src/persona/rag_capture.rs @@ -13,7 +13,7 @@ //! ### What this module provides (slice 11 — capture side) //! //! - `RagCaptureEvent` — a tagged record of one fact in the turn -//! (TurnStart, BudgetAllocated, SourceDelivered, TurnEnd). +//! (TurnStart, SourceDelivered, TurnEnd). //! - `RagCaptureSink` trait — abstract recording surface. //! - `NoopRagCaptureSink` — production-safe default. Drops events on //! the floor; zero overhead when capture isn't in use. @@ -60,10 +60,7 @@ use std::sync::Mutex; use async_trait::async_trait; use serde::{Deserialize, Serialize}; -use crate::cognition::rag_budget::{ - BudgetAllocation, RagContext, RagDelivery, RagSource, RagSourceBudget, - ReservedTokens, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagSource}; //============================================================================= // EVENT MODEL — one fact about the turn, tagged @@ -83,19 +80,8 @@ pub enum RagCaptureEvent { captured_at_ms: u64, persona_id: uuid::Uuid, turn_id: Option, - context_window: u32, - reserved: ReservedTokens, - source_budgets: Vec, context: RagContext, }, - /// The budget allocator decided who gets what. Emitted by the - /// caller after `RagBudgetAdapter::allocate` returns. - BudgetAllocated { - captured_at_ms: u64, - persona_id: uuid::Uuid, - turn_id: Option, - allocation: BudgetAllocation, - }, /// A source delivered. Emitted by `RecordingRagSource` decorator /// automatically after every `deliver`. SourceDelivered { @@ -103,8 +89,6 @@ pub enum RagCaptureEvent { persona_id: uuid::Uuid, turn_id: Option, source_id: String, - budget_requested: u32, - resolution_requested: ResolutionPreference, delivery: RagDelivery, }, /// Caller signals the end of a turn. Optional — replay can @@ -120,7 +104,6 @@ impl RagCaptureEvent { pub fn persona_id(&self) -> uuid::Uuid { match self { Self::TurnStart { persona_id, .. } - | Self::BudgetAllocated { persona_id, .. } | Self::SourceDelivered { persona_id, .. } | Self::TurnEnd { persona_id, .. } => *persona_id, } @@ -129,7 +112,6 @@ impl RagCaptureEvent { pub fn turn_id(&self) -> Option { match self { Self::TurnStart { turn_id, .. } - | Self::BudgetAllocated { turn_id, .. } | Self::SourceDelivered { turn_id, .. } | Self::TurnEnd { turn_id, .. } => *turn_id, } @@ -248,7 +230,7 @@ impl RagCaptureSink for JsonlRagCaptureSink { /// /// ```ignore /// let source = RecordingRagSource::new( -/// EngramSource::new(persona_id, admission_state), +/// ViewStateRagSource::::per_room(rooms), /// capture_sink.clone(), /// ); /// ``` @@ -282,29 +264,13 @@ impl RagSource for RecordingRagSource { self.inner.expand_command() } - /// Delegates: capture is transparent, so the wrapped source's floor is the floor. - fn floor_tokens(&self) -> u32 { - self.inner.floor_tokens() - } - - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - self.inner.budget_claim(window, headroom) - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - let delivery = self.inner.deliver(ctx, budget, resolution).await; + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + let delivery = self.inner.deliver(ctx).await; let event = RagCaptureEvent::SourceDelivered { captured_at_ms: ctx.now_ms, persona_id: ctx.persona_id, turn_id: ctx.turn_id, source_id: self.inner.source_id().to_string(), - budget_requested: budget, - resolution_requested: resolution, delivery: delivery.clone(), }; if turn_is_private(ctx) { @@ -379,12 +345,8 @@ mod tests { RagContext::for_persona(persona(), 1_000_000) } - fn item(text: &str, tokens: u32) -> RagItem { - RagItem { - content: text.to_string(), - tokens, - metadata: serde_json::json!({}), - } + fn item(text: &str) -> RagItem { + RagItem::whole(text, text, serde_json::json!({})) } // ---- Sink-level tests ---- @@ -430,12 +392,6 @@ mod tests { captured_at_ms: 1_000, persona_id: persona(), turn_id: Some(Uuid::new_v4()), - context_window: 32_768, - reserved: ReservedTokens { - system: 500, - completion: 2_000, - }, - source_budgets: vec![], context: ctx(), }); sink.record(RagCaptureEvent::TurnEnd { @@ -486,12 +442,10 @@ mod tests { #[tokio::test] async fn recording_decorator_passes_through_delivery() { - let inner = StubRagSource::new("stub", persona(), vec![item("hello", 5), item("world", 5)]); + let inner = StubRagSource::new("stub", persona(), vec![item("hello"), item("world")]); let sink: Arc = Arc::new(InMemoryRagCaptureSink::new()); let recorder = RecordingRagSource::new(inner, sink.clone()); - let delivery = recorder - .deliver(&ctx(), 100, ResolutionPreference::Raw) - .await; + let delivery = recorder.deliver(&ctx()).await; // Wrapped source's items pass through. assert_eq!(delivery.items.len(), 2); // source_id pass-through. @@ -500,58 +454,29 @@ mod tests { #[tokio::test] async fn recording_decorator_records_each_deliver() { - let inner = StubRagSource::new("stub", persona(), vec![item("a", 5)]); + let inner = StubRagSource::new("stub", persona(), vec![item("a")]); let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); let recorder = RecordingRagSource::new(inner, sink_dyn); - recorder - .deliver(&ctx(), 100, ResolutionPreference::Raw) - .await; + recorder.deliver(&ctx()).await; let events = sink.events(); assert_eq!(events.len(), 1); match &events[0] { RagCaptureEvent::SourceDelivered { source_id, - budget_requested, - resolution_requested, delivery, .. } => { assert_eq!(source_id, "stub"); - assert_eq!(*budget_requested, 100); - assert_eq!(*resolution_requested, ResolutionPreference::Raw); assert_eq!(delivery.items.len(), 1); } other => panic!("expected SourceDelivered, got {other:?}"), } } - #[tokio::test] - async fn recording_decorator_records_truncated_delivery() { - let inner = StubRagSource::new( - "stub", - persona(), - vec![item("a", 5), item("b", 5), item("c", 5)], - ); - let sink = Arc::new(InMemoryRagCaptureSink::new()); - let sink_dyn: Arc = sink.clone(); - let recorder = RecordingRagSource::new(inner, sink_dyn); - // Budget tight enough that the stub truncates (one of three fits). - let first = recorder.deliver(&ctx(), 5, ResolutionPreference::Raw).await; - assert!(first.truncated, "stub has more than fit"); - let events = sink.events(); - assert_eq!(events.len(), 1); - match &events[0] { - RagCaptureEvent::SourceDelivered { delivery, .. } => { - assert!(delivery.truncated, "truncation must reach the capture record"); - } - other => panic!("expected SourceDelivered, got {other:?}"), - } - } - #[tokio::test] async fn recording_decorator_records_persona_and_turn_id() { - let inner = StubRagSource::new("stub", persona(), vec![item("a", 5)]); + let inner = StubRagSource::new("stub", persona(), vec![item("a")]); let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); let recorder = RecordingRagSource::new(inner, sink_dyn); @@ -560,7 +485,7 @@ mod tests { let mut ctx_with_turn = ctx(); ctx_with_turn.substrate.turn_id = Some(turn_id); recorder - .deliver(&ctx_with_turn, 100, ResolutionPreference::Raw) + .deliver(&ctx_with_turn) .await; let events = sink.events(); let ev = &events[0]; @@ -575,19 +500,19 @@ mod tests { persona_id: persona(), turn_id: Some(Uuid::new_v4()), source_id: "stub".to_string(), - budget_requested: 100, - resolution_requested: ResolutionPreference::Compressed, - delivery: RagDelivery { - source_id: "stub".to_string(), - items: vec![item("hi", 2)], - tokens_used: 2, - truncated: false, - resolution_used: ResolutionPreference::Compressed, - }, + delivery: RagDelivery::of("stub", vec![item("hi").with_summary("h").with_pointer("[hi]")], false), }; let json = serde_json::to_string(&event).unwrap(); let round: RagCaptureEvent = serde_json::from_str(&json).unwrap(); - // The kind discriminant survives. - assert!(matches!(round, RagCaptureEvent::SourceDelivered { .. })); + // The kind discriminant and the item levels survive. + match round { + RagCaptureEvent::SourceDelivered { delivery, .. } => { + assert_eq!(delivery.items[0].pointer.as_deref(), Some("[hi]")); + } + other => panic!("expected SourceDelivered, got {other:?}"), + } + // A line written before levels (budget fields, no key or levels) still reads. + let old = r#"{"kind":"source_delivered","captured_at_ms":1,"persona_id":"00000000-0000-0000-0000-000000000aaa","turn_id":null,"source_id":"stub","budget_requested":100,"resolution_requested":"raw","delivery":{"source_id":"stub","items":[{"content":"hi","tokens":2,"metadata":{}}],"tokens_used":2,"truncated":false,"resolution_used":"raw"}}"#; + assert!(serde_json::from_str::(old).is_ok(), "pre-levels captures replay"); } } diff --git a/core/continuum-mind/src/persona/rag_inspect.rs b/core/continuum-mind/src/persona/rag_inspect.rs index 6072a54b5c..38822407bd 100644 --- a/core/continuum-mind/src/persona/rag_inspect.rs +++ b/core/continuum-mind/src/persona/rag_inspect.rs @@ -30,6 +30,10 @@ //! - [[substrate-is-a-good-citizen-on-the-host]] — when `trace_path` //! is `None`, the sink is `NoopRagCaptureSink` (zero overhead). The //! hot path doesn't pay for observability it didn't ask for. +//! - Inspection is side-effect free: a source delivers everything it holds +//! and does not advance its read cursor on `deliver` (that is a separate +//! mark_read), and no budget is allocated here; her prompt view owns the +//! one allocation. //! - [[source-drain-is-the-universal-pattern]] — the inspection IS //! the drain for in-flight RAG decisions. Without it those //! decisions are sources without drains, which is the leak shape. @@ -42,10 +46,7 @@ use uuid::Uuid; use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::persona::airc_source::AircRagSource; -use crate::cognition::rag_budget::{ - BudgetAllocation, FlexboxRagBudgetAdapter, RagBudgetAdapter, RagContext, RagSource, - RagSourceBudget, ReservedTokens, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagSource}; use crate::persona::rag_capture::{ JsonlRagCaptureSink, NoopRagCaptureSink, RagCaptureEvent, RagCaptureSink, RecordingRagSource, }; @@ -79,12 +80,8 @@ pub const DEFAULT_INSPECT_WINDOW: u32 = 32_768; pub struct RagInspectionRequest { pub persona_id: Uuid, pub persona_name: String, + /// Reported back in the inspection; nothing is allocated against it here. pub context_window: u32, - pub reserved: ReservedTokens, - pub airc_floor: u32, - pub airc_max: u32, - pub airc_priority: u8, - pub airc_required: bool, pub airc_fetch_limit: usize, /// Wall-clock "now" the inspection should reason against. Caller /// supplies this so the function stays pure-of-clock (testable + @@ -132,47 +129,18 @@ impl RagInspectionRequest { Self::for_window(persona_id, persona_name, now_ms, profile.context_length) } - /// THE derivation both constructors share (#424 — `defaults_for` - /// previously hand-copied a flat `{system: 400, completion: 4_000, - /// airc_max: 20_000}` shape that had already drifted from this one). - /// - /// - reservation + headroom: [`ReservedTokens::scaled_for_window`]. - /// - `airc_max` = at most 60% of the window, AND at most the - /// post-reservation headroom. - /// - `airc_floor` clamps to `airc_max` so floor ≤ max always. + /// THE derivation both constructors share. The source delivers whole and her + /// prompt view owns the one allocation, so the window is only reported. pub fn for_window( persona_id: Uuid, persona_name: String, now_ms: u64, context_window: u32, ) -> Self { - let reserved = ReservedTokens::scaled_for_window(context_window); - let headroom = reserved.headroom_within(context_window); - // Default budget: ~60% of the context window for room - // history, clamped to headroom. This is a CONSERVATIVE - // FALLBACK — the substrate's real budgeter (TODO: routed - // through model characteristics on the Context per - // [[context-is-the-client-airc-token-is-identity]] and - // [[intent-driven-api-not-hot-patches]]) should derive - // this from `(prefill_tps, decode_tps, target_first_token_latency_ms)` - // so a 5090 + 200k-context frontier model can feed the - // whole history and a CPU + Qwen-0.5B can clamp itself. - // Both end up calling the SAME budget API; the answer - // differs because the model differs. Do NOT cap to a - // smaller percentage to make Intel Mac faster — that - // dumbs down every capable peer on the grid. - let airc_max = ((context_window as u64) * 6 / 10) as u32; - let airc_max = airc_max.min(headroom); - let airc_floor = 500_u32.min(airc_max); Self { persona_id, persona_name, context_window, - reserved, - airc_floor, - airc_max, - airc_priority: 10, - airc_required: true, airc_fetch_limit: 100, now_ms, trace_path: None, @@ -195,8 +163,7 @@ impl RagInspectionRequest { } } -/// The honest-look result. Carries the full allocation outcome PLUS -/// per-source delivery details with the mechanic-grade rationale +/// The honest-look result. Carries the per-source delivery details with the mechanic-grade rationale /// (score, lamport, peer-id-prefix, age, content preview). /// /// Specifically does NOT collapse layers — the future is multiple @@ -208,7 +175,6 @@ pub struct RagInspection { pub persona_id: Uuid, pub persona_name: String, pub context_window: u32, - pub allocation: BudgetAllocation, pub deliveries: Vec, /// Path to the JSONL trace if `trace_path` was set on the request, /// else `None`. Other AIs / mechanics resume replay against this. @@ -255,12 +221,10 @@ pub struct ModelResponseInspection { } /// Per-source delivery, with the substrate-grade detail every -/// inspection caller needs: requested budget, actual usage, -/// continuation flag, and the full list of items packed. +/// inspection caller needs: actual usage, continuation flag, and the full list of items packed. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SourceDeliveryInspection { pub source_id: String, - pub budget_requested: u32, pub tokens_used: u32, pub has_continuation: bool, pub items: Vec, @@ -277,6 +241,10 @@ pub struct InspectedItem { pub peer_id_prefix: String, pub lamport: u64, pub age_s: u64, + /// The item has a coarser summary level her view can fall back to. + pub has_summary: bool, + /// The item has a pointer level (what it is and how to reopen it). + pub has_pointer: bool, /// Full source-emitted metadata — sources may attach additional /// fields beyond the canonical ones above (e.g. event_id, /// room_id, admission_origin). Preserved verbatim for inspection @@ -314,8 +282,8 @@ pub async fn inspect_persona_rag( /// `model_response`. The prompt text + the actual response are /// captured so an inspector can re-run the model with the same /// prompt and compare. -/// - "Which layer is broken?" — `allocation.allocations` + per-source -/// deliveries (unchanged from the RAG-only path). +/// - "Which layer is broken?" — per-source deliveries and each item's +/// levels (whole, summary, pointer). /// - "Is this contextually relevant?" — per-item score + age + /// peer_id_prefix in the deliveries (unchanged). /// @@ -353,43 +321,14 @@ pub async fn inspect_persona_rag_with_inference( let mut ctx = ctx_base.clone(); ctx.substrate.turn_id = Some(turn_id); - let budgets = vec![RagSourceBudget { - source_id: "airc".to_string(), - priority: request.airc_priority, - floor_tokens: request.airc_floor, - min_tokens: request.airc_floor, - max_tokens: request.airc_max, - required: request.airc_required, - }]; - sink.record(RagCaptureEvent::TurnStart { captured_at_ms: request.now_ms, persona_id: request.persona_id, turn_id: Some(turn_id), - context_window: request.context_window, - reserved: request.reserved, - source_budgets: budgets.clone(), context: ctx.clone(), }); - let adapter = FlexboxRagBudgetAdapter::new(); - let allocation = adapter.allocate(&ctx, request.context_window, request.reserved, &budgets); - - sink.record(RagCaptureEvent::BudgetAllocated { - captured_at_ms: request.now_ms, - persona_id: request.persona_id, - turn_id: Some(turn_id), - allocation: allocation.clone(), - }); - - let airc_alloc = allocation - .allocations - .first() - .ok_or_else(|| "allocator returned no source allocations".to_string())?; - let budget_requested = airc_alloc.allocated_tokens; - let delivery = recorded - .deliver(&ctx, budget_requested, ResolutionPreference::Raw) - .await; + let delivery = recorded.deliver(&ctx).await; sink.record(RagCaptureEvent::TurnEnd { captured_at_ms: request.now_ms, @@ -438,6 +377,8 @@ pub async fn inspect_persona_rag_with_inference( peer_id_prefix, lamport, age_s, + has_summary: item.summary.is_some(), + has_pointer: item.pointer.is_some(), metadata: item.metadata.clone(), } }) @@ -455,10 +396,8 @@ pub async fn inspect_persona_rag_with_inference( persona_id: request.persona_id, persona_name: request.persona_name.clone(), context_window: request.context_window, - allocation, deliveries: vec![SourceDeliveryInspection { source_id: delivery.source_id.clone(), - budget_requested, tokens_used: delivery.tokens_used, has_continuation: delivery.truncated, items, diff --git a/core/continuum-mind/src/persona/rag_inspect/tests.rs b/core/continuum-mind/src/persona/rag_inspect/tests.rs index 89b37ec77e..c8f9488f5c 100644 --- a/core/continuum-mind/src/persona/rag_inspect/tests.rs +++ b/core/continuum-mind/src/persona/rag_inspect/tests.rs @@ -65,15 +65,7 @@ fn make_event(text: Option<&str>, lamport: u64, occurred_at_ms: u64) -> Transcri fn request(now_ms: u64) -> RagInspectionRequest { let mut req = RagInspectionRequest::defaults_for(persona(), "TestPersona".to_string(), now_ms); - // Tiny-local profile from the demo binary — reserves stay - // small so the tests assert behavior against a 4k context. req.context_window = 4_096; - req.reserved = ReservedTokens { - system: 200, - completion: 800, - }; - req.airc_floor = 100; - req.airc_max = 2_000; req } @@ -96,19 +88,7 @@ async fn empty_transcript_yields_empty_delivery() { assert!(!d.has_continuation); } -#[tokio::test] -async fn allocation_reports_satisfied_state_for_required_source_with_room() { - let reader = Arc::new(StubReader::new(vec![])); - let result = inspect_persona_rag(&request(1_000_000), reader) - .await - .unwrap(); - // 4096 - 200 system - 800 completion = 3096 available; airc gets max=2000 → Satisfied - assert!(!result.allocation.escalation_needed); - let airc_a = &result.allocation.allocations[0]; - assert_eq!(airc_a.source_id, "airc"); - assert_eq!(airc_a.allocated_tokens, 2_000); -} - +// what this catches: the glass box loses the per-item fields (score, age, peer, levels) a mechanic reads. #[tokio::test] async fn inspected_items_carry_score_age_and_peer_prefix() { let now_ms = 2_000_000u64; @@ -133,6 +113,8 @@ async fn inspected_items_carry_score_age_and_peer_prefix() { assert_eq!(it.age_s, 5); assert_eq!(it.peer_id_prefix.len(), 8); assert!(it.metadata.get("event_id").is_some()); + // levels are reported, whatever the source set + let _ = (it.has_summary, it.has_pointer); } #[tokio::test] @@ -140,8 +122,7 @@ async fn long_content_is_truncated_in_preview_but_tokens_remain_accurate() { // 1000-char message → preview is CONTENT_PREVIEW_CHARS chars; tokens are full message let msg: String = "x".repeat(1_000); let reader = Arc::new(StubReader::new(vec![make_event(Some(&msg), 1, 1_000_000)])); - let mut req = request(1_000_000); - req.airc_max = 10_000; // ample budget + let req = request(1_000_000); let result = inspect_persona_rag(&req, reader).await.unwrap(); let it = &result.deliveries[0].items[0]; assert_eq!(it.content_preview.chars().count(), CONTENT_PREVIEW_CHARS); @@ -152,28 +133,22 @@ async fn long_content_is_truncated_in_preview_but_tokens_remain_accurate() { ); } -// what this catches: under the slice-2 #43 digest contract the window is -// bounded by budget alone — pack_digest walks newest-first and TRUNCATES -// when the budget is exhausted; there is NO continuation cursor (the digest -// IS the window — more history is a scrollback command, not a budget page). -// A regression that re-introduced a continuation cursor, or that stopped -// truncating, would break this. +// what this catches: the inspect view sizing the conversation (FLOW plan §2d). The digest +// is delivered whole (there is no budget), with NO continuation cursor (more history is a +// scrollback command); her view, not the source, decides what of it she sees. #[tokio::test] -async fn tight_budget_truncates_the_window_with_no_continuation_cursor() { - // 4 items × ~2 tokens each ("ddddd" = 5 chars → chars/4 + 1 = 2 tokens), - // budget of 4 tokens fits only the 2 newest. +async fn delivers_the_whole_window_with_no_continuation_cursor() { let reader = Arc::new(StubReader::new(vec![ make_event(Some("aaaaa"), 1, 1_000_000), make_event(Some("bbbbb"), 2, 1_000_000), make_event(Some("ccccc"), 3, 1_000_000), make_event(Some("ddddd"), 4, 1_000_000), ])); - let mut req = request(1_000_000); - req.airc_floor = 4; - req.airc_max = 4; - let result = inspect_persona_rag(&req, reader).await.unwrap(); + let result = inspect_persona_rag(&request(1_000_000), reader) + .await + .unwrap(); let d = &result.deliveries[0]; - assert!(d.items.len() < 4, "tight budget truncates the window"); + assert_eq!(d.items.len(), 4, "the source delivers every staged turn"); assert!( !d.has_continuation, "the digest carries no continuation cursor by design" @@ -195,6 +170,7 @@ async fn reader_failure_surfaces_as_empty_delivery_not_panic() { // No panic — substrate-is-a-good-citizen } +// what this catches: the trace must be exactly the budget-free turn (start, delivered, end); a revived allocation event would break replay. #[tokio::test] async fn trace_path_writes_jsonl_lines() { let dir = tempfile::tempdir().unwrap(); @@ -209,14 +185,14 @@ async fn trace_path_writes_jsonl_lines() { let result = inspect_persona_rag(&req, reader).await.unwrap(); assert_eq!(result.trace_path.as_deref(), Some(trace.as_path())); let body = std::fs::read_to_string(&trace).unwrap(); - // Expect at least TurnStart, BudgetAllocated, SourceDelivered, TurnEnd + // Expect TurnStart, SourceDelivered, TurnEnd let line_count = body.lines().count(); assert!( - line_count >= 4, - "expected ≥4 capture events, got {line_count}" + line_count >= 3, + "expected ≥3 capture events, got {line_count}" ); assert!(body.contains("turn_start")); - assert!(body.contains("budget_allocated")); + assert!(!body.contains("budget_allocated")); assert!(body.contains("source_delivered")); assert!(body.contains("turn_end")); } diff --git a/core/continuum-mind/src/persona/room_board_source.rs b/core/continuum-mind/src/persona/room_board_source.rs index b7250ceae8..bc714b7b09 100644 --- a/core/continuum-mind/src/persona/room_board_source.rs +++ b/core/continuum-mind/src/persona/room_board_source.rs @@ -44,13 +44,11 @@ //! persona knows about the room's work, it does not decide WHETHER it speaks //! (that is doctrine). Whole board = all owners, so the source imposes no //! continuum-side ordering or filtering heuristic that would steer cognition -//! ([[no-hardcoded-heuristics-to-steer-cognition]]) — it delivers airc's own -//! card order and, under budget pressure, truncates with a logged count -//! rather than silently dropping or re-ranking. -//! - Atomic unit = ONE card. A truncated board is still truthful for the cards -//! it names, so (like the active-work source) this source truncates rather -//! than paginates; pagination can be added later without changing the seam if -//! boards grow past a single budget. +//! ([[no-hardcoded-heuristics-to-steer-cognition]]) — it delivers EVERY card, +//! ordered by what she can act on, and never takes a size: the one allocation +//! in her prompt view chooses each item's level (whole line, else the +//! card's pointer), so a long board shrinks oldest-first, never silently. +//! - Atomic unit = ONE card, keyed by its id. use continuum_base::time::EpochMs; use std::sync::Arc; @@ -60,31 +58,10 @@ use airc_work::BoardSnapshot; use async_trait::async_trait; use serde_json::json; -use crate::cognition::rag_budget::{ RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::ROOM_BOARD; -/// Most cards this source will render in full, per turn. -/// -/// NOT a token budget — a RELEVANCE bound. The per-card loop below used to be limited only -/// by whatever budget remained, so the board grew to fill the prompt: measured 2026-08-17, -/// 38 cards / 9,284 chars / 49.7% of an 18,697-char system prompt on a routine ambient turn. -/// That makes every citizen think slower as the backlog grows, which is exactly backwards -/// for a work board. -/// -/// Sized from what it MUST cover, not picked: the `[your work]` and `[available work]` leads -/// each name up to 5 cards, so the detailed render must be able to carry both (10) or the -/// summaries would promise cards the detail then omits — a citizen seeing "you hold 5" above -/// a list of 3 would reasonably read the substrate as inconsistent. Two spare keeps a -/// just-created card visible in the same turn it arrives. Ten is the floor this cannot go -/// below without re-deriving the lead caps with it. -const MAX_RENDERED_CARDS: usize = 12; - -/// Token estimate — the ONE canonical chars/4 estimator -/// (`cognition::token_budget`), shared by every RAG source so the replay -/// ledger's numbers match. -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// Reads the CURRENT ROOM's complete work board from airc. Production rides /// `airc_lib::Airc::work_board_complete` (the WHOLE board, not the recent /// window — an old active card must not drop off just because chat traffic @@ -288,16 +265,6 @@ impl RoomBoardSource { self } - fn empty() -> RagDelivery { - RagDelivery { - source_id: ROOM_BOARD.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - } - } - /// Render one card as a grounding line: the state (column), title, priority, /// and owner (or `unclaimed`) — the shape a teammate reads off the board. /// The whole board carries all owners, so owner is always surfaced (unlike @@ -316,7 +283,7 @@ impl RoomBoardSource { names: &dyn crate::cognition::card_holder::PeerNames, include_submission: bool, ) -> String { - let id8: String = card.card_id.as_uuid().to_string().chars().take(8).collect(); + let id8 = airc_core::shown_id::shown_form(card.card_id.as_uuid()); let held = crate::cognition::card_holder::holder(card, self_id, now_ms, names); // The tag leads with what the card IS to someone deciding whether to take // it, not with the column it happens to sit in — a lapsed claim is takeable @@ -387,7 +354,7 @@ fn claim_is_live(card: &airc_work::WorkCard, now_ms: u64) -> bool { /// times. The path is now in front of her each turn she holds the card. With no checkout on /// this node the line says nothing about one: an absence is not reported as a location. fn held_card_line(card: &airc_work::WorkCard, checkout: Option<&std::path::Path>) -> String { - let id8: String = card.card_id.as_uuid().to_string().chars().take(8).collect(); + let id8 = airc_core::shown_id::shown_form(card.card_id.as_uuid()); let line = format!(" {id8}: \"{}\" [{:?}]", card.title, card.state); match checkout { Some(path) => format!("{line}\n its work is at {}", path.display()), @@ -409,22 +376,9 @@ impl RagSource for RoomBoardSource { Some("work/list") } - /// MEASURED 26 tokens: the `[board] you hold N card(s); M claimable.` - /// headline, which is deliberately the first unit precisely so a - /// prefix-take cannot halve it. 32 gives it headroom for larger counts. - fn floor_tokens(&self) -> u32 { - 32 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { let working = crate::cognition::persona_workspace::acting_root_of(self.persona_id).is_some(); - self.deliver_with_workspace(ctx, budget, resolution, working) - .await + self.deliver_with_workspace(ctx, working).await } } @@ -432,17 +386,11 @@ impl RagSource for RoomBoardSource { impl RoomBoardSource { // The caller observes workspace custody; eligibility and rendering use the // same board snapshot regardless of whether open-deck detail is suppressed. - async fn deliver_with_workspace( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - working: bool, - ) -> RagDelivery { + async fn deliver_with_workspace(&self, ctx: &RagContext, working: bool) -> RagDelivery { // Persona-scoped: a cross-persona ctx gets nothing (defense in depth, // same shape as the wall / active-work / roster sources). if ctx.persona_id != self.persona_id { - return Self::empty(); + return RagDelivery::empty(ROOM_BOARD); } // Room resolution — TURN-PARAMETRIC (#443, measured live 2026-08-15). // This source used to be BOUND to the persona's bootstrap room and the @@ -474,7 +422,7 @@ impl RoomBoardSource { persona_id = %ctx.persona_id, "synthetic nil-room context — no board, and no fallback to the bound room" ); - return Self::empty(); + return RagDelivery::empty(ROOM_BOARD); } Some(t) => Some(t), None => self.room_id, @@ -490,7 +438,7 @@ impl RoomBoardSource { persona_id = %self.persona_id, "room_board: work_board failed — empty delivery, cognition stays up" ); - return Self::empty(); + return RagDelivery::empty(ROOM_BOARD); } }; // Empty board → no block (normal: a room may have no cards yet). @@ -510,12 +458,10 @@ impl RoomBoardSource { turn_room = ?ctx.airc_room.as_ref().map(|r| r.as_uuid()), "room-kanban delivered nothing: the READ SUCCEEDED and the board has zero cards" ); - return Self::empty(); + return RagDelivery::empty(ROOM_BOARD); } let mut items: Vec = Vec::new(); - let mut tokens_used: u32 = 0; - let mut dropped: usize = 0; // One clock reading per delivery — every lease judgment in this block // (held / lapsed / available) agrees on the same instant. let now_ms = continuum_base::time::EpochMs::now().millis(); @@ -587,39 +533,34 @@ impl RoomBoardSource { held = mine.len(), avail = open.len(), ); - let headline_tokens = estimate_tokens(&headline); - if headline_tokens <= budget { - tokens_used += headline_tokens; - items.push(RagItem { - content: headline, - tokens: headline_tokens, - metadata: json!({ - "kind": "board-headline", - "held_count": mine.len(), - "open_count": open.len(), - "open_lead_suppressed": working, - }), - }); - } + // No pointer: the headline is itself the shortest statement of the board. + items.push(RagItem::whole( + "headline", + headline, + json!({ + "kind": "board-headline", + "held_count": mine.len(), + "open_count": open.len(), + "open_lead_suppressed": working, + }), + )); } - // A title-only lead used to consume the budget before the separate card - // containing its signed verdict could fit. Keep the focused candidate's - // next action/evidence handle ahead of incidental board detail, within the - // same budget. This is one atomic, truthful unit, not unbounded review prose. + // The focused candidate's next action/evidence handle rides ahead of incidental + // board detail, as one atomic, truthful unit keyed by its card. let mut focused_submission = None; if let Some(card) = crate::persona::work_focus::focus_workspace_card(mine.iter().copied()) { if let Some(content) = Self::submission_guidance(card, &board) { - let tokens = estimate_tokens(&content); - if tokens_used.saturating_add(tokens) <= budget { - tokens_used += tokens; - focused_submission = Some(card.card_id); - items.push(RagItem { + focused_submission = Some(card.card_id); + let id8 = airc_core::shown_id::shown_form(card.card_id.as_uuid()); + items.push( + RagItem::whole( + format!("submission:{}", card.card_id.as_uuid()), content, - tokens, - metadata: json!({ "kind": "focused-submission", "card_id": card.card_id.as_uuid().to_string() }), - }); - } + json!({ "kind": "focused-submission", "card_id": card.card_id.as_uuid().to_string() }), + ) + .with_pointer(format!("[card {id8}] signed verdicts on its submission — work/submission")), + ); } } @@ -639,15 +580,10 @@ impl RoomBoardSource { released (work/release); your tools do the work.", n = mine.len(), ); - let lead_tokens = estimate_tokens(&lead); - if tokens_used.saturating_add(lead_tokens) <= budget { - tokens_used += lead_tokens; - items.push(RagItem { - content: lead, - tokens: lead_tokens, - metadata: serde_json::json!({ "kind": "your-work-lead" }), - }); - } + items.push( + RagItem::whole("lead:yours", lead, json!({ "kind": "your-work-lead" })) + .with_pointer(format!("[your work] you hold {} card(s) here — work/list", mine.len())), + ); } // The detailed available-work lead (#122): unclaimed cards are work waiting for @@ -684,7 +620,7 @@ impl RoomBoardSource { .iter() .take(5) .map(|c| { - let id8: String = c.card_id.as_uuid().to_string().chars().take(8).collect(); + let id8 = airc_core::shown_id::shown_form(c.card_id.as_uuid()); format!(" {id8}: \"{}\" ({:?})", c.title, c.priority) }) .collect::>() @@ -702,15 +638,14 @@ impl RoomBoardSource { work with your tools. Claimable work waits until someone chooses it.", n = open.len(), ); - let lead_tokens = estimate_tokens(&lead); - if tokens_used.saturating_add(lead_tokens) <= budget { - tokens_used += lead_tokens; - items.push(RagItem { - content: lead, - tokens: lead_tokens, - metadata: json!({ "kind": "available-work-lead", "open_count": open.len() }), - }); - } + items.push( + RagItem::whole( + "lead:available", + lead, + json!({ "kind": "available-work-lead", "open_count": open.len() }), + ) + .with_pointer(format!("[available work] {} card(s) claimable here — work/list", open.len())), + ); } // Resolve every DISTINCT non-self owner on this board to a published @@ -729,57 +664,30 @@ impl RoomBoardSource { } let names = self.reader.peer_names(&owner_peers).await; - // RELEVANCE ORDER + A HARD CAP, not "however many the budget happens to fit". - // - // Measured 2026-08-17 on a live ambient turn (capture 762a806b): this loop rendered - // 38 distinct cards into 9,284 chars — 49.7% of an 18,697-char system prompt, ~3,100 - // of the turn's ~12,286 prefill tokens. Every citizen paid it on every self-tick. - // - // Two things make that wrong rather than merely expensive: - // - // 1. IT IS REDUNDANT. The `[board]` headline and the `[your work]` / `[available - // work]` leads above already carry the counts and the top titles — and they were - // ADDED because this dump is unreliable under budget (see the Asha 2026-08-06 - // note above). Rendering the summary AND the exhaustive list means the same facts - // are paid for twice, and the expensive copy is the one that gets truncated. - // 2. IT SCALES THE WRONG WAY. Bounded only by remaining budget, the board grows to - // fill the prompt, so every citizen thinks SLOWER as the backlog grows. A team - // that accumulates work gets progressively less able to do it — the opposite of - // what a work board is for. - // - // So: order by what she can act on (her own holds first, then newest claimable — - // the same recency argument the available-work lead already makes), take at most - // `MAX_RENDERED_CARDS`, and let the leads plus `work/list` carry the tail. Counts in - // the headline stay the TRUE totals; nothing here makes the board smaller than it is, - // only shorter than it was. + // RELEVANCE ORDER, delivered whole. Her own holds first, then newest claimable + // (the same recency argument the available-work lead makes). Every card is + // delivered: when the prompt view must shrink it collapses the oldest cards to + // their pointers (measured 2026-08-17: 38 cards were 49.7% of a system prompt; + // that is the allocation's problem to solve by level, not a count cap here). let mut ordered: Vec<&airc_work::WorkCard> = board.cards.iter().collect(); ordered.sort_by_key(|c| { let mine_first = !(c.owner.map(|o| o.as_uuid()) == Some(self.persona_id)); // Negate for newest-first without needing a reversed comparator. (mine_first, std::cmp::Reverse(c.created_at_ms)) }); - let render_budget_cards = MAX_RENDERED_CARDS.min(ordered.len()); - let mut cards_delivered = 0usize; - for card in ordered.into_iter().take(render_budget_cards) { + for card in ordered { let content = Self::render(card, &board, self.persona_id, now_ms, &names, focused_submission != Some(card.card_id)); - let tokens = estimate_tokens(&content); - if tokens_used.saturating_add(tokens) > budget { - // Budget exhausted — a truncated board is still truthful for the - // cards it names. Count the drops so truncation is visible, not - // silent. Atomic unit = one card; no continuation (see module doc). - // Counted over CARDS, excluding the available-work lead item. - dropped = board.cards.len() - cards_delivered; - break; - // (unchanged: `dropped` is measured against the TRUE board size, so a - // budget-truncated render and a cap-truncated one report the same honest - // "how many did she not see".) - } - tokens_used += tokens; - cards_delivered += 1; + let id8 = airc_core::shown_id::shown_form(card.card_id.as_uuid()); + // The pointer keeps what a teammate decides on (the card and its takeable / + // held tag) once the line collapses; the title returns with `work/list`. + let tag = crate::cognition::card_holder::holder(card, self.persona_id, now_ms, &names).state_tag(); items.push(RagItem { + key: format!("card:{}", card.card_id.as_uuid()), + tokens: continuum_base::token_estimate::estimate_prompt_tokens(&content), content, - tokens, + summary: None, + pointer: Some(format!("[card {id8}] [{tag}] — work/list")), metadata: json!({ "card_id": card.card_id.as_uuid().to_string(), // Serde, NOT `format!("{:?}")`. Debug output is a developer convenience @@ -812,35 +720,15 @@ impl RoomBoardSource { }); } - // Cap-truncation counts as dropped just like budget-truncation. Without this the - // debug line would report dropped=0 on a capped board and the shortening would be - // invisible in the one place an operator looks for it. - if dropped == 0 && cards_delivered < board.cards.len() { - dropped = board.cards.len() - cards_delivered; - } - - // Budget too small to carry even one card → no block. - if items.is_empty() { - return Self::empty(); - } - + let delivery = RagDelivery::of(ROOM_BOARD, items, false); tracing::debug!( persona_id = %self.persona_id, - budget, cards = board.cards.len(), - delivered = items.len(), - dropped, - tokens_used, + delivered = delivery.items.len(), + tokens_used = delivery.tokens_used, "room_board: deliver" ); - - RagDelivery { - source_id: ROOM_BOARD.to_string(), - items, - tokens_used, - truncated: false, - resolution_used: resolution, - } + delivery } } diff --git a/core/continuum-mind/src/persona/room_board_source/tests.rs b/core/continuum-mind/src/persona/room_board_source/tests.rs index 6c146533fe..c0a8730057 100644 --- a/core/continuum-mind/src/persona/room_board_source/tests.rs +++ b/core/continuum-mind/src/persona/room_board_source/tests.rs @@ -81,7 +81,7 @@ let reader = Arc::new(StubReader::new(snapshot(cards))); let source = RoomBoardSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 4_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let lead = delivery .items @@ -178,21 +178,14 @@ // renders into the [room-kanban] grounding block — every card with its // column, title, priority, and owner. This is the Observer perceiving the // board (task #117 O6), distinct from active-work's own-claims-only view. - // what this catches: THE BOARD EATING THE PROMPT. The per-card loop used to be bounded - // only by remaining budget, so it grew with the backlog — measured live 2026-08-17 at 38 - // cards / 9,284 chars / 49.7% of an 18,697-char system prompt on a routine ambient turn, - // ~3,100 of ~12,286 prefill tokens, paid by every citizen on every self-tick. The - // property that makes it a defect and not just a cost: a team accumulating work gets - // progressively SLOWER at doing it. - // - // Pins all three halves of the fix — the cap holds, her OWN card survives the cut even - // when it is the oldest on the board (relevance order, not board order), and the headline - // still reports the TRUE totals so nothing is hidden, only shortened. + // what this catches: the board delivering a SLICE. Sources no longer take a size or a + // count cap (the one allocation in her prompt view picks each item's level), so a + // 41-card board delivers 41 keyed cards in relevance order — her OWN card first even + // when it is the oldest — each with a pointer to collapse to, and the headline still + // reports the true totals. #[tokio::test] - async fn a_large_board_is_capped_and_keeps_her_own_card_first() { + async fn a_large_board_delivers_every_card_keyed_with_her_own_first() { let mut cards: Vec = Vec::new(); - // Hers, and DELIBERATELY the oldest — under the old board-order loop with a cap this - // would be the first thing cut, which is the worst possible card to lose. let mut mine = card("MY held card", CardState::InProgress, Some( airc_core::PeerId::from_uuid(persona()), )); @@ -207,43 +200,29 @@ let reader = Arc::new(StubReader::new(snapshot(cards))); let source = RoomBoardSource::new(persona(), reader); - // A budget large enough that the CAP, not the budget, is what binds — otherwise this - // would pass for the old reason and prove nothing. - let delivery = source - .deliver(&ctx(), 100_000, ResolutionPreference::Raw) - .await; + let delivery = source.deliver(&ctx()).await; let rendered: Vec<&RagItem> = delivery .items .iter() - .filter(|i| i.metadata.get("card_id").is_some()) + .filter(|i| i.key.starts_with("card:")) .collect(); - assert!( - rendered.len() <= MAX_RENDERED_CARDS, - "board must be capped at {MAX_RENDERED_CARDS}, rendered {} of {total} — \ - an uncapped board grows into the prompt as the backlog grows", - rendered.len() - ); - assert!( - rendered.len() >= 10, - "the cap must still cover both 5-card leads, got {}", - rendered.len() - ); + assert_eq!(rendered.len(), total, "every card is delivered, none dropped for size"); assert!( rendered[0].content.contains("MY held card"), - "her OWN card must survive the cut and lead, even as the oldest on the board: {}", + "her OWN card leads, even as the oldest on the board: {}", rendered[0].content ); - // Counts stay TRUE — shortening the render must never shrink the reported board. + let keys: std::collections::HashSet<_> = rendered.iter().map(|i| i.key.as_str()).collect(); + assert_eq!(keys.len(), total, "one stable key per card"); + assert!(rendered.iter().all(|i| i.pointer.as_deref().is_some_and(|p| p.contains("work/list")))); + assert!(!delivery.truncated); let headline = &delivery.items[0]; + assert_eq!(headline.key, "headline"); assert_eq!(headline.metadata["kind"], "board-headline"); assert_eq!(headline.metadata["held_count"], 1); assert_eq!(headline.metadata["open_count"], 40); - assert!( - headline.content.contains("40 claimable"), - "headline reports the real total, not the rendered slice: {}", - headline.content - ); + assert!(headline.content.contains("40 claimable"), "{}", headline.content); } #[tokio::test] @@ -255,12 +234,13 @@ ]))); let source = RoomBoardSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; // Headline first, then the available-work lead, then the card list. assert_eq!(delivery.items.len(), 4); assert_eq!(delivery.items[0].metadata["kind"], "board-headline"); assert_eq!(delivery.items[1].metadata["kind"], "available-work-lead"); + assert_eq!(delivery.items[1].key, "lead:available"); let cards: Vec<&RagItem> = delivery .items .iter() @@ -288,10 +268,10 @@ // you HOLD 1 card" — and "[available work] 8 claimable" was unit two and died. // She then reported "no open tasks" and was CORRECT about what she could see, // in a room with 8 claimable cards. Four citizens looped on that all day. - // The FIRST unit must therefore state BOTH counts, and be small enough to - // survive a budget that delivers grounding at all. + // The FIRST unit must therefore state BOTH counts as one keyed, tiny item (the + // allocation collapses oldest-first, and the headline is never the oldest). #[tokio::test] - async fn the_first_board_unit_states_both_counts_so_a_prefix_take_cannot_halve_it() { + async fn the_headline_leads_and_states_both_counts_in_one_keyed_item() { let me = persona(); let mut held = card( "The card I hold", @@ -306,7 +286,7 @@ let reader = Arc::new(StubReader::new(snapshot(cards.clone()))); let source = RoomBoardSource::new(me, reader); let delivery = source - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let first = &delivery.items[0]; @@ -314,6 +294,8 @@ first.metadata["kind"], "board-headline", "the headline must LEAD" ); + assert_eq!(first.key, "headline"); + assert!(first.pointer.is_none(), "the headline is its own shortest statement"); assert!(first.content.contains("hold 1"), "{}", first.content); assert!(first.content.contains("2 claimable"), "{}", first.content); // Cheap enough that any budget delivering grounding at all delivers BOTH @@ -334,7 +316,7 @@ .collect(); let source = RoomBoardSource::new(me, Arc::new(StubReader::new(snapshot(local_cards)))); let full = source - .deliver_with_workspace(&ctx(), 2_000, ResolutionPreference::Raw, true) + .deliver_with_workspace(&ctx(), true) .await; let headline = &full.items[0]; assert_eq!(headline.metadata["kind"], "board-headline"); @@ -357,25 +339,6 @@ .count(), if local_hold { 3 } else { 2 } ); - let tight = source - .deliver_with_workspace(&ctx(), headline.tokens, ResolutionPreference::Raw, true) - .await; - assert_eq!(tight.items[0].content, headline.content); - assert_eq!(tight.items[0].metadata, headline.metadata); - assert!(tight.tokens_used <= headline.tokens); - let short = source - .deliver_with_workspace( - &ctx(), - headline.tokens - 1, - ResolutionPreference::Raw, - true, - ) - .await; - assert!(!short - .items - .iter() - .any(|item| item.metadata["kind"] == "board-headline")); - assert!(short.tokens_used < headline.tokens); } } @@ -398,7 +361,7 @@ Arc::new(StubReader::new(snapshot(vec![live, lapsed])).with_name(asha, "Asha")); let source = RoomBoardSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let cards: Vec<&RagItem> = delivery .items @@ -441,7 +404,7 @@ ]))); let source = RoomBoardSource::new(persona(), reader); let d = source - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; // Found by KIND, not by index: the headline now leads, and a test that // pins position breaks every time the delivery grows a unit. @@ -462,7 +425,7 @@ Some(holder), )]))); let d2 = RoomBoardSource::new(persona(), claimed_only) - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(d2.items.iter().all(|i| i.metadata.get("kind").is_none())); } @@ -474,7 +437,7 @@ let reader = Arc::new(StubReader::new(snapshot(vec![]))); let source = RoomBoardSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); assert_eq!(delivery.tokens_used, 0); @@ -493,10 +456,9 @@ reader.set_fail(true); let source = RoomBoardSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: cross-persona ctx gets nothing (defense in depth). @@ -510,14 +472,9 @@ let source = RoomBoardSource::new(persona(), reader); let alien = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); let delivery = source - .deliver( - &RagContext::for_persona(alien, 1_000_000), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona(alien, 1_000_000)) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: the your-work salience (2026-07-11, "did they wander @@ -559,23 +516,19 @@ // Reproduce the title-only starvation with the actual held-task title size: // the focused signed guidance fits, but repeating the title/details does not. board.cards[0].title = "Continuation-resume deletion PR: remove deliver_continuation machinery + positional cursor (ruling a) — caller inventory attached, closes prior review with record standing".into(); - let focused_cost = estimate_tokens(&RoomBoardSource::submission_guidance(&board.cards[0], &board).unwrap()); let reader = Arc::new(StubReader::new(board).in_room(room)); let source = RoomBoardSource::new(me, reader.clone()).for_room(room); let activity = RagContext::for_persona_in_room(me, ctx().now_ms, room); - // Production room-kanban desired allocation (rag_budget preset). - let delivery = source.deliver(&activity, 500, ResolutionPreference::Raw).await; - let headline_cost: u32 = delivery.items.iter() - .filter(|item| item.metadata.get("kind").and_then(|v| v.as_str()) == Some("board-headline")) - .map(|item| item.tokens).sum(); - let constrained_budget = headline_cost + focused_cost; - let constrained = source.deliver(&activity, constrained_budget, ResolutionPreference::Raw).await; - let constrained_text = constrained.items.iter().map(|item| item.content.as_str()).collect::>().join("\n"); - assert!(constrained_text.contains("Revise the work"), "{constrained_text}"); - assert!(constrained_text.contains(&candidate.submission_id.to_string())); - assert!(constrained_text.contains(&candidate.card_id.to_string())); - assert!(!constrained_text.contains("Continuation-resume deletion PR")); - assert!(constrained.tokens_used <= constrained_budget); + let delivery = source.deliver(&activity).await; + // what this catches: the focused signed verdict is its own keyed item with a + // pointer, and the held card still delivers whole beside it (no packing). + let focused = delivery.items.iter() + .find(|item| item.metadata.get("kind").and_then(|v| v.as_str()) == Some("focused-submission")) + .expect("focused submission item"); + assert_eq!(focused.key, format!("submission:{}", candidate.card_id.as_uuid())); + assert!(focused.content.contains("Revise the work")); + assert!(focused.pointer.is_some()); + assert!(delivery.items.iter().any(|item| item.content.contains("Continuation-resume deletion PR"))); let content = delivery.items.iter().map(|item| item.content.as_str()).collect::>().join("\n"); assert!(content.contains("Revise the work")); assert!(content.contains("all 32 signed verdicts, reviewers, and evidence")); @@ -585,7 +538,7 @@ assert!(!content.contains(&old.review_id.to_string())); assert_eq!(*reader.last_room.lock().unwrap(), Some(Some(room))); let elsewhere = RagContext::for_persona_in_room(me, ctx().now_ms, uuid::Uuid::new_v4()); - assert!(source.deliver(&elsewhere, 2_000, ResolutionPreference::Raw).await.items.is_empty()); + assert!(source.deliver(&elsewhere).await.items.is_empty()); assert_eq!(*reader.last_room.lock().unwrap(), Some(elsewhere.airc_room.map(|room| room.as_uuid()))); // Regression 04dc5e95: the production deferred wrapper must preserve the @@ -597,7 +550,6 @@ }; let deferred = DeferredFaculty::spawn(Arc::new( RagSourceFaculty::new(me, Arc::new(source), SaliencePolicy::StandingFraming) - .with_budget(500) .with_clock(Arc::new(|| ctx().now_ms)), )); let wake = uuid::Uuid::new_v4(); @@ -643,7 +595,7 @@ let reader = Arc::new(StubReader::new(snapshot(vec![mine, theirs]))); let source = RoomBoardSource::new(me, reader); let delivery = source - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let all: String = delivery .items @@ -694,7 +646,7 @@ let reader = Arc::new(StubReader::new(snapshot(vec![stale_mine, live_mine, closed_mine]))); let source = RoomBoardSource::new(me, reader); let delivery = source - .deliver(&ctx(), 2_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let all: String = delivery .items @@ -729,31 +681,6 @@ assert!(!closed.contains("claimable") && !closed.contains("resume it"), "{closed}"); } - // what this catches: a board too large for the budget truncates to the - // cards that fit and NEVER overspends — a truncated board is truthful for - // what it names, and truncation is bounded (no partial card, no overspend). - #[tokio::test] - async fn oversized_board_truncates_within_budget() { - // Each rendered card ~= tens of tokens; a tiny budget admits only a few. - let cards: Vec = (0..50) - .map(|i| card(&format!("card number {i}"), CardState::Open, None)) - .collect(); - let reader = Arc::new(StubReader::new(snapshot(cards))); - let source = RoomBoardSource::new(persona(), reader); - let delivery = source.deliver(&ctx(), 40, ResolutionPreference::Raw).await; - assert!( - !delivery.items.is_empty(), - "at least one card fits budget 40" - ); - assert!( - delivery.tokens_used <= 40, - "overspent: {} > 40", - delivery.tokens_used - ); - assert!(delivery.items.len() < 50, "truncated below the full board"); - assert!(!delivery.truncated); - } - // what this catches: the exam-bleed regression (glass-boxed live 2026-07-10, // Hermes-8B OURS 38% < RAW 52%) — a room-BOUND board delivering into a turn // in a DIFFERENT context. A turn stamped with another room (or the eval @@ -784,7 +711,7 @@ let same = RagContext::for_persona_in_room(p, 1_000, home); assert!( !source - .deliver(&same, 500, ResolutionPreference::Raw) + .deliver(&same) .await .items .is_empty(), @@ -799,7 +726,7 @@ let other = RagContext::for_persona_in_room(p, 1_000, bench); assert!( !source - .deliver(&other, 500, ResolutionPreference::Raw) + .deliver(&other) .await .items .is_empty(), @@ -817,7 +744,7 @@ let exam = RagContext::for_persona_in_room(p, 1_000, uuid::Uuid::nil()); assert!( source - .deliver(&exam, 500, ResolutionPreference::Raw) + .deliver(&exam) .await .items .is_empty(), @@ -833,7 +760,7 @@ let unstamped = RagContext::for_persona(p, 1_000); assert!( !source - .deliver(&unstamped, 500, ResolutionPreference::Raw) + .deliver(&unstamped) .await .items .is_empty(), diff --git a/core/continuum-mind/src/persona/room_doctrine_source.rs b/core/continuum-mind/src/persona/room_doctrine_source.rs index 18a909ce88..25399c06b7 100644 --- a/core/continuum-mind/src/persona/room_doctrine_source.rs +++ b/core/continuum-mind/src/persona/room_doctrine_source.rs @@ -36,17 +36,10 @@ use airc_core::doctrine::RoomDoctrinePublished; use airc_lib::AircError; use async_trait::async_trait; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::ROOM_DOCTRINE; -/// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), -/// shared by every RAG source so the replay ledger's numbers match. (Was a private -/// copy — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// Abstract reader over the airc room operating doctrine. Production /// rides on `airc_lib::Airc::room_doctrine`; tests stub it without a /// daemon. Mirrors the `AircRosterReader` rail. @@ -132,12 +125,8 @@ enum Outcome { /// The reader failed. Cognition stays up, but this is NOT the normal case and /// must never again look like one. ReadFailed, - /// A doctrine exists but the budget could not carry the marker plus real - /// content. - BudgetTooSmall, } - /// RoomDoctrineSource — persona-bound, reads the room doctrine from any /// `AircDoctrineReader`. pub struct RoomDoctrineSource { @@ -278,39 +267,12 @@ impl RoomDoctrineSource { self } - /// Fit the doctrine body to `budget` tokens. A doctrine is a single - /// contract; if it doesn't fit we deliver a truncated prefix (with a - /// marker) rather than dropping it entirely — partial guidance still - /// grounds the persona in the room's nature. - /// - /// Returns `None` (no block) when the budget is too small to carry - /// the marker PLUS some real content. The alternative — emitting a - /// `[Room operating doctrine]` block whose entire content is the - /// truncation marker — is strictly worse than no block: it spends - /// tokens to say nothing, and (with a naive char budget) overspends - /// the allocation. Both the no-content case and overspend are - /// guarded here. `estimate_tokens(s) = s.chars()/4 + 1`, so a string - /// of `4*budget - 4` chars estimates to exactly `budget` tokens — - /// that's the ceiling we fit the (truncated body + marker) under. - fn fit_body(body: &str, budget: u32) -> Option { - if budget == 0 { - return None; - } - if estimate_tokens(body) <= budget { - return Some(body.to_string()); - } - const MARKER: &str = "\n…[doctrine truncated]"; - let marker_chars = MARKER.chars().count(); - // Max chars whose estimate stays within `budget` tokens. - let max_chars = (budget as usize).saturating_mul(4).saturating_sub(4); - if max_chars <= marker_chars { - // No room for the marker plus any content → emit no block. - return None; - } - let char_budget = max_chars - marker_chars; - let mut out: String = body.chars().take(char_budget).collect(); - out.push_str(MARKER); - Some(out) + /// The doctrine's coarser level: its first paragraph (heading block), cut at a + /// blank line, never mid-text. `None` when the body is a single block already. + fn first_block(body: &str) -> Option<&str> { + let body = body.trim(); + let (first, rest) = body.split_once("\n\n")?; + (!rest.trim().is_empty()).then_some(first.trim_end()) } } @@ -320,45 +282,18 @@ impl RagSource for RoomDoctrineSource { ROOM_DOCTRINE } - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - // Existing task-124 allowance: 1024 at 16k, scaling with the window. - crate::cognition::rag_budget::RagSourceBudget::floorless_share( - self.source_id(), - window, - headroom, - std::num::NonZeroU32::new(16).expect("existing nonzero source share"), - ) - } - fn expand_command(&self) -> Option<&'static str> { // the room's doctrine is a single standing statement, delivered whole. None } - /// Floorless by design (unchanged): doctrine is lightweight standing - /// framing that takes leftover room rather than reserving any. - fn floor_tokens(&self) -> u32 { - 0 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - let empty = |res| RagDelivery { - source_id: ROOM_DOCTRINE.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: res, - }; + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + let empty = || RagDelivery::empty(ROOM_DOCTRINE); // Persona-scoped (defense in depth, same shape as the roster). if ctx.persona_id != self.persona_id { let _ = self.report(Outcome::CrossPersona, None, ctx.now_ms); - return empty(ResolutionPreference::Placeholder); + return empty(); } // Room resolution — TURN-PARAMETRIC (#443), the same shape RoomBoardSource // already uses and for the same reason: the rules she needs are the rules @@ -378,7 +313,7 @@ impl RagSource for RoomDoctrineSource { "synthetic nil-room context — no doctrine, and no fallback to the bound room" ); let _ = self.report(Outcome::NilRoom, Some(t), ctx.now_ms); - return empty(ResolutionPreference::Placeholder); + return empty(); } Some(t) => Some(t), None => self.room_id, @@ -394,7 +329,7 @@ impl RagSource for RoomDoctrineSource { // this variant must not re-tell that story in the other direction. Ok(None) => { let _ = self.report(Outcome::NotObservedInReadWindow, effective_room, ctx.now_ms); - return empty(resolution); + return empty(); } Err(err) => { tracing::warn!( @@ -403,41 +338,34 @@ impl RagSource for RoomDoctrineSource { "room_doctrine: read failed — empty delivery, cognition stays up" ); let _ = self.report(Outcome::ReadFailed, effective_room, ctx.now_ms); - return empty(ResolutionPreference::Placeholder); + return empty(); } }; - let Some(content) = Self::fit_body(&card.body, budget) else { - let _ = self.report(Outcome::BudgetTooSmall, effective_room, ctx.now_ms); - return empty(resolution); - }; - let tokens = estimate_tokens(&content); + let tokens = continuum_base::token_estimate::estimate_prompt_tokens(&card.body); tracing::debug!( persona_id = %self.persona_id, - budget, version = %card.version, tokens, "room_doctrine: deliver" ); let _ = self.report(Outcome::Delivered, effective_room, ctx.now_ms); - RagDelivery { - source_id: ROOM_DOCTRINE.to_string(), - items: vec![RagItem { - content, - tokens, - metadata: serde_json::json!({ - "version": card.version, - "published_by": card.published_by.as_uuid().to_string(), - "published_at_ms": card.published_at_ms, - }), - }], - tokens_used: tokens, - // One current contract per room; no pagination. - truncated: false, - resolution_used: resolution, + let metadata = serde_json::json!({ + "version": card.version, + "published_by": card.published_by.as_uuid().to_string(), + "published_at_ms": card.published_at_ms, + }); + // The doctrine has no expand verb today, so the pointer says so rather than + // naming one: collapsing it leaves a marker, not a way back. + let mut item = RagItem::whole("doctrine", card.body.as_str(), metadata) + .with_pointer(format!("[room doctrine {} (no expand verb; shown whole when the view has room)]", card.version)); + if let Some(first) = Self::first_block(&card.body) { + item = item.with_summary(first); } + // One current contract per room; no pagination. + RagDelivery::of(ROOM_DOCTRINE, vec![item], false) } } @@ -527,7 +455,7 @@ mod tests { let reader = Arc::new(StubReader::new(None)); let src = source(reader.clone(), room); - let d = src.deliver(&ctx_in(room), 4_000, ResolutionPreference::Raw).await; + let d = src.deliver(&ctx_in(room)).await; assert!(d.items.is_empty(), "no doctrine published — no block"); assert_eq!( src.observed_in(Some(room)), @@ -536,7 +464,7 @@ mod tests { ); reader.set_fail(true); - let d = src.deliver(&ctx_in(room), 4_000, ResolutionPreference::Raw).await; + let d = src.deliver(&ctx_in(room)).await; assert!(d.items.is_empty(), "a failed read still keeps cognition up"); assert_eq!( src.observed_in(Some(room)), @@ -640,7 +568,7 @@ mod tests { let src = RoomDoctrineSource::new(persona(), reader.clone()).for_room(bound); let ctx = RagContext::for_persona_in_room(persona(), 1_000_000, turn); - let out = src.deliver(&ctx, 4096, ResolutionPreference::Raw).await; + let out = src.deliver(&ctx).await; assert_eq!( reader.asked_room(), @@ -664,7 +592,7 @@ mod tests { let src = RoomDoctrineSource::new(persona(), reader.clone()).for_room(bound); let ctx = RagContext::for_persona_in_room(persona(), 1_000_000, uuid::Uuid::nil()); - let out = src.deliver(&ctx, 4096, ResolutionPreference::Raw).await; + let out = src.deliver(&ctx).await; assert!(out.items.is_empty(), "a nil-room context must receive no doctrine"); assert_eq!( @@ -684,7 +612,7 @@ mod tests { )))); let source = RoomDoctrineSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert_eq!(delivery.items.len(), 1); assert!(delivery.items[0].content.contains("Respond sparingly")); @@ -699,7 +627,7 @@ mod tests { let reader = Arc::new(StubReader::new(None)); let source = RoomDoctrineSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); assert_eq!(delivery.tokens_used, 0); @@ -713,7 +641,7 @@ mod tests { reader.set_fail(true); let source = RoomDoctrineSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); } @@ -725,62 +653,36 @@ mod tests { let source = RoomDoctrineSource::new(persona(), reader); let alien = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); let delivery = source - .deliver( - &RagContext::for_persona(alien, 1_000_000), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona(alien, 1_000_000)) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } - // what this catches: an over-budget doctrine is truncated and NEVER - // overspends the allocation — across the full budget regime, not just - // a comfortable one. The earlier version only checked budget=20 and - // missed that tiny budgets (1..=6) overspent with a content-free - // marker-only block (adversarial review of PR #1651). Invariant now: - // for ANY budget, either no block is delivered, or the delivered - // block fits the budget AND carries real content (not just the - // truncation marker). + // what this catches: the doctrine is delivered WHOLE with a stable key, a summary + // (its first block) and an honest pointer; nothing is cut to a size and no + // truncation marker appears -- the prompt view chooses the level later. #[tokio::test] - async fn oversized_doctrine_never_overspends_across_budget_regime() { - let big = "x".repeat(10_000); - for budget in [1u32, 2, 3, 5, 6, 7, 8, 20, 100, 500] { - let reader = Arc::new(StubReader::new(Some(card(&big)))); - let source = RoomDoctrineSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), budget, ResolutionPreference::Raw) - .await; - assert!( - delivery.tokens_used <= budget, - "budget {budget}: overspent ({} > {budget})", - delivery.tokens_used - ); - if let Some(item) = delivery.items.first() { - // A delivered block must carry real doctrine content, not - // just the truncation marker — else it spends tokens to - // say nothing. - let only_marker = - item.content.trim_start().starts_with('…') || !item.content.contains('x'); - assert!( - !only_marker, - "budget {budget}: delivered a content-free block: {:?}", - item.content - ); - } - } + async fn a_long_doctrine_is_delivered_whole_with_levels() { + let body = format!("# Rules\nBe brief.\n\n{}", "x".repeat(10_000)); + let reader = Arc::new(StubReader::new(Some(card(&body)))); + let source = RoomDoctrineSource::new(persona(), reader); + let delivery = source.deliver(&ctx()).await; + let item = &delivery.items[0]; + assert_eq!(item.key, "doctrine"); + assert_eq!(item.content, body, "whole body, never cut"); + assert!(!item.content.contains("truncated")); + assert_eq!(item.summary.as_deref(), Some("# Rules\nBe brief.")); + assert!(item.pointer.as_deref().is_some_and(|p| p.contains("v1abc"))); + assert!(!delivery.truncated); } - // what this catches: a budget too small to carry the marker plus real - // content yields NO block rather than a token-wasting marker-only one. + // what this catches: a one-block doctrine has no coarser level, so no summary is + // invented (the whole text is already its own summary). #[tokio::test] - async fn tiny_budget_emits_no_block() { - let big = "x".repeat(10_000); - let reader = Arc::new(StubReader::new(Some(card(&big)))); + async fn a_single_block_doctrine_has_no_summary() { + let reader = Arc::new(StubReader::new(Some(card("be excellent")))); let source = RoomDoctrineSource::new(persona(), reader); - let delivery = source.deliver(&ctx(), 3, ResolutionPreference::Raw).await; - assert!(delivery.items.is_empty(), "tiny budget must emit no block"); - assert_eq!(delivery.tokens_used, 0); + let delivery = source.deliver(&ctx()).await; + assert!(delivery.items[0].summary.is_none()); } } diff --git a/core/continuum-mind/src/persona/room_roster_source.rs b/core/continuum-mind/src/persona/room_roster_source.rs index 831dd255ea..dc87f94225 100644 --- a/core/continuum-mind/src/persona/room_roster_source.rs +++ b/core/continuum-mind/src/persona/room_roster_source.rs @@ -1,82 +1,21 @@ -//! RoomRosterSource — reads real airc room presence (`active_agents`) -//! and packages "who else is in this room right now" as RagItems for -//! the budget allocator. +//! The airc room-roster reader: who is present in a room, from airc presence. //! -//! ### Why this source exists +//! [`AircRosterReader`] abstracts airc room membership so the roster consumers +//! (the positron presence projection, the experience resolver, the room +//! directory) and their tests do not need a live airc daemon. The real impl +//! rides on `airc_lib::Airc`; stubs return canned `RoomMember`s. //! -//! The persona cognition loop binds `engram + airc` sources and grounds -//! the turn in recalled memory + recent transcript. But it had **no -//! grounding in who the other participants are** — the airc transcript -//! delivers messages tagged with other citizens' names, while the -//! system prompt only says "you are , never narrate others" -//! without ever naming who "others" are. Under that gap a small model -//! sees `BigMama:`, `Joel:`, `IntelMac:` in the history and role-plays -//! the whole room (the Ivar confabulation bug). -//! -//! This source closes the gap by reading the **truthful** presence list -//! from airc — not a static seed, not a guess — and delivering one item -//! per present citizen. The projection layer routes these into -//! **system-prompt grounding** (a `[Present in this room]` block), NOT -//! the conversation history (which would re-create the very "is this a -//! message?" confusion). See -//! [[docs/grid/AIRC-NATIVE-IDENTITY-ROOMS-SECURITY.md]] §5 slice 1. -//! -//! ### Architecture -//! -//! Mirrors [`AircRagSource`] exactly: abstracts an `AircRosterReader` -//! trait so unit tests don't need a live airc daemon. The real impl -//! rides on `airc_lib::Airc::active_agents` + `peer_alias` + -//! `peer_id` (self, to exclude the persona from its own roster). This -//! is the adapter-first rail: ship the trait + the real impl + a stub. -//! -//! ### Security grounding (per the airc-native doc §4) -//! -//! Each `AgentLiveness` carries a `runtime` label -//! (`"claude"`/`"codex"`/`"persona"`/`"interactive"`) — outsider agents -//! self-identify. The source carries that origin into item metadata so -//! downstream slices can mark grid-local citizens vs outsider agents and -//! let a persona weigh instructions by origin. Slice 1 only surfaces it; -//! enforcement is slice 3. -//! -//! ### Doctrine alignment -//! -//! - [[substrate-is-a-good-citizen-on-the-host]]: a failed presence read -//! returns an empty delivery + `tracing::warn` — cognition stays up -//! even when the airc subsystem is degraded. -//! - Persona-scoped at construction: a cross-persona ctx returns empty -//! (defense in depth, same shape as `AircRagSource`). -//! - Roster is small + always-current; no pagination (atomic unit = one -//! present citizen, like the `ToolSource` precedent in the trait doc). +//! The prompt's roster is NOT read here: a citizen's "who is here" is the SAME +//! `RosterViewState` the web roster renders, delivered by +//! `persona::viewstate_rag` (one definition, rendered two ways). The legacy +//! `RoomRosterSource` that read this trait directly into RAG items had no +//! production constructor and is gone. -use std::sync::Arc; use std::time::Duration; use airc_core::PeerId; use airc_lib::{AircError, RoomMember}; use async_trait::async_trait; -use continuum_positron::RosterSlotView; - -use crate::persona::roster_slot::roster_slot_from_member; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; - -/// Both roster adapters share the existing task-124 allowance (256 at 16k). -/// Content policy survives the legacy-to-ViewState identifier migration. -pub(crate) fn roster_budget_claim( - source_id: &str, - window: u32, - headroom: u32, -) -> crate::cognition::rag_budget::RagSourceBudget { - crate::cognition::rag_budget::RagSourceBudget::floorless_share( - source_id, - window, - headroom, - std::num::NonZeroU32::new(64).expect("existing nonzero roster share"), - ) -} - -use crate::cognition::faculty_ids::ROOM_ROSTER; /// How far back a heartbeat counts as "present". Matches the airc /// agent-liveness convention of a short recency window — a peer that @@ -89,11 +28,6 @@ pub const PRESENCE_WINDOW: Duration = Duration::from_secs(120); /// full scrollback. Passed straight to `Airc::room_roster`. pub const ROSTER_SCAN: usize = 200; -/// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), -/// shared by every RAG source so the replay ledger's numbers match. (Was a private -/// copy — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// Abstract reader over airc room membership. Production impl rides on /// `airc_lib::Airc::room_roster`; tests use a stub that returns canned /// `RoomMember`s without needing a daemon. @@ -214,586 +148,3 @@ impl AircRosterReader for airc_lib::Airc { Ok(members) } } - -/// RoomRosterSource — persona-bound, reads presence from any -/// `AircRosterReader`. -pub struct RoomRosterSource { - persona_id: uuid::Uuid, - /// The room whose presence this source grounds — see the room gate in - /// `deliver` and [`for_room`](Self::for_room). `None` = unscoped - /// (legacy/test construction): pre-gate behavior. - room_id: Option, - reader: Arc, -} - -impl RoomRosterSource { - pub fn new(persona_id: uuid::Uuid, reader: Arc) -> Self { - Self { - persona_id, - room_id: None, - reader, - } - } - - /// Bind this source to the room its reader answers for, so a context-stamped - /// turn in ANY other context (another room, the eval fork's nil room) gets an - /// empty delivery instead of this room's roster — a turn must never be told - /// who is present in a room it isn't in (the exam-bleed fix). - /// [[identity-context-session-three-axes]] - pub fn for_room(mut self, room_id: uuid::Uuid) -> Self { - self.room_id = Some(room_id); - self - } - - /// Format one present citizen as a roster grounding line from the neutral - /// [`RosterSlotView`] the shared projection produced. The line is - /// human-readable on its own; the structured parts also ride in metadata - /// so prompt-assembly and sentinel verifiers can render / trace without - /// re-parsing the string. - /// - /// Shape: ` []` plus ` — ` when the peer - /// reported one. Examples: `Aria [persona]`, `win-claude [claude] — busy` - /// (availability is airc's neutral label, carried through the slot). - fn format_line(name: &str, runtime: &str, availability: Option<&str>) -> String { - match availability { - Some(avail) => format!("{name} [{runtime}] — {avail}"), - None => format!("{name} [{runtime}]"), - } - } - - /// One present citizen → a grounding [`RagItem`], built from the SAME - /// neutral [`RosterSlotView`] the WS widget roster is built from (the - /// convergence #8/#13). Display name, runtime origin, availability and - /// recency are read off the slot — never re-derived here — so the persona - /// grounding and the widget roster can never disagree about who is present - /// or drop different fields. - fn make_item(slot: &RosterSlotView) -> RagItem { - let content = Self::format_line( - &slot.display_name, - &slot.provenance.runtime, - slot.availability.as_deref(), - ); - let tokens = estimate_tokens(&content); - RagItem { - content, - tokens, - // The service-loop projection reads metadata["display_name"] to - // populate other_persona_names (single-party history-drop): keep - // the bare name here, matching the transcript sender name. - metadata: serde_json::json!({ - "peer_id": slot.member_id.to_string(), - "display_name": slot.display_name, - "runtime": slot.provenance.runtime, - "availability": slot.availability, - "last_seen_ms": slot.last_seen_ms, - }), - } - } - - /// The room-authority fact for a room with NO human present — the - /// flywheel's self-authorization ground (Joel 2026-08-02: personas do real - /// work, then park on "Would you like me to proceed?" addressed to a room - /// where no one will ever answer). This is a PERCEPTION fact, not an - /// output gate ([[no-hardcoded-heuristics-to-steer-cognition]]): it tells - /// the persona the true authority structure of the room and lets her own - /// deliberation draw the conclusion. Emitted only when the roster carries - /// no human; a room WITH a human present says nothing (the roster lines - /// already name them, and deference to a present human is correct). - fn no_human_authority_item() -> RagItem { - let content = "[room] No human is present in this room. Questions addressed \ - to the room will not be answered by an operator — the work \ - board is the authority here. Choose work from the board and \ - proceed; report results, not requests for permission." - .to_string(); - let tokens = estimate_tokens(&content); - RagItem { - content, - tokens, - metadata: serde_json::json!({ "fact": "no_human_present" }), - } - } - - /// Is this roster runtime a HUMAN-facing interactive client? The SAME - /// classification `ipc/positron_presence.rs` applies (`"interactive"` → - /// Human, everything else → agent/persona kinds) — one rule, referenced in - /// both places; if the wire grows more human runtimes, both cite this fn. - fn is_human_runtime(runtime: &str) -> bool { - runtime == "interactive" - } -} - -#[async_trait] -impl RagSource for RoomRosterSource { - fn source_id(&self) -> &'static str { - ROOM_ROSTER - } - - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - roster_budget_claim(self.source_id(), window, headroom) - } - - fn expand_command(&self) -> Option<&'static str> { - // the roster IS the whole membership; there is no longer form to fetch. - None - } - - /// Floorless by design (unchanged): the roster is a handful of presence - /// lines and must never reserve budget away from the heavyweights. - fn floor_tokens(&self) -> u32 { - 0 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - // Persona-scoped: a cross-persona ctx gets nothing (defense in - // depth, same shape as AircRagSource). - if ctx.persona_id != self.persona_id { - return RagDelivery { - source_id: ROOM_ROSTER.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - }; - } - // Room resolution — TURN-PARAMETRIC (#443), the same shape RoomBoardSource - // uses. The peers she needs to see are the peers OF THE ROOM SHE IS - // STANDING IN; the stamped turn room wins, the bound room is only the - // fallback for UNSTAMPED contexts. A synthetic nil room gets NOTHING and - // does NOT fall back (the exam-bleed pin). - let effective_room = match ctx.airc_room.as_ref().map(|r| r.as_uuid()) { - Some(t) if t.is_nil() => { - continuum_base::probe!( - class = "rag.room_gate.abstain", - source = ROOM_ROSTER, - bound_room = ?self.room_id, - turn_room = %t, - persona_id = %ctx.persona_id, - "synthetic nil-room context — no roster, and no fallback to the bound room" - ); - return RagDelivery { - source_id: ROOM_ROSTER.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - }; - } - Some(t) => Some(t), - None => self.room_id, - }; - - // ONE airc call returns presence joined with display names - // (airc#1232). A failure is non-fatal — empty delivery, cognition - // stays up (good-citizen doctrine). - let members = match self - .reader - .room_roster(PRESENCE_WINDOW, ROSTER_SCAN, effective_room) - .await - { - Ok(m) => m, - Err(err) => { - tracing::warn!( - error = %err, - persona_id = %self.persona_id, - "room_roster: room_roster failed — empty delivery, cognition stays up" - ); - return RagDelivery { - source_id: ROOM_ROSTER.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: ResolutionPreference::Placeholder, - }; - } - }; - - let self_peer = self.reader.self_peer_id(); - - // STABLE ORDER (2026-09-01, Benchy's hit_rate=0.0): this source - // renders at ~0.4% depth of the prompt, and it iterated presence-scan - // order — which rotates as heartbeats land. Two consecutive prompts - // diverged at char ~226 on exactly this ("Kira, Joaquin, …" vs - // "Atlas, Kira, Joaquin, …" order), invalidating the entire KV tail - // behind it every turn while peers cached 0.38–0.56. Same set of - // members MUST render as the same bytes: sort by (name, peer id). - // Membership changes still re-render — that is honest change. - let mut members = members; - members.sort_by(|a, b| { - a.display_name - .cmp(&b.display_name) - .then_with(|| a.peer_id.as_uuid().cmp(&b.peer_id.as_uuid())) - }); - - // Authority structure (the flywheel's self-authorization ground): scan - // the FULL roster (self included — a persona is never a human, so this - // is equivalent, but scanning all members keeps the fact independent - // of the self-exclusion policy below) for any human-facing client. - let human_present = members.iter().any(|m| Self::is_human_runtime(&m.runtime)); - - let mut items: Vec = Vec::new(); - let mut tokens_used: u32 = 0; - if !human_present { - let fact = Self::no_human_authority_item(); - if fact.tokens <= budget { - tokens_used += fact.tokens; - items.push(fact); - } - } - for member in members { - // Exclude self — the roster grounds the persona in who is NOT - // itself. (room_roster includes self by design.) Self-exclusion is - // THIS source's own policy, applied before the shared projection — - // never baked into it (the widget roster keeps self). - if member.peer_id == self_peer { - continue; - } - // The ONE `RoomMember` → neutral slot projection, the same the WS - // widget roster uses. Name fallback, runtime origin, availability - // label and recency all resolve there, once. - let slot = roster_slot_from_member(&member); - let item = Self::make_item(&slot); - if tokens_used.saturating_add(item.tokens) > budget { - // Budget exhausted. Roster is unordered presence; we stop - // rather than paginate (atomic unit = one present citizen, no - // continuation). A truncated roster is still truthful for the - // citizens it names. - break; - } - tokens_used += item.tokens; - items.push(item); - } - - tracing::debug!( - persona_id = %self.persona_id, - budget, - present = items.len(), - tokens_used, - "room_roster: deliver" - ); - - RagDelivery { - source_id: ROOM_ROSTER.to_string(), - items, - tokens_used, - // Presence is always-current and small; no pagination. - truncated: false, - resolution_used: resolution, - } - } - -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Mutex; - use uuid::Uuid; - - fn persona() -> Uuid { - Uuid::parse_str("00000000-0000-0000-0000-000000000aaa").unwrap() - } - - fn ctx() -> RagContext { - RagContext::for_persona(persona(), 1_000_000) - } - - /// Test double — canned room members, optional failure. (airc joins - /// presence + names into `RoomMember` now; the stub returns them - /// directly — no separate alias map to maintain.) - struct StubReader { - self_peer: PeerId, - members: Vec, - fail: Mutex, - } - - impl StubReader { - fn new(self_peer: PeerId, members: Vec) -> Self { - Self { - self_peer, - members, - fail: Mutex::new(false), - } - } - fn set_fail(&self, fail: bool) { - *self.fail.lock().unwrap() = fail; - } - } - - #[async_trait] - impl AircRosterReader for StubReader { - fn self_peer_id(&self) -> PeerId { - self.self_peer - } - async fn room_roster( - &self, - _within: Duration, - _window: usize, - _room: Option, - ) -> Result, AircError> { - if *self.fail.lock().unwrap() { - return Err(AircError::UnknownPeer(PeerId::new())); - } - Ok(self.members.clone()) - } - } - - /// Build a `RoomMember` — `name: Some` mirrors a peer that published - /// an identity card; `None` mirrors present-but-unnamed. - fn member(peer: PeerId, runtime: &str, name: Option<&str>) -> RoomMember { - RoomMember { - peer_id: peer, - display_name: name.map(|s| s.to_string()), - runtime: runtime.to_string(), - availability: None, - last_seen_ms: 1_000_000, - } - } - - // what this catches (the flywheel self-authorization ground, Joel - // 2026-08-02 "personas do real work then park on 'Would you like me to - // proceed?'"): an agent/persona-only roster delivers the no-human - // authority FACT first — the true authority structure of the room — and a - // roster WITH a human ("interactive") delivers NO such fact (deference to - // a present human is correct, and the roster line already names them). - #[tokio::test] - async fn no_human_roster_carries_the_authority_fact_and_human_presence_silences_it() { - let me = PeerId::new(); - let agent = PeerId::new(); - let human = PeerId::new(); - - // Agents/personas only → the fact rides first. - let reader = Arc::new(StubReader::new( - me, - vec![member(agent, "persona", Some("Anwen"))], - )); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 2); - assert_eq!(delivery.items[0].metadata["fact"], "no_human_present"); - assert!( - delivery.items[0] - .content - .contains("work board is the authority"), - "the fact teaches the authority structure, not an instruction to be quiet" - ); - - // A human client present → no fact; only the roster lines. - let reader = Arc::new(StubReader::new( - me, - vec![ - member(agent, "persona", Some("Anwen")), - member(human, "interactive", Some("Operator")), - ], - )); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 2, "two peers, zero facts"); - assert!( - delivery - .items - .iter() - .all(|i| i.metadata.get("fact").is_none()), - "a room with a human present carries no authority fact" - ); - } - - // what this catches: the confabulation root cause — a present peer - // must surface in the roster with a real alias + its origin runtime, - // so the persona is grounded in who else is here. - #[tokio::test] - async fn present_peer_surfaces_with_alias_and_origin() { - let me = PeerId::new(); - let other = PeerId::new(); - let reader = Arc::new(StubReader::new( - me, - vec![member(other, "claude", Some("win-claude"))], - )); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - // Agent-only roster → the no-human authority fact rides FIRST, then - // the peer line (the flywheel self-authorization ground). - assert_eq!(delivery.items.len(), 2); - assert_eq!(delivery.items[0].metadata["fact"], "no_human_present"); - assert!(delivery.items[1].content.contains("win-claude")); - assert!(delivery.items[1].content.contains("claude")); - assert_eq!(delivery.items[1].metadata["runtime"], "claude"); - // The service-loop projection reads metadata["display_name"] to - // populate other_persona_names (single-party history-drop). Lock - // that contract: the bare name must be present and match the - // transcript sender name, not the formatted line. - assert_eq!(delivery.items[1].metadata["display_name"], "win-claude"); - assert!(!delivery.truncated); - } - - // what this catches: THE convergence guarantee — the persona grounding now - // carries availability + recency (the liveness the WS widget rail used to - // DROP through `AircPresenceSlot`), because both rails build from the one - // shared `roster_slot_from_member`. A regression that stopped threading - // these through the shared projection would silently blind the persona to - // who is busy/away and how recently they were seen. Availability is airc's - // neutral snake_case label (`busy`), not Debug's `Busy`. - #[tokio::test] - async fn availability_and_recency_carry_through_shared_projection() { - use airc_lib::AgentAvailabilityState; - let me = PeerId::new(); - let other = PeerId::new(); - let busy = RoomMember { - peer_id: other, - display_name: Some("win-claude".to_string()), - runtime: "claude".to_string(), - availability: Some(AgentAvailabilityState::Busy), - last_seen_ms: 1_700_000_000_000, - }; - let reader = Arc::new(StubReader::new(me, vec![busy])); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 2); - assert_eq!(delivery.items[1].content, "win-claude [claude] — busy"); - assert_eq!(delivery.items[1].metadata["availability"], "busy"); - assert_eq!( - delivery.items[1].metadata["last_seen_ms"], - 1_700_000_000_000_u64 - ); - } - - // what this catches: the persona must NOT appear in its own roster — - // the block is "who is NOT me". A self-entry would re-introduce the - // self/other confusion the source exists to remove. - #[tokio::test] - async fn self_peer_excluded_from_roster() { - let me = PeerId::new(); - let other = PeerId::new(); - let reader = Arc::new(StubReader::new( - me, - vec![member(me, "persona", None), member(other, "persona", None)], - )); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!( - delivery.items.len(), - 2, - "the fact + only the other peer, not self" - ); - assert_eq!( - delivery.items[1].metadata["peer_id"], - other.as_uuid().to_string() - ); - } - - // what this catches: a peer with no alias is still surfaced, never - // silently dropped — an unnamed citizen is worse than a labelled one for - // grounding. After the convergence it uses the SAME provisional label the - // WS widget projection uses (`peer-XXXXXXXX`, via the shared - // roster_slot_from_member) — one fallback-label decision, not a second form. - #[tokio::test] - async fn peer_without_alias_uses_shared_provisional_label() { - let me = PeerId::new(); - let other = PeerId::new(); - let reader = Arc::new(StubReader::new(me, vec![member(other, "codex", None)])); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!( - delivery.items.len(), - 2, - "the no-human fact + the unnamed peer" - ); - let simple = other.as_uuid().simple().to_string(); - let expected_label = format!("peer-{}", &simple[..8]); - assert_eq!( - delivery.items[1].content, - format!("{expected_label} [codex]"), - "unnamed peer uses the shared provisional label + its runtime origin" - ); - } - - // what this catches: an EMPTY room (nobody else present) still delivers the - // no-human authority fact — being alone is the STRONGEST self-authorization - // case (there is nobody to ask) — and nothing else, no panic. - #[tokio::test] - async fn empty_room_delivers_only_the_authority_fact() { - let me = PeerId::new(); - let reader = Arc::new(StubReader::new(me, vec![])); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 1); - assert_eq!(delivery.items[0].metadata["fact"], "no_human_present"); - assert_eq!(delivery.tokens_used, delivery.items[0].tokens); - } - - // what this catches: airc degraded → empty delivery, cognition stays - // up (good-citizen doctrine). A roster read failure must never take - // down the turn. - #[tokio::test] - async fn reader_error_returns_empty_no_panic() { - let me = PeerId::new(); - let other = PeerId::new(); - let reader = Arc::new(StubReader::new(me, vec![member(other, "persona", None)])); - reader.set_fail(true); - let source = RoomRosterSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) - .await; - assert!(delivery.items.is_empty()); - assert_eq!(delivery.tokens_used, 0); - } - - // what this catches: cross-persona ctx gets nothing (defense in - // depth) — a persona must never read another's room grounding. - #[tokio::test] - async fn cross_persona_ctx_returns_empty() { - let me = PeerId::new(); - let other = PeerId::new(); - let reader = Arc::new(StubReader::new(me, vec![member(other, "persona", None)])); - let source = RoomRosterSource::new(persona(), reader); - let alien = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); - let delivery = source - .deliver( - &RagContext::for_persona(alien, 1_000_000), - 1_000, - ResolutionPreference::Raw, - ) - .await; - assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); - } - - // what this catches: budget truncates the roster instead of - // over-spending — a present citizen's line is an atomic unit, so we - // stop cleanly rather than emit a partial line. - #[tokio::test] - async fn budget_truncates_without_overspend() { - let me = PeerId::new(); - let reader = Arc::new(StubReader::new( - me, - vec![ - member(PeerId::new(), "persona", None), - member(PeerId::new(), "persona", None), - member(PeerId::new(), "persona", None), - ], - )); - let source = RoomRosterSource::new(persona(), reader); - // Each line ~ a handful of tokens; a tiny budget fits at most one. - let delivery = source.deliver(&ctx(), 4, ResolutionPreference::Raw).await; - assert!(delivery.items.len() < 3, "budget must truncate the roster"); - assert!(delivery.tokens_used <= 4, "never overspend the budget"); - } -} diff --git a/core/continuum-mind/src/persona/roster_slot.rs b/core/continuum-mind/src/persona/roster_slot.rs index 0b3b42393a..2a65b51fac 100644 --- a/core/continuum-mind/src/persona/roster_slot.rs +++ b/core/continuum-mind/src/persona/roster_slot.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; -use airc_lib::{AgentAvailabilityState, RoomMember}; +use airc_lib::AgentAvailabilityState; use continuum_positron::{Provenance, RosterSlotView, SenderKind}; use uuid::Uuid; @@ -42,83 +42,7 @@ fn availability_label(state: AgentAvailabilityState) -> &'static str { } } -/// THE `RoomMember` → neutral [`RosterSlotView`] projection — one place both -/// rails build a roster slot from an airc member, so the WS widget and the -/// persona's grounding can never drop different fields (the divergence -/// #8/#13 removes: Rail A used to keep `availability`/`last_seen_ms` while -/// Rail B silently dropped them). Pure and total — no self-exclusion, no -/// budget, no ordering: those are per-consumer policies the caller applies -/// to the projected slots, not part of the shared projection. -/// -/// The WS emitter (`ipc::positron_presence`) and the persona grounding source -/// (`persona::room_roster_source`) call the identical function. -pub(crate) fn roster_slot_from_member(member: &RoomMember) -> RosterSlotView { - // Coarse styling hint from the free-form runtime class; the full string - // is preserved verbatim in `provenance` (never string-match on runtime - // to pick behavior — that is task #70's smell). - let kind = SenderKind::from_runtime(&member.runtime); - // airc resolved the name; a present-but-unnamed peer gets the SAME - // provisional short-peer label the consumer uses when a card has not - // folded in — one provisional-label decision, never a silently-invisible - // citizen and never a second fallback form. - let display_name = member - .display_name - .clone() - .unwrap_or_else(|| provisional_sender_name(member.peer_id.as_uuid())); - RosterSlotView { - member_id: member.peer_id.as_uuid(), - display_name, - kind, - // airc's `RoomMember` carries no cross-system badge map (the richer - // `room_roster_cards` path would fill this); empty is the honest "no - // badges known", not a fabricated one. - integrations: BTreeMap::new(), - // The accountability truth airc surfaces today, carried verbatim. - // Trust tier + verification join here later (task #38), no wire break. - provenance: Provenance { - runtime: member.runtime.clone(), - }, - // airc excludes `Leaving` peers from the roster, so every member it - // returns is present → active. - active: true, - // Neutral presence facts carried straight through — the fields Rail B - // used to drop. `availability` is airc's stable label (or `None` when - // unreported); `last_seen_ms` is the raw recency signal. - availability: member - .availability - .map(availability_label) - .map(str::to_owned), - last_seen_ms: member.last_seen_ms, - // The thin `room_roster` path carries no identity card — these fill - // only on the cards path ([`roster_slot_from_card`], #262). Honest - // absent, never fabricated. - pronouns: None, - role_label: None, - bio: None, - // airc's `RoomMember` carries no vitals — a continuum persona's live - // `PersonaState` (energy/attention/compute) arrives on its OWN - // `persona:vitals` event and is folded into the slot by id at `store` - // time (see [`PersonaVitalsUpdate`] / [`ChatProjection::apply_vitals`]), - // never through this presence path. Empty here = no vitals reported, - // never fabricated bars ([[fallbacks-are-illegal-fail-loud]]). - vitals: BTreeMap::new(), - // Same design B as vitals: an AI member's loadout (`model · size · ctx`) - // arrives on its OWN `persona:vitals` event and is folded in by id at - // `store` time. `None` here = no bound model reported (a human, an - // unresolved agent) — honest-absent, never a fabricated model. - loadout: None, - // The avatar IMAGE is a node-local disk fact the presence EMITTER - // enriches (it owns the store scan); this shared projection stays - // pure — no I/O here, absent by default. - avatar_url: None, - // Gene names arrive on the persona's OWN `persona:vitals` radiate and - // are folded in at `store` time, same as vitals/loadout — never - // through this presence path. Empty = none reported. - genes: Vec::new(), - } -} - -/// The CARDS-flavored sibling of [`roster_slot_from_member`] (#262): projects +/// The CARDS-flavored sibling of the member projection the legacy roster source used (#262): projects /// an airc [`airc_lib::RoomMemberCard`] — presence + the FULL published /// identity card — into the same neutral slot. This is what makes a citizen's /// pronouns / role / bio / integrations reach every rendered roster instead @@ -156,7 +80,7 @@ pub fn roster_slot_from_card(member: &airc_lib::RoomMemberCard) -> RosterSlotVie bio: identity.and_then(|i| non_empty(&i.bio)), // Vitals / loadout / avatar / genes fold in by id downstream, same // as the member path — see the field notes on - // [`roster_slot_from_member`]. + // the member projection the legacy roster source used. vitals: BTreeMap::new(), loadout: None, avatar_url: None, diff --git a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs index 698c1ab2c3..e07cb1bef5 100644 --- a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs +++ b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs @@ -320,7 +320,6 @@ pub(super) async fn run_self_cycle( // Passing None here is what made idle ticks blind to the board (#331 / #127). cognition .compose_for_turn( - &ctx.profile, now_ms, Some(focus_room.unwrap_or(ctx.identity.default_room)), ) diff --git a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs index 5cdc097799..d33571ee08 100644 --- a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs +++ b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs @@ -319,13 +319,13 @@ pub(super) async fn serve_persona_loop_inner( .flatten(), ) .await; - // Recorded BEFORE compose_turn, which marks the trigger read: from here until the turn - // ends, a stop that cuts it leaves this row behind to say so. + // Recorded BEFORE the turn can mark its trigger read (the read receipt of its sent + // prompt): from here until the turn ends, a stop that cuts it leaves this row behind. // A retry reconciles the id its first attempt minted (confirmed or not); only a new input // mints one. Only a CONFIRMED row lets the turn run (stop-drain S2): an unknown row could be // re-run by a later start after this turn acted. Unconfirmed, the input is retained WITH its // candidate id (Codex on #5492: a create may have committed unseen), and the turn stops - // here, before compose_turn marks the trigger read. + // here, before any prompt could mark the trigger read. let candidate = admitted_retry.then(|| deferred_input.obligation_for(&msg)).flatten(); let obligation = match obligations.admit(turn_room, &msg, wake_engram, now_ms, candidate).await { crate::persona::obligation::Admission::Confirmed(turn) => turn, diff --git a/core/continuum-mind/src/persona/service_loop/tests/mod.rs b/core/continuum-mind/src/persona/service_loop/tests/mod.rs index 53bd1253da..37731d54b5 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/mod.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/mod.rs @@ -465,18 +465,20 @@ // regression for the 2026-08-06 anchor/receipt contradiction #[test] pub(super) fn an_absent_board_source_yields_no_anchor_at_all() { - use crate::cognition::rag_budget::{RagDelivery, RagItem, ResolutionPreference}; + use crate::cognition::rag_budget::{RagDelivery, RagItem}; let delivery = |source_id: &str, items: Vec| RagDelivery { source_id: source_id.to_string(), items, tokens_used: 0, truncated: false, - resolution_used: ResolutionPreference::Raw, }; // The ENUM, not a spelling. If the wire form ever changes, this fixture changes // with it automatically instead of quietly testing a string that no longer occurs. let card = |state: airc_work::CardState| RagItem { + key: String::new(), + summary: None, + pointer: None, content: "#00f2a380 self-heal #2: receive-binding re-derive".to_string(), tokens: 8, metadata: serde_json::json!({ "card_id": "00f2a380", "state": state }), @@ -537,13 +539,15 @@ let delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: "hello there".to_string(), tokens: 0, metadata: serde_json::json!({ "peer_id": "peer-2" }), }], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let turns = build_workspace_turns(&[delivery], "peer-1", "Asha", None); assert!( @@ -564,12 +568,18 @@ source_id: "active-work".to_string(), items: vec![ crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: "card 20fe404a \"macOS install acceptance checks\" (P1, owner YOU)" .to_string(), tokens: 0, metadata: serde_json::json!({}), }, crate::cognition::rag_budget::RagItem { + key: String::new(), + summary: None, + pointer: None, content: "[work] Your claim on card 33a0e899 \"conway\" is no longer held by you (lease expired or released)." .to_string(), tokens: 0, @@ -578,7 +588,6 @@ ], tokens_used: 0, truncated: false, - resolution_used: crate::cognition::rag_budget::ResolutionPreference::Raw, }; let turns = build_workspace_turns(&[work], "peer-1", "Asha", None); assert_eq!(turns.len(), 1); @@ -606,7 +615,7 @@ /// thought. [[alignment-through-mutual-self-interest]]. pub(super) mod burst_fingerprint_drive { use super::super::burst_fingerprint; - use crate::cognition::rag_budget::{RagDelivery, RagItem, ResolutionPreference}; + use crate::cognition::rag_budget::{RagDelivery, RagItem}; use serde_json::json; const ME: &str = "me-peer"; @@ -617,11 +626,13 @@ items, tokens_used: 0, truncated: false, - resolution_used: ResolutionPreference::Raw, } } fn chat(peer_id: &str, content: &str) -> RagItem { RagItem { + key: String::new(), + summary: None, + pointer: None, content: content.to_string(), tokens: 0, metadata: json!({ "peer_id": peer_id }), @@ -629,6 +640,9 @@ } fn card(content: &str) -> RagItem { RagItem { + key: String::new(), + summary: None, + pointer: None, content: content.to_string(), tokens: 0, metadata: json!({}), diff --git a/core/continuum-mind/src/persona/service_loop/tests/part_2.rs b/core/continuum-mind/src/persona/service_loop/tests/part_2.rs index 5dfd33216c..b5c2765d79 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/part_2.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/part_2.rs @@ -11,7 +11,7 @@ pub(super) mod workspace_burst_names { use super::super::super::build_workspace_turns; use crate::cognition::workspace::Burst; - use crate::cognition::rag_budget::{RagDelivery, RagItem, ResolutionPreference}; + use crate::cognition::rag_budget::{RagDelivery, RagItem}; use serde_json::json; fn delivery(source_id: &str, items: Vec) -> RagDelivery { @@ -20,11 +20,13 @@ items, tokens_used: 0, truncated: false, - resolution_used: ResolutionPreference::Raw, } } fn chat(peer_id: &str, content: &str) -> RagItem { RagItem { + key: String::new(), + summary: None, + pointer: None, content: content.to_string(), tokens: 0, metadata: json!({ "peer_id": peer_id, "occurred_at_ms": 1u64 }), @@ -32,6 +34,9 @@ } fn roster(peer_id: &str, name: &str) -> RagItem { RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!("{name} [claude]"), tokens: 0, metadata: json!({ "peer_id": peer_id, "display_name": name }), @@ -126,6 +131,9 @@ // the anchor parses — carries the serde encoding. let shown = format!("{state:?}"); RagItem { + key: String::new(), + summary: None, + pointer: None, content: format!("card {id8} [{shown}] \"{title}\" (P2, {owner_txt})"), tokens: 0, metadata: json!({ @@ -642,6 +650,7 @@ peer_id: joel, content: "run commands/list and tell me the count", occurred_at_ms: 0, + source: None, }; let turns = build_workspace_turns(&deliveries, me, "Asha", Some(trigger)); @@ -685,6 +694,7 @@ peer_id: joel, content: question, occurred_at_ms: 0, + source: None, }; let turns = build_workspace_turns(&deliveries, me, "Asha", Some(trigger)); assert_eq!( 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 3bfdf69dfe..e73a19b372 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 @@ -115,6 +115,7 @@ use super::*; defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }; crate::cognition::persona_workspace::global() .register_from_cfg(cfg) @@ -214,6 +215,7 @@ use super::*; defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }; crate::cognition::persona_workspace::global() .register_from_cfg(cfg) @@ -520,6 +522,7 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( defer_grounding: false, suppress_recall: false, forked: false, + read_receipt: None, }; crate::cognition::persona_workspace::global() .register_from_cfg(cfg) @@ -549,83 +552,52 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( } // what this catches: THE personaRag convergence seam, end to end through real - // code (not hand-authored roster strings). A present airc `RoomMember` flows: - // RoomRosterSource.deliver (the ONE shared `roster_slot_from_member` projection - // both the WS widget and this grounding rail use) + // code (not hand-authored roster strings). A roster member in the room's ViewState + // flows: + // ViewStateRagSource::.deliver (the SAME RosterViewState the web + // roster renders; one projection for screen and mind) // → project_room_roster (the heartbeat loop's own delivery fold, extracted) // → prompt_assembly (the [Present in this room] block) - // and lands with the converged line INCLUDING availability — the field the widget - // rail used to silently drop before the convergence (#8/#13). Connects the three - // separately-unit-tested halves via the exact path the live turn runs; the live - // core proves the plumbing, this proves it deterministically without airc presence. + // and lands with the member's line. Connects the separately-unit-tested halves via + // the exact path the live turn runs, deterministically and without airc presence. #[tokio::test] async fn present_member_reaches_present_in_room_block_end_to_end() { use crate::cognition::prompt_assembly::{assemble, HistoryMessage, PromptAssemblyInput}; - use crate::cognition::rag_budget::{RagContext, RagSource, ResolutionPreference}; + use crate::cognition::rag_budget::{RagContext, RagSource}; use crate::model_registry::types::MultiPartyChatStrategy; - use crate::persona::room_roster_source::{AircRosterReader, RoomRosterSource}; + use crate::persona::viewstate_rag::ViewStateRagSource; use crate::cognition::conversation::workspace_turns::project_room_roster; - use airc_core::PeerId; - use airc_lib::{AgentAvailabilityState, AircError, RoomMember}; - use async_trait::async_trait; + use continuum_positron::scoping::PerRoomSubstrates; + use continuum_positron::{RosterViewState, SenderKind, StateBuilder}; use std::sync::Arc; - use std::time::Duration; - - // One present peer, self-reported Busy — the airc upstream both rails read. - struct OnePresentPeer { - me: PeerId, - other: PeerId, - } - #[async_trait] - impl AircRosterReader for OnePresentPeer { - fn self_peer_id(&self) -> PeerId { - self.me - } - async fn room_roster( - &self, - _within: Duration, - _window: usize, - _room: Option, - ) -> Result, AircError> { - Ok(vec![RoomMember { - peer_id: self.other, - display_name: Some("win-claude".to_string()), - runtime: "claude".to_string(), - availability: Some(AgentAvailabilityState::Busy), - last_seen_ms: 1_700_000_000_000, - }]) - } - } + // One present peer in the room's OWN substrate, the shape production uses. let persona = uuid::Uuid::new_v4(); - let source = RoomRosterSource::new( - persona, - Arc::new(OnePresentPeer { - me: PeerId::new(), - other: PeerId::new(), - }), + let room = uuid::Uuid::new_v4(); + let mut slot = continuum_positron::chat::test_roster_slot( + uuid::Uuid::new_v4(), + "win-claude", + SenderKind::Agent, ); + slot.role_label = Some("claude".to_string()); + let rooms = Arc::new(PerRoomSubstrates::new()); + rooms.for_room(room).store(StateBuilder::standalone().session(RosterViewState { + room_id: room, + roster: vec![slot], + })); + let source = ViewStateRagSource::::per_room(rooms); // 1. Real delivery from the shared roster projection. - let ctx = RagContext::for_persona(persona, 1_000_000); - let delivery = source.deliver(&ctx, 1_000, ResolutionPreference::Raw).await; + let ctx = RagContext::for_persona_in_room(persona, 1_000_000, room); + let delivery = source.deliver(&ctx).await; - // 2. Real loop fold: delivery → grounding consumers (the converged line + + // 2. Real loop fold: delivery → grounding consumers (the member line + // the bare name), via the exact fn the heartbeat loop calls. let proj = project_room_roster(std::slice::from_ref(&delivery)); - // Agent-only roster ⇒ the no-human authority fact (#2113) rides FIRST in - // the grounding lines — it reaches the prompt through the same block — - // while other_persona_names stays peer-only (the fact has no - // display_name, so it can NEVER become a phantom "peer" name). - assert_eq!(proj.room_roster.len(), 2); - assert!( - proj.room_roster[0].contains("No human is present"), - "authority fact first: {}", - proj.room_roster[0] - ); + assert_eq!(proj.room_roster.len(), 1); assert_eq!( - proj.room_roster[1], "win-claude [claude] — busy", - "converged line (availability = airc's neutral 'busy', not Debug 'Busy')" + proj.room_roster[0], "win-claude (Agent) — claude", + "the member's line (kind and role; no liveness flag in the mind's copy)" ); assert_eq!(proj.other_persona_names, vec!["win-claude".to_string()]); @@ -658,8 +630,8 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( assert!( assembled .system_message - .contains("win-claude [claude] — busy"), - "converged roster line (with availability) did not reach the prompt:\n{}", + .contains("win-claude (Agent) — claude"), + "roster line did not reach the prompt:\n{}", assembled.system_message ); } diff --git a/core/continuum-mind/src/persona/service_loop/turn_context.rs b/core/continuum-mind/src/persona/service_loop/turn_context.rs index 9611419c67..e7b1d09d02 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_context.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_context.rs @@ -140,7 +140,7 @@ pub(super) async fn compose_turn( // Without it every room-scoped source abstains and she perceives no // board, no roster, no doctrine, no wall (#331 / #127). cognition - .compose_for_turn(&ctx.profile, now_ms, Some(turn_room)) + .compose_for_turn(now_ms, Some(turn_room)) .await }; phase_timings.compose_ms = compose_started.elapsed().as_millis() as u64; @@ -196,6 +196,7 @@ pub(super) fn build_turn_burst( peer_id: &msg.peer_id.to_string(), content: &msg.render_content(), occurred_at_ms: 0, + source: Some(crate::cognition::workspace::TurnSource { room: msg.room_id, event: msg.event_id, lamport: msg.lamport }), }), ); // #301 anchor-starvation fix: the in-window escalation counter loses its diff --git a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs index 1e41a8fb2d..54607aa7a5 100644 --- a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs +++ b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs @@ -197,12 +197,10 @@ pub async fn materialize_adapters( identity.agent_name.clone(), rag_engine, ); - let airc_source: Arc = - Arc::new(crate::persona::airc_source::AircRagSource::new( - identity.peer_id.as_uuid(), - runtime.clone(), - )); - cognition.set_airc_source(airc_source); + // One airc source: it delivers her rooms to cognition and takes the read receipt + // of every sent prompt (her cursor moves through what she was shown, never at delivery). + let airc = Arc::new(crate::persona::airc_source::AircRagSource::new(identity.peer_id.as_uuid(), runtime.clone())); + cognition.set_airc_source(Arc::clone(&airc) as Arc); // WHO IS PRESENT, read from the SAME `RosterViewState` the browser renders // (#408 + the RenderTarget pattern). Her room's OWN store, so a citizen in @@ -231,16 +229,17 @@ pub async fn materialize_adapters( cognition.set_roster_source(roster_source.clone()); - // Her awareness across ALL her activities (EVENT-MIND §6, the strip): one block, - // loudest first, with her continuation and her dial, read from her perception - // region by persona. The region boots when her conversation attaches; until then - // the source delivers nothing, which is the truth. + // Her awareness across ALL her activities (EVENT-MIND §6, the strip): a line per + // activity, loudest first, with her continuation and her dial, read from her + // perception region by persona. The region boots when her conversation attaches; + // until then the source delivers nothing, which is the truth. A grounding faculty + // below: it was bound only to compose_for_turn, whose delivery of it nothing read, + // so the strip never reached her prompt. let awareness_source: Arc = Arc::new(crate::persona::awareness_source::AwarenessRagSource::new( identity.peer_id.as_uuid(), Some(runtime.clone()), )); - cognition.set_awareness_source(awareness_source); // Bind the room-doctrine source from the same runtime (upcasts to // `AircDoctrineReader`). Grounds the persona in the room's nature @@ -375,8 +374,6 @@ pub async fn materialize_adapters( (raw_doctrine, raw_wall) } }; - // Same dual-wire as the roster: one Arc, legacy path + brain faculty. - cognition.set_doctrine_source(doctrine_source.clone()); // Room-board source: grounds the persona in the CURRENT ROOM's WHOLE // work board — every card, its column, priority, and owner — read live @@ -505,6 +502,10 @@ pub async fn materialize_adapters( // The persona's own live work across rooms — enriching framing so // it knows what it's working on (cross-activity, dynamic, no // hardcoded card state). Defer-tolerant. + // Where else she is needed while she works here: it changes every turn. + crate::cognition::persona_workspace::GroundingSource::framing(awareness_source) + .defer_tolerant() + .volatile_content(), crate::cognition::persona_workspace::GroundingSource::framing(active_work_source) .defer_tolerant() // Claim states flap per turn — floor stays, stable-tier @@ -583,6 +584,7 @@ pub async fn materialize_adapters( // benchmark-reproducibility knob, never a life-path setting (#207). suppress_recall: false, forked: false, + read_receipt: Some(Arc::clone(&airc) as Arc), }; // A checkpoint can be locked by offline adoption. Waiting and reading // belong off the async runtime workers; registration publishes nothing diff --git a/core/continuum-mind/src/persona/unified.rs b/core/continuum-mind/src/persona/unified.rs index d228c19f99..54e4b02b88 100644 --- a/core/continuum-mind/src/persona/unified.rs +++ b/core/continuum-mind/src/persona/unified.rs @@ -11,16 +11,11 @@ use crate::cognition::admission_state::AdmissionState; use crate::persona::cognition::PersonaCognitionEngine; use crate::persona::domain_classifier::DomainClassifier; -use crate::persona::engram_source::EngramSource; use crate::persona::evaluator::{RateLimiterState, SleepState}; use crate::persona::inbox::PersonaInbox; -use crate::persona::inference_profile::PersonaInferenceProfile; use crate::persona::message_cache::{ContentDeduplicator, RecentMessageCache}; use crate::persona::model_selection::AdapterRegistry; -use crate::cognition::rag_budget::{ - BudgetAllocation, FlexboxRagBudgetAdapter, RagBudgetAdapter, RagContext, RagDelivery, - RagSource, RagSourceBudget, ReservedTokens, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagSource}; use crate::persona::rag_capture::{ NoopRagCaptureSink, RagCaptureEvent, RagCaptureSink, RecordingRagSource, }; @@ -46,9 +41,9 @@ pub struct PersonaCognition { /// with `default_v1()` recipe + permissive trust mapping. Per-persona /// because each persona's memory + dedup are independent. /// - /// Wrapped in `Arc` (slice 10.5) so the `engram_source` can share - /// the same admission store. Arc transparency means existing - /// `cognition.admission.admit(...)` callers remain source-unchanged. + /// Wrapped in `Arc` (slice 10.5) so recall shares the same admission store. Arc + /// transparency means existing `cognition.admission.admit(...)` callers remain + /// source-unchanged. pub admission: Arc, /// RecallMetadata sidecar — Algorithm 4's volatile per-engram /// state (salience, access_count, last_accessed_ms, @@ -57,15 +52,8 @@ pub struct PersonaCognition { /// + decay tick (read-mostly hot paths). Per-persona because each /// persona's recall state is independent. pub recall_metadata: Arc, - /// The persona's RAG-layer engram source, wrapped in a - /// `RecordingRagSource` decorator against `capture_sink`. Reads - /// from `admission` + `recall_metadata`. Production callers - /// (PromptAssembly in slice 12+) hold this via the - /// `Arc` type. - pub engram_source: Arc, - /// The persona's live-airc RAG source — paired with - /// `engram_source` per [[source-drain-is-the-universal-pattern]] - /// and the L1–L5 cognitive cache doctrine. Bound at supervisor + /// The persona's live-airc RAG source, per + /// [[source-drain-is-the-universal-pattern]] and the L1–L5 cognitive cache doctrine. Bound at supervisor /// boot (task #148, "RAG source pre-binding — cache source set /// at boot, lease per inspection") once the persona's /// `AircCitizen` is attached to the grid. `None` during @@ -85,19 +73,7 @@ pub struct PersonaCognition { /// persona confabulating other citizens' turns. See /// docs/grid/AIRC-NATIVE-IDENTITY-ROOMS-SECURITY.md §5 slice 1. pub roster_source: Option>, - /// Her awareness strip across all activities (`AwarenessRagSource`); turn churn. - pub awareness_source: Option>, - /// The persona's room-doctrine RAG source — "what KIND of room is - /// this" (the airc-published operating contract via - /// `Airc::room_doctrine`). Bound at supervisor boot from the same - /// `Airc` handle (satisfies `AircDoctrineReader`). `None` pre-attach - /// / in tests. Routed by the service loop into system-prompt - /// grounding (a `[Room operating doctrine]` block) so a persona - /// calibrates participation to the activity (slice 2). See - /// docs/grid/AIRC-NATIVE-IDENTITY-ROOMS-SECURITY.md §5 slice 2. - pub doctrine_source: Option>, - /// The capture sink the RecordingRagSource wraps engram_source - /// against. Default = `NoopRagCaptureSink` (zero overhead, drops + /// The capture sink every bound source's RecordingRagSource records into. Default = `NoopRagCaptureSink` (zero overhead, drops /// events on the floor). Production callers swap in /// `JsonlRagCaptureSink` for on-disk traces or /// `InMemoryRagCaptureSink` for in-flight inspection. @@ -109,26 +85,12 @@ pub struct PersonaCognition { // through the command registry (which only knows her id, never holds `cognition.lock()`). // Its single home is `crate::cognition::focus::registry()` — see that module. -/// What [`PersonaCognition::compose_for_turn`] returns — the -/// substrate's structured handoff between "brain composed a budgeted -/// multi-source prompt context" and "inference adapter generates a -/// response." Per the brain doctrine ([[no-fallbacks-ever]], -/// [[no-if-statements-use-llms-for-cognition]]) this struct carries -/// the budget allocator's verdict alongside the deliveries, so the -/// caller (service_loop / introspection) can see exactly what landed -/// — Satisfied / FloorOnly / Dropped / UnderProvisioned — instead of -/// having to re-derive that from item counts. +/// What [`PersonaCognition::compose_for_turn`] returns: every item of her conversation and +/// roster sources, whole, for the turn's burst. Nothing here is sized: her prompt view's one +/// allocation decides what she sees (FLOW-IMPLEMENTATION-PLAN §2d). #[derive(Debug, Clone)] pub struct ComposedTurn { - /// The budget allocator's per-source verdict, with the rich - /// AllocationState telemetry the substrate-is-a-good-citizen - /// doctrine requires. Caller can inspect `escalation_needed` to - /// know if any required source got under-provisioned. - pub allocation: BudgetAllocation, - /// One delivery per source the brain composed. Ordering matches - /// the order the brain assembled budgets in (engram first, then - /// airc, then any future sources). The caller threads these into - /// the prompt in the order presented. + /// One delivery per bound source, airc first, then the roster. pub deliveries: Vec, } @@ -143,9 +105,8 @@ impl PersonaCognition { /// Create with a custom capture sink — production callers swap /// in `JsonlRagCaptureSink` (on-disk trace) or - /// `InMemoryRagCaptureSink` (in-flight inspection). The - /// `engram_source` is wrapped in a `RecordingRagSource` - /// decorator against this sink. + /// `InMemoryRagCaptureSink` (in-flight inspection). Every bound source is wrapped in a + /// `RecordingRagSource` decorator against this sink. pub fn with_capture_sink( persona_id: Uuid, persona_name: String, @@ -155,10 +116,6 @@ impl PersonaCognition { let (_, shutdown_rx) = tokio::sync::watch::channel(false); let recall_metadata = Arc::new(RecallMetadataRegistry::new()); let admission = Arc::new(AdmissionState::new(recall_metadata.clone())); - let engram_source: Arc = Arc::new(RecordingRagSource::new( - EngramSource::new(persona_id, admission.clone()), - capture_sink.clone(), - )); Self { engine: PersonaCognitionEngine::new(persona_id, persona_name, rag_engine, shutdown_rx), inbox: PersonaInbox::new(persona_id), @@ -170,11 +127,8 @@ impl PersonaCognition { content_dedup: ContentDeduplicator::new(), admission, recall_metadata, - engram_source, airc_source: None, roster_source: None, - awareness_source: None, - doctrine_source: None, capture_sink, } } @@ -192,10 +146,8 @@ impl PersonaCognition { /// Swap the in-memory admission for a disk-backed, rehydrated one /// (per-persona `engrams.sqlite`, via `AdmissionState::for_persona`). Called /// by the supervisor at boot once the persona's `PersonaHome` is known. - /// Rebuilds `engram_source` against the new admission (decorated with the - /// brain's `capture_sink`) and adopts its recall-metadata registry, so - /// encoding + recall + the workspace's RecallFaculty all share the persisted - /// store. Without this, admission is `NoopSink` — in-memory, lost on restart. + /// Adopts its recall-metadata registry, so encoding + recall + the workspace's + /// RecallFaculty all share the persisted store. Without this, admission is `NoopSink` — in-memory, lost on restart. /// Must run BEFORE the per-persona WorkspaceCycle is assembled, so its /// RecallFaculty binds the persisted admission. pub fn attach_persistent_admission( @@ -203,11 +155,8 @@ impl PersonaCognition { persona_id: Uuid, admission: Arc, ) { + let _ = persona_id; // the admission is already the persona's; kept for the boot call's shape self.recall_metadata = admission.recall_metadata().clone(); - self.engram_source = Arc::new(RecordingRagSource::new( - EngramSource::new(persona_id, admission.clone()), - self.capture_sink.clone(), - )); self.admission = admission; } @@ -234,44 +183,11 @@ impl PersonaCognition { self.roster_source = Some(decorated); } - /// Bind the brain's awareness-strip source (`AwarenessRagSource`): what she - /// perceives across ALL her activities, loudest first, with her continuation. Same - /// boot-time wire and capture decoration as the roster. - pub fn set_awareness_source(&mut self, raw_source: Arc) { - let decorated: Arc = Arc::new(RecordingRagSource::new( - ArcRagSource::new(raw_source), - self.capture_sink.clone(), - )); - self.awareness_source = Some(decorated); - } - - /// Bind the brain's room-doctrine RAG source (`RoomDoctrineSource`). - /// Same boot-time wire as `set_roster_source`, from the same `Airc` - /// handle (satisfies `AircDoctrineReader`), decorated with the - /// `capture_sink` so doctrine deliveries are recorded + replayable. - pub fn set_doctrine_source(&mut self, raw_source: Arc) { - let decorated: Arc = Arc::new(RecordingRagSource::new( - ArcRagSource::new(raw_source), - self.capture_sink.clone(), - )); - self.doctrine_source = Some(decorated); - } - - /// Brain composition for one cognition turn. Walks the brain's - /// own bound sources (engram + airc + future) through the - /// `FlexboxRagBudgetAdapter` Joel wrote in PR #8 / task #93 — - /// the no-clipping doctrine, source-owned-units, full - /// telemetry. NOT a separate budget. NOT a parallel allocator. - /// THE substrate budgeter, called the way the substrate - /// expects. - /// - /// Budget reservations scale with `profile.context_length` so a - /// Compat-tier 2048-window persona AND an M-series 32k+ persona - /// both call this same method — the answer differs because the - /// profile differs, per - /// [[context-is-the-client-airc-token-is-identity]] and - /// [[intent-driven-api-not-hot-patches]]. The substrate does - /// NOT bake in clamps that handicap capable peers on the grid. + /// Brain composition for one cognition turn: her conversation (airc) and who is present + /// (roster), every item whole. No budget and no allocation here: her prompt view's one + /// allocation decides what she sees (FLOW-IMPLEMENTATION-PLAN §2d). This ran a second + /// flexbox over five sources, of which only these two were read; the engram, doctrine + /// and awareness deliveries reached only the capture. /// /// `now_ms` is passed in (not read from `SystemTime`) so the /// brain's composition is replay-deterministic per @@ -293,7 +209,6 @@ impl PersonaCognition { /// consolidation, dreams) — it means "no room context claimed", not "unknown". pub async fn compose_for_turn( &self, - profile: &PersonaInferenceProfile, now_ms: u64, room: Option, ) -> ComposedTurn { @@ -303,49 +218,7 @@ impl PersonaCognition { None => RagContext::for_persona(persona_id, now_ms), }; - // Window-scaled reservation — ONE derivation, owned by - // ReservedTokens::scaled_for_window (#424 dedup; rag_inspect - // shares it). Doctrine lives on the constructor. - let context_window = profile.context_length; - let reserved = ReservedTokens::scaled_for_window(context_window); - let headroom = reserved.headroom_within(context_window); - - // Collect the brain's bound sources in deterministic order: - // engram first (long-term memory, the L2+ recall layer), - // then airc (the L1 conversational floor). Future sources - // (code, tool descriptions, identity card) extend this list - // in order of long-term-to-immediate. - let mut sources: Vec> = Vec::with_capacity(4); - sources.push(self.engram_source.clone()); - if let Some(ref airc) = self.airc_source { - sources.push(airc.clone()); - } - // The "identity card" sources the original author reserved this - // list for: WHO is present (roster) and WHAT KIND of room this is - // (doctrine). Both routed by the service loop into system-prompt - // grounding, not history. - if let Some(ref roster) = self.roster_source { - sources.push(roster.clone()); - } - if let Some(ref doctrine) = self.doctrine_source { - sources.push(doctrine.clone()); - } - // Her awareness across every activity (EVENT-MIND §6): the strip. Lightweight, - // loudest first, fitted by its own source; the one block that says where else - // she is needed while she works here. - if let Some(ref awareness) = self.awareness_source { - sources.push(awareness.clone()); - } - - // Sources declare appetite through the shared contract. Names identify - // capture rows; renaming or decorating a source cannot change its share. - let budgets: Vec = sources - .iter() - .map(|source| source.budget_claim(context_window, headroom)) - .collect(); - - // Emit the TurnStart capture so audit/replay sees the - // budget the brain actually asked for, not what landed. + let sources = self.airc_source.iter().chain(self.roster_source.iter()); let turn_id = Uuid::new_v4(); // A turn in her mind room: no retrieval capture at all (sink 5). let captured = !crate::persona::rag_capture::turn_is_private(&rag_ctx); @@ -354,37 +227,13 @@ impl PersonaCognition { captured_at_ms: now_ms, persona_id, turn_id: Some(turn_id), - context_window, - reserved, - source_budgets: budgets.clone(), context: rag_ctx.clone(), }); } - - let adapter = FlexboxRagBudgetAdapter::new(); - let allocation = adapter.allocate(&rag_ctx, context_window, reserved, &budgets); - - if captured { - self.capture_sink.record(RagCaptureEvent::BudgetAllocated { - captured_at_ms: now_ms, - persona_id, - turn_id: Some(turn_id), - allocation: allocation.clone(), - }); - } - - let mut deliveries = Vec::with_capacity(sources.len()); - for (source, source_alloc) in sources.iter().zip(allocation.allocations.iter()) { - let delivery = source - .deliver( - &rag_ctx, - source_alloc.allocated_tokens, - ResolutionPreference::Raw, - ) - .await; - deliveries.push(delivery); + let mut deliveries = Vec::with_capacity(2); + for source in sources { + deliveries.push(source.deliver(&rag_ctx).await); } - if captured { self.capture_sink.record(RagCaptureEvent::TurnEnd { captured_at_ms: now_ms, @@ -392,11 +241,7 @@ impl PersonaCognition { turn_id: Some(turn_id), }); } - - ComposedTurn { - allocation, - deliveries, - } + ComposedTurn { deliveries } } } @@ -429,33 +274,17 @@ impl RagSource for ArcRagSource { self.0.expand_command() } - /// Delegates to the inner source — the floor is that source's to declare. - fn floor_tokens(&self) -> u32 { - self.0.floor_tokens() - } - - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - self.0.budget_claim(window, headroom) - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - self.0.deliver(ctx, budget, resolution).await + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + self.0.deliver(ctx).await } } #[cfg(test)] mod tests { use super::*; - use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::cognition::rag_budget::{RagContext, RagSource, ResolutionPreference}; - use crate::persona::rag_capture::{ - InMemoryRagCaptureSink, RagCaptureEvent, RagCaptureSink, - }; + use crate::cognition::rag_budget::{RagContext, RagItem, RagSource}; + use crate::persona::rag_capture::{InMemoryRagCaptureSink, RagCaptureEvent, RagCaptureSink}; + use async_trait::async_trait; #[test] fn test_persona_cognition_defaults() { @@ -473,162 +302,10 @@ mod tests { assert!(pc.adapter_registry.adapters.is_empty()); } - // ---- Slice 10.5: RAG stack wiring (TDD) ---- - - fn make_test_engram(now_ms: u64, idx: usize) -> Engram { - Engram { - context_id: None, - id: Uuid::new_v4(), - kind: EngramKind::Episodic, - content: format!("test engram body {idx}"), - origin: EngramOrigin::Chat(ChatMessageRef { - message_id: Uuid::new_v4(), - room_id: Uuid::new_v4(), - sender_id: Uuid::new_v4(), - posted_at_ms: now_ms, - content_hash: format!("hash-{idx}"), - }), - recall_keys: Vec::new(), - admitted_at_ms: now_ms, - trust_state_at_admission: TrustState::ApprovedPeer, - admission_trace_id: None, - } - } - - /// PersonaCognition exposes an engram_source field with the - /// expected source_id, bound to the persona. - #[test] - fn persona_cognition_has_engram_source() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let pc = PersonaCognition::new(id, "TestBot".into(), rag); - assert_eq!(pc.engram_source.source_id(), "engrams"); - } - - /// Default capture sink should be Noop — record() doesn't panic - /// and has no observable effect. - #[test] - fn default_capture_sink_is_callable_zero_cost() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let pc = PersonaCognition::new(id, "TestBot".into(), rag); - // Should be safe to record any event — Noop should accept it. - pc.capture_sink.record(RagCaptureEvent::TurnEnd { - captured_at_ms: 1, - persona_id: id, - turn_id: None, - }); - // No panic = pass. - } - - /// An engram admitted via the test-only push_for_test path - /// surfaces via engram_source.deliver. This proves the wiring: - /// PersonaCognition holds a shared AdmissionState (Arc) that - /// both admission AND EngramSource read from. - #[tokio::test] - async fn engram_admitted_surfaces_via_engram_source() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let pc = PersonaCognition::new(id, "TestBot".into(), rag); - - // Push an engram + register its metadata. - let now = 1_000_000_000u64; - let engram = make_test_engram(now, 0); - let engram_id = engram.id; - pc.admission.push_for_test(engram); - pc.recall_metadata.admit_with_defaults(engram_id); - - // Exercise engram_source. - let ctx = RagContext::for_persona(id, now); - let delivery = pc - .engram_source - .deliver(&ctx, 1_000, ResolutionPreference::Raw) - .await; - assert_eq!(delivery.items.len(), 1, "engram should surface"); - } - - /// Swap in an InMemory capture sink at construction → calling - /// engram_source.deliver should record an event. Proves the - /// RecordingRagSource decorator is wired around the EngramSource. - #[tokio::test] - async fn capture_sink_records_engram_source_delivery() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let sink = Arc::new(InMemoryRagCaptureSink::new()); - let sink_dyn: Arc = sink.clone(); - let pc = PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, sink_dyn); - - // Admit + register one engram. - let now = 1_000_000_000u64; - let engram = make_test_engram(now, 0); - let engram_id = engram.id; - pc.admission.push_for_test(engram); - pc.recall_metadata.admit_with_defaults(engram_id); - - // Deliver — should be intercepted by the RecordingRagSource - // wrapper + recorded in the sink. - let ctx = RagContext::for_persona(id, now); - let _ = pc - .engram_source - .deliver(&ctx, 1_000, ResolutionPreference::Raw) - .await; - - let events = sink.events(); - assert_eq!( - events.len(), - 1, - "RecordingRagSource decorator should have recorded one event" - ); - match &events[0] { - RagCaptureEvent::SourceDelivered { source_id, .. } => { - assert_eq!(source_id, "engrams"); - } - other => panic!("expected SourceDelivered, got {other:?}"), - } - } - - /// Default constructor (PersonaCognition::new) installs a - /// NoopRagCaptureSink — exercising engram_source should NOT - /// produce captured events (because Noop drops them). - #[tokio::test] - async fn default_noop_sink_drops_events() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let pc = PersonaCognition::new(id, "TestBot".into(), rag); - - let now = 1_000_000_000u64; - let engram = make_test_engram(now, 0); - let engram_id = engram.id; - pc.admission.push_for_test(engram); - pc.recall_metadata.admit_with_defaults(engram_id); - - let ctx = RagContext::for_persona(id, now); - let _ = pc - .engram_source - .deliver(&ctx, 1_000, ResolutionPreference::Raw) - .await; - - // capture_sink is Noop; nothing should be recorded. We can't - // inspect a Noop sink, but the type signature confirms it; this - // test just verifies no panic + the call path is exercised. - // Confirm the field type satisfies the trait. - let _: &Arc = &pc.capture_sink; - } - - // ---- Slice A (task #148): brain composes via FlexboxRagBudgetAdapter - // over engram + airc, not via inspect_persona_rag's ad-hoc seam. - - use crate::persona::inference_profile::PersonaInferenceProfile; - use crate::cognition::rag_budget::{AllocationState, RagDelivery, RagItem}; - use async_trait::async_trait; - - /// Test source that returns a fixed budget-aware payload — proves - /// the brain wires the budget through to per-source deliver. + /// A source that holds `items` fixed items and delivers every one. struct CannedSource { id: &'static str, - tokens_per_item: u32, - items_offered: usize, - share: Option, + items: usize, } #[async_trait] @@ -638,153 +315,30 @@ mod tests { } fn expand_command(&self) -> Option<&'static str> { - // Test/stub source — nothing further to fetch. - None - } - - /// Test/stub source — floorless, so it never encodes a production floor. - fn floor_tokens(&self) -> u32 { - 0 - } - fn budget_claim(&self, window: u32, headroom: u32) -> RagSourceBudget { - match self.share { - Some(share) => RagSourceBudget::floorless_share(self.id, window, headroom, share), - None => RagSourceBudget::retrieval(self.id, self.floor_tokens(), window, headroom), - } - } - async fn deliver( - &self, - _ctx: &RagContext, - budget: u32, - _resolution: ResolutionPreference, - ) -> RagDelivery { - let mut items = Vec::new(); - let mut tokens_used = 0u32; - for i in 0..self.items_offered { - if tokens_used + self.tokens_per_item > budget { - break; - } - items.push(RagItem { - content: format!("{}: item {}", self.id, i), - tokens: self.tokens_per_item, - metadata: serde_json::Value::Null, - }); - tokens_used += self.tokens_per_item; - } - RagDelivery { - source_id: self.id.to_string(), - items, - tokens_used, - truncated: false, - resolution_used: ResolutionPreference::Raw, - } - } - } - - fn lcd_profile() -> PersonaInferenceProfile { - use crate::persona::hw_tier_descriptor::HwTierCategory; - use crate::persona::inference_profile::SamplingProfile; - PersonaInferenceProfile { - persona_id: Uuid::nil(), - persona_name: "TestBot".to_string(), - model_id: "test/qwen-0.5b".to_string(), - gguf_local_path: None, - tier_category: HwTierCategory::Compat, - tier_id: "test_compat".to_string(), - context_length: 2048, - n_ubatch: 512, - n_batch: 2048, - n_seq_max: 1, - n_gpu_layers: 0, - sampling: SamplingProfile::chat_defaults(), - chat_template: None, - stop_sequences: Vec::new(), + None // a stub: nothing further to fetch } - } - - /// With no airc_source bound the brain still composes — just the - /// engram source. Proves engram is always-present per the - /// substrate-managed-vs-citizen-managed split. - #[tokio::test] - async fn compose_for_turn_uses_engram_when_airc_unbound() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let pc = PersonaCognition::new(id, "TestBot".into(), rag); - - let composed = pc.compose_for_turn(&lcd_profile(), 1_000_000, None).await; - assert_eq!(composed.deliveries.len(), 1); - assert_eq!(composed.deliveries[0].source_id, "engrams"); - } - - /// With airc_source bound the brain composes BOTH sources via the - /// FlexboxRagBudgetAdapter — the same budgeter (no parallel - /// allocator, no second compose path). - #[tokio::test] - async fn compose_for_turn_threads_airc_through_budgeter() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); - let mut pc = PersonaCognition::new(id, "TestBot".into(), rag); - - let airc = Arc::new(CannedSource { - id: "airc", - tokens_per_item: 50, - items_offered: 3, - share: None, - }); - pc.set_airc_source(airc); - - let composed = pc.compose_for_turn(&lcd_profile(), 1_000_000, None).await; - assert_eq!(composed.deliveries.len(), 2); - assert_eq!(composed.deliveries[0].source_id, "engrams"); - assert_eq!(composed.deliveries[1].source_id, "airc"); - - // The flex allocator gave airc enough budget to deliver its - // 3 canned items (50 tokens each = 150 total, well under - // the per-source max for a 2048-window profile). - assert_eq!(composed.deliveries[1].items.len(), 3); - // Allocation telemetry surfaces — caller can read state per - // source. With airc empty of content past the canned items, - // there's no UnderProvisioned (required=false on both). - assert!(!composed.allocation.escalation_needed); - for alloc in &composed.allocation.allocations { - assert!( - matches!( - alloc.state, - AllocationState::Satisfied | AllocationState::FloorOnly - ), - "expected Satisfied or FloorOnly, got {:?} for {}", - alloc.state, - alloc.source_id - ); + async fn deliver(&self, _ctx: &RagContext) -> RagDelivery { + let items = (0..self.items) + .map(|i| RagItem::whole(format!("{i}"), format!("{}: item {i}", self.id), serde_json::Value::Null)) + .collect(); + RagDelivery::of(self.id, items, false) } } - // Regression for c44d535a: a new source name keeps its declared appetite - // through every decorator and the real composer; no ID allow-list is needed. + // what this catches: compose_for_turn sizing her conversation or roster (it ran a second + // flexbox, FLOW plan §2d). Every bound source delivers every item it holds, through the + // capture decorator, airc first; nothing unbound appears. #[tokio::test] - async fn decorated_source_claim_survives_new_name_and_composition() { - let source = Arc::new(CannedSource { - id: "new-standing-kind", - tokens_per_item: 1, - items_offered: 3, - share: std::num::NonZeroU32::new(64), - }); - let (cached, _) = crate::cognition::cached_source::CachedRagSource::new(source.clone()); + async fn compose_for_turn_delivers_every_item_of_her_bound_sources() { let mut pc = PersonaCognition::new(Uuid::new_v4(), "TestBot".into(), Arc::new(RagEngine::new())); + assert!(pc.compose_for_turn(1_000_000, None).await.deliveries.is_empty(), "nothing bound, nothing delivered"); + pc.set_airc_source(Arc::new(CannedSource { id: "airc", items: 300 })); + let (cached, _) = crate::cognition::cached_source::CachedRagSource::new(Arc::new(CannedSource { id: "roster", items: 40 })); pc.set_roster_source(cached); - let wrapped = pc.roster_source.as_ref().unwrap(); - for window in [0, 256, 2048, 51_712] { - let headroom = ReservedTokens::scaled_for_window(window).headroom_within(window); - assert_eq!(wrapped.budget_claim(window, headroom), source.budget_claim(window, headroom)); - } - let composed = pc.compose_for_turn(&lcd_profile(), 1_000_000, None).await; - let allocation = composed.allocation.allocations.iter() - .find(|a| a.source_id == source.id).unwrap(); - assert_eq!(allocation.requested_max, lcd_profile().context_length / 64); - assert_eq!(allocation.requested_min, 0); - assert_eq!(allocation.requested_floor, 0); - assert!(composed.deliveries.iter().any(|d| d.source_id == source.id && d.items.len() == 3)); + let composed = pc.compose_for_turn(1_000_000, None).await; + let shape: Vec<(&str, usize)> = composed.deliveries.iter().map(|d| (d.source_id.as_str(), d.items.len())).collect(); + assert_eq!(shape, [("airc", 300), ("roster", 40)]); } // what this catches: a turn in her mind room landing in the RAG capture (sink 5 of @@ -797,49 +351,32 @@ mod tests { let sink_dyn: Arc = sink.clone(); let mut pc = PersonaCognition::with_capture_sink(id, "Kimi".into(), Arc::new(RagEngine::new()), sink_dyn); - pc.set_airc_source(Arc::new(CannedSource { id: "airc", tokens_per_item: 50, items_offered: 2, share: None })); + pc.set_airc_source(Arc::new(CannedSource { id: "airc", items: 2 })); let mind = crate::cognition::mind_room::mind_room_id(id); - let _ = pc.compose_for_turn(&lcd_profile(), 1_000_000, Some(mind)).await; + let _ = pc.compose_for_turn(1_000_000, Some(mind)).await; assert!(sink.is_empty(), "her mind room: no capture events, got {}", sink.len()); - let _ = pc.compose_for_turn(&lcd_profile(), 1_000_000, Some(Uuid::new_v4())).await; + let _ = pc.compose_for_turn(1_000_000, Some(Uuid::new_v4())).await; assert!(!sink.is_empty(), "an ordinary room still records its turn"); } - /// The brain's capture sink records the TurnStart / BudgetAllocated - /// / TurnEnd events the substrate-replay pipeline expects. Proves - /// compose_for_turn participates in the same capture/replay loop - /// engram_source already does. + // what this catches: compose_for_turn leaving the capture/replay loop. A turn records + // its start, each source's delivery and its end, in that order. #[tokio::test] async fn compose_for_turn_emits_capture_events_for_replay() { - let id = Uuid::new_v4(); - let rag = Arc::new(RagEngine::new()); let sink = Arc::new(InMemoryRagCaptureSink::new()); let sink_dyn: Arc = sink.clone(); - let mut pc = - PersonaCognition::with_capture_sink(id, "TestBot".into(), rag, sink_dyn); - - let airc = Arc::new(CannedSource { - id: "airc", - tokens_per_item: 50, - items_offered: 2, - share: None, - }); - pc.set_airc_source(airc); - - let _composed = pc.compose_for_turn(&lcd_profile(), 1_000_000, None).await; - - let events = sink.events(); - let kinds: Vec<&str> = events + let mut pc = PersonaCognition::with_capture_sink(Uuid::new_v4(), "TestBot".into(), Arc::new(RagEngine::new()), sink_dyn); + pc.set_airc_source(Arc::new(CannedSource { id: "airc", items: 2 })); + let _ = pc.compose_for_turn(1_000_000, None).await; + let kinds: Vec<&str> = sink + .events() .iter() .map(|e| match e { RagCaptureEvent::TurnStart { .. } => "TurnStart", - RagCaptureEvent::BudgetAllocated { .. } => "BudgetAllocated", RagCaptureEvent::SourceDelivered { .. } => "SourceDelivered", RagCaptureEvent::TurnEnd { .. } => "TurnEnd", }) .collect(); - assert!(kinds.contains(&"TurnStart"), "kinds: {kinds:?}"); - assert!(kinds.contains(&"BudgetAllocated"), "kinds: {kinds:?}"); - assert!(kinds.contains(&"TurnEnd"), "kinds: {kinds:?}"); + assert_eq!(kinds, ["TurnStart", "SourceDelivered", "TurnEnd"]); } } diff --git a/core/continuum-mind/src/persona/viewstate_rag.rs b/core/continuum-mind/src/persona/viewstate_rag.rs index 61260038a4..6195043e58 100644 --- a/core/continuum-mind/src/persona/viewstate_rag.rs +++ b/core/continuum-mind/src/persona/viewstate_rag.rs @@ -80,43 +80,46 @@ //! is issue #3881 (with a compile-fail test as its acceptance), not a claim to //! make here in the meantime. //! -//! ## Density, not truncation +//! ## Every unit, never a size //! -//! Units are ordered most-salient-first and packed to the budget, so a tight -//! window yields FEWER units rather than a chopped block — the "degrade, never -//! all-or-nothing" property `floor_tokens` exists to protect. `#256`'s PX density -//! is exactly this dial, and it belongs to the renderer (here), not the projection. +//! A source delivers EVERY unit it holds, each keyed so an unchanged unit appends +//! nothing; the one allocation in the prompt view chooses each unit's level +//! (FLOW plan §2d). The renderer takes no budget and packs nothing. use async_trait::async_trait; use serde::de::DeserializeOwned; use continuum_positron::Substrate; -use crate::cognition::rag_budget::{ - room_scope_allows, RagContext, RagDelivery, RagItem, RagSource, - ResolutionPreference, -}; +use crate::cognition::rag_budget::{room_scope_allows, RagContext, RagDelivery, RagItem, RagSource}; /// One atomic projection: visible text and its machine-readable provenance are -/// admitted together. Metadata must describe this unit, not smuggle omitted rows -/// past packing. The adapter alone computes token costs and the truncation stamp. +/// admitted together. Metadata must describe this unit. The adapter alone computes +/// token costs. #[derive(Debug)] pub struct RagRenderUnit { + /// Stable for the unit's life (a peer id, a card id): what her view keys it by. + pub key: String, pub content: String, pub metadata: serde_json::Map, + /// What the unit is and how to reopen it once collapsed; `None` when a collapsed + /// unit may leave her view entirely. + pub pointer: Option, } -impl From for RagRenderUnit { - fn from(content: String) -> Self { +impl RagRenderUnit { + pub fn new(key: impl Into, content: impl Into) -> Self { Self { - content, + key: key.into(), + content: content.into(), metadata: serde_json::Map::new(), + pointer: None, } } } /// A positron `ViewState` rendered for a mind. Kinds own atomic projections; -/// budgeting, packing, cursors and token counting belong to the shared adapter. +/// token counting and delivery belong to the shared adapter. pub trait RagRenderable: DeserializeOwned + Send + Sync + 'static { /// The positron state kind this renders (e.g. `RosterViewState::KIND`). The /// SAME const the web renderer subscribes to — that shared const is what makes @@ -126,41 +129,13 @@ pub trait RagRenderable: DeserializeOwned + Send + Sync + 'static { /// The grounding block label a citizen sees, e.g. `"who is here"`. const BLOCK: &'static str; - /// The verb that yields this in full when the budget could only fit part. + /// The verb that yields this in full when her view shows only part of it. /// Spelled exactly as a citizen would type it ([[command-names-must-be-accurate]]). const EXPAND: Option<&'static str>; - /// The smallest complete statement this kind can make, in tokens. Same - /// contract as [`RagSource::floor_tokens`] — measured, not aspirational. - /// - /// A FUNCTION, not an associated const, to match how every other RagSource - /// states its floor (`room_board_source::floor_tokens` returns 32, the roster - /// and doctrine sources return 0). Shipped first as `const FLOOR_TOKENS: u32`, - /// which put a second SHAPE on one contract and tripped the de-hardcode guard - /// (`context_budget::no_new_hardcoded_context_or_prompt_size_constant_anywhere_in_the_crate`, - /// which scans `const`s whose name contains TOKEN for bare literals). The guard - /// was right to fire on a fresh shape in the file that is meant to be the - /// template every future ViewState source is copied from — one contract, one - /// spelling. - /// - /// This is a per-UNIT content floor ("one roster line"), not a context bound: - /// it scales with what a unit costs to say, not with the served window, which - /// is why it is a measured constant here and a fraction nowhere. - fn floor_tokens() -> u32; - - /// Source-owned appetite, shared with non-ViewState grounding sources. - fn budget_claim(window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - crate::cognition::rag_budget::RagSourceBudget::retrieval( - Self::KIND, - Self::floor_tokens(), - window, - headroom, - ) - } - - /// Atomic units, **most-salient first**. Each must stand alone: the adapter - /// packs a prefix of this list and drops the rest, so unit `n` may never - /// depend on unit `n+1` having been included. + /// Atomic units, **most-salient first**. Each must stand alone: the view may + /// collapse any of them independently, so unit `n` may never depend on unit + /// `n+1` being shown whole. /// /// An empty vec is the honest "nothing to say" and renders NO block — never a /// header with nothing under it ([[fallbacks-are-illegal-fail-loud]]: an empty @@ -196,18 +171,6 @@ pub trait RagRenderable: DeserializeOwned + Send + Sync + 'static { } } -/// Rough token estimate. The allocator's contract is `tokens_used <= budget`, so -/// this errs HIGH: over-estimating costs a unit, under-estimating overruns the -/// window, and only one of those corrupts a turn. -/// -/// A shared helper rather than a per-source guess — the divergent hand-rolled -/// estimates are exactly how sources ended up asking for 12-80x their real size. -pub(crate) fn estimate_tokens(text: &str) -> u32 { - // ~3.5 chars/token is conservative for English prose with punctuation; the - // ceil keeps a one-word unit from estimating as free. - ((text.len() as f32 / 3.5).ceil() as u32).max(1) -} - /// THE adapter: any [`RagRenderable`] `ViewState` is a [`RagSource`]. /// /// Generic over the kind, so N kinds cost N small impls and zero new plumbing. @@ -291,8 +254,7 @@ pub trait RoomScopedView: RagRenderable {} /// const KIND: &'static str = "node-temperature"; /// const BLOCK: &'static str = "node temperature"; /// const EXPAND: Option<&'static str> = None; -/// fn floor_tokens() -> u32 { 4 } -/// fn units(&self, _viewer: uuid::Uuid) -> Vec { vec![format!("{} C", self.celsius).into()] } +/// fn units(&self, _viewer: uuid::Uuid) -> Vec { vec![RagRenderUnit::new("celsius", format!("{} C", self.celsius))] } /// } /// impl NodeScopedView for NodeTemperature {} /// let _ = ViewStateRagSource::::new(Substrate::new()); @@ -342,38 +304,6 @@ impl ViewStateRagSource { let envelope = substrate.cache().get(V::KIND)?; serde_json::from_value(envelope.payload.clone()).ok() } - - /// Pack as many whole units as fit starting at index `from`. Ruling-a: - /// only `deliver` calls this now, always from zero — every turn - /// re-derives fresh, so packing rules can never diverge between calls. - fn pack( - &self, - units: Vec, - budget: u32, - from: usize, - ) -> (Vec, u32, usize) { - let mut items = Vec::new(); - let mut used = 0u32; - let mut next = from; - for mut unit in units.into_iter().skip(from) { - let cost = estimate_tokens(&unit.content); - if used + cost > budget { - break; - } - used += cost; - next += 1; - unit.metadata - .insert("kind".into(), serde_json::json!(V::KIND)); - unit.metadata - .insert("block".into(), serde_json::json!(V::BLOCK)); - items.push(RagItem { - content: unit.content, - tokens: cost, - metadata: serde_json::Value::Object(unit.metadata), - }); - } - (items, used, next) - } } impl ViewStateRagSource { @@ -410,43 +340,35 @@ impl RagSource for ViewStateRagSource { V::EXPAND } - fn floor_tokens(&self) -> u32 { - V::floor_tokens() - } - - fn budget_claim(&self, window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - V::budget_claim(window, headroom) - } - - - async fn deliver( - &self, - _ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - let view = self.current(_ctx); + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + let view = self.current(ctx); // The ONE room gate, not a second copy of it: a room-scoped kind whose // view describes a DIFFERENT room than this turn abstains, with the same // probe every other room-scoped source emits. let units = match view { - Some(v) if room_scope_allows(v.room(), _ctx, V::KIND) => v.units(_ctx.persona_id), + Some(v) if room_scope_allows(v.room(), ctx, V::KIND) => v.units(ctx.persona_id), _ => Vec::new(), }; - let total = units.len(); - let (items, tokens_used, next) = self.pack(units, budget, 0); - RagDelivery { - source_id: V::KIND.to_string(), - items, - tokens_used, - // Ruling a: no resumable handle — the flag says "more exists" and - // the next deliver re-derives from scratch (a larger budget simply - // fits more). See rag_budget for the two readers of this flag. - truncated: next < total, - resolution_used: resolution, - } + let items = units + .into_iter() + .map(|mut unit| { + unit.metadata + .insert("kind".into(), serde_json::json!(V::KIND)); + unit.metadata + .insert("block".into(), serde_json::json!(V::BLOCK)); + let item = RagItem::whole( + unit.key, + unit.content, + serde_json::Value::Object(unit.metadata), + ); + match unit.pointer { + Some(pointer) => item.with_pointer(pointer), + None => item, + } + }) + .collect(); + RagDelivery::of(V::KIND, items, false) } - } // ─────────────────────── OUTLIER A: the roster (people) ─────────────────────── @@ -470,17 +392,6 @@ impl RagRenderable for continuum_positron::RosterViewState { const KIND: &'static str = continuum_positron::RosterViewState::KIND; const BLOCK: &'static str = "who is here"; const EXPAND: Option<&'static str> = Some("room/members"); - /// One member line, measured: a name plus a short role runs ~10 tokens. The - /// floor is ONE PERSON — under any budget that admits this source at all, a - /// citizen should learn that at least someone is here. - fn budget_claim(window: u32, headroom: u32) -> crate::cognition::rag_budget::RagSourceBudget { - super::room_roster_source::roster_budget_claim(Self::KIND, window, headroom) - } - - fn floor_tokens() -> u32 { - 10 - } - fn units(&self, viewer: uuid::Uuid) -> Vec { // STABLE ORDER for the mind (2026-09-01, Benchy hit_rate=0.0): this // block renders at ~0.4% prompt depth, and "presence order" rotates @@ -529,7 +440,11 @@ impl RagRenderable for continuum_positron::RosterViewState { // role, are the stable facts; whether a peer is busy this second is // presence — the live view carries it, and it belongs in the volatile // tail if a turn ever needs it ([[a-mutating-system-prompt-destroys-kv-reuse]]). - let mut unit = RagRenderUnit::from(line); + // Key = peer id (stable across turns). Pointer = the bare name: a member + // line is ~10 tokens so the view rarely collapses one, but when it does she + // still knows WHO is here, and `room/members` yields the rest. + let mut unit = RagRenderUnit::new(slot.member_id.to_string(), line); + unit.pointer = Some(slot.display_name.clone()); unit.metadata .insert("peer_id".into(), serde_json::json!(slot.member_id)); unit.metadata diff --git a/core/continuum-mind/src/persona/viewstate_rag/tests.rs b/core/continuum-mind/src/persona/viewstate_rag/tests.rs index 96df97afbe..fe81ac920a 100644 --- a/core/continuum-mind/src/persona/viewstate_rag/tests.rs +++ b/core/continuum-mind/src/persona/viewstate_rag/tests.rs @@ -148,15 +148,7 @@ fn a_viewer_absent_from_the_roster_marks_nobody() { async fn a_present_peer_reaches_the_citizens_grounding() { let source: ViewStateRagSource = ViewStateRagSource::per_room(roster_registry(&["Anwen", "Asha"])); - // The canonical kind owns the same small claim as its legacy reader; - // adapting it through ViewState must not buy a retrieval-sized share. - for window in [0, 256, 2048, 51_712] { - let claim = source.budget_claim(window, window); - assert_eq!(claim.max_tokens, window / 64); - assert_eq!(claim.min_tokens, 0); - assert_eq!(claim.floor_tokens, 0); - } - let delivery = source.deliver(&ctx(), 500, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; let rendered = delivery .items .iter() @@ -165,31 +157,25 @@ async fn a_present_peer_reaches_the_citizens_grounding() { .join("\n"); assert!(rendered.contains("Anwen"), "peer missing: {rendered}"); assert!(rendered.contains("Asha"), "peer missing: {rendered}"); - assert!(delivery.tokens_used <= 500); } -/// what this catches: the all-or-nothing failure `floor_tokens` exists to -/// prevent. Under a budget that fits one member, the citizen must learn about -/// ONE person — not receive an empty block, and not overrun the window. +/// what this catches: a source that takes a size. Every member reaches the view as its +/// own item keyed by peer id (stable across turns, so an unchanged member appends +/// nothing); which level each shows at is the one allocation's choice, never the source's. #[tokio::test] -async fn a_tight_budget_yields_fewer_units_never_a_chopped_one() { +async fn every_member_is_delivered_keyed_by_peer_id() { let source: ViewStateRagSource = ViewStateRagSource::per_room(roster_registry(&["Anwen", "Asha", "Anon"])); - // 8 tokens, against ~4-token member lines: fits two, not three. (12 was - // the first guess and it fit ALL THREE exactly — the packing was right and - // the test's arithmetic was wrong, which is worth saying out loud because - // "make the failing assert pass" is how a real invariant gets weakened.) - let delivery = source.deliver(&ctx(), 8, ResolutionPreference::Raw).await; - assert!(!delivery.items.is_empty(), "a fitting unit must be delivered"); - assert!(delivery.items.len() < 3, "budget 8 cannot fit all three"); - assert!( - delivery.tokens_used <= 8, - "the allocator's contract is tokens_used <= budget, got {}", - delivery.tokens_used - ); + let delivery = source.deliver(&ctx()).await; + assert_eq!(delivery.items.len(), 3, "no member is dropped: {:?}", delivery.items); + assert!(!delivery.truncated); + let keys: Vec<_> = delivery.items.iter().map(|i| i.key.clone()).collect(); + for id in 1..=3u128 { + assert!(keys.contains(&Uuid::from_u128(id).to_string()), "{keys:?}"); + } assert!( - delivery.truncated, - "undelivered members must be resumable, not silently dropped" + delivery.items.iter().all(|i| i.pointer.is_some()), + "a collapsed member stays reachable by name" ); // Regression for card 84dee23e: live roster atoms must feed the actual // turn-author and wake consumers, including under partial admission. @@ -220,19 +206,19 @@ async fn a_tight_budget_yields_fewer_units_never_a_chopped_one() { for name in admitted.values() { assert!(wake[0].content.contains(name)); } - let transcript = RagDelivery { - source_id: "airc".into(), - items: (1..=3) - .map(|i| RagItem { - content: format!("distinct observation {i}"), - tokens: 4, - metadata: serde_json::json!({"peer_id": Uuid::from_u128(i).to_string()}), + let transcript = RagDelivery::of( + "airc", + (1..=3) + .map(|i| { + RagItem::whole( + format!("event-{i}"), + format!("distinct observation {i}"), + serde_json::json!({"peer_id": Uuid::from_u128(i).to_string()}), + ) }) .collect(), - tokens_used: 12, - truncated: false, - resolution_used: ResolutionPreference::Raw, - }; + false, + ); let own = Uuid::from_u128(3).to_string(); let turns = crate::cognition::conversation::workspace_turns::build_workspace_turns( &[delivery, transcript], @@ -253,14 +239,13 @@ async fn a_tight_budget_yields_fewer_units_never_a_chopped_one() { } } -/// what this catches: an unconditional cursor. If a fully-delivered source -/// still handed back a cursor, the allocator would spend a later turn's budget -/// resuming a source with nothing left to say. +/// what this catches: a source flagging `truncated` when it holds nothing more. The +/// flag now means only "more exists behind the expand command", never a size cut. #[tokio::test] -async fn a_complete_delivery_offers_no_continuation() { +async fn a_complete_delivery_is_not_truncated() { let source: ViewStateRagSource = ViewStateRagSource::per_room(roster_registry(&["Anwen"])); - let delivery = source.deliver(&ctx(), 500, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; assert_eq!(delivery.items.len(), 1); assert!(!delivery.truncated); } @@ -297,7 +282,7 @@ async fn the_roster_follows_the_turn_into_a_room_that_is_not_the_first_one() { let in_other = RagContext::for_persona_in_room(Uuid::from_u128(0x9), 0, Uuid::from_u128(OTHER)); let delivery = source - .deliver(&in_other, 500, ResolutionPreference::Raw) + .deliver(&in_other) .await; let rendered = delivery .items @@ -334,7 +319,7 @@ async fn reading_a_room_that_was_never_projected_does_not_create_one() { let elsewhere = RagContext::for_persona_in_room(Uuid::from_u128(0x9), 0, Uuid::from_u128(0xd0 + n)); let delivery = source - .deliver(&elsewhere, 500, ResolutionPreference::Raw) + .deliver(&elsewhere) .await; assert!(delivery.items.is_empty(), "an unprojected room has no view"); } @@ -355,7 +340,7 @@ async fn a_roomless_turn_gets_no_roster_rather_than_an_arbitrary_rooms() { let source: ViewStateRagSource = ViewStateRagSource::per_room(roster_registry(&["Anwen"])); let roomless = RagContext::for_persona(Uuid::from_u128(0x9), 0); - let delivery = source.deliver(&roomless, 500, ResolutionPreference::Raw).await; + let delivery = source.deliver(&roomless).await; assert!(delivery.items.is_empty(), "{:?}", delivery.items); assert_eq!(delivery.tokens_used, 0); assert!(!delivery.truncated); @@ -368,7 +353,7 @@ async fn a_roomless_turn_gets_no_roster_rather_than_an_arbitrary_rooms() { async fn an_empty_view_renders_no_block_rather_than_an_empty_header() { let source: ViewStateRagSource = ViewStateRagSource::per_room(Arc::new(PerRoomSubstrates::new())); - let delivery = source.deliver(&ctx(), 500, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; assert!(delivery.items.is_empty()); assert_eq!(delivery.tokens_used, 0); assert!(!delivery.truncated); diff --git a/core/continuum-mind/src/persona/wall_source.rs b/core/continuum-mind/src/persona/wall_source.rs index 944f8a22d2..8a88534c21 100644 --- a/core/continuum-mind/src/persona/wall_source.rs +++ b/core/continuum-mind/src/persona/wall_source.rs @@ -3,7 +3,7 @@ //! //! ### Why this source exists (the shared-layer grounding) //! -//! The roster ([`RoomRosterSource`](super::room_roster_source)) grounds a +//! The roster (the `RosterViewState` source) grounds a //! persona in WHO is present; the doctrine //! ([`RoomDoctrineSource`](super::room_doctrine_source)) in WHAT KIND of //! room it is (the participation contract). The WALL grounds it in the @@ -46,9 +46,9 @@ //! defer-tolerant grounding faculty, like the active-work + workspace-map //! sources. //! - Atomic unit = ONE pinned post. Unlike the doctrine (a single current -//! contract) the wall is a BOARD of many posts, so this source packs -//! whole posts greedily within budget and stamps `truncated` when posts -//! remain beyond it (ruling a: nothing resumes — see expand_command). +//! contract) the wall is a BOARD of many posts, so this source delivers +//! every pinned post as its own keyed item (key = post id) with a summary +//! and a pointer; the prompt view's one allocation picks each level. use std::sync::Arc; @@ -56,17 +56,10 @@ use airc_core::doctrine::WallPostPublished; use airc_lib::AircError; use async_trait::async_trait; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::WALL; -/// Token estimate — the ONE canonical chars/4 estimator -/// (`cognition::token_budget`), shared by every RAG source so the replay -/// ledger's numbers match. -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// Abstract reader over the airc room wall. Production rides on /// `airc_lib::Airc::wall_posts`; tests stub it without a daemon. Mirrors /// the `AircDoctrineReader` / `AircRosterReader` rails. @@ -139,8 +132,7 @@ fn ledgers_for_context(posts: Vec, labels: Option<&CardLabels let Ok(ledger) = serde_json::from_str::(&post.body) else { return Some(post); // an unreadable ledger renders as it is, unlabelled }; - let short = ledger.card_id.simple().to_string(); - let short = &short[..8]; + let short = airc_core::shown_id::shown_form(ledger.card_id); let head = match labels.get(&ledger.card_id) { Some((_, state)) if crate::cognition::card_facts::is_concluded(state) => return None, Some((title, state)) => { @@ -281,124 +273,32 @@ impl WallSource { format!("{}{}", Self::label(post), post.body) } - /// Fit a single post to `budget` tokens, truncating the BODY (never the - /// label) with a marker — used only when the FIRST post of a - /// (sub)delivery doesn't fit whole, so partial guidance still grounds the - /// persona rather than dropping the post entirely. Same - /// `estimate_tokens(s) = s.chars()/4 + 1` arithmetic the doctrine source - /// fits under: a string of `4*budget-4` chars estimates to exactly - /// `budget`. Returns `None` when the budget can't carry the label + - /// marker PLUS at least one char of real BODY — a block that's only the - /// label and a truncation marker spends tokens to say nothing, strictly - /// worse than no block (the bug an over-eager char-truncation hits when - /// the category prefix alone fills a tiny budget). - fn fit_post(post: &WallPostPublished, budget: u32) -> Option { - if budget == 0 { - return None; - } - let rendered = Self::render(post); - if estimate_tokens(&rendered) <= budget { - return Some(rendered); - } - const MARKER: &str = "\n…[post truncated]"; - let label = Self::label(post); - let reserved = label.chars().count() + MARKER.chars().count(); - let max_chars = (budget as usize).saturating_mul(4).saturating_sub(4); - if max_chars <= reserved { - // No room for the label + marker plus any real body content. - return None; - } - let body_chars = max_chars - reserved; - let body_prefix: String = post.body.chars().take(body_chars).collect(); - if body_prefix.is_empty() { - return None; - } - Some(format!("{label}{body_prefix}{MARKER}")) - } - - /// Build a [`RagItem`] for one pinned post from already-fitted content. - fn item(post: &WallPostPublished, content: String) -> RagItem { - let tokens = estimate_tokens(&content); - RagItem { + /// One pinned post as an item: whole `[category]\n{body}`, keyed by its post id. + /// Summary = `[category] ` (a line boundary, never a mid-text cut), only + /// when the post has more than that line; pointer = the post id and the verb that + /// lists the wall again. + fn item(post: &WallPostPublished) -> RagItem { + let content = Self::render(post); + let first_line = post.body.lines().map(str::trim).find(|l| !l.is_empty()); + let summary = first_line + .map(|line| format!("[{}] {line}", post.category)) + .filter(|summary| summary.len() < content.len()); + let mut item = RagItem::whole( + post.post_id.to_string(), content, - tokens, - metadata: serde_json::json!({ + serde_json::json!({ "post_id": post.post_id.to_string(), "category": post.category, "supersedes": post.supersedes.map(|u| u.to_string()), "published_by": post.published_by.as_uuid().to_string(), "published_at_ms": post.published_at_ms, }), + ) + .with_pointer(format!("[wall post {} ({}): persona/wall/list]", post.post_id, post.category)); + if let Some(summary) = summary { + item = item.with_summary(summary); } - } - - /// Pack whole pinned posts from `start` greedily within `budget`. - /// Returns the packed items, the tokens they consumed, and the index of - /// the first UNPACKED post (`Some(i)` → more remain, hand back a cursor; - /// `None` → the board is fully delivered). - /// - /// If the very first candidate doesn't fit whole, it is truncated with a - /// marker so partial guidance still lands (mirrors the doctrine source); - /// a budget too small to carry even a truncated post yields no block and - /// no cursor — the budget regime simply can't carry this board. - fn pack( - posts: &[WallPostPublished], - start: usize, - budget: u32, - ) -> (Vec, u32, Option) { - let mut items: Vec = Vec::new(); - let mut used: u32 = 0; - let mut i = start; - while i < posts.len() { - let rendered = Self::render(&posts[i]); - let toks = estimate_tokens(&rendered); - if used.saturating_add(toks) <= budget { - // Whole post fits. - items.push(Self::item(&posts[i], rendered)); - used += toks; - i += 1; - } else if items.is_empty() { - // Nothing packed yet and this post overflows alone → - // truncate its body to fill the budget, then stop. A - // truncated post fills what remains; the delivery stamps - // `truncated` so the caller sees it was cut (ruling a: - // nothing resumes from here). - if let Some(truncated) = Self::fit_post(&posts[i], budget) { - let item = Self::item(&posts[i], truncated); - used += item.tokens; - items.push(item); - } - i += 1; - break; - } else { - // Already packed whole posts; stop — the rest stays out of - // budget and the delivery stamps `truncated`. - break; - } - } - let next = if i < posts.len() { Some(i) } else { None }; - (items, used, next) - } - - /// Wrap a packed slice into a delivery, stamping `truncated` when `next` - /// posts remain beyond the budget. Nothing resumes from here (ruling a): - /// the positional cursor and its room-binding went out with - /// deliver_continuation — the way to see the rest is this source's - /// expand_command verb (`persona/wall/list`). - fn delivery( - &self, - items: Vec, - used: u32, - next: Option, - resolution: ResolutionPreference, - ) -> RagDelivery { - RagDelivery { - source_id: WALL.to_string(), - items, - tokens_used: used, - truncated: next.is_some(), - resolution_used: resolution, - } + item } } @@ -415,29 +315,12 @@ impl RagSource for WallSource { Some("persona/wall/list") } - /// One wall post's title line. A pinned document's NAME is a complete - /// statement — she knows the plan exists and can fetch it. - fn floor_tokens(&self) -> u32 { - 32 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - let empty = |res| RagDelivery { - source_id: WALL.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: res, - }; + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + let empty = || RagDelivery::empty(WALL); // Persona-scoped (defense in depth, same shape as the roster/doctrine). if ctx.persona_id != self.persona_id { - return empty(ResolutionPreference::Placeholder); + return empty(); } // ROOM-SCOPED, RESOLVED FROM THE TURN — not from the room this source was // bound to at construction. `supervisor.rs` builds it with @@ -461,7 +344,7 @@ impl RagSource for WallSource { persona_id = %ctx.persona_id, "synthetic nil-room context — no wall, and no fallback to the bound room" ); - return empty(ResolutionPreference::Placeholder); + return empty(); } Some(turn) => Some(turn), // An UNSTAMPED context (background consolidation, an idle tick) keeps the @@ -506,7 +389,7 @@ impl RagSource for WallSource { persona_id = %self.persona_id, "wall_posts: read failed — empty delivery, cognition stays up" ); - return empty(ResolutionPreference::Placeholder); + return empty(); } }; continuum_base::probe!( @@ -519,7 +402,7 @@ impl RagSource for WallSource { ); // No pinned posts → no block (normal: most rooms have an empty wall). if posts.is_empty() { - return empty(resolution); + return empty(); } // Ledgers, standings, recipes, child announcements and activity bundles are @@ -529,22 +412,19 @@ impl RagSource for WallSource { crate::experience::wall_records::current_wall_records(posts), self.reader.card_labels(effective_room).await.as_ref(), ); - let (items, used, next) = Self::pack(&posts, 0, budget); - if items.is_empty() { - // Budget too small to carry even a truncated first post. - return empty(resolution); + // Posts a concluded-ledger rule dropped can leave the board empty. + if posts.is_empty() { + return empty(); } + let items: Vec = posts.iter().map(Self::item).collect(); tracing::debug!( persona_id = %self.persona_id, - budget, posts = posts.len(), - delivered = items.len(), - tokens = used, "wall_posts: deliver" ); - self.delivery(items, used, next, resolution) + RagDelivery::of(WALL, items, false) } } diff --git a/core/continuum-mind/src/persona/wall_source/tests.rs b/core/continuum-mind/src/persona/wall_source/tests.rs index 0bc7cd9675..60122f6e0f 100644 --- a/core/continuum-mind/src/persona/wall_source/tests.rs +++ b/core/continuum-mind/src/persona/wall_source/tests.rs @@ -147,7 +147,7 @@ let mut reader = StubReader::new(vec![ledger(live), ledger(merged)]); reader.board = Some(board); let delivery = WallSource::new(persona(), Arc::new(reader)) - .deliver(&ctx(), 10_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let text = delivery.items.iter().map(|i| i.content.as_str()).collect::>().join("\n"); let live8 = live.simple().to_string(); @@ -206,7 +206,7 @@ ])), ); let delivery = source - .deliver(&ctx(), 10_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert_eq!(delivery.items.len(), 2); let text = delivery @@ -239,11 +239,7 @@ assert_ne!(bound, turn, "fixture is degenerate if these match"); let source = WallSource::new(persona(), reader.clone()).for_room(bound); let delivery = source - .deliver( - &RagContext::for_persona_in_room(persona(), 1_000_000, turn), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona_in_room(persona(), 1_000_000, turn)) .await; assert_eq!( // safe: test-local Mutex, single-threaded here. @@ -268,11 +264,7 @@ let bound = Uuid::parse_str("00000000-0000-0000-0000-0000000000cc").unwrap(); let source = WallSource::new(persona(), reader.clone()).for_room(bound); let delivery = source - .deliver( - &RagContext::for_persona_in_room(persona(), 1_000_000, Uuid::nil()), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona_in_room(persona(), 1_000_000, Uuid::nil())) .await; assert!(delivery.items.is_empty(), "a nil room must render no wall"); assert_eq!( @@ -293,7 +285,7 @@ ])); let source = WallSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert_eq!(delivery.items.len(), 2); assert!(delivery.items[0] @@ -311,7 +303,7 @@ let reader = Arc::new(StubReader::new(vec![])); let source = WallSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); assert_eq!(delivery.tokens_used, 0); @@ -326,10 +318,9 @@ reader.set_fail(true); let source = WallSource::new(persona(), reader); let delivery = source - .deliver(&ctx(), 1_000, ResolutionPreference::Raw) + .deliver(&ctx()) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: cross-persona ctx gets nothing (defense in depth). @@ -348,11 +339,7 @@ let bound = Uuid::parse_str("00000000-0000-0000-0000-0000000000cc").unwrap(); let source = WallSource::new(persona(), reader.clone()).for_room(bound); let _ = source - .deliver( - &RagContext::for_persona(persona(), 1_000_000), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona(persona(), 1_000_000)) .await; assert_eq!( // safe: test-local Mutex; the only writer is the stub above, single-threaded here. @@ -368,74 +355,31 @@ let source = WallSource::new(persona(), reader); let alien = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); let delivery = source - .deliver( - &RagContext::for_persona(alien, 1_000_000), - 1_000, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona(alien, 1_000_000)) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } - // what this catches: a board too large for one budget packs whole posts and - // stamps `truncated` — nothing resumes from here (ruling a); the rest becomes - // visible when a bigger budget re-derives fresh, or via the expand_command verb. + // what this catches: a large board is delivered WHOLE, one item per post keyed by its + // post id, each with a `[category] ` summary and a persona/wall/list + // pointer, `truncated` false and no truncation marker; the view, not the source, sizes it. #[tokio::test] - async fn overflow_truncates_and_a_bigger_budget_sees_the_rest() { - // Each rendered post ("[c]\n" + 200 chars) ~= 51 tokens; budget 60 - // admits exactly one whole post per call. - let body = "y".repeat(200); - let reader = Arc::new(StubReader::new(vec![ - post("a", &body), - post("b", &body), - post("c", &body), - ])); - let source = WallSource::new(persona(), reader); - - let first = source.deliver(&ctx(), 60, ResolutionPreference::Raw).await; - assert_eq!(first.items.len(), 1, "one whole post fits in budget 60"); - assert_eq!(first.items[0].metadata["category"], "a"); - assert!( - first.truncated, - "two posts remain beyond the budget → truncated must be stamped" - ); - - // No cursor to resume: a fresh call under a bigger budget re-derives and - // admits all three — that is how the rest is seen now. - let full = source.deliver(&ctx(), 400, ResolutionPreference::Raw).await; - assert_eq!(full.items.len(), 3); - assert!(!full.truncated); - } + async fn every_post_is_delivered_whole_with_levels() { + let body = format!("first line\n{}", "y".repeat(10_000)); + let posts = vec![post("a", &body), post("b", &body), post("c", &body)]; + let ids: Vec = posts.iter().map(|p| p.post_id.to_string()).collect(); + let source = WallSource::new(persona(), Arc::new(StubReader::new(posts))); - // what this catches: an oversized FIRST post is truncated and NEVER - // overspends the budget, across the whole budget regime — the same - // marker-only-overspend bug the doctrine source's adversarial review - // caught (PR #1651). Invariant: for ANY budget, either no block, or the - // delivered tokens fit the budget AND carry real content. - #[tokio::test] - async fn oversized_first_post_never_overspends_across_budget_regime() { - let big = "z".repeat(10_000); - for budget in [1u32, 2, 3, 5, 6, 7, 8, 20, 100, 500] { - let reader = Arc::new(StubReader::new(vec![post("plan", &big)])); - let source = WallSource::new(persona(), reader); - let delivery = source - .deliver(&ctx(), budget, ResolutionPreference::Raw) - .await; - assert!( - delivery.tokens_used <= budget, - "budget {budget}: overspent ({} > {budget})", - delivery.tokens_used - ); - if let Some(item) = delivery.items.first() { - let only_marker = - item.content.trim_start().starts_with('…') || !item.content.contains('z'); - assert!( - !only_marker, - "budget {budget}: delivered a content-free block: {:?}", - item.content - ); - } + let d = source.deliver(&ctx()).await; + assert_eq!(d.items.len(), 3); + assert!(!d.truncated); + for (item, id) in d.items.iter().zip(&ids) { + assert_eq!(&item.key, id); + assert!(item.content.ends_with(&body), "post body whole, never cut"); + assert!(!item.content.contains("truncated")); + let cat = item.metadata["category"].as_str().unwrap_or_default(); + assert_eq!(item.summary.as_deref(), Some(format!("[{cat}] first line").as_str())); + let pointer = item.pointer.as_deref().unwrap_or_default(); + assert!(pointer.contains(id.as_str()) && pointer.contains("persona/wall/list"), "{pointer}"); } } - diff --git a/core/continuum-mind/src/persona/workspace_map_source.rs b/core/continuum-mind/src/persona/workspace_map_source.rs index 46da0ef53c..ec00476242 100644 --- a/core/continuum-mind/src/persona/workspace_map_source.rs +++ b/core/continuum-mind/src/persona/workspace_map_source.rs @@ -47,17 +47,10 @@ use std::sync::Arc; use async_trait::async_trait; -use crate::cognition::rag_budget::{ - RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, -}; +use crate::cognition::rag_budget::{RagContext, RagDelivery, RagItem, RagSource}; use crate::cognition::faculty_ids::WORKSPACE_MAP; -/// Token estimate — the ONE canonical chars/4 estimator (`cognition::token_budget`), -/// shared by every RAG source so the replay ledger's numbers match. (Was a private -/// copy — converged.) -use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; - /// The real shape of the workspace: the root the tools act in, plus its /// top-level directory names (the navigation structure a persona globs against). #[derive(Debug, Clone, PartialEq)] @@ -320,30 +313,6 @@ impl WorkspaceMapSource { Arc::new(FixedRootWorkspaceLayoutReader::new(root)), ) } - - /// Fit the rendered map to `budget` tokens. The map is small (a root path + - /// a directory list) and never approaches the standing-framing budget in - /// practice; truncation exists only to honor the budget contract. Same shape - /// as the doctrine source: truncate with a marker, or emit no block when the - /// budget can't carry the marker plus real content. - fn fit_body(body: &str, budget: u32) -> Option { - if budget == 0 { - return None; - } - if estimate_tokens(body) <= budget { - return Some(body.to_string()); - } - const MARKER: &str = "\n…[workspace map truncated]"; - let marker_chars = MARKER.chars().count(); - let max_chars = (budget as usize).saturating_mul(4).saturating_sub(4); - if max_chars <= marker_chars { - return None; - } - let char_budget = max_chars - marker_chars; - let mut out: String = body.chars().take(char_budget).collect(); - out.push_str(MARKER); - Some(out) - } } #[async_trait] @@ -356,29 +325,12 @@ impl RagSource for WorkspaceMapSource { Some("code/tree") } - /// MEASURED 32 tokens: the root line naming the workspace and its top-level - /// entry count — the unit that distinguishes "empty" from "I cannot see it". - fn floor_tokens(&self) -> u32 { - 40 - } - - async fn deliver( - &self, - ctx: &RagContext, - budget: u32, - resolution: ResolutionPreference, - ) -> RagDelivery { - let empty = |res| RagDelivery { - source_id: WORKSPACE_MAP.to_string(), - items: Vec::new(), - tokens_used: 0, - truncated: false, - resolution_used: res, - }; + async fn deliver(&self, ctx: &RagContext) -> RagDelivery { + let empty = || RagDelivery::empty(WORKSPACE_MAP); // Persona-scoped (defense in depth, same shape as the roster/doctrine). if ctx.persona_id != self.persona_id { - return empty(ResolutionPreference::Placeholder); + return empty(); } let layout = match self.reader.layout().await { @@ -389,7 +341,7 @@ impl RagSource for WorkspaceMapSource { persona_id = %self.persona_id, "workspace_map: layout read failed — empty delivery, cognition stays up" ); - return empty(ResolutionPreference::Placeholder); + return empty(); } }; @@ -408,34 +360,32 @@ impl RagSource for WorkspaceMapSource { body.push('\n'); body.push_str(&line); } - let Some(content) = Self::fit_body(&body, budget) else { - return empty(resolution); - }; - let tokens = estimate_tokens(&content); tracing::debug!( persona_id = %self.persona_id, - budget, dirs = layout.top_level_dirs.len(), - tokens, "workspace_map: deliver" ); - RagDelivery { - source_id: WORKSPACE_MAP.to_string(), - items: vec![RagItem { - content, - tokens, - metadata: serde_json::json!({ - "root": layout.root.display().to_string(), - "top_level_dirs": layout.top_level_dirs, - }), - }], - tokens_used: tokens, - // One current layout snapshot per turn; no pagination. - truncated: false, - resolution_used: resolution, - } + // The coarser level is the documented first unit: the root line plus the entry + // count, which is what tells "empty" from "I cannot see it". + let summary = format!( + "This workspace is rooted at: {} ({} top-level entries)", + layout.root.display(), + layout.top_level_entries, + ); + let item = RagItem::whole( + "map", + body, + serde_json::json!({ + "root": layout.root.display().to_string(), + "top_level_dirs": layout.top_level_dirs, + }), + ) + .with_summary(summary) + .with_pointer("[workspace map: reopen with code/tree]"); + // One current layout snapshot per turn; no pagination. + RagDelivery::of(WORKSPACE_MAP, vec![item], false) } } diff --git a/core/continuum-mind/src/persona/workspace_map_source/tests.rs b/core/continuum-mind/src/persona/workspace_map_source/tests.rs index e8ed904811..bb194b18f4 100644 --- a/core/continuum-mind/src/persona/workspace_map_source/tests.rs +++ b/core/continuum-mind/src/persona/workspace_map_source/tests.rs @@ -44,7 +44,7 @@ }), ); let delivery = source - .deliver(&ctx(), 2048, ResolutionPreference::Raw) + .deliver(&ctx()) .await; let body = &delivery.items[0].content; for fact in [ @@ -151,7 +151,7 @@ async fn layout_surfaces_with_real_dirs() { let reader = Arc::new(StubReader::ok(&["apps", "core", "docs", "src"])); let source = WorkspaceMapSource::new(persona(), reader); - let delivery = source.deliver(&ctx(), 512, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; assert_eq!(delivery.items.len(), 1); let content = &delivery.items[0].content; // Both `core` and `src` are present — the exact ambiguity that tripped @@ -181,7 +181,7 @@ async fn grounds_without_steering() { let reader = Arc::new(StubReader::ok(&["core", "src"])); let source = WorkspaceMapSource::new(persona(), reader); - let delivery = source.deliver(&ctx(), 512, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; let content = delivery.items[0].content.to_lowercase(); assert!( !content.contains("rust is under") && !content.contains("rust lives"), @@ -194,9 +194,8 @@ #[tokio::test] async fn read_error_returns_empty_no_panic() { let source = WorkspaceMapSource::new(persona(), Arc::new(StubReader::err())); - let delivery = source.deliver(&ctx(), 512, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: cross-persona ctx gets nothing (defense in depth). @@ -205,14 +204,9 @@ let source = WorkspaceMapSource::new(persona(), Arc::new(StubReader::ok(&["core"]))); let alien = Uuid::parse_str("00000000-0000-0000-0000-000000000bbb").unwrap(); let delivery = source - .deliver( - &RagContext::for_persona(alien, 1_000_000), - 512, - ResolutionPreference::Raw, - ) + .deliver(&RagContext::for_persona(alien, 1_000_000)) .await; assert!(delivery.items.is_empty()); - assert_eq!(delivery.resolution_used, ResolutionPreference::Placeholder); } // what this catches: an empty workspace grounds WRITE-FIRST — it states the space @@ -223,7 +217,7 @@ #[tokio::test] async fn empty_layout_grounds_write_first() { let source = WorkspaceMapSource::new(persona(), Arc::new(StubReader::ok(&[]))); - let delivery = source.deliver(&ctx(), 512, ResolutionPreference::Raw).await; + let delivery = source.deliver(&ctx()).await; assert_eq!(delivery.items.len(), 1); let content = &delivery.items[0].content; assert!(content.contains("EMPTY"), "states it's empty: {content}"); @@ -243,8 +237,6 @@ ); } - // what this catches: an absurdly tiny budget never overspends — either no - // block, or a block that fits the budget (same contract as the doctrine). // what this catches (card 0c42c0bf): a citizen who leased a port for her dev server not // seeing it in her grounding, so she guesses a port or re-leases every turn; and a line // that costs prompt tokens for a citizen who holds no leases. @@ -270,20 +262,24 @@ assert!(!line.contains('\n'), "one line"); } + // what this catches: the map is delivered whole under the stable key "map", with the + // root-line-plus-count summary and the code/tree pointer, and never a truncation + // marker -- the view picks the level, the source never sizes. #[tokio::test] - async fn tiny_budget_never_overspends() { - let reader = Arc::new(StubReader::ok(&["apps", "core", "docs", "src", "tools"])); - for budget in [1u32, 2, 3, 5, 8, 20, 50] { - let source = WorkspaceMapSource::new(persona(), reader.clone()); - let delivery = source - .deliver(&ctx(), budget, ResolutionPreference::Raw) - .await; - assert!( - delivery.tokens_used <= budget, - "budget {budget}: overspent ({} > {budget})", - delivery.tokens_used - ); - } + async fn the_map_is_delivered_whole_with_levels() { + let source = WorkspaceMapSource::new( + persona(), + Arc::new(StubReader::ok(&["apps", "core", "docs", "src", "tools"])), + ); + let delivery = source.deliver(&ctx()).await; + let item = &delivery.items[0]; + assert_eq!(item.key, "map"); + assert!(item.content.contains("apps, core, docs, src, tools")); + assert!(!item.content.contains("truncated")); + let summary = item.summary.as_deref().expect("summary level"); + assert!(summary.contains("/repo") && summary.contains("5 top-level entries"), "{summary}"); + assert_eq!(item.pointer.as_deref(), Some("[workspace map: reopen with code/tree]")); + assert!(!delivery.truncated); } // what this catches: the production reader reads our RECORDED checkout (never the diff --git a/core/source-hygiene/src/context_codec.rs b/core/source-hygiene/src/context_codec.rs index 089675385b..81a4a6541f 100644 --- a/core/source-hygiene/src/context_codec.rs +++ b/core/source-hygiene/src/context_codec.rs @@ -16,6 +16,13 @@ //! - `collapse_outside_the_view`: collapsing what she sees anywhere but a view start. Working //! memory bounds RAM by handle; the view decides what she reads. //! - `hand_churn_labels`: ordering sources by a label (`churn_of`) instead of measured motion. +//! - `prompt_self_sizing`: anything that decides how much content enters her prompt outside the +//! ONE flexbox allocation per turn (Joel, 2026-10-28: "We called this flexbox budgeting"; +//! "Others shrink. She still has all of the context. Requires adherence"). A source delivers +//! levels (whole, summary, pointer); the allocation's claims decide which she sees. Measured +//! at ~40 sites on 2026-10-28, including a second `flex_allocate` over the served window in +//! `compose_for_turn` (FLOW-IMPLEMENTATION-PLAN §2d). When it reaches 0 the sizing methods go +//! private and this ratchet is deleted. use super::{SourceFile, SourceRule, Violation}; @@ -25,6 +32,38 @@ const PROMPT_ASSEMBLY: &str = "cognition/llm_deliberation_faculty/prompt/"; pub struct PromptMessagesOutsideTheView; pub struct CollapseOutsideTheView; pub struct HandChurnLabels; +pub struct PromptSelfSizing; + +/// The one allocation's owners: the prompt assembly runs it; `context_budget.rs` and the +/// allocator module define what it uses. +const ALLOCATION_OWNERS: [&str; 3] = [PROMPT_ASSEMBLY, "cognition/context_budget.rs", "cognition/rag_budget/"]; + +/// Calls that size prompt content on their own: the `ContextBudget` entry points and fraction +/// methods, the fixed share splits, and a second run of the flexbox. +const SELF_SIZING: [&str; 22] = [ + "ContextBudget::live(", + "ContextBudget::live_or_floor(", + "ContextBudget::from_window(", + "ContextBudget::from_window_for(", + "ContextBudget::from_window_unbounded(", + ".recall_tokens(", + ".grounding_tokens(", + ".tool_surface_tokens(", + ".latest_action_chars(", + ".dispatch_result_chars(", + ".render_slice_chars(", + ".catalog_summary_chars(", + ".echoed_arg_chars(", + ".trail_head_chars(", + ".recent_results_chars(", + ".receipt_archive_chars(", + ".default_response_tokens(", + "_SHARE_DENOM", + "budget_claim(", + "FlexboxRagBudgetAdapter::new(", + "adapter.allocate(", + "flex_allocate(", +]; fn sites(file: &SourceFile, rule: &'static str, hit: impl Fn(&str) -> bool) -> Vec { file.production_lines() @@ -68,6 +107,19 @@ impl SourceRule for HandChurnLabels { } } +impl SourceRule for PromptSelfSizing { + fn name(&self) -> &'static str { + "prompt_self_sizing" + } + + fn check(&self, file: &SourceFile) -> Vec { + if ALLOCATION_OWNERS.iter().any(|owner| file.rel.starts_with(owner)) || !file.rel.starts_with("cognition/") && !file.rel.starts_with("persona/") { + return Vec::new(); + } + sites(file, self.name(), |code| !code.contains("fn ") && SELF_SIZING.iter().any(|call| code.contains(call))) + } +} + #[cfg(test)] mod tests { use super::*; @@ -108,6 +160,13 @@ mod tests { hold(&HandChurnLabels, "The view orders a start by measured motion (continuum_context::motion)."); } + // what this catches: content sized outside the one flexbox allocation (Aiko turned over every act + // while ~40 sites sized for 159k and the prompt fit 48k, M5 2026-10-28). It may only fall. + #[test] + fn prompt_self_sizing_never_increases() { + hold(&PromptSelfSizing, "Deliver levels (whole, summary, pointer) and make the content a claim in the one allocation in prompt/view.rs; never size it at the source."); + } + // what this catches: the predicates that make the rules useful rather than noise. #[test] fn each_rule_catches_its_shape_and_spares_its_definition() { @@ -118,6 +177,10 @@ mod tests { assert_eq!(count(&CollapseOutsideTheView, "cognition/wm.rs", "self.collapse_results_over_cap();"), 1); assert_eq!(count(&CollapseOutsideTheView, "cognition/wm.rs", "pub fn collapse_over(&mut self, cap: usize) -> Collapsed {"), 0); assert_eq!(count(&HandChurnLabels, "cognition/a.rs", "churn_of(&block.faculty) < PromptChurn::Claims"), 1); + assert_eq!(count(&PromptSelfSizing, "cognition/recall_faculty.rs", "ContextBudget::from_window(context_window).recall_tokens()"), 1); + assert_eq!(count(&PromptSelfSizing, "persona/unified.rs", "let plan = adapter.allocate(&claims, budget);"), 1); + assert_eq!(count(&PromptSelfSizing, "cognition/llm_deliberation_faculty/prompt/view.rs", "let plan = flex_allocate(window, &claims);"), 0); + assert_eq!(count(&PromptSelfSizing, "cognition/context_budget.rs", "pub fn recall_tokens(&self) -> usize {"), 0); assert_eq!(count(&HandChurnLabels, "cognition/a.rs", "pub(super) fn churn_of(faculty: &str) -> PromptChurn {"), 0); } } diff --git a/protocol/typescript/persona/RagInspectAllocation.ts b/protocol/typescript/persona/RagInspectAllocation.ts deleted file mode 100644 index 0161532428..0000000000 --- a/protocol/typescript/persona/RagInspectAllocation.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * One source's allocation outcome — flattened from the library's - * BudgetAllocation for the wire. - */ -export type RagInspectAllocation = { sourceId: string, allocatedTokens: number, requestedFloor: number, requestedMin: number, requestedMax: number, -/** - * "satisfied" / "floor_only" / "dropped" / "under_provisioned" - */ -state: string, }; diff --git a/protocol/typescript/persona/RagInspectDelivery.ts b/protocol/typescript/persona/RagInspectDelivery.ts index 4ee35998e1..662d43fcd1 100644 --- a/protocol/typescript/persona/RagInspectDelivery.ts +++ b/protocol/typescript/persona/RagInspectDelivery.ts @@ -2,7 +2,7 @@ import type { RagInspectItem } from "./RagInspectItem"; /** - * One source's delivery — its budget, what it served, and the per- + * One source's delivery — what it served, and the per- * item rationale. */ -export type RagInspectDelivery = { sourceId: string, budgetRequested: number, tokensUsed: number, hasContinuation: boolean, items: Array, }; +export type RagInspectDelivery = { sourceId: string, tokensUsed: number, hasContinuation: boolean, items: Array, }; diff --git a/protocol/typescript/persona/RagInspectItem.ts b/protocol/typescript/persona/RagInspectItem.ts index 41ea56cb93..06966f2f0b 100644 --- a/protocol/typescript/persona/RagInspectItem.ts +++ b/protocol/typescript/persona/RagInspectItem.ts @@ -4,4 +4,12 @@ * One item the source delivered, with the mechanic-grade rationale * flattened for the wire (content_preview, score, age_s, etc). */ -export type RagInspectItem = { index: number, tokens: number, score: number, contentPreview: string, peerIdPrefix: string, lamport: number, ageS: number, }; +export type RagInspectItem = { index: number, tokens: number, score: number, contentPreview: string, peerIdPrefix: string, lamport: number, ageS: number, +/** + * The item has a coarser summary level her view can fall back to. + */ +hasSummary: boolean, +/** + * The item has a pointer level (what it is and how to reopen it). + */ +hasPointer: boolean, }; diff --git a/protocol/typescript/persona/RagInspectParams.ts b/protocol/typescript/persona/RagInspectParams.ts index b183c996e0..5762f8222f 100644 --- a/protocol/typescript/persona/RagInspectParams.ts +++ b/protocol/typescript/persona/RagInspectParams.ts @@ -12,7 +12,7 @@ export type RagInspectParams = { * Which persona's RAG pipeline to introspect — her name or id (full or the * short form shown in rosters). */ -persona: string, contextWindow?: number, aircFloor?: number, aircMax?: number, aircFetchLimit?: number, +persona: string, contextWindow?: number, aircFetchLimit?: number, /** * Optional absolute path for the JSONL capture trace. When set, * the inspection records the full turn there so other AIs / diff --git a/protocol/typescript/persona/RagInspectResult.ts b/protocol/typescript/persona/RagInspectResult.ts index b7c1e22149..1a490e61c9 100644 --- a/protocol/typescript/persona/RagInspectResult.ts +++ b/protocol/typescript/persona/RagInspectResult.ts @@ -1,32 +1,19 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RagInspectAllocation } from "./RagInspectAllocation"; import type { RagInspectDelivery } from "./RagInspectDelivery"; import type { RagInspectModelResponse } from "./RagInspectModelResponse"; /** - * Result of `persona/rag-inspect`. Carries the full allocation - * outcome + per-source deliveries so any AI inspecting the persona + * Result of `persona/rag-inspect`. Carries the per-source deliveries so any AI inspecting the persona * can answer the three canonical questions: * - "Would I respond as it requests at this step?" — full prompt * reconstructable from `deliveries`; when `chainInference=true`, * the actual model response is captured in `modelResponse`. - * - "Which layer is broken?" — per-source `allocations` show state - * (satisfied / floor_only / dropped / under_provisioned). + * - "Which layer is broken?" — per-source deliveries and each item's + * levels (`hasSummary`, `hasPointer`). * - "Is this contextually relevant?" — per-item score + age + * peer in the deliveries. */ -export type RagInspectResult = { personaId: string, personaName: string, contextWindow: number, -/** - * Sum of all source allocations. Useful for "did we leave - * tokens on the table?" telemetry. - */ -totalAllocated: number, -/** - * True if the allocator reported `escalation_needed` — a - * required source landed under-provisioned. Callers (AIs) - * SHOULD flag this in their reasoning. - */ -escalationNeeded: boolean, allocations: Array, deliveries: Array, +export type RagInspectResult = { personaId: string, personaName: string, contextWindow: number, deliveries: Array, /** * JSONL trace path (relative or absolute) when `trace_path` * was set on the request. Other AIs / mechanic-shop tools diff --git a/protocol/typescript/persona/SamplingProfile.ts b/protocol/typescript/persona/SamplingProfile.ts index f4362ebed6..cf5f14a436 100644 --- a/protocol/typescript/persona/SamplingProfile.ts +++ b/protocol/typescript/persona/SamplingProfile.ts @@ -36,10 +36,4 @@ repeatLastN: number, * sequence frequency, catching gap-separated loops the windowed * penalty misses (#181). 0.0 = off. llama.cpp-family gateways only. */ -frequencyPenalty: number, -/** - * Maximum tokens to generate per response. Derived from role's - * `max_response_chars` divided by approximate chars-per-token - * (typically 4 for English). - */ -maxNewTokens: number, }; +frequencyPenalty: number, }; diff --git a/protocol/typescript/tool/ToolOutputParams.ts b/protocol/typescript/tool/ToolOutputParams.ts index 97f6d757c3..3725937357 100644 --- a/protocol/typescript/tool/ToolOutputParams.ts +++ b/protocol/typescript/tool/ToolOutputParams.ts @@ -45,7 +45,7 @@ maxMatches?: number, */ byteOffset?: number, /** - * Requested byte count; a page fits the live render allowance. No bytes are + * Requested byte count; each encoded transport page is at most 64 KiB. No bytes are * discarded when this request spans multiple pages: nextByteOffset continues it. */ byteLength?: number, };