diff --git a/Cargo.lock b/Cargo.lock index c6dc1d7367..1704172c5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2811,6 +2811,7 @@ version = "0.1.0" dependencies = [ "chrono", "dirs 5.0.1", + "serde", "tempfile", "tracing", "uuid", @@ -2978,6 +2979,8 @@ dependencies = [ name = "continuum-context" version = "0.1.0" dependencies = [ + "continuum-base", + "continuum-tool-protocol", "serde", "serde_json", "sha2", diff --git a/core/continuum-base/Cargo.toml b/core/continuum-base/Cargo.toml index 20aa600bf2..2dee1c65b4 100644 --- a/core/continuum-base/Cargo.toml +++ b/core/continuum-base/Cargo.toml @@ -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 diff --git a/core/continuum-base/src/lib.rs b/core/continuum-base/src/lib.rs index b12373c1a6..1820a98029 100644 --- a/core/continuum-base/src/lib.rs +++ b/core/continuum-base/src/lib.rs @@ -12,3 +12,4 @@ pub mod secrets; pub mod shell_portable; pub mod time; pub mod token_estimate; +pub mod tool_effect; diff --git a/core/continuum-base/src/tool_effect.rs b/core/continuum-base/src/tool_effect.rs new file mode 100644 index 0000000000..456723bce2 --- /dev/null +++ b/core/continuum-base/src/tool_effect.rs @@ -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) -> Option { + 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); + } +} diff --git a/core/continuum-cognition/src/cognition/act_observe/page_budget.rs b/core/continuum-cognition/src/cognition/act_observe/page_budget.rs index d67c08649b..e00da4e062 100644 --- a/core/continuum-cognition/src/cognition/act_observe/page_budget.rs +++ b/core/continuum-cognition/src/cognition/act_observe/page_budget.rs @@ -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 diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 980b235b73..02e5084c6e 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -76,12 +76,14 @@ impl Source 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 } @@ -113,6 +115,18 @@ impl Source 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, ancestor: &Item) -> Option { + 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> { diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index c426a6aa62..7785cd5df9 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -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 { 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::>().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"); + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index 759f25b8f1..6d64871507 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -65,6 +65,11 @@ pub(crate) struct ActionRecord { /// result received since). #[serde(default, skip_serializing_if = "Option::is_none")] pub received_ms: Option, + /// 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, } impl ActionRecord { diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index f827e38765..d86ec55d0f 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -321,6 +321,7 @@ impl WorkingMemory { handle, stored_chars: None, received_ms: Some(continuum_base::time::EpochMs::now().millis()), + act: act_identity(&acts), }, ); } @@ -449,3 +450,19 @@ fn result_summary(result: &str, acts: &[Observation]) -> Option { } } } + +/// 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 { + let calls: Vec<(String, Vec)> = 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 }) +} diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 92cec3e533..9754f12ee4 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -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, } impl WorkingMemory { @@ -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) 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 5aec0500b8..feb8065dd6 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -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(); diff --git a/core/continuum-context/Cargo.toml b/core/continuum-context/Cargo.toml index c3e4474d7d..b21a8999cb 100644 --- a/core/continuum-context/Cargo.toml +++ b/core/continuum-context/Cargo.toml @@ -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]] diff --git a/core/continuum-context/examples/replay.rs b/core/continuum-context/examples/replay.rs index 116483f2df..b1736ba58e 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -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> { let mut restored = validate::Restored::default(); let (mut rereads, mut retained) = (0usize, 0usize); + let mut repeats = validate::Repeats::default(); let mut view: Option> = None; let mut previous_sent: Option<&str> = None; let mut previous_head: Option<&str> = None; @@ -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 = cut .sources .iter() @@ -481,6 +486,10 @@ fn replay(label: &str, cuts: &[Cut], window: usize, (rule, placed): (Rule, Order let line: Vec = 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 }) } diff --git a/core/continuum-context/examples/replay/validate.rs b/core/continuum-context/examples/replay/validate.rs index fea4584591..d4e32a9804 100644 --- a/core/continuum-context/examples/replay/validate.rs +++ b/core/continuum-context/examples/replay/validate.rs @@ -13,6 +13,7 @@ use std::collections::{BTreeMap, HashSet}; +use continuum_context::cause::{ContentHash, Fingerprint}; use continuum_context::levels::{summarize, Shape}; use continuum_context::source::Item; @@ -27,6 +28,12 @@ pub struct Act { /// continues this one only when it is the very next cycle of the same session, so a skipped /// capture is a broken chain, never a result filed under the wrong action (Cormac on #5432). pub cycle: Option<(String, u64)>, + /// What the act asked for (MIND-CONTEXT invariant 4): its calls' fingerprint, through the + /// core's one canonical encoding. `None` for an act with no calls. + pub fingerprint: Option, + /// Every call is a read tool: the only acts whose unchanged outcome can be a repeat. Until the + /// commands declare their effect this is the validator's read list (`READ_TOOLS`). + pub observes: bool, } impl Act { @@ -60,6 +67,18 @@ pub fn act_of(request: &serde_json::Value) -> Act { let calls_of = |m: &serde_json::Value| -> Vec { parts(m).into_iter().filter(|p| p["type"] == "tool_use").collect() }; let calls = calls_of(messages[last_assistant]); let mut act = Act::default(); + if !calls.is_empty() { + let encoded: Vec<(String, Vec)> = calls + .iter() + .map(|call| { + let name = call["name"].as_str().unwrap_or_default().to_owned(); // unwrap_or_default: a nameless call fingerprints as its arguments alone + let canonical = continuum_tool_protocol::ToolCall { id: String::new(), name: name.clone(), input: call["input"].clone() }.canonical_input(); + (name, canonical) + }) + .collect(); + act.fingerprint = Some(Fingerprint::of(encoded.iter().map(|(name, input)| (name.as_str(), input.as_slice())))); + act.observes = calls.iter().all(|call| call["name"].as_str().is_some_and(|name| READ_TOOLS.contains(&name))); + } let mut answered = Vec::new(); for message in &messages[last_assistant + 1..] { for part in parts(message) { @@ -104,6 +123,22 @@ pub struct Restored { /// Acts whose result could not be tied to exactly one action: more than one new action /// key, or a capture missing between two (Codex on #5432). Counted, never restored. pub ambiguous: usize, + /// Each earlier observing act: its fingerprint, its result's hash and its result, for + /// invariant 4's repeat identity. + observed: Vec<(Fingerprint, ContentHash, String)>, +} + +/// One act's invariant-4 identity against the acts before it. +#[derive(Default, Clone, Copy)] +pub struct Repeats { + /// It asked an earlier observing act's exact request again (equal fingerprint). + pub requests: usize, + /// ...and got the same outcome (equal result hash): an unchanged observation. + pub unchanged: usize, + /// ...and that earlier whole was in the prompt she decided this act on: the view renders + /// this act as a repeat. An unchanged one whose earlier whole was not in her prompt arrives + /// whole, because she needs it again (Codex and Fable on the design). + pub rendered: usize, } /// One act's re-reads under a policy. @@ -162,6 +197,30 @@ impl Restored { } } + /// `act`'s invariant-4 identity against every earlier observing act, judged against `prompt`, + /// the prompt the act was decided on; then `act` joins the earlier acts. Counts only: no + /// text leaves this function (THE-PROVING-GROUND P9). + pub fn repeats(&mut self, act: &Act, prompt: &str) -> Repeats { + let mut counted = Repeats::default(); + let (Some(fingerprint), Some(result), true) = (act.fingerprint, act.result.as_deref(), act.observes) else { + return counted; + }; + let hash = ContentHash::of(result); + let asked: Vec<&(Fingerprint, ContentHash, String)> = self.observed.iter().filter(|(earlier, _, _)| *earlier == fingerprint).collect(); + if !asked.is_empty() { + counted.requests = 1; + } + let unchanged: Vec<&&(Fingerprint, ContentHash, String)> = asked.iter().filter(|(_, earlier, _)| *earlier == hash).collect(); + if !unchanged.is_empty() { + counted.unchanged = 1; + } + if unchanged.iter().any(|(_, _, whole)| prompt.contains(whole.as_str())) { + counted.rendered = 1; + } + self.observed.push((fingerprint, hash, result.to_owned())); + counted + } + /// The re-reads among `act`'s reads, judged against the prompt the act was decided on: held /// when that prompt still had the earlier read whole or as its outline. pub fn rereads(&self, act: &Act, prompt: &str) -> Rereads { @@ -215,7 +274,7 @@ mod tests { #[test] fn ambiguous_batches_and_gaps_are_counted_not_restored() { let mut restored = Restored::default(); - let act = |path: &str, cycle: u64| Act { result: Some(format!("{path} body")), reads: vec![path.to_owned()], cycle: Some(("s".into(), cycle)) }; + let act = |path: &str, cycle: u64| Act { result: Some(format!("{path} body")), reads: vec![path.to_owned()], cycle: Some(("s".into(), cycle)), ..Act::default() }; let keys = |n: u32| -> Vec { (1..=n).map(|k| k.to_string()).collect() }; restored.learn(&keys(1), &act("a.rs", 1)); restored.learn(&keys(2), &act("b.rs", 2)); @@ -230,4 +289,37 @@ mod tests { assert_eq!(restored.ambiguous, 3, "no new action is ambiguous"); assert!(["3", "4", "5"].iter().all(|k| !restored.by_seq.contains_key(*k))); } + + fn read(path: &str, result: &str) -> Act { + act_of(&request(serde_json::json!([ + {"role":"assistant","content":[{"type":"tool_use","id":"r","name":"read_file","input":{"file_path": path}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"r","content": result}]} + ]))) + } + + // what this catches: invariant 4's validator counting a repeat it would not render (the + // earlier whole was not in her prompt, so she needed it again), missing one it would (the + // 2026-10-30 read loop on the M5), or counting a changed outcome or a write as unchanged. + #[test] + fn a_repeat_is_counted_only_for_an_unchanged_read_whose_earlier_whole_she_had() { + let mut restored = Restored::default(); + let first = read("a.rs", "fn a() {}"); + assert_eq!(restored.repeats(&first, "").requests, 0); + let again = restored.repeats(&read("a.rs", "fn a() {}"), "earlier: fn a() {} still here"); + assert_eq!((again.requests, again.unchanged, again.rendered), (1, 1, 1)); + let folded = restored.repeats(&read("a.rs", "fn a() {}"), "[#1 collapsed]"); + assert_eq!((folded.requests, folded.unchanged, folded.rendered), (1, 1, 0), "not in her prompt: arrives whole"); + let changed = restored.repeats(&read("a.rs", "fn a() { 1 }"), "fn a() {}"); + assert_eq!((changed.requests, changed.unchanged, changed.rendered), (1, 0, 0)); + let write = act_of(&request(serde_json::json!([ + {"role":"assistant","content":[{"type":"tool_use","id":"w","name":"write_file","input":{"file_path":"a.rs"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"w","content":"fn a() {}"}]} + ]))); + assert_eq!(restored.repeats(&write, "fn a() {}").requests, 0, "a write is never a repeat"); + let keys_reordered = act_of(&request(serde_json::json!([ + {"role":"assistant","content":[{"type":"tool_use","id":"r","name":"read_file","input":{"path": "b.rs", "file_path": "a.rs"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"r","content":"x"}]} + ]))); + assert_ne!(keys_reordered.fingerprint, read("a.rs", "x").fingerprint, "every argument is part of the request"); + } } diff --git a/core/continuum-context/src/cause.rs b/core/continuum-context/src/cause.rs index 3f5268a250..66515aff3a 100644 --- a/core/continuum-context/src/cause.rs +++ b/core/continuum-context/src/cause.rs @@ -27,12 +27,7 @@ impl ElementId { /// so the boundary between parts is part of the identity: `["ab", "c"]` and `["a", "bc"]` are /// different occurrences (Cormac on #5611). pub fn of(identity: &[&[u8]]) -> Self { - let mut hasher = Sha256::new(); - for part in identity { - hasher.update((part.len() as u64).to_le_bytes()); - hasher.update(part); - } - let digest: [u8; 32] = hasher.finalize().into(); + let digest = length_prefixed_digest(identity.iter().copied()); let (head, _) = digest.split_at(std::mem::size_of::()); let mut bytes = [0u8; std::mem::size_of::()]; bytes.copy_from_slice(head); @@ -40,6 +35,45 @@ impl ElementId { } } +/// SHA-256 over parts, each prefixed by its length, so the boundary between parts is part of +/// what is hashed. The one derivation behind every identity built from parts here. +fn length_prefixed_digest<'a>(parts: impl IntoIterator) -> [u8; 32] { + let mut hasher = Sha256::new(); + for part in parts { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part); + } + hasher.finalize().into() +} + +/// What an act asked for (MIND-CONTEXT invariant 4): its calls in order, each the verb and its +/// arguments as the tool saw them (`ToolCall::canonical_input`). No argument is excluded here; +/// an exclusion is named only by the tool's own schema. Two acts with equal fingerprints asked +/// the same thing; whether the outcome was unchanged is the producer's evidence, never this. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Fingerprint([u8; 32]); + +impl Fingerprint { + /// The fingerprint of an act's calls, each `(verb, canonical arguments)`, in the order made. + pub fn of<'a>(calls: impl IntoIterator) -> Self { + Self(length_prefixed_digest( + calls.into_iter().flat_map(|(verb, arguments)| [verb.as_bytes(), arguments]), + )) + } +} + +/// What a command declares its calls do to the world: one type, on the floor, declared by each +/// command in the kernel's descriptor and read here. +pub use continuum_base::tool_effect::ToolEffect; + +/// What an act asked for and what its tool declares it does: the producer's half of invariant 4. +/// Whether its outcome was unchanged is decided by the view, from this and the item's content. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Act { + pub fingerprint: Fingerprint, + pub effect: ToolEffect, +} + /// What an element follows from. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Cause { @@ -101,6 +135,19 @@ mod tests { // what this catches: two different occurrences sharing an id because their identity parts // concatenate to the same bytes; every chain is keyed by the id (Cormac on #5611). + // what this catches: two acts that asked different things sharing a fingerprint because a + // verb's bytes ran into its arguments, or because the order of calls was dropped (invariant 4 + // would then call a new request a repeat). + #[test] + fn a_fingerprint_keeps_each_calls_verb_arguments_and_order() { + let read = Fingerprint::of([("code/read", br#"{"path":"a.rs"}"#.as_slice())]); + assert_eq!(read, Fingerprint::of([("code/read", br#"{"path":"a.rs"}"#.as_slice())])); + assert_ne!(read, Fingerprint::of([("code/search", br#"{"path":"a.rs"}"#.as_slice())])); + assert_ne!(read, Fingerprint::of([("code/rea", br#"d{"path":"a.rs"}"#.as_slice())])); + let (a, b) = (("code/read", b"1".as_slice()), ("code/search", b"2".as_slice())); + assert_ne!(Fingerprint::of([a, b]), Fingerprint::of([b, a])); + } + #[test] fn the_boundary_between_identity_parts_is_part_of_the_id() { assert_ne!(ElementId::of(&[b"ab", b"c"]), ElementId::of(&[b"a", b"bc"])); diff --git a/core/continuum-context/src/level.rs b/core/continuum-context/src/level.rs index b802fd3387..dfbf36a7c4 100644 --- a/core/continuum-context/src/level.rs +++ b/core/continuum-context/src/level.rs @@ -9,4 +9,9 @@ pub enum Level { Summary, Pointer, Folded, + /// An unchanged observation she already holds whole in this epoch, shown as its repeat block + /// ("repeat of #n, outcome unchanged", MIND-CONTEXT invariant 4). Never her whole: a receipt + /// reader asking whether a result was shown whole matches `Full` only. `of` is the occurrence + /// it repeats, the one she was shown whole. + Repeat { of: crate::cause::ElementId }, } diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index 3ae41e21a4..0b98f3d0a9 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -6,7 +6,7 @@ //! them. A source that cannot key its state (the clock, this act's ask) is not a source: //! it rides the fresh tail after the epoch. -use crate::cause::{Cause, Content, ContentHash, ElementId}; +use crate::cause::{Act, Cause, Content, ContentHash, ElementId}; use crate::epoch::Block; /// One item of a source's state, in both renderings the view may choose between. @@ -38,6 +38,9 @@ pub struct Item { /// what she can see (Cormac's proposal, FLOW plan §2d; the RAM storage budget is by bytes, /// from governed RAM, never from the window). pub(crate) stored: Option, + /// What this occurrence asked for and what its tool declares it does, when it is an act + /// (MIND-CONTEXT invariant 4); `None` for an element that is not one (a message, a notice). + pub(crate) act: Option, } /// Where a non-resident whole lives and what it costs, measured when it was stored. @@ -60,7 +63,7 @@ impl Item { /// cannot build an element without saying what it follows from. pub fn whole(id: ElementId, cause: Cause, key: impl Into, full: T) -> Self { let content = Content::Hashed(ContentHash::of(full.text())); - Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None } + Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None, act: None } } /// An occurrence whose `full` is a rendering of a whole held elsewhere (a result shown under @@ -68,7 +71,7 @@ impl Item { /// is held, so two equal outcomes compare equal whatever their labels say. `Absent` when the /// whole is not held. pub fn rendered(id: ElementId, cause: Cause, key: impl Into, full: T, content: Content) -> Self { - Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None } + Self { key: key.into(), id, cause, content, full, summary: None, pointer: None, stored: None, act: None } } /// Its pointer level: what it costs once collapsed, and how to reopen it. `None` when it @@ -90,6 +93,12 @@ impl Item { self } + /// It is an act: what it asked for and what its tool declares it does. + pub fn with_act(mut self, act: Act) -> Self { + self.act = Some(act); + self + } + pub fn key(&self) -> &str { &self.key } @@ -121,6 +130,10 @@ impl Item { pub fn stored(&self) -> Option<&StoredWhole> { self.stored.as_ref() } + + pub fn act(&self) -> Option { + self.act + } } /// A source of a mind's context. @@ -167,6 +180,15 @@ pub trait Source { fn fold(&self, _folded: &[Item]) -> Option { None } + + /// The block `item` renders as when the view finds it repeats `ancestor` (MIND-CONTEXT + /// invariant 4: the same request to a tool that only observes, with the same outcome). The + /// view decides; the source words it, naming the ancestor and how to reopen it even when the + /// ancestor is folded or paged out, never "as above". The default words none, so its items + /// always render as themselves. + fn repeat(&self, _item: &Item, _ancestor: &Item) -> Option { + None + } } /// What an item's whole level costs: its stored size when the whole is not resident, else diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index d3d47bf858..2386590bd1 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -19,6 +19,7 @@ use crate::motion::{fingerprint, Motion}; use crate::source::{Item, Source}; mod allot; +mod repeat; use allot::{allot, rank}; pub use crate::level::Level; @@ -61,6 +62,9 @@ impl std::error::Error for GrantMismatch {} pub struct Advance { pub items: usize, pub chars: usize, + /// Arrivals rendered as a repeat of an occurrence held whole (MIND-CONTEXT invariant 4): the + /// health line's repeats. + pub repeats: usize, } /// What an epoch start rendered: the one full re-prefill an epoch costs. @@ -110,6 +114,11 @@ pub struct View { /// until a start raises them. Absent in a view saved before folding. #[serde(default)] folded: HashSet, + /// Items rendered as a repeat of an occurrence held whole this epoch. A repeat shows its + /// content only by reference, so it is never a read of a whole ([`View::renders`]). Absent in + /// a view saved before repeats, which held none. + #[serde(default)] + repeats: HashSet, /// Characters each act of this epoch appended, in order. appended: Vec, /// How each source moved across this view's starts; carried over every turnover and @@ -239,6 +248,7 @@ impl View { collapsed: HashSet::new(), summarized: HashSet::new(), folded: HashSet::new(), + repeats: HashSet::new(), appended: Vec::new(), motion: Motion::default(), act: None, @@ -252,7 +262,8 @@ impl View { let element = item.id(); let item_key = item.key.clone(); // its fingerprint after the level consumed it; once per item per start let text = match level { - Level::Full => Some(crate::source::whole(&**source, item)), + // A start re-renders every item as itself: no repeat is allotted here. + Level::Full | Level::Repeat { .. } => Some(crate::source::whole(&**source, item)), Level::Summary => { view.summarized.insert(id.clone()); item.summary @@ -298,7 +309,17 @@ impl View { /// (her room cursor) only advances through what this answers true for. pub fn renders(&self, source: &str, item: &str) -> bool { let id = key(source, item); - self.epoch.holds(&id) && !self.collapsed.contains(&id) + self.epoch.holds(&id) && !self.collapsed.contains(&id) && !self.repeats.contains(&id) + } + + /// Whether `id` is held whole this epoch: rendered at its whole level, not collapsed, + /// summarized, folded or a repeat. What a repeat may point at. + fn holds_whole(&self, id: &SourceId) -> bool { + self.epoch.holds(id) + && !self.collapsed.contains(id) + && !self.summarized.contains(id) + && !self.folded.contains(id) + && !self.repeats.contains(id) } pub fn advance(&mut self, sources: &[&dyn Source]) -> Advance { @@ -344,8 +365,19 @@ impl View { fn append(&mut self, sources: &[&dyn Source], limit: Option<(usize, usize)>) -> Advance { let mut advance = Advance::default(); for source in sources { - for item in source.items() { + let name = source.name(); + let (items, repeats) = repeat::resolve( + &**source, + source.items(), + |earlier| self.holds_whole(&key(name, &earlier.key)), + |item| !self.epoch.holds(&key(name, &item.key)), + ); + for (item, repeat_of) in items.into_iter().zip(repeats) { let id = key(source.name(), &item.key); + let repeat = repeat_of.is_some(); + if repeat { + self.repeats.insert(id.clone()); + } // A folded item is held by its source's fold block, fixed at the start: it // arrives on its own only when a later start raises it (the prefix never moves). if self.folded.contains(&id) { @@ -369,9 +401,14 @@ impl View { self.collapsed.insert(id.clone()); Level::Pointer }; + // A repeat renders its block where its whole would go; the receipt says which. + let level = match (level, repeat_of) { + (Level::Full, Some(of)) => Level::Repeat { of }, + (level, _) => level, + }; let element = item.id(); let text = match level { - Level::Full => Some(crate::source::whole(&**source, item)), + Level::Full | Level::Repeat { .. } => Some(crate::source::whole(&**source, item)), Level::Summary => item.summary.or(item.pointer), Level::Pointer | Level::Folded => item.pointer, }; @@ -380,6 +417,7 @@ impl View { if let Observed::Appended { .. } = self.epoch.observe(id, Some(element), level, text) { advance.items += 1; advance.chars += chars; + advance.repeats += usize::from(repeat); } } } diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs index 42ac556d15..9d8f50e4a3 100644 --- a/core/continuum-context/src/view/allot.rs +++ b/core/continuum-context/src/view/allot.rs @@ -17,7 +17,7 @@ pub(super) fn rank(level: &Level) -> u8 { Level::Folded => 0, Level::Pointer => 1, Level::Summary => 2, - Level::Full => 3, + Level::Full | Level::Repeat { .. } => 3, } } diff --git a/core/continuum-context/src/view/repeat.rs b/core/continuum-context/src/view/repeat.rs new file mode 100644 index 0000000000..5f26af27f0 --- /dev/null +++ b/core/continuum-context/src/view/repeat.rs @@ -0,0 +1,104 @@ +//! MIND-CONTEXT invariant 4: a cycle cannot be presented as progress. +//! +//! An act that asks a tool which only observes for exactly what an earlier act in its chain asked +//! (equal [`Fingerprint`](crate::cause::Fingerprint)), and gets the same outcome (equal content +//! hash), arrives as its source's repeat block ("repeat of #n, outcome unchanged") instead of a +//! second copy of a whole she already has. It keeps its own id, order and cause, so nothing is +//! erased. The view decides here, once, for every source; the source only words it +//! ([`Source::repeat`]). This is perception, never a gate or an instruction. +//! +//! Only where the earlier whole is actually in front of her (Codex and Fable on the design): a +//! repeat is chosen for an act's first arrival in an epoch, and only when the occurrence it +//! repeats is held WHOLE in that epoch, so it was in the context she was sent. An ancestor that is +//! folded, collapsed, summarized or gone with a turnover gives no repeat: she needs the content +//! again and it arrives whole. A turnover re-renders every item as itself, and a reopen is never a +//! repeat ([`ToolEffect::Reopens`]). + +use std::collections::HashMap; + +use crate::cause::{Cause, Content, ContentHash, ElementId, Fingerprint, ToolEffect}; +use crate::epoch::Block; +use crate::source::{Item, Source}; + +/// `items` with each repeat replaced by its source's repeat block, and for each item the +/// occurrence it repeats (`None` when it is not one). `whole` answers whether an earlier item +/// is held whole in this epoch; `arriving` whether an item is arriving for the first time (an +/// item already rendered keeps its rendering for the epoch). The block is the item's whole and its +/// pointer, with no summary and nothing stored: it costs what it says at every level. +pub(super) fn resolve( + source: &(impl Source + ?Sized), + items: Vec>, + whole: impl Fn(&Item) -> bool, + arriving: impl Fn(&Item) -> bool, +) -> (Vec>, Vec>) { + let ancestors = ancestors(&items, &whole, &arriving); + let blocks: Vec> = items + .iter() + .zip(&ancestors) + .map(|(item, ancestor)| ancestor.and_then(|at| source.repeat(item, &items[at]))) + .collect(); + let repeated_of: Vec> = ancestors + .iter() + .zip(&blocks) + .map(|(ancestor, block)| block.as_ref().and(*ancestor).map(|at| items[at].id)) + .collect(); + let repeated = items + .into_iter() + .zip(blocks) + .map(|(mut item, block)| { + if let Some(block) = block { + item.pointer = Some(block.clone()); + item.full = block; + item.summary = None; + item.stored = None; + } + item + }) + .collect(); + (repeated, repeated_of) +} + +/// For each arriving act, the position of the occurrence it repeats: walking its `Cause::Of` chain +/// back through earlier items of this source, the nearest act with its fingerprint and content +/// hash whose whole is held. An ancestor that matches but is not whole (folded, collapsed, itself +/// a repeat) is passed over for an older one. Every step lands strictly before the previous one, +/// so a malformed chain (a cause cycle) ends the walk instead of looping. +fn ancestors( + items: &[Item], + whole: &impl Fn(&Item) -> bool, + arriving: &impl Fn(&Item) -> bool, +) -> Vec> { + let at: HashMap = + items.iter().enumerate().map(|(position, item)| (item.id, position)).collect(); + items + .iter() + .enumerate() + .map(|(position, item)| { + let identity = observed(item).filter(|_| arriving(item))?; + let mut cause = item.cause; + // Each step must land strictly before the last one visited, so a cycle among earlier + // causes (1 -> 2 -> 1) ends the walk instead of looping (Codex on #5652). + let mut bound = position; + while let Cause::Of(parent) = cause { + let earlier = at.get(&parent).copied().filter(|&earlier| earlier < bound)?; + let ancestor = &items[earlier]; + if observed(ancestor) == Some(identity) && whole(ancestor) { + return Some(earlier); + } + bound = earlier; + cause = ancestor.cause; + } + None + }) + .collect() +} + +/// An item's repeat identity, only for an act whose tool declares it observes and whose content is +/// hashed. Anything else is never a repeat and never repeated. +fn observed(item: &Item) -> Option<(Fingerprint, ContentHash)> { + let act = item.act?; + match (act.effect, item.content) { + (ToolEffect::Observes, Content::Hashed(hash)) => Some((act.fingerprint, hash)), + _ => None, + } +} diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 0915573e2f..cefc0e327f 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -91,7 +91,7 @@ fn an_act_appends_only_the_items_that_changed() { let (mut view, _) = View::start(vec![], &[&views], all_full).unwrap(); views.push("b.rs", "b.rs lines 1-40"); let advance = view.advance(&[&views]); - assert_eq!(advance, Advance { items: 1, chars: "b.rs lines 1-40".len() }); + assert_eq!(advance, Advance { items: 1, chars: "b.rs lines 1-40".len(), repeats: 0 }); assert_eq!(view.advance(&[&views]), Advance::default(), "nothing changed, nothing appended"); } @@ -107,7 +107,7 @@ fn a_collapsed_item_stays_collapsed_and_a_new_one_arrives_in_full() { let at_start = view.chars(); actions.push("#2", "short"); let advance = view.advance(&[&actions]); - assert_eq!(advance, Advance { items: 1, chars: "short".len() }, "only the new result, in full"); + assert_eq!(advance, Advance { items: 1, chars: "short".len(), repeats: 0 }, "only the new result, in full"); assert!(view.chars() - at_start < 100, "the old result did not come back in full"); } @@ -556,7 +556,7 @@ fn an_act_appends_one_result_and_neither_turns_over_nor_grows_the_floor() -> Res let (mut view, _) = View::start(Vec::new(), &[&actions], |_| vec![grant])?; let before = rendered(&view); actions.push(1_000); - assert_eq!(view.advance(&[&actions]), Advance { items: 1, chars: 1_000 }); + assert_eq!(view.advance(&[&actions]), Advance { items: 1, chars: 1_000, repeats: 0 }); assert!(rendered(&view).starts_with(&before), "the act rewrote the prefix"); assert_eq!(fold_blocks(&view), 1, "the fold block is not re-rendered mid-epoch"); assert_eq!(claims(&[&actions])[0].floor_chars, floor, "one more act, the same one-block floor"); @@ -592,3 +592,163 @@ fn the_receipt_names_each_shown_occurrence_and_its_level_in_prompt_order() -> Re assert_eq!(view.take_submitted(), None); Ok(()) } + +/// MIND-CONTEXT invariant 4: an unchanged observation arrives as a repeat only while the whole it +/// repeats is in front of her. +mod repeats { + use super::*; + use crate::cause::{Act, ContentHash, Fingerprint, ToolEffect}; + + /// Her acts as one chain, each caused by the one before; each act's content is its raw + /// output's hash, never its labelled rendering (two equal outputs compare equal). + struct Acts(Vec<(&'static str, &'static str, ToolEffect, String)>); + + impl Acts { + fn push(&mut self, verb: &'static str, args: &'static str, effect: ToolEffect, output: &str) { + self.0.push((verb, args, effect, output.to_owned())); + } + } + + impl Source for Acts { + fn name(&self) -> &str { + "acts" + } + fn priority(&self) -> u8 { + 5 + } + fn items(&self) -> Vec> { + let id = |seq: usize| ElementId::of(&[b"act", &seq.to_be_bytes()]); + self.0 + .iter() + .enumerate() + .map(|(i, (verb, args, effect, output))| { + let seq = i + 1; + let cause = if seq == 1 { Cause::Root(crate::cause::Origin::ActivityStart) } else { Cause::Of(id(seq - 1)) }; + let act = Act { fingerprint: Fingerprint::of([(*verb, args.as_bytes())]), effect: *effect }; + Item::rendered(id(seq), cause, seq.to_string(), format!("[#{seq} {verb}] {output}"), Content::Hashed(ContentHash::of(output))) + .with_pointer(format!("[#{seq} {verb}: collapsed; reopen with tool/output act={seq}]")) + .with_act(act) + }) + .collect() + } + fn repeat(&self, item: &Item, ancestor: &Item) -> Option { + Some(format!( + "[#{} repeat of #{}, outcome unchanged; reopen with tool/output act={}]", + item.key(), + ancestor.key(), + ancestor.key() + )) + } + } + + /// A file she reads whole: far larger than its collapsed pointer, as a real read is. + fn body(name: &str) -> String { + format!("// {name}\n") + &"fn parse(&mut self) -> Result { self.step()?; }\n".repeat(60) + } + + fn floors(claims: &[Claim]) -> Vec { + claims.iter().map(|claim| claim.floor_chars).collect() + } + + // what this catches: the M5 2026-10-30 read loop, the same unchanged file arriving whole + // again and again while the first copy is still in front of her: the second read arrives as + // a repeat naming #1, is counted, and never counts as reading a whole. + #[test] + fn an_unchanged_read_repeated_mid_epoch_arrives_as_a_repeat() { + let mut acts = Acts(Vec::new()); + let (mut view, _) = View::start(vec!["identity".into()], &[&acts], all_full).unwrap(); // unwrap: one grant per claim cannot mismatch + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + assert_eq!(view.advance(&[&acts]).repeats, 0); + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + let advance = view.advance(&[&acts]); + assert_eq!(advance.repeats, 1); + let text = rendered(&view); + assert_eq!(text.matches(&body("a.rs")).count(), 1, "the whole arrives once"); + assert!(text.contains("[#2 repeat of #1, outcome unchanged; reopen with tool/output act=1]"), "{text}"); + assert!(view.renders("acts", "1")); + assert!(!view.renders("acts", "2"), "a repeat is never a read of a whole"); + // The receipt says so too: #2 was shown as a repeat of #1, never at `Full` (a reader asking + // "was this result shown whole?" matches `Full` only). + let id = |seq: usize| ElementId::of(&[b"act", &seq.to_be_bytes()]); + let levels: Vec<_> = view.receipt().items.iter().filter(|r| r.element.is_some()).map(|r| (r.element, r.level)).collect(); + assert_eq!(levels, [(Some(id(1)), Level::Full), (Some(id(2)), Level::Repeat { of: id(1) })], "{levels:?}"); + } + + // what this catches (Codex on #5652): a cause cycle among earlier acts (1 -> 2 -> 1, a malformed + // chain) looping the ancestor walk forever when a later act arrives under it. Each step must land + // strictly before the last; the walk runs on a thread so a regression fails instead of hanging. + #[test] + fn a_cause_cycle_beneath_an_arrival_ends_the_walk() { + let (sent, got) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let id = |seq: usize| ElementId::of(&[b"act", &seq.to_be_bytes()]); + let read = |seq: usize, cause: Cause, output: &str| { + let act = Act { fingerprint: Fingerprint::of([("code/read", br#"{"path":"a.rs"}"#.as_slice())]), effect: ToolEffect::Observes }; + Item::rendered(id(seq), cause, seq.to_string(), output.to_owned(), Content::Hashed(ContentHash::of(output))).with_act(act) + }; + let items = vec![read(1, Cause::Of(id(2)), "one"), read(2, Cause::Of(id(1)), "two"), read(3, Cause::Of(id(2)), "three")]; + let (_, repeated_of) = super::super::repeat::resolve(&Acts(Vec::new()), items, |_| true, |_| true); + sent.send(repeated_of).ok(); + }); + let repeated_of = got.recv_timeout(std::time::Duration::from_secs(5)); + assert_eq!(repeated_of, Ok(vec![None, None, None]), "the walk ends at the cycle and finds no repeat"); + } + + // what this catches: the same output from a tool that changes the world read as "nothing + // happened" (Codex: two appends that both answer OK are two appends), and a tool that + // declares nothing, or a reopen, ever rendered as a repeat. + #[test] + fn only_a_declared_observation_can_repeat() { + for effect in [ToolEffect::Changes, ToolEffect::Reopens, ToolEffect::Undeclared] { + let mut acts = Acts(Vec::new()); + let (mut view, _) = View::start(vec!["identity".into()], &[&acts], all_full).unwrap(); // unwrap: one grant per claim cannot mismatch + acts.push("tool/x", r#"{"line":"a"}"#, effect, "OK"); + view.advance(&[&acts]); + acts.push("tool/x", r#"{"line":"a"}"#, effect, "OK"); + assert_eq!(view.advance(&[&acts]).repeats, 0, "{effect:?}"); + assert!(view.renders("acts", "1") && view.renders("acts", "2"), "{effect:?}: both occurrences whole"); + } + } + + // what this catches: a repeat pointing at a whole that is not in front of her (collapsed by + // the start, or gone with a turnover), whose reopen would answer another repeat and trap her + // (Codex and Fable on the design). The re-read arrives whole; and a turnover renders an + // earlier repeat as itself. + #[test] + fn a_repeat_needs_its_ancestor_whole_in_this_epoch() { + let mut acts = Acts(Vec::new()); + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + acts.push("code/read", r#"{"path":"b.rs"}"#, ToolEffect::Observes, &body("b.rs")); + let (mut view, start) = View::start(vec!["identity".into()], &[&acts], floors).unwrap(); // unwrap: one grant per claim cannot mismatch + assert_eq!(start.collapsed + start.folded, 2, "the start holds both at their floor"); + assert!(!view.renders("acts", "1")); + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + assert_eq!(view.advance(&[&acts]).repeats, 0, "#1 is collapsed: the re-read arrives whole"); + assert!(view.renders("acts", "3")); + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + assert_eq!(view.advance(&[&acts]).repeats, 1, "#3 is whole now: #4 repeats it"); + assert!(rendered(&view).contains("[#4 repeat of #3,")); + view.turn_over(vec!["identity".into()], &[&acts], all_full).unwrap(); // unwrap: one grant per claim cannot mismatch + let text = rendered(&view); + assert!(!text.contains("repeat of"), "a turnover re-renders every item as itself: {text}"); + assert!(view.renders("acts", "4")); + } + + // what this catches: an item already sent whole rewritten as a repeat on a later act, which + // changes text she was already sent and breaks the prefix every act appends to. Two equal + // reads arriving in one append both arrive whole (the first was not yet held), and the second + // keeps its whole rendering for the epoch. + #[test] + fn a_rendering_already_sent_is_never_turned_into_a_repeat() { + let mut acts = Acts(Vec::new()); + let (mut view, _) = View::start(vec!["identity".into()], &[&acts], all_full).unwrap(); // unwrap: one grant per claim cannot mismatch + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + acts.push("code/read", r#"{"path":"a.rs"}"#, ToolEffect::Observes, &body("a.rs")); + assert_eq!(view.advance(&[&acts]).repeats, 0); + let before = rendered(&view); + acts.push("code/read", r#"{"path":"b.rs"}"#, ToolEffect::Observes, &body("b.rs")); + let advance = view.advance(&[&acts]); + assert_eq!((advance.items, advance.repeats), (1, 0), "only the new read arrives"); + assert!(rendered(&view).starts_with(&before)); + } +} diff --git a/core/continuum-core/src/modules/ext_commands/manifest.rs b/core/continuum-core/src/modules/ext_commands/manifest.rs index 6bfd0cc854..36cb6d9fd8 100644 --- a/core/continuum-core/src/modules/ext_commands/manifest.rs +++ b/core/continuum-core/src/modules/ext_commands/manifest.rs @@ -334,6 +334,9 @@ impl DynCommand for ProcessCommand { wire: WireShape::Bare, native: self.manifest.native, aliases: &[], + // An authored command runs an arbitrary process and its manifest declares no + // effect: undeclared, so it is never a repeat and never taken as observing. + effect: continuum_base::tool_effect::ToolEffect::Undeclared, params: json.clone(), params_schema: self.manifest.params.clone(), result: json.clone(), diff --git a/core/continuum-hands/src/modules/code_commands/engine_err.rs b/core/continuum-hands/src/modules/code_commands/engine_err.rs index 6bc4002a64..e675e7d24d 100644 --- a/core/continuum-hands/src/modules/code_commands/engine_err.rs +++ b/core/continuum-hands/src/modules/code_commands/engine_err.rs @@ -274,6 +274,7 @@ pub struct CodeReadParams { #[async_trait] impl ActionCommand for CodeRead { const NAME: &'static str = "code/read"; + const EFFECT: continuum_base::tool_effect::ToolEffect = continuum_base::tool_effect::ToolEffect::Observes; const ALIASES: &'static [&'static str] = &["read_file", "view", "cat", "open_file"]; const NATIVE: bool = true; // core agentic working set — offered natively (auto-derived) const DESCRIPTION: &'static str = diff --git a/core/continuum-kernel/src/sdk_codegen/command.rs b/core/continuum-kernel/src/sdk_codegen/command.rs index 0a8193cbb9..e7488cca7c 100644 --- a/core/continuum-kernel/src/sdk_codegen/command.rs +++ b/core/continuum-kernel/src/sdk_codegen/command.rs @@ -341,6 +341,9 @@ pub trait ActionCommand: Send + Sync + Sized + 'static { /// generated inverse index ([`crate::ai::tool_dialect`]); a name two /// commands both claim is a build-time panic. Defaults to none. const ALIASES: &'static [&'static str] = &[]; + /// What this command's calls do to the world. See [`CommandSpec::EFFECT`]; defaults to + /// `Undeclared`. + const EFFECT: continuum_base::tool_effect::ToolEffect = continuum_base::tool_effect::ToolEffect::Undeclared; /// The typed request payload (a ts-rs wire type). `JsonSchema` so its schema /// is derived automatically (no hand-authoring) and exposed to every SDK. @@ -361,6 +364,7 @@ impl CommandSpec for T { const DESCRIPTION: &'static str = ::DESCRIPTION; const NATIVE: bool = ::NATIVE; const ALIASES: &'static [&'static str] = ::ALIASES; + const EFFECT: continuum_base::tool_effect::ToolEffect = ::EFFECT; const WIRE: WireShape = WireShape::Bare; type Params = ::Params; type Result = ::Output; diff --git a/core/continuum-kernel/src/sdk_codegen/ext.rs b/core/continuum-kernel/src/sdk_codegen/ext.rs index 7118a2b67f..078ac78d53 100644 --- a/core/continuum-kernel/src/sdk_codegen/ext.rs +++ b/core/continuum-kernel/src/sdk_codegen/ext.rs @@ -27,3 +27,18 @@ pub fn command_registry_live() -> Vec { all } + +/// What the command named `canonical` declares its calls do ([`super::CommandSpec::EFFECT`]), +/// for a name already resolved through the dispatch seam (`tool_dialect::resolve_wire_name`), +/// so the effect is the descriptor's of the command that runs, never read off what the model +/// typed. A name no command claims is `Undeclared`: it authorizes nothing. Built once from the +/// live catalogue, which is immutable after boot's one install. +pub fn effect_of(canonical: &str) -> continuum_base::tool_effect::ToolEffect { + static EFFECTS: std::sync::OnceLock> = + std::sync::OnceLock::new(); + let effects = EFFECTS.get_or_init(|| command_registry_live().iter().map(|d| (d.name, d.effect)).collect()); + match effects.get(canonical) { + Some(effect) => *effect, + None => continuum_base::tool_effect::ToolEffect::Undeclared, + } +} diff --git a/core/continuum-kernel/src/sdk_codegen/is.rs b/core/continuum-kernel/src/sdk_codegen/is.rs index e1d2fae887..34c44cd1c7 100644 --- a/core/continuum-kernel/src/sdk_codegen/is.rs +++ b/core/continuum-kernel/src/sdk_codegen/is.rs @@ -116,6 +116,11 @@ pub trait CommandSpec { /// by the command in its own file so it stays portable; aggregated into one /// generated inverse index. Defaults to none. const ALIASES: &'static [&'static str] = &[]; + /// What this command's calls do to the world (MIND-CONTEXT invariant 4): declared HERE, + /// by the command in its own file, never inferred from its name or output. Defaults to + /// `Undeclared`, which authorizes nothing: such a call is never a repeat and never taken as + /// observing, and the replay validator counts it. + const EFFECT: continuum_base::tool_effect::ToolEffect = continuum_base::tool_effect::ToolEffect::Undeclared; /// The handler's ACTUAL wire convention — decides whether the generated /// surface is enveloped or bare. MUST match what the handler really does /// (a mismatch is a type that lies about the wire). @@ -252,6 +257,9 @@ pub struct CommandDescriptor { /// (`ai::tool_dialect`) that maps a model's reflex name back to this /// command. Empty for most commands. pub aliases: &'static [&'static str], + /// What its calls do to the world (from [`CommandSpec::EFFECT`]): the effect an executed + /// call carries into her act, read from the command that actually ran. + pub effect: continuum_base::tool_effect::ToolEffect, pub params: TypeRef, /// The params' JSON Schema (from [`CommandSpec::params_schema`]) — the /// canonical input contract every SDK/interface adapts from. `Null` when the @@ -298,6 +306,7 @@ impl CommandDescriptor { wire: C::WIRE, native: C::NATIVE, aliases: C::ALIASES, + effect: C::EFFECT, params, params_schema: C::params_schema(), result, diff --git a/core/continuum-tool-protocol/src/lib.rs b/core/continuum-tool-protocol/src/lib.rs index 5a04ebce07..3ad88e8e1b 100644 --- a/core/continuum-tool-protocol/src/lib.rs +++ b/core/continuum-tool-protocol/src/lib.rs @@ -64,19 +64,48 @@ pub struct ToolCall { } impl ToolCall { - /// Stable identity of THIS call for loop / repeat detection: `name|json(input)`. - /// - /// The random per-call `id` is deliberately excluded — two calls with the same name - /// and arguments ARE the same action regardless of their generated ids. This is the - /// SINGLE source of the fingerprint that both the settle loop's stuck-batch signature - /// (`act_observe::settle::drive_to_settle`) and `apply_act`'s repeat guard key on; - /// two hand-inlined copies of this format drifting apart would silently break loop - /// detection, so they share this one method. - pub fn loop_fingerprint(&self) -> String { - format!( - "{}|{}", - self.name, - serde_json::to_string(&self.input).unwrap_or_default() - ) + /// The call's arguments as the tool saw them, in one canonical encoding: compact JSON with + /// every object's keys sorted, so two calls that ask the same thing encode to the same bytes + /// whatever order the model wrote their keys in. The random per-call `id` is not part of it. + /// This is the single source repeat identity is built from (MIND-CONTEXT invariant 4, + /// `continuum_context::cause::Fingerprint`). `Value`'s `Display` cannot fail, so no call falls + /// back to an empty encoding that would collide with every other; its keys come out sorted + /// because serde_json's map is ordered (without `preserve_order`, which the test below pins). + pub fn canonical_input(&self) -> Vec { + self.input.to_string().into_bytes() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(input: Value) -> ToolCall { + ToolCall { id: uuid::Uuid::new_v4().to_string(), name: "code/read".into(), input } + } + + // what this catches: one request encoding two ways (key order the model chose, a fresh call + // id), which would let a repeated read pass as new; and two different requests colliding. + #[test] + fn equal_requests_encode_equal_whatever_their_key_order_or_id() { + let a = call(serde_json::json!({"path": "a.rs", "range": {"start": 1, "end": 9}, "tags": ["x", 2, null, true]})); + // Built key by key in reverse order, so an insertion-ordered map (serde_json's + // `preserve_order`, if any dependency ever enables it) fails here instead of silently + // giving one request two identities. + let mut range = serde_json::Map::new(); + range.insert("end".into(), 9.into()); + range.insert("start".into(), 1.into()); + let mut reversed = serde_json::Map::new(); + reversed.insert("tags".into(), serde_json::json!(["x", 2, null, true])); + reversed.insert("range".into(), Value::Object(range)); + reversed.insert("path".into(), "a.rs".into()); + let b = call(Value::Object(reversed)); + assert_eq!(a.canonical_input(), b.canonical_input()); + assert_eq!( + a.canonical_input(), + br#"{"path":"a.rs","range":{"end":9,"start":1},"tags":["x",2,null,true]}"#.to_vec() + ); + assert_ne!(a.canonical_input(), call(serde_json::json!({"path": "b.rs"})).canonical_input()); + assert_ne!(call(serde_json::json!({"p": "a\"b"})).canonical_input(), call(serde_json::json!({"p": "a", "b": ""})).canonical_input()); } } diff --git a/core/continuum-tool-protocol/src/parser.rs b/core/continuum-tool-protocol/src/parser.rs index a225f3faee..cb5dbc048a 100644 --- a/core/continuum-tool-protocol/src/parser.rs +++ b/core/continuum-tool-protocol/src/parser.rs @@ -27,7 +27,7 @@ use crate::{NativeToolSpec, ToolCall}; mod resolve_name; pub use resolve_name::*; mod cli_flag_format; -pub use cli_flag_format::*; +use cli_flag_format::*; mod narrated_write_format; pub use narrated_write_format::*; diff --git a/core/continuum-tool-protocol/src/parser/tests/mod.rs b/core/continuum-tool-protocol/src/parser/tests/mod.rs index 6480cc77d0..a97520e849 100644 --- a/core/continuum-tool-protocol/src/parser/tests/mod.rs +++ b/core/continuum-tool-protocol/src/parser/tests/mod.rs @@ -731,6 +731,6 @@ Please provide the output so I can review it."; } mod part_2; -pub use part_2::*; + mod part_3; -pub use part_3::*; + diff --git a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md index d657bf89f1..5f39117450 100644 --- a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md +++ b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md @@ -403,8 +403,18 @@ reply edges. The view's `Item` gains the same link. argument is excluded by default; an exclusion is named only by the tool's own schema, never by the view. (Key plus cause cannot catch the loop: each re-read's result is caused by a new act. Cormac's review.) A new act whose fingerprint matches a prior act in its chain, and whose outcome content is - unchanged, is recorded as an edge back to that ancestor and renders as "repeat of #n, outcome - unchanged", never as a fresh element. + unchanged, renders as "repeat of #n, outcome unchanged", never as a fresh element, but only while + #n's whole is in front of her (Codex and Fable on the design, 2026-10-31): + - the view chooses it on the act's first arrival in an epoch, and only when #n is held whole in + that epoch (not folded, collapsed, summarized or itself a repeat). Otherwise she needs the + content again and it arrives whole, so a repeat never points at what her view lacks and her + reopen never answers another repeat; + - a turnover re-renders every item as itself; an explicit reopen (`tool/output`) is always whole; + - a repeat is never a read of a whole: it never discharges a whole-result obligation; + - the effect is the command's own declaration (`CommandSpec::EFFECT`: `Observes`, `Changes`, + `Reopens`, `Undeclared`), read from the descriptor of the command the call resolved to, never + from a name or an output. `Undeclared` authorizes nothing, and an act mixing effects takes the + strongest (a read plus a write is a change). - **Same output is not the same effect** (Codex). Two appends or sends can both return "OK" and still cause two effects. Every occurrence keeps its own id, order and side-effect receipt, and is never erased. Repeated content renders by reference to the earlier occurrence. "Outcome unchanged" is @@ -448,6 +458,11 @@ reply edges. The view's `Item` gains the same link. `continuum-context`, with every source supplying causes. Owner: Fable. 2. Invariant 4's fingerprint and its replay validator, which builds on the deferred-whole and fold code. Owner: Cormac. The validator replays the M5 2026-10-30 captures and must fire on the 8-reads-an-hour case. + Built (card dcf95bce): `cause::Fingerprint` over `ToolCall::canonical_input`; `ToolEffect` in + `continuum-base`, declared per command (`code/read`, `code/search` observe; `tool/output` reopens); + the view's repeat rule (`view/repeat.rs`) and `Source::repeat`; the replay's invariant-4 line + (`examples/replay/validate.rs`). On IntelMac's own captures it fires: 8 exact re-reads, 8 unchanged, + 6 rendered as repeats. The M5 run is Fable's. 3. Invariant 5 and the overflow rule, together with ONE-BUDGET slice 6's measured claims. Owner: Fable. Each step lands with its validator and a 15-minute live read.