From 631a49e540f34890b2cd7b9a0bd49a56a44ff84a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 12:09:33 -0500 Subject: [PATCH 1/2] fix(context): allocate open-view intent above its cursor floor --- .../cognition/context_streams/open_views.rs | 13 +++-- .../src/cognition/open_views.rs | 47 ++++++++--------- .../cognition/working_memory/perception.rs | 4 +- .../working_memory/tests/open_views.rs | 50 ++++++++++++++++--- 4 files changed, 76 insertions(+), 38 deletions(-) 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 2f6e4adf02..12bb6512e1 100644 --- a/core/continuum-cognition/src/cognition/context_streams/open_views.rs +++ b/core/continuum-cognition/src/cognition/context_streams/open_views.rs @@ -13,8 +13,7 @@ pub(crate) struct OpenViews<'a> { pub memory: &'a WorkingMemory, } -/// Required, as the block was: the history fit dropping it made her re-read from line 1 every -/// turn (Benchy, the M5, 2026-10-17), so collapsed it is still itself. +/// 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 } @@ -26,7 +25,7 @@ impl Source for OpenViews<'_> { } fn priority(&self) -> u8 { - priority::NOTICES + priority::ACTIONS } fn required(&self) -> bool { @@ -39,7 +38,13 @@ impl Source for OpenViews<'_> { return Vec::new(); } let mut items = vec![required("banner".to_owned(), Views::BANNER.to_owned())]; - items.extend(lines.into_iter().map(|(key, line)| required(key, format!("- {line}")))); + 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, + })); items } diff --git a/core/continuum-cognition/src/cognition/open_views.rs b/core/continuum-cognition/src/cognition/open_views.rs index 389fda856b..c2b93407cb 100644 --- a/core/continuum-cognition/src/cognition/open_views.rs +++ b/core/continuum-cognition/src/cognition/open_views.rs @@ -51,22 +51,16 @@ pub struct OpenView { /// checkout; `None` = her own workspace. #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option, - /// What she understood when she last read it, in her own words: the reasoning she stated - /// for that act. A view that says only "read 1-498 (all of it)" told her THAT she read a - /// file but not WHAT it said, so once the bytes left her window she read it again (Benchy, - /// the M5, 2026-10-18 05:01-05:03Z, `lib.rs` re-read whole with this very line in her - /// prompt). Her note carries the takeaway forward; the bytes stay a page away. + /// Intent stated before the read, not a conclusion drawn from its result. Offered only + /// in the whole representation; the shared context allocator decides its visibility. #[serde(default, skip_serializing_if = "Option::is_none")] pub note: Option, } -/// How many views a mind keeps open. A count of views is the size of this state, not a -/// context bound: each renders as one line (~150 chars), so eight cost ~300 tokens, under -/// 1% of the 34,560-token lane this was measured on and ~6% of a 5,000-token one. A card's -/// working set is a handful of files and the outputs that came back from building them; -/// the ninth view opened evicts the least recently touched one. -// derived-or-floor: a count of records in her own state (one rendered line each), never a -// token, a second or a rate; the per-line cost above is what it spends of a window +/// Storage retention in records, not a prompt budget. Cursor and intent costs are measured +/// separately by the shared context allocator. The ninth view evicts the least recently +/// touched record; this bound must never be used to estimate its rendered cost. +// derived-or-floor: a count of retained records in her own state, never prompt tokens const OPEN_VIEWS_KEPT: usize = 8; /// The open views of one mind, least recently touched first. @@ -228,11 +222,8 @@ impl OpenViews { } } - /// One compact block, one line per view visible from `scope`, ordered by what each view - /// is OF (never by recency), so a page read changes only its own line. `None` when no - /// view is open here. - /// Attach her stated reasoning to every view the acts of this receipt touched (the views - /// whose `touched_seq` is `seq`), clipped to `max_chars` (her window-relative echo budget). + /// Retain the intent preceding this receipt without applying a source-local budget. + /// Visibility of this detail belongs to the shared context allocation. pub fn annotate(&mut self, seq: u64, label: &str) -> bool { let note = label.split_whitespace().collect::>().join(" "); if note.is_empty() { @@ -254,12 +245,19 @@ impl OpenViews { start_line/end_line pages a file; tool/output with outputId and startLine/endLine \ pages an output:"; - /// Each view visible from `scope`: its stable key (its checkout and subject, so the same - /// relative path in two checkouts is two views) and its one line. - pub fn lines(&self, scope: Option<&str>) -> Vec<(String, String)> { + /// 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)> { 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| (view_key(view), render_line(view))).collect() + visible.into_iter().map(|view| { + let pointer = render_cursor(view); + let full = match &view.note { + Some(note) => format!("{pointer}; intent before this read: \"{note}\""), + None => pointer.clone(), + }; + (view_key(view), full, pointer) + }).collect() } /// The keys of views her hands cannot see from `scope` (they stand in another checkout): @@ -275,7 +273,7 @@ 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); } @@ -299,7 +297,7 @@ fn view_key(view: &OpenView) -> String { } } -fn render_line(view: &OpenView) -> String { +fn render_cursor(view: &OpenView) -> String { let mut line = match &view.subject { ViewSubject::File { path } => path.clone(), ViewSubject::Output { handle } => format!("output `{handle}` (from {})", view.label), @@ -327,9 +325,6 @@ fn render_line(view: &OpenView) -> String { if let (ViewSubject::File { .. }, Some(handle)) = (&view.subject, &view.handle) { line.push_str(&format!(" (that whole read is saved as output `{handle}`)")); } - if let Some(note) = &view.note { - line.push_str(&format!("; my note when I read it: \"{note}\"")); - } line } diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 73cf063c74..a448d7d36d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -209,9 +209,9 @@ impl WorkingMemory { self.open_views.lock().render(scope.as_deref()) } - /// Her open views visible from where her hands stand, one `(key, line)` each: the items of + /// 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)> { + pub(crate) fn open_view_lines(&self) -> Vec<(String, String, String)> { let scope = self.scope.lock().clone(); self.open_views.lock().lines(scope.as_deref()) } 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 4aa0ae6652..098174285f 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 @@ -57,18 +57,16 @@ fn record(wm: &WorkingMemory, act: Observation) { wm.record_receipt_typed(&[act], "[action] code/read", None, saved("open-view-receipt")); } -// what this catches: a view that says she read a file but not what it said, so once the -// bytes left her window she read it again (Benchy, the M5, 2026-10-18 05:01-05:03Z: -// `lib.rs` re-read whole with "read 1-498 (all of it)" in her prompt). Her stated -// reasoning for the read rides the view; a later read replaces it. +// Intent is retained as detail, but cannot truthfully be described as understanding of +// a result that had not arrived when the intent was written. #[test] -fn a_view_keeps_what_she_understood_when_she_read_it() { +fn a_view_keeps_pre_read_intent_without_claiming_it_is_understanding() { let wm = WorkingMemory::new(3); wm.set_served_window(46_848); record(&wm, read(1, 498, 498, None)); wm.annotate_open_views("each rule is a module with a predicate over SourceFile, registered in scan()"); let block = wm.open_views_block().expect("an open view renders"); - assert!(block.contains("my note when I read it: \"each rule is a module with a predicate over SourceFile, registered in scan()\""), "{block}"); + assert!(block.contains("intent before this read: \"each rule is a module with a predicate over SourceFile, registered in scan()\""), "{block}"); record(&wm, read(1, 80, 498, None)); wm.annotate_open_views("the Violation struct is the report shape"); let block = wm.open_views_block().expect("still open"); @@ -178,3 +176,43 @@ fn a_view_in_a_checkout_her_hands_left_is_retired_from_her_view() { let back = view.advance(&[&views as &dyn Source<_>]); assert_eq!(back.items, 1, "offered again when her hands return"); } + +// Capture57: eight cursor records carried 25,534 characters of copied pre-read intent +// as mandatory pointers. A larger note must increase demand, never the cursor floor. +// Exercise the actual source and epoch turnover; no per-source truncation or cap. +#[test] +fn planning_detail_yields_to_cursor_and_returns_when_granted() { + use continuum_context::source::Source; + use continuum_context::view::{claims, Claim, View}; + + let wm = WorkingMemory::new(3); + record(&wm, read(1, 498, 498, None)); + let source = crate::cognition::context_streams::open_views::OpenViews { memory: &wm }; + 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); + wm.annotate_open_views(&intent); + let demand = claims(sources); + assert_eq!(demand[0].floor_chars, cursor_floor, "intent is not mandatory input"); + assert!(demand[0].full_chars > cursor_floor + intent.len()); + let whole = |claims: &[Claim]| claims.iter().map(|c| c.full_chars).collect(); + let floor = |claims: &[Claim]| claims.iter().map(|c| c.floor_chars).collect(); + let (mut view, _) = View::start(Vec::new(), sources, whole).expect("matching grants"); + let text = |view: &View| { + view.render().map(|m| m.text.clone()).collect::>().join("\n") + }; + assert!(text(&view).contains(intent.trim())); + view.turn_over(Vec::new(), sources, floor).expect("matching grants"); + let reduced = text(&view); + assert!(reduced.contains(PATH) && reduced.contains("read 1-498 (all of it)"), "{reduced}"); + assert!(reduced.contains("code/read") && reduced.contains("start_line/end_line"), "retrieval remains resolvable: {reduced}"); + assert!(!reduced.contains("I need to inspect"), "pre-read planning must yield: {reduced}"); + assert_eq!(claims(sources), demand, "allocation does not rewrite stored wants"); + + // 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 }; + view.turn_over(Vec::new(), &[&restored_source], whole).expect("matching grants"); + assert!(text(&view).contains(intent.trim()), "the allocation never deleted the note"); +} From e6f6fe3483238954be4bfcb2fd5e034277779fb9 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 30 Oct 2026 12:40:45 -0500 Subject: [PATCH 2/2] Prove bilateral addressed readiness in shared loopback fixture --- .../src/two_airc_loopback.rs | 115 ++++++++++++++---- 1 file changed, 92 insertions(+), 23 deletions(-) diff --git a/core/airc-test-fixtures/src/two_airc_loopback.rs b/core/airc-test-fixtures/src/two_airc_loopback.rs index 854982764f..1b57a50ee6 100644 --- a/core/airc-test-fixtures/src/two_airc_loopback.rs +++ b/core/airc-test-fixtures/src/two_airc_loopback.rs @@ -58,6 +58,9 @@ use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; + +use airc_core::{Body, Headers, MentionTarget}; use airc_lib::Airc; use thiserror::Error; @@ -71,6 +74,7 @@ const FIXTURE_ROOM: &str = "two-airc-loopback"; /// Default bind address for peer_b's LAN listen. `:0` lets the kernel /// pick a free port so parallel test runs don't collide. const LOOPBACK_BIND: &str = "127.0.0.1:0"; +const READINESS_TIMEOUT: Duration = Duration::from_secs(5); /// Typed errors the fixture surfaces. Each variant names the specific /// piece that failed so a test failure points straight at the issue @@ -86,6 +90,12 @@ pub enum LoopbackError { /// add_peer, join, listen_lan, connect_lan). #[error("airc spawn: {0}")] AircSpawn(String), + + #[error("addressed readiness: {0}")] + Readiness(String), + + #[error("addressed readiness deadline elapsed")] + ReadinessDeadline, } /// Two `airc_lib::Airc` peers wired over a real LAN loopback. @@ -113,7 +123,9 @@ impl TwoAircLoopback { /// 4. wired a LAN transport (peer_b listens; peer_a connects) /// /// After this, `peer_a.request(MentionTarget::Peer(peer_b_id), ...)` - /// reaches peer_b's `subscribe()` stream, and vice versa. + /// reaches peer_b's addressed inbox, and vice versa. Setup proves an + /// authenticated round trip, so the addressed session is already warm. + /// Cold-handshake tests must construct their peers explicitly. pub async fn new() -> Result { let peer_a_home = tempfile::TempDir::new()?; let peer_b_home = tempfile::TempDir::new()?; @@ -187,6 +199,8 @@ impl TwoAircLoopback { )) })?; + prove_readiness(&peer_a, &peer_b).await?; + Ok(Self { peer_a: Arc::new(peer_a), peer_b: Arc::new(peer_b), @@ -230,16 +244,70 @@ impl TwoAircLoopback { } } +// A completed client connect installs only A's outbound channel. B installs its +// channel on the independent accept task. Receiving on B and replying to A is +// the causal barrier; neither a delay nor a successful client connect is one. +async fn prove_readiness(a: &Airc, b: &Airc) -> Result<(), LoopbackError> { + let deadline = tokio::time::Instant::now() + READINESS_TIMEOUT; + let exchange = async { + let mut inbox = b + .addressed_inbox(deadline) + .await + .map_err(|e| LoopbackError::Readiness(e.to_string()))?; + let mut headers = Headers::new(); + headers.insert("airc.command_kind".into(), "test.fixture.ready".into()); + let pending = a + .request( + MentionTarget::Peer(b.peer_id()), + headers, + Body::text("ready"), + READINESS_TIMEOUT, + ) + .await + .map_err(|e| LoopbackError::Readiness(e.to_string()))?; + let request = inbox + .next() + .await + .map_err(|e| LoopbackError::Readiness(e.to_string()))?; + if request.from() != a.peer_id() + || request.to() != b.peer_id() + || request.kind() != airc_lib::AddressedKind::Command + { + return Err(LoopbackError::Readiness( + "unexpected readiness request".into(), + )); + } + b.reply(&request, Headers::new(), Body::text("ready")) + .await + .map_err(|e| LoopbackError::Readiness(e.to_string()))?; + let reply = a + .await_reply(pending) + .await + .map_err(|e| LoopbackError::Readiness(e.to_string()))?; + if reply.from() != b.peer_id() + || reply.to() != a.peer_id() + || reply.kind() != airc_lib::AddressedKind::CommandResult + { + return Err(LoopbackError::Readiness( + "unexpected readiness reply".into(), + )); + } + Ok(()) + }; + tokio::time::timeout_at(deadline, exchange) + .await + .map_err(|_| LoopbackError::ReadinessDeadline)? +} + #[cfg(test)] mod tests { use super::*; - use std::time::Duration; use airc_core::{Body, Headers, MentionTarget, PeerId}; - /// Bare-airc roundtrip smoke: peer_a sends an addressed command to peer_b, - /// peer_b's addressed inbox receives it verified and replies bound to it, - /// peer_a's await_reply resolves. Proves the fixture's wire is alive + /// The listening peer B immediately sends to A after setup. A verifies + /// and replies; B awaits the correlated result. No sleep or retry can + /// conceal an incomplete listening-side connection. Proves the fixture's wire is alive /// end-to-end without any continuum-specific protocol on top. #[tokio::test] async fn bare_request_reply_round_trips_over_loopback() { @@ -247,45 +315,46 @@ mod tests { .await .expect("fixture setup should succeed"); - let peer_b_handle = Arc::clone(loop_back.peer_b()); - let peer_a_id = PeerId::from_uuid(loop_back.peer_a_id()); + let responder_handle = Arc::clone(loop_back.peer_a()); + let requester_id = PeerId::from_uuid(loop_back.peer_b_id()); + let mut inbox = responder_handle + .addressed_inbox(tokio::time::Instant::now() + Duration::from_secs(5)) + .await + .expect("peer_a addressed inbox"); let responder = tokio::spawn(async move { - let mut inbox = peer_b_handle - .addressed_inbox(tokio::time::Instant::now() + Duration::from_secs(5)) - .await - .expect("peer_b addressed inbox"); let request = inbox.next().await.expect("an addressed command arrives"); - assert_eq!(request.from(), peer_a_id, "verified sender"); - assert_eq!(request.to(), peer_b_handle.peer_id(), "addressed to peer_b"); + assert_eq!(request.from(), requester_id, "verified sender"); + assert_eq!( + request.to(), + responder_handle.peer_id(), + "addressed to peer_a" + ); assert_eq!(request.kind(), airc_lib::AddressedKind::Command); let mut reply_headers = Headers::new(); reply_headers.insert("test.reply".into(), "loopback.pong".into()); - peer_b_handle + responder_handle .reply(&request, reply_headers, Body::text("pong")) .await - .expect("peer_b reply"); + .expect("peer_a reply"); }); - // Give peer_b time to open its inbox before peer_a emits the request. - tokio::time::sleep(Duration::from_millis(50)).await; - let mut headers = Headers::new(); headers.insert("airc.command_kind".into(), "test.loopback.ping".into()); let pending = loop_back - .peer_a() + .peer_b() .request( - MentionTarget::Peer(PeerId::from_uuid(loop_back.peer_b_id())), + MentionTarget::Peer(PeerId::from_uuid(loop_back.peer_a_id())), headers, Body::text("ping"), Duration::from_secs(5), ) .await - .expect("peer_a request"); + .expect("peer_b request"); let reply = loop_back - .peer_a() + .peer_b() .await_reply(pending) .await - .expect("peer_a await_reply"); + .expect("peer_b await_reply"); // The body should be our pong. `Body::text("pong")` constructs // `Body::Json({"text": "pong"})` so we extract the `text` field.