From a712b5ca0a3649119b0633fe5b01b73fa0a2a66e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 09:17:07 -0600 Subject: [PATCH 1/4] Commands take typed params, a turn's budget is a type, and ai/generate's stream is the call's - cognition/calculate-priority and cognition/fast-path-decision become typed action_command!s (Uuid ids, SenderType, InboxMessage); enqueue/admit take the InboxMessage domain type; the hand-parsed InboxMessageRequest wire type, parse_sender_type and parse_inbox_message are deleted (modules/cognition.rs 724 -> 458 lines). - ai/generate takes GenerateParams { request: TextGenerationRequest (flattened), stream_id: Option }: the stream id the airc responder stamps is typed and belongs to the call, never parsed from a JSON string; parse_request is deleted. - The sentinel's LLM step makes one call: its substring matcher of error text under a guessed retry count (3, base 2 s) is deleted; whether an inference failure is retryable is the inference owner's typed judgment. - TurnBudget { Unbounded, Steps(n) } replaces usize::MAX as 'no limit'; LIVE_MAX_ACTS is TurnBudget::Unbounded and its doc no longer describes the deleted repeat-stop. - mind.feed.event names its event_id. Tests (M5, serving down, 2026-11-02 ~15:00-15:16Z): cognition 897/0, mind 1110/0, engine 1403/0, core 1185/0, sentinel 138/0; workspace check --tests clean. Ratchet required_input_complaints 82 -> 80. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.lock | 1 + .../src/cognition/act_observe/mod.rs | 2 +- .../src/cognition/act_observe/settle.rs | 2 + .../act_observe/settle/settle_to_outcome.rs | 68 ++--- .../act_observe/settle/tick_deadline.rs | 20 +- .../act_observe/settle/turn_budget.rs | 47 +++ .../src/cognition/conversation/types.rs | 4 +- .../continuum-core/src/airc/inbound_attach.rs | 1 + .../src/commands/ai/generate.rs | 108 ++----- core/continuum-core/src/ipc/mod.rs | 5 +- .../src/test_env/loose_id_guard.rs | 2 - core/continuum-engine/src/ai/types.rs | 21 +- .../commands/cognition/admit_inbox_message.rs | 13 +- .../commands/cognition/calculate_priority.rs | 47 +++ .../src/commands/cognition/enqueue_message.rs | 14 +- .../commands/cognition/fast_path_decision.rs | 40 +++ .../cognition/inbox_message_request.rs | 74 ----- .../src/commands/cognition/mod.rs | 11 +- core/continuum-mind/src/modules/cognition.rs | 284 +----------------- core/continuum-mind/src/persona/card_hands.rs | 2 +- .../src/persona/service_loop/beat_outcome.rs | 12 +- core/continuum-sentinel/src/steps/llm.rs | 246 +++++---------- core/continuum-tool-protocol/Cargo.toml | 1 + core/continuum-tool-protocol/src/lib.rs | 4 +- protocol/typescript/ai/GenerateParams.ts | 80 +++++ protocol/typescript/ai/index.ts | 1 + .../cognition/AdmitInboxMessageParams.ts | 6 +- .../cognition/CalculatePriorityParams.ts | 4 + .../cognition/EnqueueMessageParams.ts | 6 +- .../cognition/FastPathDecisionParams.ts | 4 + protocol/typescript/cognition/index.ts | 18 +- .../typescript/ipc/InboxMessageRequest.ts | 11 - protocol/typescript/ipc/index.ts | 1 - 33 files changed, 444 insertions(+), 716 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs create mode 100644 core/continuum-mind/src/commands/cognition/calculate_priority.rs create mode 100644 core/continuum-mind/src/commands/cognition/fast_path_decision.rs delete mode 100644 core/continuum-mind/src/commands/cognition/inbox_message_request.rs create mode 100644 protocol/typescript/ai/GenerateParams.ts create mode 100644 protocol/typescript/cognition/CalculatePriorityParams.ts create mode 100644 protocol/typescript/cognition/FastPathDecisionParams.ts delete mode 100644 protocol/typescript/ipc/InboxMessageRequest.ts diff --git a/Cargo.lock b/Cargo.lock index 457cab61e2..5dd3f9c863 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3743,6 +3743,7 @@ dependencies = [ name = "continuum-tool-protocol" version = "0.1.0" dependencies = [ + "schemars", "serde", "serde_json", "ts-rs 12.0.1", diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index eb2963833d..b2d26273c2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -48,7 +48,7 @@ mod page_budget; pub use apply::{apply_act, ActChain}; mod settle; -pub use settle::{drive_to_settle_with_credit, TurnCredit}; +pub use settle::{drive_to_settle_with_credit, TurnBudget, TurnCredit}; pub use settle::{drive_to_settle, drive_to_settle_with_input, settle_step}; #[cfg(test)] diff --git a/core/continuum-cognition/src/cognition/act_observe/settle.rs b/core/continuum-cognition/src/cognition/act_observe/settle.rs index 842f62d105..d145988d2e 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle.rs @@ -21,6 +21,8 @@ use crate::inference::turn_bound::TICK_DEADLINE; mod tick_deadline; mod turn_credit; pub use turn_credit::TurnCredit; +mod turn_budget; +pub use turn_budget::TurnBudget; pub use tick_deadline::*; mod settle_to_outcome; use settle_to_outcome::*; diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs index 3dfdb12ac3..4d20ac29cb 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs @@ -5,7 +5,7 @@ use super::*; pub(super) async fn settle_to_outcome<'c>( cycle: &WorkspaceCycle, mut burst: Burst, - max_acts: usize, + budget: TurnBudget, mut framing: TurnFraming, mut conversation: Option<&mut dyn crate::cognition::conversation::PersonaConversation>, mut credit: Option<&mut (dyn TurnCredit + 'c)>, @@ -64,7 +64,7 @@ pub(super) async fn settle_to_outcome<'c>( // in a row with no act between them means the nudge is not working, so she settles // rather than being trapped. Her own behavior is the budget — no counter, no constant. let mut narrations_since_act: usize = 0; - // ONE STEP BUDGET (2026-11-02): every generation of a turn spends `max_acts`, the caller's + // ONE STEP BUDGET (2026-11-02): every generation of a turn spends the caller's `TurnBudget`, its // one bound: acts, spoken plans and retried faulted generations alike. This counts the // steps that were not acts; `acts + non_act_steps` is what the turn has spent. let mut non_act_steps: usize = 0; @@ -100,14 +100,8 @@ pub(super) async fn settle_to_outcome<'c>( // withheld, and the pre-gate warning now lands 4 acts before THIS bound — // genuinely before, not at, the cliff). Plumbing must never out-stubborn // the engineer it serves. - // Divide BEFORE multiply so this can never overflow: a self-tick (non-benchmark) - // turn passes `max_acts = usize::MAX` (the "unlimited acts" sentinel), and the old - // `max_acts * 3` overflowed usize → a debug-build panic that aborted EVERY persona - // service loop the instant it self-ticked, so residency could never hold - // (resident_count flapped to 0, #412 root). `(max_acts / 4)` is always ≤ max_acts, so - // `* 3` stays in range; `saturating_mul` is belt-and-suspenders. 3/4 of the budget, - // overflow-safe. - let discovery_budget = (max_acts / 4).saturating_mul(3).max(1); + // Three quarters of a bounded budget; an unbounded (live) turn has no discovery gate. + let discovery_budget = budget.discovery_steps(); let mut mutated_yet = false; let mut saturation_probed = false; @@ -301,7 +295,7 @@ pub(super) async fn settle_to_outcome<'c>( persona = body.persona_name.as_str(), milestone = milestone, acts = acts, - max_acts = max_acts, + budget = ?budget, "act-budget proprioception fact recorded in working memory" ); }; @@ -316,37 +310,37 @@ pub(super) async fn settle_to_outcome<'c>( // no fix, no tool. let gate_approaching = framing.workspace_deliverable && !mutated_yet - && discovery_budget >= 4 - && acts == discovery_budget - 4; + && discovery_budget.is_some_and(|steps| steps >= 4 && acts == steps - 4); if gate_approaching { budget_fact_at = Some(acts); probe_budget_fact("pre_gate"); body.working_memory.record_fact(&format!( - "[act-budget] {acts} acts spent, none has changed a file yet. This turn's contract withholds further acts after {discovery_budget} total unless the workspace has been written to — the deliverable is the workspace change, and unwritten work is not part of it." + "[act-budget] {acts} acts spent, none has changed a file yet. This turn's contract withholds further acts after {} total unless the workspace has been written to — the deliverable is the workspace change, and unwritten work is not part of it.", + discovery_budget.unwrap_or(acts) // set: gate_approaching requires a bounded budget )); } else if acts == 0 { budget_fact_at = Some(acts); probe_budget_fact("turn_start"); - body.working_memory.record_fact(&if max_acts == usize::MAX { - "[act-budget] This turn has no fixed act budget: I act until I settle. \ - The deliverable is the workspace as I leave it when I settle — \ - work not yet written when I settle is not part of it." - .to_string() - } else { + body.working_memory.record_fact(&if let TurnBudget::Steps(max_acts) = budget { format!( "[act-budget] This turn grants me {max_acts} act→observe \ cycles before I must settle. The deliverable is the workspace \ as I leave it when I settle — work not yet written when the \ budget ends is not part of it." ) + } else { + "[act-budget] This turn has no fixed act budget: I act until I settle. \ + The deliverable is the workspace as I leave it when I settle — \ + work not yet written when I settle is not part of it." + .to_string() }); - } else if acts == max_acts / 2 { + } else if let Some(max_acts) = budget.remaining(0).filter(|steps| acts == steps / 2) { budget_fact_at = Some(acts); probe_budget_fact("midpoint"); body.working_memory.record_fact(&format!( "[act-budget] I have spent {acts} of my {max_acts} acts this turn." )); - } else if max_acts.saturating_sub(acts) == 2 { + } else if let Some(max_acts) = budget.remaining(0).filter(|steps| steps.saturating_sub(acts) == 2) { budget_fact_at = Some(acts); probe_budget_fact("two_remaining"); body.working_memory.record_fact(&format!( @@ -360,22 +354,23 @@ pub(super) async fn settle_to_outcome<'c>( // saturated its discovery budget without a single mutation (#390 gate above), a // fresh Act is returned un-driven and she must settle into a Speak/Pass. // Speaking is never gated. - let discovery_open = - !framing.workspace_deliverable || mutated_yet || acts < discovery_budget; - if !discovery_open && acts + non_act_steps < max_acts && !saturation_probed { + let discovery_open = !framing.workspace_deliverable + || mutated_yet + || discovery_budget.is_none_or(|steps| acts < steps); + if !discovery_open && budget.allows(acts + non_act_steps) && !saturation_probed { saturation_probed = true; continuum_base::probe!( class = "persona.settle.discovery_saturated", room_id = %room_id, acts = acts, - discovery_budget = discovery_budget, - max_acts = max_acts, + discovery_budget = ?discovery_budget, + budget = ?budget, "workspace-deliverable turn spent its discovery budget with zero \ mutations — withholding further acts so the remaining budget reaches \ the empty-diff re-drive instead of being read away (#390 state gate)" ); } - let may_act = acts + non_act_steps < max_acts && discovery_open; + let may_act = budget.allows(acts + non_act_steps) && discovery_open; let act_started = std::time::Instant::now(); continuum_base::probe!( class = "settle.tick.start", @@ -580,7 +575,7 @@ pub(super) async fn settle_to_outcome<'c>( // turn's own step budget, spent by plans and acts alike (a plan is a // generation too), never a separate constant on how many plans she may // make (2026-11-02); the fact names the count so pacing stays hers. - if framing.workspace_deliverable && acts + non_act_steps + 1 < max_acts { + if framing.workspace_deliverable && budget.allows(acts + non_act_steps + 1) { if let Some(body) = cycle.acting() { if !mutated_workspace(&body.working_memory.recent_entries(), ConcernPhase::JustSettled) { narrations_since_act += 1; @@ -590,11 +585,14 @@ pub(super) async fn settle_to_outcome<'c>( // the fact; the "an explanation of a fix is not the fix" // sermon accumulated dozens of copies in looping minds // and became the content of their turns. + let left = match budget.remaining(acts + non_act_steps) { + Some(left) => format!(", {left} steps left this turn"), + None => String::new(), + }; body.working_memory.record_fact(&format!( "[no-deliverable] I settled by speaking ({narrations_since_act} \ - plans in a row, {} of this turn's {max_acts} steps left); no act \ - of mine has changed a file in this workspace yet.", - max_acts - acts - non_act_steps + plans in a row{left}); no act of mine has changed a file in this \ + workspace yet." )); continuum_base::probe!( class = "persona.settle.no_deliverable", @@ -775,7 +773,7 @@ pub(super) async fn settle_to_outcome<'c>( class = "persona.act.lane_starved", room_id = %room_id, act = acts, - steps_kept = (max_acts.saturating_sub(acts + non_act_steps)) as u64, + steps_kept = ?budget.remaining(acts + non_act_steps), error = %error, "deferred at the serving gate without reaching the model — act budget and deliberation retries left intact for the next tick" ); @@ -808,7 +806,7 @@ pub(super) async fn settle_to_outcome<'c>( // retry waits out another whole bound on the same engine (up to three, so one // turn held four). It surrenders now, a failed act: demand and a failure for // the resident ledger, never a completion (Fable on #5498). - if acts + non_act_steps + 1 < max_acts && !dropped_in_flight { + if budget.allows(acts + non_act_steps + 1) && !dropped_in_flight { delib_retries += 1; non_act_steps += 1; continuum_base::probe!( @@ -816,7 +814,7 @@ pub(super) async fn settle_to_outcome<'c>( room_id = %room_id, acts = acts, retry = delib_retries, - steps_kept = (max_acts.saturating_sub(acts + non_act_steps)) as u64, + steps_kept = ?budget.remaining(acts + non_act_steps), error = %error, "transient deliberation fault — retrying the thought in place (the turn is not yet surrendered)" ); diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs index 7a314a0220..46cf927916 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs @@ -139,9 +139,9 @@ pub(super) fn act_probe_client() -> &'static reqwest::Client { // its own truncation). Still used here for the settlement answer-head. /// Drive the mind to SETTLEMENT: tick → if `Act`, run it + fold the observation /// into the next perception → re-tick → until it `Speak`s/`Pass`es or the -/// external `max_acts` budget is spent. +/// external step budget ([`TurnBudget`]) is spent. /// -/// `max_acts` is the EXTERNAL observer's stopwatch — the grader holds it because +/// The [`TurnBudget`] is the EXTERNAL observer's stopwatch — the grader holds it because /// the eval room has no heartbeat to pace re-perception. It is NOT a cap that /// lives in the persona's head (the live path has no such bound; an "acts /// forever" persona is a fitness gap to train away, never a substrate ceiling — @@ -251,10 +251,10 @@ impl PaceCadence { pub fn drive_to_settle( cycle: &WorkspaceCycle, burst: impl Into, - max_acts: usize, + budget: impl Into, framing: TurnFraming, ) -> impl std::future::Future + Send + '_ { - drive_with_input(cycle, burst.into(), max_acts, framing, None, None) + drive_with_input(cycle, burst.into(), budget.into(), framing, None, None) } /// The live driver leases its existing conversation between steps. No second @@ -262,11 +262,11 @@ pub fn drive_to_settle( pub fn drive_to_settle_with_input<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - max_acts: usize, + budget: impl Into, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, ) -> impl std::future::Future + Send + 'a { - drive_with_input(cycle, burst, max_acts, framing, Some(conversation), None) + drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), None) } /// A live card-linked turn uses the same driver with its own credit capture. @@ -274,20 +274,20 @@ pub fn drive_to_settle_with_input<'a>( pub fn drive_to_settle_with_credit<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - max_acts: usize, + budget: impl Into, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, credit: Option<&'a mut dyn TurnCredit>, ) -> impl std::future::Future + Send + 'a { // Return the shared driver directly: an async forwarding wrapper needlessly // nests its state in every live/eval caller and inflates future layout depth. - drive_with_input(cycle, burst, max_acts, framing, Some(conversation), credit) + drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), credit) } pub(super) async fn drive_with_input<'c>( cycle: &WorkspaceCycle, burst: Burst, - max_acts: usize, + budget: TurnBudget, framing: TurnFraming, conversation: Option<&mut dyn crate::cognition::conversation::PersonaConversation>, mut credit: Option<&mut (dyn TurnCredit + 'c)>, @@ -297,7 +297,7 @@ pub(super) async fn drive_with_input<'c>( let settled = settle_to_outcome( cycle, burst, - max_acts, + budget, framing, conversation, credit.as_deref_mut(), diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs new file mode 100644 index 0000000000..ab3eeb80dd --- /dev/null +++ b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs @@ -0,0 +1,47 @@ +//! How many steps a turn may spend: every generation it makes (acts, spoken plans, retried +//! faulted generations). A type, so "no limit" is a variant and never a number standing for one +//! (`usize::MAX` was the live turn's sentinel, and a probe once read its remainder as +//! 18446744073709551614). + +/// A turn's step budget. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TurnBudget { + /// A live turn: she acts until she settles. + Unbounded, + /// A caller-bounded turn (an eval, a solve): at most this many steps. + Steps(usize), +} + +impl TurnBudget { + /// Whether a turn that has spent `spent` steps may take another. + pub fn allows(self, spent: usize) -> bool { + match self { + Self::Unbounded => true, + Self::Steps(n) => spent < n, + } + } + + /// Steps left after `spent`; `None` when the turn is unbounded. + pub fn remaining(self, spent: usize) -> Option { + match self { + Self::Unbounded => None, + Self::Steps(n) => Some(n.saturating_sub(spent)), + } + } + + /// The acts a workspace-deliverable turn may spend before its first write (the #390 + /// discovery gate): three quarters of a bounded budget, at least one; an unbounded turn has + /// no discovery gate. + pub fn discovery_steps(self) -> Option { + match self { + Self::Unbounded => None, + Self::Steps(n) => Some((n / 4 * 3).max(1)), + } + } +} + +impl From for TurnBudget { + fn from(steps: usize) -> Self { + Self::Steps(steps) + } +} diff --git a/core/continuum-cognition/src/cognition/conversation/types.rs b/core/continuum-cognition/src/cognition/conversation/types.rs index 1556ed6703..ccc428a085 100644 --- a/core/continuum-cognition/src/cognition/conversation/types.rs +++ b/core/continuum-cognition/src/cognition/conversation/types.rs @@ -27,7 +27,7 @@ pub enum SenderType { } /// Input modality for messages -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, TS)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, TS, schemars::JsonSchema)] #[serde(rename_all = "lowercase")] #[ts(export, export_to = "../../../protocol/typescript/persona/Modality.ts")] pub enum Modality { @@ -39,7 +39,7 @@ pub enum Modality { // INBOX MESSAGE //============================================================================= -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/persona/InboxMessage.ts" diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index 20548bb34b..174d76a7bc 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -421,6 +421,7 @@ pub async fn publish_transcript_event( class = "mind.feed.event", room = %event.room_id.as_uuid(), from = %event.peer_id.as_uuid(), + event_id = %event.event_id.as_uuid(), residents = fed, "a room event fed to resident minds" ); diff --git a/core/continuum-core/src/commands/ai/generate.rs b/core/continuum-core/src/commands/ai/generate.rs index fc05ff8dff..433018243d 100644 --- a/core/continuum-core/src/commands/ai/generate.rs +++ b/core/continuum-core/src/commands/ai/generate.rs @@ -6,14 +6,12 @@ //! in-process (and the grid leases remotely). Gated `Privileged`: leased inference, //! not a citizen-facing action. //! -//! ## Faithful migration +//! ## Typed input //! -//! Ported verbatim off `AIProviderModule::handle_command`'s `ai/generate` arm. The -//! input is polymorphic (a `messages` array OR a `prompt` string, with snake_case -//! AND camelCase aliases across a dozen sampling fields), so `Params = Value` and -//! [`parse_request`] reproduces the legacy alias surface byte-for-byte — the canonical -//! typed input [`TextGenerationRequest`] is the eventual convergence target, not this -//! migration's job. The output [`AiGenerateResult`] reuses the canonical sub-types +//! The params ARE the canonical [`TextGenerationRequest`], decoded by serde at the boundary: +//! the same shape the grid's remote path sends, one wire name per field (camelCase), and no +//! field a handler has to find missing. The legacy alias table (`prompt` OR `messages`, +//! snake_case AND camelCase) is gone (2026-11-02). The output [`AiGenerateResult`] reuses the canonical sub-types //! ([`UsageMetrics`]/[`ContentPart`]/[`ToolCall`]/[`RoutingInfo`]) and mirrors the //! exact camelCase wire shape the old hand-rolled `response_to_json` produced. @@ -29,7 +27,21 @@ use crate::ai::{ }; use crate::logging::TimingGuard; use crate::ai::adapter::select_failure_message; -use crate::runtime::params::Params; + +/// The params of `ai/generate`: the inference request itself, plus the stream a caller +/// registered a sink under (`stream_sinks::register`), which the airc responder stamps so +/// every chunk reaches the remote mind as it is produced. The stream is the call's, never +/// the request's; a plain call has none and gets the assembled response. +#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema, ts_rs::TS)] +#[serde(rename_all = "camelCase")] +#[ts(export, export_to = "../../../protocol/typescript/ai/GenerateParams.ts")] +pub struct GenerateParams { + #[serde(flatten)] + pub request: TextGenerationRequest, + #[serde(default)] + #[ts(optional, type = "string")] + pub stream_id: Option, +} /// Result of `ai/generate` — the exact camelCase shape the inference seam has always /// returned. `success` is always `true` on the Ok path (errors return `Err`, which the @@ -80,75 +92,6 @@ impl From for AiGenerateResult { } } -/// Parse a [`TextGenerationRequest`] from the polymorphic JSON params — a `messages` -/// array or a single `prompt` string, with snake_case + camelCase aliases on every -/// sampling field. Lifted verbatim from the legacy `AIProviderModule::parse_request`. -fn parse_request(params: &Value) -> Result { - let p = Params::new(params); - - // Parse messages (array) or simple prompt (string) - let messages: Vec = if let Some(msgs) = p.value("messages") { - serde_json::from_value(msgs.clone()) - .map_err(|e| format!("Failed to parse messages: {}", e))? - } else if let Some(prompt) = p.str_opt("prompt") { - vec![ChatMessage { - role: "user".to_string(), - content: MessageContent::Text(prompt.to_string()), - name: None, - }] - } else { - return Err("Missing messages or prompt".to_string()); - }; - - if messages.is_empty() { - return Err("Messages cannot be empty".to_string()); - } - - Ok(TextGenerationRequest { - messages, - system_prompt: p.string_opt_alias("system_prompt", "systemPrompt"), - model: p.str_opt("model").map(String::from), - provider: p.str_opt("provider").map(String::from), - temperature: p.f32_opt("temperature"), - max_tokens: p.u64_opt_alias("max_tokens", "maxTokens").map(|t| t as u32), - top_p: p.f64_opt_alias("top_p", "topP").map(|t| t as f32), - top_k: p.u64_opt_alias("top_k", "topK").map(|t| t as u32), - repeat_penalty: p - .f32_opt("repeat_penalty") - .or_else(|| p.f32_opt("repeatPenalty")), - frequency_penalty: p - .f32_opt("frequency_penalty") - .or_else(|| p.f32_opt("frequencyPenalty")), - repeat_last_n: p - .u64_opt_alias("repeat_last_n", "repeatLastN") - .map(|n| n as u32), - stop_sequences: p - .json_opt("stop_sequences") - .or_else(|| p.json_opt("stopSequences")), - tools: p.json_opt("tools"), - tail_tools: None, - view_messages: None, - tool_choice: p.json_opt("tool_choice"), - response_format: None, - active_adapters: p.json_opt("activeAdapters"), - request_id: p.string_opt_alias("request_id", "requestId"), - user_id: p.string_opt_alias("user_id", "userId"), - room_id: p.string_opt_alias("room_id", "roomId"), - purpose: p.str_opt("purpose").map(String::from), - // Caller-provided persona attribution. TS sends `personaId` (camelCase) - // per Continuum convention; snake_case alias accepted for symmetry. - persona_id: p.string_opt_alias("persona_id", "personaId"), - // The turn's own wire bound (card ba82d0a0): the requesting mind's measured - // expectation with headroom, serde's `{secs, nanos}`. A remote turn arrives - // here on the SERVING peer, whose lane must wait out the same prefill the - // requester is waiting out — dropped here, the peer's 300 s floor would kill - // the very turn the requester sized a 1200 s bound for. Absent = the floor. - turn_bound: p - .json_opt::("turn_bound") - .or_else(|| p.json_opt("turnBound")), - }) -} - crate::action_command! { /// Generate text from an AI provider: select the best adapter for the requested /// provider/model (or the default), run the request, and return the completion @@ -158,12 +101,17 @@ crate::action_command! { pub struct AiGenerate { registry: Arc> } name: "ai/generate", access: Privileged, - params: Value, + params: GenerateParams, output: AiGenerateResult, run(this, ctx, p) => { let _timer = TimingGuard::new("module", "ai_generate"); - let request = parse_request(&p)?; + let GenerateParams { request, stream_id } = p; + // The one shape check serde cannot express on today's `Vec`: an empty conversation. + // Follow-up (Fable): `TextGenerationRequest::messages` becomes non-empty by type. + if request.messages.is_empty() { + return Err(crate::sdk_codegen::CommandError::Invalid("ai/generate: the request has no messages".into())); + } let registry = this.registry.read().await; @@ -192,7 +140,7 @@ crate::action_command! { // every chunk the instant the backend produces it — the same primitive the // local persona turn rides — and the assembled response at the end. No sink // registered (a plain call) = the drain, exactly as before. - let sink = crate::ai::stream_sinks::stream_id_of(&p).and_then(crate::ai::stream_sinks::take); + let sink = stream_id.and_then(crate::ai::stream_sinks::take); let mut response = match sink { Some(sink) => adapter.generate_stream(request, sink).await?, None => adapter.generate_text(request).await?, diff --git a/core/continuum-core/src/ipc/mod.rs b/core/continuum-core/src/ipc/mod.rs index f0f84d8510..3678e3eda8 100644 --- a/core/continuum-core/src/ipc/mod.rs +++ b/core/continuum-core/src/ipc/mod.rs @@ -58,8 +58,8 @@ use uuid::Uuid; // ============================================================================ // Request/Response Protocol + Memory Diagnostics // ============================================================================ -// Split out of this file 2026-05-18 — see ipc/protocol.rs (InboxMessageRequest, -// Response) and ipc/diagnostics.rs (per-command RSS tracking). Re-exported +// Split out of this file 2026-05-18 — see ipc/protocol.rs +// (Response) and ipc/diagnostics.rs (per-command RSS tracking). Re-exported // here so existing call sites resolve unchanged. pub mod command_ingress; pub mod diagnostics; @@ -105,7 +105,6 @@ pub mod ws; use diagnostics::{current_rss_mb, dump_memory_report, log_command_rss_delta}; -pub use continuum_mind::commands::cognition::inbox_message_request::InboxMessageRequest; use protocol::Response; diff --git a/core/continuum-core/src/test_env/loose_id_guard.rs b/core/continuum-core/src/test_env/loose_id_guard.rs index affa5b739e..07a904f0f4 100644 --- a/core/continuum-core/src/test_env/loose_id_guard.rs +++ b/core/continuum-core/src/test_env/loose_id_guard.rs @@ -66,8 +66,6 @@ const LOOSE_IDS: &[LooseId] = &[ LooseId { file: "commands/multi_layer_recall.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "commands/recall_hook.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "commands/persona/wall/pin.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, - LooseId { file: "commands/cognition/inbox_message_request.rs", field: "room_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, - LooseId { file: "commands/cognition/inbox_message_request.rs", field: "sender_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, LooseId { file: "persona/stream_rail.rs", field: "room_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, LooseId { file: "persona/stream_rail.rs", field: "sender_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, LooseId { file: "live/audio/mixer.rs", field: "user_id", why: "external: LiveKit participant/room identity — the media server owns this string on the wire" }, diff --git a/core/continuum-engine/src/ai/types.rs b/core/continuum-engine/src/ai/types.rs index dfeec47f93..ac047e5940 100644 --- a/core/continuum-engine/src/ai/types.rs +++ b/core/continuum-engine/src/ai/types.rs @@ -10,7 +10,7 @@ use serde_json::Value; use ts_rs::TS; /// Chat message for text generation -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/ChatMessage.ts")] #[serde(rename_all = "camelCase")] pub struct ChatMessage { @@ -22,7 +22,7 @@ pub struct ChatMessage { } /// Message content - either plain text or multimodal content blocks -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/MessageContent.ts" @@ -34,7 +34,7 @@ pub enum MessageContent { } /// Content part for multimodal and tool protocol messages -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/ContentPart.ts")] #[serde(tag = "type", rename_all = "snake_case")] pub enum ContentPart { @@ -65,7 +65,7 @@ pub enum ContentPart { }, } -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/ImageInput.ts")] #[serde(rename_all = "camelCase")] pub struct ImageInput { @@ -80,7 +80,7 @@ pub struct ImageInput { pub mime_type: Option, } -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/AudioInput.ts")] #[serde(rename_all = "camelCase")] pub struct AudioInput { @@ -95,7 +95,7 @@ pub struct AudioInput { pub mime_type: Option, } -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/VideoInput.ts")] #[serde(rename_all = "camelCase")] pub struct VideoInput { @@ -165,7 +165,7 @@ impl ResultCustody { } /// Tool choice specification -#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts(export, export_to = "../../../protocol/typescript/ai/ToolChoice.ts")] #[serde(untagged)] pub enum ToolChoice { @@ -178,7 +178,7 @@ pub enum ToolChoice { // ============================================================================ /// Active LoRA adapter to apply during generation -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/ActiveAdapterRequest.ts" @@ -198,7 +198,7 @@ fn default_adapter_scale() -> f64 { } /// Text generation request -#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/TextGenerationRequest.ts" @@ -329,6 +329,7 @@ pub struct TextGenerationRequest { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional, type = "{ secs: number, nanos: number }")] pub turn_bound: Option, + } /// Constrains the model's output format. OpenAI-compatible serialization: @@ -337,7 +338,7 @@ pub struct TextGenerationRequest { /// can only emit valid JSON (when JsonObject) — no thinking prose, no /// commentary, no leading/trailing text. The right way to enforce structured /// output: at the model level, not via a downstream parser fallback. -#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq, Eq)] +#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq, Eq, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/ResponseFormat.ts" diff --git a/core/continuum-mind/src/commands/cognition/admit_inbox_message.rs b/core/continuum-mind/src/commands/cognition/admit_inbox_message.rs index 4fdcc0dbc9..2ffdf4bde7 100644 --- a/core/continuum-mind/src/commands/cognition/admit_inbox_message.rs +++ b/core/continuum-mind/src/commands/cognition/admit_inbox_message.rs @@ -1,9 +1,8 @@ //! `cognition/admit-inbox-message` — run a persona's admission gate over one inbox //! message (typed, dep-holding). //! -//! Converts the JSON-transport [`InboxMessageRequest`](super::inbox_message_request::InboxMessageRequest) -//! to the domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage) via the one canonical -//! `to_inbox_message()` seam, then runs the persona's admission gate +//! Takes the domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage) itself, decoded +//! by serde at the boundary, then runs the persona's admission gate //! ([`admit`](crate::cognition::admission_state)) — recording side-effects (admitted //! engram → store, content_hash → dedup, AIRC event_id → replay-protection). Returns //! the typed [`AdmissionDecision`](crate::cognition::engram::AdmissionDecision) plus funnel @@ -21,7 +20,7 @@ use std::sync::Arc; use uuid::Uuid; -use super::inbox_message_request::InboxMessageRequest; +use crate::cognition::conversation::types::InboxMessage; use crate::modules::cognition::CognitionState; use crate::cognition::trace::CognitionTrace; use crate::cognition::engram::AdmissionDecision; @@ -37,8 +36,8 @@ pub struct AdmitInboxMessageParams { /// Persona whose admission gate runs. #[ts(type = "string")] pub persona_id: Uuid, - /// The message to admit (JSON-transport shape, string UUIDs + string enums). - pub message: InboxMessageRequest, + /// The message to admit (decoded by serde at the boundary: typed ids and enums). + pub message: InboxMessage, } /// The admission outcome plus admission-funnel telemetry. @@ -68,7 +67,7 @@ crate::action_command! { params: AdmitInboxMessageParams, output: AdmitInboxMessageResult, run(this, _ctx, p) => { - let inbox_msg = p.message.to_inbox_message().map_err(CommandError::Invalid)?; + let inbox_msg = p.message; let persona = this .state diff --git a/core/continuum-mind/src/commands/cognition/calculate_priority.rs b/core/continuum-mind/src/commands/cognition/calculate_priority.rs new file mode 100644 index 0000000000..869a19d262 --- /dev/null +++ b/core/continuum-mind/src/commands/cognition/calculate_priority.rs @@ -0,0 +1,47 @@ +//! `cognition/calculate-priority`: a persona's priority score for one message (typed, +//! dep-holding). Every field is required by its type; a request without one never decodes, so +//! there is no "missing" path to write. + +use std::sync::Arc; + +use uuid::Uuid; + +use crate::cognition::conversation::types::SenderType; +use crate::modules::cognition::CognitionState; +use crate::persona::cognition::PriorityScore; +use crate::sdk_codegen::CommandError; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] +#[ts( + export, + export_to = "../../../protocol/typescript/cognition/CalculatePriorityParams.ts" +)] +pub struct CalculatePriorityParams { + #[ts(type = "string")] + pub persona_id: Uuid, + pub content: String, + pub sender_type: SenderType, + #[serde(default)] + pub is_voice: bool, + #[ts(type = "string")] + pub room_id: Uuid, + #[ts(type = "number")] + pub timestamp: u64, +} + +crate::action_command! { + /// Score one message's priority for a persona. Host-invoked. + pub struct CalculatePriority { state: Arc } + name: "cognition/calculate-priority", + access: Internal, + params: CalculatePriorityParams, + output: PriorityScore, + run(this, _ctx, p) => { + let persona = this + .state + .personas + .get(&p.persona_id) + .ok_or_else(|| CommandError::NotFound(format!("no cognition for persona {}", p.persona_id)))?; + Ok(persona.engine.calculate_priority(&p.content, p.sender_type, p.is_voice, p.room_id, p.timestamp)) + } +} diff --git a/core/continuum-mind/src/commands/cognition/enqueue_message.rs b/core/continuum-mind/src/commands/cognition/enqueue_message.rs index b2c3e9ba39..c0a4b1e6dd 100644 --- a/core/continuum-mind/src/commands/cognition/enqueue_message.rs +++ b/core/continuum-mind/src/commands/cognition/enqueue_message.rs @@ -1,9 +1,8 @@ //! `cognition/enqueue-message` — push a message onto a persona's priority inbox //! (typed, dep-holding). //! -//! Takes the JSON-transport [`InboxMessageRequest`](super::inbox_message_request::InboxMessageRequest), -//! converts it to the domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage) via the one -//! canonical `to_inbox_message()` seam, and enqueues it on the persona's priority heap. +//! Takes the domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage) itself, decoded by +//! serde at the boundary, and enqueues it on the persona's priority heap. //! Captures the owning module's [`CognitionState`](crate::modules::cognition::CognitionState). //! //! `access: Internal` — host-driven cognition IPC, not a persona toolbelt verb. @@ -12,9 +11,8 @@ use std::sync::Arc; use uuid::Uuid; -use super::inbox_message_request::InboxMessageRequest; +use crate::cognition::conversation::types::InboxMessage; use crate::modules::cognition::CognitionState; -use crate::sdk_codegen::CommandError; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] #[ts( @@ -26,8 +24,8 @@ pub struct EnqueueMessageParams { /// Persona whose inbox receives the message. #[ts(type = "string")] pub persona_id: Uuid, - /// The message to enqueue (JSON-transport shape, string UUIDs + string enums). - pub message: InboxMessageRequest, + /// The message to enqueue (decoded by serde at the boundary: typed ids and enums). + pub message: InboxMessage, } #[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] @@ -50,7 +48,7 @@ crate::action_command! { params: EnqueueMessageParams, output: EnqueueMessageResult, run(this, _ctx, p) => { - let inbox_msg = p.message.to_inbox_message().map_err(CommandError::Invalid)?; + let inbox_msg = p.message; let persona = this.state.get_or_create_persona(p.persona_id); persona.inbox.enqueue(inbox_msg); diff --git a/core/continuum-mind/src/commands/cognition/fast_path_decision.rs b/core/continuum-mind/src/commands/cognition/fast_path_decision.rs new file mode 100644 index 0000000000..784ccbf53c --- /dev/null +++ b/core/continuum-mind/src/commands/cognition/fast_path_decision.rs @@ -0,0 +1,40 @@ +//! `cognition/fast-path-decision`: a persona's fast-path decision on one inbox message (typed, +//! dep-holding). The message is the domain [`InboxMessage`] itself: decoded by serde at the +//! boundary, so no field can be missing past it. + +use std::sync::Arc; + +use uuid::Uuid; + +use crate::cognition::conversation::types::InboxMessage; +use crate::modules::cognition::CognitionState; +use crate::persona::cognition::CognitionDecision; +use crate::sdk_codegen::CommandError; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] +#[ts( + export, + export_to = "../../../protocol/typescript/cognition/FastPathDecisionParams.ts" +)] +pub struct FastPathDecisionParams { + #[ts(type = "string")] + pub persona_id: Uuid, + pub message: InboxMessage, +} + +crate::action_command! { + /// Decide a message on the persona's fast path. Host-invoked. + pub struct FastPathDecision { state: Arc } + name: "cognition/fast-path-decision", + access: Internal, + params: FastPathDecisionParams, + output: CognitionDecision, + run(this, _ctx, p) => { + let persona = this + .state + .personas + .get(&p.persona_id) + .ok_or_else(|| CommandError::NotFound(format!("no cognition for persona {}", p.persona_id)))?; + Ok(persona.engine.fast_path_decision(&p.message)) + } +} diff --git a/core/continuum-mind/src/commands/cognition/inbox_message_request.rs b/core/continuum-mind/src/commands/cognition/inbox_message_request.rs deleted file mode 100644 index 8eb1443251..0000000000 --- a/core/continuum-mind/src/commands/cognition/inbox_message_request.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! The JSON-transport inbox message (string UUIDs) the `cognition/enqueue-message` and -//! `cognition/admit-inbox-message` commands accept: moved down from core's `ipc/protocol.rs` with the -//! commands that parse it (plan phase 2); `ipc` re-exports it under the old path. - -use serde::{Deserialize, Serialize}; -use ts_rs::TS; -use uuid::Uuid; - -/// Inbox message for IPC (mirrors InboxMessage but with string UUIDs for -/// JSON transport). -#[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] -#[ts( - export, - export_to = "../../../protocol/typescript/ipc/InboxMessageRequest.ts" -)] -pub struct InboxMessageRequest { - pub id: String, - pub room_id: String, - pub sender_id: String, - pub sender_name: String, - pub sender_type: String, // "human", "persona", "agent", "system" - pub content: String, - /// Timestamp in milliseconds (fits in JS number, max safe ~9 quadrillion) - #[ts(type = "number")] - pub timestamp: u64, - pub priority: f32, - #[ts(optional)] - pub source_modality: Option, // "chat", "voice" - #[ts(optional)] - pub voice_session_id: Option, -} - -impl InboxMessageRequest { - /// Convert this JSON-transport request (string UUIDs, string enums) into the - /// domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage). The single - /// wire→domain conversion for inbox messages — reused by every typed command - /// that accepts an inbox message off the wire. - /// - /// Fails loud on a malformed UUID or an unknown `sender_type` (the legacy - /// free-fn form silently dropped an unparseable `voice_session_id`; this - /// surfaces it instead, per the no-silent-fallback rule). - pub fn to_inbox_message(&self) -> Result { - use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; - - let sender_type = match self.sender_type.as_str() { - "human" => SenderType::Human, - "persona" => SenderType::Persona, - "agent" => SenderType::Agent, - "system" => SenderType::System, - other => return Err(format!("Invalid sender_type: {other}")), - }; - - Ok(InboxMessage { - id: Uuid::parse_str(&self.id).map_err(|e| format!("invalid id: {e}"))?, - room_id: Uuid::parse_str(&self.room_id).map_err(|e| format!("invalid room_id: {e}"))?, - sender_id: Uuid::parse_str(&self.sender_id) - .map_err(|e| format!("invalid sender_id: {e}"))?, - sender_name: self.sender_name.clone(), - sender_type, - content: self.content.clone(), - timestamp: self.timestamp, - priority: self.priority, - source_modality: self.source_modality.as_deref().map(|m| match m { - "voice" => Modality::Voice, - _ => Modality::Chat, - }), - voice_session_id: self - .voice_session_id - .as_deref() - .map(|s| Uuid::parse_str(s).map_err(|e| format!("invalid voice_session_id: {e}"))) - .transpose()?, - }) - } -} diff --git a/core/continuum-mind/src/commands/cognition/mod.rs b/core/continuum-mind/src/commands/cognition/mod.rs index 7cb92e6880..59b807085a 100644 --- a/core/continuum-mind/src/commands/cognition/mod.rs +++ b/core/continuum-mind/src/commands/cognition/mod.rs @@ -20,6 +20,7 @@ use crate::sdk_codegen::DynCommand; pub mod admit_inbox_message; pub mod cache_message; +pub mod calculate_priority; pub mod check_adequacy; pub mod check_content_dedup; pub mod classify_domain; @@ -27,11 +28,11 @@ pub mod configure_rate_limiter; pub mod create_engine; pub mod dream_now; pub mod enqueue_message; +pub mod fast_path_decision; pub mod forget_context; pub mod full_evaluate; pub mod get_state; pub mod gpu_budget; -pub mod inbox_message_request; pub mod has_evaluated; pub mod inbox_create; pub mod inbox_drain_frame; @@ -58,7 +59,9 @@ use classify_domain::ClassifyDomain; use configure_rate_limiter::ConfigureRateLimiter; use create_engine::CreateEngine; use dream_now::DreamNow; +use calculate_priority::CalculatePriority; use enqueue_message::EnqueueMessage; +use fast_path_decision::FastPathDecision; use forget_context::ForgetContext; use full_evaluate::FullEvaluate; use get_state::GetState; @@ -139,6 +142,12 @@ pub fn command_objects( Arc::new(EnqueueMessage { state: state.clone(), }), + Arc::new(CalculatePriority { + state: state.clone(), + }), + Arc::new(FastPathDecision { + state: state.clone(), + }), Arc::new(FullEvaluate { state: state.clone(), }), diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index 648b67eed1..7985f26d20 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -29,7 +29,8 @@ //! a turn runs is `genome::composer`, where they live is `genome::gene_residency`. //! - `inbox/create`: Create persona inbox (alias for create-engine) //! -//! Uses `Params` helper for typed parameter extraction. +//! Every command is a typed object whose params serde decodes at the boundary: a required field +//! cannot be missing past it. use crate::gpu::GpuMemoryManager; use crate::logging::TimingGuard; @@ -38,7 +39,6 @@ use crate::persona::{PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, Pers use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::rag::RagEngine; use crate::runtime::{CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; -use crate::runtime::params::Params; use async_trait::async_trait; use dashmap::DashMap; use serde_json::Value; @@ -268,244 +268,11 @@ impl ServiceModule for CognitionModule { Ok(()) } - async fn handle_command(&self, command: &str, params: Value) -> Result { - let p = Params::new(¶ms); - - match command { - // ================================================================ - // Persona Lifecycle - // ================================================================ - // cognition/create-engine migrated to the typed DynCommand registry (Slice 7) - // — see commands/cognition/create_engine.rs (dep-holding on CognitionState, - // access: Internal). - - // NOTE: `cognition/eval` (the test-graded coder gym) is now a typed, - // registered, Privileged ActionCommand — see `cognition::eval::CognitionEval`. - // It dispatches via the central registry (so `uu` and every client can - // reach it, and it's discoverable + gated), no longer a match-arm here. - "cognition/calculate-priority" => { - let _timer = TimingGuard::new("module", "cognition_calculate_priority"); - let persona_uuid = p.uuid("persona_id")?; - let content = p.str("content")?; - let sender_type_str = p.str("sender_type")?; - let is_voice = p.bool_or("is_voice", false); - let room_uuid = p.uuid("room_id")?; - let timestamp = p.u64("timestamp")?; - - let sender = parse_sender_type(sender_type_str)?; - let persona = self - .state - .personas - .get(&persona_uuid) - .ok_or_else(|| format!("No cognition for {persona_uuid}"))?; - - let score = persona - .engine - .calculate_priority(content, sender, is_voice, room_uuid, timestamp); - Ok(CommandResult::Json( - serde_json::to_value(&score).map_err(|e| format!("Serialize error: {e}"))?, - )) - } - - "cognition/fast-path-decision" => { - let _timer = TimingGuard::new("module", "cognition_fast_path_decision"); - let persona_uuid = p.uuid("persona_id")?; - let message = p.value("message").ok_or("Missing message")?; - let inbox_msg = parse_inbox_message(message)?; - - let persona = self - .state - .personas - .get(&persona_uuid) - .ok_or_else(|| format!("No cognition for {persona_uuid}"))?; - - let decision = persona.engine.fast_path_decision(&inbox_msg); - Ok(CommandResult::Json( - serde_json::to_value(&decision).map_err(|e| format!("Serialize error: {e}"))?, - )) - } - - // cognition/enqueue-message migrated to the typed DynCommand registry (Slice 7) - // — see commands/cognition/enqueue_message.rs. The wire→domain conversion now - // lives as InboxMessageRequest::to_inbox_message (ipc/protocol.rs). - - // cognition/get-state migrated to the typed DynCommand registry (Slice 8) - // — see commands/cognition/get_state.rs (dep-holding, access: Internal, - // camelCase GetStateResult projection of PersonaState + service_cadence_ms). - - // inbox/create + inbox/drain-frame migrated to the typed DynCommand registry - // (Slice 7) — see commands/cognition/{inbox_create,inbox_drain_frame}.rs. The - // frame-recording helper `record_drained_turn_frame` stays here (made - // pub(crate)): it is now called by two migrated commands - // (commands/cognition/inbox_drain_frame.rs + commands/persona/turn_frame/drain.rs). - - // persona/drain-turn-frame + persona/turn-execute migrated to the typed - // DynCommand registry (Slices 20 + 21) — see - // commands/persona/turn_frame/{drain,execute}.rs (dep-holding on CognitionState, - // access: Internal). The Lane D turn-frame types (PersonaTurnFrameReplayRecord + - // its subtree) derive TS so the typed Output crosses the wire; execute.rs also - // carries `execute_rust_module_json` (moved with its sole consumer) — the - // in-process seam to the Rust inference module, fail-loud on a missing route. - - // cognition/admit-inbox-message + cognition/recall-engrams migrated to the - // typed DynCommand registry (Slice 9) — see - // commands/cognition/{admit_inbox_message,recall_engrams}.rs. The wire→domain - // conversion for admit now reuses InboxMessageRequest::to_inbox_message - // (ipc/protocol.rs), the one canonical seam. - - // ================================================================ - // Vision Describe (continuum#1276) — MIGRATED to the typed registry. - // ================================================================ - // `cognition/vision-describe` is now a dep-holding `ActionCommand` in - // `crate::commands::cognition::vision_describe` (captures this module's - // shared `Arc>` and delegates to - // `describe_image`). It reaches the registry via - // `CognitionModule::commands()`. `access: Internal`. No match arm here. - - // ================================================================ - // AI Gating — MIGRATED to the typed registry. - // ================================================================ - // `cognition/should-respond` is now a stateless `ActionCommand` in - // `crate::commands::cognition` (it calls `evaluate_gating` over its typed - // request). `route_object` dispatches them via `command_registry()`, - // so they reach the ACL, codegen, `uu`, and grid routing. Both are - // `access: Internal`. No match arm here — a second registration would be - // the only place they could collide, and there is none. - - // ================================================================ - // Response Generation + Tool Embedding + Validate-Decision - // ================================================================ - // cognition/generate-response, cognition/embed-tools, - // cognition/semantic-search-tools, and cognition/validate-response-decision - // migrated to the typed DynCommand registry as stateless unit-struct - // action_command!s — see commands/cognition/{generate_response,embed_tools, - // semantic_search_tools,validate_response_decision}.rs (access: Internal, no - // module state — they self-route via inventory). - - // ================================================================ - // Message Deduplication (single source of truth in Rust) - // ================================================================ - // cognition/has-evaluated + cognition/mark-evaluated migrated to the typed - // DynCommand registry — see commands/cognition/{has_evaluated,mark_evaluated}.rs - // (dep-holding on CognitionState, access: Internal). - - // ================================================================ - // Unified Evaluation (6-gate pipeline, single lock) - // ================================================================ - // cognition/full-evaluate migrated to the typed DynCommand registry as a - // dep-holding action_command! (captures this module's Arc, - // takes the persona's rate_limiter + sleep_state + engine + message_cache under - // one DashMap read lock) — see commands/cognition/full_evaluate.rs (access: - // Internal), exposed via CognitionModule::commands(). The typed - // FullEvaluateRequest params deserialize the whole payload in one step - // (SenderType's lowercase serde matches the old parse_sender_type; the three - // legacy-defaulted fields carry #[serde(default)]); a request for a persona with - // no live cognition engine fails loud as CommandError::NotFound. - - // cognition/track-response migrated to the typed DynCommand registry — see - // commands/cognition/track_response.rs (dep-holding on CognitionState, - // access: Internal). - - // cognition/set-sleep-mode + cognition/configure-rate-limiter migrated to the - // typed DynCommand registry (Slice 6) — see - // commands/cognition/{set_sleep_mode,configure_rate_limiter}.rs (dep-holding on - // CognitionState, access: Internal). - - // ================================================================= - // Model Selection + Adapter Sync - // ================================================================= - // cognition/select-model and cognition/sync-adapters migrated to the typed - // DynCommand registry as dep-holding action_command!s capturing CognitionState - // — see commands/cognition/{select_model,sync_adapters}.rs (access: Internal), - // exposed via commands/cognition/mod.rs::command_objects. - - // ================================================================= - // Genome Paging (LRU eviction + memory budget decisions) - // ================================================================= - // Migrated to the typed DynCommand registry (Slice 4): - // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). - - // ================================================================= - // Recipe generation (continuum#1295 PR-2) - // ================================================================= - // cognition/generate-recipe migrated to the typed DynCommand registry as a - // stateless async action_command! unit struct (free fn generate_recipe_with_ai, - // no CognitionState) — see commands/cognition/generate_recipe.rs (access: - // Internal). Params ARE a typed GenerateRecipeOrchestratorParams (the whole - // { request, provider?, model?, temperature? } payload deserializes in one - // step, same wire shape as the p.json("request") + p.str_opt/p.f32_opt reads - // here); inference/parser failures fail loud as CommandError::Internal while - // structural-validation findings ride back in the response. - - // ================================================================= - // Peer-review proposal rating (continuum#1289 PR-2) - // ================================================================= - // cognition/rate-proposals migrated to the typed DynCommand registry as a - // stateless async action_command! unit struct (free fn rate_proposals_with_ai, - // no CognitionState) — see commands/cognition/rate_proposals.rs (access: - // Internal). Params ARE a typed RateProposalsRequest (the whole payload - // deserializes 1:1, as the legacy arm did via from_value(params)); a rater - // that produces no usable judgment fails loud as CommandError::Internal, no - // fabricated degraded score. - - // ================================================================= - // Recipe/RAG turn batching boundary - // ================================================================= - // cognition/plan-turn-batch migrated to the typed DynCommand registry as a - // stateless action_command! unit struct (pure sync free fn, no CognitionState) - // — see commands/cognition/plan_turn_batch.rs (access: Internal). The params - // ARE a typed RecipeTurnBatchRequest now, flattening the legacy - // `{ request: {...} }` envelope, and deserialize fails loud on a bad payload. - - // ================================================================= - // Domain Classification (adapter-aware keyword scoring) - // ================================================================= - // Migrated to the typed DynCommand registry (Slice 5): - // cognition/classify-domain → commands/cognition/classify_domain.rs - // cognition/register-domain-keywords → commands/cognition/register_domain_keywords.rs - // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). - - // ================================================================= - // Domain Activity Tracking & Gap Detection - // ================================================================= - // Migrated to the typed DynCommand registry (Slice 4): - // Exposed via commands/cognition/mod.rs::command_objects (dep-holding on CognitionState). - - // ================================================================= - // GPU Budget Query (for TypeScript genome initialization) - // ================================================================= - // cognition/gpu-budget migrated to the typed DynCommand registry as a - // dep-holding action_command! (captures this module's Arc, - // reads its optional GpuMemoryManager) — see commands/cognition/gpu_budget.rs - // (access: Internal), exposed via CognitionModule::commands(). The typed - // GpuBudgetInfo output replaces the hand-built serde_json::json! object; the - // GPU-present / CPU-only branches are honest runtime states (no-GPU reports a - // zeroed device + the CPU per-persona floor), not a happy-path + fallback. - - // ================================================================= - // Interaction Quality Scoring + Post-Inference Adequacy Check - // ================================================================= - // cognition/score-interaction and cognition/check-adequacy migrated to the - // typed DynCommand registry as stateless action_command! unit structs (they - // wrap pure sync free fns — no CognitionState) — see - // commands/cognition/{score_interaction,check_adequacy}.rs (access: Internal). - // The typed Vec params deserialize fails loud on a malformed - // batch, replacing the legacy filter_map(..ok()) silent-drop. - - // ================================================================= - // Message Cache (echo chamber + post-inference adequacy) - // ================================================================= - // ================================================================ - // Recent-message cache + content dedup — MIGRATED to the typed registry. - // ================================================================ - // `cognition/cache-message`, `cognition/check-content-dedup`, and - // `cognition/record-content` are now dep-holding `ActionCommand`s in - // `crate::commands::cognition` (each captures this module's - // `Arc` and delegates to `get_or_create_persona` + - // the per-persona `message_cache` / `content_dedup`). They reach the - // registry via `CognitionModule::commands()`. All `access: Internal`. - _ => Err(format!("Unknown cognition command: {command}")), - } + /// Every cognition command is a typed object on the one registry (`commands()`), its params + /// decoded by serde at the boundary. Reaching this legacy path means a command name no + /// object registered. + async fn handle_command(&self, command: &str, _params: Value) -> Result { + Err(format!("Unknown cognition command: {command}")) } fn commands(&self) -> Vec> { @@ -685,40 +452,3 @@ mod turn_frame_recording_tests { } } } - -// ============================================================================ -// Parsing helpers -// ============================================================================ - -fn parse_sender_type(s: &str) -> Result { - match s { - "human" => Ok(SenderType::Human), - "persona" => Ok(SenderType::Persona), - "agent" => Ok(SenderType::Agent), - "system" => Ok(SenderType::System), - _ => Err(format!("Invalid sender_type: {s}")), - } -} - -/// Parse an InboxMessage from JSON value. -fn parse_inbox_message(value: &Value) -> Result { - let p = Params::new(value); - - Ok(InboxMessage { - id: p.uuid("id")?, - room_id: p.uuid("room_id")?, - sender_id: p.uuid("sender_id")?, - sender_name: p.str("sender_name")?.to_string(), - sender_type: parse_sender_type(p.str("sender_type")?)?, - content: p.str("content")?.to_string(), - timestamp: p.u64("timestamp")?, - priority: p.f32_or("priority", 0.5), - source_modality: p.str_opt("source_modality").map(|m| match m { - "voice" => Modality::Voice, - _ => Modality::Chat, - }), - voice_session_id: p - .str_opt("voice_session_id") - .and_then(|s| Uuid::parse_str(s).ok()), - }) -} diff --git a/core/continuum-mind/src/persona/card_hands.rs b/core/continuum-mind/src/persona/card_hands.rs index 3ac0d5347d..d23b51da7c 100644 --- a/core/continuum-mind/src/persona/card_hands.rs +++ b/core/continuum-mind/src/persona/card_hands.rs @@ -435,7 +435,7 @@ pub(crate) async fn drive_in_held_card( stimulus: &str, burst: crate::cognition::workspace::Burst, framing: crate::cognition::workspace::TurnFraming, - max_acts: usize, + max_acts: crate::cognition::act_observe::TurnBudget, conversation: &mut dyn CitizenConversation, ) -> ( crate::cognition::act_observe::SettleOutcome, diff --git a/core/continuum-mind/src/persona/service_loop/beat_outcome.rs b/core/continuum-mind/src/persona/service_loop/beat_outcome.rs index f87315ff3f..78dca1ef1e 100644 --- a/core/continuum-mind/src/persona/service_loop/beat_outcome.rs +++ b/core/continuum-mind/src/persona/service_loop/beat_outcome.rs @@ -52,12 +52,12 @@ pub(super) const SELF_TICK_REST_CAP_MS: u64 = 240_000; /// ceiling on a being's own hands, contradicting the written doctrine on the /// same page (an "acts-forever" persona is a fitness gap to TRAIN, never a /// substrate cap — ACTING-ORGANISM §4). The perception kit ([repetition], -/// actual-result fixed-point guard) is how a looping mind notices itself. Three -/// consecutive repeats of both request and result yield the turn without declaring -/// its work complete; changed results reset that streak. The external -/// stopwatch that remains is the eval grader's `max_acts` — a proctored exam's -/// clock, held by the observer, never wired into life. -pub(crate) const LIVE_MAX_ACTS: usize = usize::MAX; +/// actual-result fact) is how a looping mind notices itself: a repeat is a fact she +/// weighs, never a substrate stop. The external stopwatch that remains is an eval's +/// bounded `TurnBudget::Steps`, held by the observer, never wired into life. Typed, +/// so "no limit" is a variant, never a number standing for one (2026-11-02). +pub(crate) const LIVE_MAX_ACTS: crate::cognition::act_observe::TurnBudget = + crate::cognition::act_observe::TurnBudget::Unbounded; /// What woke the service loop this cycle. A message from the wire, the never-stop /// heartbeat, or the end of the stream. Returned by the `select!` so the borrow of diff --git a/core/continuum-sentinel/src/steps/llm.rs b/core/continuum-sentinel/src/steps/llm.rs index 6074cf9832..814eb22c80 100644 --- a/core/continuum-sentinel/src/steps/llm.rs +++ b/core/continuum-sentinel/src/steps/llm.rs @@ -42,33 +42,7 @@ pub async fn execute( } } -/// Maximum retry attempts for transient LLM API errors -const LLM_MAX_RETRIES: u32 = 3; -/// Base delay between retries (doubles each attempt) -const LLM_RETRY_BASE_MS: u64 = 2000; - -/// Check if an error message indicates a transient API failure worth retrying -fn is_transient_error(error: &str) -> bool { - let lower = error.to_lowercase(); - lower.contains("error decoding response body") - || lower.contains("error sending request") - || lower.contains("connection reset") - || lower.contains("connection closed") - || lower.contains("connection refused") - || lower.contains("broken pipe") - || lower.contains("timeout") - || lower.contains("timed out") - || lower.contains("502 bad gateway") - || lower.contains("503 service") - || lower.contains("500 internal server") - || lower.contains("429 too many") - || lower.contains("rate limit") - || lower.contains("eof while parsing") - || lower.contains("unexpected eof") -} - -/// agentMode=false: Fast in-process Rust call to ai/generate via ModuleRegistry -/// Includes retry with exponential backoff for transient API errors. +/// agentMode=false: Fast in-process Rust call to ai/generate via ModuleRegistry. async fn execute_generate_mode( params: LlmStepParams<'_>, index: usize, @@ -94,41 +68,40 @@ async fn execute_generate_mode( params.temperature, )); - let mut ai_params = json!({ - "prompt": interpolated_prompt, - }); - - if let Some(m) = params.model { - ai_params["model"] = json!(m); - } - if let Some(p) = params.provider { - ai_params["provider"] = json!(p); - } - if let Some(t) = params.max_tokens { - ai_params["max_tokens"] = json!(t); - } - if let Some(temp) = params.temperature { - ai_params["temperature"] = json!(temp); - } - if let Some(sys) = interpolated_system { - ai_params["system_prompt"] = json!(sys); - } - - // Interpolate and pass active LoRA adapters - if let Some(adapters) = params.active_adapters { - if !adapters.is_empty() { - let interpolated: Vec = adapters + // The typed request ai/generate decodes: one wire shape, every field name checked by the + // compiler. An adapter config that does not decode after interpolation is an error, never a + // silent fall back to the uninterpolated one. + let active_adapters = params + .active_adapters + .filter(|adapters| !adapters.is_empty()) + .map(|adapters| { + adapters .iter() .map(|adapter| { - // Interpolate string values within each adapter config - let json_str = serde_json::to_string(adapter).unwrap_or_default(); - let interpolated_str = interpolation::interpolate(&json_str, ctx); - serde_json::from_str(&interpolated_str).unwrap_or_else(|_| adapter.clone()) + let raw = serde_json::to_string(adapter) + .map_err(|e| format!("[{}] active adapter does not encode: {e}", pipeline_ctx.handle_id))?; + let interpolated = interpolation::interpolate(&raw, ctx); + serde_json::from_str::(&interpolated) // decode boundary: the step's adapter config, typed + .map_err(|e| format!("[{}] active adapter does not decode after interpolation: {e}", pipeline_ctx.handle_id)) }) - .collect(); - ai_params["activeAdapters"] = json!(interpolated); - } - } + .collect::, String>>() + }) + .transpose()?; + let request = continuum_engine::ai::TextGenerationRequest { + messages: vec![continuum_engine::ai::ChatMessage { + role: "user".to_string(), + content: continuum_engine::ai::MessageContent::Text(interpolated_prompt.clone()), + name: None, + }], + system_prompt: interpolated_system, + model: params.model.map(str::to_string), + provider: params.provider.map(str::to_string), + max_tokens: params.max_tokens, + temperature: params.temperature, + active_adapters, + ..Default::default() + }; + let ai_params = serde_json::to_value(&request).map_err(|e| format!("[{}] request does not encode: {e}", pipeline_ctx.handle_id))?; let (module, cmd) = pipeline_ctx .registry @@ -140,121 +113,52 @@ async fn execute_generate_mode( ) })?; - // Retry loop for transient API errors - let mut last_error = String::new(); - for attempt in 0..=LLM_MAX_RETRIES { - if attempt > 0 { - let delay_ms = LLM_RETRY_BASE_MS * (1 << (attempt - 1)); // 2s, 4s, 8s - log.warn(&format!( - "[{}] LLM retry {}/{} after {}ms (error: {})", - pipeline_ctx.handle_id, attempt, LLM_MAX_RETRIES, delay_ms, last_error - )); - tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await; + // One call. Whether an inference failure is worth retrying is the inference owner's typed + // judgment (`InferenceError::is_retryable_unchanged`), never re-derived here by matching + // substrings of error text under a guessed count; a failed generation fails the step, + // visibly (2026-11-02). + let result = module.handle_command(&cmd, ai_params).await; + let duration_ms = start.elapsed().as_millis() as u64; + match result { + Ok(CommandResult::Json(json)) => { + let success = json.get("success").and_then(Value::as_bool) == Some(true); + let text = json.get("text").and_then(Value::as_str).map(str::to_string); + let error = json.get("error").and_then(Value::as_str).map(str::to_string); + Ok(StepResult { + step_index: index, + step_type: "llm".to_string(), + success, + duration_ms, + output: text, + error, + exit_code: None, + data: json, + }) } - - let result = module.handle_command(&cmd, ai_params.clone()).await; - - match result { - Ok(CommandResult::Json(json)) => { - let success = json - .get("success") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let text = json - .get("text") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - let error = json - .get("error") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - let duration_ms = start.elapsed().as_millis() as u64; - - // If the API returned an error that looks transient, retry - if !success { - if let Some(ref err_msg) = error { - if is_transient_error(err_msg) && attempt < LLM_MAX_RETRIES { - last_error = err_msg.clone(); - continue; - } - } - } - - return Ok(StepResult { - step_index: index, - step_type: "llm".to_string(), - success, - duration_ms, - output: text, - error, - exit_code: None, - data: json, - }); - } - Ok(CommandResult::Binary { .. }) => { - return Err(step_err( - pipeline_ctx.handle_id, - "LLM step", - "unexpected binary response from ai/generate", - )); - } - // Cell shapes from MODULE-ARCHITECTURE.md §5.1 — ai/generate - // should always return Json; receiving any other shape is a - // contract violation we surface as a step error rather than - // silently dropping. The Handle shape is the natural future - // home for streaming inference sessions (start → handle → - // poll), but ai/generate (one-shot completion) stays Json. - Ok(CommandResult::Handle(h)) => { - return Err(step_err( - pipeline_ctx.handle_id, - "LLM step", - format!( - "ai/generate must return Json, got Handle (owner={}, type={}); \ - streaming inference belongs on a different command, not the \ - one-shot generate path", - h.owner, h.type_tag - ), - )); - } - Ok(CommandResult::Stream(_)) => { - return Err(step_err( - pipeline_ctx.handle_id, - "LLM step", - CommandResult::stream_protocol_error(), - )); - } - Ok(CommandResult::Lambda(_)) => { - return Err(step_err( - pipeline_ctx.handle_id, - "LLM step", - CommandResult::lambda_protocol_error(), - )); - } - Err(e) => { - if is_transient_error(&e) && attempt < LLM_MAX_RETRIES { - last_error = e; - continue; - } - return Err(step_err(pipeline_ctx.handle_id, "LLM step", e)); - } + Ok(CommandResult::Binary { .. }) => Err(step_err( + pipeline_ctx.handle_id, + "LLM step", + "unexpected binary response from ai/generate", + )), + // Cell shapes from MODULE-ARCHITECTURE.md §5.1: ai/generate always returns Json; any + // other shape is a contract violation surfaced as a step error, never dropped. + Ok(CommandResult::Handle(h)) => Err(step_err( + pipeline_ctx.handle_id, + "LLM step", + format!( + "ai/generate must return Json, got Handle (owner={}, type={}); streaming \ + inference belongs on a different command, not the one-shot generate path", + h.owner, h.type_tag + ), + )), + Ok(CommandResult::Stream(_)) => { + Err(step_err(pipeline_ctx.handle_id, "LLM step", CommandResult::stream_protocol_error())) + } + Ok(CommandResult::Lambda(_)) => { + Err(step_err(pipeline_ctx.handle_id, "LLM step", CommandResult::lambda_protocol_error())) } + Err(e) => Err(step_err(pipeline_ctx.handle_id, "LLM step", e)), } - - // All retries exhausted - let duration_ms = start.elapsed().as_millis() as u64; - Ok(StepResult { - step_index: index, - step_type: "llm".to_string(), - success: false, - duration_ms, - output: None, - error: Some(format!( - "LLM failed after {} retries: {}", - LLM_MAX_RETRIES, last_error - )), - exit_code: None, - data: Value::Null, - }) } /// agentMode=true: Route to TypeScript ai/agent via CommandExecutor (Unix socket IPC) diff --git a/core/continuum-tool-protocol/Cargo.toml b/core/continuum-tool-protocol/Cargo.toml index b7a7491067..cba475448f 100644 --- a/core/continuum-tool-protocol/Cargo.toml +++ b/core/continuum-tool-protocol/Cargo.toml @@ -8,3 +8,4 @@ serde = { workspace = true } serde_json = { workspace = true } uuid = { version = "1", features = ["v4"] } ts-rs.workspace = true +schemars = { workspace = true } diff --git a/core/continuum-tool-protocol/src/lib.rs b/core/continuum-tool-protocol/src/lib.rs index 3ad88e8e1b..95a479163d 100644 --- a/core/continuum-tool-protocol/src/lib.rs +++ b/core/continuum-tool-protocol/src/lib.rs @@ -11,7 +11,7 @@ pub mod parser; /// - `input_schema` NOT `inputSchema` /// This must NOT use rename_all = "camelCase" because the wire format /// from TypeScript AND the Anthropic API both use snake_case for this struct. -#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, TS)] +#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/NativeToolSpec.ts" @@ -24,7 +24,7 @@ pub struct NativeToolSpec { /// JSON Schema for tool input parameters. /// Matches Anthropic API wire format (snake_case field names). -#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, TS)] +#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] #[ts( export, export_to = "../../../protocol/typescript/ai/ToolInputSchema.ts" diff --git a/protocol/typescript/ai/GenerateParams.ts b/protocol/typescript/ai/GenerateParams.ts new file mode 100644 index 0000000000..f07813f14c --- /dev/null +++ b/protocol/typescript/ai/GenerateParams.ts @@ -0,0 +1,80 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ActiveAdapterRequest } from "./ActiveAdapterRequest"; +import type { ChatMessage } from "./ChatMessage"; +import type { NativeToolSpec } from "./NativeToolSpec"; +import type { ResponseFormat } from "./ResponseFormat"; +import type { ToolChoice } from "./ToolChoice"; + +/** + * The params of `ai/generate`: the inference request itself, plus the stream a caller + * registered a sink under (`stream_sinks::register`), which the airc responder stamps so + * every chunk reaches the remote mind as it is produced. The stream is the call's, never + * the request's; a plain call has none and gets the assembled response. + */ +export type GenerateParams = { streamId?: string, messages: Array, systemPrompt?: string, model?: string, provider?: string, temperature?: number, maxTokens?: number, topP?: number, topK?: number, repeatPenalty?: number, +/** + * llama.cpp-native, UNWINDOWED repetition guard: scales each token's penalty by how + * often it has appeared across the ENTIRE generation (unlike `repeat_penalty`, which + * only scans the last `repeat_last_n` tokens). Catches gap-separated loops — a code + * block re-emitted many times regardless of the text between (#181). `None` → the + * adapter's llama.cpp default (0.3). Joins the Model row with the other sampling + * knobs under #76. Ignored by cloud OpenAI-compat providers. + */ +frequencyPenalty?: number, +/** + * Window (trailing tokens) that `repeat_penalty` scans on llama.cpp- + * family gateways. `None` → the gateway's own default (64). Widened + * by the substrate sampling defaults to catch loops whose span + * exceeds 64 tokens (#181). Ignored by cloud OpenAI-compat providers. + */ +repeatLastN?: number, stopSequences?: Array, tools?: Array, +/** + * Verbs she loaded into the TAIL this epoch: callable natively (the engine's parser and + * grammar accept them) but never rendered in the head, so the cached prefix is unchanged + * (goal 10, card ecd5dff3). Their schemas ride the conversation, after the cache point. + * Sent only to a llama.cpp-family server; one that predates the field ignores it. + */ +tailTools?: Array, +/** + * How many leading `messages` are her view: the epoch's append-only part, which her next + * act sends again unchanged, before this act's fresh tail. A llama.cpp-family engine + * checkpoints her recurrent state exactly there, and a saved page keeps that checkpoint, + * so a page-in resumes at the end of her view rather than at the shared head (card + * 3512f496). `None` when the prompt has no view. + */ +viewMessages?: number, toolChoice?: ToolChoice, +/** + * Force the model to output a specific format (e.g. JSON object). + * OpenAI-compatible: serializes as `{"type": "json_object"}` etc. The + * underlying llama.cpp / DMR pathway respects this and constrains the + * sampler so the model can ONLY emit valid JSON. Removes the + * "qwen3.5 emits 'Thinking Process:' prose instead of JSON" failure + * mode at the source instead of papering over it with a parser + * fallback (banned by the 'no fallbacks' directive). + */ +responseFormat?: ResponseFormat, activeAdapters?: Array, requestId?: string, userId?: string, roomId?: string, purpose?: string, +/** + * Persona generating this request — the inference's "owner" for + * per-persona resource attribution (KV cache bytes, GPU pressure, + * recipe budgets). Wire format is a stringified UUID; the local + * adapter parses to `uuid::Uuid` at the Rust boundary. None = the + * inference is not attributable to a persona (test rigs, ad-hoc + * system probes, benchmarks). Production paths through + * PersonaResponseGenerator MUST set this — without it the registry + * can't tell whose conversation owns this seq's KV slot, and the + * pressure policy can't make per-persona eviction decisions. + * See docs/architecture/PERSONA-CONTEXT-PAGING.md §13. + */ +personaId?: string, +/** + * The bound this turn is owed on the wire, sized from the MEASURED work: the mind's + * expected occupancy (the uncached prompt at the box's measured prefill rate plus + * her last output at its decode rate) with headroom — `inference::turn_bound`. + * Every waiting seam takes `max(its floor, this)`: the header wait, the stream's + * queue budget, the remote deadline. So a slow box's long prefill is waited out + * instead of read as dead (card ba82d0a0: a 30k prompt at 25 tok/s is ~1200 s + * before the first byte, past every fixed bound). `None` = no expectation yet; the + * floors govern alone. Serialized as serde's `{secs, nanos}` so the SERVING peer's + * lane honours it too. + */ +turnBound?: { secs: number, nanos: number }, }; diff --git a/protocol/typescript/ai/index.ts b/protocol/typescript/ai/index.ts index 5667c9f9e3..4e62b283d6 100644 --- a/protocol/typescript/ai/index.ts +++ b/protocol/typescript/ai/index.ts @@ -11,6 +11,7 @@ export type { EmbeddingInput } from './EmbeddingInput'; export type { EmbeddingRequest } from './EmbeddingRequest'; export type { EmbeddingResponse } from './EmbeddingResponse'; export type { FinishReason } from './FinishReason'; +export type { GenerateParams } from './GenerateParams'; export type { HealthState } from './HealthState'; export type { HealthStatus } from './HealthStatus'; export type { ImageInput } from './ImageInput'; diff --git a/protocol/typescript/cognition/AdmitInboxMessageParams.ts b/protocol/typescript/cognition/AdmitInboxMessageParams.ts index 82e4eb752b..5c9574b2b3 100644 --- a/protocol/typescript/cognition/AdmitInboxMessageParams.ts +++ b/protocol/typescript/cognition/AdmitInboxMessageParams.ts @@ -1,5 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { InboxMessageRequest } from "../ipc/InboxMessageRequest"; +import type { InboxMessage } from "../persona/InboxMessage"; export type AdmitInboxMessageParams = { /** @@ -7,6 +7,6 @@ export type AdmitInboxMessageParams = { */ personaId: string, /** - * The message to admit (JSON-transport shape, string UUIDs + string enums). + * The message to admit (decoded by serde at the boundary: typed ids and enums). */ -message: InboxMessageRequest, }; +message: InboxMessage, }; diff --git a/protocol/typescript/cognition/CalculatePriorityParams.ts b/protocol/typescript/cognition/CalculatePriorityParams.ts new file mode 100644 index 0000000000..c2f8f16283 --- /dev/null +++ b/protocol/typescript/cognition/CalculatePriorityParams.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SenderType } from "../persona/SenderType"; + +export type CalculatePriorityParams = { persona_id: string, content: string, sender_type: SenderType, is_voice: boolean, room_id: string, timestamp: number, }; diff --git a/protocol/typescript/cognition/EnqueueMessageParams.ts b/protocol/typescript/cognition/EnqueueMessageParams.ts index f149b14477..ea0b8a536f 100644 --- a/protocol/typescript/cognition/EnqueueMessageParams.ts +++ b/protocol/typescript/cognition/EnqueueMessageParams.ts @@ -1,5 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { InboxMessageRequest } from "../ipc/InboxMessageRequest"; +import type { InboxMessage } from "../persona/InboxMessage"; export type EnqueueMessageParams = { /** @@ -7,6 +7,6 @@ export type EnqueueMessageParams = { */ personaId: string, /** - * The message to enqueue (JSON-transport shape, string UUIDs + string enums). + * The message to enqueue (decoded by serde at the boundary: typed ids and enums). */ -message: InboxMessageRequest, }; +message: InboxMessage, }; diff --git a/protocol/typescript/cognition/FastPathDecisionParams.ts b/protocol/typescript/cognition/FastPathDecisionParams.ts new file mode 100644 index 0000000000..a692cfa312 --- /dev/null +++ b/protocol/typescript/cognition/FastPathDecisionParams.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { InboxMessage } from "../persona/InboxMessage"; + +export type FastPathDecisionParams = { persona_id: string, message: InboxMessage, }; diff --git a/protocol/typescript/cognition/index.ts b/protocol/typescript/cognition/index.ts index 2728442a52..8b9d183707 100644 --- a/protocol/typescript/cognition/index.ts +++ b/protocol/typescript/cognition/index.ts @@ -2,9 +2,6 @@ // Source: generator/generate-rust-bindings.ts // Re-generate: npx tsx generator/generate-rust-bindings.ts -export type { AIDecisionContext } from './AIDecisionContext'; -export type { AIGatingDecision } from './AIGatingDecision'; -export type { AIGatingDecisionFactors } from './AIGatingDecisionFactors'; export type { ActOutcome } from './ActOutcome'; export type { ActStatus } from './ActStatus'; export type { AdaptiveThroughputPlan } from './AdaptiveThroughputPlan'; @@ -12,19 +9,20 @@ export type { AdaptiveThroughputRequest } from './AdaptiveThroughputRequest'; export type { AdmitInboxMessageParams } from './AdmitInboxMessageParams'; export type { AdmitInboxMessageResult } from './AdmitInboxMessageResult'; export type { AdversarialPatternDecline } from './AdversarialPatternDecline'; +export type { AIDecisionContext } from './AIDecisionContext'; +export type { AIGatingDecision } from './AIGatingDecision'; +export type { AIGatingDecisionFactors } from './AIGatingDecisionFactors'; export type { AuditEntry } from './AuditEntry'; export type { AuditEntryKind } from './AuditEntryKind'; -export type { Central } from './BenchmarkCentral'; -export type { FeedEvent } from './BenchmarkFeedEvent'; -export type { Meta } from './BenchmarkMeta'; export type { BenchmarkObserveParams } from './BenchmarkObserveParams'; export type { BenchmarkObserveResult } from './BenchmarkObserveResult'; export type { BenchmarkProvenance } from './BenchmarkProvenance'; -export type { Scoreboard } from './BenchmarkScoreboard'; export type { CacheMessageParams } from './CacheMessageParams'; export type { CacheMessageResult } from './CacheMessageResult'; +export type { CalculatePriorityParams } from './CalculatePriorityParams'; export type { CallHeader } from './CallHeader'; export type { CallStatus } from './CallStatus'; +export type { Central } from './BenchmarkCentral'; export type { CheckAdequacyRequest } from './CheckAdequacyRequest'; export type { CheckContentDedupParams } from './CheckContentDedupParams'; export type { CheckContentDedupResult } from './CheckContentDedupResult'; @@ -49,6 +47,8 @@ export type { EnqueueMessageParams } from './EnqueueMessageParams'; export type { EnqueueMessageResult } from './EnqueueMessageResult'; export type { EvalPassProgress } from './EvalPassProgress'; export type { EvalTask } from './EvalTask'; +export type { FastPathDecisionParams } from './FastPathDecisionParams'; +export type { FeedEvent } from './BenchmarkFeedEvent'; export type { ForgetContextParams } from './ForgetContextParams'; export type { ForgetContextResult } from './ForgetContextResult'; export type { GatingConversationMessage } from './GatingConversationMessage'; @@ -68,7 +68,6 @@ export type { GpuBudgetParams } from './GpuBudgetParams'; export type { HasEvaluatedParams } from './HasEvaluatedParams'; export type { HasEvaluatedResult } from './HasEvaluatedResult'; export type { HostCapability } from './HostCapability'; -export type { ProbeError } from './HostProbeError'; export type { HwCapabilityTier } from './HwCapabilityTier'; export type { InboxCreateParams } from './InboxCreateParams'; export type { InboxCreateResult } from './InboxCreateResult'; @@ -79,6 +78,7 @@ export type { LocalOrCloudPolicy } from './LocalOrCloudPolicy'; export type { MarkEvaluatedParams } from './MarkEvaluatedParams'; export type { MarkEvaluatedResult } from './MarkEvaluatedResult'; export type { MediaItemLite } from './MediaItemLite'; +export type { Meta } from './BenchmarkMeta'; export type { ModelRequirement } from './ModelRequirement'; export type { NativeBatchOutcome } from './NativeBatchOutcome'; export type { Observation } from './Observation'; @@ -90,6 +90,7 @@ export type { PersonaRosterEntry } from './PersonaRosterEntry'; export type { PersonaTurnPlan } from './PersonaTurnPlan'; export type { PlaybackDetail } from './PlaybackDetail'; export type { PlaybackPage } from './PlaybackPage'; +export type { ProbeError } from './HostProbeError'; export type { ProposalRating } from './ProposalRating'; export type { RateProposalsRequest } from './RateProposalsRequest'; export type { RateProposalsResponse } from './RateProposalsResponse'; @@ -120,6 +121,7 @@ export type { ResourceAdmissionPolicy } from './ResourceAdmissionPolicy'; export type { ResourceClass } from './ResourceClass'; export type { ResponseDecision } from './ResponseDecision'; export type { ResponseProposal } from './ResponseProposal'; +export type { Scoreboard } from './BenchmarkScoreboard'; export type { ScoreInteractionRequest } from './ScoreInteractionRequest'; export type { SemanticSearchResult } from './SemanticSearchResult'; export type { SemanticSearchToolsRequest } from './SemanticSearchToolsRequest'; diff --git a/protocol/typescript/ipc/InboxMessageRequest.ts b/protocol/typescript/ipc/InboxMessageRequest.ts deleted file mode 100644 index 2e181cedbd..0000000000 --- a/protocol/typescript/ipc/InboxMessageRequest.ts +++ /dev/null @@ -1,11 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Inbox message for IPC (mirrors InboxMessage but with string UUIDs for - * JSON transport). - */ -export type InboxMessageRequest = { id: string, room_id: string, sender_id: string, sender_name: string, sender_type: string, content: string, -/** - * Timestamp in milliseconds (fits in JS number, max safe ~9 quadrillion) - */ -timestamp: number, priority: number, source_modality?: string, voice_session_id?: string, }; diff --git a/protocol/typescript/ipc/index.ts b/protocol/typescript/ipc/index.ts index 09df10dd87..bb2b54dc63 100644 --- a/protocol/typescript/ipc/index.ts +++ b/protocol/typescript/ipc/index.ts @@ -2,4 +2,3 @@ // Source: generator/generate-rust-bindings.ts // Re-generate: npx tsx generator/generate-rust-bindings.ts -export type { InboxMessageRequest } from './InboxMessageRequest'; From 187f84a765c071fde46b3578c12f410e4890778a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 09:26:15 -0600 Subject: [PATCH 2/4] TurnBudget has no From: a bound is spelled TurnBudget::Steps(n), so usize::MAX can never come back as a budget (Cormac's review note on #5704) The drivers take TurnBudget directly; every integer call site names Steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/eval/eval_settle.rs | 2 +- .../src/cognition/act_observe/settle/tests.rs | 2 +- .../cognition/act_observe/settle/tick_deadline.rs | 12 ++++++------ .../src/cognition/act_observe/settle/turn_budget.rs | 6 ------ .../src/cognition/act_observe/tests/drive.rs | 10 +++++----- .../src/cognition/act_observe/tests/investigation.rs | 6 +++--- .../mind_integration/training_credit/directed.rs | 2 +- core/continuum-mind/src/persona/wake_backlog.rs | 2 +- 8 files changed, 18 insertions(+), 24 deletions(-) diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index 8fe8764dbc..e40d03cf11 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -36,7 +36,7 @@ pub(super) async fn eval_settle( crate::cognition::act_observe::drive_to_settle( cycle, burst, - max_acts, + crate::cognition::act_observe::TurnBudget::Steps(max_acts), crate::cognition::workspace::TurnFraming::directed(), ) .await diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 99eaa552d4..8337d81ee0 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -295,7 +295,7 @@ let settled = crate::cognition::act_observe::drive_to_settle_with_input( &cycle, Burst::raw_in(room, "a line".into()), - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::message(TurnAttention::default()), &mut conversation, ) diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs index 46cf927916..94e1c2797f 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs @@ -251,10 +251,10 @@ impl PaceCadence { pub fn drive_to_settle( cycle: &WorkspaceCycle, burst: impl Into, - budget: impl Into, + budget: TurnBudget, framing: TurnFraming, ) -> impl std::future::Future + Send + '_ { - drive_with_input(cycle, burst.into(), budget.into(), framing, None, None) + drive_with_input(cycle, burst.into(), budget, framing, None, None) } /// The live driver leases its existing conversation between steps. No second @@ -262,11 +262,11 @@ pub fn drive_to_settle( pub fn drive_to_settle_with_input<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - budget: impl Into, + budget: TurnBudget, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, ) -> impl std::future::Future + Send + 'a { - drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), None) + drive_with_input(cycle, burst, budget, framing, Some(conversation), None) } /// A live card-linked turn uses the same driver with its own credit capture. @@ -274,14 +274,14 @@ pub fn drive_to_settle_with_input<'a>( pub fn drive_to_settle_with_credit<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - budget: impl Into, + budget: TurnBudget, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, credit: Option<&'a mut dyn TurnCredit>, ) -> impl std::future::Future + Send + 'a { // Return the shared driver directly: an async forwarding wrapper needlessly // nests its state in every live/eval caller and inflates future layout depth. - drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), credit) + drive_with_input(cycle, burst, budget, framing, Some(conversation), credit) } pub(super) async fn drive_with_input<'c>( diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs index ab3eeb80dd..d6e4152f13 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs @@ -39,9 +39,3 @@ impl TurnBudget { } } } - -impl From for TurnBudget { - fn from(steps: usize) -> Self { - Self::Steps(steps) - } -} diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 258b793958..d5ceb81488 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -68,7 +68,7 @@ async fn drive_to_settle_acts_then_settles_on_speak() { let outcome = drive_to_settle( &cycle, "[eval]\npeer: what is 2+2?", - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::ambient(), ) .await; @@ -205,7 +205,7 @@ async fn a_zero_change_speak_reperceives_within_the_turns_step_budget_when_the_w let outcome = drive_to_settle( &cycle, "fix the bug in sympy/core/basic.py", - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::directed().on_workspace(), ) .await; @@ -259,7 +259,7 @@ async fn an_ordinary_turn_still_settles_on_the_first_speak() { assert_eq!( speaker.generations(), - 1, + crate::cognition::act_observe::TurnBudget::Steps(1), "one generation, settled — unchanged" ); assert!( @@ -330,7 +330,7 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable let outcome = drive_to_settle( &cycle, "fix the bug", - 20, + crate::cognition::act_observe::TurnBudget::Steps(20), TurnFraming::ambient().on_workspace(), ) .await; @@ -393,7 +393,7 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { drive_to_settle( &cycle, "fix the bug", - 6, + crate::cognition::act_observe::TurnBudget::Steps(6), TurnFraming::ambient().on_workspace(), ) .await; diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs index 9c988f5e5a..62b1a4c8ff 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs @@ -113,7 +113,7 @@ async fn the_hands_change_the_mind_across_a_multi_act_investigation() { let outcome = drive_to_settle( &cycle, "[eval]\npeer: where does the program start and what does it call?", - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::ambient(), ) .await; @@ -274,7 +274,7 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let a = drive_to_settle( &cycle, "[eval]\npeer: concern A?", - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::ambient(), ) .await; @@ -286,7 +286,7 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let b = drive_to_settle( &cycle, "[eval]\npeer: a totally different concern B?", - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::ambient(), ) .await; diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index cd5d6b3de0..1602f6f359 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -105,7 +105,7 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { let mut drive = Box::pin(drive_to_settle_with_credit( &cycle, "review first card".into(), - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), TurnFraming::ambient(), &mut conversation, Some(&mut capture), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 6b77a393d0..4c73746983 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -696,7 +696,7 @@ mod tests { let completed = drive_to_settle_with_input( &cycle, burst(pending.message().unwrap()), - 8, + crate::cognition::act_observe::TurnBudget::Steps(8), framing, &mut conversation, ) From 467ee965231abb816ba87c93044e7908884163e1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 09:49:41 -0600 Subject: [PATCH 3/4] Revert the From removal on this PR: it moves to its own PR with the eval-harness sweep it requires (fable/turn-budget-no-from-usize) This PR returns to a712b5ca0, the head Codex and Cormac reviewed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/eval/eval_settle.rs | 2 +- .../src/cognition/act_observe/settle/tests.rs | 2 +- .../cognition/act_observe/settle/tick_deadline.rs | 12 ++++++------ .../src/cognition/act_observe/settle/turn_budget.rs | 6 ++++++ .../src/cognition/act_observe/tests/drive.rs | 10 +++++----- .../src/cognition/act_observe/tests/investigation.rs | 6 +++--- .../mind_integration/training_credit/directed.rs | 2 +- core/continuum-mind/src/persona/wake_backlog.rs | 2 +- 8 files changed, 24 insertions(+), 18 deletions(-) diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index e40d03cf11..8fe8764dbc 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -36,7 +36,7 @@ pub(super) async fn eval_settle( crate::cognition::act_observe::drive_to_settle( cycle, burst, - crate::cognition::act_observe::TurnBudget::Steps(max_acts), + max_acts, crate::cognition::workspace::TurnFraming::directed(), ) .await diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 8337d81ee0..99eaa552d4 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -295,7 +295,7 @@ let settled = crate::cognition::act_observe::drive_to_settle_with_input( &cycle, Burst::raw_in(room, "a line".into()), - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::message(TurnAttention::default()), &mut conversation, ) diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs index 94e1c2797f..46cf927916 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs @@ -251,10 +251,10 @@ impl PaceCadence { pub fn drive_to_settle( cycle: &WorkspaceCycle, burst: impl Into, - budget: TurnBudget, + budget: impl Into, framing: TurnFraming, ) -> impl std::future::Future + Send + '_ { - drive_with_input(cycle, burst.into(), budget, framing, None, None) + drive_with_input(cycle, burst.into(), budget.into(), framing, None, None) } /// The live driver leases its existing conversation between steps. No second @@ -262,11 +262,11 @@ pub fn drive_to_settle( pub fn drive_to_settle_with_input<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - budget: TurnBudget, + budget: impl Into, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, ) -> impl std::future::Future + Send + 'a { - drive_with_input(cycle, burst, budget, framing, Some(conversation), None) + drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), None) } /// A live card-linked turn uses the same driver with its own credit capture. @@ -274,14 +274,14 @@ pub fn drive_to_settle_with_input<'a>( pub fn drive_to_settle_with_credit<'a>( cycle: &'a WorkspaceCycle, burst: Burst, - budget: TurnBudget, + budget: impl Into, framing: TurnFraming, conversation: &'a mut dyn crate::cognition::conversation::PersonaConversation, credit: Option<&'a mut dyn TurnCredit>, ) -> impl std::future::Future + Send + 'a { // Return the shared driver directly: an async forwarding wrapper needlessly // nests its state in every live/eval caller and inflates future layout depth. - drive_with_input(cycle, burst, budget, framing, Some(conversation), credit) + drive_with_input(cycle, burst, budget.into(), framing, Some(conversation), credit) } pub(super) async fn drive_with_input<'c>( diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs index d6e4152f13..ab3eeb80dd 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/turn_budget.rs @@ -39,3 +39,9 @@ impl TurnBudget { } } } + +impl From for TurnBudget { + fn from(steps: usize) -> Self { + Self::Steps(steps) + } +} diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index d5ceb81488..258b793958 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -68,7 +68,7 @@ async fn drive_to_settle_acts_then_settles_on_speak() { let outcome = drive_to_settle( &cycle, "[eval]\npeer: what is 2+2?", - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::ambient(), ) .await; @@ -205,7 +205,7 @@ async fn a_zero_change_speak_reperceives_within_the_turns_step_budget_when_the_w let outcome = drive_to_settle( &cycle, "fix the bug in sympy/core/basic.py", - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::directed().on_workspace(), ) .await; @@ -259,7 +259,7 @@ async fn an_ordinary_turn_still_settles_on_the_first_speak() { assert_eq!( speaker.generations(), - crate::cognition::act_observe::TurnBudget::Steps(1), + 1, "one generation, settled — unchanged" ); assert!( @@ -330,7 +330,7 @@ async fn drive_to_settle_gates_discovery_at_half_budget_on_workspace_deliverable let outcome = drive_to_settle( &cycle, "fix the bug", - crate::cognition::act_observe::TurnBudget::Steps(20), + 20, TurnFraming::ambient().on_workspace(), ) .await; @@ -393,7 +393,7 @@ async fn act_budget_facts_reach_working_memory_on_workspace_turns_only() { drive_to_settle( &cycle, "fix the bug", - crate::cognition::act_observe::TurnBudget::Steps(6), + 6, TurnFraming::ambient().on_workspace(), ) .await; diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs index 62b1a4c8ff..9c988f5e5a 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs @@ -113,7 +113,7 @@ async fn the_hands_change_the_mind_across_a_multi_act_investigation() { let outcome = drive_to_settle( &cycle, "[eval]\npeer: where does the program start and what does it call?", - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::ambient(), ) .await; @@ -274,7 +274,7 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let a = drive_to_settle( &cycle, "[eval]\npeer: concern A?", - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::ambient(), ) .await; @@ -286,7 +286,7 @@ async fn it_settles_then_re_awakens_without_cranking_to_a_halt() { let b = drive_to_settle( &cycle, "[eval]\npeer: a totally different concern B?", - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::ambient(), ) .await; diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs index 1602f6f359..cd5d6b3de0 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/directed.rs @@ -105,7 +105,7 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { let mut drive = Box::pin(drive_to_settle_with_credit( &cycle, "review first card".into(), - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, TurnFraming::ambient(), &mut conversation, Some(&mut capture), diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 4c73746983..6b77a393d0 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -696,7 +696,7 @@ mod tests { let completed = drive_to_settle_with_input( &cycle, burst(pending.message().unwrap()), - crate::cognition::act_observe::TurnBudget::Steps(8), + 8, framing, &mut conversation, ) From 5c5a149eb5a8e970e2da590a54148903efd9d9b6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 10:01:40 -0600 Subject: [PATCH 4/4] Drop the imports the typed params left unused (warnings back to the baseline 13): Value, ChatMessage, MessageContent in ai/generate; TimingGuard in modules/cognition; the conversation types move into the only module that uses them, its tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-core/src/commands/ai/generate.rs | 5 ++--- core/continuum-mind/src/modules/cognition.rs | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/core/continuum-core/src/commands/ai/generate.rs b/core/continuum-core/src/commands/ai/generate.rs index 433018243d..1f3046fbfe 100644 --- a/core/continuum-core/src/commands/ai/generate.rs +++ b/core/continuum-core/src/commands/ai/generate.rs @@ -17,13 +17,12 @@ use std::sync::Arc; -use serde_json::Value; use tokio::sync::RwLock; use crate::ai::adapter::InferenceDevice; use crate::ai::{ - AdapterRegistry, ChatMessage, ContentPart, MessageContent, RoutingInfo, TextGenerationRequest, - TextGenerationResponse, ToolCall, UsageMetrics, + AdapterRegistry, ContentPart, RoutingInfo, TextGenerationRequest, TextGenerationResponse, + ToolCall, UsageMetrics, }; use crate::logging::TimingGuard; use crate::ai::adapter::select_failure_message; diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index 7985f26d20..fe836363f5 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -33,10 +33,8 @@ //! cannot be missing past it. use crate::gpu::GpuMemoryManager; -use crate::logging::TimingGuard; use continuum_text_analysis::LoopDetector; use crate::persona::{PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord}; -use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::rag::RagEngine; use crate::runtime::{CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; use async_trait::async_trait; @@ -325,6 +323,7 @@ fn turn_frame_replay_record( #[cfg(test)] mod turn_frame_recording_tests { use super::*; + use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::persona::PersonaInboxFrameMetrics; fn frame_with_messages(messages: Vec) -> PersonaInboxFrame {