Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ impl Source<ContextMessage> 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<String> {
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<Item<ContextMessage>> {
Expand Down
31 changes: 25 additions & 6 deletions core/continuum-cognition/src/cognition/context_streams/blocks.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
//! 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};

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<uuid::Uuid>,
/// 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`).
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<ContextMessage> for Grounding {
fn name(&self) -> &str {
&self.faculty
Expand All @@ -28,8 +42,13 @@ impl Source<ContextMessage> for Grounding {
fn items(&self) -> Vec<Item<ContextMessage>> {
// 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) }]
}
}
25 changes: 25 additions & 0 deletions core/continuum-cognition/src/cognition/context_streams/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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:?}");
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
Expand Down
63 changes: 38 additions & 25 deletions core/continuum-cognition/src/cognition/open_views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,41 @@ pub struct OpenView {
pub note: Option<String>,
}

/// 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<u32>,
}

/// 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<FileRead> {
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<u32> { 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
Expand Down Expand Up @@ -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<u32> {
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 {
Expand Down
4 changes: 3 additions & 1 deletion core/continuum-cognition/src/cognition/rag_source_faculty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions core/continuum-cognition/src/cognition/recall_faculty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ impl Faculty for RecallFaculty {
top_salience,
reasoning,
)
.about_room(ws.room_id)
.trailing(),
);
}
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions core/continuum-cognition/src/cognition/working_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,7 @@ impl VolatileSnapshot {
handle: None,
written_pointer: None,
summary: None,
touches: Vec::new(),
};
let mut records: BTreeMap<u64, action_log::ActionRecord> = BTreeMap::new();
let mut unkeyed = 0usize;
Expand Down
125 changes: 125 additions & 0 deletions core/continuum-cognition/src/cognition/working_memory/action_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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<Touch>,
}

/// 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 {
Expand All @@ -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<Touch> {
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.
Expand Down Expand Up @@ -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<u64> {
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.
Expand Down Expand Up @@ -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<Touch>) -> 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]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ impl WorkingMemory {
result: Some(tail),
handle,
written_pointer: None,
touches: action_log::Touch::of(&acts),
},
budget.receipt_archive_chars(),
);
Expand Down
Loading
Loading