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
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions core/continuum-base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ description = "The floor of the core: leaf utilities every other crate may depen

[dependencies]
chrono.workspace = true
serde = { workspace = true }
dirs = "5.0"
tracing.workspace = true
uuid.workspace = true
Expand Down
1 change: 1 addition & 0 deletions core/continuum-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ pub mod secrets;
pub mod shell_portable;
pub mod time;
pub mod token_estimate;
pub mod tool_effect;
58 changes: 58 additions & 0 deletions core/continuum-base/src/tool_effect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//! What a command declares its calls do to the world. Declared once, by the command itself
//! (`CommandSpec::EFFECT` in the kernel), and read by the view's repeat rule (MIND-CONTEXT
//! invariant 4, `continuum-context`). It lives on the floor because both reach it and neither may
//! import the other: the kernel never imports a mind crate, and the view stays a leaf.

/// The effect a command declares. Never inferred from a name, an output or a body: a command that
/// has not declared is `Undeclared`, which authorizes nothing (Codex).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ToolEffect {
/// It only observes: two calls with one fingerprint and one outcome hash saw the same thing,
/// so the later one is "outcome unchanged".
Observes,
/// It changes the world: every call is its own effect, never a repeat, however alike its
/// output (two appends that both answer "OK" made two appends). A command that reads and
/// writes is `Changes`.
Changes,
/// It reopens a whole she asked to see again (`tool/output`): always whole, never a repeat,
/// because she reopens exactly what her view no longer holds.
Reopens,
/// The command declares none of these: never a repeat and never taken as observing; nothing
/// is suppressed, and the replay validator counts these so missing declarations are visible.
Undeclared,
}

impl ToolEffect {
/// The effect of an act that made several calls: any change makes it a change; otherwise any
/// undeclared call leaves it undeclared; otherwise any reopen makes it a reopen; only an act
/// whose every call observes observes. So one undeclared or changing call can never let the
/// act count as an unchanged observation.
pub fn of_calls(effects: impl IntoIterator<Item = ToolEffect>) -> Option<ToolEffect> {
effects.into_iter().reduce(|a, b| match (a, b) {
(ToolEffect::Changes, _) | (_, ToolEffect::Changes) => ToolEffect::Changes,
(ToolEffect::Undeclared, _) | (_, ToolEffect::Undeclared) => ToolEffect::Undeclared,
(ToolEffect::Reopens, _) | (_, ToolEffect::Reopens) => ToolEffect::Reopens,
(ToolEffect::Observes, ToolEffect::Observes) => ToolEffect::Observes,
})
}
}

#[cfg(test)]
mod tests {
use super::*;

// what this catches: an act whose calls mix effects counted as an observation (a read plus a
// write is a change; a read plus an undeclared call is undeclared), and an act of no calls
// given an effect at all.
#[test]
fn an_act_observes_only_when_every_call_observes() {
use ToolEffect::*;
assert_eq!(ToolEffect::of_calls([Observes, Observes]), Some(Observes));
assert_eq!(ToolEffect::of_calls([Observes, Changes]), Some(Changes));
assert_eq!(ToolEffect::of_calls([Undeclared, Changes]), Some(Changes));
assert_eq!(ToolEffect::of_calls([Observes, Undeclared]), Some(Undeclared));
assert_eq!(ToolEffect::of_calls([Reopens, Undeclared]), Some(Undeclared));
assert_eq!(ToolEffect::of_calls([Observes, Reopens]), Some(Reopens));
assert_eq!(ToolEffect::of_calls([]), None);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
//! epoch is measured there is none, and every read is whole. Each new epoch starts unmeasured,
//! so a page size that fell with her acts is tested whole again at every turnover.
//!
//! Only the DISPATCHED copy carries the budget. Her own calls, which repeat detection keys on
//! (`ToolCall::loop_fingerprint`), stay exactly as she made them.
//! Only the DISPATCHED copy carries the budget. Her own calls, which repeat identity is built
//! from (`ToolCall::canonical_input`), stay exactly as she made them.
//!
//! [`WorkingMemory::view_headroom`]: crate::cognition::working_memory::WorkingMemory::view_headroom

Expand Down
26 changes: 20 additions & 6 deletions core/continuum-cognition/src/cognition/context_streams/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,14 @@ impl Source<ContextMessage> for Actions<'_> {
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),
);
let item = 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.push(match act.act {
Some(identity) => item.with_act(identity),
None => item,
});
}
items
}
Expand Down Expand Up @@ -113,6 +115,18 @@ impl Source<ContextMessage> for Actions<'_> {
)))
}

/// An act the view found repeats an earlier one whose whole she has in front of her (the same
/// request to a command that only observes, the same outcome): one line naming it and how to
/// reopen it, never a second copy of the whole (MIND-CONTEXT invariant 4).
fn repeat(&self, item: &Item<ContextMessage>, ancestor: &Item<ContextMessage>) -> Option<ContextMessage> {
Some(ContextMessage::user(format!(
"[result #{}: repeat of #{}, outcome unchanged; reopen with tool/output act={}]",
item.key(),
ancestor.key(),
ancestor.key()
)))
}

/// Once she has acted, the void said earlier in this epoch is superseded, never edited:
/// her view reads as the timeline it is (the statement was true when it was made).
fn retired(&self) -> Vec<Item<ContextMessage>> {
Expand Down
38 changes: 38 additions & 0 deletions core/continuum-cognition/src/cognition/context_streams/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,41 @@ fn a_repeated_settlement_reaches_her_view_as_its_own_occurrence() {
assert_eq!(text.matches("tests passed").count(), 2, "{text}");
assert!(text.rfind("tests passed") > text.rfind("tests failed"), "her latest settlement reads last: {text}");
}

// what this catches: invariant 4 left unreachable from her real acts (a correct view rule no
// producer feeds). Two `read_file` calls of one path with one result, recorded the way the act
// seam records them, reach her view as the whole once and then "repeat of #1": the alias resolves
// to `code/read`, whose descriptor declares it observes. Two identical `code/write` calls, which
// declare no effect, both arrive whole (an undeclared effect authorizes nothing; Codex).
#[test]
fn her_unchanged_reread_reaches_her_view_as_a_repeat_and_an_undeclared_act_never_does() {
use crate::cognition::act_observe::test_support::act;
use continuum_context::view::{Claim, View};

let whole = |claims: &[Claim]| claims.iter().map(|claim| claim.full_chars).collect();
let body = "fn parse(&mut self) -> Result<Tree, Error> { self.step()?; }\n".repeat(40);
let memory = WorkingMemory::new(8);
let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() };
let (mut view, _) = View::start(Vec::new(), &[&actions as &dyn Source<_>], whole).unwrap(); // unwrap: one grant per claim cannot mismatch
let unsaved = || crate::ai::types::ResultCustody::Unsaved;
// Each act settles before the next, as her turn does: an act still in flight rides whole
// after her view, so it enters the actions stream once it is settled.
memory.record_receipt_typed(&[act("read_file", Some("src/parse.rs"))], &body, None, unsaved());
memory.record_settlement("read", None);
assert_eq!(view.advance(&[&actions as &dyn Source<_>]).repeats, 0);
memory.record_receipt_typed(&[act("read_file", Some("src/parse.rs"))], &body, None, unsaved());
memory.record_settlement("read again", None);
assert_eq!(view.advance(&[&actions as &dyn Source<_>]).repeats, 1);
let text = view.render().map(|m: &super::ContextMessage| m.text.clone()).collect::<Vec<_>>().join("\n");
assert_eq!(text.matches(body.as_str()).count(), 1, "the whole arrives once");
assert!(text.contains("repeat of #1, outcome unchanged; reopen with tool/output act=1]"), "{text}");

let memory = WorkingMemory::new(8);
let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() };
let (mut view, _) = View::start(Vec::new(), &[&actions as &dyn Source<_>], whole).unwrap(); // unwrap: one grant per claim cannot mismatch
for _ in 0..2 {
memory.record_receipt_typed(&[act("code/write", Some("src/parse.rs"))], "wrote 40 lines", None, unsaved());
memory.record_settlement("wrote", None);
assert_eq!(view.advance(&[&actions as &dyn Source<_>]).repeats, 0, "an undeclared act is never a repeat");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ pub(crate) struct ActionRecord {
/// result received since).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub received_ms: Option<u64>,
/// What the act asked for and what its commands declare they do (MIND-CONTEXT invariant 4):
/// the view renders an unchanged observation as a repeat from this. `None` for a record from
/// a build before it was kept, or a legacy text receipt: such an act is never a repeat.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub act: Option<continuum_context::cause::Act>,
}

impl ActionRecord {
Expand Down
17 changes: 17 additions & 0 deletions core/continuum-cognition/src/cognition/working_memory/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ impl WorkingMemory {
handle,
stored_chars: None,
received_ms: Some(continuum_base::time::EpochMs::now().millis()),
act: act_identity(&acts),
},
);
}
Expand Down Expand Up @@ -449,3 +450,19 @@ fn result_summary(result: &str, acts: &[Observation]) -> Option<String> {
}
}
}

/// An act's invariant-4 identity, from her calls as she made them (never the dispatched copy that
/// carries a page budget): each call resolved through the dispatch seam to the command that runs,
/// fingerprinted with its canonical arguments, and given that command's declared effect. `None`
/// for an act with no typed call.
fn act_identity(acts: &[crate::cognition::act_observe::Observation]) -> Option<continuum_context::cause::Act> {
let calls: Vec<(String, Vec<u8>)> = acts
.iter()
.map(|act| (crate::ai::tool_dialect::resolve_wire_name(&act.call.name), act.call.canonical_input()))
.collect();
let effect = continuum_base::tool_effect::ToolEffect::of_calls(
calls.iter().map(|(command, _)| crate::sdk_codegen::ext::effect_of(command)),
)?;
let fingerprint = continuum_context::cause::Fingerprint::of(calls.iter().map(|(command, input)| (command.as_str(), input.as_slice())));
Some(continuum_context::cause::Act { fingerprint, effect })
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub(crate) struct ActRendering {
/// 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,
/// What the act asked for and what its commands declare (`ActionRecord::act`).
pub act: Option<continuum_context::cause::Act>,
}

impl WorkingMemory {
Expand Down Expand Up @@ -275,7 +277,7 @@ impl WorkingMemory {
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 }
ActRendering { seq: record.seq, room: record.room, full, summary, pointer, stored, content, act: record.act }
})
.collect();
(renderings, in_flight)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ fn a_restored_handleless_receipt_keeps_its_children_under_its_new_handle() {
summary: None,
stored_chars: None,
received_ms: None,
act: None,
});
snapshot.receipt_children.insert(receipt_key(7, None), vec![child.clone()]);
let unsaved = snapshot.unsaved_receipts();
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-context/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ edition = "2021"
description = "A mind's model view as an epoch materialization: a stable head, then keyed items that only append; collapse happens once, at an epoch start, by the caller's one allocator (docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md)."

[dependencies]
continuum-base = { path = "../continuum-base" }
serde = { workspace = true }
sha2 = { workspace = true }

[dev-dependencies]
serde_json = { workspace = true }
# The replay validator fingerprints captured calls through the one canonical encoding the core
# uses (`ToolCall::canonical_input`), so offline and live repeat identity cannot drift.
continuum-tool-protocol = { path = "../continuum-tool-protocol" }

# The replay validator's tests run with the crate's (`cargo test -p continuum-context`).
[[example]]
Expand Down
9 changes: 9 additions & 0 deletions core/continuum-context/examples/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ struct Outcome {
fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order), keyed_turn: bool, admit: bool, trace: bool, share: usize) -> Result<Outcome, Box<dyn std::error::Error>> {
let mut restored = validate::Restored::default();
let (mut rereads, mut retained) = (0usize, 0usize);
let mut repeats = validate::Repeats::default();
let mut view: Option<View<String>> = None;
let mut previous_sent: Option<&str> = None;
let mut previous_head: Option<&str> = None;
Expand All @@ -389,6 +390,10 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order
let counted = restored.rereads(&cut.act, &previous_view);
rereads += counted.total;
retained += counted.held;
let identity = restored.repeats(&cut.act, &previous_view);
repeats.requests += identity.requests;
repeats.unchanged += identity.unchanged;
repeats.rendered += identity.rendered;
let mut sources: Vec<Captured> = cut
.sources
.iter()
Expand Down Expand Up @@ -481,6 +486,10 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order
let line: Vec<String> = appended.iter().map(|(name, chars)| format!("{name} {}", chars / acts)).collect();
println!(" appended per act by source: {}", line.join(", "));
println!(" her re-reads of a file read before: {rereads}, of which the prompt still held the earlier read whole or as its outline (a retention proxy): {retained}; acts whose result was ambiguous (not restored): {}", restored.ambiguous);
println!(
" invariant 4: reads asking an earlier read's exact request again {}, with the outcome unchanged {}, of which the view renders as a repeat (the earlier whole in her prompt) {}",
repeats.requests, repeats.unchanged, repeats.rendered
);
Ok(Outcome { turnovers, prefill_chars: view_prefill, rereads, retained, turnover_prefill })
}

Expand Down
Loading
Loading