diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 99d4c371fd..0c21dde737 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -73,6 +73,12 @@ impl Source for Actions<'_> { items } + /// A read she has since read again or changed: a start gives it its outline, its whole + /// result one expand away by its handle. + fn superseded(&self) -> Vec { + self.memory.superseded_actions().into_iter().map(|seq| seq.to_string()).collect() + } + /// Once she has acted, the void said earlier in this epoch is superseded, never edited: /// her view reads as the timeline it is (the statement was true when it was made). fn retired(&self) -> Vec> { diff --git a/core/continuum-cognition/src/cognition/context_streams/blocks.rs b/core/continuum-cognition/src/cognition/context_streams/blocks.rs index 624a1785f0..c378a960d0 100644 --- a/core/continuum-cognition/src/cognition/context_streams/blocks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/blocks.rs @@ -1,7 +1,7 @@ //! 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 about the room it describes. 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. use continuum_context::source::{Item, Source}; @@ -9,6 +9,9 @@ use super::{priority, ContextMessage}; pub(crate) struct Grounding { pub faculty: String, + /// The room the block describes (`Contribution::room`), `None` for one that is hers in + /// every room. It names the item, so each room's block is one item of her view. + pub room: Option, /// The whole block. pub text: String, /// What it guarantees when the window is short: a long list's first units with a line @@ -16,6 +19,17 @@ pub(crate) struct Grounding { pub minimum: String, } +impl Grounding { + /// The block's header: its faculty, and the room it describes, so two rooms' blocks in + /// one view never read as one (the newest copy is no longer the current room's). + fn header(&self) -> String { + match self.room { + Some(room) => format!("[{}] (room {room})", self.faculty), + None => format!("[{}]", self.faculty), + } + } +} + impl Source for Grounding { fn name(&self) -> &str { &self.faculty @@ -28,8 +42,13 @@ 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) }] + let header = self.header(); + let full = ContextMessage::user(format!("{header}\n{}", self.text)); + let pointer = ContextMessage::user(format!("{header}\n{}", self.minimum)); + // Keyed by the room it describes: the same subject is the same item. Keyed by the + // faculty alone, a switch between two rooms superseded each room's block with the + // other's, and every switch back re-appended a block that had not changed. + let key = self.room.map_or_else(|| "block".to_owned(), |room| format!("room/{room}")); // map_or_else: a block that is hers in every room is one item + vec![Item { key, full, summary: None, pointer: Some(pointer) }] } } diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index cc5c45ba45..4594245baa 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -135,3 +135,28 @@ fn a_thought_renders_the_same_whatever_the_served_window() { memory.set_served_window(131_072); assert_eq!(render(&memory), narrow, "the window changed and the thought's rendering did not"); } + +// what this catches: a room's block re-appended on every room switch. Keyed by the faculty +// alone, two rooms' walls superseded each other, so each switch back appended an unchanged +// 18,755-char wall again (Aiko, the M5, 2026-10-26 23:07-00:25Z: the wall, roster and recall +// of two rooms, 20-26k chars of identical copies per request). Keyed by the room, returning to +// a room whose block has not changed appends nothing, and each copy names its room. +#[test] +fn a_room_block_is_one_item_per_room() { + use continuum_context::view::{Claim, View}; + + use super::blocks::Grounding; + + let (a, b) = (uuid::Uuid::from_u128(0xa), uuid::Uuid::from_u128(0xb)); + let wall = |room, text: &str| Grounding { faculty: "room-wall".into(), room: Some(room), text: text.into(), minimum: text.into() }; + let in_a = wall(a, "RECIPE of room a"); + let in_b = wall(b, "LEDGER of room b"); + let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); + let (mut view, _) = View::start(Vec::new(), &[&in_a as &dyn Source<_>], whole).expect("test: one grant per source"); + assert_eq!(view.advance(&[&in_b as &dyn Source<_>]).items, 1, "another room's wall is its own item"); + let back = view.advance(&[&in_a as &dyn Source<_>]); + assert_eq!(back.items, 0, "returning to room a appends nothing: {back:?}"); + let texts: Vec = view.render().map(|m: &super::ContextMessage| m.text.clone()).collect(); + assert_eq!(texts.len(), 2); + assert!(texts[0].starts_with(&format!("[room-wall] (room {a})")) && texts[1].starts_with(&format!("[room-wall] (room {b})")), "{texts:?}"); +} 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..9b047d14da 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,7 +8,7 @@ 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 { faculty: faculty.to_owned(), room: None, text: text.to_owned(), minimum: text.to_owned() } } fn turn(n: usize) -> Turn { 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..1558e680bf 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 @@ -238,7 +238,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(), room: c.room, text, minimum } }) .collect(); let result_pointers = Vec::new(); 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 73a2b29542..6379fcc4f2 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 @@ -173,6 +173,8 @@ impl LlmDeliberationFaculty { all_messages.streams.blocks.extend(contracts.into_iter().map(|contract| { crate::cognition::context_streams::blocks::Grounding { faculty: contract.name.to_owned(), + // A contract in force is hers in every room. + room: None, text: contract.body.to_owned(), minimum: contract.body.to_owned(), } diff --git a/core/continuum-cognition/src/cognition/open_views.rs b/core/continuum-cognition/src/cognition/open_views.rs index 519d26ad3f..ae408c37c7 100644 --- a/core/continuum-cognition/src/cognition/open_views.rs +++ b/core/continuum-cognition/src/cognition/open_views.rs @@ -60,6 +60,41 @@ pub struct OpenView { pub note: Option, } +/// What a successful `code/read` showed: the file, the 1-based lines shown when they are +/// known, and the file's length when its producer said. +pub(crate) struct FileRead { + pub path: String, + pub shown: Option<(u32, u32)>, + pub total_lines: Option, +} + +/// The file read an act made, from the read's own header when she was shown all of it, and from +/// the gutter numbers of the head she was shown when it was stored. `None` for a failed read or +/// an act that is not one. One reading of a read's result for her open views and her action log. +pub(crate) fn file_read(act: &Observation) -> Option { + if act.output.verb != ToolVerb::Read || !act.completed_successfully() { + return None; + } + let result = &act.output.result; + let header = crate::cognition::tool_executor::spill::result_scalars(&result.content); + let field_u32 = |key: &str| -> Option { header.as_ref()?.get(key)?.as_u64().and_then(|n| u32::try_from(n).ok()) }; + let path = header + .as_ref() + .and_then(|h| h.get("file_path")?.as_str().map(str::to_owned)) + .or_else(|| act.call.input.get("file_path")?.as_str().map(str::to_owned))?; + let shown = match &result.custody { + ResultCustody::Pointer { .. } => { + let mut numbers = result.content.lines().filter_map(crate::code::file_engine::gutter_line_number); + numbers.next().map(|first| (first, numbers.last().unwrap_or(first))) // unwrap_or: a one-line head ends where it starts + } + _ => match (field_u32("start_line"), field_u32("end_line"), field_u32("lines_returned")) { + (Some(start), Some(end), Some(returned)) if returned > 0 && end >= start => Some((start, end)), + _ => None, + }, + }; + Some(FileRead { path, shown, total_lines: field_u32("total_lines") }) +} + /// How many views a mind keeps open. A count of views is the size of this state, not a /// context bound: each renders as one line (~150 chars), so eight cost ~300 tokens, under /// 1% of the 34,560-token lane this was measured on and ~6% of a 5,000-token one. A card's @@ -120,35 +155,13 @@ impl OpenViews { /// A `code/read`: the range she was shown, from the read's own header when she was shown /// all of it, and from the gutter numbers of the head she was shown when it was stored. fn note_file_read(&mut self, act: &Observation, seq: u64, scope: Option<&str>) -> bool { - if !act.completed_successfully() { - return false; - } - let result = &act.output.result; - let header = crate::cognition::tool_executor::spill::result_scalars(&result.content); - let field_u32 = |key: &str| -> Option { - header.as_ref()?.get(key)?.as_u64().and_then(|n| u32::try_from(n).ok()) - }; - let Some(path) = header - .as_ref() - .and_then(|h| h.get("file_path")?.as_str().map(str::to_owned)) - .or_else(|| act.call.input.get("file_path")?.as_str().map(str::to_owned)) - else { + let Some(FileRead { path, shown, total_lines }) = file_read(act) else { return false; }; - let shown = match &result.custody { - ResultCustody::Pointer { .. } => { - let mut numbers = - result.content.lines().filter_map(crate::code::file_engine::gutter_line_number); - numbers.next().map(|first| (first, numbers.last().unwrap_or(first))) // unwrap_or: a one-line head ends where it starts - } - _ => match (field_u32("start_line"), field_u32("end_line"), field_u32("lines_returned")) { - (Some(start), Some(end), Some(returned)) if returned > 0 && end >= start => Some((start, end)), - _ => None, - }, - }; + let result = &act.output.result; let view = self.view_mut(ViewSubject::File { path }, "code/read", seq, scope); view.touched_seq = seq; - if let Some(total) = field_u32("total_lines") { + if let Some(total) = total_lines { view.total_lines = Some(total); } if let Some(range) = shown { diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty.rs b/core/continuum-cognition/src/cognition/rag_source_faculty.rs index c4e4dbc6c8..c32395f30e 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty.rs @@ -413,7 +413,9 @@ impl Faculty for RagSourceFaculty { .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). - .with_source_truncated(delivery.truncated); + .with_source_truncated(delivery.truncated) + // Delivered for `room`: her view keys the block by it (one item per room). + .about_room(room); let c = if self.standing_grounding { c.standing_grounding() } else { diff --git a/core/continuum-cognition/src/cognition/recall_faculty.rs b/core/continuum-cognition/src/cognition/recall_faculty.rs index e979aad692..488daf4bbd 100644 --- a/core/continuum-cognition/src/cognition/recall_faculty.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty.rs @@ -714,6 +714,7 @@ impl Faculty for RecallFaculty { top_salience, reasoning, ) + .about_room(ws.room_id) .trailing(), ); } @@ -751,6 +752,8 @@ impl Faculty for RecallFaculty { Some( Contribution::context(FacultyId::Recall, content, top_salience, reasoning) + // Recalled for this room (its sticky cache is per room): one item per room. + .about_room(ws.room_id) // 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 diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 381eeef95d..725153723c 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -541,6 +541,7 @@ impl VolatileSnapshot { handle: None, written_pointer: None, summary: None, + touches: Vec::new(), }; let mut records: BTreeMap = BTreeMap::new(); let mut unkeyed = 0usize; diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index f3ce1c40d0..2e137d73a4 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -41,6 +41,22 @@ pub(crate) struct ActionRecord { /// Kept after the result collapses, so what she read stays addressable. #[serde(default, skip_serializing_if = "Option::is_none")] pub summary: Option, + /// What each of its calls did to a file, from the typed acts at the receipt: what lets a + /// later read or edit of the same file supersede this result ([`ActionLog::superseded`]). + /// Empty for a record restored from a checkpoint written before it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub touches: Vec, +} + +/// What one call of an act did to a file. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum Touch { + /// Read it; `lines` is the 1-based range shown, when its producer said. + Read { path: String, lines: Option<(u32, u32)> }, + /// Wrote or edited it. + Changed { path: String }, + /// Anything that is not a file read or change (a search, a shell, a board call). + Other, } impl ActionRecord { @@ -55,6 +71,30 @@ impl ActionRecord { } } +impl Touch { + /// What each typed act of a receipt did to a file: a read by the lines it showed + /// (`open_views::file_read`, the one reading of a read's result), a write or edit by the + /// path its call named, anything else `Other`. An apply names no single file, so it is + /// `Other`: it never supersedes a read, the conservative side. + pub fn of(acts: &[crate::cognition::act_observe::Observation]) -> Vec { + use crate::cognition::act_observe::ToolVerb; + acts.iter() + .map(|act| { + if let Some(read) = crate::cognition::open_views::file_read(act) { + return Touch::Read { path: read.path, lines: read.shown }; + } + let named = act.call.input.get("file_path").or_else(|| act.call.input.get("path")).and_then(|path| path.as_str()); + match (&act.output.verb, named) { + (ToolVerb::Write | ToolVerb::Edit, Some(path)) if act.completed_successfully() => { + Touch::Changed { path: path.to_owned() } + } + _ => Touch::Other, + } + }) + .collect() + } +} + /// What a collapse left behind. pub(super) struct Collapsed { /// Characters still retained in full. @@ -131,6 +171,42 @@ impl ActionLog { self.retained().chain(self.indexed_pointers()).map(ActionRecord::receipt_key).collect() } + /// Results a newer act made redundant: every call of it read a file (in its workspace) + /// that a later act changed, or read again showing at least the same lines. Their whole + /// result is still one expand away by their handle; a start gives them their summary + /// (`Source::superseded`). A record with any call that is not a file read never is: its + /// other output is not repeated anywhere. + pub fn superseded(&self) -> Vec { + let records: Vec<&ActionRecord> = self.records.iter().collect(); + let covered = |earlier: &ActionRecord, path: &str, lines: Option<(u32, u32)>| { + records.iter().filter(|later| later.seq > earlier.seq && later.scope == earlier.scope).any(|later| { + later.touches.iter().any(|touch| match touch { + Touch::Changed { path: changed } => changed == path, + Touch::Read { path: read, lines: shown } => { + read == path + && match (lines, shown) { + (Some((a, b)), Some((c, d))) => *c <= a && b <= *d, + // A range unknown on either side proves no coverage. + _ => false, + } + } + Touch::Other => false, + }) + }) + }; + records + .iter() + .filter(|record| record.result.is_some() && !record.touches.is_empty()) + .filter(|record| { + record.touches.iter().all(|touch| match touch { + Touch::Read { path, lines } => covered(**record, path.as_str(), *lines), + Touch::Changed { .. } | Touch::Other => false, + }) + }) + .map(|record| record.seq) + .collect() + } + /// Collapse the oldest saved results to their handles once the retained results exceed /// `cap`, down to half of it, so the head of what she reads stays byte-stable between two /// bursts. The newest result always stays, and an unsaved one stays whole. @@ -167,3 +243,52 @@ impl ActionLog { self.records.retain(|record| record.result.is_some() || keep.contains(&record.seq)); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn record(seq: u64, scope: &str, touches: Vec) -> ActionRecord { + ActionRecord { + seq, + room: None, + scope: Some(scope.to_owned()), + operation: "code/read".into(), + head: None, + result: Some(format!("result {seq}")), + handle: Some(format!("h{seq}")), + written_pointer: None, + summary: None, + touches, + } + } + + fn read(path: &str, lines: Option<(u32, u32)>) -> Touch { + Touch::Read { path: path.into(), lines } + } + + // what this catches: a whole read kept whole after she read the same lines again or edited + // the file (Aiko, the M5, 2026-10-26: command_inbound_pump.rs, 33k chars, still whole 2.5 + // hours later), and the opposite error, a result summarized when nothing newer repeats it: + // a partial re-read, an unknown range, another checkout's file, or a batch with other output. + #[test] + fn a_read_is_superseded_only_by_a_newer_read_of_the_same_lines_or_a_change() { + let changed = |path: &str| Touch::Changed { path: path.into() }; + let records = vec![ + record(1, "w", vec![read("a.rs", Some((1, 100)))]), + record(2, "w", vec![read("a.rs", Some((1, 200)))]), + record(3, "w", vec![read("b.rs", Some((1, 50)))]), + record(4, "w", vec![changed("b.rs")]), + record(5, "w", vec![read("c.rs", Some((1, 50))), Touch::Other]), + record(6, "w", vec![changed("c.rs")]), + record(7, "w", vec![read("d.rs", None)]), + record(8, "w", vec![read("d.rs", Some((1, 10)))]), + record(9, "w", vec![read("e.rs", Some((1, 300)))]), + record(10, "w", vec![read("e.rs", Some((100, 200)))]), + record(11, "other", vec![read("f.rs", Some((1, 9)))]), + record(12, "w", vec![read("f.rs", Some((1, 9)))]), + ]; + let log = ActionLog::from_records(records, usize::MAX); + assert_eq!(log.superseded(), [1, 3]); + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f378e933cf..239f0bda5a 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -335,6 +335,7 @@ impl WorkingMemory { result: Some(tail), handle, written_pointer: None, + touches: action_log::Touch::of(&acts), }, budget.receipt_archive_chars(), ); diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index dbdb8f105d..c679c36ffc 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -219,6 +219,11 @@ impl WorkingMemory { /// else what its pointer says; the pointer names the handle that reopens it, or is the /// ledger line when nothing was saved. The act still in flight is not among them (it /// rides whole as the newest message of the turn); the flag says whether there is one. + /// Her acts whose result a newer act made redundant ([`action_log::ActionLog::superseded`]). + pub(crate) fn superseded_actions(&self) -> Vec { + self.actions.lock().superseded() + } + pub(crate) fn action_renderings(&self) -> (Vec<(u64, String, Option, String)>, bool) { let active = self.in_flight_action_seq(); let actions = self.actions.lock(); diff --git a/core/continuum-cognition/src/cognition/workspace/edit.rs b/core/continuum-cognition/src/cognition/workspace/edit.rs index 49e895dcac..253026eae2 100644 --- a/core/continuum-cognition/src/cognition/workspace/edit.rs +++ b/core/continuum-cognition/src/cognition/workspace/edit.rs @@ -374,9 +374,23 @@ 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 room this block describes, when it describes one (the wall, roster, board or + /// recall of the room the turn was in). Her view keys the block by it, so a room's block + /// is ONE item: returning to a room whose block has not changed appends nothing, where + /// keyed by the faculty alone each room switch re-appended the other room's whole block + /// (Aiko, the M5, 2026-10-26 23:07-00:25Z: an 18,755-char wall, its roster and recall + /// re-added on every switch between two rooms). `None` for a block that is hers in + /// every room. Set via [`about_room`](Self::about_room). + pub room: Option, } impl Contribution { + /// Name the room this block describes ([`Contribution::room`]). + pub fn about_room(mut self, room: uuid::Uuid) -> Self { + self.room = Some(room); + self + } + /// A context contribution (no decision) — recall, world-model, affect, etc. pub fn context( faculty: FacultyId, @@ -395,6 +409,7 @@ impl Contribution { parts: vec![content.clone()], expand_command: None, source_truncated: false, + room: None, content, salience: salience.clamp(0.0, 1.0), reasoning: reasoning.into(), @@ -462,6 +477,7 @@ impl Contribution { parts: vec![content.clone()], expand_command: None, source_truncated: false, + room: None, content, salience: salience.clamp(0.0, 1.0), reasoning: reasoning.into(), @@ -511,6 +527,7 @@ impl Contribution { parts: vec![error.clone()], expand_command: None, source_truncated: false, + room: None, content: error.clone(), salience: 1.0, reasoning: "deliberation inference failed".to_string(), diff --git a/core/continuum-cognition/src/cognition/workspace_capture.rs b/core/continuum-cognition/src/cognition/workspace_capture.rs index f4678b65a5..74f00d9142 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, + room: None, }; let verdict = Contribution { faculty: FacultyId::Deliberation, @@ -285,6 +286,7 @@ mod tests { parts: Vec::new(), expand_command: None, source_truncated: false, + room: None, }; 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..9d9f769f25 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -9,7 +9,7 @@ //! changes between acts restarts the view: nothing after it is reusable); room turns (`[occurred ] :`) are her conversation, keyed by when and //! who; results, pointers, the steps ledger and the action lines of working memory are ONE //! action log keyed by `#n`; each `[faculty]` block and each list-shaped block (open views, -//! notices, recall, thoughts) is a source of `- ` items; whatever is left (facts, clock, the +//! notices, thoughts) is a source of `- ` items, recall one block as the core renders it; whatever is left (facts, clock, the //! ask, the live act) is this act's fresh tail. Everything is measured in characters: as //! sent, and as the view would have sent it. //! @@ -39,6 +39,10 @@ //! charging each later page her acts show she needed as an extra request (`replay/paged.rs`). //! Each run prints one `TABLE` line. //! +//! `--engine ` prices each request at the share of its carried prefix the engine +//! kept, read from its own receipt, and compares the core's rule today with room-keyed blocks and +//! superseded reads at their summary (`replay/engine.rs`). Each run prints one `TABLE` line per policy. +//! //! `--chars-per-token ` prices the window at the core's own estimate instead of the //! engine's bill; `--keyed-turn` keys the standing turn text into the epoch; `--trace` //! prints each act's view against what it may hold. @@ -57,11 +61,15 @@ mod outline; mod paged; #[path = "replay/sediment.rs"] mod sediment; +#[path = "replay/engine.rs"] +mod engine; use continuum_context::view::View; struct Captured { name: String, items: Vec>, + /// Keys a later item supersedes (`--engine`'s superseded rule); empty otherwise. + superseded: Vec, } /// What the allocator weighs each source by, as the core's `context_streams::priority` does: @@ -114,6 +122,9 @@ impl Source for Captured { fn items(&self) -> Vec> { self.items.clone() } + fn superseded(&self) -> Vec { + self.superseded.clone() + } } /// The captures hold what was sent, not each item's pointer; a pointer is modelled as the @@ -236,6 +247,9 @@ struct Cut { said: Vec, /// Its read calls (`--paged-reads`). reads: paged::Reads, + /// The share of what it shared with the request before it that the engine kept, from its + /// receipt (`replay/engine.rs`); `None` without one. + kept: Option, } /// A tail piece that repeats from act to act (the work-turn ask, the own-time framing, the @@ -257,12 +271,35 @@ fn turn_key(text: &str) -> Option { Some(format!("{when} {who}")) } -fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { +/// A block's name and the room its header names: `[name]` or `[name] (room )`, the line +/// alone, then its body. +fn block(text: &str) -> Option<(&str, Option<&str>)> { + let (first, _) = text.split_once('\n')?; + let (name, rest) = first.strip_prefix('[')?.split_once(']')?; + if name.contains(' ') { + return None; + } + match rest { + "" => Some((name, None)), + _ => Some((name, Some(rest.strip_prefix(" (room ")?.strip_suffix(')')?))), + } +} + +/// `room`: key each block by the room it was rendered in (the core's `Grounding` key since +/// blocks name their room); `None` keys it by its name alone, as before. +fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool, room: Option<&str>) -> Cut { let head = format!("{}\n{tools}", request["systemPrompt"].as_str().unwrap_or_default()); let mut sources: BTreeMap>> = BTreeMap::new(); let mut tail = Vec::new(); let mut sent = head.clone(); - let mut push = |source: &str, items: Vec>| sources.entry(source.to_owned()).or_default().extend(items); + // `latest`: the source offers only the newest of these items under each key. + let mut push = |source: &str, items: Vec>, latest: bool| { + let held = sources.entry(source.to_owned()).or_default(); + if latest { + held.retain(|old| items.iter().all(|new| new.key != old.key)); + } + held.extend(items); + }; for message in request["messages"].as_array().into_iter().flatten() { let text = match &message["content"] { serde_json::Value::String(text) => text.clone(), @@ -271,22 +308,22 @@ fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { sent.push('\n'); sent.push_str(&text); if let Some(key) = turn_key(&text) { - push("conversation", vec![item(key, text)]); + push("conversation", vec![item(key, text)], false); } else if let Some(seq) = seq_after(&text, "[result #") { - push("actions", vec![item(seq.to_string(), text)]); + push("actions", vec![item(seq.to_string(), text)], false); } else if text.starts_with("Recent results of your own actions") || text.starts_with("[actions] ") { - push("actions", vec![item("banner".into(), text)]); + push("actions", vec![item("banner".into(), text)], false); } else if text.starts_with("Older results, collapsed to pointers") { for line in text.lines().skip(1) { if let Some(seq) = seq_after(line, "[result #") { - push("actions", vec![item(seq.to_string(), line.to_owned())]); + push("actions", vec![item(seq.to_string(), line.to_owned())], false); } } } else if text.starts_with("[steps taken this session]") { // The ledger is the action log's pointer rendering: one item per act. for line in text.lines().skip(1) { if let Some(seq) = seq_after(line, "[action #") { - push("ledger", vec![item(seq.to_string(), line.to_owned())]); + push("ledger", vec![item(seq.to_string(), line.to_owned())], false); } } } else if text.starts_with("[working-memory]") { @@ -295,24 +332,23 @@ fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { .into_iter() .filter(|item| !item.full.starts_with("- [action #")) .collect(); - push("working-memory", thoughts); + push("working-memory", thoughts, false); } else if text.starts_with("My own recent thoughts") { - push("working-memory", vec![item("working-memory/header".into(), text)]); + push("working-memory", vec![item("working-memory/header".into(), text)], false); } else if text.starts_with("- ") { // One of her thoughts, a message of its own since the view keyed them. - push("working-memory", vec![item(text.clone(), text)]); + push("working-memory", vec![item(text.clone(), text)], false); } else if text.starts_with("[open views]") { - push("open-views", bullets("open-views", &text)); + push("open-views", bullets("open-views", &text), false); } else if text.starts_with("Notices my substrate posted") { - push("notices", bullets("notices", &text)); - } else if text.starts_with("[recall]") { - push("recall", bullets("recall", &text)); - } else if let Some(name) = text.strip_prefix('[').and_then(|rest| rest.split_once("]\n")).map(|(name, _)| name) - .filter(|name| !name.contains(' ')) - { - push(name, vec![item("block".into(), text.clone())]); + push("notices", bullets("notices", &text), false); + } else if let Some((name, named)) = block(&text) { + let key = named.or(room).map_or_else(|| "block".to_owned(), |room| format!("room/{room}")); // map_or_else: a block of no room is one item + // A capture holds every version its view appended; the source offers only its + // current one, the last. Offering all of them alternated two versions every act. + push(name, vec![item(key, text.clone())], true); } else if let Some(key) = standing(&text).filter(|_| keyed_turn) { - push("turn", vec![item(key, text)]); + push("turn", vec![item(key, text)], false); } else { tail.push(text); } @@ -323,7 +359,7 @@ fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { let missing = ledger.into_iter().filter(|line| !held.contains(&line.key)).collect::>(); sources.entry("actions".into()).or_default().extend(missing); } - Cut { head, sources, tail, sent, act: validate::act_of(request), said: outline::said(request), reads: paged::reads(request) } + Cut { head, sources, tail, sent, act: validate::act_of(request), said: outline::said(request), reads: paged::reads(request), kept: None } } fn shared(a: &str, b: &str) -> usize { @@ -354,9 +390,24 @@ struct Outcome { retained: usize, /// The view's prefill on each act that turned over. turnover_prefill: Vec, + /// Each request's prefill at the share of its carried prefix the engine kept (`--engine`). + engine_prefill: Vec, + /// Each request's whole prompt, view and tail: what an act the engine lost costs. + prompt_chars: Vec, + /// Items rendered at their summary and at their pointer by every start. + summarized: usize, + collapsed: usize, +} + +/// The start decisions a run replays beyond the core's window rule (`replay/engine.rs`). +#[derive(Clone, Copy, Default)] +struct Policy { + superseded: bool, } -fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order), keyed_turn: bool, admit: bool, trace: bool, share: usize) -> Result> { +#[allow(clippy::too_many_arguments)] // the replay's knobs, each a flag of the CLI +fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order), keyed_turn: bool, admit: bool, trace: bool, share: usize, policy: Policy) -> Result> { + let (mut engine_prefill, mut prompt_chars) = (Vec::new(), Vec::new()); let mut restored = validate::Restored::default(); let (mut rereads, mut retained) = (0usize, 0usize); let mut view: Option> = None; @@ -386,7 +437,8 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order if name == "actions" { restored.enrich(&mut items); } - Captured { name: name.clone(), items } + let superseded = if policy.superseded && name == "actions" { engine::superseded(&items) } else { Vec::new() }; + Captured { name: name.clone(), items, superseded } }) .collect(); sources.sort_by_key(|source| order(placed, &source.name)); @@ -448,7 +500,13 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order turnover_prefill.push((length - kept) as f64); } view_share.push(kept as f64 / length.max(1) as f64); + // The engine lost the share of the carried prefix this request's receipt says it lost. + let engine_kept = cut.kept.unwrap_or(1.0); // unwrap_or: no receipt, the engine kept it all, as the other modes price it + engine_prefill.push((length - kept) as f64 + (1.0 - engine_kept) * kept as f64); + } else { + engine_prefill.push(rendered.chars().count() as f64); } + prompt_chars.push(rendered.chars().count() as f64); previous_sent = Some(&cut.sent); previous_view = rendered; } @@ -470,7 +528,17 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order let line: Vec = appended.iter().map(|(name, chars)| format!("{name} {}", chars / acts)).collect(); println!(" appended per act by source: {}", line.join(", ")); println!(" her re-reads of a file read before: {rereads}, of which the prompt still held the earlier read whole or as its outline (a retention proxy): {retained}; acts whose result was ambiguous (not restored): {}", restored.ambiguous); - Ok(Outcome { turnovers, prefill_chars: view_prefill, rereads, retained, turnover_prefill }) + Ok(Outcome { + turnovers, + prefill_chars: view_prefill, + rereads, + retained, + turnover_prefill, + engine_prefill, + prompt_chars, + summarized: summarized_at_starts, + collapsed: collapsed_at_starts, + }) } /// Characters a request sends: the system prompt, every message, and `tools`. @@ -496,6 +564,10 @@ fn main() -> Result<(), Box> { // measured prefill rate (the node's `state/serving-rates.json`, or a live read). let mut validate_tps: Option = None; let mut append_tps: Option = None; + // `--engine `: price each policy at the engine's measured keep (`replay/engine.rs`). + let mut engine_tps: Option = None; + // `--since `: replay only the requests captured from then on. + let mut since_ms = 0u64; let mut reply_override: Option = None; let mut fixed_tools: Option = None; let (mut outline_results, mut generational, mut paged_reads) = (false, false, false); @@ -517,6 +589,14 @@ fn main() -> Result<(), Box> { } validate_tps = Some(tps); } + "--since" => since_ms = args.next().ok_or("--since needs an epoch millisecond")?.parse()?, + "--engine" => { + let tps: f64 = args.next().ok_or("--engine needs the prefill rate in tokens/s")?.parse()?; + if !(tps.is_finite() && tps > 0.0) { + return Err("--engine needs a finite, positive measured prefill rate".into()); + } + engine_tps = Some(tps); + } "--append-tail" => { let tps: f64 = args.next().ok_or("--append-tail needs the prefill rate in tokens/s")?.parse()?; if !(tps.is_finite() && tps > 0.0) { @@ -537,6 +617,7 @@ fn main() -> Result<(), Box> { } let mut rows = Vec::new(); let mut billed: BTreeMap = BTreeMap::new(); + let mut receipts = engine::Receipts::new(); for path in &paths { for line in std::fs::read_to_string(path)?.lines() { let Ok(event) = serde_json::from_str::(line) else { continue }; @@ -545,6 +626,9 @@ fn main() -> Result<(), Box> { Some("completed") => { if let (Some(id), Some(tokens)) = (event["request_id"].as_str(), event["response"]["usage"]["inputTokens"].as_u64()) { billed.insert(id.to_owned(), tokens); + if let Some(cached) = event["response"]["timing"]["cachedTokens"].as_u64() { + receipts.insert(id.to_owned(), (tokens, cached)); + } } } _ => {} @@ -568,6 +652,7 @@ fn main() -> Result<(), Box> { rows.retain(|row| { row["room_id"].as_str().is_some_and(|id| id.starts_with(&room)) && row["request"]["purpose"].as_str().is_some_and(|p| p.ends_with(&purpose)) + && row["captured_at_ms"].as_u64().is_some_and(|at| at >= since_ms) }); rows.sort_by_key(|row| row["captured_at_ms"].as_u64()); let context_window = rows.iter().filter_map(|row| row["context_window"].as_u64()).max().unwrap_or(0); // unwrap_or: no rows in the room, nothing replays @@ -601,14 +686,30 @@ fn main() -> Result<(), Box> { .iter() .zip(&sent_tools) .map(|(row, tools)| { - let mut cut = cut(&row["request"], tools, keyed_turn); + let mut cut = cut(&row["request"], tools, keyed_turn, None); cut.act = std::mem::take(&mut cut.act).at(row); cut }) .collect(); + if let Some(tps) = engine_tps { + let resident = paths.iter().map(|path| path.rsplit('/').next().unwrap_or(path).chars().take(8).collect::()).collect::>().join("+"); // unwrap_or: rsplit always yields one piece + let mut by_name = cuts; + let mut by_room: Vec = rows + .iter() + .zip(&sent_tools) + .map(|(row, tools)| { + let mut cut = cut(&row["request"], tools, keyed_turn, row["room_id"].as_str()); + cut.act = std::mem::take(&mut cut.act).at(row); + cut + }) + .collect(); + engine::stamp(&mut by_name, &rows, &receipts, chars_per_token); + engine::stamp(&mut by_room, &rows, &receipts, chars_per_token); + return engine::compare(&label, &resident, (&by_name, &by_room), &rows, &receipts, window, share, (chars_per_token, tps)); + } if let Some(tps) = append_tps { // The core's rule as it renders today, then the same rule with the act loop appended. - let today = replay(&label, &cuts, window, (Rule::Reserved, Order::SettledFirst), keyed_turn, true, trace, share)?; + let today = replay(&label, &cuts, window, (Rule::Reserved, Order::SettledFirst), keyed_turn, true, trace, share, Policy::default())?; let resident = paths.iter().map(|path| path.rsplit('/').next().unwrap_or(path).chars().take(8).collect::()).collect::>().join("+"); // unwrap_or: rsplit always yields one piece let rate = (chars_per_token, tps); let whole = append::Options { outline: outline::Mode::Whole, generational: false, paged: false }; @@ -647,7 +748,7 @@ fn main() -> Result<(), Box> { // one comparable line each. Prefill seconds at the measured rate `tps`. let seconds_per_char = 1.0 / (chars_per_token * tps); for share in [2usize, 3, 4, 6] { - let o = replay(&label, &cuts, window, (Rule::Reserved, Order::SettledFirst), keyed_turn, true, trace, share)?; + let o = replay(&label, &cuts, window, (Rule::Reserved, Order::SettledFirst), keyed_turn, true, trace, share, Policy::default())?; println!( "VALIDATE {label} share 1/{share}: {} acts, {} turnovers, prefill {:.1} s/act mean ({:.0} chars), re-reads {} held {}", cuts.len(), @@ -663,7 +764,7 @@ fn main() -> Result<(), Box> { for rule in [Rule::Whole, Rule::Reserved] { for placed in [Order::ConversationFirst, Order::SettledFirst] { for admit in [false, true] { - replay(&label, &cuts, window, (rule, placed), keyed_turn, admit, trace, share)?; + replay(&label, &cuts, window, (rule, placed), keyed_turn, admit, trace, share, Policy::default())?; } } } diff --git a/core/continuum-context/examples/replay/append.rs b/core/continuum-context/examples/replay/append.rs index 96402db41d..0e7ffa3cb7 100644 --- a/core/continuum-context/examples/replay/append.rs +++ b/core/continuum-context/examples/replay/append.rs @@ -151,7 +151,7 @@ pub fn replay(label: &str, cuts: &[Cut], window: usize, share: usize, (chars_per if name == "actions" { restored.enrich(&mut items); } - Captured { name: name.clone(), items } + Captured { name: name.clone(), items, superseded: Vec::new() } }) .collect(); sources.sort_by_key(|source| order(Order::SettledFirst, &source.name)); @@ -183,7 +183,7 @@ pub fn replay(label: &str, cuts: &[Cut], window: usize, share: usize, (chars_per if !turnover { // Mid-epoch: her loop arrives as the bytes she was sent, first, then what changed in // every other source. The action log is not re-rendered. - let act_loop = Captured { name: LOOP.to_owned(), items: looped.clone() }; + let act_loop = Captured { name: LOOP.to_owned(), items: looped.clone(), superseded: Vec::new() }; let mut refs: Vec<&dyn Source> = vec![&act_loop]; refs.extend(sources.iter().filter(|s| s.name != "actions").map(|s| s as &dyn Source)); open.advance(&refs); diff --git a/core/continuum-context/examples/replay/engine.rs b/core/continuum-context/examples/replay/engine.rs new file mode 100644 index 0000000000..9d24df8175 --- /dev/null +++ b/core/continuum-context/examples/replay/engine.rs @@ -0,0 +1,186 @@ +//! What the engine keeps, and what her own later acts supersede, read back from the captures +//! (`--engine `). +//! +//! The other modes price a request at the characters it does not share with the request before +//! it: an engine that never loses her slot. On the M5, 2026-10-26, about half of the residents' +//! acts reused only the shared system head, and those acts prefilled their whole prompt. Each +//! captured request's own receipt says how much of what it shared with the request before it the +//! engine kept (`cachedTokens`); a policy's request is priced at its own fresh end plus the share +//! of its carried prefix that receipt says the engine lost. The loss pattern is taken as given +//! (other minds' prefill evicts her slot): a policy whose prompts are smaller is credited only +//! with what it re-prefills less, never with evicting less, so the comparison is conservative. +//! +//! It also replays the start decision in `continuum_context::view` that an act read again or a +//! file changed since takes its summary at a start (`Source::superseded`, as the core's +//! `ActionLog::superseded` decides from the typed acts; here from the rendered call). + +use std::collections::BTreeMap; + +use continuum_context::source::Item; + +use super::{mean, median, replay, Cut, Order, Policy, Rule}; + +/// The share of what a captured request shared with the request before it (as sent) that the +/// engine reused: its `cachedTokens` over that shared prefix in tokens, the head included. A +/// request the run itself started anew shares about the head only, and is read as kept. +pub fn kept(previous_sent: &str, sent: &str, cached_tokens: u64, chars_per_token: f64) -> f64 { + let shared = super::shared(previous_sent, sent) as f64 / chars_per_token; + if shared <= 0.0 { + return 1.0; + } + (cached_tokens as f64 / shared).min(1.0) +} + +/// What one rendered act did to a file: the core's `Touch`, read from the call it renders. +#[derive(Debug, PartialEq)] +enum Touch { + Read { path: String, lines: (u32, u32) }, + Changed { path: String }, +} + +/// `key=value` arguments of the rendered call `name(...)` in `text`. +fn args<'a>(text: &'a str, name: &str) -> Option> { + let start = text.find(&format!("{name}("))? + name.len() + 1; + let end = start + text[start..].find(')')?; + Some(text[start..end].split(", ").filter_map(|pair| pair.split_once('=')).collect()) +} + +/// The workspace label of a rendered result (`workspace 20b44763]`), its scope. +fn workspace(text: &str) -> Option<&str> { + let header = text.split_once(']')?.0; + let at = header.find("workspace ")? + "workspace ".len(); + Some(header[at..].split([' ', ';']).next().unwrap_or_default()) // unwrap_or_default: split yields at least one piece +} + +/// The touch of an act whose operation is one file read or change; `None` for anything else +/// (a batch, a search, a shell), which never supersedes and is never superseded. +fn touch(text: &str) -> Option { + let operation = text.split("operation ").nth(1)?.split(';').next()?; + let path_of = |args: &[(&str, &str)]| args.iter().find(|(k, _)| *k == "file_path").map(|(_, v)| (*v).to_owned()); + match operation { + "code/read" => { + let args = args(text, "code/read")?; + let line = |key: &str, unset: u32| args.iter().find(|(k, _)| *k == key).and_then(|(_, v)| v.parse().ok()).unwrap_or(unset); // unwrap_or: an unranged read is the whole file, as the read's header reports it + Some(Touch::Read { path: path_of(&args)?, lines: (line("start_line", 1), line("end_line", u32::MAX)) }) + } + "code/edit" | "code/write" => Some(Touch::Changed { path: path_of(&args(text, operation)?)? }), + _ => None, + } +} + +/// Keys of the action items a later item supersedes: a read of the same file in the same +/// workspace showing at least the same lines, or a change of it. +pub fn superseded(items: &[Item]) -> Vec { + let acts: Vec<(&str, Option<&str>, Touch)> = + items.iter().filter_map(|item| Some((item.key.as_str(), workspace(&item.full), touch(&item.full)?))).collect(); + acts.iter() + .enumerate() + .filter(|(at, (_, scope, touch))| match touch { + Touch::Read { path, lines } => acts[at + 1..].iter().any(|(_, later_scope, later)| { + later_scope == scope + && match later { + Touch::Changed { path: changed } => changed == path, + Touch::Read { path: read, lines: shown } => read == path && shown.0 <= lines.0 && lines.1 <= shown.1, + } + }), + Touch::Changed { .. } => false, + }) + .map(|(_, (key, _, _))| (*key).to_owned()) + .collect() +} + +/// Each request's receipt: the tokens the engine counted and the tokens it reused. +pub type Receipts = BTreeMap; + +/// Stamp each cut with the share of its carried prefix its receipt says the engine kept. +pub fn stamp(cuts: &mut [Cut], rows: &[serde_json::Value], receipts: &Receipts, chars_per_token: f64) { + for n in 1..cuts.len() { + let cached = rows[n]["request_id"].as_str().and_then(|id| receipts.get(id)).map(|(_, cached)| *cached); + cuts[n].kept = cached.map(|cached| kept(&cuts[n - 1].sent, &cuts[n].sent, cached, chars_per_token)); + } +} + +/// One `TABLE` line per policy: the run as it was sent (its receipts), then the core's rule +/// today, then each change added, priced at the engine's measured keep and `tps`. +#[allow(clippy::too_many_arguments)] // the replay's knobs, each a flag of the CLI +pub fn compare( + label: &str, + resident: &str, + (by_name, by_room): (&[Cut], &[Cut]), + rows: &[serde_json::Value], + receipts: &Receipts, + window: usize, + share: usize, + (chars_per_token, tps): (f64, f64), +) -> Result<(), Box> { + let billed: Vec<(u64, u64)> = rows.iter().filter_map(|row| receipts.get(row["request_id"].as_str()?).copied()).collect(); + let fresh: f64 = billed.iter().map(|(prompt, cached)| prompt.saturating_sub(*cached) as f64).sum(); + let prompts: Vec = billed.iter().map(|(prompt, _)| *prompt as f64).collect(); + println!( + "TABLE {resident} | as sent (receipts) | prefill {fresh:.0} tok | {:.0} s/request | prompt mean {:.0} tok, median {:.0} | {} requests with receipts", + fresh / tps / billed.len().max(1) as f64, + mean(&prompts), + median(prompts.clone()), + billed.len(), + ); + let variants: [(&str, &[Cut], Policy); 3] = [ + ("core rule today", by_name, Policy::default()), + ("+ room keys", by_room, Policy::default()), + ("+ room keys + superseded", by_room, Policy { superseded: true }), + ]; + for (variant, cuts, policy) in variants { + let o = replay(label, cuts, window, (Rule::Reserved, Order::SettledFirst), false, true, false, share, policy)?; + let tokens = |chars: &[f64]| chars.iter().sum::() / chars_per_token; + let prompt: Vec = o.prompt_chars.iter().map(|chars| chars / chars_per_token).collect(); + println!( + "TABLE {resident} | {variant} | prefill {:.0} tok | {:.0} s/request | prompt mean {:.0} tok, median {:.0} | {} turnovers | {} summarized, {} collapsed at starts | re-reads {} held {} | prefill if the engine kept every slot {:.0} tok", + tokens(&o.engine_prefill), + tokens(&o.engine_prefill) / tps / o.engine_prefill.len().max(1) as f64, + mean(&prompt), + median(prompt.clone()), + o.turnovers, + o.summarized, + o.collapsed, + o.rereads, + o.retained, + tokens(&o.prefill_chars), + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn act(n: u32, call: &str) -> Item { + let operation = call.split('(').next().unwrap_or_default(); // unwrap_or_default: split yields at least one piece + let full = format!("[result #{n}; room r; operation {operation}; output handle: tool/output h{n}; workspace w] {call} because x"); + Item { key: n.to_string(), pointer: None, summary: None, full } + } + + // what this catches: the replay's superseded rule disagreeing with the core's (a partial + // re-read counted as covering, an edit missed, or an edit's own result summarized). + #[test] + fn a_read_is_superseded_by_a_covering_read_or_a_change() { + let items = vec![ + act(1, "code/read(file_path=a.rs)"), + act(2, "code/read(file_path=b.rs)"), + act(3, "code/read(end_line=200, file_path=a.rs, start_line=75)"), + act(4, "code/edit(file_path=b.rs, old=x)"), + act(5, "code/read(file_path=a.rs)"), + ]; + assert_eq!(superseded(&items), ["1", "2", "3"]); + } + + // what this catches: a cold act (only the head reused) read as warm, or a run's own start + // read as the engine losing her slot. + #[test] + fn kept_is_the_share_of_the_shared_prefix_the_engine_reused() { + let before = "h".repeat(100) + &"v".repeat(900); + let after = before.clone() + "new"; + assert!((kept(&before, &after, 100, 1.0) - 0.1).abs() < 1e-9); + assert_eq!(kept(&before, &after, 1_000, 1.0), 1.0); + assert_eq!(kept("x", "y", 0, 1.0), 1.0, "nothing shared, nothing to keep"); + } +} diff --git a/core/continuum-context/examples/replay/sediment.rs b/core/continuum-context/examples/replay/sediment.rs index 0efd072696..55cee19749 100644 --- a/core/continuum-context/examples/replay/sediment.rs +++ b/core/continuum-context/examples/replay/sediment.rs @@ -173,7 +173,7 @@ mod tests { .enumerate() .map(|(n, size)| Item { key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")) }) .collect(); - Captured { name: name.to_owned(), items } + Captured { name: name.to_owned(), items, superseded: Vec::new() } } // what this catches: a turnover that settles a NEWER item before an older one (an item more diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index 78d704f353..e002913706 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -45,6 +45,15 @@ pub trait Source { /// next turnover. fn items(&self) -> Vec>; + /// Keys of items a newer item supersedes: what they say she has since read again or + /// changed (a file read whose lines a later read showed again, a file she edited since). + /// A start gives such an item at most its summary, whatever its age and whatever the grant + /// leaves (`view::levels`); its full stays one expand away. Within an epoch nothing changes: + /// the newer item arrives as an append, and the start after it re-levels the older one. + fn superseded(&self) -> Vec { + Vec::new() + } + /// Items that must leave the view now (a closed view, a revoked result), each as the /// short notice that supersedes it (its `full`). Their tokens leave at the next /// turnover; a privacy revocation that cannot wait is the caller's reason to turn over diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index 44b97961f1..bdc093d41b 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -110,7 +110,13 @@ enum Level { /// filling them past it doubled the size of every start (median 14,238 -> 27,696 chars) and /// the median act went 83-111 s -> 140 s under the same eleven residents (canary 28bf81fa7 vs /// 3cd34f87c, the M5, 2026-10-25 17:00-18:06Z). -fn levels(items: &[Item], grant: usize) -> Vec { +/// +/// An item a newer one `superseded` (she read the same lines again, or changed the file since) +/// takes at most its summary, and its pointer when that does not fit. Its level says what a +/// newer item made redundant, not what its age allows, so it never lowers the ceiling of the +/// items older than it (Aiko, the M5, 2026-10-26: whole reads of a file she had read again or +/// edited since stayed whole until the next turnover, 15.7k tokens of results 10+ acts old). +fn levels(items: &[Item], grant: usize, superseded: &HashSet) -> Vec { let floor: usize = items.iter().map(pointer_chars).sum(); let mut spare = grant.saturating_sub(floor); let mut levels = vec![Level::Pointer; items.len()]; @@ -118,6 +124,13 @@ fn levels(items: &[Item], grant: usize) -> Vec { for (item, level) in items.iter().zip(levels.iter_mut()).rev() { let full = item.full.chars().saturating_sub(pointer_chars(item)); let summary = item.summary.as_ref().map(|s| s.chars().saturating_sub(pointer_chars(item))); + if superseded.contains(&item.key) { + if let Some(summary) = summary.filter(|summary| ceiling != Level::Pointer && *summary <= spare) { + spare -= summary; + *level = Level::Summary; + } + continue; + } if ceiling == Level::Full && full <= spare { spare -= full; *level = Level::Full; @@ -219,7 +232,8 @@ impl View { act: None, }; for ((source, items), grant) in sources.iter().zip(offered).zip(grants) { - let levels = levels(&items, grant); + let superseded: HashSet = source.superseded().into_iter().collect(); + let levels = levels(&items, grant, &superseded); let mut rendered = Vec::with_capacity(items.len()); for (item, level) in items.into_iter().zip(levels) { let id = key(source.name(), &item.key); diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 83ab568f44..a05ec16fd7 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -325,3 +325,43 @@ fn a_short_item_without_a_summary_stays_whole_under_a_summary_ceiling() -> Resul assert_eq!((start.collapsed, start.summarized), (0, 2)); Ok(()) } + +/// [`Leveled`] items, some of which a newer item supersedes. +struct Superseding(Leveled, Vec<&'static str>); + +impl Source for Superseding { + fn name(&self) -> &str { + self.0.name() + } + fn priority(&self) -> u8 { + self.0.priority() + } + fn items(&self) -> Vec> { + self.0.items() + } + fn superseded(&self) -> Vec { + self.1.iter().map(|key| (*key).to_owned()).collect() + } +} + +// what this catches: a whole read of a file she read again or edited since staying whole at +// every start the window could afford (Aiko, the M5, 2026-10-26: 15.7k tokens of whole results +// 10+ acts old per request, a 33k-char file still whole 2.5 hours after she read it). It takes +// its outline however generous the grant; an older item is not dragged down with it. +#[test] +fn a_superseded_item_takes_its_summary_and_leaves_the_older_ones_whole() -> Result<(), GrantMismatch> { + let reads = Superseding( + Leveled(vec![ + ("oldest", "an older result".to_owned(), None), + ("read-1", "x".repeat(2_000), Some("outline, read 1".to_owned())), + ("note", "a note".to_owned(), None), + ("read-2", "y".repeat(2_000), Some("outline, read 2".to_owned())), + ]), + vec!["read-1"], + ); + let (view, start) = View::start(Vec::new(), &[&reads as &dyn Source], |c| c.iter().map(|c| c.full_chars).collect())?; + let rendered: Vec = view.render().cloned().collect(); + assert_eq!(rendered, ["an older result".to_owned(), "outline, read 1".to_owned(), "a note".to_owned(), "y".repeat(2_000)]); + assert_eq!((start.collapsed, start.summarized), (0, 1)); + Ok(()) +} diff --git a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md index 01a73794a5..6641cd4c9d 100644 --- a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md +++ b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md @@ -266,6 +266,12 @@ no faculty re-implements them: 6. Every decision (start, lease size, order, prefetch) is an explicit action with an exact cost (prefill tokens, seconds). Replaying captures is the simulator in which a learned policy must beat the hand rule before it runs live (plan line 14). +7. An item's key names its whole subject, so the same subject is one item: a room's wall, roster, + board and recall are keyed by the room they describe, and returning to a room appends nothing + (`Contribution::room`; the M5, 2026-10-26: each switch between two rooms re-appended an + unchanged 18,755-char wall, its roster and recall). +8. A start gives an item a newer one superseded (she read the same lines again, or changed the + file since: `Source::superseded`) at most its summary, without lowering older items. **Gates (source-hygiene ratchets; counts on canary a59c2bf15 + #5422, 2026-10-25):** @@ -297,9 +303,11 @@ surface, observed back through her eyes and ears. **How to add a layer (the whole recipe; everything else is free):** 1. Implement `continuum_context::source::Source` for it. `name` and `priority` are required; set `required` only for input she must read. -2. `items()` returns one `Item` per subject, under a key that names that whole subject. Build its +2. `items()` returns one `Item` per subject, under a key that names that whole subject (a block + about a room is keyed by the room). Build its `summary` with `continuum_context::levels::summarize(full, Shape::…)` (`Code` with the producer's - line parser, `Output`, `List`). Its `pointer` names the handle that expands it. + line parser, `Output`, `List`). Its `pointer` names the handle that expands it. If a newer item + can make an older one redundant, name the older keys in `superseded()`. 3. Add the source to the view's source list. Never push a prompt message, never collapse, never pick an order: the view appends, levels, admits, orders by measured motion and turns over. 4. Prove it with a fixture in the source's test mod, then with the replay validator.