From da5f136906e50c9efc8423a57b1c318a9a1b9a90 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 31 Oct 2026 03:07:33 -0500 Subject: [PATCH] Her repeated settlement reaches her view: thought and settlement entries carry an occurrence id (card 4ee623ad) A thought item was keyed by its text, so a settlement that repeated an earlier one (passed, failed, passed) collapsed into the first and read as failed. Every working-memory entry now takes an occurrence from ONE counter (WorkingMemory::next_entry_seq) through ONE push path (push_entry); the thoughts source ids an item by its occurrence (`thought#{n}`), and its summary comes from levels::summarize. POINTER_KEEP and collapse_thought are deleted. The checkpoint's shape does not change (Codex on #5641: no old-format reader): an occurrence names an item within one life's view, a restart begins a new epoch that re-renders every item, so WmEntry::occurrence is serde(skip) and restore numbers each entry it brings back from the same counter. No default handling, no stamp-zero path, no counter in the snapshot; card 0a7f5642 (delete the zero stamp after a re-save) is moot. Tests: a_repeated_settlement_reaches_her_view_as_its_own_occurrence; restored_and_appended_entries_never_share_an_occurrence (the checkpoint carries no occurrence; restored and appended entries are distinct, the append newest). Both mutation-proved. continuum-cognition --lib 946 pass on enrico 2026-10-31. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/cognition/act_observe/mod.rs | 2 + .../src/cognition/act_observe/perception.rs | 1 + .../src/cognition/context_streams/tests.rs | 20 ++++++++++ .../src/cognition/context_streams/thoughts.rs | 31 ++++++++-------- .../src/cognition/working_memory.rs | 32 ++++++---------- .../cognition/working_memory/continuity.rs | 24 ++++++++---- .../src/cognition/working_memory/ledger.rs | 29 +++++++++------ .../cognition/working_memory/perception.rs | 6 +-- .../cognition/working_memory/tests/custody.rs | 37 +++++++++++-------- 9 files changed, 107 insertions(+), 75 deletions(-) diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index 2f5652cc7e..ee035c8799 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -250,6 +250,7 @@ pub mod test_support { // predicates — they read `acts`, never re-parse the string). pub fn receipt(acts: Vec) -> WmEntry { WmEntry { + occurrence: 0, disk_change: Default::default(), native_calls: Vec::new(), kind: WmKind::Receipt { n: 1 }, @@ -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, diff --git a/core/continuum-cognition/src/cognition/act_observe/perception.rs b/core/continuum-cognition/src/cognition/act_observe/perception.rs index 7a334d3fc6..358b455342 100644 --- a/core/continuum-cognition/src/cognition/act_observe/perception.rs +++ b/core/continuum-cognition/src/cognition/act_observe/perception.rs @@ -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, diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index aa4e1bfb6b..c426a6aa62 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -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=]"); 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::>().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}"); +} diff --git a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs index a192dffee6..fedf687678 100644 --- a/core/continuum-cognition/src/cognition/context_streams/thoughts.rs +++ b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs @@ -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, @@ -26,12 +23,12 @@ impl Source for Thoughts<'_> { } fn items(&self) -> Vec> { - let thoughts: Vec = 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() { @@ -45,17 +42,19 @@ impl Source 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| { diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 3df55a262d..dde95a08cb 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -87,26 +87,6 @@ use crate::cognition::act_observe::Observation; pub(crate) type ContextView = continuum_context::view::View; -/// 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 @@ -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>, + /// 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>, @@ -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, /// Original offered tool dialect, before execution normalization. Kept with diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index e37fdbba32..4c747de704 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -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 @@ -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(); } diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index a6c4f54e54..f827e38765 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -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. @@ -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), @@ -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, 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 @@ -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 diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 8db4716ce0..92cec3e533 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -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() { @@ -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 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 6dba2bf0a5..5aec0500b8 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -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. @@ -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 = 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:?}"); +}