diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 95c7deaffd..980b235b73 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -7,9 +7,10 @@ //! shelter: Anwen parked fabricated receipts in one within minutes), or acts happened whose //! details aged out (denying her own work is the inverse failure, 2026-07-13: Asha). -use continuum_context::source::{Item, Source}; +use continuum_context::cause::{Cause, Content, Origin}; +use continuum_context::source::{Item, Source, StoredWhole}; -use super::{priority, ContextMessage}; +use super::{element, priority, ContextMessage, Producer}; use crate::cognition::working_memory::WorkingMemory; pub(crate) struct Actions<'a> { @@ -19,9 +20,12 @@ 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), stored: None } + fn standing(&self, key: &str, text: String) -> Item { + super::standing(self.persona, "actions", key, ContextMessage::user(text)) + } + + fn act(&self, seq: u64) -> continuum_context::cause::ElementId { + element(self.persona, Producer::Act, &seq.to_be_bytes()) } } @@ -35,7 +39,7 @@ impl Source for Actions<'_> { } fn items(&self) -> Vec> { - let banner = Self::standing( + let banner = self.standing( "banner", "[actions] What I have done this session, oldest first: each #n is one act; a \ collapsed one names the handle that reopens it." @@ -63,16 +67,22 @@ impl Source for Actions<'_> { if taken == 1 { "" } else { "s" } ) }; - return vec![banner, Self::standing("none", none)]; + return vec![banner, self.standing("none", none)]; } let mut items = vec![banner]; - items.extend(acts.into_iter().map(|(seq, full, summary, pointer, stored)| Item { - stored: stored.map(|(chars, handle)| continuum_context::source::StoredWhole { chars, handle }), - key: seq.to_string(), - full: ContextMessage::user(full), - summary: summary.map(ContextMessage::user), - pointer: Some(ContextMessage::user(pointer)), - })); + // Her acts in one room are one chain: each follows the act before it there; the first is + // where that activity's chain starts. + let mut last_in_room: std::collections::HashMap, u64> = std::collections::HashMap::new(); + for act in acts { + let cause = last_in_room.insert(act.room, act.seq).map_or(Cause::Root(Origin::ActivityStart), |prev| Cause::Of(self.act(prev))); + let stored = act.stored.map(|(chars, handle)| StoredWhole { chars, handle, content: Content::Absent }); + items.push( + Item::rendered(self.act(act.seq), cause, act.seq.to_string(), ContextMessage::user(act.full), act.content) + .with_summary(act.summary.map(ContextMessage::user)) + .with_pointer(ContextMessage::user(act.pointer)) + .with_stored(stored), + ); + } items } @@ -80,8 +90,8 @@ impl Source for Actions<'_> { /// rule 7), read back from its spill file when her view grants it whole, labelled as it /// read resident. `None` (the resident pointer renders) when the file is gone or unreadable. fn load(&self, item: &Item) -> Option { - let stored = item.stored.as_ref()?; - let seq: u64 = item.key.parse().ok()?; + let stored = item.stored()?; + let seq: u64 = item.key().parse().ok()?; let label = self.memory.action_whole_label(seq)?; let body = crate::cognition::tool_executor::spill::saved_whole(self.persona, &stored.handle).ok()?; Some(ContextMessage::user(format!("{label}{body}"))) @@ -95,8 +105,8 @@ impl Source for Actions<'_> { fn fold(&self, folded: &[Item]) -> Option { // The banner stands as itself ahead of the run (the view never folds a standing head), // so the run is her acts alone, keyed by their #n. - let first: u64 = folded.first()?.key.parse().ok()?; - let last: u64 = folded.last()?.key.parse().ok()?; + let first: u64 = folded.first()?.key().parse().ok()?; + let last: u64 = folded.last()?.key().parse().ok()?; let count = folded.len(); Some(ContextMessage::user(format!( "[actions #{first}-#{last}: {count} earlier acts folded; reopen one with tool/output act=]" @@ -110,6 +120,6 @@ impl Source for Actions<'_> { if acts.is_empty() && !in_flight { return Vec::new(); } - vec![Self::standing("none", "(that was before my first act; my acts follow)".to_owned())] + vec![self.standing("none", "(that was before my first act; my acts follow)".to_owned())] } } diff --git a/core/continuum-cognition/src/cognition/context_streams/blocks.rs b/core/continuum-cognition/src/cognition/context_streams/blocks.rs index 2d04d54ece..453efc6d6e 100644 --- a/core/continuum-cognition/src/cognition/context_streams/blocks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/blocks.rs @@ -14,6 +14,8 @@ use crate::cognition::rag_budget::RagItem; use super::{priority, ContextMessage}; pub(crate) struct Grounding { + /// Whose block this is (its id, `super::standing`). + pub persona: uuid::Uuid, pub faculty: String, /// The whole block. pub text: String, @@ -26,9 +28,15 @@ pub(crate) struct Grounding { 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 { + pub fn atomic(persona: uuid::Uuid, 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()) } + Self { persona, faculty: faculty.into(), minimum: text.clone(), text, units: std::sync::Arc::from(Vec::new()) } + } + + /// The block as a standing item: the root of its activity; a board update is new content, not a + /// new identity. + fn block(&self, full: ContextMessage, summary: Option, pointer: ContextMessage) -> Item { + super::standing(self.persona, &self.faculty, "block", full).with_summary(summary).with_pointer(pointer) } fn render(&self, body: String) -> ContextMessage { @@ -56,7 +64,7 @@ impl Source for Grounding { // reopen it by, so collapsed it is still its truthful minimum, never a one-liner. let full = self.render(self.text.clone()); let pointer = self.render(self.minimum.clone()); - return vec![Item { key: "block".to_owned(), full, summary: None, pointer: Some(pointer), stored: None }]; + return vec![self.block(full, None, pointer)]; } let whole = self.at(|unit| &unit.content); let summary = self.units.iter().any(|unit| unit.summary.is_some()).then(|| { @@ -65,13 +73,8 @@ impl Source for Grounding { 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 { - 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, - stored: None, - }] + let pointer = 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 + vec![self.block(self.render(whole), summary.map(|summary| self.render(summary)), pointer)] } } @@ -81,7 +84,7 @@ mod tests { 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() } + Grounding { persona: uuid::Uuid::nil(), 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 @@ -96,8 +99,8 @@ mod tests { }; 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]")); + 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().map(text).as_deref(), Some("[room-board]\ncard a: short\ncard b: short")); + assert_eq!(item.pointer().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 e6183e7f8c..52b8a14528 100644 --- a/core/continuum-cognition/src/cognition/context_streams/conversation.rs +++ b/core/continuum-cognition/src/cognition/context_streams/conversation.rs @@ -3,9 +3,10 @@ //! in her view until the next epoch start. Collapsed at a start, an older turn leaves the view; //! the room's history keeps it (`chat/history` rereads it). +use continuum_context::cause::{Cause, Origin}; use continuum_context::source::{Item, Source}; -use super::{priority, ContextMessage, Role}; +use super::{element, priority, ContextMessage, Producer, Role}; pub(crate) struct Turn { pub key: String, @@ -18,6 +19,8 @@ pub(crate) struct Turn { #[derive(Default)] pub(crate) struct Conversation { + /// Whose conversation this is (its turns' ids, `super::element`). + pub persona: uuid::Uuid, pub turns: Vec, } @@ -31,18 +34,21 @@ impl Source for Conversation { } fn items(&self) -> Vec> { + // A room's conversation is one chain in its order: each turn follows the one before it + // (who answered whom is not recorded yet); the first came from outside her. + let mut previous = None; self.turns .iter() - .map(|turn| Item { - key: turn.key.clone(), - full: ContextMessage { role: turn.role, text: turn.line.clone() }, + .map(|turn| { + let id = element(self.persona, Producer::Turn, turn.key.as_bytes()); + let cause = previous.replace(id).map_or(Cause::Root(Origin::External), Cause::Of); + let full = ContextMessage { role: turn.role, text: turn.line.clone() }; + let pointer = turn.pointer.clone().map(|text| ContextMessage { role: turn.role, text }); // 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. The room-update index keeps // itself, so an update too large to show is never unknown. - summary: None, - pointer: turn.pointer.clone().map(|text| ContextMessage { role: turn.role, text }), - stored: None, + Item::whole(id, cause, turn.key.clone(), full).with_pointer(pointer) }) .collect() } diff --git a/core/continuum-cognition/src/cognition/context_streams/mod.rs b/core/continuum-cognition/src/cognition/context_streams/mod.rs index 0b5f597a9d..850cf4fa4f 100644 --- a/core/continuum-cognition/src/cognition/context_streams/mod.rs +++ b/core/continuum-cognition/src/cognition/context_streams/mod.rs @@ -22,6 +22,32 @@ use crate::cognition::working_memory::WorkingMemory; /// The streams her working memory feeds her view: her actions, her thoughts, her open views /// and the notices her substrate posted. Built once per use from her memory, never assembled /// by hand. +/// Which producer named an occurrence: part of its id, so an act and a turn never share one. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Producer { + Act, + Turn, + OpenView, + Thought, + Notice, + Standing, +} + +/// An occurrence's id from its producer's own stable identity: whose (`persona`), which producer, +/// and the producer's id for it (an act's `seq`, a turn's event, a view's key). Deterministic, so it +/// survives epochs and restarts exactly as long as the producer's identity does. +pub(crate) fn element(persona: uuid::Uuid, producer: Producer, local: &[u8]) -> continuum_context::cause::ElementId { + continuum_context::cause::ElementId::of(&[persona.as_bytes(), &[producer as u8], local]) +} + +/// A standing item of `source` (a banner, a block that leads her view): the root of its activity, +/// resident whole. Its id is namespaced by the source, so two sources' banners never share one. +pub(crate) fn standing(persona: uuid::Uuid, source: &str, key: &str, message: ContextMessage) -> continuum_context::source::Item { + use continuum_context::cause::{Cause, Origin}; + let id = element(persona, Producer::Standing, format!("{source}/{key}").as_bytes()); + continuum_context::source::Item::whole(id, Cause::Root(Origin::ActivityStart), key, message.clone()).with_pointer(message) +} + pub(crate) struct MemoryStreams<'a> { pub actions: actions::Actions<'a>, pub thoughts: thoughts::Thoughts<'a>, @@ -33,9 +59,9 @@ impl<'a> MemoryStreams<'a> { pub fn of(memory: &'a WorkingMemory, persona: uuid::Uuid) -> Self { Self { actions: actions::Actions { memory, persona }, - thoughts: thoughts::Thoughts { memory }, - open_views: open_views::OpenViews { memory }, - notices: notices::Notices { memory }, + thoughts: thoughts::Thoughts { memory, persona }, + open_views: open_views::OpenViews { memory, persona }, + notices: notices::Notices { memory, persona }, } } } @@ -75,9 +101,8 @@ impl ContextMessage { } impl Block for ContextMessage { - fn chars(&self) -> usize { - // `str::chars`, not this trait's `chars`, which `String` also implements. - self.text.as_str().chars().count() + fn text(&self) -> &str { + &self.text } } diff --git a/core/continuum-cognition/src/cognition/context_streams/notices.rs b/core/continuum-cognition/src/cognition/context_streams/notices.rs index 55e158486f..43e6fd66f0 100644 --- a/core/continuum-cognition/src/cognition/context_streams/notices.rs +++ b/core/continuum-cognition/src/cognition/context_streams/notices.rs @@ -4,20 +4,26 @@ //! M5, 2026-10-24: the largest new text per act, ahead of her own results). Keyed, an unchanged //! notice is appended once per epoch and a changed one appends its new version. +use continuum_context::cause::{Cause, Origin}; use continuum_context::source::{Item, Source}; -use super::{priority, ContextMessage}; +use super::{element, priority, ContextMessage, Producer}; use crate::cognition::framing_echo::NOTICES_HEADER; use crate::cognition::working_memory::WorkingMemory; pub(crate) struct Notices<'a> { pub memory: &'a WorkingMemory, + /// Whose occurrences these are (`super::element`). + pub persona: uuid::Uuid, } /// 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), stored: None } +impl Notices<'_> { + /// A notice comes from her situation, outside her: an external origin. + fn notice(&self, key: String, text: String) -> Item { + let message = ContextMessage::user(text); + Item::whole(element(self.persona, Producer::Notice, key.as_bytes()), Cause::Root(Origin::External), key, message.clone()).with_pointer(message) + } } impl Source for Notices<'_> { @@ -41,8 +47,8 @@ impl Source for Notices<'_> { let banner = format!( "{NOTICES_HEADER} (status observations about my situation — not a message from anyone, and not my own words):" ); - let mut items = vec![required("banner".to_owned(), banner)]; - items.extend(notices.into_iter().map(|(key, text)| required(key, format!("- {text}")))); + let mut items = vec![super::standing(self.persona, "notices", "banner", ContextMessage::user(banner))]; + items.extend(notices.into_iter().map(|(key, text)| self.notice(key, format!("- {text}")))); items } @@ -53,8 +59,11 @@ impl Source for Notices<'_> { .ended_notice_keys() .into_iter() .map(|key| { - let notice = format!("- [ended] the notice {key} no longer holds"); - required(key, notice) + // The end of a notice follows from that notice. + let message = ContextMessage::user(format!("- [ended] the notice {key} no longer holds")); + let id = element(self.persona, Producer::Notice, format!("ended/{key}").as_bytes()); + let cause = Cause::Of(element(self.persona, Producer::Notice, key.as_bytes())); + Item::whole(id, cause, key, message.clone()).with_pointer(message) }) .collect() } 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 12bb6512e1..92ac0dfdc3 100644 --- a/core/continuum-cognition/src/cognition/context_streams/open_views.rs +++ b/core/continuum-cognition/src/cognition/context_streams/open_views.rs @@ -3,20 +3,24 @@ //! every act (~1.5k chars on the M5, 2026-10-24) though a view's line changes only when she //! pages it. Keyed by subject, paging one file appends that file's line alone. +use continuum_context::cause::{Cause, Origin}; use continuum_context::source::{Item, Source}; -use super::{priority, ContextMessage}; +use super::{element, priority, ContextMessage, Producer}; use crate::cognition::open_views::OpenViews as Views; use crate::cognition::working_memory::WorkingMemory; pub(crate) struct OpenViews<'a> { pub memory: &'a WorkingMemory, + /// Whose occurrences these are (`super::element`). + pub persona: uuid::Uuid, } /// Standing notices contain no allocatable detail. -fn required(key: String, text: String) -> Item { - let message = ContextMessage::user(text); - Item { key, full: message.clone(), summary: None, pointer: Some(message), stored: None } +impl OpenViews<'_> { + fn standing(&self, key: &str, text: String) -> Item { + super::standing(self.persona, "open-views", key, ContextMessage::user(text)) + } } impl Source for OpenViews<'_> { @@ -37,13 +41,13 @@ impl Source for OpenViews<'_> { if lines.is_empty() { return Vec::new(); } - let mut items = vec![required("banner".to_owned(), Views::BANNER.to_owned())]; - items.extend(lines.into_iter().map(|(key, full, pointer)| Item { - key, - full: ContextMessage::user(format!("- {full}")), - summary: None, - pointer: Some(ContextMessage::user(format!("- {pointer}"))), - stored: None, + let mut items = vec![self.standing("banner", Views::BANNER.to_owned())]; + // A view follows from the act that last read it. + items.extend(lines.into_iter().map(|line| { + let id = element(self.persona, Producer::OpenView, format!("{}#{}", line.key, line.touched_seq).as_bytes()); + let cause = Cause::Of(element(self.persona, Producer::Act, &line.touched_seq.to_be_bytes())); + Item::whole(id, cause, line.key, ContextMessage::user(format!("- {}", line.full))) + .with_pointer(ContextMessage::user(format!("- {}", line.pointer))) })); items } @@ -55,8 +59,9 @@ impl Source for OpenViews<'_> { .open_views_out_of_scope() .into_iter() .map(|key| { - let notice = format!("- [not visible from here] {key}"); - required(key, notice) + let id = element(self.persona, Producer::Notice, key.as_bytes()); + let message = ContextMessage::user(format!("- [not visible from here] {key}")); + Item::whole(id, Cause::Root(Origin::External), key, message.clone()).with_pointer(message) }) .collect() } diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 140ad873a7..a946bb53ca 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -9,7 +9,7 @@ use super::notices::Notices; use crate::cognition::working_memory::WorkingMemory; fn rendered(memory: &WorkingMemory) -> String { - Actions { memory, persona: uuid::Uuid::nil() }.items().iter().map(|item| item.full.text.clone()).collect::>().join("\n") + Actions { memory, persona: uuid::Uuid::nil() }.items().iter().map(|item| item.full().text.clone()).collect::>().join("\n") } // what this catches: her action stream going silent or lying about her acts, the three @@ -76,10 +76,10 @@ fn an_unsaved_result_never_collapses_to_a_line_nothing_reopens() { memory.record_receipt("I ran code/shell(cat Cargo.toml) Result: [package] name = \"x\""); memory.record_settlement("read the manifest", None); let (acts, _) = memory.action_renderings(); - let (_, full, _, pointer, stored) = acts.last().expect("the act is on record"); - assert!(stored.is_none(), "an unsaved result is resident: nothing to load"); - assert!(full.contains("name = \"x\""), "{full}"); - assert_eq!(pointer, full, "an unsaved result's pointer is the result itself"); + let act = acts.last().expect("the act is on record"); + assert!(act.stored.is_none(), "an unsaved result is resident: nothing to load"); + assert!(act.full.contains("name = \"x\""), "{}", act.full); + assert_eq!(act.pointer, act.full, "an unsaved result's pointer is the result itself"); } // what this catches (FOCUS-CONTRACT rule 7, FLOW §2d): RAM storage deciding what she sees. A @@ -95,17 +95,18 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], &body, None, pin.retain(persona, &body)); memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); - let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); + let resident_whole = before.first().map(|act| act.full.clone()).expect("test: the first act"); memory.evict_resident_results_over(1, &|_, _| true); let (acts, _) = memory.action_renderings(); - let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); + let act = acts.first().cloned().expect("test: the first act"); + let (seq, full, pointer, stored) = (act.seq, act.full, act.pointer, act.stored); let (chars, _) = stored.expect("evicted to its handle and priced"); assert_eq!(full, pointer, "what stays resident is its pointer"); assert_eq!(chars, resident_whole.chars().count(), "priced at exactly the whole it rendered"); let source = super::actions::Actions { memory: &memory, persona }; let item = continuum_context::source::Source::items(&source) .into_iter() - .find(|item| item.key == seq.to_string()) + .find(|item| item.key() == seq.to_string()) .expect("test: the act's item"); assert_eq!(continuum_context::source::whole_chars(&item), chars); let whole = continuum_context::source::whole(&source, item); @@ -124,7 +125,7 @@ fn her_notices_append_once_and_an_ended_one_is_retired() { let memory = WorkingMemory::new(8); memory.pin_fact("hands", "[hands] your hands stand in the card's checkout"); memory.record_fact("[rebuilt] the substrate was rebuilt while you were away"); - let notices = Notices { memory: &memory }; + let notices = Notices { memory: &memory, persona: uuid::Uuid::nil() }; let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); let (mut view, _) = View::start(Vec::new(), &[¬ices as &dyn Source<_>], whole).unwrap(); let text = |view: &View| view.render().map(|m| m.text.clone()).collect::>().join("\n"); @@ -159,7 +160,7 @@ fn a_thought_renders_the_same_whatever_the_served_window() { let memory = WorkingMemory::new(8); memory.record(&"a long line of reasoning about the failing test. ".repeat(80)); let render = |memory: &WorkingMemory| { - Thoughts { memory }.items().into_iter().map(|item| item.full.text).collect::>() + Thoughts { memory, persona: uuid::Uuid::nil() }.items().into_iter().map(|item| item.full().text.clone()).collect::>() }; memory.set_served_window(32_768); let narrow = render(&memory); @@ -176,7 +177,10 @@ fn a_thought_renders_the_same_whatever_the_served_window() { fn her_folded_acts_name_their_range_and_count_in_one_line() { let memory = WorkingMemory::new(2); let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; - let item = |key: &str| continuum_context::source::Item::whole(key, super::ContextMessage::user(format!("act {key}"))); + let item = |key: &str| { + let id = super::element(uuid::Uuid::nil(), super::Producer::Act, key.as_bytes()); + continuum_context::source::Item::whole(id, continuum_context::cause::Cause::Unrecorded, key, super::ContextMessage::user(format!("act {key}"))) + }; let run: Vec<_> = (3200..=3330).map(|seq: u64| item(&seq.to_string())).collect(); let Some(block) = actions.fold(&run) else { panic!("a run with acts folds") }; assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts folded; reopen one with tool/output act=]"); diff --git a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs index 8a8ace1f05..a192dffee6 100644 --- a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs +++ b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs @@ -1,9 +1,10 @@ //! Her own recent thoughts and the answers she settled, one item each. Her actions are not //! here: they are the action stream, rendered once ([`super::actions`]). +use continuum_context::cause::{Cause, Origin}; use continuum_context::source::{Item, Source}; -use super::{priority, ContextMessage}; +use super::{element, priority, ContextMessage, Producer}; use crate::cognition::working_memory::{collapse_thought, render_dispatched, WmKind, WorkingMemory}; /// What a collapsed thought keeps: its end, where the decision is. @@ -11,6 +12,8 @@ const POINTER_KEEP: usize = 200; pub(crate) struct Thoughts<'a> { pub memory: &'a WorkingMemory, + /// Whose occurrences these are (`super::element`). + pub persona: uuid::Uuid, } impl Source for Thoughts<'_> { @@ -39,26 +42,24 @@ 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), stored: None }]; + let mut items = vec![super::standing(self.persona, "thoughts", "banner", banner)]; + // Her thoughts are one interior chain: each follows the one before it. + let mut previous = None; items.extend(thoughts.into_iter().map(|text| { + let id = element(self.persona, Producer::Thought, text.as_bytes()); + let cause = previous.replace(id).map_or(Cause::Root(Origin::ActivityStart), Cause::Of); // 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 // one allocation's call at an epoch start (collapsed to `pointer`), never a per-act // head here. Cut to a share of the served window, the same thought rendered 1,284 // 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 { - key: text.clone(), - full: ContextMessage::user(format!("- {text}")), - summary: None, - pointer: Some(ContextMessage::user(format!("- {}", collapse_thought(&text, POINTER_KEEP)))), - stored: None, - } + Item::whole(id, cause, text.clone(), ContextMessage::user(format!("- {text}"))) + .with_pointer(ContextMessage::user(format!("- {}", collapse_thought(&text, POINTER_KEEP)))) })); // 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), stored: None } + super::standing(self.persona, "thoughts", "dispatched", ContextMessage::user(text)) })); items } 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 1e8b2dbbd8..b85529c3b8 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 @@ -70,8 +70,8 @@ impl LlmDeliberationFaculty { // is priced from its measured size, never as the pointer resident in its place, // or the allocation would never grant room to see it (FOCUS-CONTRACT rule 7). let whole = |item: &continuum_context::source::Item| { - let extra = continuum_context::source::whole_chars(item).saturating_sub(item.full.text.chars().count()); - cost(&item.full) + extra / continuum_base::token_estimate::GUARD_CHARS_PER_TOKEN + let extra = continuum_context::source::whole_chars(item).saturating_sub(item.full().text.chars().count()); + cost(item.full()) + extra / continuum_base::token_estimate::GUARD_CHARS_PER_TOKEN }; let want: usize = items.iter().map(whole).sum(); crate::cognition::rag_budget::RagSourceBudget { 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 e745f691f2..ae1a40adef 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::atomic(faculty, text) + Grounding::atomic(uuid::Uuid::nil(), faculty, text) } fn turn(n: usize) -> Turn { @@ -20,7 +20,7 @@ fn turn(n: usize) -> Turn { /// that says something new every act. fn streams(first_turn: usize, recall: &str) -> Streams { Streams { - conversation: Conversation { turns: (first_turn..first_turn + 6).map(turn).collect() }, + conversation: Conversation { turns: (first_turn..first_turn + 6).map(turn).collect(), ..Default::default() }, blocks: vec![ block("workspace-map", "MAP: src/ tests/ docs/"), block("room-kanban", "BOARD: you hold 1 card; 3 claimable"), 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 084a964ae0..f330599492 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 @@ -268,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, units: std::sync::Arc::clone(&c.units) } + crate::cognition::context_streams::blocks::Grounding { persona: self.persona_id, faculty: c.faculty.as_str().to_owned(), text, minimum, units: std::sync::Arc::clone(&c.units) } }) .collect(); let result_pointers = Vec::new(); @@ -380,7 +380,7 @@ impl LlmDeliberationFaculty { input_identity: input.finalize().into(), history: messages, streams: super::types::Streams { - conversation: crate::cognition::context_streams::conversation::Conversation { turns }, + conversation: crate::cognition::context_streams::conversation::Conversation { persona: self.persona_id, turns }, blocks, }, result_pointers, 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 21a01c5be2..5e5f1fedf6 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 @@ -189,7 +189,7 @@ impl LlmDeliberationFaculty { visual, ); all_messages.streams.blocks.extend(contracts.into_iter().map(|contract| { - crate::cognition::context_streams::blocks::Grounding::atomic(contract.name, contract.body) + crate::cognition::context_streams::blocks::Grounding::atomic(self.persona_id, 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. 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 55bdddfb9c..923fb72ecf 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,11 @@ 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]")), stored: None }) + .map(|(key, text)| { + // A fixture turn: its id from its key, its cause unrecorded (this test is about starts). + let id = crate::cognition::context_streams::element(uuid::Uuid::nil(), crate::cognition::context_streams::Producer::Turn, key.as_bytes()); + Item::whole(id, continuum_context::cause::Cause::Unrecorded, key.clone(), text.clone()).with_pointer(format!("[{key} collapsed]")) + }) .collect() } } diff --git a/core/continuum-cognition/src/cognition/open_views.rs b/core/continuum-cognition/src/cognition/open_views.rs index c2b93407cb..d6e8e5bce4 100644 --- a/core/continuum-cognition/src/cognition/open_views.rs +++ b/core/continuum-cognition/src/cognition/open_views.rs @@ -247,7 +247,7 @@ impl OpenViews { /// Each visible view's stable key, whole representation and resolvable cursor. Planning /// prose is detail, never part of the mandatory cursor floor (FOCUS-CONTRACT rules 1–3). - pub fn lines(&self, scope: Option<&str>) -> Vec<(String, String, String)> { + pub fn lines(&self, scope: Option<&str>) -> Vec { let mut visible: Vec<&OpenView> = self.views.iter().filter(|v| visible_from(v, scope)).collect(); visible.sort_by(|a, b| a.subject.cmp(&b.subject)); visible.into_iter().map(|view| { @@ -256,7 +256,7 @@ impl OpenViews { Some(note) => format!("{pointer}; intent before this read: \"{note}\""), None => pointer.clone(), }; - (view_key(view), full, pointer) + ViewLine { key: view_key(view), full, pointer, touched_seq: view.touched_seq } }).collect() } @@ -273,14 +273,23 @@ impl OpenViews { return None; } let mut out = String::from(Self::BANNER); - for (_, line, _) in lines { + for line in lines { out.push_str("\n- "); - out.push_str(&line); + out.push_str(&line.full); } Some(out) } } +/// One open view as her view renders it: its key, its whole and pointer lines, and the act that +/// last read it (its cause). +pub struct ViewLine { + pub key: String, + pub full: String, + pub pointer: String, + pub touched_seq: u64, +} + fn visible_from(view: &OpenView, scope: Option<&str>) -> bool { view.scope.is_none() || view.scope.as_deref() == scope } diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index a448d7d36d..b170280cd7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -4,7 +4,22 @@ use super::*; /// One act as her view renders it: seq, full, summary, pointer, and its stored whole (rendered /// chars, handle) when its body is not resident. -pub(crate) type ActRendering = (u64, String, Option, String, Option<(usize, String)>); +/// One act as her view renders it: who it is (its `seq` in her ledger, the room it was for), its +/// levels, and where its whole is stored when it left RAM. +#[derive(Clone, Debug)] +pub(crate) struct ActRendering { + pub seq: u64, + /// The room the act was for; acts in one room are one chain. + pub room: Option, + pub full: String, + pub summary: Option, + pub pointer: String, + /// `(chars, handle)` of a whole that left RAM for its saved output. + pub stored: Option<(usize, String)>, + /// The hash of the act's RAW result bytes, before any label: two identical outcomes hash + /// equal whatever their seq or room (`Absent` when the result is not resident). + pub content: continuum_context::cause::Content, +} impl WorkingMemory { /// Typed snapshot of the window, oldest → newest — the kind-aware sibling @@ -211,7 +226,7 @@ impl WorkingMemory { /// Her open views visible from where her hands stand, one `(key, full, pointer)` each: the items of /// her view's open-views stream (`context_streams::open_views`). - pub(crate) fn open_view_lines(&self) -> Vec<(String, String, String)> { + pub(crate) fn open_view_lines(&self) -> Vec { let scope = self.scope.lock().clone(); self.open_views.lock().lines(scope.as_deref()) } @@ -262,7 +277,10 @@ impl WorkingMemory { }; let full = whole.unwrap_or_else(|| pointer.clone()); let summary = record.summary.as_deref().map(|summary| format!("[result {attribution}{workspace} — summary; expand with tool/output] {summary}")); - (record.seq, full, summary, pointer, stored) + let content = record.result.as_deref().map_or(continuum_context::cause::Content::Absent, |result| { + continuum_context::cause::Content::Hashed(continuum_context::cause::ContentHash::of(result)) + }); + ActRendering { seq: record.seq, room: record.room, full, summary, pointer, stored, content } }) .collect(); (renderings, in_flight) diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index 52f119b7ca..55f8dd8d55 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -159,7 +159,7 @@ fn a_moved_body_s_handle_stays_live_behind_any_number_of_newer_pointers() { assert!(live(&first), "the oldest moved body's handle is still protected"); let (acts, _) = wm.action_renderings(); let oldest = acts.first().expect("test: the first act"); - assert_eq!(oldest.4.as_ref().map(|(_, h)| h.as_str()), Some(first.as_str()), "its record stays, priced and reloadable"); + assert_eq!(oldest.stored.as_ref().map(|(_, h)| h.as_str()), Some(first.as_str()), "its record stays, priced and reloadable"); drop(wm); assert!(!live(&first), "released when the mind drops"); } @@ -427,7 +427,7 @@ fn a_restore_prices_a_legacy_evicted_result_from_its_saved_output() { let restored = WorkingMemory::new(8); restored.restore(snapshot); let (acts, _) = restored.action_renderings(); - let label = restored.action_whole_label(acts[0].0).expect("test: a label").chars().count(); - assert_eq!(acts[0].4.as_ref().map(|(chars, _)| *chars), Some(label + measured), "priced from its saved output, label included"); - assert_eq!(acts[1].4, None, "an output that can't be read stays a pointer"); + let label = restored.action_whole_label(acts[0].seq).expect("test: a label").chars().count(); + assert_eq!(acts[0].stored.as_ref().map(|(chars, _)| *chars), Some(label + measured), "priced from its saved output, label included"); + assert_eq!(acts[1].stored, None, "an output that can't be read stays a pointer"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs index 098174285f..5c27bcb02d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs @@ -155,7 +155,7 @@ fn a_view_in_a_checkout_her_hands_left_is_retired_from_her_view() { wm.set_served_window(46_848); wm.set_scope(Some("/checkouts/a".into())); record(&wm, read(1, 40, 498, None)); - let views = crate::cognition::context_streams::open_views::OpenViews { memory: &wm }; + let views = crate::cognition::context_streams::open_views::OpenViews { memory: &wm, persona: uuid::Uuid::nil() }; let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect(); let (mut view, _) = match View::start(Vec::new(), &[&views as &dyn Source<_>], whole) { Ok(started) => started, @@ -187,7 +187,7 @@ fn planning_detail_yields_to_cursor_and_returns_when_granted() { let wm = WorkingMemory::new(3); record(&wm, read(1, 498, 498, None)); - let source = crate::cognition::context_streams::open_views::OpenViews { memory: &wm }; + let source = crate::cognition::context_streams::open_views::OpenViews { memory: &wm, persona: uuid::Uuid::nil() }; let sources: &[&dyn Source<_>] = &[&source]; let cursor_floor = claims(sources)[0].floor_chars; let intent = "I need to inspect the implementation before deciding what to change. ".repeat(64); @@ -212,7 +212,7 @@ fn planning_detail_yields_to_cursor_and_returns_when_granted() { // Checkpointing preserves the complete note even while its visible level is a cursor. let restored = WorkingMemory::new(3); restored.restore(wm.snapshot()); - let restored_source = crate::cognition::context_streams::open_views::OpenViews { memory: &restored }; + let restored_source = crate::cognition::context_streams::open_views::OpenViews { memory: &restored, persona: uuid::Uuid::nil() }; view.turn_over(Vec::new(), &[&restored_source], whole).expect("matching grants"); assert!(text(&view).contains(intent.trim()), "the allocation never deleted the note"); } diff --git a/core/continuum-context/Cargo.toml b/core/continuum-context/Cargo.toml index 7924b9f564..c3e4474d7d 100644 --- a/core/continuum-context/Cargo.toml +++ b/core/continuum-context/Cargo.toml @@ -6,6 +6,7 @@ description = "A mind's model view as an epoch materialization: a stable head, t [dependencies] serde = { workspace = true } +sha2 = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/core/continuum-context/examples/replay.rs b/core/continuum-context/examples/replay.rs index 700f60e996..116483f2df 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -128,7 +128,14 @@ 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, stored: None } + captured(key, text).with_pointer(pointer) +} + +/// A captured element: a capture records what was sent, never what caused it, so its cause is +/// `Unrecorded` (counted, never toward closure) and its id comes from its key. +fn captured(key: String, full: String) -> Item { + let id = continuum_context::cause::ElementId::of(&[key.as_bytes()]); + Item::whole(id, continuum_context::cause::Cause::Unrecorded, key, full) } /// The one allocation, modelled: every source gets its floor, then the rest of `budget` @@ -297,7 +304,7 @@ fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { // Its action lines are the action log again; its thoughts are its own items. let thoughts = bullets("working-memory", &text) .into_iter() - .filter(|item| !item.full.starts_with("- [action #")) + .filter(|item| !item.full().starts_with("- [action #")) .collect(); push("working-memory", thoughts); } else if text.starts_with("My own recent thoughts") { @@ -323,8 +330,8 @@ fn cut(request: &serde_json::Value, tools: &str, keyed_turn: bool) -> Cut { } // A ledger line stands in for an act only when the log holds no rendering of it. if let Some(ledger) = sources.remove("ledger") { - let held: Vec = sources.get("actions").into_iter().flatten().map(|item| item.key.clone()).collect(); - let missing = ledger.into_iter().filter(|line| !held.contains(&line.key)).collect::>(); + let held: Vec = sources.get("actions").into_iter().flatten().map(|item| item.key().to_owned()).collect(); + let missing = ledger.into_iter().filter(|line| !held.iter().any(|key| key == 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) } @@ -377,7 +384,7 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order let mut tails = Vec::new(); let mut turnover_prefill = Vec::new(); for cut in cuts { - let action_keys: Vec = cut.sources.get("actions").into_iter().flatten().map(|item| item.key.clone()).collect(); + let action_keys: Vec = cut.sources.get("actions").into_iter().flatten().map(|item| item.key().to_owned()).collect(); restored.learn(&action_keys, &cut.act); let counted = restored.rereads(&cut.act, &previous_view); rereads += counted.total; @@ -400,10 +407,10 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order tails.push(tail_chars as f64); for (name, items) in &cut.sources { for item in items { - let key = (name.clone(), item.key.clone()); - if held.get(&key) != Some(&item.full) { - *appended.entry(name.clone()).or_default() += item.full.chars().count(); - held.insert(key, item.full.clone()); + let key = (name.clone(), item.key().to_owned()); + if held.get(&key) != Some(item.full()) { + *appended.entry(name.clone()).or_default() += item.full().chars().count(); + held.insert(key, item.full().clone()); } } } diff --git a/core/continuum-context/examples/replay/append.rs b/core/continuum-context/examples/replay/append.rs index 174482cb2c..0e161f23d2 100644 --- a/core/continuum-context/examples/replay/append.rs +++ b/core/continuum-context/examples/replay/append.rs @@ -141,7 +141,7 @@ pub fn replay(label: &str, cuts: &[Cut], window: usize, share: usize, (chars_per paging.said(n, &cut.said); // The pages her last act needed past a first page: one extra request each, appended. let extra_pages = if options.paged { pager.said(n, &cut.said, &cut.reads) } else { Vec::new() }; - let action_keys: Vec = cut.sources.get("actions").into_iter().flatten().map(|item| item.key.clone()).collect(); + let action_keys: Vec = cut.sources.get("actions").into_iter().flatten().map(|item| item.key().to_owned()).collect(); restored.learn(&action_keys, &cut.act); let mut sources: Vec = cut .sources @@ -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, stored: None }); + looped.push(crate::captured(looped.len().to_string(), full)); } for full in extra_pages { - looped.push(Item { key: looped.len().to_string(), pointer: None, summary: None, full, stored: None }); + looped.push(crate::captured(looped.len().to_string(), 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 ca3824adb6..cdd0821f16 100644 --- a/core/continuum-context/examples/replay/sediment.rs +++ b/core/continuum-context/examples/replay/sediment.rs @@ -67,7 +67,7 @@ impl Sediment { } for source in sources { let name = source.name.clone(); - source.items.retain(|item| !self.keys.contains(&(name.clone(), item.key.clone()))); + source.items.retain(|item| !self.keys.contains(&(name.clone(), item.key().to_owned()))); } } @@ -76,15 +76,15 @@ impl Sediment { pub fn settle(&mut self, sources: &mut [Captured], grants: &[usize]) -> usize { let mut batch = Vec::new(); for (source, grant) in sources.iter_mut().zip(grants) { - let standing: usize = source.items.iter().filter(|item| !settles(&source.name, &item.key)).map(|item| item.full.chars().count()).sum(); + let standing: usize = source.items.iter().filter(|item| !settles(&source.name, item.key())).map(|item| item.full().chars().count()).sum(); let mut room = grant.saturating_sub(standing); // Newest first: the items that still fit whole stay young; from the first that does // not, every older item settles (a contiguous oldest run). Her newest item of each // source stays young whatever its grant: the newest is never collapsed. let mut boundary = 0; let mut newest = true; - for (index, item) in source.items.iter().enumerate().rev().filter(|(_, item)| settles(&source.name, &item.key)) { - let chars = item.full.chars().count(); + for (index, item) in source.items.iter().enumerate().rev().filter(|(_, item)| settles(&source.name, item.key())) { + let chars = item.full().chars().count(); if std::mem::take(&mut newest) { room = room.saturating_sub(chars); continue; @@ -98,11 +98,11 @@ impl Sediment { let name = source.name.clone(); let mut index = 0; source.items.retain(|item| { - let settle = index < boundary && settles(&name, &item.key); + let settle = index < boundary && settles(&name, item.key()); index += 1; if settle { - let key = (name.clone(), item.key.clone()); - let pointer = item.pointer.clone().unwrap_or_else(|| item.full.clone()); // unwrap_or_else: an item without a pointer is its own handle + let key = (name.clone(), item.key().to_owned()); + let pointer = item.pointer().cloned().unwrap_or_else(|| item.full().clone()); // unwrap_or_else: an item without a pointer is its own handle self.keys.insert(key.clone()); batch.push((key, pointer)); } @@ -152,7 +152,7 @@ impl Sediment { /// Every (source, key) the sources offer this act, before the sediment filters them. pub fn offered(sources: &[Captured]) -> HashSet<(String, String)> { - sources.iter().flat_map(|source| source.items.iter().map(|item| (source.name.clone(), item.key.clone()))).collect() + sources.iter().flat_map(|source| source.items.iter().map(|item| (source.name.clone(), item.key().to_owned()))).collect() } /// The grants each source gets under `rule`'s start, mapped back to `sources` by name: the @@ -165,13 +165,14 @@ pub fn grants_by_source(sources: &[Captured], claims: &[Claim], grants: &[usize] #[cfg(test)] mod tests { use super::*; - use continuum_context::source::Item; fn source(name: &str, sizes: &[usize]) -> Captured { let items = sizes .iter() .enumerate() - .map(|(n, size)| Item { key: n.to_string(), full: "x".repeat(*size), summary: None, pointer: Some(format!("[result #{n}]")), stored: None }) + .map(|(n, size)| { + crate::captured(n.to_string(), "x".repeat(*size)).with_pointer(format!("[result #{n}]")) + }) .collect(); Captured { name: name.to_owned(), items } } @@ -183,7 +184,7 @@ mod tests { let mut sources = vec![source("actions", &[100, 100, 10, 100, 50]), source("room-doctrine", &[500])]; let mut sediment = Sediment::default(); assert_eq!(sediment.settle(&mut sources, &[150, 0]), 3); - let young: Vec<&str> = sources[0].items.iter().map(|item| item.key.as_str()).collect(); + let young: Vec<&str> = sources[0].items.iter().map(|item| item.key()).collect(); assert_eq!(young, ["3", "4"], "from the first item that does not fit, the whole oldest run settles"); assert_eq!(sources[1].items.len(), 1, "a standing block never settles"); assert!(sediment.heads("head")[1].starts_with(HEADER) && sediment.heads("head")[1].ends_with("[result #2]")); diff --git a/core/continuum-context/examples/replay/validate.rs b/core/continuum-context/examples/replay/validate.rs index 21b0f458c0..fea4584591 100644 --- a/core/continuum-context/examples/replay/validate.rs +++ b/core/continuum-context/examples/replay/validate.rs @@ -146,17 +146,19 @@ impl Restored { /// its pointer. An item sent whole already is left as it was. pub fn enrich(&self, items: &mut [Item]) { for item in items { - let Some(whole) = self.by_seq.get(&item.key) else { continue }; - if item.full.chars().count() >= whole.chars().count() { + let Some(whole) = self.by_seq.get(item.key()) else { continue }; + if item.full().chars().count() >= whole.chars().count() { continue; } - let sent = item.full.clone(); + let sent = item.full().clone(); let header = sent.lines().next().unwrap_or_default().to_owned(); // unwrap_or_default: an empty item has no header line - item.summary = summarize(whole, Shape::Code(&gutter)) + let summary = summarize(whole, Shape::Code(&gutter)) .or_else(|| summarize(whole, Shape::Output)) .map(|summary| format!("{header}\n{summary}")); - item.full = format!("{header}\n{whole}"); - item.pointer = Some(sent); + // Rebuilt, never edited in place: its content hash is the whole it now holds. + *item = Item::whole(item.id(), item.cause(), item.key(), format!("{header}\n{whole}")) + .with_summary(summary) + .with_pointer(sent); } } diff --git a/core/continuum-context/src/cause.rs b/core/continuum-context/src/cause.rs new file mode 100644 index 0000000000..2e20d44ec6 --- /dev/null +++ b/core/continuum-context/src/cause.rs @@ -0,0 +1,110 @@ +//! What each element she perceives follows from (MIND-CONTEXT-AND-ENGINE-CONFIG.md, "causality is +//! in the type"). Every element is one occurrence in a causal chain: an act and its result, a +//! message and its reply, a move and the position after it. The view keeps chains whole at their +//! heads, folds a chain without breaking it, and renders an element only with its cause +//! represented, so no source can present a repeat as progress or an effect without its cause. + +use sha2::{Digest, Sha256}; + +/// One occurrence, named by the producer that persists it (an act, a message, an engram): +/// stable across epochs and restarts, never an in-view position. Two reads of one file are two +/// occurrences with two ids; the file they read is the item's `key`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ElementId(u128); + +impl ElementId { + pub const fn from_u128(raw: u128) -> Self { + Self(raw) + } + + pub const fn as_u128(self) -> u128 { + self.0 + } + + /// The id named by a producer's stable identity, given as its parts (whose, which producer, + /// the producer's own id for it): the first 128 bits of their SHA-256. One derivation, so two + /// producers never disagree about how an identity becomes an id. Each part is length-prefixed, + /// so the boundary between parts is part of the identity: `["ab", "c"]` and `["a", "bc"]` are + /// different occurrences (Cormac on #5611). + pub fn of(identity: &[&[u8]]) -> Self { + let mut hasher = Sha256::new(); + for part in identity { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part); + } + let digest: [u8; 32] = hasher.finalize().into(); + let (head, _) = digest.split_at(std::mem::size_of::()); + let mut bytes = [0u8; std::mem::size_of::()]; + bytes.copy_from_slice(head); + Self(u128::from_be_bytes(bytes)) + } +} + +/// What an element follows from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Cause { + /// The occurrence it follows from: her act for its result, the message a reply answers, the + /// act before this one in her chain. + Of(ElementId), + /// A genuine origin, the only cause that is not another element. The source-hygiene ratchet + /// counts each source's `Root` constructions: an origin claimed where a cause exists is how a + /// chain breaks without anyone seeing it. + Root(Origin), + /// A record restored from before causes were kept: its cause was never written. Counted + /// by the validator, never toward causal closure and never a repeat's ancestor; not + /// `CauseNotHeld`, which promises a durable handle these never had (Cormac on #5607). + Unrecorded, +} + +/// The genuine origins. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Origin { + /// From outside her: a person's message, a peer's event, a notice from the world. + External, + /// The start of an activity she entered: the first element of its chain. + ActivityStart, +} + +/// What is known of an element's whole: its hash, or nothing at all for a record restored from +/// before hashes were kept. Never a minted hash. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Content { + Hashed(ContentHash), + Absent, +} + +/// The hash of an element's whole, computed once where the whole is held or stored, so a deferred +/// whole is compared without being read again. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ContentHash([u8; 32]); + +impl ContentHash { + /// The hash of a whole's text. + pub fn of(whole: &str) -> Self { + Self(Sha256::digest(whole.as_bytes()).into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: two occurrences with the same output compared as one effect. Content + // equality is evidence only for an unchanged observation; the occurrences stay distinct + // (Codex on #5607: two appends can both return "OK"). + #[test] + fn equal_content_hashes_equal_and_distinct_occurrences_stay_distinct() { + assert_eq!(ContentHash::of("fn a() {}"), ContentHash::of("fn a() {}")); + assert_ne!(ContentHash::of("fn a() {}"), ContentHash::of("fn b() {}")); + assert_ne!(ElementId::from_u128(1), ElementId::from_u128(2)); + } + + // what this catches: two different occurrences sharing an id because their identity parts + // concatenate to the same bytes; every chain is keyed by the id (Cormac on #5611). + #[test] + fn the_boundary_between_identity_parts_is_part_of_the_id() { + assert_ne!(ElementId::of(&[b"ab", b"c"]), ElementId::of(&[b"a", b"bc"])); + assert_ne!(ElementId::of(&[b"ab"]), ElementId::of(&[b"a", b"b"])); + assert_eq!(ElementId::of(&[b"a", b"bc"]), ElementId::of(&[b"a", b"bc"])); + } +} diff --git a/core/continuum-context/src/epoch.rs b/core/continuum-context/src/epoch.rs index 32fddcf830..543bbe6e5b 100644 --- a/core/continuum-context/src/epoch.rs +++ b/core/continuum-context/src/epoch.rs @@ -13,15 +13,20 @@ pub struct SourceId(pub String); /// What a block holds: plain text, or a caller's richer rendering (a role-tagged message). /// The epoch compares blocks for equality and counts their characters; nothing else. pub trait Block: Clone + PartialEq + std::hash::Hash { - /// Characters this block costs the view, the unit [`Epoch::superseded_chars`] counts. - fn chars(&self) -> usize; + /// The block's text: what it costs and what its content hash is taken over. + fn text(&self) -> &str; + + /// Characters this block costs the view, the unit [`Epoch::superseded_chars`] counts: + /// characters, never bytes (bytes would weigh a non-ASCII block heavier than its twin and skew + /// the one allocation). + fn chars(&self) -> usize { + self.text().chars().count() + } } impl Block for String { - /// Characters, the same unit every block counts in (bytes would weigh a non-ASCII - /// block heavier than its twin and skew the one allocation). - fn chars(&self) -> usize { - self.as_str().chars().count() + fn text(&self) -> &str { + self } } diff --git a/core/continuum-context/src/lib.rs b/core/continuum-context/src/lib.rs index ef2f0dd0ac..a4e61ea425 100644 --- a/core/continuum-context/src/lib.rs +++ b/core/continuum-context/src/lib.rs @@ -1,12 +1,14 @@ //! A mind's context as an epoch materialization (docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md). //! Its own crate so the monolith never grows by it and its tests run in seconds. //! +//! - [`cause`]: what each element follows from: its occurrence id, its cause, its content. //! - [`epoch`]: a stable head, then keyed blocks that only append. //! - [`source`]: what a context source offers: its current items, each under a stable key. //! - [`levels`]: each item's summary level, generated from its shape (mipmaps for context). //! - [`motion`]: how each source moves between epoch starts, which orders the next start. //! - [`view`]: one mind's epoch fed by its sources; turnover is the only rewrite. +pub mod cause; pub mod epoch; pub mod levels; pub mod motion; diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index b22be1952a..3ae41e21a4 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -6,30 +6,38 @@ //! them. A source that cannot key its state (the clock, this act's ask) is not a source: //! it rides the fresh tail after the epoch. +use crate::cause::{Cause, Content, ContentHash, ElementId}; use crate::epoch::Block; /// One item of a source's state, in both renderings the view may choose between. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Item { - /// Stable for the item's life: the same result, file or notice keeps its key. - pub key: String, + /// Stable for the item's life: the same result, file or notice keeps its key. What the item is + /// ABOUT; the occurrence is `id`. + pub(crate) key: String, + /// This occurrence, named by its producer: two reads of one file share a `key` and have two ids. + pub(crate) id: ElementId, + /// What this occurrence follows from (`crate::cause`). + pub(crate) cause: Cause, + /// Its whole's hash, taken once where the whole is held or stored. + pub(crate) content: Content, /// The item itself. - pub full: T, + pub(crate) full: T, /// A coarser rendering between whole and pointer (a file's outline and the lines she /// works in), like a mipmap level: what the view gives an item too large to keep whole /// before it gives it only its pointer. `None` when the item has no such level. - pub summary: Option, + pub(crate) summary: Option, /// What it is and how to reopen it: what the item costs once collapsed. `None` when the /// 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, + pub(crate) 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, + pub(crate) stored: Option, } /// Where a non-resident whole lives and what it costs, measured when it was stored. @@ -39,12 +47,79 @@ pub struct StoredWhole { pub chars: usize, /// The handle the render's loader opens (a spill path, a result id). pub handle: String, + /// The whole's hash, taken at spill time with its size so it is compared without reading the + /// body back; `Absent` for a whole spilled before hashes were kept (never a minted hash). + pub content: Content, } -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 } +/// An item's fields are private to this crate: a source builds one through a constructor, which +/// requires its cause and takes its content hash from bytes, and adds coarser levels with the +/// builders below. There is no way to replace `full` after it is hashed (Cormac on #5611). +impl Item { + /// An occurrence resident whole, with no coarser levels yet. Its cause is required: a source + /// cannot build an element without saying what it follows from. + pub fn whole(id: ElementId, cause: Cause, key: impl Into, full: T) -> Self { + let content = Content::Hashed(ContentHash::of(full.text())); + Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None } + } + + /// An occurrence whose `full` is a rendering of a whole held elsewhere (a result shown under + /// its attribution label): `content` is that whole's hash, taken over its raw bytes where it + /// is held, so two equal outcomes compare equal whatever their labels say. `Absent` when the + /// whole is not held. + pub fn rendered(id: ElementId, cause: Cause, key: impl Into, full: T, content: Content) -> Self { + Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None } + } + + /// Its pointer level: what it costs once collapsed, and how to reopen it. `None` when it + /// leaves the view entirely once collapsed. + pub fn with_pointer(mut self, pointer: impl Into>) -> Self { + self.pointer = pointer.into(); + self + } + + /// Its summary level, between whole and pointer. + pub fn with_summary(mut self, summary: Option) -> Self { + self.summary = summary; + self + } + + /// Its whole is stored, not resident (`StoredWhole`). + pub fn with_stored(mut self, stored: Option) -> Self { + self.stored = stored; + self + } + + pub fn key(&self) -> &str { + &self.key + } + + pub fn id(&self) -> ElementId { + self.id + } + + pub fn cause(&self) -> Cause { + self.cause + } + + pub fn content(&self) -> Content { + self.content + } + + pub fn full(&self) -> &T { + &self.full + } + + pub fn summary(&self) -> Option<&T> { + self.summary.as_ref() + } + + pub fn pointer(&self) -> Option<&T> { + self.pointer.as_ref() + } + + pub fn stored(&self) -> Option<&StoredWhole> { + self.stored.as_ref() } } diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 4e7c1241e6..86905e2da0 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -1,6 +1,17 @@ use super::*; +use crate::cause::{Cause, Content, ElementId}; use crate::source::Item; +/// A fixture occurrence at `key`: its id from the key, its cause unrecorded (these tests are about +/// levels and starts, not chains). +fn item(key: impl Into, full: String, summary: Option, pointer: Option) -> Item { + let key = key.into(); + let mut item = Item::whole(ElementId::of(&[key.as_bytes()]), Cause::Unrecorded, key, full); + item.summary = summary; + item.pointer = pointer; + item +} + /// A source shaped like the M5's: items keyed, each renderable in full or as a pointer. struct Fake { name: &'static str, @@ -31,19 +42,13 @@ impl Source for Fake { fn items(&self) -> Vec> { self.items .iter() - .map(|(key, text)| Item { - key: key.clone(), - full: text.clone(), - summary: None, - pointer: Some(format!("[{key}: {} chars, reopen by key]", text.len())), - stored: None, - }) + .map(|(key, text)| item(key.clone(), text.clone(), None, Some(format!("[{key}: {} chars, reopen by key]", text.len())))) .collect() } fn retired(&self) -> Vec> { self.retired .iter() - .map(|(key, text)| Item { key: key.clone(), full: text.clone(), summary: None, pointer: Some(text.clone()), stored: None }) + .map(|(key, text)| item(key.clone(), text.clone(), None, Some(text.clone()))) .collect() } } @@ -180,7 +185,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, stored: None }).collect() + self.0.iter().map(|t| item(*t, (*t).to_owned(), None, None)).collect() } } let mut turns = Turns(vec!["one", "two", "three"]); @@ -244,13 +249,7 @@ impl Source for Leveled { fn items(&self) -> Vec> { self.0 .iter() - .map(|(key, full, summary)| Item { - key: (*key).to_owned(), - full: full.clone(), - summary: summary.clone(), - pointer: Some(format!("[{key}]")), - stored: None, - }) + .map(|(key, full, summary)| item(*key, full.clone(), summary.clone(), Some(format!("[{key}]")))) .collect() } } @@ -386,13 +385,12 @@ impl Source for Spilled { fn items(&self) -> Vec> { let pointer = "[result #3341: saved, reopen by its handle]".to_owned(); vec![ - Item { key: "3340".to_owned(), full: "an older result".to_owned(), summary: None, pointer: Some("[result #3340]".to_owned()), stored: None }, - Item { - key: "3341".to_owned(), - full: pointer.clone(), - summary: None, - pointer: Some(pointer), - stored: Some(crate::source::StoredWhole { chars: self.body.chars(), handle: "spill/3341".to_owned() }), + item("3340", "an older result".to_owned(), None, Some("[result #3340]".to_owned())), + { + let mut stored = item("3341", pointer.clone(), None, Some(pointer)); + stored.stored = Some(crate::source::StoredWhole { chars: self.body.chars(), handle: "spill/3341".to_owned(), content: Content::Absent }); + stored.content = Content::Absent; + stored }, ] } @@ -449,13 +447,7 @@ impl Source for Folding { fn items(&self) -> Vec> { self.items .iter() - .map(|(seq, full, summary)| Item { - key: seq.to_string(), - full: full.clone(), - summary: summary.clone(), - pointer: Some(format!("[result #{seq}; room r; operation code/read; output handle: tool/output {seq:0>16} — collapsed; {}]", "p".repeat(80))), - stored: None, - }) + .map(|(seq, full, summary)| item(seq.to_string(), full.clone(), summary.clone(), Some(format!("[result #{seq}; room r; operation code/read; output handle: tool/output {seq:0>16} — collapsed; {}]", "p".repeat(80))))) .collect() } fn fold(&self, folded: &[Item]) -> Option {