Skip to content
Merged
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
2 changes: 2 additions & 0 deletions core/continuum-cognition/src/cognition/act_observe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ pub mod test_support {
// predicates — they read `acts`, never re-parse the string).
pub fn receipt(acts: Vec<Observation>) -> WmEntry {
WmEntry {
occurrence: 0,
disk_change: Default::default(),
native_calls: Vec::new(),
kind: WmKind::Receipt { n: 1 },
Expand All @@ -261,6 +262,7 @@ pub mod test_support {

pub fn settle() -> WmEntry {
WmEntry {
occurrence: 0,
disk_change: Default::default(),
native_calls: Vec::new(),
kind: WmKind::Settlement,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ mod tests {
)])]));
assert!(!any_real_receipt(&[settle()]));
let facty = WmEntry {
occurrence: 0,
disk_change: Default::default(),
native_calls: Vec::new(),
kind: WmKind::Fact,
Expand Down
20 changes: 20 additions & 0 deletions core/continuum-cognition/src/cognition/context_streams/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,23 @@ fn her_folded_acts_name_their_range_and_count_in_one_line() {
assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts folded; reopen one with tool/output act=<n>]");
assert!(actions.fold(&[item("banner")]).is_none(), "a run that is not acts names nothing");
}

// what this catches: a repeated settlement collapsing into the earlier one because thoughts were
// keyed by their text: she settled passed, failed, passed and her view read passed once and
// failed once, so her latest state looked like "failed" (found porting e731576c, 2026-10-31).
// Each settlement is its own occurrence, in order.
#[test]
fn a_repeated_settlement_reaches_her_view_as_its_own_occurrence() {
use continuum_context::view::{Claim, View};
let memory = WorkingMemory::new(8);
let thoughts = super::thoughts::Thoughts { 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(), &[&thoughts as &dyn Source<_>], whole).unwrap(); // unwrap: one grant per claim cannot mismatch
for state in ["passed", "failed", "passed"] {
memory.record_settlement(&format!("all regression tests {state}"), None);
view.advance(&[&thoughts as &dyn Source<_>]);
}
let text = view.render().map(|m: &super::ContextMessage| m.text.clone()).collect::<Vec<_>>().join("\n");
assert_eq!(text.matches("tests passed").count(), 2, "{text}");
assert!(text.rfind("tests passed") > text.rfind("tests failed"), "her latest settlement reads last: {text}");
}
31 changes: 15 additions & 16 deletions core/continuum-cognition/src/cognition/context_streams/thoughts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ use continuum_context::cause::{Cause, Origin};
use continuum_context::source::{Item, Source};

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.
const POINTER_KEEP: usize = 200;
use crate::cognition::working_memory::{render_dispatched, WmKind, WorkingMemory};

pub(crate) struct Thoughts<'a> {
pub memory: &'a WorkingMemory,
Expand All @@ -26,12 +23,12 @@ impl Source<ContextMessage> for Thoughts<'_> {
}

fn items(&self) -> Vec<Item<ContextMessage>> {
let thoughts: Vec<String> = self
let thoughts: Vec<(u64, String)> = self
.memory
.recent_entries()
.into_iter()
.filter(|entry| matches!(entry.kind, WmKind::Thought | WmKind::Settlement))
.map(|entry| entry.text)
.map(|entry| (entry.occurrence, entry.text))
.collect();
let dispatched = render_dispatched(&self.memory.dispatched_snapshot());
if thoughts.is_empty() && dispatched.is_none() {
Expand All @@ -45,17 +42,19 @@ impl Source<ContextMessage> for Thoughts<'_> {
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());
items.extend(thoughts.into_iter().map(|(occurrence, text)| {
// Keyed by its occurrence, never by what it says: a settlement that repeats an
// earlier one ("passed" after "failed" after "passed") is its own item, so her latest
// state reads right (it collapsed into the first and read as "failed"). A thought,
// once recorded, does not change, and neither may its rendering: whole, its summary
// from the codec (`levels`), and how much of her thoughts she reads is the one
// allocation's call at an epoch start, never a per-act cut here (Benchy on the M5,
// 2026-10-24: a share-of-window cut re-appended every thought on every act).
let id = element(self.persona, Producer::Thought, &occurrence.to_be_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::whole(id, cause, text.clone(), ContextMessage::user(format!("- {text}")))
.with_pointer(ContextMessage::user(format!("- {}", collapse_thought(&text, POINTER_KEEP))))
let summary = continuum_context::levels::summarize(&text, continuum_context::levels::Shape::Output)
.map(|summary| ContextMessage::user(format!("- {summary}")));
Item::whole(id, cause, format!("thought#{occurrence}"), ContextMessage::user(format!("- {text}"))).with_summary(summary)
}));
// Fresh each event, newest last; one item, so a status change appends one line set.
items.extend(dispatched.map(|text| {
Expand Down
32 changes: 12 additions & 20 deletions core/continuum-cognition/src/cognition/working_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,26 +87,6 @@ use crate::cognition::act_observe::Observation;
pub(crate) type ContextView =
continuum_context::view::View<crate::cognition::context_streams::ContextMessage>;

/// Clip a full action-result body to [`WM_ACTION_FULL_MAX_CHARS`] for prompt inclusion.
/// Returns the body unchanged when it fits; otherwise a `char`-boundary-safe head plus
/// a marker naming exactly how many chars were dropped and how to see them (re-run the
/// tool with a narrower scope). One place so the render site and its test agree.
/// One of her earlier thoughts, collapsed to `keep` chars for the trail: the END is
/// kept, because that is where a thought's decision lives. Kimi, 2026-10-04, asked
/// which end she needs: "keep the end. The beginning is cheap: six acts I can redo
/// against the board. The ending is expensive when lost: drop it and I'm tempted back
/// down paths I already closed." Measured in her rooms the same day: 69 of her last
/// 89 thoughts OPENED with re-orientation ("Let me organize my state as Kimi") and
/// ENDED with what she decided, and the head clip kept exactly the re-orientation.
/// The full text stays in the entry; only this render is bounded.
pub fn collapse_thought(text: &str, keep: usize) -> String {
let total = text.chars().count();
if total <= keep {
return text.to_string();
}
let tail: String = text.chars().skip(total - keep).collect();
format!("[{} earlier chars — my full thought, collapsed] …{tail}", total - keep)
}


/// Borrowed provenance already carried by the result ring. Displaying a result
Expand Down Expand Up @@ -232,6 +212,9 @@ pub struct WorkingMemory {
/// the deliberation guard still trims the assembled prompt to the real `n_ctx`, so an
/// unknown window must never be replaced with an invented one.
entries: Mutex<VecDeque<WmEntry>>,
/// The next entry occurrence (`WmEntry::occurrence`): one sequence for every entry, kept in
/// the checkpoint so a restore and the next append never share one.
next_entry_seq: AtomicU64,
/// The acting root her receipts are stamped with (set at the work-turn
/// rooting seam, cleared on restore). See [`WmEntry::scope`].
scope: Mutex<Option<String>>,
Expand Down Expand Up @@ -589,6 +572,15 @@ pub(crate) fn reachable_handles(
pub struct WmEntry {
pub kind: WmKind,
pub text: String,
/// This entry's occurrence, stamped once by the one owner of entry identity
/// (`WorkingMemory::push_entry`, from `next_entry_seq`): two entries that say the same
/// thing are two occurrences, so a settlement that repeats an earlier one is its own item
/// in her view (passed, failed, passed reads as passed). Never a content hash. Never in a
/// checkpoint: an occurrence names an item within one life's view, a restart begins a new
/// epoch that re-renders every item, and restore numbers each entry it brings back from
/// the same counter, so the checkpoint's shape does not change.
#[serde(skip)]
pub occurrence: u64,
#[serde(default)]
pub acts: Vec<Observation>,
/// Original offered tool dialect, before execution normalization. Kept with
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,17 +142,15 @@ impl WorkingMemory {
return;
}
let mut e = self.entries.lock();
e.push_back(WmEntry {
self.push_entry(&mut e, WmEntry {
disk_change: Default::default(),
kind: WmKind::Fact,
text: f.to_string(),
acts: Vec::new(),
native_calls: Vec::new(),
scope: None,
occurrence: 0,
});
while e.len() > self.capacity {
e.pop_front();
}
}

/// Snapshot the volatile tier for PAUSE/RESUME across deploy reboots — the
Expand Down Expand Up @@ -271,10 +269,20 @@ impl WorkingMemory {
// "restored from a checkpoint saved under a minute ago … rebuilt 480243761 →
// 374144c34" on every turn for five hours. The notices are pinned for two
// turns below; any that a snapshot still carries are dropped here.
e.extend(snap.entries.into_iter().filter(|w| {
!(w.kind == WmKind::Fact
&& (w.text.starts_with("[resumed]") || w.text.starts_with("[rebuilt]")))
}));
// Each restored entry takes its occurrence from the one counter as it arrives
// (`WmEntry::occurrence` is never checkpointed), so no two entries share one.
e.extend(
snap.entries
.into_iter()
.filter(|w| {
!(w.kind == WmKind::Fact
&& (w.text.starts_with("[resumed]") || w.text.starts_with("[rebuilt]")))
})
.map(|mut w| {
w.occurrence = self.next_entry_seq.fetch_add(1, Ordering::Relaxed);
w
}),
);
while e.len() > self.capacity {
e.pop_front();
}
Expand Down
29 changes: 17 additions & 12 deletions core/continuum-cognition/src/cognition/working_memory/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,15 @@ impl WorkingMemory {
}
let scope = self.scope.lock().clone();
let mut entries = self.entries.lock();
entries.push_back(WmEntry {
self.push_entry(&mut entries, WmEntry {
disk_change: Default::default(),
kind: WmKind::ActionStatement { room },
text: text.to_owned(),
acts: Vec::new(),
native_calls: calls.to_vec(),
scope,
occurrence: 0,
});
while entries.len() > self.capacity {
entries.pop_front();
}
}

/// The latest authored decision in this exact activity/root, until settlement.
Expand Down Expand Up @@ -56,6 +54,7 @@ impl WorkingMemory {
ended_pins: Mutex::new(Vec::new()),
restored_acting_card: Mutex::new(None),
entries: Mutex::new(VecDeque::new()),
next_entry_seq: AtomicU64::new(1),
scope: Mutex::new(None),
pending_emissions: Mutex::new(Vec::new()),
last_action: Mutex::new(None),
Expand Down Expand Up @@ -168,23 +167,31 @@ impl WorkingMemory {

/// Record the reasoning the persona just produced. Blank/empty is ignored
/// (suppressed-thinking turns record nothing). Oldest ages out past capacity.
/// Record `entry` in her ring: stamped with the next occurrence (the one owner of entry
/// identity), the oldest leaving past capacity.
pub(super) fn push_entry(&self, entries: &mut VecDeque<WmEntry>, mut entry: WmEntry) {
entry.occurrence = self.next_entry_seq.fetch_add(1, Ordering::Relaxed);
entries.push_back(entry);
while entries.len() > self.capacity {
entries.pop_front();
}
}

pub fn record(&self, reasoning: &str) {
let r = reasoning.trim();
if r.is_empty() {
return;
}
let mut e = self.entries.lock();
e.push_back(WmEntry {
self.push_entry(&mut e, WmEntry {
disk_change: Default::default(),
kind: WmKind::Thought,
text: r.to_string(),
acts: Vec::new(),
native_calls: Vec::new(),
scope: None,
occurrence: 0,
});
while e.len() > self.capacity {
e.pop_front();
}
}

/// Record an ACTION the persona's hands just took (a tool call + its result
Expand Down Expand Up @@ -336,17 +343,15 @@ impl WorkingMemory {
let native_calls = e.iter_mut().rev()
.find(|entry| entry.scope == scope && matches!(entry.kind, WmKind::ActionStatement { room: r } if Some(r) == room))
.map(|entry| std::mem::take(&mut entry.native_calls)).unwrap_or_default();
e.push_back(WmEntry {
self.push_entry(&mut e, WmEntry {
disk_change,
kind: WmKind::Receipt { n: seq },
text,
acts,
native_calls,
scope,
occurrence: 0,
});
while e.len() > self.capacity {
e.pop_front();
}
drop(e);
// After BOTH the ring and the entry carrying this batch's acts: the set published
// here names the receipt's handle and each call's, which is what lets the act seam
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ impl WorkingMemory {
entry.scope != scope
|| !matches!(entry.kind, WmKind::ActionStatement { room: authored_room } if Some(authored_room) == room)
});
e.push_back(WmEntry {
self.push_entry(&mut e, WmEntry {
disk_change: Default::default(),
kind: WmKind::Settlement,
text: if a.is_empty() {
Expand All @@ -450,10 +450,8 @@ impl WorkingMemory {
scope: None,
acts: Vec::new(),
native_calls: Vec::new(),
occurrence: 0,
});
while e.len() > self.capacity {
e.pop_front();
}
drop(e);
// Settling closes over the current act→observe loop: the most recent action's
// FULL result has done its "what next" job. Advance the active boundary PAST it
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,6 @@
#![cfg(test)]
use super::*;

// what this catches: her collapsed thought keeping the re-orientation and losing
// the decision (Kimi, 2026-10-04: "keep the end"). The decision survives, the
// marker still names the collapse for the framing-echo detector, short thoughts
// are untouched.

#[test]
fn a_collapsed_thought_keeps_its_end() {
let thought = format!("Let me organize my state as Kimi. {} Decision: re-claim after the core redeploys.", "x".repeat(400));
let shown = collapse_thought(&thought, 60);
assert!(shown.ends_with("Decision: re-claim after the core redeploys."), "{shown}");
assert!(!shown.contains("Let me organize"), "the re-orientation is what collapses");
assert!(shown.contains(crate::cognition::framing_echo::COLLAPSE_MARKER));
assert_eq!(collapse_thought("short", 60), "short");
}

// what this catches: a receipt made while rooted at one card's checkout
// leaking into perception while she stands at another (the 9/5 "my context
// is confused" opener), and coming back when she returns.
Expand Down Expand Up @@ -408,3 +393,25 @@ fn a_restore_prices_a_legacy_evicted_result_from_its_saved_output() {
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");
}

// what this catches: two entries sharing an occurrence after a restore (Codex on card 4ee623ad).
// An occurrence is never checkpointed, so the checkpoint's shape is unchanged; restore numbers
// every entry it brings back from the one counter, and the next append is distinct and newest.
#[test]
fn restored_and_appended_entries_never_share_an_occurrence() {
let wm = WorkingMemory::new(8);
wm.record_settlement("first", None);
wm.record_settlement("second", None);
let saved = serde_json::to_value(wm.snapshot()).expect("test: a snapshot serializes");
assert!(!saved.to_string().contains("occurrence"), "no occurrence in the checkpoint: {saved}");
let restored = WorkingMemory::new(8);
restored.restore(serde_json::from_value(saved).expect("test: the checkpoint loads"));
restored.record_settlement("after the restore", None);
let occurrences: Vec<u64> = restored.recent_entries().iter().map(|entry| entry.occurrence).collect();
let mut distinct = occurrences.clone();
distinct.sort_unstable();
distinct.dedup();
assert_eq!(distinct.len(), occurrences.len(), "every occurrence distinct: {occurrences:?}");
assert!(occurrences.iter().all(|&o| o > 0), "none left unstamped: {occurrences:?}");
assert_eq!(occurrences.last(), distinct.last(), "the append is the newest: {occurrences:?}");
}
Loading