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
115 changes: 92 additions & 23 deletions core/airc-test-fixtures/src/two_airc_loopback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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<Self, LoopbackError> {
let peer_a_home = tempfile::TempDir::new()?;
let peer_b_home = tempfile::TempDir::new()?;
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -230,62 +244,117 @@ 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() {
let loop_back = TwoAircLoopback::new()
.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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ContextMessage> {
let message = ContextMessage::user(text);
Item { key, full: message.clone(), summary: None, pointer: Some(message), stored: None }
Expand All @@ -26,7 +25,7 @@ impl Source<ContextMessage> for OpenViews<'_> {
}

fn priority(&self) -> u8 {
priority::NOTICES
priority::ACTIONS
}

fn required(&self) -> bool {
Expand All @@ -39,7 +38,13 @@ impl Source<ContextMessage> 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
}

Expand Down
47 changes: 21 additions & 26 deletions core/continuum-cognition/src/cognition/open_views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,16 @@ pub struct OpenView {
/// checkout; `None` = her own workspace.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
/// 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<String>,
}

/// 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.
Expand Down Expand Up @@ -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::<Vec<_>>().join(" ");
if note.is_empty() {
Expand All @@ -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):
Expand All @@ -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);
}
Expand All @@ -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),
Expand Down Expand Up @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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<crate::cognition::context_streams::ContextMessage>| {
view.render().map(|m| m.text.clone()).collect::<Vec<_>>().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");
}
Loading