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
57 changes: 18 additions & 39 deletions core/continuum-cognition/src/cognition/act_observe/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,6 @@ pub async fn apply_act(
// Call history is not a cache-validity proof. Reads can change, failures can
// recover, and earlier results may no longer fit the prompt. Execute through
// the owning command; authorization and operation-specific idempotency stay there.
// EVERY re-injection bound in this act comes from her LIVE served window, never a
// constant — an unknown window folds NOTHING rather than inventing a number
// ([[never-hardcode-a-context-window-4k-defaults-destroy-the-moe-thesis]]).
// WM clips inside its OWN record path (it owns its truncation), so it needs the live
// window too — pushed from here, the seam that has the cycle. Re-pushed every act so a
// lane relaunch at a different `-c` is picked up without a restart.
if let Some((_, w)) = cycle.model_loadout() {
body.working_memory.set_served_window(w);
}
let ctx = crate::cognition::tool_executor::ToolExecutionContext {
persona_id: body.persona_id,
persona_name: body.persona_name.clone(),
Expand Down Expand Up @@ -398,14 +389,14 @@ pub async fn apply_act(
// handle and the executor decodes it once from the full value.
if verdict.running() {
if let Some(handle) = projected.and_then(|v| v.dispatch_handle) {
// Her command whole, as she wrote it: this label is what her view shows for the
// handle, and a cut command reads as a different one.
let label: String = call
.input
.get("command")
.and_then(|v| v.as_str())
.unwrap_or(call.name.as_str()) // label only — the handle is the key
.chars()
.take(80)
.collect();
.to_owned();
body.working_memory.record_dispatch_event(
handle,
&format!("{}: {label}", call.name),
Expand All @@ -426,7 +417,7 @@ pub async fn apply_act(
},
status: ActStatus::Executed,
};
observation.push_str(&obs.render_recency(intent));
observation.push_str(&obs.render_recency());
recall_observation.push_str(&obs.render_recall(intent));
// (The canvas feed publishes at the tool-executor seam, PRE-fold — a
// flood-sized ObserveResult here is already a spilled preview that no
Expand Down Expand Up @@ -471,19 +462,7 @@ pub async fn apply_act(
// The human OBJECT of the act: the first extracted path (reads,
// writes, edits), else the shell command head, else empty —
// honest-thin, never dumped raw JSON args.
let summary = obs
.output
.paths
.first()
.map(|p| p.display().to_string())
.or_else(|| {
obs.call
.input
.get("command")
.and_then(|c| c.as_str())
.map(|c| c.chars().take(80).collect::<String>())
})
.unwrap_or_default();
let summary = act_object(obs);
let update = crate::cognition::mind_events::PersonaActUpdate {
act_id: Uuid::new_v4(),
room_id,
Expand Down Expand Up @@ -532,19 +511,7 @@ pub async fn apply_act(
lines.push(crate::cognition::presence_glyph::said_line(said.trim()));
}
lines.extend(acts.iter().map(|obs| {
let object = obs
.output
.paths
.first()
.map(|p| p.display().to_string())
.or_else(|| {
obs.call
.input
.get("command")
.and_then(|c| c.as_str())
.map(|c| c.chars().take(80).collect::<String>())
})
.unwrap_or_default();
let object = act_object(obs);
crate::cognition::presence_glyph::act_line(
&obs.call.name,
&object,
Expand Down Expand Up @@ -836,3 +803,15 @@ mod tests {
);
}
}

/// The human object of an act, for the clients' act line and presence glyph: its first extracted
/// path (a read, a write, an edit), else its shell command, else empty, never raw JSON arguments.
/// Whole: how much of it a client shows is that client's rendering, not a cut made here.
fn act_object(obs: &Observation) -> String {
obs.output
.paths
.first()
.map(|p| p.display().to_string())
.or_else(|| obs.call.input.get("command").and_then(|c| c.as_str()).map(str::to_owned))
.unwrap_or_default() // unwrap_or_default: an act with no path and no command has no object
}
40 changes: 36 additions & 4 deletions core/continuum-cognition/src/cognition/act_observe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ mod perception;
mod recency;

mod observation;
pub use observation::{extract_paths, intent_label, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb};
pub use observation::{extract_paths, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb};

mod types;
pub use types::{SettleOutcome, SettleStep};
Expand Down Expand Up @@ -76,7 +76,7 @@ pub mod test_support {
}

/// Body that shares a specific working-memory buffer — so a test can wire the
/// SAME buffer into a `WorkingMemoryFaculty` on the cycle and watch the
/// SAME buffer into her view's sources and watch the
/// perception of the persona's own hands flow act→memory→next-tick perception
/// (the proprioception channel that replaced the deleted world-state fold).
pub fn body_with_wm(
Expand Down Expand Up @@ -335,7 +335,7 @@ pub mod test_support {
/// canonical act→observe arc the driver exists to run.
///
/// It perceives its own hands through the working-memory proprioception channel
/// (the `WorkingMemoryFaculty` stamps each act `[action #n]`), NOT the deleted
/// (her trail stamps each act `[action #n]`), NOT the deleted
/// world-state fold. It remembers the highest action stamp it has already spoken
/// about (`responded_through`) so that across SEPARATE concerns — where the
/// volatile buffer still carries the prior concern's action — it re-awakens and
Expand All @@ -345,14 +345,46 @@ pub mod test_support {
pub struct ActThenSpeak {
pub responded_through: std::sync::atomic::AtomicU64,
pub admission_open: Option<Arc<std::sync::atomic::AtomicBool>>,
/// The working memory her view reads, when the test wires one (`perceived_with`).
pub memory: Option<Arc<crate::cognition::working_memory::WorkingMemory>>,
}
impl ActThenSpeak {
pub fn new() -> Self {
Self {
responded_through: std::sync::atomic::AtomicU64::new(0),
admission_open: None,
memory: None,
}
}

/// Perceive her own acts the way her view gives them, from `memory`.
pub fn with_memory(mut self, memory: Arc<crate::cognition::working_memory::WorkingMemory>) -> Self {
self.memory = Some(memory);
self
}
}

/// What a fixture deliberation perceives, as production's does: the broadcast, plus (when
/// wired) what her view gives her from working memory, which is her settled acts' results
/// (the actions source), the newest result riding whole after her view, and her trail.
pub fn perceived_with(ws: &Workspace, memory: Option<&crate::cognition::working_memory::WorkingMemory>) -> String {
let mut perceived = ws.perceived();
if let Some(memory) = memory {
let (acts, _) = memory.action_renderings();
for act in acts {
perceived.push('\n');
perceived.push_str(&act.full);
}
if let Some(newest) = memory.pinned_active_result_block() {
perceived.push('\n');
perceived.push_str(&newest);
}
for line in memory.recent() {
perceived.push('\n');
perceived.push_str(&line);
}
}
perceived
}
/// Highest `[action #N]` stamp present in the assembled perception, 0 if none.
pub fn latest_action_seq(perceived: &str) -> u64 {
Expand Down Expand Up @@ -380,7 +412,7 @@ pub mod test_support {
}

use std::sync::atomic::Ordering;
let latest = latest_action_seq(&ws.perceived());
let latest = latest_action_seq(&perceived_with(ws, self.memory.as_deref()));
if latest > self.responded_through.load(Ordering::Relaxed) {
self.responded_through.store(latest, Ordering::Relaxed);
Some(Contribution::verdict(
Expand Down
69 changes: 23 additions & 46 deletions core/continuum-cognition/src/cognition/act_observe/observation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,14 @@ impl ActOutcome {
}
}

/// A call's arguments as she reads them, by shape and never by size: a single-line value whole,
/// a multi-line value (a file's body, a heredoc) by its reference, so one line stays one line.
/// The one argument renderer (`Observation::call_line`, and a result's status line in
/// `tool_executor::answer`).
pub(crate) fn call_args(input: &serde_json::Value) -> String {
render_call_args(input)
}

impl Observation {
/// Execution alone is not success: projected running/failed/undecodable
/// results do not establish an effect. Legacy unprojected commands retain
Expand Down Expand Up @@ -257,44 +265,31 @@ impl Observation {
self.output.verdict.failed() || self.output.result.is_error == Some(true)
}

/// The RECENCY-channel rendering: the FULL trace working memory keeps so the
/// mind can act on what it just fetched. Byte-identical to the old inline
/// `apply.rs` block (`{name}({args}){because}\nResult:\n{bounded}\n\n`) — the
/// #205 KV-stability invariant. `intent` is batch-level (one per `apply_act`
/// call, shared by every act in the batch), so it is passed rather than
/// stored per-`Observation`.
pub fn render_recency(&self, intent: &str) -> String {
let args = render_call_args(&self.call.input);
// The intent rides the result as a ONE-LINE reason, its first line: a shape rule,
// never a size, and never the whole monologue.
// Measured 2026-09-04: one result header carried 2,902 chars of intent
// ("Let me get oriented…") ahead of 790 chars of actual output; across a
// turn, 6.1k of 20.6k result chars were intent echo. The output is what
// she must read; the reason is a label.
let because = if intent.trim().is_empty() {
String::new()
} else {
format!(" because {}", intent_label(intent))
};
format!(
"{}({}){}\nResult:\n{}\n\n",
self.call.name,
args,
because,
self.body_text().trim(),
)
/// The call as she made it, `name(args)`: its arguments by shape, never by size
/// (`render_call_args`). The one rendering of a call, for its recency trace, its summary part
/// and its ledger line.
pub(crate) fn call_line(&self) -> String {
format!("{}({})", self.call.name, call_args(&self.call.input))
}

/// The RECENCY-channel rendering: the FULL trace working memory keeps so the mind can act on
/// what it just fetched, `{call}\nResult:\n{body}\n\n`, stable across acts (the #205
/// KV-stability invariant).
pub fn render_recency(&self) -> String {
// No reason clause: her intent reaches her whole as her own thought, and #5611's causes
// link each result to its act, so a result carries its call and its output only.
format!("{}\nResult:\n{}\n\n", self.call_line(), self.body_text().trim())
}

/// This act as one part of a batch receipt's summary level: the recency header (its name and
/// args, the same fold) over its HUMANIZED body at `level` (its summary, else whole), so a
/// summary reads what the receipt shows her, never the executor's serialized JSON, where a
/// read's numbered lines are escaped and no code level is found (Codex on #5424).
pub(crate) fn render_summary_part(&self, level: impl Fn(&str) -> Option<String>) -> String {
let args = render_call_args(&self.call.input);
let body = self.body_text();
let body = body.trim();
let shown = level(body).unwrap_or_else(|| body.to_owned()); // unwrap_or: a body with no smaller level is its own summary
format!("{}({})\nResult:\n{}\n\n", self.call.name, args, shown)
format!("{}\nResult:\n{}\n\n", self.call_line(), shown)
}

/// The RECALL-channel rendering: the COLLAPSED reference the Episodic engram
Expand Down Expand Up @@ -351,27 +346,9 @@ pub fn extract_paths(input: &serde_json::Value) -> Vec<PathBuf> {
out
}

/// Clip an act's intent to a one-line reason of at most `max_chars` characters
/// (first line, head-trimmed with an ellipsis). Pure; used by the recency render.
/// The intent's label on a result: its first line. A shape rule, never a size: the rest of what she
/// thought is her own message, already in her view.
pub fn intent_label(intent: &str) -> String {
intent.trim().lines().next().map_or_else(String::new, |first| first.trim().to_string()) // an empty intent labels nothing
}

#[cfg(test)]
mod tests {

// what this catches: the monologue riding every result (2,902 chars of intent ahead of 790
// chars of output, measured 2026-09-04). The label is the first line, by shape, never a size.
#[test]
fn intent_on_a_result_is_its_first_line() {
let long = "Let me get oriented properly this time. I've been confusing myself with stale context and the board says otherwise.\nSecond line never rides.";
let label = super::intent_label(long);
assert!(label.starts_with("Let me get oriented") && !label.contains("Second line"), "{label:?}");
assert_eq!(super::intent_label("read the card"), "read the card");
assert_eq!(super::intent_label(" "), "");
}

use super::*;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@
std::future::pending().await
}
}
let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc<dyn Faculty>], Arc::new(SalienceArbiter), 8);
let cycle = WorkspaceCycle::new(vec![Arc::new(Hangs) as Arc<dyn Faculty>], Arc::new(SalienceArbiter));
let mut conversation = ScriptedConversation::new();
conversation.prime().await.unwrap(); // unwrap: test fixture
let room = crate::identity::ActivityRoom::from_uuid(uuid::Uuid::new_v4()).unwrap(); // unwrap: a fresh uuid is a valid room
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async fn a_batch_whose_effect_mark_is_refused_never_reaches_the_executor() {
result_content: "4\n".into(),
});
let adm = admission();
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(exec.clone(), adm.clone()));
let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused))));
let outcome = apply_act(&cycle, &[tool_call()], "check the math", Uuid::new_v4(), &chain, None, None).await;
Expand Down Expand Up @@ -69,7 +69,7 @@ async fn a_sentinel_only_batch_is_no_effect_and_takes_no_mark() {
seen_context: Arc::new(Mutex::new(None)),
result_content: "reported".into(),
});
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(exec.clone(), admission()));
let chain = ActChain::new().with_effects(Some(crate::cognition::act_observe::EffectGate(Arc::new(Refused))));
let cut = ToolCall {
Expand All @@ -95,7 +95,7 @@ async fn apply_act_scopes_to_the_room_and_observes_the_result() {
result_content: "4\n".into(),
});
let adm = admission();
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(exec.clone(), adm.clone()));

let room = Uuid::new_v4();
Expand Down Expand Up @@ -235,7 +235,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() {
let exec = Arc::new(FoldedRunningExecutor { handle });
let the_body = body(exec.clone(), admission());
let wm = the_body.working_memory.clone();
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(the_body);

let call = ToolCall {
Expand Down Expand Up @@ -292,7 +292,7 @@ async fn a_folded_running_alias_still_registers_its_dispatch_handle() {
// live in the faculty now lives here (the faculty only emits the Act verdict).
#[tokio::test]
async fn apply_act_without_hands_abstains() {
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8);
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter));
assert!(
matches!(
apply_act(
Expand All @@ -317,7 +317,7 @@ async fn apply_act_without_hands_abstains() {
#[tokio::test]
async fn apply_act_abstains_when_the_hand_fails() {
let adm = admission();
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(Arc::new(FailingExecutor), adm.clone()));
assert!(
matches!(
Expand Down Expand Up @@ -394,21 +394,21 @@ async fn an_acts_calls_carry_the_generation_that_issued_them() {
];

let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) };
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(Arc::new(exec.clone()), admission()));
let stamped = apply_act(&cycle, &two_submits, "submit both", Uuid::new_v4(), &ActChain::new(), None, Some("gen-1".into())).await;
assert!(matches!(stamped, ActOutcome::Acted { .. }), "{stamped:?}");
assert_eq!(seen_of(&exec), vec![Some("gen-1".to_string()); 2], "one act, one issuing generation, every call");

let exec = StampingExecutor { issued: None, seen: Arc::new(Mutex::new(Vec::new())) };
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8)
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter))
.with_acting(body(Arc::new(exec.clone()), admission()));
let unstamped = apply_act(&cycle, &[tool_call()], "no generation", Uuid::new_v4(), &ActChain::new(), None, None).await;
assert!(matches!(unstamped, ActOutcome::Acted { .. }), "{unstamped:?}");
assert_eq!(seen_of(&exec), vec![None], "no generation, no stamp");

let plain = Arc::new(RecordingExecutor { seen_context: Arc::new(Mutex::new(None)), result_content: "ok".into() });
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter), 8).with_acting(body(plain, admission()));
let cycle = WorkspaceCycle::new(Vec::new(), Arc::new(SalienceArbiter)).with_acting(body(plain, admission()));
let acted = apply_act(&cycle, &[tool_call()], "cannot stamp", Uuid::new_v4(), &ActChain::new(), None, Some("gen-2".into())).await;
assert!(matches!(acted, ActOutcome::Acted { .. }), "hands that cannot stamp still act: {acted:?}");
}
Loading
Loading