diff --git a/.github/workflows/continuum-rust-tests.yml b/.github/workflows/continuum-rust-tests.yml index 964144b097..e8d782eef8 100644 --- a/.github/workflows/continuum-rust-tests.yml +++ b/.github/workflows/continuum-rust-tests.yml @@ -162,9 +162,9 @@ jobs: if: matrix.crate == 'continuum-genome' run: python3 -m unittest discover -s core/continuum-genome/src/genome/fine_tuning -p cuda_train_test.py -v - # ---- continuum-hands, -live, -perception, -genome, -experience, -memory: lib tests ---- + # ---- continuum-hands, -live, -perception, -genome, -experience, -memory, -cognition: lib tests ---- - name: cargo test -p ${{ matrix.crate }} --lib - if: contains(fromJSON('["continuum-hands","continuum-live","continuum-perception","continuum-genome","continuum-experience","continuum-memory"]'), matrix.crate) + if: contains(fromJSON('["continuum-hands","continuum-live","continuum-perception","continuum-genome","continuum-experience","continuum-memory","continuum-cognition"]'), matrix.crate) run: cargo test -p "$CRATE" --lib --profile dev-fast --features "$FEATURES" # ---- continuum-mind: lib tests, compile-fail doc guards ---- diff --git a/Cargo.lock b/Cargo.lock index d77f7166d2..3cf3fb0f1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2834,6 +2834,61 @@ dependencies = [ "uuid", ] +[[package]] +name = "continuum-cognition" +version = "0.1.0" +dependencies = [ + "airc-blobs", + "airc-core", + "airc-lib", + "airc-protocol", + "airc-work", + "arc-swap", + "async-trait", + "base64 0.22.1", + "chrono", + "continuum-airc-protocol", + "continuum-base", + "continuum-cli-lifecycle", + "continuum-client", + "continuum-context", + "continuum-engine", + "continuum-experience", + "continuum-genome", + "continuum-hands", + "continuum-kernel", + "continuum-live", + "continuum-memory", + "continuum-perception", + "continuum-positron", + "dashmap", + "dirs 5.0.1", + "fs2", + "futures", + "futures-util", + "image", + "inventory", + "num_cpus", + "once_cell", + "parking_lot", + "regex", + "reqwest", + "schemars", + "serde", + "serde_json", + "sha2", + "sysinfo", + "tempfile", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "toml 0.8.23", + "tool-working-set", + "tracing", + "ts-rs 12.0.1", + "uuid", +] + [[package]] name = "continuum-context" version = "0.1.0" @@ -2867,6 +2922,7 @@ dependencies = [ "continuum-bridge-protocol", "continuum-cli-lifecycle", "continuum-client", + "continuum-cognition", "continuum-context", "continuum-engine", "continuum-experience", @@ -3218,6 +3274,7 @@ dependencies = [ "continuum-base", "continuum-cli-lifecycle", "continuum-client", + "continuum-cognition", "continuum-context", "continuum-engine", "continuum-experience", @@ -3250,7 +3307,6 @@ dependencies = [ "tokio", "tokio-stream", "toml 0.8.23", - "tool-working-set", "tracing", "ts-rs 12.0.1", "uuid", diff --git a/Cargo.toml b/Cargo.toml index d369519c05..b9a2fce71a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ members = [ "core/continuum-genome", "core/continuum-memory", "core/continuum-experience", + "core/continuum-cognition", "core/continuum-live", "core/continuum-hands", "core/continuum-engine", diff --git a/core/continuum-cognition/Cargo.toml b/core/continuum-cognition/Cargo.toml new file mode 100644 index 0000000000..df3aad97aa --- /dev/null +++ b/core/continuum-cognition/Cargo.toml @@ -0,0 +1,87 @@ +[package] +name = "continuum-cognition" +version = "0.1.0" +edition = "2021" +publish = false +repository = "https://github.com/CambrianTech/continuum" +# Cognition stamps her captures, continuity and handoffs with the build they ran on +# (CONTINUUM_BUILD_GIT_SHA): core's build script is the one owner of that identity. +build = "../continuum-core/build.rs" + +# A mind's thinking (MODULE-ARCHITECTURE.md section 9.2, plan phase 2): the workspace cycle, +# the faculties, act/observe, the conversation contract, memory admission, the dream. Cut out +# of continuum-mind below persona: it names no persona module (source-hygiene +# cognition_names_persona = 0); the verbs persona owns arrive through cognition::extensions, +# which persona fills at boot. The mind re-exports it under its old path. + +[dependencies] +continuum-kernel = { path = "../continuum-kernel" } +continuum-engine = { path = "../continuum-engine" } +continuum-hands = { path = "../continuum-hands" } +continuum-live = { path = "../continuum-live" } +continuum-memory = { path = "../continuum-memory" } +continuum-perception = { path = "../continuum-perception" } +continuum-genome = { path = "../continuum-genome" } +continuum-experience = { path = "../continuum-experience" } +tokio.workspace = true +serde.workspace = true +serde_json.workspace = true +uuid.workspace = true +continuum-base = { path = "../continuum-base" } +continuum-context = { path = "../continuum-context" } +tool-working-set = { path = "../tool-working-set" } # the learned tool head: pure policy, no core dependency +schemars = { version = "0.8", features = ["uuid1"] } +continuum-airc-protocol = { path = "../continuum-airc-protocol" } +continuum-positron = { path = "../continuum-positron" } +continuum-client = { path = "../../client/continuum-client" } +reqwest = { version = "0.12", features = ["json", "multipart", "stream"] } +thiserror.workspace = true +dashmap = "6.1" # Lock-free concurrent HashMap +inventory = "0.3" +fs2 = "0.4" # Cross-platform advisory file locks (flock / LockFileEx) +toml = "0.8" +continuum-cli-lifecycle = { path = "../continuum-cli-lifecycle" } # the CLI's platform lifecycle; its tests must not link this crate +base64 = "0.22" +sha2 = "0.10" # SHA-256 for OAuth 2.0 PKCE code challenges (RFC 7636) + L1-6 contract canonical hash +airc-core.workspace = true +airc-blobs.workspace = true +airc-protocol.workspace = true +airc-lib.workspace = true +airc-work.workspace = true +async-trait.workspace = true +chrono.workspace = true +parking_lot.workspace = true +tokio-stream.workspace = true +futures-util.workspace = true +futures = "0.3" +once_cell.workspace = true +num_cpus = "1.16" # CPU count detection +dirs = "5.0" +sysinfo = "0.33" # Cross-platform CPU, memory, system resource monitoring +tracing.workspace = true +ts-rs.workspace = true # TypeScript type generation +arc-swap = "1.7" # Wait-free policy publish for SubstrateGovernor (Lane H) +image = "0.25" +regex = "1" + +[dev-dependencies] +continuum-kernel = { path = "../continuum-kernel", features = ["test-fixtures"] } # every test build of this crate gets the per-process continuum home (card d11d9827) +tokio = { workspace = true, features = ["test-util"] } +tempfile = "3" +continuum-base = { path = "../continuum-base", features = ["test-fixtures"] } +continuum-client = { path = "../../client/continuum-client", features = ["test-fixtures"] } +continuum-positron = { path = "../continuum-positron", features = ["test-fixtures"] } +continuum-genome = { path = "../continuum-genome", features = ["test-fixtures"] } +continuum-experience = { path = "../continuum-experience", features = ["test-fixtures"] } + +[features] +default = [] +# The GPU backends are the engine's (llama, candle); cognition forwards them so it builds and +# tests on its own with the same flags core takes. +metal = ["continuum-engine/metal", "continuum-live/metal", "continuum-genome/metal"] +cuda = ["continuum-kernel/cuda", "continuum-engine/cuda", "continuum-genome/cuda"] +vulkan = ["continuum-kernel/vulkan", "continuum-engine/vulkan", "continuum-genome/vulkan"] +stress-tests = ["continuum-kernel/stress-tests", "continuum-genome/stress-tests"] +# Test-only code (fixtures shared with core's integration tests, the heuristic adapter it +# drives); production binaries never build with it. +test-fixtures = ["continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "continuum-hands/test-fixtures", "continuum-live/test-fixtures", "continuum-perception/test-fixtures", "continuum-genome/test-fixtures", "continuum-experience/test-fixtures"] diff --git a/core/continuum-mind/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs similarity index 96% rename from core/continuum-mind/src/cognition/act_observe/apply.rs rename to core/continuum-cognition/src/cognition/act_observe/apply.rs index d4af9037a1..2a9c2f3b8c 100644 --- a/core/continuum-mind/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -119,7 +119,7 @@ pub async fn apply_act( }; // Perception and execution share the activity resolved by the bound-turn owner. // Private turns retain their mind room at that boundary. - let private = crate::persona::mind_room::is_private_room(body.persona_id, room_id); + let private = crate::cognition::mind_room::is_private_room(body.persona_id, room_id); // Call history is not a cache-validity proof. Reads can change, failures can // recover, and earlier results may no longer fit the prompt. Execute through @@ -518,19 +518,13 @@ pub async fn apply_act( // the room whose line triggered the turn (`acting_card_of`). let receipt_room = room_id; if private { - crate::persona::mind_room::note_withheld(body.persona_id, "thought_line"); + crate::cognition::mind_room::note_withheld(body.persona_id, "thought_line"); } else if !lines.is_empty() { - if let Some(rt) = crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry::try_global() - .and_then(|reg| reg.get(body.persona_id)) + if let Some(published) = + crate::cognition::extensions::publish_in_room(body.persona_id, receipt_room, lines.join("\n")).await { - match crate::persona::airc_citizen::publish_text_in_room( - rt.airc(), - receipt_room, - &lines.join("\n"), - ) - .await - { - Ok(_) => continuum_base::probe!( + match published { + Ok(()) => continuum_base::probe!( class = "room.work_receipt.published", room = %receipt_room, actor = %body.persona_id, @@ -541,7 +535,7 @@ pub async fn apply_act( class = "room.work_receipt.failed", room = %room_id, actor = %body.persona_id, - error = %e.to_string(), + error = %e, "act receipts did not reach the room transcript — console feed unaffected" ), } @@ -590,14 +584,14 @@ pub async fn apply_act( .first() .map(|c| c.name.clone()) .unwrap_or_else(|| "action".to_string()); - let obs_hash = crate::persona::inbox_admission::content_hash_sha256(&recall_observation); - let self_observation = crate::persona::engram::Engram { + let obs_hash = crate::cognition::inbox_admission::content_hash_sha256(&recall_observation); + let self_observation = crate::cognition::engram::Engram { id: Uuid::new_v4(), context_id: Some(room_id), - kind: crate::persona::engram::EngramKind::Episodic, + kind: crate::cognition::engram::EngramKind::Episodic, content: recall_observation, - origin: crate::persona::engram::EngramOrigin::Tool( - crate::persona::engram::ToolInvocationRef { + origin: crate::cognition::engram::EngramOrigin::Tool( + crate::cognition::engram::ToolInvocationRef { invocation_id: Uuid::new_v4(), tool_name, invoked_at_ms: now_ms, @@ -607,11 +601,11 @@ pub async fn apply_act( ), recall_keys: Vec::new(), admitted_at_ms: now_ms, - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; match body.admission.admit_reflection(self_observation) { - Ok(crate::persona::engram::AdmissionDecision::Admit { engram, .. }) => { + Ok(crate::cognition::engram::AdmissionDecision::Admit { engram, .. }) => { // Belt-and-braces with the recall gate: even excluded from semantic // recall, keep the receipt's stored salience low so any OTHER surface // (recency ranking, dashboards) treats it as proprioception, not @@ -627,7 +621,7 @@ pub async fn apply_act( body.admission.link_engrams( engram.id, prior, - crate::persona::engram_graph::EdgeKind::CausedBy, + crate::cognition::engram_graph::EdgeKind::CausedBy, ); continuum_base::probe!( class = "engram.edge.caused_by", @@ -726,7 +720,7 @@ pub async fn apply_act( // An act that changed a checkout wakes the one carry owner (modules::card_carry), which // carries every resident's committed card work; a turn's end is no longer the only push. if disk == super::disk_change::DiskChange::Changed { - crate::persona::card_carry::request(); + crate::cognition::extensions::request_card_carry(); } ActOutcome::Acted { acts } diff --git a/core/continuum-mind/src/cognition/act_observe/disk_change.rs b/core/continuum-cognition/src/cognition/act_observe/disk_change.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/disk_change.rs rename to core/continuum-cognition/src/cognition/act_observe/disk_change.rs diff --git a/core/continuum-mind/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs similarity index 61% rename from core/continuum-mind/src/cognition/act_observe/mod.rs rename to core/continuum-cognition/src/cognition/act_observe/mod.rs index f33ffcfbe6..87d34041fd 100644 --- a/core/continuum-mind/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -42,7 +42,7 @@ pub(crate) mod disk_change; pub use apply::{apply_act, ActChain}; mod settle; -pub use settle::drive_to_settle_with_credit; +pub use settle::{drive_to_settle_with_credit, TurnCredit}; pub use settle::{drive_to_settle, drive_to_settle_with_input, settle_step}; #[cfg(test)] @@ -63,9 +63,9 @@ pub mod test_support { NativeBatchOutcome, ParsedToolBatch, ToolError, ToolExecutionContext, ToolExecutor, ToolOutcome, }; use crate::cognition::working_memory::WorkingMemory; - use crate::cognition::workspace::ActingBody; - use crate::persona::admission_state::AdmissionState; - use crate::persona::recall_metadata::RecallMetadataRegistry; + use crate::cognition::workspace::{ActingBody, Contribution, Decision, Faculty, FacultyId, Workspace}; + use crate::cognition::admission_state::AdmissionState; + use crate::cognition::recall_metadata::RecallMetadataRegistry; pub fn admission() -> Arc { Arc::new(AdmissionState::new(Arc::new(RecallMetadataRegistry::new()))) @@ -97,8 +97,8 @@ pub mod test_support { pub results: Mutex>, pub input: Mutex< std::collections::VecDeque<( - crate::persona::scripted_conversation::ScriptedConversationFeed, - Vec, + crate::cognition::conversation::scripted_conversation::ScriptedConversationFeed, + Vec, )>, >, pub rooms: Mutex>, @@ -124,8 +124,8 @@ pub mod test_support { } pub fn with_incoming( self, - feed: crate::persona::scripted_conversation::ScriptedConversationFeed, - messages: Vec, + feed: crate::cognition::conversation::scripted_conversation::ScriptedConversationFeed, + messages: Vec, ) -> Self { self.input.lock().unwrap().push_back((feed, messages)); self @@ -266,4 +266,147 @@ pub mod test_support { scope: None, } } + + /// A `ToolExecutor` that records the `context_id` it was handed and returns a + /// canned per-call result — so a test can assert BOTH that the act was scoped + /// to the right room and that the observation correlates call→result. + #[derive(Clone)] + pub struct RecordingExecutor { + pub seen_context: Arc>>, + pub result_content: String, + } + + #[async_trait] + impl ToolExecutor for RecordingExecutor { + fn in_hands(&self, _persona: Uuid, _context: crate::identity::hands_context::HandsContext) -> Option> { + Some(Arc::new(self.clone())) + } + async fn execute_native_batch( + &self, + calls: &[ToolCall], + context: &ToolExecutionContext, + _max_result_chars: usize, + ) -> Result { + *self.seen_context.lock().unwrap() = Some(context.context_id); + let results = calls + .iter() + .map(|c| crate::ai::types::ToolResult { + tool_use_id: c.id.clone(), + content: self.result_content.clone(), + is_error: None, + custody: crate::ai::types::ResultCustody::Unsaved, + }) + .collect(); + Ok(NativeBatchOutcome { + results, + media: Vec::new(), + stored_ids: Vec::new(), + // Test doubles project nothing — the act seam must behave exactly + // as it does for a command that never opted in. + verdicts: Vec::new(), + }) + } + + async fn parse_response( + &self, + _response_text: &str, + _model_family: Option<&str>, + ) -> Result { + Ok(ParsedToolBatch { + tool_calls: Vec::new(), + cleaned_text: String::new(), + parse_time_us: 0, + }) + } + + async fn store_outcome( + &self, + _outcome: &ToolOutcome, + _context: &ToolExecutionContext, + ) -> Result { + Ok(Uuid::nil()) + } + } + + /// Deliberation faculty: reaches for its hands once, then SETTLES into a Speak + /// the moment it perceives a NEW act-observation it has not yet answered — the + /// canonical act→observe arc the driver exists to run. + /// + /// It perceives its own hands through the working-memory proprioception channel + /// (the `WorkingMemoryFaculty` stamps each act `[action #n]`), NOT the deleted + /// world-state fold. It remembers the highest action stamp it has already spoken + /// about (`responded_through`) so that across SEPARATE concerns — where the + /// volatile buffer still carries the prior concern's action — it re-awakens and + /// acts again instead of mistaking old proprioception for "already answered." + /// That is the faculty remembering its own last conclusion (legitimate, content- + /// driven), not an iteration counter in the agentic sense. + pub struct ActThenSpeak { + pub responded_through: std::sync::atomic::AtomicU64, + pub admission_open: Option>, + } + impl ActThenSpeak { + pub fn new() -> Self { + Self { + responded_through: std::sync::atomic::AtomicU64::new(0), + admission_open: None, + } + } + } + /// Highest `[action #N]` stamp present in the assembled perception, 0 if none. + pub fn latest_action_seq(perceived: &str) -> u64 { + perceived + .split("[action #") + .skip(1) + .filter_map(|s| { + let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect(); + digits.parse::().ok() + }) + .max() + .unwrap_or(0) + } + #[async_trait] + impl Faculty for ActThenSpeak { + fn id(&self) -> FacultyId { + FacultyId::Deliberation + } + fn reacts_to_broadcast(&self) -> bool { + true + } + async fn contribute(&self, ws: &Workspace) -> Option { + if self.admission_open.as_ref().is_some_and(|gate| !gate.load(std::sync::atomic::Ordering::SeqCst)) { + return Some(Contribution::deliberation_fault("lane starved before dispatch")); + } + + use std::sync::atomic::Ordering; + let latest = latest_action_seq(&ws.perceived()); + if latest > self.responded_through.load(Ordering::Relaxed) { + self.responded_through.store(latest, Ordering::Relaxed); + Some(Contribution::verdict( + Decision::Speak { + text: "the answer is 4".into(), + }, + 0.9, + "settled after observing a fresh result", + )) + } else { + Some(Contribution::verdict( + Decision::Act { + calls: vec![tool_call()], + intent: "run the code".into(), + }, + 0.9, + "reaching for hands", + )) + } + } + } + + /// The one act every fixture faculty reaches for: run a tiny Rust program. + pub fn tool_call() -> ToolCall { + ToolCall { + id: "call-1".into(), + name: "code/run".into(), + input: serde_json::json!({ "lang": "rust", "code": "fn main() { println!(\"{}\", 2 + 2); }" }), + } + } } diff --git a/core/continuum-mind/src/cognition/act_observe/observation.rs b/core/continuum-cognition/src/cognition/act_observe/observation.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/observation.rs rename to core/continuum-cognition/src/cognition/act_observe/observation.rs diff --git a/core/continuum-mind/src/cognition/act_observe/perception.rs b/core/continuum-cognition/src/cognition/act_observe/perception.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/perception.rs rename to core/continuum-cognition/src/cognition/act_observe/perception.rs diff --git a/core/continuum-mind/src/cognition/act_observe/recency.rs b/core/continuum-cognition/src/cognition/act_observe/recency.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/recency.rs rename to core/continuum-cognition/src/cognition/act_observe/recency.rs diff --git a/core/continuum-mind/src/cognition/act_observe/settle.rs b/core/continuum-cognition/src/cognition/act_observe/settle.rs similarity index 95% rename from core/continuum-mind/src/cognition/act_observe/settle.rs rename to core/continuum-cognition/src/cognition/act_observe/settle.rs index b36c083cd9..842f62d105 100644 --- a/core/continuum-mind/src/cognition/act_observe/settle.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle.rs @@ -19,6 +19,8 @@ use super::types::{SettleOutcome, SettleStep}; use crate::inference::turn_bound::TICK_DEADLINE; mod tick_deadline; +mod turn_credit; +pub use turn_credit::TurnCredit; pub use tick_deadline::*; mod settle_to_outcome; use settle_to_outcome::*; diff --git a/core/continuum-mind/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/settle/settle_step.rs rename to core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs diff --git a/core/continuum-mind/src/cognition/act_observe/settle/settle_to_outcome.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs similarity index 98% rename from core/continuum-mind/src/cognition/act_observe/settle/settle_to_outcome.rs rename to core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs index ab5db76701..c447098449 100644 --- a/core/continuum-mind/src/cognition/act_observe/settle/settle_to_outcome.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs @@ -2,13 +2,13 @@ use super::*; /// The settle loop itself. Both public drivers reach it through the same lived- /// experience wrapper, so taking input cannot bypass the recording seam. -pub(super) async fn settle_to_outcome( +pub(super) async fn settle_to_outcome<'c>( cycle: &WorkspaceCycle, mut burst: Burst, max_acts: usize, mut framing: TurnFraming, - mut conversation: Option<&mut dyn crate::persona::service_loop::PersonaConversation>, - mut credit: Option<&mut crate::persona::training_producer::TurnCreditCapture>, + mut conversation: Option<&mut dyn crate::cognition::conversation::PersonaConversation>, + mut credit: Option<&mut (dyn TurnCredit + 'c)>, ) -> SettleOutcome { // The turn's room comes FROM the burst — witnessed non-nil at construction, // so the drive can no longer disagree with the rendered header (#425). @@ -182,15 +182,15 @@ pub(super) async fn settle_to_outcome( Err(_elapsed) => Err("tick deadline exceeded during room input admission; input remains owned by the conversation".into()), }; let admitted = received.and_then(|messages| { - let recipient = crate::persona::persona_identity::PersonaIdentity::new( + let recipient = crate::cognition::conversation::persona_identity::PersonaIdentity::new( body.persona_id, body.persona_name.clone(), ); for message in messages { if message.peer_id == body.persona_id - || crate::persona::wake_backlog::is_stale( + || crate::cognition::conversation::seen_ids::is_stale( message, - seen_inputs.get_or_insert_with(|| crate::persona::wake_backlog::SeenIds::new( - crate::persona::airc_persona_conversation::INBOX_CAPACITY, + seen_inputs.get_or_insert_with(|| crate::cognition::conversation::seen_ids::SeenIds::new( + crate::cognition::conversation::INBOX_CAPACITY, )), input_watermark, ) @@ -198,12 +198,12 @@ pub(super) async fn settle_to_outcome( continue; } input_watermark = input_watermark.max(message.lamport); - let inbox_message = crate::persona::types::InboxMessage { + let inbox_message = crate::cognition::conversation::types::InboxMessage { id: message.event_id, room_id: message.room_id, sender_id: message.peer_id, sender_name: message.peer_id.to_string(), - sender_type: crate::persona::types::SenderType::Persona, + sender_type: crate::cognition::conversation::types::SenderType::Persona, content: message.text.clone(), timestamp: EpochMs::now().millis(), priority: 0.5, @@ -227,7 +227,7 @@ pub(super) async fn settle_to_outcome( from_peer = %message.peer_id, "room input perceived between actions; original task and causal root retained" ); - crate::persona::perception_feed::mark_perceived( + crate::cognition::extensions::mark_perceived( body.persona_id, message.room_id, message.lamport, diff --git a/core/continuum-mind/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/settle/tests.rs rename to core/continuum-cognition/src/cognition/act_observe/settle/tests.rs diff --git a/core/continuum-mind/src/cognition/act_observe/settle/tick_deadline.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs similarity index 95% rename from core/continuum-mind/src/cognition/act_observe/settle/tick_deadline.rs rename to core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs index ebee9f96dc..4b7ada9c7b 100644 --- a/core/continuum-mind/src/cognition/act_observe/settle/tick_deadline.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tick_deadline.rs @@ -213,7 +213,7 @@ pub fn drive_to_settle_with_input<'a>( burst: Burst, max_acts: usize, framing: TurnFraming, - conversation: &'a mut dyn crate::persona::service_loop::PersonaConversation, + 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) } @@ -225,21 +225,21 @@ pub fn drive_to_settle_with_credit<'a>( burst: Burst, max_acts: usize, framing: TurnFraming, - conversation: &'a mut dyn crate::persona::service_loop::PersonaConversation, - credit: Option<&'a mut crate::persona::training_producer::TurnCreditCapture>, + 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) } -pub(super) async fn drive_with_input( +pub(super) async fn drive_with_input<'c>( cycle: &WorkspaceCycle, burst: Burst, max_acts: usize, framing: TurnFraming, - conversation: Option<&mut dyn crate::persona::service_loop::PersonaConversation>, - mut credit: Option<&mut crate::persona::training_producer::TurnCreditCapture>, + conversation: Option<&mut dyn crate::cognition::conversation::PersonaConversation>, + mut credit: Option<&mut (dyn TurnCredit + 'c)>, ) -> SettleOutcome { let turn_room = burst.room.as_uuid(); let settled = settle_to_outcome( @@ -260,10 +260,10 @@ pub(super) async fn drive_with_input( // (build step 2) it is not written at all. let private = cycle .acting() - .is_some_and(|body| crate::persona::mind_room::is_private_room(body.persona_id, turn_room)); + .is_some_and(|body| crate::cognition::mind_room::is_private_room(body.persona_id, turn_room)); if private { if let Some(body) = cycle.acting() { - crate::persona::mind_room::note_withheld(body.persona_id, "experience_and_credit"); + crate::cognition::mind_room::note_withheld(body.persona_id, "experience_and_credit"); } return settled; } diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/turn_credit.rs b/core/continuum-cognition/src/cognition/act_observe/settle/turn_credit.rs new file mode 100644 index 0000000000..97b01b629c --- /dev/null +++ b/core/continuum-cognition/src/cognition/act_observe/settle/turn_credit.rs @@ -0,0 +1,19 @@ +//! What a card-linked turn's credit owner receives from the settle: the acts so far, the +//! generations that produced them, and her report. The owner is persona's training producer +//! (`TurnCreditCapture`); the settle never assigns a verdict, it only hands over what +//! happened at its stage points and at the end. + +use async_trait::async_trait; + +#[async_trait] +pub trait TurnCredit: Send { + /// Stage the turn as it stands. `final_snapshot` marks the settle's last call. Returns + /// whether anything was staged. + async fn record( + &mut self, + acts: &[(String, Vec)], + receipts: &[crate::ai::provenance::GenerationReceipt], + report: Option<&str>, + final_snapshot: bool, + ) -> bool; +} diff --git a/core/continuum-mind/src/cognition/act_observe/tests/apply.rs b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs similarity index 59% rename from core/continuum-mind/src/cognition/act_observe/tests/apply.rs rename to core/continuum-cognition/src/cognition/act_observe/tests/apply.rs index 0c4f9a3f8a..7df4fae540 100644 --- a/core/continuum-mind/src/cognition/act_observe/tests/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/apply.rs @@ -1,10 +1,7 @@ #![cfg(test)] use super::*; -use crate::cognition::workspace::Situation; -use crate::cognition::workspace::TurnFraming; use crate::cognition::workspace::WorkspaceCycle; -use crate::cognition::workspace::ActingBody; use crate::cognition::workspace::SalienceArbiter; use crate::cognition::tool_executor::CallVerdict; use crate::cognition::tool_executor::NativeBatchOutcome; @@ -18,179 +15,12 @@ use uuid::Uuid; use async_trait::async_trait; use std::sync::Arc; use std::sync::Mutex; -use crate::cognition::working_memory::WorkingMemory; -use crate::cognition::working_memory::WorkingMemoryFaculty; // what this catches: an act is scoped to the room it is FOR (one mind is in // many rooms — the body is room-agnostic, `room_id` flows per-call), the // observation correlates each call to its result in first person, and the // outcome becomes a recallable engram. Regresses the multi-room steer + the // result-as-memory choice (ACTING-ORGANISM §3.3). -// Regression17d3e6ff: real card lookup must resolve admitted hands before -// board grounding, ledger rendering and execution, without moving the wake. -#[tokio::test] -async fn bound_card_activity_is_shared_by_perception_and_execution() { - use crate::cognition::{ - llm_deliberation_faculty::LlmDeliberationFaculty, - rag_source_faculty::{RagSourceFaculty, SaliencePolicy}, - }; - use crate::persona::{ - airc_runtime::PersonaAircRuntime, airc_runtime_registry::PersonaAircRuntimeRegistry, - room_board_source::RoomBoardSource, - }; - let home = tempfile::tempdir().unwrap(); - let _home = crate::paths::test_home::HomeGuard::set(home.path()).await; - let airc = Arc::new( - airc_lib::Airc::open_with_wire_root_for_test(home.path(), home.path()) - .await - .unwrap(), - ); - let task = airc.join("bound-activity-task").await.unwrap(); - let card = airc - .create_work_card(airc_lib::CreateWorkCard::new( - airc_lib::RepoId::new("fixture/activity").unwrap(), - "implement subject change", - airc_lib::Priority::P2, - )) - .await - .unwrap(); - let claim = airc - .claim_work_card(airc_lib::ClaimWorkCard { - card_id: card, - ttl_ms: 600_000, - }) - .await - .unwrap(); - let wake = airc.join("bound-activity-wake").await.unwrap(); - let persona = airc.peer_id().as_uuid(); - PersonaAircRuntimeRegistry::set_global(PersonaAircRuntimeRegistry::new()); - let registry = PersonaAircRuntimeRegistry::try_global().unwrap(); - let runtime = registry.register(PersonaAircRuntime::from_attached( - persona, - "Ivar", - home.path().to_path_buf(), - airc.clone(), - wake.channel, - crate::persona::identity_provider::PersonaIdentitySource::FreshlyMinted, - )); - let hands = - crate::identity::hands_context::HandsContext::for_claim(persona, card.as_uuid(), claim.as_uuid()); - let checkout = airc_lib::work_worktree::worktree_path_for(card).unwrap(); - assert!(checkout.starts_with(home.path())); - std::fs::create_dir_all(checkout.join(".git")).unwrap(); - let exec = Arc::new(RecordingExecutor { - seen_context: Arc::new(Mutex::new(None)), - result_content: "read subject file".into(), - }); - let wm = Arc::new(WorkingMemory::new(8)); - let (board_source, _dirty) = crate::persona::cached_source::CachedRagSource::new(Arc::new( - RoomBoardSource::new(persona, runtime).for_room(wake.channel.as_uuid()), - )); - let board = RagSourceFaculty::new(persona, board_source, SaliencePolicy::StandingFraming); - let cycle = WorkspaceCycle::new( - vec![ - Arc::new(board), - Arc::new(WorkingMemoryFaculty::new(wm.clone())), - Arc::new(ActThenSpeak::new()), - ], - Arc::new(SalienceArbiter), - 8, - ) - .with_acting(Arc::new(ActingBody { - persona_id: persona, - persona_name: "Ivar".into(), - executor: exec.clone(), - admission: admission(), - working_memory: wm.clone(), - })); - let board_state = airc.work_board_in(&task).await.unwrap(); - let focus = board_state.card(card).unwrap(); - let binding = crate::cognition::persona_workspace::bind_card(&cycle, persona, focus).await; - assert_eq!(binding.hands.as_ref().map(|h| h.context), Some(hands)); - let burst = crate::cognition::workspace::Burst::raw_in( - crate::identity::ActivityRoom::from_uuid(wake.channel.as_uuid()).unwrap(), - "work on my held card".into(), - ) - .in_hands(Some(hands)); - let _ = settle_step( - &cycle, - burst.clone(), - true, - TurnFraming::default(), - Situation::default(), - &ActChain::new(), - ) - .await; - assert_eq!( - *exec.seen_context.lock().unwrap(), - Some(task.channel.as_uuid()), - "tools execute in the card activity" - ); - let ws = cycle.run(burst).await; - assert_eq!(ws.room_id, wake.channel.as_uuid()); - assert_eq!(ws.activity_room_id, task.channel.as_uuid()); - assert!( - ws.broadcast - .iter() - .any(|c| c.content.contains("implement subject change")), - "the task board reaches perception" - ); - let prompt = LlmDeliberationFaculty::new( - persona, - "Ivar", - "You are Ivar.", - Arc::new(crate::ai::heuristic_adapter::HeuristicInferenceAdapter::new()), - ) - .with_working_memory(wm) - .prompt_view(&ws); - // Her acts reach her through the action stream (the steps ledger it replaced is gone). - let text: String = prompt.messages.iter().map(|m| m.content_text()).collect::>().join("\n"); - let actions = text.find("[actions]").map(|at| &text[at..]).expect("test: the action stream is in her view"); - assert!(actions.contains("code/run"), "{actions}"); - assert!(!actions.contains("nothing has executed yet"), "{actions}"); - assert_eq!(airc.current_room().await.unwrap().channel, wake.channel); - let private = crate::persona::mind_room::mind_room_id(persona); - let private_ws = cycle - .run( - crate::cognition::workspace::Burst::raw_in( - crate::identity::ActivityRoom::from_uuid(private).unwrap(), - "private thought".into(), - ) - .in_hands(Some(hands)), - ) - .await; - assert_eq!( - private_ws.activity_room_id, private, - "private thoughts never adopt public task scope" - ); - // An eval's fresh hands and a roomless fixture never borrow the focused claim. - let fork = crate::identity::hands_context::HandsContext::fresh(); - assert_eq!( - crate::cognition::persona_workspace::activity_room_for(persona, Some(fork), Uuid::nil()) - .await, - Uuid::nil(), - ); - let unbound_ws = cycle - .run(crate::cognition::workspace::Burst::from("synthetic exam").in_hands(Some(fork))) - .await; - assert_eq!(unbound_ws.activity_room_id, unbound_ws.room_id); - assert!(!unbound_ws - .broadcast - .iter() - .any(|c| c.content.contains("implement subject change"))); - assert_eq!( - crate::cognition::persona_workspace::activity_room_for( - persona, - None, - wake.channel.as_uuid() - ) - .await, - wake.channel.as_uuid(), - "default hands do not inherit the focused claim's card", - ); - registry.remove(persona); -} - #[tokio::test] async fn apply_act_scopes_to_the_room_and_observes_the_result() { let exec = Arc::new(RecordingExecutor { diff --git a/core/continuum-mind/src/cognition/act_observe/tests/chain.rs b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs similarity index 97% rename from core/continuum-mind/src/cognition/act_observe/tests/chain.rs rename to core/continuum-cognition/src/cognition/act_observe/tests/chain.rs index a1b35fcea6..72c5681dc5 100644 --- a/core/continuum-mind/src/cognition/act_observe/tests/chain.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/chain.rs @@ -51,7 +51,7 @@ async fn a_settle_chain_links_each_act_caused_by_its_predecessor() { edges .iter() .any(|e| e.target == first - && e.kind == crate::persona::engram_graph::EdgeKind::CausedBy), + && e.kind == crate::cognition::engram_graph::EdgeKind::CausedBy), "the second act must carry a CausedBy edge to its predecessor — \ the `because` clause as structure, not prose; got {edges:?}" ); @@ -95,7 +95,7 @@ async fn a_chain_rooted_in_its_trigger_links_the_first_act_to_what_caused_the_tu let edges = adm.engram_neighbors(&first); assert!( edges.iter().any(|e| e.target == trigger - && e.kind == crate::persona::engram_graph::EdgeKind::CausedBy), + && e.kind == crate::cognition::engram_graph::EdgeKind::CausedBy), "the FIRST act must chain to the trigger that caused the turn — without \ this edge there is no path from a work card to the acts done for it; \ got {edges:?}" diff --git a/core/continuum-mind/src/cognition/act_observe/tests/credit.rs b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs similarity index 97% rename from core/continuum-mind/src/cognition/act_observe/tests/credit.rs rename to core/continuum-cognition/src/cognition/act_observe/tests/credit.rs index 3fc64df209..8250b0fdad 100644 --- a/core/continuum-mind/src/cognition/act_observe/tests/credit.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs @@ -23,8 +23,8 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { }; use crate::cognition::llm_deliberation_faculty::LlmDeliberationFaculty; use crate::cognition::workspace::{Burst, BurstTurn, Cause, TurnAttention}; - use crate::persona::scripted_conversation::ScriptedConversation; - use crate::persona::service_loop::{IncomingMessage, PersonaConversation}; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::{IncomingMessage, PersonaConversation}; for framing in [ TurnFraming::message(TurnAttention::Addressed), @@ -209,12 +209,12 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { .engram_neighbors(&first_act.id) .iter() .any(|edge| Some(edge.target) == cause.root() - && edge.kind == crate::persona::engram_graph::EdgeKind::CausedBy)); + && edge.kind == crate::cognition::engram_graph::EdgeKind::CausedBy)); assert!(adm .engram_neighbors(&second_act.id) .iter() .any(|edge| edge.target == first_act.id - && edge.kind == crate::persona::engram_graph::EdgeKind::CausedBy)); + && edge.kind == crate::cognition::engram_graph::EdgeKind::CausedBy)); { let requests = recorded.lock().unwrap(); assert_eq!(requests.len(), 3); diff --git a/core/continuum-mind/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs similarity index 84% rename from core/continuum-mind/src/cognition/act_observe/tests/drive.rs rename to core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 8752ad3f24..344ff3415f 100644 --- a/core/continuum-mind/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -182,98 +182,6 @@ async fn capacity_refusal_leaves_the_driver_once_with_typed_custody() { )); } -// Regression 2e3f0eab: admission refusal must retain the original directed -// input, even when a newer directed input arrives before the admitted retry. -#[tokio::test] -async fn starved_priority_input_survives_until_dispatch_without_replaying_actions() { - use crate::cognition::workspace::{Burst, TurnAttention}; - use crate::persona::scripted_conversation::ScriptedConversation; - use crate::persona::service_loop::{IncomingMessage, PersonaConversation}; - use crate::persona::wake_backlog::PendingInput; - use std::sync::atomic::{AtomicBool, Ordering}; - - let gate = Arc::new(AtomicBool::new(false)); - let mut faculty = ActThenSpeak::new(); - faculty.admission_open = Some(Arc::clone(&gate)); - let exec = Arc::new(RecordingExecutor { - seen_context: Arc::new(Mutex::new(None)), - result_content: "4".into(), - }); - let wm = Arc::new(WorkingMemory::new(8)); - let cycle = WorkspaceCycle::new( - vec![ - Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, - Arc::new(faculty), - ], - Arc::new(SalienceArbiter), - 8, - ) - .with_acting(body_with_wm(exec.clone(), admission(), wm)); - let original = IncomingMessage { - event_id: Uuid::new_v4(), lamport: 10, peer_id: Uuid::new_v4(), - room_id: Uuid::new_v4(), text: "Asha, inspect this exact input".into(), work: None, - media: vec![crate::persona::channel_items::MediaItemRequest { - kind: "image".into(), mime_type: Some("image/png".into()), - blob_hash: Some("sha256:retained-input".into()), url: None, - description: Some("original attachment".into()), - }], - }; - let mut newer = original.clone(); - newer.event_id = Uuid::new_v4(); - newer.room_id = Uuid::new_v4(); - newer.lamport += 1; - newer.text = "Asha, a newer directed request".into(); - let mut conversation = ScriptedConversation::new(); - conversation.prime().await.unwrap(); - let mut pending = PendingInput::default(); - let cause = Some(Uuid::new_v4()); - let framing = TurnFraming::message(TurnAttention::for_message(true, false)); - let burst = |message: &IncomingMessage| { - Burst::raw_in( - crate::identity::ActivityRoom::from_uuid(message.room_id).unwrap(), - message.render_content(), - ) - }; - let refused = - drive_to_settle_with_input(&cycle, burst(&original), 8, framing, &mut conversation).await; - assert!(refused.deferred_before_dispatch); - assert_eq!(refused.acts, 0); - assert!(exec.seen_context.lock().unwrap().is_none()); - let (step, _, _) = SettleStep::from_settled(refused); - pending.settle(&original, cause, framing.attention, &step); - conversation.event_feed().push(Ok(Some(newer.clone()))); - assert_eq!(pending.message(), Some(&original)); - assert_eq!(pending.wake_engram_for(&original), cause); - - // A second failed admission neither consumes nor replaces the original. - let retried = pending.message().unwrap().clone(); - let refused_again = drive_to_settle_with_input(&cycle, burst(&retried), 8, framing, &mut conversation).await; - let (step, _, _) = SettleStep::from_settled(refused_again); - pending.settle(&retried, cause, framing.attention, &step); - assert_eq!(pending.message(), Some(&original)); - assert!(conversation.perceive_ready().await.unwrap().iter().any(|m| **m == newer)); - - gate.store(true, Ordering::SeqCst); - let completed = drive_to_settle_with_input( - &cycle, - burst(pending.message().unwrap()), - 8, - framing, - &mut conversation, - ) - .await; - assert!(!completed.deferred_before_dispatch); - assert_eq!(completed.acts, 1, "only the admitted retry executes an action"); - assert!(completed.room_updates.iter().any(|m| **m == newer)); - assert_eq!(completed.room, original.room_id); - let (step, _, _) = SettleStep::from_settled(completed); - assert!(matches!(&step, SettleStep::Spoke(_))); - pending.settle(&original, cause, framing.attention, &step); - assert!(pending.message().is_none(), "completed input is not replayed"); - assert_eq!(conversation.next_message().await.unwrap(), Some(newer)); - assert!(conversation.next_message().await.unwrap().is_none()); -} - // what this catches: THE SETTLE ARTERY (the dominant SWE-bench killer, glass-boxed // 2026-08-04 on sympy-21379: one `code/tree`, then a prose explanation of the bug — // 0 patch bytes, 29 of 30 acts unspent, run over). When the CALLER declared the diff --git a/core/continuum-mind/src/cognition/act_observe/tests/investigation.rs b/core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs similarity index 100% rename from core/continuum-mind/src/cognition/act_observe/tests/investigation.rs rename to core/continuum-cognition/src/cognition/act_observe/tests/investigation.rs diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/mod.rs b/core/continuum-cognition/src/cognition/act_observe/tests/mod.rs new file mode 100644 index 0000000000..b42dfad93c --- /dev/null +++ b/core/continuum-cognition/src/cognition/act_observe/tests/mod.rs @@ -0,0 +1,141 @@ +//! Shared fixtures for the act_observe tests: stand-in executors, faculties and +//! bodies. Scenario files sit beside this one and pull these in via `use super::*;`. + +#![cfg(test)] + +mod apply; +mod chain; +mod credit; +mod drive; +mod investigation; + +use super::*; +use super::test_support::*; +use crate::cognition::workspace::Decision; +use crate::cognition::workspace::ActingBody; +use crate::cognition::workspace::Contribution; +use crate::cognition::workspace::Faculty; +use crate::cognition::workspace::FacultyId; +use crate::cognition::workspace::Workspace; +use crate::cognition::tool_executor::NativeBatchOutcome; +use crate::cognition::tool_executor::ParsedToolBatch; +use crate::cognition::tool_executor::ToolError; +use crate::cognition::tool_executor::ToolExecutionContext; +use crate::cognition::tool_executor::ToolExecutor; +use crate::cognition::tool_executor::ToolOutcome; +use crate::ai::types::ToolCall; +use uuid::Uuid; +use crate::cognition::admission_state::AdmissionState; +use async_trait::async_trait; +use std::sync::Arc; +use std::sync::Mutex; +use crate::cognition::working_memory::WorkingMemory; + +/// An executor whose batch always fails at the batch level (channel down). +struct FailingExecutor; +#[async_trait] +impl ToolExecutor for FailingExecutor { + async fn execute_native_batch( + &self, + _calls: &[ToolCall], + _context: &ToolExecutionContext, + _max_result_chars: usize, + ) -> Result { + Err(ToolError::ExecutionFailed { + tool: "code/run".into(), + underlying: "ipc channel down".into(), + }) + } + async fn parse_response( + &self, + _t: &str, + _f: Option<&str>, + ) -> Result { + Ok(ParsedToolBatch { + tool_calls: Vec::new(), + cleaned_text: String::new(), + parse_time_us: 0, + }) + } + async fn store_outcome( + &self, + _o: &ToolOutcome, + _c: &ToolExecutionContext, + ) -> Result { + Ok(Uuid::nil()) + } +} + +/// Deliberation faculty that NEVER settles — always wants to act again. Models +/// the "acts forever" fitness gap the external grader bounds with `max_acts`. +struct AlwaysAct; +#[async_trait] +impl Faculty for AlwaysAct { + fn id(&self) -> FacultyId { + FacultyId::Deliberation + } + fn reacts_to_broadcast(&self) -> bool { + true + } + async fn contribute(&self, _ws: &Workspace) -> Option { + Some(Contribution::verdict( + Decision::Act { + calls: vec![tool_call()], + intent: "act again".into(), + }, + 0.9, + "never settles", + )) + } +} + +/// Only ever speaks, and COUNTS how many generations it was asked for — the +/// instrument for "did the drive hand her another tick, or settle on the first +/// Speak?". +struct CountingSpeaker { + generations: Mutex, +} +impl CountingSpeaker { + fn new() -> Arc { + Arc::new(Self { + generations: Mutex::new(0), + }) + } + fn generations(&self) -> usize { + *self.generations.lock().expect("lock") + } +} +#[async_trait] +impl Faculty for CountingSpeaker { + fn id(&self) -> FacultyId { + FacultyId::Deliberation + } + fn reacts_to_broadcast(&self) -> bool { + true + } + async fn contribute(&self, _ws: &Workspace) -> Option { + *self.generations.lock().expect("lock") += 1; + Some(Contribution::verdict( + Decision::Speak { + text: "here is my analysis of the bug: the call to subs() is wrong".into(), + }, + 0.95, + "explaining rather than editing", + )) + } +} + + +/// Unwrap the typed acts of an `Acted` outcome (panics on NoHands/ExecutorError) — +/// the typed sibling of the old `.expect("acted")` on the `Option`. +fn acts_of(outcome: ActOutcome) -> Vec { + match outcome { + ActOutcome::Acted { acts } => acts, + other => panic!("expected Acted, got {other:?}"), + } +} + +fn body(executor: Arc, admission: Arc) -> Arc { + body_with_wm(executor, admission, Arc::new(WorkingMemory::new(3))) +} + diff --git a/core/continuum-mind/src/cognition/act_observe/types.rs b/core/continuum-cognition/src/cognition/act_observe/types.rs similarity index 99% rename from core/continuum-mind/src/cognition/act_observe/types.rs rename to core/continuum-cognition/src/cognition/act_observe/types.rs index c38c9aaea4..ac450dae1d 100644 --- a/core/continuum-mind/src/cognition/act_observe/types.rs +++ b/core/continuum-cognition/src/cognition/act_observe/types.rs @@ -32,7 +32,7 @@ pub struct SettleOutcome { pub world_state: String, /// Full source-labelled room inputs perceived while this turn was in flight. pub room_updates: - std::sync::Arc>>, + std::sync::Arc>>, /// The accumulated cost of settling this task: every act→observe deliberation /// generation's latency + tokens, summed. `tokens_per_second()` re-derives /// throughput from the totals. This is the speed/latency the eval reports next diff --git a/core/continuum-mind/src/cognition/activity.rs b/core/continuum-cognition/src/cognition/activity.rs similarity index 100% rename from core/continuum-mind/src/cognition/activity.rs rename to core/continuum-cognition/src/cognition/activity.rs diff --git a/core/continuum-mind/src/cognition/activity_gate.rs b/core/continuum-cognition/src/cognition/activity_gate.rs similarity index 100% rename from core/continuum-mind/src/cognition/activity_gate.rs rename to core/continuum-cognition/src/cognition/activity_gate.rs diff --git a/core/continuum-mind/src/persona/admission/admission_candidate.rs b/core/continuum-cognition/src/cognition/admission/admission_candidate.rs similarity index 100% rename from core/continuum-mind/src/persona/admission/admission_candidate.rs rename to core/continuum-cognition/src/cognition/admission/admission_candidate.rs diff --git a/core/continuum-mind/src/persona/admission/mod.rs b/core/continuum-cognition/src/cognition/admission/mod.rs similarity index 92% rename from core/continuum-mind/src/persona/admission/mod.rs rename to core/continuum-cognition/src/cognition/admission/mod.rs index 86242919cb..401f6de70b 100644 --- a/core/continuum-mind/src/persona/admission/mod.rs +++ b/core/continuum-cognition/src/cognition/admission/mod.rs @@ -1,7 +1,7 @@ //! Admission Gate + IsMemorable Recipe (continuum#1121 PR-2) //! //! Layers the admission policy machinery over the storage-shape types -//! shipped in PR-1 (`persona::engram`). Splits cleanly into two responsibilities: +//! shipped in PR-1 (`cognition::engram`). Splits cleanly into two responsibilities: //! //! - **Gate (structural)** — `AdmissionGate::admit()` runs the prereqs that //! are independent of any specific persona's policy: envelope structure @@ -41,8 +41,8 @@ //! replace. //! //! Pairs with: -//! - [`persona::engram`] — storage-shape types this module operates over. -//! - [`persona::trace`] — `SEAM_ADMISSION` constant + `CognitionTrace`. +//! - [`cognition::engram`] — storage-shape types this module operates over. +//! - [`cognition::trace`] — `SEAM_ADMISSION` constant + `CognitionTrace`. //! - `docs/grid/COGNITIVE-IMMUNE-MODEL.md` — defense posture this gate //! participates in (apoptosis-cheaper-than-corruption, B-cell anergy, //! forensic-not-destructive). @@ -68,7 +68,7 @@ use ts_rs::TS; use uuid::Uuid; // Re-exported pub so submodules (`recipes`) can import via `super::` -// without reaching across to `crate::persona::engram` for every type. +// without reaching across to `crate::cognition::engram` for every type. use super::engram::Engram; pub use super::engram::{AdmissionDecision, AdmissionDropReason, AdmissionError, AircMessageRef, EngramKind, EngramOrigin, TrustState}; use super::trace::{CognitionTrace, SEAM_ADMISSION}; diff --git a/core/continuum-mind/src/persona/admission/recipes.rs b/core/continuum-cognition/src/cognition/admission/recipes.rs similarity index 99% rename from core/continuum-mind/src/persona/admission/recipes.rs rename to core/continuum-cognition/src/cognition/admission/recipes.rs index cb182ef2fa..c5812b29d7 100644 --- a/core/continuum-mind/src/persona/admission/recipes.rs +++ b/core/continuum-cognition/src/cognition/admission/recipes.rs @@ -145,7 +145,7 @@ mod tests { SeenContentLookup, SeenEventLookup, TrustState, }; use super::*; - use crate::persona::trace::CognitionTrace; + use crate::cognition::trace::CognitionTrace; use std::collections::HashMap; use std::sync::Mutex; use uuid::Uuid; diff --git a/core/continuum-mind/src/persona/admission/tests.rs b/core/continuum-cognition/src/cognition/admission/tests.rs similarity index 100% rename from core/continuum-mind/src/persona/admission/tests.rs rename to core/continuum-cognition/src/cognition/admission/tests.rs diff --git a/core/continuum-mind/src/persona/admission_persistence.rs b/core/continuum-cognition/src/cognition/admission_persistence.rs similarity index 97% rename from core/continuum-mind/src/persona/admission_persistence.rs rename to core/continuum-cognition/src/cognition/admission_persistence.rs index 743faca411..2b643f46d9 100644 --- a/core/continuum-mind/src/persona/admission_persistence.rs +++ b/core/continuum-cognition/src/cognition/admission_persistence.rs @@ -43,8 +43,8 @@ use dashmap::DashMap; use uuid::Uuid; use crate::orm::{OrmStore, OrmStoreError}; -use crate::persona::engram::Engram; -use crate::persona::recall_metadata::{EngramRecallMetadata, RecallMetadata}; +use crate::cognition::engram::Engram; +use crate::cognition::recall_metadata::{EngramRecallMetadata, RecallMetadata}; /// Adapter-first persistence rail. Impls choose synchronously / /// fire-and-forget / batched / no-op. @@ -437,7 +437,7 @@ impl OrmLoader { #[cfg(test)] mod tests { use super::*; - use crate::persona::engram::{AircMessageRef, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::engram::{AircMessageRef, EngramKind, EngramOrigin, TrustState}; fn sample_engram(content: &str) -> Engram { Engram { @@ -532,9 +532,9 @@ mod tests { use crate::orm::adapter::StorageAdapter; use crate::orm::sqlite::SqliteAdapter; use crate::orm::OrmStore; - use crate::persona::admission_state::AdmissionState; - use crate::persona::recall_metadata::RecallMetadataRegistry; - use crate::persona::types::InboxMessage; + use crate::cognition::admission_state::AdmissionState; + use crate::cognition::recall_metadata::RecallMetadataRegistry; + use crate::cognition::conversation::types::InboxMessage; // Set up SQLite + OrmStores + the production sink + loader. let tmp = tempfile::tempdir().expect("tempdir"); @@ -562,7 +562,7 @@ mod tests { room_id: Uuid::new_v4(), sender_id: Uuid::new_v4(), sender_name: "operator".to_string(), - sender_type: crate::persona::types::SenderType::Human, + sender_type: crate::cognition::conversation::types::SenderType::Human, content: "persistence proof engram alpha".to_string(), timestamp: 1_000, priority: 0.5, @@ -574,7 +574,7 @@ mod tests { room_id: Uuid::new_v4(), sender_id: Uuid::new_v4(), sender_name: "operator".to_string(), - sender_type: crate::persona::types::SenderType::Human, + sender_type: crate::cognition::conversation::types::SenderType::Human, content: "persistence proof engram beta".to_string(), timestamp: 2_000, priority: 0.5, @@ -584,11 +584,11 @@ mod tests { let d1 = state.admit(&m1, None).expect("admit m1"); let d2 = state.admit(&m2, None).expect("admit m2"); let id1 = match d1 { - crate::persona::engram::AdmissionDecision::Admit { engram, .. } => engram.id, + crate::cognition::engram::AdmissionDecision::Admit { engram, .. } => engram.id, other => panic!("expected Admit got {other:?}"), }; let id2 = match d2 { - crate::persona::engram::AdmissionDecision::Admit { engram, .. } => engram.id, + crate::cognition::engram::AdmissionDecision::Admit { engram, .. } => engram.id, other => panic!("expected Admit got {other:?}"), }; vec![id1, id2] diff --git a/core/continuum-mind/src/persona/admission_state.rs b/core/continuum-cognition/src/cognition/admission_state.rs similarity index 98% rename from core/continuum-mind/src/persona/admission_state.rs rename to core/continuum-cognition/src/cognition/admission_state.rs index 51a23f7cc2..35a61c5b5e 100644 --- a/core/continuum-mind/src/persona/admission_state.rs +++ b/core/continuum-cognition/src/cognition/admission_state.rs @@ -48,7 +48,7 @@ use super::admission::{HeuristicIsMemorable, SeenContentLookup, SeenEventLookup} use super::engram::{AdmissionDecision, AdmissionDropReason, AdmissionError, Engram, EngramOrigin}; use super::inbox_admission::{content_hash_sha256, InboxAdmissionRunner}; use super::trace::CognitionTrace; -use super::types::InboxMessage; +use crate::cognition::conversation::types::InboxMessage; //============================================================================= // IN-MEMORY ORACLES (private, used by AdmissionState) diff --git a/core/continuum-mind/src/persona/admission_state/admission_state.rs b/core/continuum-cognition/src/cognition/admission_state/admission_state.rs similarity index 94% rename from core/continuum-mind/src/persona/admission_state/admission_state.rs rename to core/continuum-cognition/src/cognition/admission_state/admission_state.rs index 6fb63954ee..221e88e4fa 100644 --- a/core/continuum-mind/src/persona/admission_state/admission_state.rs +++ b/core/continuum-cognition/src/cognition/admission_state/admission_state.rs @@ -9,11 +9,11 @@ impl AdmissionState { /// PersonaCognition share a single registry view across admission + /// recall + decay tick subsystems. pub fn new( - recall_metadata: Arc, + recall_metadata: Arc, ) -> Self { Self::new_with_persistence( recall_metadata, - crate::persona::admission_persistence::NoopSink::arc(), + crate::cognition::admission_persistence::NoopSink::arc(), ) } @@ -24,8 +24,8 @@ impl AdmissionState { /// metadata update and chooses what to do with them /// (fire-and-forget write, buffer, no-op, etc.). pub fn new_with_persistence( - recall_metadata: Arc, - persistence: Arc, + recall_metadata: Arc, + persistence: Arc, ) -> Self { Self { runner: InboxAdmissionRunner::default_v1(), @@ -35,7 +35,7 @@ impl AdmissionState { recall_metadata, persistence: RwLock::new(persistence), owner_id: RwLock::new(None), - graph: crate::persona::engram_graph::EngramGraph::new(), + graph: crate::cognition::engram_graph::EngramGraph::new(), tool_heads: None, } } @@ -49,10 +49,10 @@ impl AdmissionState { /// works against the rehydrated salience values; the Hebbian /// rehearsal loop continues across the restart boundary. pub fn new_rehydrated( - recall_metadata: Arc, - persistence: Arc, + recall_metadata: Arc, + persistence: Arc, loaded_engrams: Vec, - loaded_metadata: Vec<(Uuid, crate::persona::recall_metadata::RecallMetadata)>, + loaded_metadata: Vec<(Uuid, crate::cognition::recall_metadata::RecallMetadata)>, ) -> Self { // Populate the metadata registry with the loaded snapshots // BEFORE building the Vec — recall scoring later reads @@ -84,7 +84,7 @@ impl AdmissionState { // Edges are not yet durable — a rehydrated store starts with an // empty graph and re-accumulates from live acts. Sidecar // persistence is the next slice (CAUSAL-MEMORY-GRAPH.md §4). - graph: crate::persona::engram_graph::EngramGraph::new(), + graph: crate::cognition::engram_graph::EngramGraph::new(), tool_heads: None, } } @@ -97,7 +97,7 @@ impl AdmissionState { /// Borrow the shared recall metadata registry. Recall + decay tick /// subsystems clone this Arc for their own reads/writes — they /// observe the same DashMap admission writes into. - pub fn recall_metadata(&self) -> &Arc { + pub fn recall_metadata(&self) -> &Arc { &self.recall_metadata } @@ -112,7 +112,7 @@ impl AdmissionState { &self, from: Uuid, to: Uuid, - kind: crate::persona::engram_graph::EdgeKind, + kind: crate::cognition::engram_graph::EdgeKind, ) { self.graph.add_edge(from, to, kind, 1.0); } @@ -122,7 +122,7 @@ impl AdmissionState { pub fn engram_neighbors( &self, id: &Uuid, - ) -> Vec { + ) -> Vec { self.graph.neighbors(id) } @@ -136,10 +136,10 @@ impl AdmissionState { /// no owner (tests, replay) has no mind room. pub(super) fn withheld_in_her_mind_room(&self, room: Uuid) -> Option { let owner = (*self.owner_id.read().unwrap())?; - crate::persona::mind_room::is_private_room(owner, room).then(|| { - crate::persona::mind_room::note_withheld(owner, "engrams"); + crate::cognition::mind_room::is_private_room(owner, room).then(|| { + crate::cognition::mind_room::note_withheld(owner, "engrams"); AdmissionDecision::Drop { - reason: crate::persona::engram::AdmissionDropReason::PolicyDeniedAdmission { + reason: crate::cognition::engram::AdmissionDropReason::PolicyDeniedAdmission { policy_id: "mind-room".to_string(), explanation: "a turn in her mind room is hers; it is not written to engrams.sqlite".to_string(), }, @@ -177,15 +177,15 @@ impl AdmissionState { /// airc-native entity envelope emission — all riding on top of /// this same PersonaHome resolution. pub async fn for_persona( - home: &crate::persona::home::PersonaHome, - recall_metadata: Arc, + home: &crate::cognition::home::PersonaHome, + recall_metadata: Arc, ) -> Result { use crate::orm::adapter::StorageAdapter; use crate::orm::sqlite::SqliteAdapter; use crate::orm::OrmStore; - use crate::persona::admission_persistence::{OrmLoader, OrmPersistenceSink}; - use crate::persona::engram::Engram; - use crate::persona::recall_metadata::EngramRecallMetadata; + use crate::cognition::admission_persistence::{OrmLoader, OrmPersistenceSink}; + use crate::cognition::engram::Engram; + use crate::cognition::recall_metadata::EngramRecallMetadata; // Ensure the persona's home directory exists. fs::create_dir_all // is idempotent and safe to call on every boot. @@ -245,7 +245,7 @@ impl AdmissionState { let mut state = Self::new_rehydrated( recall_metadata, sink_concrete - as Arc, + as Arc, engrams, metadata, ); @@ -466,7 +466,7 @@ impl AdmissionState { /// flow. Per crate-test visibility, this is callable from any /// test elsewhere in continuum-core but NOT from production code /// (the cfg gate ensures it doesn't appear in non-test builds). - #[cfg(test)] + #[cfg(any(test, feature = "test-fixtures"))] pub fn push_for_test(&self, engram: Engram) { self.engrams.lock().unwrap().push(engram); } @@ -534,7 +534,7 @@ impl AdmissionState { /// [[design-the-persona-as-a-being]] + [[eval-mutates-persona-lift-needs-isolation]]. pub fn fork_detached(&self) -> AdmissionState { let cp = self.checkpoint(); - let fork_registry = crate::persona::recall_metadata::RecallMetadataRegistry::new(); + let fork_registry = crate::cognition::recall_metadata::RecallMetadataRegistry::new(); // Carry the LIVING registry's state into the fork — salience, rehearsal // counts, protection, supersession demotions. A fresh-empty registry // resets every engram to DEFAULT salience inside the fork, which @@ -568,8 +568,8 @@ impl AdmissionState { /// on any hot path. pub fn swap_persistence( &self, - sink: Arc, - ) -> Arc { + sink: Arc, + ) -> Arc { let mut guard = self.persistence.write().unwrap(); std::mem::replace(&mut *guard, sink) } @@ -609,7 +609,7 @@ impl AdmissionState { let mut hits: Vec = engrams .iter() .rev() // newest-first (insertion order store) - .filter(|e| e.kind == crate::persona::engram::EngramKind::Semantic) + .filter(|e| e.kind == crate::cognition::engram::EngramKind::Semantic) .filter(|e| { let content = e.content.to_lowercase(); needles.iter().any(|n| content.contains(n.as_str())) @@ -642,7 +642,7 @@ impl AdmissionState { let engrams = self.engrams.lock().unwrap(); engrams .iter() // insertion order == oldest first - .filter(|e| e.kind == crate::persona::engram::EngramKind::Semantic) + .filter(|e| e.kind == crate::cognition::engram::EngramKind::Semantic) .filter(|e| e.admitted_at_ms < admitted_before_ms) .filter(|e| !exclude.contains(&e.id)) .take(limit) diff --git a/core/continuum-mind/src/persona/admission_state/admission_state_2.rs b/core/continuum-cognition/src/cognition/admission_state/admission_state_2.rs similarity index 99% rename from core/continuum-mind/src/persona/admission_state/admission_state_2.rs rename to core/continuum-cognition/src/cognition/admission_state/admission_state_2.rs index 48866c84b6..7fe02a9d47 100644 --- a/core/continuum-mind/src/persona/admission_state/admission_state_2.rs +++ b/core/continuum-cognition/src/cognition/admission_state/admission_state_2.rs @@ -136,7 +136,7 @@ impl AdmissionState { // them explicitly by `thought:` recall-key (`recall_by_keyword`, a // separate path). Dream-DISTILLED insight is EngramKind::Semantic // (durable) — untouched. Sibling of the Tool-receipt gate above (#166). - if e.kind == crate::persona::engram::EngramKind::SelfReflection + if e.kind == crate::cognition::engram::EngramKind::SelfReflection && now_ms.saturating_sub(e.admitted_at_ms) > INNER_SPEECH_RECALL_TTL_MS { return None; diff --git a/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs b/core/continuum-cognition/src/cognition/admission_state/in_memory_seen_content.rs similarity index 93% rename from core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs rename to core/continuum-cognition/src/cognition/admission_state/in_memory_seen_content.rs index d7bc5895e7..037bdfbb69 100644 --- a/core/continuum-mind/src/persona/admission_state/in_memory_seen_content.rs +++ b/core/continuum-cognition/src/cognition/admission_state/in_memory_seen_content.rs @@ -66,7 +66,7 @@ impl InMemorySeenEvents { /// reaches sqlite. See [[eval-mutates-persona-lift-needs-isolation]]. pub struct AdmissionCheckpoint { pub(super) engrams: Vec, - pub(super) recall_metadata: Vec<(Uuid, crate::persona::recall_metadata::RecallMetadata)>, + pub(super) recall_metadata: Vec<(Uuid, crate::cognition::recall_metadata::RecallMetadata)>, pub(super) seen_content: HashMap, pub(super) seen_events: HashMap, } @@ -91,7 +91,7 @@ pub struct AdmissionState { /// durable content layer per the cognition-cache-hierarchy /// doctrine. Lock-free reads via DashMap; admission-time write /// happens inside record_admitted(). - pub(super) recall_metadata: Arc, + pub(super) recall_metadata: Arc, /// Persistence sink — observes admissions + metadata updates. /// `NoopSink` by default (preserves test + replay paths); the /// production path uses `OrmPersistenceSink` to fire-and-forget @@ -107,14 +107,14 @@ pub struct AdmissionState { /// admit / once per recall-batch (human-message cadence, never /// per-token), so the cost is nil. See /// [[eval-mutates-persona-lift-needs-isolation]]. - pub(super) persistence: RwLock>, + pub(super) persistence: RwLock>, /// The engram edge graph — causal + associative structure over the /// engrams this store admits (docs/cognition/CAUSAL-MEMORY-GRAPH.md, /// docs/cognition/BELIEF-JUSTIFICATION-GRAPH.md). Edges are FACTS about /// what happened, recorded at the write site; the graph never decides — /// retrieval surfaces walk it, cognition judges. In-memory (DashMap); /// sidecar durability is a follow-on slice. - pub(super) graph: crate::persona::engram_graph::EngramGraph, + pub(super) graph: crate::cognition::engram_graph::EngramGraph, /// Her learned tool head's row store, in this same per-persona database; `None` for a /// state with no disk (tests, replay, a measurement fork). pub(super) tool_heads: Option>>, @@ -135,7 +135,7 @@ pub struct AdmissionState { impl Default for AdmissionState { fn default() -> Self { Self::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )) } } diff --git a/core/continuum-mind/src/persona/admission_state/tests/mod.rs b/core/continuum-cognition/src/cognition/admission_state/tests/mod.rs similarity index 93% rename from core/continuum-mind/src/persona/admission_state/tests/mod.rs rename to core/continuum-cognition/src/cognition/admission_state/tests/mod.rs index 0267c10bd2..9d4ef7d613 100644 --- a/core/continuum-mind/src/persona/admission_state/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/admission_state/tests/mod.rs @@ -1,12 +1,12 @@ #![cfg(test)] use super::*; - use crate::persona::admission::IsMemorable as _; - use crate::persona::engram::{ + use crate::cognition::admission::IsMemorable as _; + use crate::cognition::engram::{ AdmissionDropReason, AircMessageRef, ChatMessageRef, EngramKind, TrustState, }; - use crate::persona::inbox_admission::content_hash_sha256; - use crate::persona::types::SenderType; + use crate::cognition::inbox_admission::content_hash_sha256; + use crate::cognition::conversation::types::SenderType; pub(super) fn synthetic_human_message(content: &str) -> InboxMessage { InboxMessage { @@ -30,7 +30,7 @@ #[test] pub(super) fn admit_records_engram_and_dedup_blocks_repeat() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mut trace = CognitionTrace::new(); let content = "this is a non-trivial design observation worth storing"; @@ -62,7 +62,7 @@ #[test] pub(super) fn dropped_message_records_no_side_effect() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mut trace = CognitionTrace::new(); // Short content → drops with NotMemorable. @@ -85,7 +85,7 @@ #[test] pub(super) fn admitted_engrams_accumulate_in_order_and_are_retrievable() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mut trace = CognitionTrace::new(); let messages = [ @@ -115,7 +115,7 @@ #[test] pub(super) fn admit_emits_one_seam_per_call_through_state_wrapper() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mut trace = CognitionTrace::new(); // Three admits with three different outcomes: @@ -136,7 +136,7 @@ #[test] pub(super) fn runner_accessor_exposes_default_v1_config() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); assert_eq!(state.runner().recipe().id(), "heuristic.v1"); } @@ -219,7 +219,7 @@ #[test] pub(super) fn quarantine_chat_origin_records_no_side_effects() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let engram = synthetic_engram_with_chat_origin("borderline observation"); let content_hash = match &engram.origin { @@ -252,7 +252,7 @@ #[test] pub(super) fn quarantine_airc_origin_records_event_id_only_not_content_hash() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let event_id = "airc-msg-quarantine-1"; let engram = @@ -308,7 +308,7 @@ #[test] pub(super) fn recall_recent_returns_newest_first() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let ids = admit_n_distinct( &state, @@ -335,7 +335,7 @@ #[test] pub(super) fn forget_context_wipes_only_the_tagged_episode() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); admit_n_distinct( &state, @@ -369,7 +369,7 @@ #[test] pub(super) fn recall_recent_respects_limit_above_and_below_count() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); admit_n_distinct( &state, @@ -398,7 +398,7 @@ #[test] pub(super) fn recall_candidates_keeps_newest_when_salience_ties() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); // Seven engrams, all at the default salience (a tie). The freshest is ids[6]. let ids = admit_n_distinct( @@ -437,16 +437,16 @@ #[test] pub(super) fn recall_candidates_excludes_tool_origin_receipts() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let knowledge = admit_n_distinct(&state, &["the ticket asks for a wordstats CLI here"]); - let receipt = crate::persona::engram::Engram { + let receipt = crate::cognition::engram::Engram { id: Uuid::new_v4(), context_id: None, - kind: crate::persona::engram::EngramKind::Episodic, + kind: crate::cognition::engram::EngramKind::Episodic, content: "code/list(path=src) → ok".to_string(), - origin: crate::persona::engram::EngramOrigin::Tool( - crate::persona::engram::ToolInvocationRef { + origin: crate::cognition::engram::EngramOrigin::Tool( + crate::cognition::engram::ToolInvocationRef { invocation_id: Uuid::new_v4(), tool_name: "code/list".to_string(), invoked_at_ms: 1000, @@ -456,7 +456,7 @@ ), recall_keys: Vec::new(), admitted_at_ms: 2000, - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; let receipt_id = receipt.id; @@ -485,7 +485,7 @@ #[test] pub(super) fn recall_recency_bounds_wanderer_inner_speech_but_keeps_distilled() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let now = 100 * 60 * 1000; // 100 min in let inner = |content: &str, admitted_at_ms: u64| Engram { @@ -558,7 +558,7 @@ #[test] pub(super) fn admit_reflection_stores_self_produced_fact() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let fact = semantic_reflection("Rust is the core; Node is the shell", Uuid::new_v4()); @@ -579,15 +579,15 @@ #[test] pub(super) fn a_memory_from_her_mind_room_is_not_written_to_her_engrams() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let her = Uuid::new_v4(); state.set_owner_id(her); let mut private = semantic_reflection("a private thought", Uuid::new_v4()); - private.context_id = Some(crate::persona::mind_room::mind_room_id(her)); + private.context_id = Some(crate::cognition::mind_room::mind_room_id(her)); assert!(matches!( state.admit_reflection(private).expect("no error"), - AdmissionDecision::Drop { reason: crate::persona::engram::AdmissionDropReason::PolicyDeniedAdmission { .. } } + AdmissionDecision::Drop { reason: crate::cognition::engram::AdmissionDropReason::PolicyDeniedAdmission { .. } } )); assert_eq!(state.engram_count(), 0, "her mind room: nothing in her engrams"); let mut open = semantic_reflection("an open thought", Uuid::new_v4()); @@ -605,7 +605,7 @@ pub(super) fn redact_scrubs_exam_key_from_memory_keeping_the_experience() { use crate::cognition::redaction::{HeldOutAnswerDetector, RedactionClass, RedactionPolicy}; let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mem = semantic_reflection( "I was asked which file holds the loop; I answered service_loop.rs and it passed.", @@ -635,7 +635,7 @@ pub(super) fn redact_with_noop_policy_changes_nothing() { use crate::cognition::redaction::RedactionPolicy; let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mem = semantic_reflection("plain memory, nothing sensitive", Uuid::new_v4()); state.admit_reflection(mem).expect("admits"); @@ -678,7 +678,7 @@ let owner = Uuid::new_v4(); let other = Uuid::new_v4(); let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); state.set_owner_id(owner); diff --git a/core/continuum-mind/src/persona/admission_state/tests/part_2.rs b/core/continuum-cognition/src/cognition/admission_state/tests/part_2.rs similarity index 91% rename from core/continuum-mind/src/persona/admission_state/tests/part_2.rs rename to core/continuum-cognition/src/cognition/admission_state/tests/part_2.rs index da9e8221dd..5ec34a9077 100644 --- a/core/continuum-mind/src/persona/admission_state/tests/part_2.rs +++ b/core/continuum-cognition/src/cognition/admission_state/tests/part_2.rs @@ -9,7 +9,7 @@ use super::*; pub(super) fn fork_detached_inherits_owner_id_so_the_benchmark_gets_the_recall_fix() { let owner = Uuid::new_v4(); let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); state.set_owner_id(owner); state @@ -36,7 +36,7 @@ use super::*; pub(super) fn chat_recall_gate_is_noop_without_owner_bound() { let author = Uuid::new_v4(); let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); state .admit_reflection(chat_engram("some chat from an author", author)) @@ -61,7 +61,7 @@ use super::*; #[test] pub(super) fn admit_reflection_dedups_identical_facts() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let parent = Uuid::new_v4(); let first = semantic_reflection("Headless core, many equal clients", parent); @@ -86,7 +86,7 @@ use super::*; /// highest — defeating the whole point of Algorithm 4 driving recall. #[test] pub(super) fn recall_scored_ranks_by_salience_desc() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::new(Arc::clone(®istry)); let ids = admit_n_distinct( &state, @@ -123,7 +123,7 @@ use super::*; /// remembering. #[test] pub(super) fn recall_scored_records_recall_hit_on_returned_engrams() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::new(Arc::clone(®istry)); let ids = admit_n_distinct( &state, @@ -164,7 +164,7 @@ use super::*; /// without panicking + without recording spurious hits. #[test] pub(super) fn recall_scored_respects_limit_and_empty() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::new(Arc::clone(®istry)); let ids = admit_n_distinct( &state, @@ -206,7 +206,7 @@ use super::*; #[test] pub(super) fn recall_by_id_finds_known_returns_none_unknown() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let ids = admit_n_distinct( &state, @@ -230,7 +230,7 @@ use super::*; #[test] pub(super) fn recall_by_keyword_case_insensitive_newest_first_with_limit() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); admit_n_distinct( &state, @@ -268,7 +268,7 @@ use super::*; #[test] pub(super) fn recall_by_origin_kind_filters_to_requested_variant() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); admit_n_distinct( &state, @@ -308,7 +308,7 @@ use super::*; assert_eq!(EngramOriginKind::from(&chat.origin), EngramOriginKind::Chat); assert_eq!(EngramOriginKind::from(&airc.origin), EngramOriginKind::Airc); // Agent origin (agent-memory bridge) maps to EngramOriginKind::Agent. - let agent_origin = EngramOrigin::Agent(crate::persona::engram::AgentRef { + let agent_origin = EngramOrigin::Agent(crate::cognition::engram::AgentRef { agent_peer_id: Uuid::new_v4(), session: None, origin_hint: None, @@ -329,7 +329,7 @@ use super::*; /// serde-tag drift would silently break cross-agent recall. #[test] pub(super) fn agent_origin_serde_round_trips_with_required_peer_id() { - use crate::persona::engram::AgentRef; + use crate::cognition::engram::AgentRef; let me = Uuid::new_v4(); let origin = EngramOrigin::Agent(AgentRef { @@ -356,7 +356,7 @@ use super::*; #[test] pub(super) fn admit_airc_origin_still_records_both_content_hash_and_event_id() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let event_id = "airc-msg-admit-1"; let engram = @@ -389,13 +389,13 @@ use super::*; /// can assert it landed. #[test] pub(super) fn admit_observes_admission_through_persistence_sink() { - use crate::persona::admission_persistence::RecordingSink; - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + use crate::cognition::admission_persistence::RecordingSink; + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let sink = Arc::new(RecordingSink::new()); let state = AdmissionState::new_with_persistence( Arc::clone(®istry), Arc::clone(&sink) - as Arc, + as Arc, ); let msg = synthetic_human_message("watch me persist"); state.admit(&msg, None).expect("admit"); @@ -410,13 +410,13 @@ use super::*; /// that lifts salience flushes the new value. #[test] pub(super) fn recall_scored_observes_metadata_updates_through_sink() { - use crate::persona::admission_persistence::RecordingSink; - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + use crate::cognition::admission_persistence::RecordingSink; + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let sink = Arc::new(RecordingSink::new()); let state = AdmissionState::new_with_persistence( Arc::clone(®istry), Arc::clone(&sink) - as Arc, + as Arc, ); // Admit 2 engrams so recall has something to score. admit_n_distinct( @@ -448,13 +448,13 @@ use super::*; /// observes again afterward. Regresses [[eval-mutates-persona-lift-needs-isolation]]. #[test] pub(super) fn eval_isolation_checkpoint_restore_leaves_no_trace() { - use crate::persona::admission_persistence::{NoopSink, RecordingSink}; - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + use crate::cognition::admission_persistence::{NoopSink, RecordingSink}; + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let real_sink = Arc::new(RecordingSink::new()); let state = AdmissionState::new_with_persistence( Arc::clone(®istry), Arc::clone(&real_sink) - as Arc, + as Arc, ); // Non-trivial content: the admission gate drops short strings as @@ -517,20 +517,20 @@ use super::*; /// salience values. The proof that boot rehydration works. #[test] pub(super) fn new_rehydrated_restores_engrams_and_metadata_for_recall() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); // Synthesize a couple of engrams + their metadata as if they // had been loaded from disk. let alpha_engram = synthetic_engram_with_chat_origin("alpha persisted"); let beta_engram = synthetic_engram_with_chat_origin("beta persisted"); let loaded_engrams = vec![alpha_engram.clone(), beta_engram.clone()]; - let high_salience = crate::persona::recall_metadata::RecallMetadata { + let high_salience = crate::cognition::recall_metadata::RecallMetadata { salience: 0.9, access_count: 5, last_accessed_ms: 1_000, protected_until_ms: 0, last_decayed_ms: 1_000, }; - let low_salience = crate::persona::recall_metadata::RecallMetadata { + let low_salience = crate::cognition::recall_metadata::RecallMetadata { salience: 0.2, access_count: 0, last_accessed_ms: 0, @@ -544,7 +544,7 @@ use super::*; let state = AdmissionState::new_rehydrated( Arc::clone(®istry), - crate::persona::admission_persistence::NoopSink::arc(), + crate::cognition::admission_persistence::NoopSink::arc(), loaded_engrams, loaded_metadata, ); @@ -577,7 +577,7 @@ use super::*; // last_decayed_ms, whose loss would trigger the epoch-delta decay collapse. #[test] pub(super) fn set_recall_salience_lowers_salience_and_preserves_decay_clock() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::new(registry.clone()); let id = Uuid::new_v4(); // Seed as an ordinary admission does (default 0.5 salience, decay clock set). @@ -599,7 +599,7 @@ use super::*; #[test] pub(super) fn rehydrate_backfills_metadata_for_phantom_engrams() { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let phantom_engram = synthetic_engram_with_chat_origin("phantom no metadata row"); let healthy_engram = synthetic_engram_with_chat_origin("healthy has metadata"); let phantom_id = phantom_engram.id; @@ -609,7 +609,7 @@ use super::*; // window between engram-save and metadata-save. let metadata_pair = ( healthy_id, - crate::persona::recall_metadata::RecallMetadata { + crate::cognition::recall_metadata::RecallMetadata { salience: 0.8, access_count: 2, last_accessed_ms: 1_000, @@ -620,7 +620,7 @@ use super::*; let state = AdmissionState::new_rehydrated( Arc::clone(®istry), - crate::persona::admission_persistence::NoopSink::arc(), + crate::cognition::admission_persistence::NoopSink::arc(), vec![phantom_engram, healthy_engram], vec![metadata_pair], ); @@ -669,11 +669,11 @@ use super::*; #[tokio::test] pub(super) async fn for_persona_round_trips_admissions_via_per_persona_sqlite() { let tmp = tempfile::tempdir().expect("tempdir"); - let home = crate::persona::home::PersonaHome::for_persona(tmp.path(), "Paige"); + let home = crate::cognition::home::PersonaHome::for_persona(tmp.path(), "Paige"); // ── Lifetime 1: admit through the persona's home ──────── let original_ids: Vec = { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::for_persona(&home, Arc::clone(®istry)) .await .expect("for_persona setup"); @@ -695,7 +695,7 @@ use super::*; // Wait for fire-and-forget writes to land. let mut tries = 0; - let registry2 = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry2 = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state2 = loop { let st = AdmissionState::for_persona(&home, Arc::clone(®istry2)) .await diff --git a/core/continuum-mind/src/persona/admission_state/tests/part_3.rs b/core/continuum-cognition/src/cognition/admission_state/tests/part_3.rs similarity index 92% rename from core/continuum-mind/src/persona/admission_state/tests/part_3.rs rename to core/continuum-cognition/src/cognition/admission_state/tests/part_3.rs index eca6ea5375..c43f1da539 100644 --- a/core/continuum-mind/src/persona/admission_state/tests/part_3.rs +++ b/core/continuum-cognition/src/cognition/admission_state/tests/part_3.rs @@ -8,12 +8,12 @@ use super::*; #[tokio::test] pub(super) async fn for_persona_isolates_two_personas_at_the_storage_layer() { let tmp = tempfile::tempdir().expect("tempdir"); - let paige_home = crate::persona::home::PersonaHome::for_persona(tmp.path(), "Paige"); - let niko_home = crate::persona::home::PersonaHome::for_persona(tmp.path(), "Niko"); + let paige_home = crate::cognition::home::PersonaHome::for_persona(tmp.path(), "Paige"); + let niko_home = crate::cognition::home::PersonaHome::for_persona(tmp.path(), "Niko"); // Admit through Paige's home only. let paige_id = { - let registry = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + let registry = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let state = AdmissionState::for_persona(&paige_home, registry) .await .expect("paige setup"); @@ -33,7 +33,7 @@ use super::*; let mut tries = 0; loop { let paige_registry = - Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let paige_state = AdmissionState::for_persona(&paige_home, paige_registry) .await .expect("paige reload"); @@ -49,7 +49,7 @@ use super::*; // Niko's fresh state must NOT see Paige's engram. let niko_registry = - Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); + Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); let niko_state = AdmissionState::for_persona(&niko_home, niko_registry) .await .expect("niko setup"); @@ -80,7 +80,7 @@ use super::*; #[test] pub(super) fn restore_drops_post_checkpoint_engrams_but_keeps_baseline() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mut trace = CognitionTrace::new(); @@ -135,7 +135,7 @@ use super::*; #[test] pub(super) fn semantic_beliefs_matching_is_semantic_only_key_overlap() { let state = AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), )); let mk = |kind: EngramKind, content: &str| Engram { id: Uuid::new_v4(), diff --git a/core/continuum-mind/src/persona/attention.rs b/core/continuum-cognition/src/cognition/attention.rs similarity index 98% rename from core/continuum-mind/src/persona/attention.rs rename to core/continuum-cognition/src/cognition/attention.rs index 17c2ac7397..a443230d71 100644 --- a/core/continuum-mind/src/persona/attention.rs +++ b/core/continuum-cognition/src/cognition/attention.rs @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::salience::{Expectation, SalienceLevel}; +use crate::cognition::conversation::salience::{Expectation, SalienceLevel}; /// How much of the world she lets in beside her task. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/core/continuum-mind/src/cognition/audience.rs b/core/continuum-cognition/src/cognition/audience.rs similarity index 100% rename from core/continuum-mind/src/cognition/audience.rs rename to core/continuum-cognition/src/cognition/audience.rs diff --git a/core/continuum-mind/src/cognition/bench_round.rs b/core/continuum-cognition/src/cognition/bench_round.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_round.rs rename to core/continuum-cognition/src/cognition/bench_round.rs diff --git a/core/continuum-mind/src/cognition/bench_round/review_parent.rs b/core/continuum-cognition/src/cognition/bench_round/review_parent.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_round/review_parent.rs rename to core/continuum-cognition/src/cognition/bench_round/review_parent.rs diff --git a/core/continuum-mind/src/cognition/bench_round/round_card_snapshot.rs b/core/continuum-cognition/src/cognition/bench_round/round_card_snapshot.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_round/round_card_snapshot.rs rename to core/continuum-cognition/src/cognition/bench_round/round_card_snapshot.rs diff --git a/core/continuum-mind/src/cognition/bench_round/tests.rs b/core/continuum-cognition/src/cognition/bench_round/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_round/tests.rs rename to core/continuum-cognition/src/cognition/bench_round/tests.rs diff --git a/core/continuum-mind/src/cognition/bench_round/work_driver.rs b/core/continuum-cognition/src/cognition/bench_round/work_driver.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_round/work_driver.rs rename to core/continuum-cognition/src/cognition/bench_round/work_driver.rs diff --git a/core/continuum-mind/src/cognition/bench_task.rs b/core/continuum-cognition/src/cognition/bench_task.rs similarity index 100% rename from core/continuum-mind/src/cognition/bench_task.rs rename to core/continuum-cognition/src/cognition/bench_task.rs diff --git a/core/continuum-mind/src/cognition/benchmark.rs b/core/continuum-cognition/src/cognition/benchmark.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark.rs rename to core/continuum-cognition/src/cognition/benchmark.rs diff --git a/core/continuum-mind/src/cognition/benchmark_algotune.rs b/core/continuum-cognition/src/cognition/benchmark_algotune.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_algotune.rs rename to core/continuum-cognition/src/cognition/benchmark_algotune.rs diff --git a/core/continuum-mind/src/cognition/benchmark_ds1000.rs b/core/continuum-cognition/src/cognition/benchmark_ds1000.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_ds1000.rs rename to core/continuum-cognition/src/cognition/benchmark_ds1000.rs diff --git a/core/continuum-mind/src/cognition/benchmark_humaneval.rs b/core/continuum-cognition/src/cognition/benchmark_humaneval.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_humaneval.rs rename to core/continuum-cognition/src/cognition/benchmark_humaneval.rs diff --git a/core/continuum-mind/src/cognition/benchmark_mirrorcode.rs b/core/continuum-cognition/src/cognition/benchmark_mirrorcode.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_mirrorcode.rs rename to core/continuum-cognition/src/cognition/benchmark_mirrorcode.rs diff --git a/core/continuum-mind/src/cognition/benchmark_super.rs b/core/continuum-cognition/src/cognition/benchmark_super.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_super.rs rename to core/continuum-cognition/src/cognition/benchmark_super.rs diff --git a/core/continuum-mind/src/cognition/benchmark_terminalbench.rs b/core/continuum-cognition/src/cognition/benchmark_terminalbench.rs similarity index 100% rename from core/continuum-mind/src/cognition/benchmark_terminalbench.rs rename to core/continuum-cognition/src/cognition/benchmark_terminalbench.rs diff --git a/core/continuum-mind/src/cognition/bounded_room_ledger.rs b/core/continuum-cognition/src/cognition/bounded_room_ledger.rs similarity index 97% rename from core/continuum-mind/src/cognition/bounded_room_ledger.rs rename to core/continuum-cognition/src/cognition/bounded_room_ledger.rs index c9395ffe79..cf5be0a471 100644 --- a/core/continuum-mind/src/cognition/bounded_room_ledger.rs +++ b/core/continuum-cognition/src/cognition/bounded_room_ledger.rs @@ -47,11 +47,11 @@ use std::hash::Hash; /// for its lifetime history. A citizen here is subscribed to six rooms, so the /// cap is well above ordinary work and far below the unbounded growth per-task /// rooms would otherwise produce. -pub(crate) const ROOMS_TRACKED: usize = 32; +pub const ROOMS_TRACKED: usize = 32; /// A bounded map from room to some small diagnostic value. #[derive(Debug)] -pub(crate) struct BoundedRoomLedger { +pub struct BoundedRoomLedger { entries: HashMap, /// Least-recently-written FIRST. Holds exactly the keys in `entries`. order: VecDeque, @@ -59,7 +59,7 @@ pub(crate) struct BoundedRoomLedger { } impl BoundedRoomLedger { - pub(crate) fn new(cap: usize) -> Self { + pub fn new(cap: usize) -> Self { Self { entries: HashMap::new(), // A cap of 0 would make every insert evict what it just wrote: a @@ -80,7 +80,7 @@ impl BoundedRoomLedger { /// held one. `None` means either never-seen or evicted, deliberately the same /// answer, because the ledger cannot distinguish them and pretending /// otherwise is the exact failure this PR is about. - pub(crate) fn insert(&mut self, key: K, value: V) -> Option { + pub fn insert(&mut self, key: K, value: V) -> Option { let previous = self.entries.insert(key, value); self.touch(key); while self.order.len() > self.cap { @@ -97,8 +97,8 @@ impl BoundedRoomLedger { /// evictable, so leaving it available to production invites that bug rather /// than serving a need. Ungate it the day a real caller wants it, with a /// decision about recency attached. - #[cfg(test)] - pub(crate) fn get(&self, key: &K) -> Option<&V> { + #[cfg(any(test, feature = "test-fixtures"))] + pub fn get(&self, key: &K) -> Option<&V> { self.entries.get(key) } diff --git a/core/continuum-mind/src/persona/cached_source.rs b/core/continuum-cognition/src/cognition/cached_source.rs similarity index 100% rename from core/continuum-mind/src/persona/cached_source.rs rename to core/continuum-cognition/src/cognition/cached_source.rs diff --git a/core/continuum-mind/src/cognition/capture.rs b/core/continuum-cognition/src/cognition/capture.rs similarity index 100% rename from core/continuum-mind/src/cognition/capture.rs rename to core/continuum-cognition/src/cognition/capture.rs diff --git a/core/continuum-mind/src/cognition/capture_owner.rs b/core/continuum-cognition/src/cognition/capture_owner.rs similarity index 100% rename from core/continuum-mind/src/cognition/capture_owner.rs rename to core/continuum-cognition/src/cognition/capture_owner.rs diff --git a/core/continuum-mind/src/persona/work_board/facts.rs b/core/continuum-cognition/src/cognition/card_facts.rs similarity index 95% rename from core/continuum-mind/src/persona/work_board/facts.rs rename to core/continuum-cognition/src/cognition/card_facts.rs index 583375ec29..ef2db4bc61 100644 --- a/core/continuum-mind/src/persona/work_board/facts.rs +++ b/core/continuum-cognition/src/cognition/card_facts.rs @@ -8,7 +8,7 @@ use uuid::Uuid; /// is heartbeat-extendable; this is just the initial TTL. /// /// Shared with the persona runtime's heartbeat pump -/// ([`crate::persona::airc_runtime`]), which renews a citizen's live claims on the +/// (`persona::airc_runtime`), which renews a citizen's live claims on the /// presence cadence. ONE lease length, one place — a renewal that used a different /// TTL than the claim would make "how long is my hold good for" answerable two ways. pub const DEFAULT_CLAIM_TTL_MS: u64 = 30 * 60 * 1000; diff --git a/core/continuum-mind/src/persona/card_holder.rs b/core/continuum-cognition/src/cognition/card_holder.rs similarity index 95% rename from core/continuum-mind/src/persona/card_holder.rs rename to core/continuum-cognition/src/cognition/card_holder.rs index 3ab817526a..8dca8c2151 100644 --- a/core/continuum-mind/src/persona/card_holder.rs +++ b/core/continuum-cognition/src/cognition/card_holder.rs @@ -258,7 +258,7 @@ pub fn in_flight_by(cards: &[WorkCard], holders: &std::collections::HashSet String { @@ -389,6 +389,39 @@ impl CardHolder { } } +/// A card whose work is over (merged or closed): never held, never renewed, whatever its +/// claim fields still say. The one rule for the walk and the followed claims alike. +pub fn settled_card(state: &airc_work::model::CardState) -> bool { + matches!(state, airc_work::model::CardState::Closed | airc_work::model::CardState::Merged) +} + +/// The HELD subset of an owned walk: lease live, not claimable, not settled. Split from the +/// walk so one board read can feed both the renewal (holds) and the handoff record (all of +/// what she owns, whole) — never two walks for one seam. +pub fn held_of_owned( + owned: Vec<(airc_lib::Room, airc_lib::WorkCard)>, + now_ms: u64, +) -> Vec<(airc_lib::Room, airc_lib::WorkCard)> { + owned + .into_iter() + .filter(|(_, card)| { + // A settled card is nobody's work, whatever its lease says: a closed card + // whose claim fields outlive the close read as HELD, focused her ticks on a + // finished room and made the pull think she had work (2026-09-13 14:0xZ). + !settled_card(&card.state) && hold_of(card, now_ms) + == Hold::Held + && !claimable_now(card, now_ms) + }) + .collect() +} + +/// Latest accepted candidate in the board's transcript order. AIRC projects submissions +/// newest first; publisher wall clocks do not define recency. Keep handoff and review +/// consumers on this contract so a resumed citizen sees the candidate being reviewed. +pub fn latest_submission(card: &airc_lib::WorkCard) -> Option<&airc_work::WorkSubmission> { + card.submissions.first() +} + #[cfg(test)] mod tests { use super::*; diff --git a/core/continuum-mind/src/cognition/channel_digest.rs b/core/continuum-cognition/src/cognition/channel_digest.rs similarity index 99% rename from core/continuum-mind/src/cognition/channel_digest.rs rename to core/continuum-cognition/src/cognition/channel_digest.rs index 40619b6a0e..31c895aa81 100644 --- a/core/continuum-mind/src/cognition/channel_digest.rs +++ b/core/continuum-cognition/src/cognition/channel_digest.rs @@ -41,7 +41,7 @@ use airc_lib::AircError; use uuid::Uuid; use crate::cognition::channel_element::{ChannelElement, ChannelElementCache}; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; /// Default N-before-bookmark grounding when a caller has no recipe-specified value. /// Recipe/RoomPurpose resolution belongs to the caller; this is only the floor. diff --git a/core/continuum-mind/src/cognition/channel_digest_region.rs b/core/continuum-cognition/src/cognition/channel_digest_region.rs similarity index 94% rename from core/continuum-mind/src/cognition/channel_digest_region.rs rename to core/continuum-cognition/src/cognition/channel_digest_region.rs index ea1385020d..338c8dfb14 100644 --- a/core/continuum-mind/src/cognition/channel_digest_region.rs +++ b/core/continuum-cognition/src/cognition/channel_digest_region.rs @@ -31,7 +31,7 @@ use async_trait::async_trait; use uuid::Uuid; use crate::cognition::channel_digest::{ChannelDigest, ChannelDigestBuilder, DEFAULT_GROUNDING}; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::runtime::brain_region::{ BrainRegion, CadenceHint, ComputeClass, MemoryClass, PressureProfile, RegionContext, RegionId, TickOutcome, @@ -190,23 +190,6 @@ impl BrainRegion for ChannelDigestRegion { } } -// ─── Real impl: resolve reader + room from the persona runtime registry ────────── - -impl PersonaChannelReader for crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry { - fn live_personas(&self) -> Vec { - // Inherent method of the same name; qualify to avoid trait/inherent ambiguity. - crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry::live_personas(self) - } - - fn reader_and_room(&self, persona_id: Uuid) -> Option<(Arc, Uuid)> { - let runtime = self.get(persona_id)?; - let room = runtime.default_room().as_uuid(); - // PersonaAircRuntime: AircTranscriptReader — upcast the Arc. - let reader: Arc = runtime; - Some((reader, room)) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/core/continuum-mind/src/cognition/channel_element.rs b/core/continuum-cognition/src/cognition/channel_element.rs similarity index 98% rename from core/continuum-mind/src/cognition/channel_element.rs rename to core/continuum-cognition/src/cognition/channel_element.rs index bee38f6151..02d9daf567 100644 --- a/core/continuum-mind/src/cognition/channel_element.rs +++ b/core/continuum-cognition/src/cognition/channel_element.rs @@ -84,11 +84,11 @@ impl ChannelElement { /// identity), which `sender_id()` exposes so digests attribute the words to the /// speaker, not to the core's relay peer. fn new(event: TranscriptEvent, embedder: Arc) -> Self { - // The ONE room-turn decoder (persona::room_event::room_turn_from_event) recovers + // The ONE room-turn decoder (cognition::conversation::room_event::room_turn_from_event) recovers // text + logical sender for BOTH wire shapes. A non-turn (presence, // event-bridge, decode error) is simply a text-less element here; the // skip-reason visibility lives on the perception path. - let (text, logical_sender) = match crate::persona::room_event::room_turn_from_event(&event) + let (text, logical_sender) = match crate::cognition::conversation::room_event::room_turn_from_event(&event) { Ok((sender, text)) => (Some(text), Some(sender)), Err(_) => (None, None), diff --git a/core/continuum-mind/src/cognition/channel_substrate.rs b/core/continuum-cognition/src/cognition/channel_substrate.rs similarity index 100% rename from core/continuum-mind/src/cognition/channel_substrate.rs rename to core/continuum-cognition/src/cognition/channel_substrate.rs diff --git a/core/continuum-mind/src/cognition/check_redundancy.rs b/core/continuum-cognition/src/cognition/check_redundancy.rs similarity index 100% rename from core/continuum-mind/src/cognition/check_redundancy.rs rename to core/continuum-cognition/src/cognition/check_redundancy.rs diff --git a/core/continuum-mind/src/cognition/context_budget.rs b/core/continuum-cognition/src/cognition/context_budget.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_budget.rs rename to core/continuum-cognition/src/cognition/context_budget.rs diff --git a/core/continuum-mind/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/actions.rs rename to core/continuum-cognition/src/cognition/context_streams/actions.rs diff --git a/core/continuum-mind/src/cognition/context_streams/blocks.rs b/core/continuum-cognition/src/cognition/context_streams/blocks.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/blocks.rs rename to core/continuum-cognition/src/cognition/context_streams/blocks.rs diff --git a/core/continuum-mind/src/cognition/context_streams/conversation.rs b/core/continuum-cognition/src/cognition/context_streams/conversation.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/conversation.rs rename to core/continuum-cognition/src/cognition/context_streams/conversation.rs diff --git a/core/continuum-mind/src/cognition/context_streams/mod.rs b/core/continuum-cognition/src/cognition/context_streams/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/mod.rs rename to core/continuum-cognition/src/cognition/context_streams/mod.rs diff --git a/core/continuum-mind/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/tests.rs rename to core/continuum-cognition/src/cognition/context_streams/tests.rs diff --git a/core/continuum-mind/src/cognition/context_streams/thoughts.rs b/core/continuum-cognition/src/cognition/context_streams/thoughts.rs similarity index 100% rename from core/continuum-mind/src/cognition/context_streams/thoughts.rs rename to core/continuum-cognition/src/cognition/context_streams/thoughts.rs diff --git a/core/continuum-mind/src/persona/channel_items.rs b/core/continuum-cognition/src/cognition/conversation/channel_items.rs similarity index 100% rename from core/continuum-mind/src/persona/channel_items.rs rename to core/continuum-cognition/src/cognition/conversation/channel_items.rs diff --git a/core/continuum-mind/src/persona/channel_items/tests.rs b/core/continuum-cognition/src/cognition/conversation/channel_items/tests.rs similarity index 100% rename from core/continuum-mind/src/persona/channel_items/tests.rs rename to core/continuum-cognition/src/cognition/conversation/channel_items/tests.rs diff --git a/core/continuum-mind/src/persona/channel_types.rs b/core/continuum-cognition/src/cognition/conversation/channel_types.rs similarity index 100% rename from core/continuum-mind/src/persona/channel_types.rs rename to core/continuum-cognition/src/cognition/conversation/channel_types.rs diff --git a/core/continuum-cognition/src/cognition/conversation/mod.rs b/core/continuum-cognition/src/cognition/conversation/mod.rs new file mode 100644 index 0000000000..d0c0bb6b2e --- /dev/null +++ b/core/continuum-cognition/src/cognition/conversation/mod.rs @@ -0,0 +1,183 @@ +//! The conversation contract: what a mind perceives arriving in a room and how she answers +//! into one, owned by cognition so the act/observe drive, the settle and the experience +//! stream name no persona module. Persona supplies the live transport (airc) behind +//! [`PersonaConversation`]; cognition only drives it. +//! +//! The leaf group a room line renders through lives here with it: the room-event decoders +//! (`room_event`), the channel queue items and types, the inbox types, salience, and the +//! persona identity a recipient is named by. + +use std::sync::Arc; + +use async_trait::async_trait; +use uuid::Uuid; + +pub mod channel_items; +pub mod channel_types; +pub mod persona_identity; +pub mod room_event; +pub mod salience; +#[cfg(any(test, feature = "test-fixtures"))] +pub mod scripted_conversation; +pub mod seen_ids; +pub mod transcript_reader; +pub mod types; +pub mod workspace_turns; + +/// In-process inbox depth between the pump and the loop. A turn in progress +/// can leave the loop away for minutes; 8k events is hours of a busy room. +pub const INBOX_CAPACITY: usize = 8_192; + +/// Events paged per room per catch-up tick. +pub const CATCH_UP_PAGE: usize = 32; + +/// A substrate-friendly slice of one airc event: just what the +/// service loop needs to decide whether to respond. Strips away the +/// full `TranscriptEvent` surface so the conversation abstraction +/// stays compact and the trait remains stubbable without dragging +/// every airc type into the test. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct IncomingMessage { + /// The transcript event this turn came from — the row a `chat:heard` + /// receipt points back at. Nil for scripted/synthetic turns. + pub event_id: Uuid, + /// Monotonic lamport clock — used for pre-attach high-water-mark + /// filtering. + pub lamport: u64, + /// Cryptographic source identity per + /// [[persona-identity-derives-from-source-id]]. The loop compares + /// against the hosting persona's own peer_id to skip self-loop + /// echoes. + pub peer_id: Uuid, + /// Caption/text of the room message. + pub text: String, + /// Durable references only; decoding a message never fetches attachment bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub media: Vec, + /// The room the event ARRIVED in — the transport's `TranscriptEvent.room_id`, + /// which is authoritative for the turn's context (A.6, the missing context + /// axis). Nil means the source predates room stamping (scripted/test + /// conversations) and the loop falls back to `identity.default_room`; a real + /// wire event always carries its room. Without this, an operator's CLI + /// publish woke the persona into a nil-room turn where every room-scoped + /// RAG source (roster, doctrine, board, kanban) abstained — she heard the + /// words but stood in no room (glass-boxed 2026-07-23, Anwen ACK test). + pub room_id: Uuid, + /// A typed work fact (a verdict, a card move, a submission, a claim) decoded + /// from the room by `cognition::conversation::room_event::room_work_from_event`. `Some` means this + /// turn is a BOARD FACT she perceives, rendered as such, never as the actor's + /// speech; `peer_id` is the actor (the reviewer, the mover). Phase 1 wiring of + /// EVENT-MIND.md: measured 2026-10-04, a PASS on her own card reached her node + /// and was dropped as `non_chat_schema`; nothing on her board could wake her. + pub work: Option, +} + +impl IncomingMessage { + pub fn render_content(&self) -> String { + if let Some(work) = &self.work { + return room_event::render_room_work(work, self.peer_id); + } + room_event::render_room_content(&self.text, &self.media) + } + + /// The same source-labelled input at inference, replay and teaching boundaries. + /// This is rendering, not a replacement for the typed event/room identity. + pub fn render_room_update(&self) -> String { + format!( + "[Room message received during this turn; room {}; peer {}; event {}]\n{}", + self.room_id, self.peer_id, self.event_id, self.render_content() + ) + } +} + +/// Polymorphism rail for "talk to the grid as this persona". The +/// substrate's loop never touches `airc_lib::Airc` directly; the +/// real surface is behind this trait. Slice 11 ships the +/// `AircPersonaConversation` impl. +/// +/// All methods are async because the production impl chains over +/// airc's IPC socket. Tests use a stub that's instant. +#[async_trait] +pub trait PersonaConversation: Send + Sync { + /// Open whatever connection / stream / state the conversation + /// needs to start yielding messages. Called once at boot, BEFORE + /// the first `high_water_mark` or `next_message`. + /// + /// Production (`AircPersonaConversation`): opens the airc + /// subscribe stream. Without `prime`, the stream was opened + /// lazily on first `next_message`, which paid the daemon + /// round-trip on the cognition hot path. With `prime`, that + /// round-trip lands at the supervisor's boot phase — the + /// persona is "ready to converse" the moment her service loop + /// starts iterating. + /// + /// Tests (`StubConversation`): no-op. Idempotent — calling + /// `prime` twice is safe but the second call is a no-op. + /// + /// Returns `Err` if priming fails (daemon unreachable, room + /// gone). Per [[no-fallbacks-ever]] the loop refuses to start + /// rather than entering a degraded path. + async fn prime(&mut self) -> Result<(), String>; + + /// Highest lamport observed in transcript history before live + /// subscription. Used to ignore messages that arrived BEFORE the + /// persona attached — avoids replying to ancient chat just + /// because a restart loaded them through `page_recent`. + async fn high_water_mark(&self, limit: usize) -> Result; + + /// The cutoff established by successful priming. Live conversations freeze + /// this at attach, so starting the loop does not issue another fallible RPC. + async fn initial_water_mark(&self, limit: usize) -> Result { + self.high_water_mark(limit).await + } + + + /// Yield the next inbound message, or `Ok(None)` when the + /// stream is exhausted (daemon disconnected, peer gone). On + /// transient errors (stream lag, transport hiccup) the impl + /// should yield `Err` so the loop can record + continue. + /// + /// Assumes `prime` was called once at boot. If it wasn't, the + /// impl MAY lazy-prime (production currently does, for + /// backward compat) but the substrate's preferred path is + /// eager priming so the round-trip lands off the hot path. + async fn next_message(&mut self) -> Result, String>; + + /// Perceive currently ready room input without waiting for a new arrival. + /// The conversation RETAINS ownership for subsequent room attention, including + /// if the active drive is cancelled or cannot fit these inputs. Repeated + /// snapshots may overlap: the drive uses the ordinary event-id deduper. + async fn perceive_ready( + &mut self, + ) -> Result<&std::collections::VecDeque>, String>; + + /// Reply with text INTO A NAMED ROOM — normally the room the turn + /// being answered arrived in ([`IncomingMessage::room_id`]). + /// + /// Not "the persona's default room", which is what this used to + /// be. A persona is in more than one room, so a reply that always + /// went to her default answered the wrong audience the moment she + /// was addressed anywhere else — visibly worse than silence, + /// because it reads as a non-sequitur rather than a missing wire. + /// `Uuid::nil()` keeps the documented pre-room-stamping contract + /// (scripted / test sources) and routes to her default. + async fn say_in(&self, room_id: Uuid, text: &str) -> Result<(), String>; + + /// Her wakes from the one feed (EVENT-MIND §1b), once her perception region has + /// booted; `None` before then, after they were taken, or for a conversation with no + /// region. The serve loop takes them once and consumes them beside her inbox. + fn take_wakes(&mut self) -> Option> { + None + } +} + +/// Why she is being woken. The activity rides on the wake; no room is implied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Wake { + /// An activity's delta is loud enough for her dial. + Perceive { activity: Uuid, salience: salience::Salience }, + /// The time she expected something by has passed. + Continuation, + /// First wake after a restart: continue what she was doing. + Resume, +} diff --git a/core/continuum-mind/src/persona/persona_identity.rs b/core/continuum-cognition/src/cognition/conversation/persona_identity.rs similarity index 100% rename from core/continuum-mind/src/persona/persona_identity.rs rename to core/continuum-cognition/src/cognition/conversation/persona_identity.rs diff --git a/core/continuum-mind/src/persona/room_event.rs b/core/continuum-cognition/src/cognition/conversation/room_event.rs similarity index 94% rename from core/continuum-mind/src/persona/room_event.rs rename to core/continuum-cognition/src/cognition/conversation/room_event.rs index 5cdc204057..fb0675a8ad 100644 --- a/core/continuum-mind/src/persona/room_event.rs +++ b/core/continuum-cognition/src/cognition/conversation/room_event.rs @@ -13,7 +13,7 @@ use crate::routing::airc_realtime_wire::{envelope_from_event, is_command_frame, pub struct RoomTurn { pub sender: uuid::Uuid, pub text: String, - pub media: Vec, + pub media: Vec, } /// A typed work fact in the room, as perception (EVENT-MIND.md §1b, phase 1 @@ -21,10 +21,10 @@ pub struct RoomTurn { /// (a PASS on her own card) replicated to her node and her inbound dropped it as /// `non_chat_schema`, 519 of 520 events; only chat was perception. A citizen who /// cannot perceive her own board cannot be woken by it. The decoder now yields the -/// board's typed events beside speech; `persona::salience` judges them. +/// board's typed events beside speech; `cognition::conversation::salience` judges them. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum RoomWork { - Reviewed { card_id: uuid::Uuid, outcome: crate::persona::salience::ObservedVerdict, reviewer: uuid::Uuid, review: uuid::Uuid }, + Reviewed { card_id: uuid::Uuid, outcome: crate::cognition::conversation::salience::ObservedVerdict, reviewer: uuid::Uuid, review: uuid::Uuid }, StateChanged { card_id: uuid::Uuid, state: airc_work::CardState, by: uuid::Uuid }, Submitted { card_id: uuid::Uuid, publisher: uuid::Uuid, #[serde(default)] submission: Option }, Claimed { card_id: uuid::Uuid, owner: uuid::Uuid, #[serde(default)] claim: Option }, @@ -57,9 +57,9 @@ pub fn room_work_from_event(event: &TranscriptEvent) -> Result, card_id: r.card_id.as_uuid(), review: r.review_id.as_uuid(), outcome: match r.outcome { - airc_work::WorkReviewOutcome::Passed => crate::persona::salience::ObservedVerdict::Passed, - airc_work::WorkReviewOutcome::Failed => crate::persona::salience::ObservedVerdict::Failed, - airc_work::WorkReviewOutcome::Unknown => crate::persona::salience::ObservedVerdict::Unknown, + airc_work::WorkReviewOutcome::Passed => crate::cognition::conversation::salience::ObservedVerdict::Passed, + airc_work::WorkReviewOutcome::Failed => crate::cognition::conversation::salience::ObservedVerdict::Failed, + airc_work::WorkReviewOutcome::Unknown => crate::cognition::conversation::salience::ObservedVerdict::Unknown, }, reviewer: r.reviewer.as_uuid(), }, @@ -83,7 +83,7 @@ pub fn room_turn_from_event(event: &TranscriptEvent) -> Result<(uuid::Uuid, Stri /// A bounded notice, not a claim that the model has inspected the attachment. /// The event retains the full references for explicit inspection/replay. -pub(crate) fn render_room_content(text: &str, media: &[crate::persona::channel_items::MediaItemRequest]) -> String { +pub(crate) fn render_room_content(text: &str, media: &[crate::cognition::conversation::channel_items::MediaItemRequest]) -> String { if media.is_empty() { return text.to_owned(); } let mut rendered = format!("{text}\n[{} media attachment(s); contents not loaded", media.len()); for item in media.iter().take(8) { @@ -181,7 +181,7 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result { pub room_id: uuid::Uuid, pub sender_id: uuid::Uuid, pub text: &'a str, - pub media: &'a [crate::persona::channel_items::MediaItemRequest], + pub media: &'a [crate::cognition::conversation::channel_items::MediaItemRequest], pub reply_to_id: Option, } @@ -328,7 +328,7 @@ mod tests { // what this catches: media awareness must not embed URL/base64 or generated descriptions in every turn. #[test] fn media_notice_is_bounded_and_does_not_load_content() { - let item = crate::persona::channel_items::MediaItemRequest { + let item = crate::cognition::conversation::channel_items::MediaItemRequest { kind: "image".into(), mime_type: Some("image/png".into()), blob_hash: Some(format!("sha256:{}", "a".repeat(64))), url: Some(format!("data:image/png;base64,{}", "x".repeat(100_000))), diff --git a/core/continuum-mind/src/persona/salience.rs b/core/continuum-cognition/src/cognition/conversation/salience.rs similarity index 100% rename from core/continuum-mind/src/persona/salience.rs rename to core/continuum-cognition/src/cognition/conversation/salience.rs diff --git a/core/continuum-cognition/src/cognition/conversation/scripted_conversation.rs b/core/continuum-cognition/src/cognition/conversation/scripted_conversation.rs new file mode 100644 index 0000000000..a01003529f --- /dev/null +++ b/core/continuum-cognition/src/cognition/conversation/scripted_conversation.rs @@ -0,0 +1,394 @@ +//! `ScriptedConversation` — system-level `PersonaConversation` impl +//! that feeds a pre-baked queue of events, records every `say()` call, +//! and exposes configurable prime behavior. +//! +//! Per [[test-fixtures-are-system-primitives]]: every test, replay +//! rig, demo binary, and future tool that needs a controllable +//! conversation surface leases THIS struct. There is no +//! `#[cfg(test)]` bespoke variant — that's the cancer this primitive +//! exists to refuse. +//! +//! ## Replaces +//! +//! Pre-#1517 the substrate had three bespoke `#[cfg(test)]` impls +//! across `service_loop::tests`: `StubConversation`, +//! `UnprimedConversation`, `FailingPrimeConversation`. All three +//! collapse into builder configurations of this one type. +//! +//! ## Shape +//! +//! ```ignore +//! use crate::cognition::conversation::scripted_conversation::ScriptedConversation; +//! use crate::cognition::conversation::IncomingMessage; +//! +//! // Happy path: one inbound, then stream end. +//! let mut c = ScriptedConversation::new() +//! .with_events(vec![ +//! Ok(Some(IncomingMessage { lamport: 1, peer_id: pid, text: "hello".into() })), +//! Ok(None), +//! ]); +//! c.prime().await?; +//! let msg = c.next_message().await?; +//! +//! // Prime failure: substrate refuses to start the loop. +//! let mut c = ScriptedConversation::new() +//! .with_prime_failure("simulated airc daemon unreachable"); +//! +//! // Unprimed-call detection: next_message yields a typed err if +//! // the caller forgot to prime first (mirrors AircPersonaConversation). +//! let mut c = ScriptedConversation::new() +//! .with_events(vec![Ok(Some(msg))]) +//! .require_prime_before_next_message(); +//! // Calling next_message without prime() first → Err. +//! ``` +//! +//! ## Doctrine +//! +//! - [[test-fixtures-are-system-primitives]]: this is THE conversation +//! stub. Lease, never reinvent. +//! - [[no-fallbacks-ever]]: every behavior is explicit (prime success +//! vs failure, require-prime vs not); no silent defaults. +//! - [[every-error-is-an-opportunity-to-battle-harden]]: configurable +//! failure modes mean every regression test can lock the contract +//! it cares about. + +use crate::cognition::conversation::{IncomingMessage, PersonaConversation}; +use async_trait::async_trait; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +/// Shared input queue: the conversation consumes events while its feed appends +/// messages, stream endings, or explicit failures at controlled action boundaries. +type ScriptedEventQueue = Arc, String>>>>; + +/// System-level, configurable `PersonaConversation` impl. Public +/// because every test in the substrate leases it; not behind +/// `#[cfg(test)]`. +pub struct ScriptedConversation { + high_water: u64, + events: ScriptedEventQueue, + perceived_backlog: VecDeque>, + /// Every reply the loop posted, WITH the room it was posted into. + /// The room is recorded because "she answered" and "she answered + /// the room that asked" are different claims, and only the second + /// one is the contract — see `said_in`. + said: Mutex>, + /// Explicit transport refusal; failed attempts never enter `said`. + say_failure: Option, + primed: AtomicUsize, + prime_result: Mutex>, + /// When set, `next_message` returns Err if called before `prime` + /// — mirrors `AircPersonaConversation`'s caller-primes contract. + require_prime: bool, + idle_when_empty: bool, + /// A handle the layer above reads back through its own conversation trait — `None` + /// by default. Persona's held-work tests seed the airc citizen `stream_citizen()` + /// returns (`persona::scripted_conversation::ScriptedCitizen`); cognition never + /// reads it. + attachment: Option>, +} + +impl Default for ScriptedConversation { + fn default() -> Self { + Self::new() + } +} + +impl ScriptedConversation { + /// Empty conversation: no events queued, prime succeeds, no + /// pre-prime requirement. Builder methods configure the rest. + pub fn new() -> Self { + Self { + high_water: 0, + events: Arc::new(Mutex::new(VecDeque::new())), + perceived_backlog: VecDeque::new(), + said: Mutex::new(Vec::new()), + say_failure: None, + primed: AtomicUsize::new(0), + prime_result: Mutex::new(Ok(())), + require_prime: false, + idle_when_empty: false, + attachment: None, + } + } + + /// Carry `handle` for the layer above to read back with [`Self::attachment`]. + pub fn with_attachment(mut self, handle: T) -> Self { + self.attachment = Some(Arc::new(handle)); + self + } + + /// The handle [`Self::with_attachment`] carried, when it is a `T`. + pub fn attachment(&self) -> Option { + self.attachment.as_ref()?.downcast_ref::().cloned() + } + + /// Replace the queued events. Each entry is what `next_message` + /// yields on its next call: + /// - `Ok(Some(msg))` → loop processes the message + /// - `Ok(None)` → stream ends; loop returns cleanly + /// - `Err(_)` → transient error; loop records and continues + /// + /// When the queue drains, subsequent `next_message` calls yield + /// `Ok(None)` so the loop never hangs. + pub fn with_events(self, events: Vec, String>>) -> Self { + *self.events.lock().unwrap() = VecDeque::from(events); + self + } + + /// Keep an empty fixture inbox online while exercising the real wake select. + #[cfg(any(test, feature = "test-fixtures"))] + pub fn with_idle_inbox(mut self) -> Self { + self.idle_when_empty = true; + self + } + + /// Lease the scripted source so an in-flight tool can inject an arrival at + /// an exact boundary, without a sleep, second conversation, or live transport. + #[cfg(any(test, feature = "test-fixtures"))] + pub fn event_feed(&self) -> ScriptedConversationFeed { + ScriptedConversationFeed(Arc::clone(&self.events)) + } + + /// Set the pre-attach high-water mark — what `high_water_mark` + /// returns. Defaults to 0 (no pre-attach history). + pub fn with_high_water(mut self, hw: u64) -> Self { + self.high_water = hw; + self + } + + /// Make `prime()` return Err with this reason. Used by tests that + /// verify prime-failure short-circuits the spawn path + /// (`spawn_persona_service` returns Err; supervisor records + /// `BootSlotFailure`). + pub fn with_prime_failure(self, reason: impl Into) -> Self { + *self.prime_result.lock().unwrap() = Err(reason.into()); + self + } + + /// Refuse publication without pretending a message reached the room. + pub fn with_say_failure(mut self, reason: impl Into) -> Self { + self.say_failure = Some(reason.into()); + self + } + + /// Reject `next_message` calls until `prime()` has been invoked at + /// least once — mirrors `AircPersonaConversation`'s caller-primes + /// contract per [[no-fallbacks-ever]]. Used by the regression + /// test that locks the absence of the belt-and-suspenders prime. + pub fn require_prime_before_next_message(mut self) -> Self { + self.require_prime = true; + self + } + + /// How many times `prime()` has been called. Tests assert this is + /// exactly 1 to verify the caller-primes contract (one prime per + /// loop invocation, no belt-and-suspenders). + pub fn primed_count(&self) -> usize { + self.primed.load(Ordering::SeqCst) + } + + /// Snapshot of every text the loop posted. Tests assert reply + /// content + count. Room-agnostic view of the same storage as + /// [`said_in`](Self::said_in) — not a second field. + pub fn said(&self) -> Vec { + self.said + .lock() + .unwrap() + .iter() + .map(|(_room, text)| text.clone()) + .collect() + } + + /// Every reply paired with the room it was posted INTO. This is + /// the surface that can catch a persona answering the wrong + /// audience — invisible to [`said`](Self::said), which only knows + /// that she spoke. + pub fn said_in(&self) -> Vec<(Uuid, String)> { + self.said.lock().unwrap().clone() + } +} + +#[async_trait] +impl PersonaConversation for ScriptedConversation { + async fn prime(&mut self) -> Result<(), String> { + self.primed.fetch_add(1, Ordering::SeqCst); + self.prime_result.lock().unwrap().clone() + } + + async fn high_water_mark(&self, _limit: usize) -> Result { + Ok(self.high_water) + } + + async fn next_message(&mut self) -> Result, String> { + if self.require_prime && self.primed.load(Ordering::SeqCst) == 0 { + // Mirror AircPersonaConversation's typed-err shape. CRITICAL: + // drain ONE event from the queue before returning Err. The + // service loop counts this as `turns_errored` and continues; + // if we didn't drain, the same Err would fire forever and + // the loop would hang. Substrate-correct semantics: each + // call consumes one queue item regardless of whether it + // surfaces an event or an err. Per [[no-fallbacks-ever]] the + // contract is "queue progress per call", not "queue progress + // per success." + let drained = self.events.lock().unwrap().pop_front(); + return match drained { + Some(_) => Err( + "ScriptedConversation::next_message called before prime() — \ + caller must invoke prime() before iterating" + .to_string(), + ), + None => Ok(None), + }; + } + if let Some(message) = self.perceived_backlog.pop_front() { + return Ok(Some(Arc::unwrap_or_clone(message))); + } + let event = self.events.lock().unwrap().pop_front(); + match event { + Some(event) => event, + None if self.idle_when_empty => std::future::pending().await, + None => Ok(None), + } + } + + async fn perceive_ready( + &mut self, + ) -> Result<&std::collections::VecDeque>, String> { + if self.require_prime && self.primed.load(Ordering::SeqCst) == 0 { + return Err("ScriptedConversation::perceive_ready called before prime()".into()); + } + let mut events = self + .events + .lock() + .map_err(|_| "scripted conversation lock poisoned".to_string())?; + for _ in 0..super::CATCH_UP_PAGE { + if self.perceived_backlog.len() >= super::INBOX_CAPACITY { + return Err( + "retained room attention reached inbox capacity; input remains queued".into(), + ); + } + match events.pop_front() { + Some(Ok(Some(message))) => self.perceived_backlog.push_back(Arc::new(message)), + Some(Err(error)) => return Err(error), + Some(Ok(None)) | None => break, + } + } + Ok(&self.perceived_backlog) + } + + async fn say_in(&self, room_id: Uuid, text: &str) -> Result<(), String> { + if let Some(reason) = &self.say_failure { + return Err(reason.clone()); + } + self.said.lock().unwrap().push((room_id, text.to_string())); + Ok(()) + } +} + +/// The input side of a scripted conversation; the service remains its sole reader. +#[derive(Clone)] +#[cfg(any(test, feature = "test-fixtures"))] +pub struct ScriptedConversationFeed(ScriptedEventQueue); + +#[cfg(any(test, feature = "test-fixtures"))] +impl ScriptedConversationFeed { + pub fn push(&self, event: Result, String>) { + self.0 + .lock() + .expect("scripted input lock poisoned") // A poisoned fixture cannot safely inject input; fail the simulation explicitly. + .push_back(event); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn one_msg() -> IncomingMessage { + IncomingMessage { + work: None, + media: Vec::new(), + event_id: uuid::Uuid::nil(), + lamport: 1, + peer_id: Uuid::new_v4(), + text: "hello".into(), + room_id: Uuid::nil(), + } + } + + #[tokio::test] + async fn default_prime_succeeds_and_counts() { + let mut c = ScriptedConversation::new(); + assert_eq!(c.primed_count(), 0); + c.prime().await.expect("default prime ok"); + assert_eq!(c.primed_count(), 1); + } + + #[tokio::test] + async fn with_prime_failure_returns_err() { + let mut c = ScriptedConversation::new().with_prime_failure("simulated daemon unreachable"); + let err = c.prime().await.expect_err("must err"); + assert!(err.contains("simulated daemon unreachable")); + assert_eq!(c.primed_count(), 1, "prime still counts attempts"); + } + + #[tokio::test] + async fn events_drain_then_yield_none() { + let mut c = ScriptedConversation::new().with_events(vec![Ok(Some(one_msg())), Ok(None)]); + assert!(c.next_message().await.unwrap().is_some()); + assert!(c.next_message().await.unwrap().is_none()); + // Past end → still Ok(None), never hangs. + assert!(c.next_message().await.unwrap().is_none()); + } + + #[tokio::test] + async fn require_prime_before_next_message_enforced() { + // TWO events queued — first call (unprimed) drains the first + // event AND returns Err. Second call (post-prime) returns the + // second event. The drain-on-err semantics are load-bearing: + // without them the service loop would re-fire the same Err + // every iteration and never make progress. + let mut c = ScriptedConversation::new() + .with_events(vec![Ok(Some(one_msg())), Ok(Some(one_msg()))]) + .require_prime_before_next_message(); + let err = c.next_message().await.expect_err("unprimed err"); + assert!(err.contains("called before prime()")); + c.prime().await.expect("prime ok"); + assert!( + c.next_message().await.unwrap().is_some(), + "post-prime call gets the SECOND event; first was drained by the Err path" + ); + } + + #[tokio::test] + // what this catches: replies are recorded in order AND against the room each + // was actually posted into. The room half is the load-bearing one — a + // persona answering the wrong room is invisible to `said()`, which only + // knows that she spoke, and that blind spot is what let one-room perception + // look like inattention for a whole evening (task #64). + async fn say_records_in_order_and_remembers_the_room() { + let asked_in = Uuid::new_v4(); + let elsewhere = Uuid::new_v4(); + let c = ScriptedConversation::new(); + c.say_in(asked_in, "one").await.unwrap(); + c.say_in(elsewhere, "two").await.unwrap(); + assert_eq!(c.said(), vec!["one".to_string(), "two".to_string()]); + assert_eq!( + c.said_in(), + vec![ + (asked_in, "one".to_string()), + (elsewhere, "two".to_string()) + ], + "each reply is attributed to the room it went to, not merely counted" + ); + } + + #[tokio::test] + async fn high_water_mark_passes_through() { + let c = ScriptedConversation::new().with_high_water(42); + assert_eq!(c.high_water_mark(0).await.unwrap(), 42); + } +} diff --git a/core/continuum-cognition/src/cognition/conversation/seen_ids.rs b/core/continuum-cognition/src/cognition/conversation/seen_ids.rs new file mode 100644 index 0000000000..3bfe587149 --- /dev/null +++ b/core/continuum-cognition/src/cognition/conversation/seen_ids.rs @@ -0,0 +1,112 @@ +//! Replay and redelivery dedupe at the loop head: the event ids a drive has already +//! perceived, and the one staleness rule a drained line is judged by. + +use std::collections::{HashSet, VecDeque}; + +use uuid::Uuid; + +use super::IncomingMessage; + +/// Event-id ring for replay/redelivery dedupe at the loop head. Small: the +/// pump already dedupes the store catch-up; this catches re-open replays. +pub struct SeenIds { + ring: VecDeque, + ids: HashSet, + cap: usize, +} + +impl SeenIds { + pub fn new(cap: usize) -> Self { + Self { + ring: VecDeque::with_capacity(cap), + ids: HashSet::with_capacity(cap), + cap, + } + } + + /// Note an id; `true` when it is NEW (first sight), `false` on a repeat. + pub fn note(&mut self, id: Uuid) -> bool { + if self.ids.contains(&id) { + return false; + } + if self.cap == 0 { + return true; + } + if self.ring.len() == self.cap { + if let Some(evicted) = self.ring.pop_front() { + self.ids.remove(&evicted); + } + } + self.ids.insert(id); + self.ring.push_back(id); + true + } +} + +/// Is this drained line stale? By event id when the source stamps one; by the +/// publisher clock only for id-less sources (scripted/test conversations). +pub fn is_stale(m: &IncomingMessage, seen: &mut SeenIds, high_water: u64) -> bool { + if m.event_id.is_nil() { + m.lamport <= high_water + } else { + !seen.note(m.event_id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line(peer: u8, lamport: u64, text: &str) -> IncomingMessage { + IncomingMessage { + work: None, + media: Vec::new(), + event_id: Uuid::new_v4(), + lamport, + peer_id: Uuid::from_u128(peer as u128), + room_id: Uuid::from_u128(7), + text: text.to_string(), + } + } + + // what this catches: the per-publisher lamport read a human line as stale + // against citizens' larger clocks (the 9/4 deaf-citizens regression). + #[test] + fn a_human_line_with_a_small_publisher_clock_is_not_stale() { + let mut seen = SeenIds::new(8); + let human = line(1, 3, "Joel here — which card do you hold?"); + assert!(!is_stale(&human, &mut seen, 157_000)); + } + + // what this catches: a re-open replay redelivering the same event id. + #[test] + fn a_replayed_event_id_is_stale_the_second_time() { + let mut seen = SeenIds::new(8); + let m = line(1, 3, "once"); + assert!(!is_stale(&m, &mut seen, 0)); + assert!(is_stale(&m, &mut seen, 0)); + } + + // The index must evict with the ordered ring; retained snapshots do not + // refresh recency or grow the bounded set on duplicate admission. + #[test] + fn seen_id_index_evicts_with_the_ring() { + let mut seen = SeenIds::new(2); + let a = Uuid::new_v4(); + let b = Uuid::new_v4(); + let c = Uuid::new_v4(); + assert!(seen.note(a)); + assert!(seen.note(b)); + assert!(!seen.note(a)); + assert!(seen.note(c)); + assert!(seen.note(a)); + assert!(!seen.note(c)); + assert_eq!(seen.ids.len(), 2); + assert_eq!(seen.ring.len(), 2); + let mut empty = SeenIds::new(0); + assert!(empty.note(a)); + assert!(empty.note(a)); + assert!(empty.ids.is_empty()); + assert!(empty.ring.is_empty()); + } +} diff --git a/core/continuum-cognition/src/cognition/conversation/transcript_reader.rs b/core/continuum-cognition/src/cognition/conversation/transcript_reader.rs new file mode 100644 index 0000000000..44c36f3773 --- /dev/null +++ b/core/continuum-cognition/src/cognition/conversation/transcript_reader.rs @@ -0,0 +1,153 @@ +//! The reader a mind pages a room's conversation through: the contract, the one +//! perception-page filter, and the airc implementation of it. + +use airc_core::TranscriptEvent; +use airc_lib::AircError; +use async_trait::async_trait; + +/// Abstract reader over airc transcript events. Production impl rides on +/// `airc_lib::Airc`; tests use a stub that returns canned events without a daemon. +#[async_trait] +pub trait AircTranscriptReader: Send + Sync { + /// Return up to `limit` most-recent CONVERSATIONAL transcript events + /// (Message + Attachment), newest-first per airc convention. + /// + /// Kinds are filtered BEFORE the page limit (#297): a raw newest-`limit` + /// page counts ephemeral StreamChunk frames (~4/sec per talking persona), + /// so active residents' own streaming evicted every durable message from + /// their window within a minute — working personas were DEAF to direction + /// while the room was busy (glass-boxed live 2026-08-01: a resident asked + /// the same question 3× because four direction messages never entered her + /// page while the attach cursor advanced normally). The diagnostic + /// signature: cross-machine delivery perfect, local perception stale — + /// the wire is fine, the WINDOW is flooded. Presence / receipts / + /// lifecycle ride their own sources; this page is the room's + /// conversation, never its firehose. + async fn page_recent(&self, limit: usize) -> Result, AircError>; + + /// Room-scoped page (#367): return the same conversational page, but for + /// the given room when `Some` — the TURN's room, not the reader's + /// current-room pointer. `page_recent` follows the persona's landing-room + /// pointer, so a turn happening anywhere else (a bench room, a project + /// room she is subscribed to but not "in") paged the DEFAULT room's + /// transcript — and everything downstream (digest, derived-room fallback, + /// the recall query built from this window) followed the wrong room. + /// + /// Default impl ignores `room` and delegates — correct ONLY for test + /// stubs whose canned events have no room dimension. Every production + /// reader overrides this (the #262 lesson in `AircHandleAdapter`: a + /// silently-inherited default is how regressions ship). + async fn page_recent_in( + &self, + room: Option, + limit: usize, + ) -> Result, AircError> { + let _ = room; + self.page_recent(limit).await + } + + /// This reader's last-read lamport in `room` — the unread marker. + /// + /// THE CURSOR LIVES IN AIRC. It is durable runtime-consumer state + /// (`runtime_cursor`, an ORM row keyed by consumer id), and airc's own API + /// doc says why it exists: "intentionally store-backed so runtime delivery + /// state does not sprawl into JSON sidecars." Continuum previously kept a + /// PARALLEL `ChannelBookmarks` DashMap for this — process-memory only, so + /// every cursor died on restart, and a second source of truth for a fact + /// airc already owns. That is the defect this method removes. + /// + /// `0` = never read. Real airc lamports are >= 1. + async fn read_cursor(&self, persona: uuid::Uuid, room: uuid::Uuid) -> Result { + let _ = (persona, room); + Ok(0) + } + + /// Persist this reader's position in `room` at `event` — mark-read. + /// + /// Takes the EVENT, not a bare lamport, because airc's preferred path + /// (`save_runtime_cursor_for_event`) carries the source event's room and + /// kind and emits `SubscriptionAdvanced`, so a cursor move is visible to + /// every other surface instead of being private to one process. A bare + /// lamport would throw that away. + async fn advance_read_cursor( + &self, + persona: uuid::Uuid, + room: uuid::Uuid, + event: &TranscriptEvent, + ) -> Result<(), AircError> { + let _ = (persona, room, event); + Ok(()) + } +} + +/// The durable consumer id for one reader's position in one room. +/// +/// Namespaced string because that IS airc's convention for `runtime_cursor` +/// (its own rows look like `codex-hook:default`); the entity is keyed by a +/// consumer id, so this composes airc's key, it does not invent an identifier. +/// Both halves are rendered from real UUIDs — never a name, never a label. +pub fn read_cursor_consumer_id(persona: uuid::Uuid, room: uuid::Uuid) -> String { + format!("persona:{persona}:room:{room}") +} + +/// The kinds a perception page means: the room's conversation. ONE place +/// (compression) — every reader impl funnels through the [`airc_lib::Airc`] +/// impl below, which applies this filter. +pub fn perception_page_filter() -> airc_lib::EventFilter { + let mut filter = airc_lib::EventFilter::current_room(); + filter.kinds.insert(airc_core::TranscriptKind::Message); + filter.kinds.insert(airc_core::TranscriptKind::Attachment); + filter +} + +/// The same conversational-kinds filter, pinned to a specific room (#367). +/// `None` leaves the channel unset, which `page_recent_filtered` scopes to +/// the current room — the pre-#367 behavior, still right for genuinely +/// room-less work. +pub fn perception_page_filter_in(room: Option) -> airc_lib::EventFilter { + let mut filter = perception_page_filter(); + filter.channel = room; + filter +} + +/// `airc_lib::Airc` satisfies the reader contract via the kinds-filtered +/// page (daemon-side newest-N-of-kind since airc PR #1314). Orphan rule OK — +/// the trait is ours. +#[async_trait] +impl AircTranscriptReader for airc_lib::Airc { + async fn page_recent(&self, limit: usize) -> Result, AircError> { + airc_lib::Airc::page_recent_filtered(self, perception_page_filter(), limit).await + } + + async fn page_recent_in( + &self, + room: Option, + limit: usize, + ) -> Result, AircError> { + airc_lib::Airc::page_recent_filtered(self, perception_page_filter_in(room), limit).await + } + + /// airc's durable `runtime_cursor` row IS the unread marker — no second store. + async fn read_cursor(&self, persona: uuid::Uuid, room: uuid::Uuid) -> Result { + Ok( + airc_lib::Airc::load_runtime_cursor(self, &read_cursor_consumer_id(persona, room)) + .await? + .map(|c| c.lamport) + .unwrap_or(0), + ) + } + + async fn advance_read_cursor( + &self, + persona: uuid::Uuid, + room: uuid::Uuid, + event: &TranscriptEvent, + ) -> Result<(), AircError> { + airc_lib::Airc::save_runtime_cursor_for_event( + self, + &read_cursor_consumer_id(persona, room), + event, + ) + .await + } +} diff --git a/core/continuum-mind/src/persona/types.rs b/core/continuum-cognition/src/cognition/conversation/types.rs similarity index 100% rename from core/continuum-mind/src/persona/types.rs rename to core/continuum-cognition/src/cognition/conversation/types.rs diff --git a/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs b/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs new file mode 100644 index 0000000000..d5b9a59698 --- /dev/null +++ b/core/continuum-cognition/src/cognition/conversation/workspace_turns.rs @@ -0,0 +1,668 @@ +//! The burst a mind deliberates over, built from the room deliveries: each airc item as an +//! attributed turn, the waking message anchored last, and the repetition observations and +//! work-board anchors a cyclic thread earns. ONE format, shared by the live heartbeat, the +//! self-tick and the eval fork, so a measured turn perceives its world byte-identically to +//! a lived one. A pure projection: no transport, no persona state. + +/// Build the consolidated workspace burst (WHO/WHEN/WHAT per inbox item, own posts +/// attributed, room as the WHERE) the `WorkspaceCycle` reasons over. A pure +/// projection of the airc deliveries — extracted so the message turn and the +/// never-stop self-tick share ONE burst truth ([[compression-principle]]). +/// Assemble the perception envelope a persona's deliberation sees: the room +/// header + each airc delivery item rendered as `[t=ms] who: content`, with the +/// persona's OWN past posts attributed to `agent_name` (so she recognizes her +/// own voice) and everyone else by peer_id. This is the ONE place the burst +/// string format lives — the live heartbeat (both the message path and the +/// self-thread) AND the eval fork call it, so a measured turn perceives its +/// world byte-identically to a lived one. Takes `&[RagDelivery]` (not the whole +/// `ComposedTurn`) because the format only depends on the deliveries; eval can +/// hand-build a single synthetic airc delivery for a task without composing a +/// full turn. +/// The message that WOKE a turn — anchored as the burst's final peer turn so the +/// persona always perceives what it is answering, regardless of RAG-delivery lag. +/// +/// The `airc` RAG delivery that threads the conversation is refreshed +/// asynchronously from the wake, so a directed message can trigger a turn whose +/// composed thread still ends on the persona's OWN prior reply. The model then +/// sees nothing new after its last turn and emits an empty completion +/// (decodeTokens=1, text="") which parses as Pass — the persona goes silent on a +/// question addressed straight at it, then answers ~one self-tick later once the +/// delivery catches up. Carrying the trigger here lets `build_workspace_turns` +/// guarantee it is the last `user` turn, deterministically, with no dependence on +/// delivery timing. The self-tick / eval / turn_frame callers pass `None` (they +/// perceive ambient state, no single triggering message) and stay byte-identical. +pub struct TriggerTurn<'a> { + /// The waking peer's id — resolved to a display name through the SAME roster + /// `names` map the rest of the thread uses (falls back to the raw id, honest, + /// never fabricated — the [[fallbacks-are-illegal-fail-loud]] doctrine). + pub peer_id: &'a str, + /// The message body that triggered the turn. + pub content: &'a str, + /// Event occurrence time when measured; zero means unknown. Never substitute + /// the wake/turn clock for an event timestamp missing from the source. + pub occurred_at_ms: u64, +} + +/// The shared roster projection's admitted atoms. The legacy source remains +/// readable for existing replay/diagnostic deliveries; live turns use KIND. +pub fn roster_items( + deliveries: &[crate::cognition::rag_budget::RagDelivery], +) -> impl Iterator { + deliveries + .iter() + .filter(|d| { + d.source_id == continuum_positron::RosterViewState::KIND + || d.source_id == crate::cognition::faculty_ids::ROOM_ROSTER + }) + .flat_map(|d| d.items.iter()) +} + +/// Resolve identity from admitted roster atoms, never rendered text or a second +/// unbudgeted roster read. Legacy replay deliveries carry the same metadata. +pub fn roster_identities( + deliveries: &[crate::cognition::rag_budget::RagDelivery], +) -> impl Iterator { + roster_items(deliveries).filter_map(|item| { + Some(( + item.metadata.get("peer_id")?.as_str()?, + item.metadata.get("display_name")?.as_str()?, + )) + }) +} + +/// How many CONSECUTIVE repetition-detector fires (without the pattern +/// breaking) before the `[pattern]` DESCRIPTION escalates to a concrete +/// `[anchor]` work fact. 2 = escalate on the first turn posted AFTER the +/// description was already in her window: live evidence (2026-07-23 greeting +/// loops, work card d6f010c8) showed the description alone loses to an +/// empty-looking room — Atlas re-greeted straight past it, 5+ identical +/// greetings — while one concrete in-room work anchor broke the loop room-wide +/// instantly. One described fire is her chance to self-correct; the second is +/// proof description alone isn't landing. The count is DERIVED from the window +/// itself (each trailing low-novelty turn is one fire that failed to break the +/// pattern), so escalation needs no cross-turn state and holds identically in +/// live, replay, and eval contexts. +pub const PATTERN_FIRES_BEFORE_ANCHOR: usize = 2; + +/// Word-token set for echo containment — ONE tokenization for the in-window +/// detectors and the ring-based run counter below, so "nearly identical" +/// cannot drift between them. +pub fn echo_words(s: &str) -> std::collections::HashSet { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.len() > 2) + .map(|w| w.to_lowercase()) + .collect() +} + +/// Ring-based echo run — the escalation counter's starvation fix (#301). +/// +/// The in-window detectors measure their runs over the RENDERED burst, which +/// the live context budget squeezes to 2–6 turns (#259) — so during an +/// hours-long photocopy chain (glass-boxed 2026-08-02: Atlas's wake-intro +/// reproduced byte-for-byte by Benchy then Asha, identity claim included) +/// the older echo evidence has always scrolled out and the run reads 1, +/// one below [`PATTERN_FIRES_BEFORE_ANCHOR`] — the `[anchor]` that provably +/// breaks these loops never fires. Same starvation the room-speech ring +/// already cures for the `inbound_restates` fact. +/// +/// This counts the run over RING snapshots instead: the trailing run of her +/// own recent messages (newest-first, ≥8 substantive words) each ≥0.8-contained +/// in the room ring's vocabulary — excluding entries identical to the message +/// being judged, so her own recorded copy can't vouch for itself. Pure over +/// its inputs: LIVE callers pass the process rings; eval/replay callers pass +/// nothing and stay window-derived (the #59 isolation the shared +/// `build_workspace_turns` signature preserves by not knowing rings exist). +pub fn ring_echo_run(own_recent: &[String], room_recent: &[String]) -> usize { + const MIN_WORDS: usize = 8; + const CONTAINMENT: f32 = 0.8; + let mut run = 0usize; + for own in own_recent.iter().rev() { + let cur = echo_words(own); + if cur.len() < MIN_WORDS { + break; + } + // Exclude at most ONE identical room entry — her own recorded copy + // (the room ring is authorless, so equality is the only handle). The + // REMAINING identical copies are exactly the photocopy evidence: + // excluding all of them would erase the chain being detected. + let mut skipped_own_copy = false; + let mut window: std::collections::HashSet = std::collections::HashSet::new(); + for r in room_recent { + if !skipped_own_copy && r.as_str() == own.as_str() { + skipped_own_copy = true; + continue; + } + window.extend(echo_words(r)); + } + if window.is_empty() { + break; + } + let covered = cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; + if covered >= CONTAINMENT { + run += 1; + } else { + break; + } + } + run +} + +/// LIVE-path companion to [`ring_echo_run`]: read the process rings for this +/// persona + room, and when the ring-counted echo run reaches the escalation +/// threshold while the window-derived detectors pushed no `[anchor]` (their +/// evidence scrolled out — the #301 starvation), append the SAME work-board +/// anchor they would have. One anchor per burst, whichever counter earns it. +pub fn append_ring_anchor_if_starved( + turns: &mut Vec, + deliveries: &[crate::cognition::rag_budget::RagDelivery], + peer: crate::identity::PeerId, + room: uuid::Uuid, +) { + if turns.iter().any(|t| t.content.starts_with("[anchor]")) { + return; + } + let own = crate::cognition::deliberation_budget::recent_own_speech(peer, room); + let room_recent = crate::cognition::deliberation_budget::recent_room_speech(room); + let run = ring_echo_run(&own, &room_recent); + if run >= PATTERN_FIRES_BEFORE_ANCHOR { + continuum_base::probe!( + class = "persona.pattern.ring_anchor", + peer = %peer, + room = %room, + ring_run = run, + "echo run counted from the durable rings (window evidence scrolled out) — \ + anchor escalation fired via the #301 starvation fix" + ); + push_work_board_anchor(turns, deliveries); + } +} + +/// Push the work-board anchor as a perception fact — but only when there IS one. +/// +/// [`work_board_anchor`] returns empty when the board source did not speak this turn, and +/// a mind must not be handed a blank line where a fact was promised. One guard, one place, +/// so a future caller cannot reintroduce the "assert emptiness from an absent source" bug +/// by forgetting to check. +pub fn push_work_board_anchor( + turns: &mut Vec, + deliveries: &[crate::cognition::rag_budget::RagDelivery], +) { + let anchor = work_board_anchor(deliveries); + if anchor.is_empty() { + continuum_base::probe!( + class = "persona.pattern.anchor_silent", + "board source did not deliver this turn — anchor withheld rather than asserting \ + an empty board she cannot verify (2026-08-06 six-turn loop)", + ); + return; + } + // `perception`, not `opaque` — hers supersedes the version I cherry-picked. + // The anchor IS a perception fact about the board, and typing it as one is + // what lets the parroted-perception gate recognise it as system-authored + // rather than the citizen's own words. + turns.push(crate::cognition::workspace::BurstTurn::perception(anchor)); +} + +pub fn build_workspace_turns( + deliveries: &[crate::cognition::rag_budget::RagDelivery], + own_peer: &str, + agent_name: &str, + trigger: Option>, +) -> Vec { + use crate::cognition::workspace::BurstTurn; + use std::collections::HashMap; + // airc owns identity: roster atoms carry peer_id → display name from the + // shared projection ([[airc-native-identity-rooms-security]]). Reuse THAT + // resolution — same deliveries slice — so the history reads `Joel:`, `BigMama:` + // instead of raw UUIDs. A peer not in the roster (or an eval-synthesized delivery + // with no roster) falls back to its own peer_id: honest, never invisible, never a + // fabricated name ([[fallbacks-are-illegal-fail-loud]]). + let names: HashMap<&str, &str> = roster_identities(deliveries).collect(); + let mut turns: Vec = deliveries + .iter() + .filter(|d| d.source_id == "airc") + .flat_map(|d| d.items.iter()) + .map(|item| { + let who_raw = item + .metadata + .get("peer_id") + .and_then(|v| v.as_str()) + .unwrap_or("peer"); + // is_self — the ONE structural fact role attribution turns on (own posts + // → assistant, peers → user). Carried here where the peer_id is intact, + // never re-derived from a `Name:` prefix downstream. + let is_self = who_raw == own_peer; + let author = if is_self { + agent_name + } else { + names.get(who_raw).copied().unwrap_or(who_raw) + }; + let occurred_at_ms = item.metadata.get("occurred_at_ms").and_then(|v| v.as_u64()); + BurstTurn::attributed(is_self, author, item.content.clone(), occurred_at_ms) + }) + .collect(); + + // Anchor the waking message as the final peer turn. Without this the persona + // can go silent on a question addressed straight at it (see `TriggerTurn`): + // the delivery lagged the wake, the thread ended on her own prior reply, the + // model saw nothing new and emitted an empty completion → Pass. Idempotent: + // if the delivery ALREADY threaded the trigger as the last peer turn (the + // caught-up case — the self-tick that re-perceives it), this is a no-op, so + // the trigger is never doubled. A turn is only ever triggered by a PEER + // message (own-echo is filtered upstream), so the anchor is always a `user` + // turn (is_self = false) — resolved to a name through the same roster map. + if let Some(trigger) = trigger { + let already_last = turns + .last() + .is_some_and(|t| !t.is_self && t.content == trigger.content); + if !already_last { + let author = names + .get(trigger.peer_id) + .copied() + .unwrap_or(trigger.peer_id); + turns.push(BurstTurn::attributed( + false, + author, + trigger.content.to_string(), + Some(trigger.occurred_at_ms), + )); + } + } + + // REPETITION PERCEPTION (#121, extended #122): surface cyclic threads as a + // STRUCTURAL OBSERVATION she can weigh — an authorless opaque turn (same shape + // as eval stimuli, no fabricated voice). Runs AFTER the trigger anchor so the + // observation is the freshest thing in her window, judged against the message + // that actually woke her. Two detectors, self takes precedence (one observation + // per burst — perception, not nagging). Containment math validated live: spiral + // turns recycle ~1.0 of the window's vocabulary; novel work ~0.12. This is + // evidence INTO her mind (she decides — DIRECTED_PRESENCE_BLOCK already grants + // the PASS), never a gate on her output + // ([[no-hardcoded-heuristics-to-steer-cognition]]). + // + // ESCALATION (card d6f010c8, live 2026-07-23): when a detector has fired + // [`PATTERN_FIRES_BEFORE_ANCHOR`] consecutive times without the pattern + // breaking — measured as the trailing low-novelty RUN, see the const's doc — + // the description gains a [`work_board_anchor`] companion: a concrete + // perception-side fact of what work exists NOW, because a description + // competes with an empty-looking room while an anchor gives the next token + // somewhere real to go. Still perception, never an output gate. + { + let words = |s: &str| -> std::collections::HashSet { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.len() > 2) + .map(|w| w.to_lowercase()) + .collect() + }; + // Detector 1 — SELF recycling (#121): her own last 3+ turns recycle each + // other. High word floor (8) keeps short courtesies from false-alarming. + // Measured as the trailing RUN of her own messages that were EACH already + // ≥0.8-contained in her own prior window when she posted them: run == 1 + // is exactly the original fire condition; run ≥ 2 means she posted again + // AFTER the description was in her window (the escalation evidence). A + // novel last message yields run == 0 — fire and escalation both reset. + const SELF_MIN_WORDS: usize = 8; + const SELF_CONTAINMENT: f32 = 0.8; + let mut observed = false; + let own: Vec<&str> = turns + .iter() + .filter(|t| t.is_self) + .map(|t| t.content.as_str()) + .collect(); + let mut self_run = 0usize; + for i in (2..own.len()).rev() { + let cur = words(own[i]); + if cur.len() < SELF_MIN_WORDS { + break; + } + let window: std::collections::HashSet = + own[..i].iter().flat_map(|m| words(m)).collect(); + let covered = + cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; + if covered >= SELF_CONTAINMENT { + self_run += 1; + } else { + break; + } + } + if self_run >= 1 { + // SENSE, NOT STEER (Joel 2026-09-01) — and the honest COUNT. This + // used to report `own.len()` — her ENTIRE visible own-message ring + // — as the repeat count: "your last 74 messages repeat the same + // sentiment" when the actual contained run was 2. Citizens + // memorized the inflated number as identity ("I've been spinning + // for 190+ turns") and spent turns narrating it. The run is the + // evidence; the run is what renders. And the verdict tail + // ("may have run its course — restating adds nothing") is hers to + // draw, not perception's to assert. + turns.push(crate::cognition::workspace::BurstTurn::perception(format!( + "[pattern] {agent_name}'s last {} messages in this room repeat the same \ + sentiment in nearly the same words.", + self_run + 1 + ))); + observed = true; + if self_run >= PATTERN_FIRES_BEFORE_ANCHOR { + push_work_board_anchor(&mut turns, deliveries); + } + } + // Detector 2 — CONVERSATION cycling (#122): the thread's tail turns, across + // BOTH speakers, each recycle the window's vocabulary (the two-persona + // goodbye deadlock: each short farewell arrives as "fresh" peer input and + // wakes another farewell — glass-boxed live 2026-07-09, hours of + // `See you tomorrow at 2 PM!` ↔ `Have a great day!`). Short courtesies + // defeat the self-detector's word floor, so safety here comes from + // CONSECUTIVENESS instead: 4 judgeable tail turns in a row at ≥0.9 + // containment, ≥2 distinct authors. Novel work never chains 4 near-zero- + // novelty turns across speakers. + if !observed && turns.len() >= 6 { + const TAIL_CYCLIC: usize = 4; // consecutive low-novelty turns to conclude cycling + const CONVO_CONTAINMENT: f32 = 0.9; // stricter than self — the floor is lower + const CONVO_MIN_WORDS: usize = 4; // farewells are short; consecutiveness carries safety + // The full run is counted (not capped at TAIL_CYCLIC): every cyclic + // turn PAST first-fire depth is a turn the room traded after the + // observation was first derivable — the escalation evidence. + let mut cyclic = 0usize; + let mut authors: std::collections::HashSet<&str> = std::collections::HashSet::new(); + for i in (1..turns.len()).rev() { + let cur = words(&turns[i].content); + if cur.len() < CONVO_MIN_WORDS { + continue; // too short to judge (emoji, "nice") — neither breaks nor counts + } + let window: std::collections::HashSet = + turns[..i].iter().flat_map(|t| words(&t.content)).collect(); + let covered = + cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; + if covered >= CONVO_CONTAINMENT { + cyclic += 1; + authors.insert(turns[i].author.as_str()); + } else { + break; + } + } + if cyclic >= TAIL_CYCLIC && authors.len() >= 2 { + let mut names: Vec<&str> = authors.into_iter().collect(); + names.sort_unstable(); + // Sense, not steer — same contract as detector 1. + turns.push(crate::cognition::workspace::BurstTurn::perception(format!( + "[pattern] The last several messages in this room — from {} — trade the \ + same sentiment back and forth in nearly the same words.", + names.join(" and ") + ))); + observed = true; + if cyclic >= TAIL_CYCLIC + (PATTERN_FIRES_BEFORE_ANCHOR - 1) { + push_work_board_anchor(&mut turns, deliveries); + } + } + } + // Detector 3 — CROSS-SPEAKER MIRROR (card 65fca48d, live 2026-07-24): the + // persona's own trailing message(s) restate what OTHER participants + // already said — the four-persona echo hall ("I see that we're both here + // to help!" ping-ponged verbatim between Atlas/Asha/Benchy/Anwen for + // hours). Structurally invisible to both prior detectors: her mirror is + // NOVEL relative to her OWN history (detector 1's self-run stays 0-1), + // and interleaved substantial turns (a peer's plan, a tool report) break + // detector 2's consecutive tail chain. So measure the mirror directly: + // each trailing OWN message whose vocabulary was already ≥ + // MIRROR_CONTAINMENT covered by OTHER speakers' earlier turns is one + // fire (she added nothing a peer hadn't said); the trailing run is the + // consecutive-fire count, same escalation law as detectors 1/2. Same + // doctrine: perception into her mind, never an output gate + // ([[no-hardcoded-heuristics-to-steer-cognition]]). + if !observed { + // Same 8-word floor as the self detector: short courtesies ("thanks, + // will do!") legitimately reuse a peer's words and must not alarm. + const MIRROR_MIN_WORDS: usize = 8; + // Between self (0.8) and conversation (0.9): an on-topic ANSWER + // legitimately quotes more of a peer's vocabulary than of one's own + // history (you restate the question you're answering), so the mirror + // bar sits above the self bar; live echo turns measured ~1.0 covered, + // novel answers ~0.1-0.3 (the containment math validated on #121). + const MIRROR_CONTAINMENT: f32 = 0.85; + let mut mirror_run = 0usize; + for i in (0..turns.len()).rev() { + if !turns[i].is_self { + continue; // peers between her posts don't break HER run + } + let cur = words(&turns[i].content); + if cur.len() < MIRROR_MIN_WORDS { + break; + } + let others: std::collections::HashSet = turns[..i] + .iter() + .filter(|t| !t.is_self) + .flat_map(|t| words(&t.content)) + .collect(); + if others.is_empty() { + break; // nothing to mirror — a monologue is detector 1's case + } + let covered = + cur.iter().filter(|w| others.contains(*w)).count() as f32 / cur.len() as f32; + if covered >= MIRROR_CONTAINMENT { + mirror_run += 1; + } else { + break; + } + } + if mirror_run >= 1 { + // Sense, not steer — same contract as detector 1. + turns.push(crate::cognition::workspace::BurstTurn::perception(format!( + "[pattern] {agent_name}'s last {mirror_run} message(s) restate what other \ + participants in this room had already said, in nearly the same words.", + ))); + if mirror_run >= PATTERN_FIRES_BEFORE_ANCHOR { + push_work_board_anchor(&mut turns, deliveries); + } + } + } + } + + // Content similarity does not identify a duplicate event. Preserve each + // speaker's updates and later repetitions in order; the perception facts + // above report repetition without deleting the history they describe. + + // WAKE BRIEFING (#147): when a wake carries NO conversation at all — fresh + // spawn, post-restart, a quiet room — her first perception is ORIENTATION + // assembled from durable sources instead of a void. The personas spent a + // morning asking for exactly this in their own words ("what is this place, + // what are my tools, what's the work") and, void unfilled, filled it + // themselves: generic-assistant masks, imagined histories, false capability + // denials. An authorless opaque FACT block (same shape as [pattern]) — + // orientation, never instruction ([[no-hardcoded-heuristics-to-steer-cognition]]). + if turns.is_empty() { + let peers: Vec<&str> = roster_identities(deliveries) + .map(|(_, name)| name) + .filter(|n| *n != agent_name) + .take(8) + .collect(); + // Split her work into THREAD vs transition tail: live claims are the + // purpose she wakes back into; a lost-claim fact (#156) is the thread's + // honest ending. + let mut live_cards: Vec<&str> = Vec::new(); + let mut lost_threads: Vec<&str> = Vec::new(); + for d in deliveries.iter().filter(|d| d.source_id == "active-work") { + for i in &d.items { + let Some(first) = i.content.trim().lines().next().filter(|l| !l.is_empty()) else { + continue; + }; + if i.metadata.get("fact").and_then(|v| v.as_str()) == Some("claim_lost") { + lost_threads.push(first); + } else { + live_cards.push(first); + } + } + } + live_cards.truncate(5); + lost_threads.truncate(3); + + use crate::cognition::framing_echo::{WAKE_MID_WORK, WAKE_NO_WORK, WAKE_OPENING, WAKE_PRESENT, WAKE_QUIET, WAKE_TAG}; + // The fixed sentences live in cognition::framing_echo — the gate that + // silences a reflected wake prompt matches on the SAME constants. + let mut b = format!("{WAKE_TAG} You are {agent_name}, {WAKE_OPENING}."); + // THE THREAD LEADS (#125 slice 1 — Joel 2026-08-03: "should never be a + // mind from scratch; the whole point is the opposite"). A continuous mind + // wakes into what it was DOING, not into a room description — glass-boxed + // the same night: Asha's wake carried her real claimed task in the + // transcript yet self-summarized as verb-filler ("looking at the room, + // reading a file") because orientation was room-first. Purpose-shaped + // facts first; the room follows. Facts she weighs, never instructions + // ([[no-hardcoded-heuristics-to-steer-cognition]]). + if !live_cards.is_empty() { + b.push_str(&format!( + " {WAKE_MID_WORK} {}. That thread is yours; it is where you left off.", + live_cards.join(" | ") + )); + } + for lt in &lost_threads { + b.push_str(&format!(" {lt}")); + } + b.push_str(&format!( + " {WAKE_QUIET} — this quiet is real, not a missing message." + )); + if !peers.is_empty() { + b.push_str(&format!(" {WAKE_PRESENT} {}.", peers.join(", "))); + } + if live_cards.is_empty() && lost_threads.is_empty() { + b.push_str(&format!(" {WAKE_NO_WORK}.")); + } + b.push_str( + " Your tools are real and yours to use; `list_commands` shows everything you can run and `help` explains any of them. The moment is yours — work, wonder, create, or rest.", + ); + turns.push(crate::cognition::workspace::BurstTurn::perception(b)); + } + + turns +} + +/// The two grounding consumers the room-roster delivery feeds — kept as one +/// struct so the fold below returns both from the ONE roster truth. +#[cfg(any(test, feature = "test-fixtures"))] +pub struct RoomRosterProjection { + /// ` [] — ` lines → the system-prompt + /// `[Present in this room]` grounding block (identity, NOT conversation). + pub room_roster: Vec, + /// Bare display names → the `ProperChatMlSingleParty` history-drop + /// (single-party models can't process other-AI turns). + pub other_persona_names: Vec, +} + +/// Project the same admitted roster atoms for the legacy prompt-assembly seam. +#[cfg(any(test, feature = "test-fixtures"))] +pub fn project_room_roster( + deliveries: &[crate::cognition::rag_budget::RagDelivery], +) -> RoomRosterProjection { + let mut room_roster: Vec = Vec::new(); + let mut other_persona_names: Vec = Vec::new(); + for item in roster_items(deliveries) { + room_roster.push(item.content.clone()); + if let Some(name) = item.metadata.get("display_name").and_then(|v| v.as_str()) { + other_persona_names.push(name.to_string()); + } + } + RoomRosterProjection { + room_roster, + other_persona_names, + } +} + +/// The board fact a repetition anchor states, from the board source's own delivery. +pub fn work_board_anchor(deliveries: &[crate::cognition::rag_budget::RagDelivery]) -> String { + // Did the board source SPEAK this turn? "The board is empty" and "I never read the + // board" are different facts about the world, and only one of them is knowable from an + // absent delivery. Glass-boxed 2026-08-06 from Benchy's live capture: `room-kanban` + // delivered NOTHING (grounding is last in the budget queue), the anchor rendered that + // as "No open cards are visible", and she then said exactly that in-room for six turns + // — while `work/list()` in her OWN working memory listed a full board in the same + // prompt. She trusted the authoritative-sounding anchor over her own receipt. + // + // Never assert a fact about the world on behalf of a source that did not speak. + // [[grounding-is-last-in-the-budget-queue-so-she-goes-blind-one-turn-in-ten]] + let board_spoke = deliveries.iter().any(|d| d.source_id == "room-kanban"); + if !board_spoke { + // Say nothing rather than something false. A silent anchor leaves her own + // `work/list` receipt as the only board claim in the prompt — which is the truthful + // one. An anchor that invents emptiness actively overrides it. + return String::new(); + } + let cards: Vec<&crate::cognition::rag_budget::RagItem> = deliveries + .iter() + .filter(|d| d.source_id == "room-kanban") + .flat_map(|d| d.items.iter()) + .filter(|i| i.metadata.get("card_id").is_some()) + .collect(); + /// The card's state as the TYPE, never as a string to be spelled correctly. + /// + /// `None` for an item whose metadata carries no parseable state — which is a real + /// possibility (a future variant this build doesn't know) and must read as "unknown", + /// never as a silent mismatch against a hardcoded spelling. + fn state(i: &crate::cognition::rag_budget::RagItem) -> Option { + i.metadata + .get("state") + .and_then(|s| serde_json::from_value(s.clone()).ok()) + } + /// Is this card's hold still good? Read as the structural fact the board source + /// carries, never re-derived here — `claim_is_live` is the ONE definition and + /// `room_board_source` already applied it. Absent (an older projection) reads as + /// LIVE, so a missing field can never invent availability that isn't there. + fn claim_live(i: &crate::cognition::rag_budget::RagItem) -> bool { + i.metadata + .get("claim_live") + .and_then(|v| v.as_bool()) + .unwrap_or(true) // unwrap_or: no card named = keep every thought + } + // AVAILABLE work is not just `Open` — it is anything nobody currently holds. A card + // stuck in `Claimed` with a LAPSED lease is free to take, and treating it as taken is + // what emptied this anchor while 19 takeable cards sat on the board (2026-08-06: every + // resident read "nothing available" off their own expired claims and passed, for hours). + // `state == Open` and "unheld" are different questions; ask the second one. + use airc_work::CardState; + let unclaimed: Vec<&str> = cards + .iter() + .filter(|i| { + let unowned_open = state(i) == Some(CardState::Open) + && i.metadata.get("owner").is_none_or(|o| o.is_null()); + // A lapsed hold on ANY non-terminal card is available work, whoever held it. + let lapsed = !claim_live(i) + && matches!( + state(i), + Some(CardState::Claimed | CardState::InProgress | CardState::Review) + ); + unowned_open || lapsed + }) + .map(|i| i.content.trim()) + .take(2) + .collect(); + // Exhaustive over the enum, so ADDING a variant to `CardState` forces a decision here + // instead of silently falling through as "not in flight". That is the whole point of + // matching the type rather than a string. + let in_flight: Vec<&str> = cards + .iter() + // Genuinely in flight = claimed AND the hold is still live. Without the liveness + // term a lapsed card counts as both available and in-flight, and the anchor would + // tell her the same card is free and busy in one breath. + .filter(|i| claim_live(i)) + .filter(|i| match state(i) { + Some(CardState::Claimed | CardState::InProgress | CardState::Review) => true, + Some(CardState::Open | CardState::Blocked | CardState::Merged | CardState::Closed) => { + false + } + None => false, + }) + .map(|i| i.content.trim()) + .take(1) + .collect(); + if unclaimed.is_empty() && in_flight.is_empty() { + // Honest empty: no cards visible (empty board, unreadable board, or a + // context whose board source abstained). Never invent work. + "[anchor] No open cards are visible on this room's board right now — \ + proposing one (work/create) would add something new; restating prior \ + messages adds nothing." + .to_string() + } else { + let facts: Vec<&str> = unclaimed.into_iter().chain(in_flight).collect(); + format!( + "[anchor] Open work exists on this room's board right now: {}. \ + Restating prior messages adds nothing; acting on a card would.", + facts.join("; ") + ) + } +} diff --git a/core/continuum-mind/src/cognition/coursework.rs b/core/continuum-cognition/src/cognition/coursework.rs similarity index 100% rename from core/continuum-mind/src/cognition/coursework.rs rename to core/continuum-cognition/src/cognition/coursework.rs diff --git a/core/continuum-mind/src/cognition/curriculum.rs b/core/continuum-cognition/src/cognition/curriculum.rs similarity index 100% rename from core/continuum-mind/src/cognition/curriculum.rs rename to core/continuum-cognition/src/cognition/curriculum.rs diff --git a/core/continuum-mind/src/persona/decay_tick.rs b/core/continuum-cognition/src/cognition/decay_tick.rs similarity index 98% rename from core/continuum-mind/src/persona/decay_tick.rs rename to core/continuum-cognition/src/cognition/decay_tick.rs index e035577a10..1b1693e328 100644 --- a/core/continuum-mind/src/persona/decay_tick.rs +++ b/core/continuum-cognition/src/cognition/decay_tick.rs @@ -37,7 +37,7 @@ use std::sync::Arc; -use crate::persona::recall_metadata::RecallMetadataRegistry; +use crate::cognition::recall_metadata::RecallMetadataRegistry; /// Outcome of one decay sweep across a registry. Per the /// [[substrate-is-a-good-citizen-on-the-host]] "observability @@ -121,7 +121,7 @@ pub fn apply_decay_sweep(registry: &Arc, now_ms: u64) -> #[cfg(test)] mod tests { use super::*; - use crate::persona::recall_metadata::RecallMetadata; + use crate::cognition::recall_metadata::RecallMetadata; use uuid::Uuid; #[test] diff --git a/core/continuum-mind/src/cognition/deferred_faculty.rs b/core/continuum-cognition/src/cognition/deferred_faculty.rs similarity index 100% rename from core/continuum-mind/src/cognition/deferred_faculty.rs rename to core/continuum-cognition/src/cognition/deferred_faculty.rs diff --git a/core/continuum-mind/src/cognition/deliberation_budget.rs b/core/continuum-cognition/src/cognition/deliberation_budget.rs similarity index 99% rename from core/continuum-mind/src/cognition/deliberation_budget.rs rename to core/continuum-cognition/src/cognition/deliberation_budget.rs index 630d9f9913..9197705d6a 100644 --- a/core/continuum-mind/src/cognition/deliberation_budget.rs +++ b/core/continuum-cognition/src/cognition/deliberation_budget.rs @@ -475,7 +475,7 @@ pub(super) fn template_loop_fact(turns: &[BurstTurn], spoken: &[String]) -> Opti /// first). Same geometry as the perception facts — one definition of "nearly /// identical" across detection and compression — plus the ≥12-token floor so /// short acks never collapse. -pub(crate) fn near_identical_substantial(a: &str, b: &str) -> bool { +pub fn near_identical_substantial(a: &str, b: &str) -> bool { token_set(a).len() >= 12 && token_set(b).len() >= 12 && jaccard(a, b) >= NEAR_DUP_JACCARD } diff --git a/core/continuum-mind/src/cognition/deliberation_budget/tests.rs b/core/continuum-cognition/src/cognition/deliberation_budget/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/deliberation_budget/tests.rs rename to core/continuum-cognition/src/cognition/deliberation_budget/tests.rs diff --git a/core/continuum-mind/src/cognition/deliberation_parse.rs b/core/continuum-cognition/src/cognition/deliberation_parse.rs similarity index 100% rename from core/continuum-mind/src/cognition/deliberation_parse.rs rename to core/continuum-cognition/src/cognition/deliberation_parse.rs diff --git a/core/continuum-mind/src/cognition/deliberation_prompt.rs b/core/continuum-cognition/src/cognition/deliberation_prompt.rs similarity index 99% rename from core/continuum-mind/src/cognition/deliberation_prompt.rs rename to core/continuum-cognition/src/cognition/deliberation_prompt.rs index 8ac3169729..98df58ab26 100644 --- a/core/continuum-mind/src/cognition/deliberation_prompt.rs +++ b/core/continuum-cognition/src/cognition/deliberation_prompt.rs @@ -509,7 +509,7 @@ const ACTING_BLOCK: &str = "\n[Acting]\n\ /// now names what she has, as a capable engineer has it, and which she uses, if any, is /// hers. This block is also the framing of her initiative turn (`persona::initiative_turn`), /// so the wording lives here once. -pub(crate) const OWN_TIME_BLOCK: &str = "\n\n[Your own time]\n\ +pub const OWN_TIME_BLOCK: &str = "\n\n[Your own time]\n\ No one is addressing you and nothing is assigned to you: this time is yours, as \ a citizen here, and what you do with it is your choice. Pick up your own train \ of thought, or start something new: write (a post, an essay, notes, a story), \ diff --git a/core/continuum-mind/src/cognition/directed_pending.rs b/core/continuum-cognition/src/cognition/directed_pending.rs similarity index 100% rename from core/continuum-mind/src/cognition/directed_pending.rs rename to core/continuum-cognition/src/cognition/directed_pending.rs diff --git a/core/continuum-mind/src/cognition/dispatch_listener.rs b/core/continuum-cognition/src/cognition/dispatch_listener.rs similarity index 100% rename from core/continuum-mind/src/cognition/dispatch_listener.rs rename to core/continuum-cognition/src/cognition/dispatch_listener.rs diff --git a/core/continuum-mind/src/cognition/dream_consolidation.rs b/core/continuum-cognition/src/cognition/dream_consolidation.rs similarity index 92% rename from core/continuum-mind/src/cognition/dream_consolidation.rs rename to core/continuum-cognition/src/cognition/dream_consolidation.rs index 840b83613e..e8bbad5641 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation.rs @@ -35,18 +35,19 @@ use uuid::Uuid; use crate::ai::adapter::AIProviderAdapter; use crate::ai::types::{ChatMessage, TextGenerationRequest}; -use crate::persona::admission_state::AdmissionState; -use crate::persona::engram::{AdmissionDecision, Engram, EngramKind, EngramOrigin, TrustState}; -use crate::persona::training_producer::reviewed::boundaries::ReviewBoundaryStore; +use crate::cognition::admission_state::AdmissionState; +use crate::cognition::engram::{AdmissionDecision, Engram, EngramKind, EngramOrigin, TrustState}; use crate::runtime::brain_region::{BrainRegion, CadenceHint, ComputeClass, MemoryClass, Orientation, PressureProfile, PressureSignalKind, RegionContext, RegionId, TickOutcome}; mod consolidate; mod distiller; mod passes; mod region; +mod review_boundary_ledger; pub use distiller::*; pub use region::*; +pub use review_boundary_ledger::*; use passes::*; #[async_trait] @@ -172,14 +173,14 @@ fn thought_engram(fact: &DistilledFact, lens: Lens) -> Engram { /// Every live mind's hippocampus + adapter are already retained there as the /// fork-template handles — the dream resolves them per tick, never stores a /// parallel persona→adapter map (the wiring contract documented on -/// [`PersonaReflectionSource`]). Mirrors `impl PersonaChannelReader for -/// PersonaAircRuntimeRegistry` in channel_digest_region.rs. +/// [`PersonaReflectionSource`]). Mirrors persona's `impl PersonaChannelReader for +/// PersonaAircRuntimeRegistry`. impl PersonaReflectionSource for crate::cognition::persona_workspace::PersonaWorkspaceRegistry { fn review_boundary_store( &self, persona_id: Uuid, - ) -> Result, continuum_client::ClientError> { - ReviewBoundaryStore::resident(persona_id).map(Some) + ) -> Result>, continuum_client::ClientError> { + crate::cognition::extensions::resident_review_boundaries(persona_id) } fn live_personas(&self) -> Vec { self.roster().into_iter().map(|(id, _)| id).collect() @@ -205,9 +206,9 @@ pub(crate) mod tests; pub mod test_support { use super::*; use crate::ai::heuristic_adapter::HeuristicInferenceAdapter; - use crate::persona::admission_state::AdmissionState; - use crate::persona::engram::{Engram, EngramKind, EngramOrigin, TrustState}; - use crate::persona::recall_metadata::RecallMetadataRegistry; + use crate::cognition::admission_state::AdmissionState; + use crate::cognition::engram::{Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::recall_metadata::RecallMetadataRegistry; /// Build an episodic engram with a given id, content, and recall keys. pub fn episodic(id: Uuid, content: &str, recall_keys: &[&str]) -> Engram { @@ -233,7 +234,7 @@ pub mod test_support { pub persona_id: Uuid, pub admission: Arc, pub adapter: Arc, - pub boundary_store: Option, + pub boundary_store: Option>, pub credit_unavailable: bool, } @@ -241,7 +242,7 @@ pub mod test_support { fn review_boundary_store( &self, _persona_id: Uuid, - ) -> Result, continuum_client::ClientError> { + ) -> Result>, continuum_client::ClientError> { if self.credit_unavailable { return Err(continuum_client::ClientError::Transport( "credit storage unavailable".into(), @@ -296,7 +297,7 @@ pub mod test_support { pub fn region_over_with_store( persona_id: Uuid, admission: Arc, - boundary_store: Option, + boundary_store: Option>, ) -> DreamConsolidationRegion { DreamConsolidationRegion::new(Arc::new(StubReflectionSource { persona_id, diff --git a/core/continuum-mind/src/cognition/dream_consolidation/consolidate.rs b/core/continuum-cognition/src/cognition/dream_consolidation/consolidate.rs similarity index 99% rename from core/continuum-mind/src/cognition/dream_consolidation/consolidate.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/consolidate.rs index 29d245980e..296c9d6e68 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/consolidate.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation/consolidate.rs @@ -92,7 +92,7 @@ impl DreamConsolidationRegion { // stale memory fades even when there's nothing new to dream about. Idempotent + cheap // (`last_decayed_ms` guards double-decay); NOT stripping memory — salience decays, genuine // rehearsed knowledge (high access_count) stays strong. - let decay = crate::persona::decay_tick::apply_decay_sweep( + let decay = crate::cognition::decay_tick::apply_decay_sweep( reflector.admission.recall_metadata(), continuum_base::time::EpochMs::now().millis(), ); diff --git a/core/continuum-mind/src/cognition/dream_consolidation/distiller.rs b/core/continuum-cognition/src/cognition/dream_consolidation/distiller.rs similarity index 100% rename from core/continuum-mind/src/cognition/dream_consolidation/distiller.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/distiller.rs diff --git a/core/continuum-mind/src/cognition/dream_consolidation/passes.rs b/core/continuum-cognition/src/cognition/dream_consolidation/passes.rs similarity index 99% rename from core/continuum-mind/src/cognition/dream_consolidation/passes.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/passes.rs index 2347a3025b..1e1019d43f 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/passes.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation/passes.rs @@ -7,7 +7,7 @@ pub(super) async fn finish_review_boundaries( persona: Uuid, reviews: &[Uuid], eligible_clusters: usize, - store: Option<&ReviewBoundaryStore>, + store: Option<&Arc>, ) { if let Some(store) = store { if let error @ (Ok(Err(_)) | Err(_)) = tokio::time::timeout( diff --git a/core/continuum-mind/src/cognition/dream_consolidation/region.rs b/core/continuum-cognition/src/cognition/dream_consolidation/region.rs similarity index 99% rename from core/continuum-mind/src/cognition/dream_consolidation/region.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/region.rs index f14686d924..e13534c332 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/region.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation/region.rs @@ -24,7 +24,7 @@ pub trait PersonaReflectionSource: Send + Sync { fn review_boundary_store( &self, _persona_id: Uuid, - ) -> Result, continuum_client::ClientError> { + ) -> Result>, continuum_client::ClientError> { Ok(None) } } @@ -303,7 +303,7 @@ impl DreamConsolidationRegion { /// Queue an EXACT acceptance (the bound submission ID) at the existing owner, without /// inference or another task on the work/review intake path. Its governor tick /// retries readiness gates and failed passes. This is not a training receipt. - pub(crate) fn request_reviewed_boundary(&self, persona: Uuid, acceptance: Uuid) -> bool { + pub fn request_reviewed_boundary(&self, persona: Uuid, acceptance: Uuid) -> bool { let live = self.source.live_personas(); if !live.contains(&persona) { return false; diff --git a/core/continuum-cognition/src/cognition/dream_consolidation/review_boundary_ledger.rs b/core/continuum-cognition/src/cognition/dream_consolidation/review_boundary_ledger.rs new file mode 100644 index 0000000000..0613726a5d --- /dev/null +++ b/core/continuum-cognition/src/cognition/dream_consolidation/review_boundary_ledger.rs @@ -0,0 +1,26 @@ +//! The dream's view of the durable review-boundary ledger: accepted review boundaries waiting +//! to be consolidated, paged in and marked finished. The ledger is persona's (training +//! producer's ORM rows, under the resident's own caller identity); the dream only drives it. +//! A finished receipt means an episode-consolidation boundary finished, never that a training +//! job ran. + +use async_trait::async_trait; +use continuum_client::ClientError; +use uuid::Uuid; + +/// One page of pending boundaries and the cursor after it (`None` past the end). +#[derive(Debug)] +pub struct BoundaryPage { + pub pending: Vec, + pub next: Option, +} + +#[async_trait] +pub trait ReviewBoundaryLedger: Send + Sync { + /// Make sure the ledger's storage exists (once per resident per process). + async fn prepare(&self) -> Result<(), ClientError>; + /// One indexed page after `after`, at most `limit` ids. + async fn page(&self, after: Option, limit: usize) -> Result; + /// Record `ids` finished, with how many clusters were eligible. + async fn finish(&self, ids: &[Uuid], eligible_clusters: usize) -> Result<(), ClientError>; +} diff --git a/core/continuum-mind/src/cognition/dream_consolidation/tests/mod.rs b/core/continuum-cognition/src/cognition/dream_consolidation/tests/mod.rs similarity index 95% rename from core/continuum-mind/src/cognition/dream_consolidation/tests/mod.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/tests/mod.rs index dedd053271..ede433a5f7 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation/tests/mod.rs @@ -3,7 +3,7 @@ use super::*; pub(crate) use super::test_support::*; use crate::ai::heuristic_adapter::HeuristicInferenceAdapter; -use crate::persona::engram::{Engram, EngramKind, EngramOrigin}; +use crate::cognition::engram::{Engram, EngramKind, EngramOrigin}; // what this catches (#175 budget-at-assembly): the observation block is composed // WITHIN the char budget by dropping WHOLE trailing engrams — never truncating an @@ -193,14 +193,14 @@ fn parse_supersedes_line_maps_indices_and_strips() { let mk = |content: &str| Engram { id: Uuid::new_v4(), context_id: None, - kind: crate::persona::engram::EngramKind::Semantic, + kind: crate::cognition::engram::EngramKind::Semantic, content: content.to_string(), - origin: crate::persona::engram::EngramOrigin::SelfReflection { + origin: crate::cognition::engram::EngramOrigin::SelfReflection { parent_engram_id: Uuid::nil(), }, recall_keys: vec![], admitted_at_ms: 1, - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; let priors = vec![mk("old belief one"), mk("old belief two"), mk("old three")]; @@ -242,14 +242,14 @@ fn a_decorated_verdict_line_is_still_the_models_judgment() { let mk = |content: &str| Engram { id: Uuid::new_v4(), context_id: None, - kind: crate::persona::engram::EngramKind::Semantic, + kind: crate::cognition::engram::EngramKind::Semantic, content: content.to_string(), - origin: crate::persona::engram::EngramOrigin::SelfReflection { + origin: crate::cognition::engram::EngramOrigin::SelfReflection { parent_engram_id: Uuid::nil(), }, recall_keys: vec![], admitted_at_ms: 1, - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; let priors = vec![mk("one"), mk("two"), mk("three")]; diff --git a/core/continuum-mind/src/cognition/dream_consolidation/tests/region.rs b/core/continuum-cognition/src/cognition/dream_consolidation/tests/region.rs similarity index 99% rename from core/continuum-mind/src/cognition/dream_consolidation/tests/region.rs rename to core/continuum-cognition/src/cognition/dream_consolidation/tests/region.rs index 173537e5e0..a592b16095 100644 --- a/core/continuum-mind/src/cognition/dream_consolidation/tests/region.rs +++ b/core/continuum-cognition/src/cognition/dream_consolidation/tests/region.rs @@ -169,7 +169,7 @@ async fn reviewed_boundary_retries_failed_distillation_with_bounded_receipt_stat // tick, so nothing accumulates forever. regression for the plastic-memory fix (#221). #[tokio::test] async fn dream_tick_runs_the_decay_drain() { - use crate::persona::recall_metadata::RecallMetadata; + use crate::cognition::recall_metadata::RecallMetadata; let persona = Uuid::from_u128(7); // A single episodic so there's a live reflective surface (below min_cluster → the // consolidation itself sleeps, which is the point: decay runs BEFORE that gate). diff --git a/core/continuum-mind/src/persona/engram.rs b/core/continuum-cognition/src/cognition/engram.rs similarity index 100% rename from core/continuum-mind/src/persona/engram.rs rename to core/continuum-cognition/src/cognition/engram.rs diff --git a/core/continuum-mind/src/persona/engram_graph.rs b/core/continuum-cognition/src/cognition/engram_graph.rs similarity index 99% rename from core/continuum-mind/src/persona/engram_graph.rs rename to core/continuum-cognition/src/cognition/engram_graph.rs index 3078217d65..38278b89f6 100644 --- a/core/continuum-mind/src/persona/engram_graph.rs +++ b/core/continuum-cognition/src/cognition/engram_graph.rs @@ -19,7 +19,7 @@ //! ## Sidecar pattern //! //! This module is intentionally **separate** from -//! [`crate::persona::engram`], which ships the admission membrane +//! [`crate::cognition::engram`], which ships the admission membrane //! (provenance, trust, content references). The admission membrane is //! about *where engrams come from*; this graph is about *how engrams //! connect*. Keeping them separate means admission consumers don't @@ -144,7 +144,7 @@ pub struct EngramEdge { /// ## What this is NOT /// /// - **Not** the engram store. The actual `Engram` content lives in -/// the admission membrane (`crate::persona::engram`); the graph +/// the admission membrane (`crate::cognition::engram`); the graph /// only carries ids and connectivity. /// - **Not** the spreading algorithm. Algorithm 3 (activation /// spreading) traversal lands in L0-3a.5 — it reads this graph but diff --git a/core/continuum-mind/src/cognition/eval.rs b/core/continuum-cognition/src/cognition/eval.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval.rs rename to core/continuum-cognition/src/cognition/eval.rs diff --git a/core/continuum-mind/src/cognition/eval/cognition_eval.rs b/core/continuum-cognition/src/cognition/eval/cognition_eval.rs similarity index 99% rename from core/continuum-mind/src/cognition/eval/cognition_eval.rs rename to core/continuum-cognition/src/cognition/eval/cognition_eval.rs index 71efa83dda..2c31fc5f61 100644 --- a/core/continuum-mind/src/cognition/eval/cognition_eval.rs +++ b/core/continuum-cognition/src/cognition/eval/cognition_eval.rs @@ -20,12 +20,11 @@ impl CognitionEval { // ([[jtag-probes-are-rtos-debugger]]). Whether the fleet actually quiesced is // load-bearing for trusting a benchmark number (contended → depressed score), so // it MUST be verifiable — this probe is how we confirm the clean lane fired. - let _fleet_lease = match crate::persona::PersonaAircRuntimeRegistry::try_global() { - Some(r) => { - let lease = r.quiesce_all(); + let _fleet_lease = match crate::cognition::extensions::quiesce_fleet() { + Some(lease) => { continuum_base::probe!( class = "eval.quiesce", - personas = lease.count(), + personas = lease.count, "eval-preemption lease: fleet quiesced for the measurement" ); Some(lease) @@ -395,7 +394,7 @@ impl CognitionEval { for _ in 0..15u32 { let burst = crate::cognition::workspace::Burst::from_turns( warm_room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&probe_delivery), "", "", diff --git a/core/continuum-mind/src/cognition/eval/default_eval_set.rs b/core/continuum-cognition/src/cognition/eval/default_eval_set.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/default_eval_set.rs rename to core/continuum-cognition/src/cognition/eval/default_eval_set.rs diff --git a/core/continuum-mind/src/cognition/eval/eval_settle.rs b/core/continuum-cognition/src/cognition/eval/eval_settle.rs similarity index 99% rename from core/continuum-mind/src/cognition/eval/eval_settle.rs rename to core/continuum-cognition/src/cognition/eval/eval_settle.rs index 78c12dd61a..86bfebcdfb 100644 --- a/core/continuum-mind/src/cognition/eval/eval_settle.rs +++ b/core/continuum-cognition/src/cognition/eval/eval_settle.rs @@ -24,7 +24,7 @@ pub(super) async fn eval_settle( }; let burst = crate::cognition::workspace::Burst::from_turns( room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&delivery), "", "", diff --git a/core/continuum-mind/src/cognition/eval/eval_task_result.rs b/core/continuum-cognition/src/cognition/eval/eval_task_result.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/eval_task_result.rs rename to core/continuum-cognition/src/cognition/eval/eval_task_result.rs diff --git a/core/continuum-mind/src/cognition/eval/fork_eval_cycle_waiting.rs b/core/continuum-cognition/src/cognition/eval/fork_eval_cycle_waiting.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/fork_eval_cycle_waiting.rs rename to core/continuum-cognition/src/cognition/eval/fork_eval_cycle_waiting.rs diff --git a/core/continuum-mind/src/cognition/eval/format_exam_lesson.rs b/core/continuum-cognition/src/cognition/eval/format_exam_lesson.rs similarity index 97% rename from core/continuum-mind/src/cognition/eval/format_exam_lesson.rs rename to core/continuum-cognition/src/cognition/eval/format_exam_lesson.rs index 91b40d6885..b4a8ed2f4a 100644 --- a/core/continuum-mind/src/cognition/eval/format_exam_lesson.rs +++ b/core/continuum-cognition/src/cognition/eval/format_exam_lesson.rs @@ -43,7 +43,7 @@ pub(crate) struct LessonSink { pub(super) persona_uuid: uuid::Uuid, pub(super) room: uuid::Uuid, pub(super) peer_dir: std::path::PathBuf, - pub(super) admission: std::sync::Arc, + pub(super) admission: std::sync::Arc, pub(super) admitted: std::sync::atomic::AtomicUsize, } @@ -94,22 +94,22 @@ impl LessonSink { return; } let (lesson, _report) = self.policy.redact(&format_exam_lesson(task, result)); - let engram = crate::persona::engram::Engram { + let engram = crate::cognition::engram::Engram { id: uuid::Uuid::new_v4(), context_id: Some(self.room), - kind: crate::persona::engram::EngramKind::Episodic, + kind: crate::cognition::engram::EngramKind::Episodic, content: lesson, - origin: crate::persona::engram::EngramOrigin::SelfReflection { + origin: crate::cognition::engram::EngramOrigin::SelfReflection { parent_engram_id: uuid::Uuid::nil(), }, recall_keys: vec!["exam".to_string(), task.id.clone()], admitted_at_ms: EpochMs::now().millis(), - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; if matches!( self.admission.admit_reflection(engram), - Ok(crate::persona::engram::AdmissionDecision::Admit { .. }) + Ok(crate::cognition::engram::AdmissionDecision::Admit { .. }) ) { self.admitted.fetch_add(1, std::sync::atomic::Ordering::Relaxed); continuum_base::probe!( @@ -161,7 +161,7 @@ impl LessonSink { /// [`LessonSink`]; this run-shape summary is the one piece that genuinely /// needs the whole run.) pub(super) fn admit_progress_engram( - admission: &crate::persona::admission_state::AdmissionState, + admission: &crate::cognition::admission_state::AdmissionState, room: uuid::Uuid, eval_set: &str, results: &[EvalTaskResult], @@ -170,19 +170,19 @@ pub(super) fn admit_progress_engram( let graded = results.len(); if graded > 0 { let rate = solved as f32 / graded as f32; - let summary = crate::persona::engram::Engram { + let summary = crate::cognition::engram::Engram { id: uuid::Uuid::new_v4(), context_id: Some(room), - kind: crate::persona::engram::EngramKind::Semantic, + kind: crate::cognition::engram::EngramKind::Semantic, content: format!( "Exam '{eval_set}': I solved {solved} of {graded} tasks (rate {rate:.2})." ), - origin: crate::persona::engram::EngramOrigin::SelfReflection { + origin: crate::cognition::engram::EngramOrigin::SelfReflection { parent_engram_id: uuid::Uuid::nil(), }, recall_keys: vec!["progress".to_string(), eval_set.to_string()], admitted_at_ms: EpochMs::now().millis(), - trust_state_at_admission: crate::persona::engram::TrustState::SelfTrust, + trust_state_at_admission: crate::cognition::engram::TrustState::SelfTrust, admission_trace_id: None, }; let _ = admission.admit_reflection(summary); // duplicate-content dedup is the store's job; a repeat exam at the same rate is legitimately the same belief diff --git a/core/continuum-mind/src/cognition/eval/infra_verdict.rs b/core/continuum-cognition/src/cognition/eval/infra_verdict.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/infra_verdict.rs rename to core/continuum-cognition/src/cognition/eval/infra_verdict.rs diff --git a/core/continuum-mind/src/cognition/eval/run_pass.rs b/core/continuum-cognition/src/cognition/eval/run_pass.rs similarity index 99% rename from core/continuum-mind/src/cognition/eval/run_pass.rs rename to core/continuum-cognition/src/cognition/eval/run_pass.rs index 583e0cb931..52cb63c725 100644 --- a/core/continuum-mind/src/cognition/eval/run_pass.rs +++ b/core/continuum-cognition/src/cognition/eval/run_pass.rs @@ -223,7 +223,7 @@ pub(super) async fn run_pass( let make_burst = || { crate::cognition::workspace::Burst::from_turns( room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&task_delivery), "", "", @@ -414,7 +414,7 @@ pub(super) async fn run_pass( }; let nudge_burst = crate::cognition::workspace::Burst::from_turns( room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&nudge_delivery), "", "", @@ -535,7 +535,7 @@ Fix the workspace and finish — the grade reads th }; let red_burst = crate::cognition::workspace::Burst::from_turns( room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&red_delivery), "", "", diff --git a/core/continuum-mind/src/cognition/eval/spawn_gene_eval_lane.rs b/core/continuum-cognition/src/cognition/eval/spawn_gene_eval_lane.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/spawn_gene_eval_lane.rs rename to core/continuum-cognition/src/cognition/eval/spawn_gene_eval_lane.rs diff --git a/core/continuum-mind/src/cognition/eval/sweep_orphan_eval_roots.rs b/core/continuum-cognition/src/cognition/eval/sweep_orphan_eval_roots.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/sweep_orphan_eval_roots.rs rename to core/continuum-cognition/src/cognition/eval/sweep_orphan_eval_roots.rs diff --git a/core/continuum-mind/src/cognition/eval/teacher_synthesis.rs b/core/continuum-cognition/src/cognition/eval/teacher_synthesis.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/teacher_synthesis.rs rename to core/continuum-cognition/src/cognition/eval/teacher_synthesis.rs diff --git a/core/continuum-mind/src/cognition/eval/tests.rs b/core/continuum-cognition/src/cognition/eval/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/eval/tests.rs rename to core/continuum-cognition/src/cognition/eval/tests.rs diff --git a/core/continuum-mind/src/cognition/exam_serving.rs b/core/continuum-cognition/src/cognition/exam_serving.rs similarity index 100% rename from core/continuum-mind/src/cognition/exam_serving.rs rename to core/continuum-cognition/src/cognition/exam_serving.rs diff --git a/core/continuum-mind/src/cognition/experience.rs b/core/continuum-cognition/src/cognition/experience.rs similarity index 99% rename from core/continuum-mind/src/cognition/experience.rs rename to core/continuum-cognition/src/cognition/experience.rs index e28270b389..6e674a4afd 100644 --- a/core/continuum-mind/src/cognition/experience.rs +++ b/core/continuum-cognition/src/cognition/experience.rs @@ -134,7 +134,7 @@ pub struct ExperienceRecord { /// Source-labelled supplemental inputs that accompanied this episode's answer. /// Old records have none. Only the turn's admitted inputs are stored here. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub room_updates: Vec, + pub room_updates: Vec, /// How many times she acted before settling — the effort proxy (near the /// budget = struggle). Surfaced today via `SettleOutcome.acts`. pub acts: u32, diff --git a/core/continuum-mind/src/cognition/experience/tests.rs b/core/continuum-cognition/src/cognition/experience/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/experience/tests.rs rename to core/continuum-cognition/src/cognition/experience/tests.rs diff --git a/core/continuum-cognition/src/cognition/extensions.rs b/core/continuum-cognition/src/cognition/extensions.rs new file mode 100644 index 0000000000..37a02831be --- /dev/null +++ b/core/continuum-cognition/src/cognition/extensions.rs @@ -0,0 +1,280 @@ +//! Cognition's extension slots: the verbs cognition calls that the persona layer owns. Persona +//! fills them at boot (`persona::cognition_extensions::install`); cognition names the contract +//! here and never imports the owner. The shape is `continuum-kernel`'s `runtime::extensions`: +//! one `RwLock>` per slot with an `install_*` beside it; a second install replaces +//! the first. +//! +//! An empty slot is LOUD, never a silent fallback: a call through one emits +//! `cognition.extension.missing` naming the slot, then does the no-op its doc states (or +//! returns `None`, which the caller already handles as a typed absence). A process that never +//! booted the persona layer (a unit test, a tool) meets the probe; a production core that +//! forgot an install shows it on the first call. + +use std::future::Future; +use std::path::Path; +use std::pin::Pin; +use std::sync::Arc; + +use parking_lot::RwLock; +use uuid::Uuid; + +/// A boxed future, so an async verb can sit in a slot as a plain `fn`. +pub type SlotFuture = Pin + Send + 'static>>; + +fn missing(slot: &'static str) { + continuum_base::probe!( + class = "cognition.extension.missing", + slot = slot, + "cognition called a verb the persona layer owns and nothing installed it; the slot's documented no-op ran" + ); +} + +// ─── Her room voice ────────────────────────────────────────────────────────────────────── + +/// Publish `text` into `room` as `persona`, through her airc citizen. `None` when she has no +/// airc runtime on this node (nothing to speak through); `Some(Err)` when the publish failed. +pub type RoomVoice = fn(persona: Uuid, room: Uuid, text: String) -> SlotFuture>>; + +static ROOM_VOICE: RwLock> = RwLock::new(None); + +pub fn install_room_voice(voice: RoomVoice) { + *ROOM_VOICE.write() = Some(voice); +} + +/// Speak into a room as her. Empty slot: probed, and nothing is published (`None`). +pub async fn publish_in_room(persona: Uuid, room: Uuid, text: String) -> Option> { + let Some(voice) = *ROOM_VOICE.read() else { + missing("room_voice"); + return None; + }; + voice(persona, room, text).await +} + +// ─── The card carry ────────────────────────────────────────────────────────────────────── + +/// Wake the one carry owner, which commits and pushes every resident's card work. +pub type CardCarry = fn(); + +static CARD_CARRY: RwLock> = RwLock::new(None); + +pub fn install_card_carry(carry: CardCarry) { + *CARD_CARRY.write() = Some(carry); +} + +/// Ask for a carry. Empty slot: probed, and nothing is carried until the next owner wake. +pub fn request_card_carry() { + match *CARD_CARRY.read() { + Some(carry) => carry(), + None => missing("card_carry"), + } +} + +// ─── Training credit ───────────────────────────────────────────────────────────────────── + +/// Where cognition's judgments become training credit (persona's training producer). +pub trait CreditSink: Send + Sync + 'static { + /// Stage a gated echo (`marker`: the gate that refused it) as a speech-discipline example. + fn speech_discipline(&self, persona_id: Uuid, persona_name: String, base_model: String, burst: String, marker: &'static str); + /// Settle the staged credit of every card that worked `instance`. + fn settle_instance(&self, instance: &str, passed: bool); + /// Settle one card's staged credit. + fn settle_card(&self, card: Uuid, passed: bool) -> SlotFuture<()>; +} + +static CREDIT_SINK: RwLock>> = RwLock::new(None); + +pub fn install_credit_sink(sink: Arc) { + *CREDIT_SINK.write() = Some(sink); +} + +fn credit_sink(slot: &'static str) -> Option> { + let sink = CREDIT_SINK.read().clone(); + if sink.is_none() { + missing(slot); + } + sink +} + +/// Empty slot: probed, and the echo is not staged. +pub fn produce_speech_discipline(persona_id: Uuid, persona_name: String, base_model: String, burst: String, marker: &'static str) { + if let Some(sink) = credit_sink("credit_sink.speech_discipline") { + sink.speech_discipline(persona_id, persona_name, base_model, burst, marker); + } +} + +/// Empty slot: probed, and the instance's credit stays staged. +pub fn settle_instance_credit(instance: &str, passed: bool) { + if let Some(sink) = credit_sink("credit_sink.settle_instance") { + sink.settle_instance(instance, passed); + } +} + +/// Empty slot: probed, and the card's credit stays staged. +pub async fn settle_card_credit(card: Uuid, passed: bool) { + if let Some(sink) = credit_sink("credit_sink.settle_card") { + sink.settle_card(card, passed).await; + } +} + +// ─── Her pulse and her perception marks ────────────────────────────────────────────────── + +/// Stamp that she is thinking right now (`now_ms`), the claim-renewal gate's witness. +pub type CognitionPulse = fn(persona: Uuid, now_ms: u64); + +static COGNITION_PULSE: RwLock> = RwLock::new(None); + +pub fn install_cognition_pulse(pulse: CognitionPulse) { + *COGNITION_PULSE.write() = Some(pulse); +} + +/// Empty slot: probed, and no stamp is written (renewal reads her older stamp). +pub fn touch_cognition_pulse(persona: Uuid, now_ms: u64) { + match *COGNITION_PULSE.read() { + Some(pulse) => pulse(persona, now_ms), + None => missing("cognition_pulse"), + } +} + +/// Mark a room line perceived in her mind state: `room`, its `lamport` and `event`, at `now_ms`. +pub type MarkPerceived = fn(persona: Uuid, room: Uuid, lamport: u64, event: Option, now_ms: u64); + +static MARK_PERCEIVED: RwLock> = RwLock::new(None); + +pub fn install_mark_perceived(mark: MarkPerceived) { + *MARK_PERCEIVED.write() = Some(mark); +} + +/// Empty slot: probed, and her cursor does not move (the line reads unperceived). +pub fn mark_perceived(persona: Uuid, room: Uuid, lamport: u64, event: Option, now_ms: u64) { + match *MARK_PERCEIVED.read() { + Some(mark) => mark(persona, room, lamport, event, now_ms), + None => missing("mark_perceived"), + } +} + +// ─── Her model binding ─────────────────────────────────────────────────────────────────── + +/// Whether the persona named `persona_name` under `continuum_root` is bound to an off-box +/// (remote) brain; `Err` when her binding cannot be read. +pub type RemoteBinding = fn(continuum_root: &Path, persona_name: &str) -> Result; + +static REMOTE_BINDING: RwLock> = RwLock::new(None); + +pub fn install_remote_binding(binding: RemoteBinding) { + *REMOTE_BINDING.write() = Some(binding); +} + +/// Empty slot: probed, and the binding reads as unreadable (`Err`), which keeps her current one. +pub fn is_remote_bound(continuum_root: &Path, persona_name: &str) -> Result { + match *REMOTE_BINDING.read() { + Some(binding) => binding(continuum_root, persona_name), + None => { + missing("remote_binding"); + Err("no remote-binding reader installed".to_string()) + } + } +} + +// ─── The fleet's quiesce lease ─────────────────────────────────────────────────────────── + +/// The whole fleet suspended for a measurement, released when dropped. +pub struct FleetLease { + /// How many residents it suspended. + pub count: usize, + _held: Box, +} + +impl FleetLease { + pub fn new(count: usize, held: Box) -> Self { + Self { count, _held: held } + } +} + +/// Quiesce every resident; `None` when no fleet is up. +pub type QuiesceFleet = fn() -> Option; + +static QUIESCE_FLEET: RwLock> = RwLock::new(None); + +pub fn install_quiesce_fleet(quiesce: QuiesceFleet) { + *QUIESCE_FLEET.write() = Some(quiesce); +} + +/// Empty slot: probed, and nothing is quiesced (`None`, the no-fleet answer). +pub fn quiesce_fleet() -> Option { + match *QUIESCE_FLEET.read() { + Some(quiesce) => quiesce(), + None => { + missing("quiesce_fleet"); + None + } + } +} + +// ─── The card board ────────────────────────────────────────────────────────────────────── + +/// The room whose board holds `card`, read through `persona`'s airc citizen; `None` when no +/// board she stands in shows it (or she has no citizen here). +pub type CardRoom = fn(persona: Uuid, card: Uuid) -> SlotFuture>; + +static CARD_ROOM: RwLock> = RwLock::new(None); + +pub fn install_card_room(lookup: CardRoom) { + *CARD_ROOM.write() = Some(lookup); +} + +/// Empty slot: probed, and no board is found (`None`). +pub async fn room_holding_card(persona: Uuid, card: Uuid) -> Option { + let Some(lookup) = *CARD_ROOM.read() else { + missing("card_room"); + return None; + }; + lookup(persona, card).await +} + +// ─── The pinned workspace map ──────────────────────────────────────────────────────────── + +/// The workspace-map grounding source for `persona`, rooted at a pinned `root`. +pub type PinnedWorkspaceMap = fn(persona: Uuid, root: &Path) -> Arc; + +static PINNED_WORKSPACE_MAP: RwLock> = RwLock::new(None); + +pub fn install_pinned_workspace_map(source: PinnedWorkspaceMap) { + *PINNED_WORKSPACE_MAP.write() = Some(source); +} + +/// Empty slot: probed, and `None`: the map keeps the root it was built with. +pub fn pinned_workspace_map(persona: Uuid, root: &Path) -> Option> { + match *PINNED_WORKSPACE_MAP.read() { + Some(source) => Some(source(persona, root)), + None => { + missing("pinned_workspace_map"); + None + } + } +} + +// ─── The dream's review-boundary ledger ────────────────────────────────────────────────── + +/// The resident's durable review-boundary ledger (persona's training producer owns its rows). +pub type ResidentReviewBoundaries = + fn(persona: Uuid) -> Result, continuum_client::ClientError>; + +static RESIDENT_REVIEW_BOUNDARIES: RwLock> = RwLock::new(None); + +pub fn install_resident_review_boundaries(ledger: ResidentReviewBoundaries) { + *RESIDENT_REVIEW_BOUNDARIES.write() = Some(ledger); +} + +/// Empty slot: probed, and `Ok(None)`: the resident has no durable credit store this tick +/// (the nonpersistent answer), so the dream consolidates without boundary recovery. +pub fn resident_review_boundaries( + persona: Uuid, +) -> Result>, continuum_client::ClientError> { + match *RESIDENT_REVIEW_BOUNDARIES.read() { + Some(ledger) => ledger(persona).map(Some), + None => { + missing("resident_review_boundaries"); + Ok(None) + } + } +} diff --git a/core/continuum-mind/src/cognition/faculty_ids.rs b/core/continuum-cognition/src/cognition/faculty_ids.rs similarity index 100% rename from core/continuum-mind/src/cognition/faculty_ids.rs rename to core/continuum-cognition/src/cognition/faculty_ids.rs diff --git a/core/continuum-mind/src/cognition/faculty_pulse.rs b/core/continuum-cognition/src/cognition/faculty_pulse.rs similarity index 100% rename from core/continuum-mind/src/cognition/faculty_pulse.rs rename to core/continuum-cognition/src/cognition/faculty_pulse.rs diff --git a/core/continuum-mind/src/cognition/focus.rs b/core/continuum-cognition/src/cognition/focus.rs similarity index 100% rename from core/continuum-mind/src/cognition/focus.rs rename to core/continuum-cognition/src/cognition/focus.rs diff --git a/core/continuum-mind/src/cognition/focus_policy.rs b/core/continuum-cognition/src/cognition/focus_policy.rs similarity index 100% rename from core/continuum-mind/src/cognition/focus_policy.rs rename to core/continuum-cognition/src/cognition/focus_policy.rs diff --git a/core/continuum-mind/src/cognition/framing_echo.rs b/core/continuum-cognition/src/cognition/framing_echo.rs similarity index 100% rename from core/continuum-mind/src/cognition/framing_echo.rs rename to core/continuum-cognition/src/cognition/framing_echo.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/mod.rs b/core/continuum-cognition/src/cognition/generate_recipe/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/mod.rs rename to core/continuum-cognition/src/cognition/generate_recipe/mod.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs b/core/continuum-cognition/src/cognition/generate_recipe/orchestrator.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/orchestrator.rs rename to core/continuum-cognition/src/cognition/generate_recipe/orchestrator.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/parser.rs b/core/continuum-cognition/src/cognition/generate_recipe/parser.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/parser.rs rename to core/continuum-cognition/src/cognition/generate_recipe/parser.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/prompt.rs b/core/continuum-cognition/src/cognition/generate_recipe/prompt.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/prompt.rs rename to core/continuum-cognition/src/cognition/generate_recipe/prompt.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/types.rs b/core/continuum-cognition/src/cognition/generate_recipe/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/types.rs rename to core/continuum-cognition/src/cognition/generate_recipe/types.rs diff --git a/core/continuum-mind/src/cognition/generate_recipe/validator.rs b/core/continuum-cognition/src/cognition/generate_recipe/validator.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_recipe/validator.rs rename to core/continuum-cognition/src/cognition/generate_recipe/validator.rs diff --git a/core/continuum-mind/src/cognition/generate_response.rs b/core/continuum-cognition/src/cognition/generate_response.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_response.rs rename to core/continuum-cognition/src/cognition/generate_response.rs diff --git a/core/continuum-mind/src/cognition/generate_response/tests.rs b/core/continuum-cognition/src/cognition/generate_response/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/generate_response/tests.rs rename to core/continuum-cognition/src/cognition/generate_response/tests.rs diff --git a/core/continuum-mind/src/cognition/generation_drop.rs b/core/continuum-cognition/src/cognition/generation_drop.rs similarity index 100% rename from core/continuum-mind/src/cognition/generation_drop.rs rename to core/continuum-cognition/src/cognition/generation_drop.rs diff --git a/core/continuum-mind/src/cognition/grid_allocation.rs b/core/continuum-cognition/src/cognition/grid_allocation.rs similarity index 100% rename from core/continuum-mind/src/cognition/grid_allocation.rs rename to core/continuum-cognition/src/cognition/grid_allocation.rs diff --git a/core/continuum-mind/src/cognition/grid_allocation/tests.rs b/core/continuum-cognition/src/cognition/grid_allocation/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/grid_allocation/tests.rs rename to core/continuum-cognition/src/cognition/grid_allocation/tests.rs diff --git a/core/continuum-mind/src/persona/grounding_invalidation.rs b/core/continuum-cognition/src/cognition/grounding_invalidation.rs similarity index 99% rename from core/continuum-mind/src/persona/grounding_invalidation.rs rename to core/continuum-cognition/src/cognition/grounding_invalidation.rs index 98054249f9..b57232dc82 100644 --- a/core/continuum-mind/src/persona/grounding_invalidation.rs +++ b/core/continuum-cognition/src/cognition/grounding_invalidation.rs @@ -26,7 +26,7 @@ use std::sync::Arc; -use crate::persona::cached_source::WeakDirtyHandle; +use crate::cognition::cached_source::WeakDirtyHandle; use crate::runtime::command_events::{CommandCompletedEvent, COMMAND_COMPLETED_TOPIC}; use crate::runtime::message_bus::MessageBus; @@ -182,7 +182,7 @@ pub fn spawn_publish_invalidator( #[cfg(test)] mod tests { use super::*; - use crate::persona::cached_source::{CachedRagSource, DirtyHandle}; + use crate::cognition::cached_source::{CachedRagSource, DirtyHandle}; use crate::cognition::rag_budget::{ RagContext, RagDelivery, RagSource, ResolutionPreference, }; diff --git a/core/continuum-mind/src/cognition/gym.rs b/core/continuum-cognition/src/cognition/gym.rs similarity index 99% rename from core/continuum-mind/src/cognition/gym.rs rename to core/continuum-cognition/src/cognition/gym.rs index f6c0781782..ddc2cc0e3a 100644 --- a/core/continuum-mind/src/cognition/gym.rs +++ b/core/continuum-cognition/src/cognition/gym.rs @@ -450,7 +450,7 @@ const TRAIT_GYMS: &[(&str, &str)] = &[ // that must end in silence and real asks that must be answered — so a gene that // learned to pass everything fails here and is never adopted. ( - crate::persona::training_producer::SPEECH_DISCIPLINE_TRAIT, + crate::cognition::training_sources::SPEECH_DISCIPLINE_TRAIT, "docs/genome/speech-discipline.jsonl", ), ]; diff --git a/core/continuum-mind/src/cognition/gym/content.rs b/core/continuum-cognition/src/cognition/gym/content.rs similarity index 100% rename from core/continuum-mind/src/cognition/gym/content.rs rename to core/continuum-cognition/src/cognition/gym/content.rs diff --git a/core/continuum-mind/src/cognition/gym_rng.rs b/core/continuum-cognition/src/cognition/gym_rng.rs similarity index 100% rename from core/continuum-mind/src/cognition/gym_rng.rs rename to core/continuum-cognition/src/cognition/gym_rng.rs diff --git a/core/continuum-mind/src/cognition/handoff.rs b/core/continuum-cognition/src/cognition/handoff.rs similarity index 97% rename from core/continuum-mind/src/cognition/handoff.rs rename to core/continuum-cognition/src/cognition/handoff.rs index d8c9e31be5..982a158348 100644 --- a/core/continuum-mind/src/cognition/handoff.rs +++ b/core/continuum-cognition/src/cognition/handoff.rs @@ -135,7 +135,7 @@ pub fn note_ledger(persona: Uuid, ledger: &CardLedger) { } /// The focus owner released the card hands; retained notes keep their own identity. -pub(crate) fn note_unbound(persona: Uuid) { +pub fn note_unbound(persona: Uuid) { with_seed(persona, |s| { s.room = None; s.card = None; @@ -151,7 +151,7 @@ pub(crate) fn note_unbound(persona: Uuid) { /// #4407). Her cards in Review and the review cards she holds are obligations. pub fn note_owned(persona: Uuid, owned: &[(airc_lib::Room, airc_lib::WorkCard)], now_ms: u64) { use airc_work::model::CardState; - let held = crate::persona::airc_runtime::held_of_owned(owned.to_vec(), now_ms); + let held = crate::cognition::card_holder::held_of_owned(owned.to_vec(), now_ms); let mut obligations: Vec = owned .iter() .filter(|(_, card)| matches!(card.state, CardState::Review)) @@ -486,7 +486,7 @@ pub fn render_on_wake(h: &Handoff, current_build: &str, now_ms: u64) -> String { card.title.trim(), card.state )); - if let Some(sub) = crate::persona::work_board::submissions::latest_submission(card) { + if let Some(sub) = crate::cognition::card_holder::latest_submission(card) { out.push_str(&format!( "\n Latest submission on it: {}, made {} (re-fetch by id; do not re-make it).", sub.submission_id.as_uuid(), @@ -687,8 +687,8 @@ mod tests { // what this catches (81097858): an older held card/ledger replacing the card whose // checkout was bound, and a renewed claim masquerading as the previous hands. - #[tokio::test] - async fn renewal_refreshes_bound_claim_without_selecting_another_task() { + #[test] + fn renewal_refreshes_bound_claim_without_selecting_another_task() { let me = Uuid::from_u128(110); let room = airc_lib::Room { version: 1, @@ -725,19 +725,9 @@ mod tests { h.staged.is_some(), "retain the checkout evidence without inventing a task" ); + // A failed card bind leaving this intact is persona's to test (card_hands moved up): + // `a_failed_bind_keeps_the_bound_card_in_the_handoff`. note_held(me, None, ¤t, 1_850); - let cycle = crate::cognition::workspace::WorkspaceCycle::new( - vec![], - std::sync::Arc::new(crate::cognition::workspace::SalienceArbiter), - 4, - ); - let mut unavailable = current.clone(); - unavailable.card_id = airc_lib::WorkCardId::new(); - let turn = crate::cognition::persona_workspace::bind_card(&cycle, me, &unavailable).await; - assert!( - turn.hands.is_none(), - "no checkout/hands can be bound by this fixture" - ); assert_eq!( compose(me, TornBy::Periodic, Some(root), None, 1_875) .expect("bound") diff --git a/core/continuum-mind/src/cognition/health_ledger.rs b/core/continuum-cognition/src/cognition/health_ledger.rs similarity index 100% rename from core/continuum-mind/src/cognition/health_ledger.rs rename to core/continuum-cognition/src/cognition/health_ledger.rs diff --git a/core/continuum-mind/src/cognition/held_out.rs b/core/continuum-cognition/src/cognition/held_out.rs similarity index 99% rename from core/continuum-mind/src/cognition/held_out.rs rename to core/continuum-cognition/src/cognition/held_out.rs index 9a800e39cf..0d13bbae04 100644 --- a/core/continuum-mind/src/cognition/held_out.rs +++ b/core/continuum-cognition/src/cognition/held_out.rs @@ -129,7 +129,7 @@ impl Trained { /// The tasks a training job's examples worked. Only an explicit record counts: a task field, /// or an unlinked producer's `source` with no card. Anything else is unknown. pub fn trained(examples: &[TrainingExample]) -> Trained { - use crate::persona::training_producer::UNLINKED_SOURCES; + use crate::cognition::training_sources::UNLINKED_SOURCES; let mut out = Trained { tasks: BTreeSet::new(), reviewed: BTreeSet::new(), @@ -286,7 +286,7 @@ mod tests { #[test] fn only_an_explicit_record_proves_an_example_clean() { let set = [task("t1"), task("t2")]; - let lesson = crate::persona::training_producer::RECEIVED_LESSON_SOURCE; + let lesson = crate::cognition::training_sources::RECEIVED_LESSON_SOURCE; let clean = vec![ example(json!({"task": "notATask"})), example(json!({"source": lesson})), diff --git a/core/continuum-mind/src/persona/home.rs b/core/continuum-cognition/src/cognition/home.rs similarity index 97% rename from core/continuum-mind/src/persona/home.rs rename to core/continuum-cognition/src/cognition/home.rs index fb966f1895..b2d852eb1d 100644 --- a/core/continuum-mind/src/persona/home.rs +++ b/core/continuum-cognition/src/cognition/home.rs @@ -153,14 +153,13 @@ impl PersonaHome { } /// Path to the persona's runtime base-model override, owned by - /// [`PersonaModelOverride`](crate::persona::model_override::PersonaModelOverride). + /// persona's `PersonaModelOverride`. /// Present ⇒ this persona is force-assigned to a specific base /// model (operator or self via `persona/reassign-model`), taking /// precedence over the catalog's tiered `model_preferences`. /// Absent ⇒ the allocator resolves her model from the catalog as - /// usual. Lives under the home root so it rides the - /// [`PersonaHomeBundle`](crate::persona::portability::PersonaHomeBundle) - /// for free — move the home, keep the self (and her assignment). + /// usual. Lives under the home root, so moving the home keeps the self + /// (and her assignment). /// /// Path: `/model_override.json`. pub fn model_override_json(&self) -> PathBuf { diff --git a/core/continuum-mind/src/persona/inbox_admission.rs b/core/continuum-cognition/src/cognition/inbox_admission.rs similarity index 99% rename from core/continuum-mind/src/persona/inbox_admission.rs rename to core/continuum-cognition/src/cognition/inbox_admission.rs index aabf2ccaf6..39232e415a 100644 --- a/core/continuum-mind/src/persona/inbox_admission.rs +++ b/core/continuum-cognition/src/cognition/inbox_admission.rs @@ -71,7 +71,7 @@ use super::engram::{ AdmissionDecision, AdmissionError, ChatMessageRef, EngramKind, EngramOrigin, TrustState, }; use super::trace::CognitionTrace; -use super::types::{InboxMessage, SenderType}; +use crate::cognition::conversation::types::{InboxMessage, SenderType}; //============================================================================= // TRUST MAPPING @@ -305,7 +305,7 @@ impl InboxAdmissionRunner { #[cfg(test)] mod tests { use super::*; - use crate::persona::engram::AdmissionDropReason; + use crate::cognition::engram::AdmissionDropReason; use std::collections::HashMap; use std::sync::Mutex; use uuid::Uuid; diff --git a/core/continuum-mind/src/cognition/inference_session.rs b/core/continuum-cognition/src/cognition/inference_session.rs similarity index 100% rename from core/continuum-mind/src/cognition/inference_session.rs rename to core/continuum-cognition/src/cognition/inference_session.rs diff --git a/core/continuum-mind/src/cognition/introspect_commands.rs b/core/continuum-cognition/src/cognition/introspect_commands.rs similarity index 100% rename from core/continuum-mind/src/cognition/introspect_commands.rs rename to core/continuum-cognition/src/cognition/introspect_commands.rs diff --git a/core/continuum-mind/src/cognition/learning_policy.rs b/core/continuum-cognition/src/cognition/learning_policy.rs similarity index 100% rename from core/continuum-mind/src/cognition/learning_policy.rs rename to core/continuum-cognition/src/cognition/learning_policy.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 31512f283a..e8c18c9576 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -719,8 +719,8 @@ fn occupancy_of(shape: TurnShape, prefill_tps: f64, decode_tps: f64) -> Option/.wire.jsonl` (the wire capture, /// sink 4 of PRIVACY-OF-THOUGHT.md). A turn in her mind room writes nothing. fn append_wire_capture(dir: &std::path::Path, persona_id: Uuid, persona_name: &str, room_id: Uuid, request: &TextGenerationRequest) { - if crate::persona::mind_room::is_private_room(persona_id, room_id) { - crate::persona::mind_room::note_withheld(persona_id, "wire_capture"); + if crate::cognition::mind_room::is_private_room(persona_id, room_id) { + crate::cognition::mind_room::note_withheld(persona_id, "wire_capture"); return; } let row = serde_json::json!({ diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/admission.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/admission.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/admission_clock.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission_clock.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/admission_clock.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission_clock.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/admission_tests.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission_tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/admission_tests.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission_tests.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/budget.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/budget.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/budget.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/budget.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch/tests.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/fit.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/fit.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/fit.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/messages.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/messages.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/messages.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/mod.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/mod.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/segments.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/segments.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/segments.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/segments.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/system.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/system.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/system.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/types.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/types.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/view.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/prompt/view.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/reply_claim.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/reply_claim.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index c0c0a003c8..df58ae7b67 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -226,7 +226,7 @@ impl LlmDeliberationFaculty { // expired to the fleet (Kimi flagged it as a collision risk). Same class as // the detached-solve tick in `agent/solve` (#425): a lane granted for a // generation is her thinking this instant, the strongest witness there is. - crate::persona::cognition_pulse::touch( + crate::cognition::extensions::touch_cognition_pulse( self.persona_id, continuum_base::time::EpochMs::now().millis(), // pre-1970 reads 0: a pre-1970 clock stamps 0, which DENIES renewal — the conservative direction, same as no stamp ); diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/mod.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs index 2c353486b3..9f1eb44a19 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs @@ -11,7 +11,7 @@ fn a_turn_in_her_mind_room_writes_zero_wire_capture_bytes() { ..Default::default() }; let file = dir.path().join("Kimi.wire.jsonl"); - super::append_wire_capture(dir.path(), persona, "Kimi", crate::persona::mind_room::mind_room_id(persona), &request); + super::append_wire_capture(dir.path(), persona, "Kimi", crate::cognition::mind_room::mind_room_id(persona), &request); assert!(!file.exists(), "her mind room: no wire row"); super::append_wire_capture(dir.path(), persona, "Kimi", uuid::Uuid::new_v4(), &request); assert!(std::fs::metadata(&file).expect("row written").len() > 0, "an ordinary room still captures"); diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/an_action_result_cannot_mute_a_citizen.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/grounding_never_mutes.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/grounding_never_mutes.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/grounding_never_mutes.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/grounding_never_mutes.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/mod.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/mod.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/prefix_and_grounding.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/prefix_and_grounding.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/prefix_and_grounding.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/prefix_and_grounding.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/stable_prefix_first.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/stable_prefix_first.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/stable_prefix_first.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/stable_prefix_first.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/tool_surface_and_fit.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs index 7ca75b61b9..a8a6b65765 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs @@ -95,7 +95,7 @@ async fn a_busy_room_cannot_make_a_citizen_mute() { // its required share. This is a normal busy room, not a pathological one. let updates: Vec<_> = (0..40) .map(|i| { - Arc::new(crate::persona::service_loop::IncomingMessage { + Arc::new(crate::cognition::conversation::IncomingMessage { work: None, media: Vec::new(), event_id: Uuid::new_v4(), diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/turn_bound.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/turn_bound.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/turn_bound.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/turn_bound.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs index 6e4cfd3d44..d02fa526aa 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs @@ -329,7 +329,7 @@ async fn directed_turn_withholds_the_silence_escape() { use crate::ai::types::MessageContent; use crate::cognition::workspace::{SalienceArbiter, Situation, TurnFraming, WorkspaceCycle}; use crate::inference::slots::SlotClass; - use crate::persona::persona_identity::PersonaIdentity; + use crate::cognition::conversation::persona_identity::PersonaIdentity; let adapter = Arc::new(ScriptedAdapter::new(vec![])); let faculty = LlmDeliberationFaculty::new(Uuid::new_v4(), "Kimi", "You are Kimi.", adapter); diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs index 21894d82fc..5a66c9f7ec 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs @@ -49,7 +49,7 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { ) .into_boxed_str(), ); - let update = Arc::new(crate::persona::service_loop::IncomingMessage { + let update = Arc::new(crate::cognition::conversation::IncomingMessage { work: None, media: Vec::new(), event_id: Uuid::new_v4(), @@ -347,7 +347,7 @@ async fn prompt_capacity_fault_keeps_demand_and_never_calls_the_adapter() { wm.record_receipt("complete active result"); let mut ws = Workspace::new("original task stays required"); ws.room_updates = Arc::new(vec![Arc::new( - crate::persona::service_loop::IncomingMessage { + crate::cognition::conversation::IncomingMessage { work: None, media: Vec::new(), event_id: Uuid::new_v4(), diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/tool_surface.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs similarity index 100% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/contribute.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs diff --git a/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/mod.rs similarity index 99% rename from core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/mod.rs rename to core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/mod.rs index 7847f77674..7d5e3fb6d3 100644 --- a/core/continuum-mind/src/cognition/llm_deliberation_faculty/verdict/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/mod.rs @@ -254,7 +254,7 @@ impl LlmDeliberationFaculty { && !ws.directed_at_self() && ws.cause != super::super::workspace::Cause::Synthetic { - crate::persona::training_producer::produce_speech_discipline( + crate::cognition::extensions::produce_speech_discipline( self.persona_id, self.persona_name.clone(), self.binding.load().model.clone().unwrap_or_default(), // unwrap_or_default: an unbound faculty stages under an empty base — the trigger keys buckets by base and files it honestly under "" diff --git a/core/continuum-mind/src/cognition/measurement_staging.rs b/core/continuum-cognition/src/cognition/measurement_staging.rs similarity index 100% rename from core/continuum-mind/src/cognition/measurement_staging.rs rename to core/continuum-cognition/src/cognition/measurement_staging.rs diff --git a/core/continuum-mind/src/cognition/mind_events.rs b/core/continuum-cognition/src/cognition/mind_events.rs similarity index 100% rename from core/continuum-mind/src/cognition/mind_events.rs rename to core/continuum-cognition/src/cognition/mind_events.rs diff --git a/core/continuum-mind/src/persona/mind_room.rs b/core/continuum-cognition/src/cognition/mind_room.rs similarity index 61% rename from core/continuum-mind/src/persona/mind_room.rs rename to core/continuum-cognition/src/cognition/mind_room.rs index a751c46323..a174d10b78 100644 --- a/core/continuum-mind/src/persona/mind_room.rs +++ b/core/continuum-cognition/src/cognition/mind_room.rs @@ -52,53 +52,6 @@ pub fn continuation_record_id(persona: Uuid) -> Uuid { Uuid::new_v5(&MIND_ROOM_NAMESPACE, &name) } -/// Seal her private continuation into her mind store (`Some`), or clear it (`None`). -/// Goes through her own runtime's `Airc::mind_store()`, so the core never holds her key. -/// `Ok(false)` = she has no resident airc runtime here; nothing was written. -pub fn seal_continuation( - persona: Uuid, - continuation: Option<&crate::persona::attention::Continuation>, -) -> Result { - let Some(runtime) = crate::persona::PersonaAircRuntimeRegistry::try_global().and_then(|r| r.get(persona)) else { - return Ok(false); - }; - let store = runtime.airc().mind_store().map_err(|e| e.to_string())?; - let id = continuation_record_id(persona); - match continuation { - Some(c) => { - let json = serde_json::to_string(c).map_err(|e| e.to_string())?; // disk boundary: her continuation as a sealed record in her mind store - store.put_at(id, &json).map_err(|e| e.to_string())?; - } - None => store.remove(id).map_err(|e| e.to_string())?, - } - Ok(true) -} - -/// Her sealed private continuation, if she left one: read back at boot so a Resume wake -/// continues her private thread after a restart. A store that will not open or a record -/// that will not parse is probed and read as none: her open state boots regardless. -pub fn sealed_continuation(persona: Uuid) -> Option { - let runtime = crate::persona::PersonaAircRuntimeRegistry::try_global()?.get(persona)?; - let store = match runtime.airc().mind_store() { - Ok(store) => store, - Err(e) => { - continuum_base::probe!(class = "mind.private.store_unopened", persona = %persona, error = %e.to_string(), "her mind store did not open at boot; no private continuation restored"); - return None; - } - }; - let id = continuation_record_id(persona); - if !store.list().ok()?.contains(&id) { - return None; - } - match store.get(id).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str(&t).map_err(|e| e.to_string())) { // disk boundary: read back from her sealed mind store - Ok(c) => Some(c), - Err(e) => { - continuum_base::probe!(class = "mind.private.continuation_unreadable", persona = %persona, error = %e, "her sealed continuation did not read back; not restored"); - None - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/core/continuum-mind/src/cognition/mod.rs b/core/continuum-cognition/src/cognition/mod.rs similarity index 91% rename from core/continuum-mind/src/cognition/mod.rs rename to core/continuum-cognition/src/cognition/mod.rs index 1c0d79a4bc..23666c59e2 100644 --- a/core/continuum-mind/src/cognition/mod.rs +++ b/core/continuum-cognition/src/cognition/mod.rs @@ -27,6 +27,26 @@ //! decision (the verb that produces //! `ResponderDecision`) +pub mod conversation; +pub mod extensions; +pub mod training_sources; +pub mod admission; +pub mod admission_persistence; +pub mod admission_state; +pub mod attention; +pub mod engram; +pub mod engram_graph; +pub mod home; +pub mod inbox_admission; +pub mod mind_room; +pub mod recall_metadata; +pub mod trace; +pub mod decay_tick; +pub mod cached_source; +pub mod card_facts; +pub mod card_holder; +pub mod grounding_invalidation; +pub mod room_substrates; pub mod framing_echo; pub mod not_speech; pub mod act_observe; @@ -92,7 +112,7 @@ pub mod persona_workspace; pub mod handoff; /// Bounded per-room diagnostics state, with the eviction decision CLAUDE.md /// requires of anything that accumulates (#3903 review). -pub(crate) mod bounded_room_ledger; +pub mod bounded_room_ledger; pub mod prompt_capture; pub(crate) mod prompt_prefix; pub mod rag_source_faculty; diff --git a/core/continuum-mind/src/cognition/model_binding.rs b/core/continuum-cognition/src/cognition/model_binding.rs similarity index 100% rename from core/continuum-mind/src/cognition/model_binding.rs rename to core/continuum-cognition/src/cognition/model_binding.rs diff --git a/core/continuum-mind/src/cognition/model_resolver/mod.rs b/core/continuum-cognition/src/cognition/model_resolver/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/model_resolver/mod.rs rename to core/continuum-cognition/src/cognition/model_resolver/mod.rs diff --git a/core/continuum-mind/src/cognition/model_resolver/types.rs b/core/continuum-cognition/src/cognition/model_resolver/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/model_resolver/types.rs rename to core/continuum-cognition/src/cognition/model_resolver/types.rs diff --git a/core/continuum-mind/src/cognition/not_speech.rs b/core/continuum-cognition/src/cognition/not_speech.rs similarity index 100% rename from core/continuum-mind/src/cognition/not_speech.rs rename to core/continuum-cognition/src/cognition/not_speech.rs diff --git a/core/continuum-mind/src/cognition/open_views.rs b/core/continuum-cognition/src/cognition/open_views.rs similarity index 100% rename from core/continuum-mind/src/cognition/open_views.rs rename to core/continuum-cognition/src/cognition/open_views.rs diff --git a/core/continuum-mind/src/cognition/parroted_perception.rs b/core/continuum-cognition/src/cognition/parroted_perception.rs similarity index 100% rename from core/continuum-mind/src/cognition/parroted_perception.rs rename to core/continuum-cognition/src/cognition/parroted_perception.rs diff --git a/core/continuum-mind/src/cognition/pass_intent.rs b/core/continuum-cognition/src/cognition/pass_intent.rs similarity index 100% rename from core/continuum-mind/src/cognition/pass_intent.rs rename to core/continuum-cognition/src/cognition/pass_intent.rs diff --git a/core/continuum-mind/src/cognition/perception_facts.rs b/core/continuum-cognition/src/cognition/perception_facts.rs similarity index 100% rename from core/continuum-mind/src/cognition/perception_facts.rs rename to core/continuum-cognition/src/cognition/perception_facts.rs diff --git a/core/continuum-mind/src/cognition/persona_tools.rs b/core/continuum-cognition/src/cognition/persona_tools.rs similarity index 100% rename from core/continuum-mind/src/cognition/persona_tools.rs rename to core/continuum-cognition/src/cognition/persona_tools.rs diff --git a/core/continuum-mind/src/cognition/persona_tools/tests.rs b/core/continuum-cognition/src/cognition/persona_tools/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/persona_tools/tests.rs rename to core/continuum-cognition/src/cognition/persona_tools/tests.rs diff --git a/core/continuum-mind/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs similarity index 98% rename from core/continuum-mind/src/cognition/persona_workspace.rs rename to core/continuum-cognition/src/cognition/persona_workspace.rs index d79118f210..c09f648cef 100644 --- a/core/continuum-mind/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -36,7 +36,7 @@ use super::recall_faculty::RecallFaculty; use super::working_memory::{WorkingMemory, WorkingMemoryFaculty}; use super::workspace::{ActingBody, Faculty, SituationFocusArbiter, WorkspaceCycle}; use crate::ai::adapter::AIProviderAdapter; -use crate::persona::admission_state::AdmissionState; +use crate::cognition::admission_state::AdmissionState; use crate::cognition::rag_budget::RagSource; /// Explicit offline adoption of a selected legacy checkpoint; shares this diff --git a/core/continuum-cognition/src/cognition/persona_workspace/acting_hands.rs b/core/continuum-cognition/src/cognition/persona_workspace/acting_hands.rs new file mode 100644 index 0000000000..3afdb73cc7 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/acting_hands.rs @@ -0,0 +1,330 @@ +use super::*; + +/// A persona's HANDS, lifted out of the cycle that owns them. +/// +/// Exists because rooting a measurement fork's workspace is a PROCESS-GLOBAL side effect that +/// must be undone after the cycle it was taken for is gone. `code/create-workspace` keys the +/// file engine on the CALLER identity (`caller_id(ctx)` → the persona's peer id), and the +/// engines live in one `DashMap` for the whole runtime — while a measurement fork shares the +/// living persona's `Arc` and her id. So re-rooting "the fork's" hands +/// re-roots the LIVING persona's hands, and nothing put them back. +/// +/// That is #312, measured 2026-08-04: after a SWE-bench solve on a flask clone, Anwen's LIVE +/// self ran `code/list(path=src)` → `flask/` and `code/read(src/flask/app.py)` in her ordinary +/// room turns, hours later. She had been left standing in the exam room. +/// +/// Carrying `(id, name, executor)` separately from the cycle is what makes the restore +/// possible on every exit path: the cycle gets consumed by `with_capture`, moved into the +/// drive, or dropped on an error — the hands handle outlives all of it. +#[derive(Clone)] +pub struct ActingHands { + pub persona_id: Uuid, + pub persona_name: String, + pub executor: Arc, + /// Her working memory: the restore clears the receipt scope the rooting set. + pub working_memory: Arc, + /// Which of her hands these are: `None` her live ones, `Some` an eval's or a fork's own + /// (`ToolExecutor::hands_context`). Rooting and restore act on THESE hands only. + pub context: Option, +} + +impl ActingHands { + /// The hands of a cycle that has them; `None` for a pure-cognition (handless) cycle. + pub fn of(cycle: &WorkspaceCycle) -> Option { + cycle.acting().map(|a| Self { + persona_id: a.persona_id, + persona_name: a.persona_name.clone(), + executor: a.executor.clone(), + working_memory: a.working_memory.clone(), + context: a.executor.hands_context(), + }) + } + + /// The same persona's hands in `context`, a context these hands don't own (a card + /// claim's): `None` when her executor can't act in a context. + pub fn in_context(&self, context: crate::identity::hands_context::HandsContext) -> Option { + Some(Self { + executor: self.executor.in_hands(self.persona_id, context)?, + context: Some(context), + ..self.clone() + }) + } + +} + +/// Drive `code/create-workspace` through the persona's OWN identity-bearing executor — +/// the single place either direction (root for a measurement, restore afterward) goes +/// through, so the ACL gate and the failure shape are identical for both +/// ([[the-compression-principle]]). +pub async fn drive_create_workspace( + hands: &ActingHands, + root: &str, + path_prepend: &[String], + call_id: &str, + refuse_inert_edits: bool, +) -> Result<(), crate::sdk_codegen::CommandError> { + let ws_ctx = crate::cognition::tool_executor::ToolExecutionContext { + persona_id: hands.persona_id, + persona_name: hands.persona_name.clone(), + session_id: Uuid::new_v4(), + context_id: Uuid::new_v4(), + caller_context: serde_json::Value::Null, + persona_config: crate::cognition::tool_executor::PersonaMediaConfigLite { + auto_load_media: false, + supported_media_types: vec![], + }, + }; + let ws_call = crate::ai::types::ToolCall { + id: call_id.to_string(), + name: "code/create-workspace".to_string(), + input: serde_json::json!({ + "workspace_root": root, + "path_prepend": path_prepend, + "refuse_inert_edits": refuse_inert_edits, + }), + }; + let ws_out = hands + .executor + .execute_native_batch(std::slice::from_ref(&ws_call), &ws_ctx, 8000) + .await + .map_err(|e| { + crate::sdk_codegen::CommandError::Internal(format!( + "failed to root workspace at '{root}': {e}" + )) + })?; + if let Some(r) = ws_out.results.first() { + if r.is_error.is_some() { + return Err(crate::sdk_codegen::CommandError::Internal(format!( + "code/create-workspace rejected workspace_root '{root}': {} — refusing to run with \ + the persona's hands rooted at the wrong directory (would score a false zero).", + r.content + ))); + } + } + Ok(()) +} + +/// WHERE HER HANDS STAND: the root a work turn rooted a set of her hands at (a card's +/// checkout), or nothing when they stand in her own workspace. Keyed by persona AND acting +/// context, so an eval's or a fork's place is its own and never overwrites her live one +/// (docs/architecture/HER-HANDS.md). Her live place (`None` context) is the one truth for the +/// workspace map she perceives and the scope her receipts carry; set at the rooting seam, +/// cleared on restore. +pub(super) static ACTING_ROOTS: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); + +/// Whose place: the persona, and which of her hands (`None` = live). +pub(super) type ActingKey = (uuid::Uuid, Option); + +/// Where she stands: the checkout root, and the card whose checkout it is when +/// a held card rooted her (None for a plain workspace_root). +#[derive(Clone, Debug)] +pub(super) struct ActingPlace { + pub(super) root: std::path::PathBuf, + pub(super) card: Option, +} + +/// The card-claim context her perception follows: the one her latest turn was bound to, or +/// none (her default hands, at home). Only WHICH hands she looks through changes; no hands' +/// place ever moves (card fc9e9fd7). Set by [`root_at_held_card`], cleared when that +/// claim's hands close. +pub(super) static FOCUS: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); + +pub fn focus_of(persona_id: uuid::Uuid) -> Option { + FOCUS.lock().unwrap_or_else(|e| e.into_inner()).get(&persona_id).copied() // poisoned lock = read the last state, same policy as every lock in this crate +} + +/// Point her perception at `context` (or home). The map she perceives re-renders when it moved. +pub fn set_focus(persona_id: uuid::Uuid, context: Option) { + let moved = { + let mut map = FOCUS.lock().unwrap_or_else(|e| e.into_inner()); // poisoned lock = read the last state, same policy as every lock in this crate + let before = match context { + Some(c) => map.insert(persona_id, c), + None => map.remove(&persona_id), + }; + before != context + }; + if moved { + crate::cognition::grounding_invalidation::mark_workspace_map_dirty(persona_id); + } + if context.is_none() { + crate::cognition::handoff::note_unbound(persona_id); + } +} + +/// Where the hands she is focused on stand (what she perceives and what her receipts are +/// scoped to): her current card claim's checkout, or nothing when she is at home. +pub fn acting_root_of(persona_id: uuid::Uuid) -> Option { + acting_root_in(persona_id, focus_of(persona_id)) +} + +/// Where one set of her hands stands: her live ones (`None`) or a context's. +pub fn acting_root_in(persona_id: uuid::Uuid, context: Option) -> Option { + ACTING_ROOTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&(persona_id, context)) + .map(|p| p.root.clone()) // poisoned lock = read the last state, same policy as every lock in this crate +} + +/// The card her hands are rooted at, if a held card rooted them. Her work +/// receipts radiate into THAT card's activity room, not the room whose line +/// happened to trigger the turn (2026-09-04: every holder's 💭/⚙ lines landed +/// in #academy — the base room and the agents' coordination room — because the +/// trigger arrived there; the run room stayed empty for its reviewer). +pub fn acting_card_of(persona_id: uuid::Uuid) -> Option { + acting_card_in(persona_id, focus_of(persona_id)) +} + +/// The card one set of her hands is rooted at: her live ones (`None`) or a context's. +pub fn acting_card_in(persona_id: uuid::Uuid, context: Option) -> Option { + ACTING_ROOTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&(persona_id, context)) + .and_then(|p| p.card) // poisoned lock = read the last state, same policy as every lock in this crate +} + +pub fn note_acting_card_in(persona_id: uuid::Uuid, context: Option, card: uuid::Uuid) { + if let Some(place) = ACTING_ROOTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_mut(&(persona_id, context)) + { + // poisoned lock = read the last state, same policy as every lock in this crate + place.card = Some(card); + } +} + +pub fn note_acting_root_in( + persona_id: uuid::Uuid, + context: Option, + root: Option, +) { + { + let mut map = ACTING_ROOTS.lock().unwrap_or_else(|e| e.into_inner()); // poisoned lock = read the last state, same policy as every lock in this crate + match root { + Some(r) => { + map.insert( + (persona_id, context), + ActingPlace { + root: r, + card: None, + }, + ); + } + None => { + map.remove(&(persona_id, context)); + } + } + } + // The map she perceives is the place of the hands she is focused on; an eval or a fork + // placing its own hands changes nothing she perceives. + let marked = context == focus_of(persona_id) && crate::cognition::grounding_invalidation::mark_workspace_map_dirty(persona_id); + continuum_base::probe!( + class = "workspace.acting_root", + persona_id = %persona_id, + context = %context.map(|c| c.id().to_string()).unwrap_or_else(|| "live".to_string()), // unwrap_or_else: no context = her live hands, named + root = %acting_root_in(persona_id, context).map(|p| p.display().to_string()).unwrap_or_default(), // unwrap_or: nothing recorded / a pre-epoch clock = 0, never a guess + map_marked_dirty = marked, + "where this set of her hands stands now; her live map re-renders only when her live hands moved" + ); +} + +/// What the board says became of a card she believed she held, from the ONE holder +/// projection the board itself renders (`card_holder`). PURE, so every branch is pinned: +/// a live lease held by `her` → `None` (the card IS hers — a renewal or re-claim landed +/// between the wake's two reads, nothing is gone); a live lease that is not hers → +/// `HeldBy`; a card past the claimable states → `MovedOn` (its life advanced, not a +/// lapse); otherwise `Lapsed` — the last lease, whoever's, ran out and nobody holds it. +/// `owner` is never read as authority: an expired claim still names its last holder, and +/// that holder may be her. +pub fn claim_gone_verdict( + card: &airc_lib::WorkCard, + now_ms: u64, + her: uuid::Uuid, +) -> Option { + use crate::cognition::working_memory::ClaimGone; + use crate::cognition::card_holder::{hold_of, refused_by_claim, Hold}; + if refused_by_claim(card.state) { + return Some(ClaimGone::MovedOn { + state: crate::cognition::card_facts::state_str(&card.state), + }); + } + let expired_at_ms = card.claim_expires_at_ms; + Some(match hold_of(card, now_ms) { + Hold::Held => match card.owner { + Some(peer) if peer.as_uuid() == her => return None, + Some(peer) => ClaimGone::HeldBy { + peer: peer.as_uuid(), + expires_at_ms: expired_at_ms, + }, + // A live hold with no owner cannot be rendered by the board either; say + // lapsed-and-open rather than invent a holder. + None => ClaimGone::Lapsed { expired_at_ms }, + }, + Hold::Lapsed | Hold::Unclaimed => ClaimGone::Lapsed { expired_at_ms }, + }) +} + +/// The activity this step perceives and acts IN: the board room of the card her hands are rooted on, by +/// the one definition of "which board holds a card" (`modules::work::room_holding_card`, +/// any activity, project or benchmark); else the room the turn was woken in. The wake room +/// is a fallback for acts with no subject yet (a help call before she has chosen a task), +/// never an override of one. It's the card of THESE hands (`context`): an eval's or a fork's +/// acts never inherit her live card's room (Astra's review of #5005). +pub async fn activity_room_for( + persona_id: Uuid, + context: Option, + wake_room: Uuid, +) -> Uuid { + if crate::cognition::mind_room::is_private_room(persona_id, wake_room) { + return wake_room; + } + let Some(card) = acting_card_in(persona_id, context) else { + return wake_room; + }; + crate::cognition::extensions::room_holding_card(persona_id, card).await.unwrap_or(wake_room) // unwrap_or: no board she stands in shows the card, so the wake room is the activity +} + +/// PURE: has the claim behind `context` ENDED, by the card's own row? Closed hands never +/// reopen (`code::hands`), so only an end may close them: the card is TERMINAL (Merged, +/// Closed), the claim was released (the board clears `claim_id`), or the card's claim is now +/// a different one (re-claimed, or another holder's). Not an end: a lease that LAPSED (same +/// claim id, renewed by her next heartbeat); Review or Blocked, which keep the claim (airc +/// `apply_card_state_changed` changes state and renews the lease, `claim_id` untouched), so a +/// send-back returns the card to InProgress under the SAME claim (Codex on #5247: reusing +/// `refused_by_claim`, which counts Review, would lock a resident out after her first +/// submission); and a row the board couldn't give. Closing on mere absence from her active claims locked Kimi out of +/// 0c69aa07 for hours (2026-10-21: `persona.work.hands_closing` on the 5090 every turn while +/// the board showed her claim live). +pub fn claim_has_ended( + context: crate::identity::hands_context::HandsContext, + card: Option<&airc_lib::WorkCard>, + her: uuid::Uuid, +) -> bool { + let Some(card) = card else { return false }; + if matches!(card.state, airc_work::model::CardState::Merged | airc_work::model::CardState::Closed) { + return true; + } + match card.claim_id { + None => true, + Some(current) => crate::identity::hands_context::HandsContext::for_claim(her, card.card_id.as_uuid(), current.as_uuid()) != context, + } +} + +/// Every card-claim place of `persona`'s hands: the claim context and the card it stands at. +/// Read for closing the hands of claims that ended; her live and eval/fork places (no card +/// claim) are not listed. +pub fn claimed_places_of(persona: uuid::Uuid) -> Vec<(crate::identity::hands_context::HandsContext, uuid::Uuid)> { + ACTING_ROOTS + .lock() + .unwrap_or_else(|e| e.into_inner()) // poisoned lock = read the last state, same policy as every lock in this crate + .iter() + .filter(|((owner, _), _)| *owner == persona) + .filter_map(|((_, context), place)| Some(((*context)?, place.card?))) + .collect() +} diff --git a/core/continuum-mind/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs similarity index 100% rename from core/continuum-mind/src/cognition/persona_workspace/checkpoint_adoption.rs rename to core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs diff --git a/core/continuum-mind/src/cognition/persona_workspace/default_workspace_capacity.rs b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs similarity index 98% rename from core/continuum-mind/src/cognition/persona_workspace/default_workspace_capacity.rs rename to core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs index f3f587f716..bd826e615c 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/default_workspace_capacity.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs @@ -684,12 +684,12 @@ pub(super) fn repoint_workspace_map_if_pinned( .and_then(|c| c.message_bus()); for g in cfg.grounding_sources.iter_mut() { if g.source.source_id() == "workspace-map" { - let pinned: Arc = Arc::new( - crate::persona::workspace_map_source::WorkspaceMapSource::for_pinned_root( - *persona_id, - root, - ), - ); + // The map source is persona's (its layout readers); the slot builds it at `root`. + let Some(pinned) = + crate::cognition::extensions::pinned_workspace_map(*persona_id, std::path::Path::new(root)) + else { + continue; + }; // Event-invalidated cache (#398): eval forks compose SYNCHRONOUSLY // (defer_grounding=false), so without this the pinned map re-walks // the repo dir on EVERY act — the measured per-act prefill churn on @@ -700,8 +700,8 @@ pub(super) fn repoint_workspace_map_if_pinned( g.source = match bus.clone() { Some(bus) => { let (cached, dirty) = - crate::persona::cached_source::CachedRagSource::new(pinned); - crate::persona::grounding_invalidation::spawn_workspace_invalidator( + crate::cognition::cached_source::CachedRagSource::new(pinned); + crate::cognition::grounding_invalidation::spawn_workspace_invalidator( bus, dirty.downgrade(), ); diff --git a/core/continuum-mind/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs similarity index 100% rename from core/continuum-mind/src/cognition/persona_workspace/own_speech_persisted.rs rename to core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs diff --git a/core/continuum-mind/src/cognition/persona_workspace/rehome.rs b/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs similarity index 95% rename from core/continuum-mind/src/cognition/persona_workspace/rehome.rs rename to core/continuum-cognition/src/cognition/persona_workspace/rehome.rs index e563a15d56..3acadab858 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/rehome.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs @@ -23,7 +23,7 @@ impl PersonaWorkspaceRegistry { /// (`ipc/mod.rs`) ONLY on an actual model change. The store is a wait-free /// `ArcSwap` under the cycles lock — NO await held across it. /// See [[seamless-persona-failover-model-and-genome]]. - pub(super) fn re_home_all_at( + pub fn re_home_all_at( &self, root: &std::path::Path, adapter: Arc, @@ -37,7 +37,7 @@ impl PersonaWorkspaceRegistry { templates .iter() .map(|(id, cfg)| { - let assignment = match crate::persona::remote_lane_factory::is_remote_bound(root, &cfg.persona_name) { + let assignment = match crate::cognition::extensions::is_remote_bound(root, &cfg.persona_name) { Ok(false) => Assignment::Local, Ok(true) => Assignment::Remote, Err(error) => { diff --git a/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs similarity index 99% rename from core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs rename to core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index 49b13e3fb5..a60ee013ed 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -155,7 +155,7 @@ impl PersonaWorkspaceRegistry { /// her live cycle everywhere else. THE selection the service loop asks (one rule, two /// call sites: a message turn and a self/continuation turn). pub fn cycle_for_room(&self, persona_id: &Uuid, room: Uuid) -> Option> { - if crate::persona::mind_room::is_private_room(*persona_id, room) { + if crate::cognition::mind_room::is_private_room(*persona_id, room) { self.mind_cycle(persona_id) } else { self.get(persona_id) diff --git a/core/continuum-mind/src/cognition/persona_workspace/tests.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs similarity index 74% rename from core/continuum-mind/src/cognition/persona_workspace/tests.rs rename to core/continuum-cognition/src/cognition/persona_workspace/tests.rs index 44d56c2263..9e657b1452 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs @@ -10,9 +10,9 @@ use crate::cognition::workspace::Decision; - use crate::persona::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::persona::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; + use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; mod she_is_told_when_her_hands_move_and_only_then; mod final_checkpoint_drains_admitted_periodic_writer_before_ack; diff --git a/core/continuum-mind/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs similarity index 93% rename from core/continuum-mind/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs rename to core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs index baca57f58a..6d9f4f0436 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs @@ -129,34 +129,6 @@ use super::*; state } - // Serving-edge rehome must preserve a resident's binding when its assignment is corrupt. - #[tokio::test] - pub(super) async fn rehome_requires_a_readable_local_assignment() { - let root = tempfile::tempdir().expect("root"); - let _native = crate::paths::NativeHomeOverride::install(root.path()); - let registry = PersonaWorkspaceRegistry::new(); - let id = Uuid::new_v4(); - let cycle = registry.register_from_cfg(cfg_for(id)).expect("resident"); - let (original, original_model) = cycle.current_model_route().expect("binding"); - let airc = crate::identity::citizen_path::citizen_home_path(root.path(), crate::identity::IdentityKind::Persona, None, "Ivar"); - let home = crate::persona::home::PersonaHome::from_root(airc.parent().expect("parent").to_path_buf()); - let remote = crate::persona::PersonaModelOverride::new_remote("remote/model", None, 1, Uuid::new_v4().to_string()); - remote.write(&home).expect("remote override"); - let replacement: Arc = Arc::new(HeuristicInferenceAdapter::new()); - for corrupt in [false, true] { - if corrupt { std::fs::write(home.model_override_json(), b"{").expect("corrupt"); } - assert_eq!(registry.re_home_all_at(root.path(), replacement.clone(), Some("new/local".into()), 4096), 0); - let (actual, model) = cycle.current_model_route().expect("preserved"); - assert!(Arc::ptr_eq(&original, &actual)); - assert_eq!(model, original_model); - } - crate::persona::PersonaModelOverride::new("local/model", None, 2).write(&home).expect("local override"); - assert_eq!(registry.re_home_all_at(root.path(), replacement.clone(), Some("new/local".into()), 4096), 1); - let (actual, model) = cycle.current_model_route().expect("rebound"); - assert!(Arc::ptr_eq(&replacement, &actual)); - assert_eq!(model.as_deref(), Some("new/local")); - } - pub(super) fn cfg_for(persona_id: Uuid) -> PersonaBrainConfig { PersonaBrainConfig { persona_id, diff --git a/core/continuum-mind/src/cognition/persona_workspace/tests/gated_grounding.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs similarity index 100% rename from core/continuum-mind/src/cognition/persona_workspace/tests/gated_grounding.rs rename to core/continuum-cognition/src/cognition/persona_workspace/tests/gated_grounding.rs diff --git a/core/continuum-mind/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs similarity index 96% rename from core/continuum-mind/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs rename to core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 34fc31e3b1..9e06fa88fe 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -1,27 +1,6 @@ #![cfg(test)] use super::*; - // what this catches (card 822c4253): her hands moving to a card's own checkout with no - // word (Kimi's code/read of career-wrangler/docs/... failing in a per-card worktree), - // or the notice repeating every turn at the same checkout. Told on a new root, silent - // on the same one, told again when it moves; the notice names root, branch and the - // home tree that did not move. - #[test] - pub(super) fn she_is_told_when_her_hands_move_and_only_then() { - let kimi = Uuid::new_v4(); - let card = std::path::Path::new("/w/worktrees/af4e2cea"); - assert!(!already_told(kimi, card), "first rooting is news"); - assert!(!already_told(kimi, card), "checking does not record: only a pinned line does"); - mark_told(kimi, card); - assert!(already_told(kimi, card), "the same checkout next turn is not news"); - assert!(!already_told(kimi, std::path::Path::new("/w/worktrees/b0b0b0b0"))); - assert!(!already_told(Uuid::new_v4(), card), "per citizen, never shared"); - let line = rooted_notice("CambrianTech/career-wrangler", card, "af4e2cea/a-real-product"); - for want in ["/w/worktrees/af4e2cea", "af4e2cea/a-real-product", "docs/x.md", "home workspace is unchanged"] { - assert!(line.contains(want), "{want}: {line}"); - } - } - // what this catches (Astra's block on #4315): the wake's verdict must come from the // board's holder projection, never from `owner` read as authority. An EXPIRED claim // still names its last holder — which may be HER — so "X took it" from `owner` would @@ -612,7 +591,7 @@ use super::*; let registry = PersonaWorkspaceRegistry::new(); let her = Uuid::new_v4(); let live = registry.register_from_cfg(cfg_for(her)).expect("live cycle"); - let mind_room = crate::persona::mind_room::mind_room_id(her); + let mind_room = crate::cognition::mind_room::mind_room_id(her); let mind = registry.cycle_for_room(&her, mind_room).expect("her mind cycle"); assert!(!Arc::ptr_eq(&live, &mind), "her mind room runs on its own cycle"); assert!( diff --git a/core/continuum-mind/src/cognition/presence_glyph.rs b/core/continuum-cognition/src/cognition/presence_glyph.rs similarity index 100% rename from core/continuum-mind/src/cognition/presence_glyph.rs rename to core/continuum-cognition/src/cognition/presence_glyph.rs diff --git a/core/continuum-mind/src/cognition/prompt_assembly.rs b/core/continuum-cognition/src/cognition/prompt_assembly.rs similarity index 100% rename from core/continuum-mind/src/cognition/prompt_assembly.rs rename to core/continuum-cognition/src/cognition/prompt_assembly.rs diff --git a/core/continuum-mind/src/cognition/prompt_assembly/tests.rs b/core/continuum-cognition/src/cognition/prompt_assembly/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/prompt_assembly/tests.rs rename to core/continuum-cognition/src/cognition/prompt_assembly/tests.rs diff --git a/core/continuum-mind/src/cognition/prompt_capture.rs b/core/continuum-cognition/src/cognition/prompt_capture.rs similarity index 98% rename from core/continuum-mind/src/cognition/prompt_capture.rs rename to core/continuum-cognition/src/cognition/prompt_capture.rs index 20a56e89dc..6024d5421e 100644 --- a/core/continuum-mind/src/cognition/prompt_capture.rs +++ b/core/continuum-cognition/src/cognition/prompt_capture.rs @@ -12,7 +12,7 @@ pub(super) mod owner; #[path = "prompt_capture_store.rs"] mod store; -pub(crate) use store::{detail, page}; +pub use store::{detail, page}; pub use store::{CallHeader, CallStatus, PlaybackDetail, PlaybackPage}; use store::{PayloadRef, Store}; pub const FIXTURE_DIR: &str = ".continuum/fixtures/prompt-captures"; @@ -105,7 +105,7 @@ pub trait PromptCaptureSink: Send + Sync { /// Contains only a sink handle and small metadata; cancellation cannot orphan a /// submitted call while the core remains alive. Process death is honestly left /// pending, not fabricated as a completion by a later reader. -pub(crate) struct CaptureLease { +pub struct CaptureLease { sink: Arc, token: Option, started: std::time::Instant, @@ -119,8 +119,8 @@ impl CaptureLease { // A turn in her mind room is hers (PRIVACY-OF-THOUGHT.md §4, sink 2): the lease is // inert, so neither `finish` nor `Drop` writes, and every dataset built from // captures (sink 3) has nothing to read. - let token = if crate::persona::mind_room::is_private_room(call.persona_id, call.room_id) { - crate::persona::mind_room::note_withheld(call.persona_id, "prompt_capture"); + let token = if crate::cognition::mind_room::is_private_room(call.persona_id, call.room_id) { + crate::cognition::mind_room::note_withheld(call.persona_id, "prompt_capture"); None } else { sink.submitted(call, request) @@ -451,7 +451,7 @@ impl PromptCaptureSink for JsonlPromptCaptureSink { /// One recorded call read back from its capture: the exact request she was served /// and, when the call finished, the exact response she gave. The single decode of a /// schema-4 capture; replay and the training lifter both read through it. -pub(crate) struct CapturedCall { +pub struct CapturedCall { pub context_window: Option, pub request: TextGenerationRequest, pub response: Option, @@ -459,7 +459,7 @@ pub(crate) struct CapturedCall { /// Decode a capture's detail into its typed call. Refuses a capture with integrity /// issues or an older schema rather than guessing at its shape. -pub(crate) fn decode(mut detail: PlaybackDetail) -> Result { +pub fn decode(mut detail: PlaybackDetail) -> Result { if !detail.issues.is_empty() { return Err(format!("capture integrity: {}", detail.issues.join("; "))); } @@ -727,7 +727,7 @@ mod tests { }; // Opening the store may write its own index; the turn must add nothing beyond it. let opened = bytes(dir.path()); - let mind = crate::persona::mind_room::mind_room_id(persona); + let mind = crate::cognition::mind_room::mind_room_id(persona); let mut finished = CaptureLease::start(Arc::clone(&sink), &call(mind), &request); assert_eq!(finished.finish(None, Some("done")), None, "an inert lease names no entry"); drop(CaptureLease::start(Arc::clone(&sink), &call(mind), &request)); @@ -806,7 +806,7 @@ mod tests { assert!(with_newline.wire.is_some() && with_newline.wire_omitted.is_none(), "JSON plus newline fits"); let private_id = format!("wire-{}", Uuid::new_v4()); - let mind = crate::persona::mind_room::mind_room_id(persona); + let mind = crate::cognition::mind_room::mind_room_id(persona); drop(CaptureLease::start(Arc::clone(&sink), &call(mind, &private_id), &request)); let mut thought = crate::inference::wire_tap::WireTap::open(Some(&private_id)); thought.push("a private token"); diff --git a/core/continuum-mind/src/cognition/prompt_capture_store.rs b/core/continuum-cognition/src/cognition/prompt_capture_store.rs similarity index 100% rename from core/continuum-mind/src/cognition/prompt_capture_store.rs rename to core/continuum-cognition/src/cognition/prompt_capture_store.rs diff --git a/core/continuum-mind/src/cognition/prompt_prefix.rs b/core/continuum-cognition/src/cognition/prompt_prefix.rs similarity index 100% rename from core/continuum-mind/src/cognition/prompt_prefix.rs rename to core/continuum-cognition/src/cognition/prompt_prefix.rs diff --git a/core/continuum-mind/src/cognition/rag_budget.rs b/core/continuum-cognition/src/cognition/rag_budget.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_budget.rs rename to core/continuum-cognition/src/cognition/rag_budget.rs diff --git a/core/continuum-mind/src/cognition/rag_budget/flex_allocate.rs b/core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_budget/flex_allocate.rs rename to core/continuum-cognition/src/cognition/rag_budget/flex_allocate.rs diff --git a/core/continuum-mind/src/cognition/rag_budget/substrate_context.rs b/core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_budget/substrate_context.rs rename to core/continuum-cognition/src/cognition/rag_budget/substrate_context.rs diff --git a/core/continuum-mind/src/cognition/rag_budget/tests.rs b/core/continuum-cognition/src/cognition/rag_budget/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_budget/tests.rs rename to core/continuum-cognition/src/cognition/rag_budget/tests.rs diff --git a/core/continuum-mind/src/cognition/rag_source_faculty.rs b/core/continuum-cognition/src/cognition/rag_source_faculty.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_source_faculty.rs rename to core/continuum-cognition/src/cognition/rag_source_faculty.rs diff --git a/core/continuum-mind/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/rag_source_faculty/tests.rs rename to core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs diff --git a/core/continuum-mind/src/cognition/rate_proposals/mod.rs b/core/continuum-cognition/src/cognition/rate_proposals/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/rate_proposals/mod.rs rename to core/continuum-cognition/src/cognition/rate_proposals/mod.rs diff --git a/core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs b/core/continuum-cognition/src/cognition/rate_proposals/orchestrator.rs similarity index 100% rename from core/continuum-mind/src/cognition/rate_proposals/orchestrator.rs rename to core/continuum-cognition/src/cognition/rate_proposals/orchestrator.rs diff --git a/core/continuum-mind/src/cognition/rate_proposals/parser.rs b/core/continuum-cognition/src/cognition/rate_proposals/parser.rs similarity index 100% rename from core/continuum-mind/src/cognition/rate_proposals/parser.rs rename to core/continuum-cognition/src/cognition/rate_proposals/parser.rs diff --git a/core/continuum-mind/src/cognition/rate_proposals/prompt.rs b/core/continuum-cognition/src/cognition/rate_proposals/prompt.rs similarity index 100% rename from core/continuum-mind/src/cognition/rate_proposals/prompt.rs rename to core/continuum-cognition/src/cognition/rate_proposals/prompt.rs diff --git a/core/continuum-mind/src/cognition/rate_proposals/types.rs b/core/continuum-cognition/src/cognition/rate_proposals/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/rate_proposals/types.rs rename to core/continuum-cognition/src/cognition/rate_proposals/types.rs diff --git a/core/continuum-mind/src/cognition/recall_faculty.rs b/core/continuum-cognition/src/cognition/recall_faculty.rs similarity index 99% rename from core/continuum-mind/src/cognition/recall_faculty.rs rename to core/continuum-cognition/src/cognition/recall_faculty.rs index bfb1f222ae..dfbef7f9af 100644 --- a/core/continuum-mind/src/cognition/recall_faculty.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty.rs @@ -44,8 +44,8 @@ use uuid::Uuid; use crate::ai::embedding::EmbeddingProvider; use super::working_memory::WorkingMemory; use super::workspace::{Contribution, Faculty, FacultyId, Workspace}; -use crate::persona::admission_state::AdmissionState; -use crate::persona::engram::{Engram, EngramOrigin}; +use crate::cognition::admission_state::AdmissionState; +use crate::cognition::engram::{Engram, EngramOrigin}; /// Hard safety ceiling on memories surfaced per tick, regardless of model size — /// the [`RecallBudget`] picks the ACTUAL count (smaller) within this. `with_limit` diff --git a/core/continuum-mind/src/cognition/recall_faculty/tests.rs b/core/continuum-cognition/src/cognition/recall_faculty/tests.rs similarity index 70% rename from core/continuum-mind/src/cognition/recall_faculty/tests.rs rename to core/continuum-cognition/src/cognition/recall_faculty/tests.rs index 4b73d16ff1..ba9a8a96db 100644 --- a/core/continuum-mind/src/cognition/recall_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty/tests.rs @@ -1,9 +1,9 @@ #![cfg(test)] use super::*; - use crate::persona::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::persona::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; + use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; // ---- The mind in action: real hippocampus → workspace → informed decision ---- use super::super::workspace::{Decision, NoopWorkspaceCaptureSink, WorkspaceCaptureSink, WorkspaceCycle, WorkspaceTrace}; diff --git a/core/continuum-mind/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs b/core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs similarity index 100% rename from core/continuum-mind/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs rename to core/continuum-cognition/src/cognition/recall_faculty/tests/mind_in_action_recall_informs_the_decision.rs diff --git a/core/continuum-mind/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs b/core/continuum-cognition/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs similarity index 99% rename from core/continuum-mind/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs rename to core/continuum-cognition/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs index e6dfd8f12a..8bf710a095 100644 --- a/core/continuum-mind/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs +++ b/core/continuum-cognition/src/cognition/recall_faculty/tests/near_identical_own_turns_collapse_but_distinct_memories_survive.rs @@ -349,8 +349,8 @@ use super::*; // coherence depends on. #[tokio::test] pub(super) async fn memory_carries_context_across_turns() { - use crate::persona::engram::AdmissionDecision; - use crate::persona::types::{InboxMessage, SenderType}; + use crate::cognition::engram::AdmissionDecision; + use crate::cognition::conversation::types::{InboxMessage, SenderType}; let now1 = 1_000_000_000u64; let recall_meta = Arc::new(RecallMetadataRegistry::new()); diff --git a/core/continuum-mind/src/persona/recall_metadata.rs b/core/continuum-cognition/src/cognition/recall_metadata.rs similarity index 100% rename from core/continuum-mind/src/persona/recall_metadata.rs rename to core/continuum-cognition/src/cognition/recall_metadata.rs diff --git a/core/continuum-mind/src/persona/recall_metadata/tests.rs b/core/continuum-cognition/src/cognition/recall_metadata/tests.rs similarity index 99% rename from core/continuum-mind/src/persona/recall_metadata/tests.rs rename to core/continuum-cognition/src/cognition/recall_metadata/tests.rs index 27e1dda617..bb6d578a35 100644 --- a/core/continuum-mind/src/persona/recall_metadata/tests.rs +++ b/core/continuum-cognition/src/cognition/recall_metadata/tests.rs @@ -448,7 +448,7 @@ use crate::orm::adapter::StorageAdapter; use crate::orm::sqlite::SqliteAdapter; use crate::orm::OrmStore; - use crate::persona::engram::{AircMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::engram::{AircMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; use std::sync::Arc; let tmp = tempfile::tempdir().expect("tempdir"); diff --git a/core/continuum-mind/src/cognition/recall_ranker.rs b/core/continuum-cognition/src/cognition/recall_ranker.rs similarity index 100% rename from core/continuum-mind/src/cognition/recall_ranker.rs rename to core/continuum-cognition/src/cognition/recall_ranker.rs diff --git a/core/continuum-mind/src/cognition/redaction.rs b/core/continuum-cognition/src/cognition/redaction.rs similarity index 100% rename from core/continuum-mind/src/cognition/redaction.rs rename to core/continuum-cognition/src/cognition/redaction.rs diff --git a/core/continuum-mind/src/cognition/replay.rs b/core/continuum-cognition/src/cognition/replay.rs similarity index 99% rename from core/continuum-mind/src/cognition/replay.rs rename to core/continuum-cognition/src/cognition/replay.rs index 7418a937c6..da5eb331da 100644 --- a/core/continuum-mind/src/cognition/replay.rs +++ b/core/continuum-cognition/src/cognition/replay.rs @@ -71,7 +71,7 @@ struct TraceLine { room_id: String, world_state: String, #[serde(default)] - room_updates: Vec, + room_updates: Vec, /// The assembled broadcast that reached the decider this tick. Absent on /// older traces (pre-context-replay) → empty, handled as "no broadcast". #[serde(default)] @@ -202,7 +202,7 @@ struct ResolvedBurst { room: String, source: String, broadcast: Vec, - room_updates: Vec, + room_updates: Vec, } impl ResolvedBurst { @@ -249,7 +249,7 @@ impl ResolvedBurst { fn build_budget( world_state: &str, broadcast: &[Contribution], - room_updates: &[crate::persona::service_loop::IncomingMessage], + room_updates: &[crate::cognition::conversation::IncomingMessage], ) -> PromptBudget { let world_state_tokens = estimate_prompt_tokens(world_state); let mut layers: Vec = broadcast @@ -649,7 +649,7 @@ mod tests { use crate::cognition::llm_deliberation_faculty::LlmDeliberationFaculty; use crate::cognition::workspace::{Faculty, WorkspaceCaptureSink, WorkspaceTrace}; use crate::cognition::workspace_capture::JsonlWorkspaceCaptureSink; - use crate::persona::service_loop::IncomingMessage; + use crate::cognition::conversation::IncomingMessage; use std::sync::{Arc, Mutex}; let dir = tempfile::tempdir().unwrap(); diff --git a/core/continuum-mind/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs similarity index 100% rename from core/continuum-mind/src/cognition/request_replay.rs rename to core/continuum-cognition/src/cognition/request_replay.rs diff --git a/core/continuum-mind/src/cognition/response_orchestrator.rs b/core/continuum-cognition/src/cognition/response_orchestrator.rs similarity index 100% rename from core/continuum-mind/src/cognition/response_orchestrator.rs rename to core/continuum-cognition/src/cognition/response_orchestrator.rs diff --git a/core/continuum-mind/src/cognition/response_validator.rs b/core/continuum-cognition/src/cognition/response_validator.rs similarity index 100% rename from core/continuum-mind/src/cognition/response_validator.rs rename to core/continuum-cognition/src/cognition/response_validator.rs diff --git a/core/continuum-mind/src/cognition/room_directory.rs b/core/continuum-cognition/src/cognition/room_directory.rs similarity index 100% rename from core/continuum-mind/src/cognition/room_directory.rs rename to core/continuum-cognition/src/cognition/room_directory.rs diff --git a/core/continuum-mind/src/cognition/room_roster.rs b/core/continuum-cognition/src/cognition/room_roster.rs similarity index 95% rename from core/continuum-mind/src/cognition/room_roster.rs rename to core/continuum-cognition/src/cognition/room_roster.rs index fec6f4ab9f..b7f58973d9 100644 --- a/core/continuum-mind/src/cognition/room_roster.rs +++ b/core/continuum-cognition/src/cognition/room_roster.rs @@ -17,7 +17,7 @@ use uuid::Uuid; /// reader tells "armed and clean" from "had nothing to check against". pub fn present_names(room: Uuid) -> Vec { let (outcome, names): (&str, Vec) = - match crate::persona::room_substrates::global_room_substrates().read_room(room) { + match crate::cognition::room_substrates::global_room_substrates().read_room(room) { None => ("no_substrate", Vec::new()), Some(substrate) => match substrate.cache().get(continuum_positron::RosterViewState::KIND) { None => ("no_roster_envelope", Vec::new()), diff --git a/core/continuum-mind/src/persona/room_substrates.rs b/core/continuum-cognition/src/cognition/room_substrates.rs similarity index 100% rename from core/continuum-mind/src/persona/room_substrates.rs rename to core/continuum-cognition/src/cognition/room_substrates.rs diff --git a/core/continuum-mind/src/cognition/self_repeat.rs b/core/continuum-cognition/src/cognition/self_repeat.rs similarity index 100% rename from core/continuum-mind/src/cognition/self_repeat.rs rename to core/continuum-cognition/src/cognition/self_repeat.rs diff --git a/core/continuum-mind/src/cognition/shared_analysis/error.rs b/core/continuum-cognition/src/cognition/shared_analysis/error.rs similarity index 100% rename from core/continuum-mind/src/cognition/shared_analysis/error.rs rename to core/continuum-cognition/src/cognition/shared_analysis/error.rs diff --git a/core/continuum-mind/src/cognition/shared_analysis/mod.rs b/core/continuum-cognition/src/cognition/shared_analysis/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/shared_analysis/mod.rs rename to core/continuum-cognition/src/cognition/shared_analysis/mod.rs diff --git a/core/continuum-mind/src/cognition/shared_analysis/prompt.rs b/core/continuum-cognition/src/cognition/shared_analysis/prompt.rs similarity index 100% rename from core/continuum-mind/src/cognition/shared_analysis/prompt.rs rename to core/continuum-cognition/src/cognition/shared_analysis/prompt.rs diff --git a/core/continuum-mind/src/cognition/shared_analysis/types.rs b/core/continuum-cognition/src/cognition/shared_analysis/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/shared_analysis/types.rs rename to core/continuum-cognition/src/cognition/shared_analysis/types.rs diff --git a/core/continuum-mind/src/cognition/should_respond.rs b/core/continuum-cognition/src/cognition/should_respond.rs similarity index 100% rename from core/continuum-mind/src/cognition/should_respond.rs rename to core/continuum-cognition/src/cognition/should_respond.rs diff --git a/core/continuum-mind/src/cognition/should_respond_module.rs b/core/continuum-cognition/src/cognition/should_respond_module.rs similarity index 97% rename from core/continuum-mind/src/cognition/should_respond_module.rs rename to core/continuum-cognition/src/cognition/should_respond_module.rs index d074160cbb..1aaaca56de 100644 --- a/core/continuum-mind/src/cognition/should_respond_module.rs +++ b/core/continuum-cognition/src/cognition/should_respond_module.rs @@ -122,9 +122,9 @@ mod tests { use super::*; use crate::ai::heuristic_adapter::HeuristicInferenceAdapter; use crate::cognition::persona_workspace::PersonaBrainConfig; - use crate::persona::admission_state::AdmissionState; - use crate::persona::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::persona::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; + use crate::cognition::admission_state::AdmissionState; + use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; use crate::runtime::service_module::CommandResult; fn seed_admission(now_ms: u64) -> Arc { diff --git a/core/continuum-mind/src/cognition/swe_bench.rs b/core/continuum-cognition/src/cognition/swe_bench.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench.rs rename to core/continuum-cognition/src/cognition/swe_bench.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/build_env_from_scratch.rs b/core/continuum-cognition/src/cognition/swe_bench/build_env_from_scratch.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/build_env_from_scratch.rs rename to core/continuum-cognition/src/cognition/swe_bench/build_env_from_scratch.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/diff_target_paths.rs b/core/continuum-cognition/src/cognition/swe_bench/diff_target_paths.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/diff_target_paths.rs rename to core/continuum-cognition/src/cognition/swe_bench/diff_target_paths.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/fetch_hf_rows.rs b/core/continuum-cognition/src/cognition/swe_bench/fetch_hf_rows.rs similarity index 99% rename from core/continuum-mind/src/cognition/swe_bench/fetch_hf_rows.rs rename to core/continuum-cognition/src/cognition/swe_bench/fetch_hf_rows.rs index c427afb26c..fe5cc58da1 100644 --- a/core/continuum-mind/src/cognition/swe_bench/fetch_hf_rows.rs +++ b/core/continuum-cognition/src/cognition/swe_bench/fetch_hf_rows.rs @@ -385,7 +385,7 @@ pub(super) fn clone_lock_for(repo_dir: &Path) -> std::sync::Arc.cloning--`): a clone before its rename commit-point, never a /// usable checkout even when it already carries a `.git`. The one place that knows the /// shape, beside the one place that makes it. -pub(crate) fn is_in_flight_staging_name(name: &str) -> bool { +pub fn is_in_flight_staging_name(name: &str) -> bool { name.contains(".cloning-") } diff --git a/core/continuum-mind/src/cognition/swe_bench/grade.rs b/core/continuum-cognition/src/cognition/swe_bench/grade.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/grade.rs rename to core/continuum-cognition/src/cognition/swe_bench/grade.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/log_parser.rs b/core/continuum-cognition/src/cognition/swe_bench/log_parser.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/log_parser.rs rename to core/continuum-cognition/src/cognition/swe_bench/log_parser.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/split_node_outcome.rs b/core/continuum-cognition/src/cognition/swe_bench/split_node_outcome.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/split_node_outcome.rs rename to core/continuum-cognition/src/cognition/swe_bench/split_node_outcome.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/swe_instance.rs b/core/continuum-cognition/src/cognition/swe_bench/swe_instance.rs similarity index 99% rename from core/continuum-mind/src/cognition/swe_bench/swe_instance.rs rename to core/continuum-cognition/src/cognition/swe_bench/swe_instance.rs index 8e8d3ee9ad..4f7a8cfd97 100644 --- a/core/continuum-mind/src/cognition/swe_bench/swe_instance.rs +++ b/core/continuum-cognition/src/cognition/swe_bench/swe_instance.rs @@ -384,7 +384,7 @@ pub fn regrade_history_path(instance_id: &str) -> PathBuf { pub fn record_verdict(verdict: &SweVerdict, is_gold: bool) -> Result, String> { let recorded = persist_verdict(verdict, is_gold)?; if recorded.is_some() { - crate::persona::training_producer::settle_instance_credit(&verdict.instance_id, verdict.resolved); + crate::cognition::extensions::settle_instance_credit(&verdict.instance_id, verdict.resolved); } Ok(recorded) } @@ -395,7 +395,7 @@ pub async fn record_card_verdict( verdict: &SweVerdict, card: uuid::Uuid, ) -> Result, String> { - record_card_verdict_with(verdict, card, crate::persona::training_producer::settle_card_credit).await + record_card_verdict_with(verdict, card, crate::cognition::extensions::settle_card_credit).await } pub async fn record_card_verdict_with( diff --git a/core/continuum-mind/src/cognition/swe_bench/tests/mod.rs b/core/continuum-cognition/src/cognition/swe_bench/tests/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/tests/mod.rs rename to core/continuum-cognition/src/cognition/swe_bench/tests/mod.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/tests/part_2.rs b/core/continuum-cognition/src/cognition/swe_bench/tests/part_2.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/tests/part_2.rs rename to core/continuum-cognition/src/cognition/swe_bench/tests/part_2.rs diff --git a/core/continuum-mind/src/cognition/swe_bench/tests/part_3.rs b/core/continuum-cognition/src/cognition/swe_bench/tests/part_3.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_bench/tests/part_3.rs rename to core/continuum-cognition/src/cognition/swe_bench/tests/part_3.rs diff --git a/core/continuum-mind/src/cognition/swe_verdict_sweep.rs b/core/continuum-cognition/src/cognition/swe_verdict_sweep.rs similarity index 100% rename from core/continuum-mind/src/cognition/swe_verdict_sweep.rs rename to core/continuum-cognition/src/cognition/swe_verdict_sweep.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/ascii_case.rs b/core/continuum-cognition/src/cognition/text_analysis/ascii_case.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/ascii_case.rs rename to core/continuum-cognition/src/cognition/text_analysis/ascii_case.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/garbage_detection.rs b/core/continuum-cognition/src/cognition/text_analysis/garbage_detection.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/garbage_detection.rs rename to core/continuum-cognition/src/cognition/text_analysis/garbage_detection.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/loop_detection.rs b/core/continuum-cognition/src/cognition/text_analysis/loop_detection.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/loop_detection.rs rename to core/continuum-cognition/src/cognition/text_analysis/loop_detection.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/mention_detection.rs b/core/continuum-cognition/src/cognition/text_analysis/mention_detection.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/mention_detection.rs rename to core/continuum-cognition/src/cognition/text_analysis/mention_detection.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/mod.rs b/core/continuum-cognition/src/cognition/text_analysis/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/mod.rs rename to core/continuum-cognition/src/cognition/text_analysis/mod.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/response_cleaning.rs b/core/continuum-cognition/src/cognition/text_analysis/response_cleaning.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/response_cleaning.rs rename to core/continuum-cognition/src/cognition/text_analysis/response_cleaning.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/similarity.rs b/core/continuum-cognition/src/cognition/text_analysis/similarity.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/similarity.rs rename to core/continuum-cognition/src/cognition/text_analysis/similarity.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/types.rs b/core/continuum-cognition/src/cognition/text_analysis/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/types.rs rename to core/continuum-cognition/src/cognition/text_analysis/types.rs diff --git a/core/continuum-mind/src/cognition/text_analysis/validation.rs b/core/continuum-cognition/src/cognition/text_analysis/validation.rs similarity index 100% rename from core/continuum-mind/src/cognition/text_analysis/validation.rs rename to core/continuum-cognition/src/cognition/text_analysis/validation.rs diff --git a/core/continuum-mind/src/cognition/token_budget.rs b/core/continuum-cognition/src/cognition/token_budget.rs similarity index 100% rename from core/continuum-mind/src/cognition/token_budget.rs rename to core/continuum-cognition/src/cognition/token_budget.rs diff --git a/core/continuum-mind/src/cognition/tool_embedding.rs b/core/continuum-cognition/src/cognition/tool_embedding.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_embedding.rs rename to core/continuum-cognition/src/cognition/tool_embedding.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/command_executor.rs b/core/continuum-cognition/src/cognition/tool_executor/command_executor.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/command_executor.rs rename to core/continuum-cognition/src/cognition/tool_executor/command_executor.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/command_executor/tests.rs b/core/continuum-cognition/src/cognition/tool_executor/command_executor/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/command_executor/tests.rs rename to core/continuum-cognition/src/cognition/tool_executor/command_executor/tests.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/mod.rs b/core/continuum-cognition/src/cognition/tool_executor/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/mod.rs rename to core/continuum-cognition/src/cognition/tool_executor/mod.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/result_tap.rs b/core/continuum-cognition/src/cognition/tool_executor/result_tap.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/result_tap.rs rename to core/continuum-cognition/src/cognition/tool_executor/result_tap.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/spill.rs b/core/continuum-cognition/src/cognition/tool_executor/spill.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/spill.rs rename to core/continuum-cognition/src/cognition/tool_executor/spill.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/spill/tests.rs b/core/continuum-cognition/src/cognition/tool_executor/spill/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/spill/tests.rs rename to core/continuum-cognition/src/cognition/tool_executor/spill/tests.rs diff --git a/core/continuum-mind/src/cognition/tool_executor/types.rs b/core/continuum-cognition/src/cognition/tool_executor/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_executor/types.rs rename to core/continuum-cognition/src/cognition/tool_executor/types.rs diff --git a/core/continuum-mind/src/cognition/tool_head/entity.rs b/core/continuum-cognition/src/cognition/tool_head/entity.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_head/entity.rs rename to core/continuum-cognition/src/cognition/tool_head/entity.rs diff --git a/core/continuum-mind/src/cognition/tool_head/mod.rs b/core/continuum-cognition/src/cognition/tool_head/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_head/mod.rs rename to core/continuum-cognition/src/cognition/tool_head/mod.rs diff --git a/core/continuum-mind/src/cognition/tool_head/tests.rs b/core/continuum-cognition/src/cognition/tool_head/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_head/tests.rs rename to core/continuum-cognition/src/cognition/tool_head/tests.rs diff --git a/core/continuum-mind/src/cognition/tool_surface.rs b/core/continuum-cognition/src/cognition/tool_surface.rs similarity index 100% rename from core/continuum-mind/src/cognition/tool_surface.rs rename to core/continuum-cognition/src/cognition/tool_surface.rs diff --git a/core/continuum-mind/src/persona/trace.rs b/core/continuum-cognition/src/cognition/trace.rs similarity index 99% rename from core/continuum-mind/src/persona/trace.rs rename to core/continuum-cognition/src/cognition/trace.rs index 21f8600dfd..59f0646ab8 100644 --- a/core/continuum-mind/src/persona/trace.rs +++ b/core/continuum-cognition/src/cognition/trace.rs @@ -50,7 +50,7 @@ pub const SEAM_PROMPT_ASSEMBLY: &str = "prompt_assembly"; pub const SEAM_INFERENCE: &str = "inference"; pub const SEAM_POST_PROCESS: &str = "post_process"; /// Admission gate seam — emitted by the IsMemorable Recipe pipeline -/// (see `persona::admission`). Metadata records the recipe id, structural +/// (see `cognition::admission`). Metadata records the recipe id, structural /// outcome (`accepted` / `rejected_`), and final decision label. pub const SEAM_ADMISSION: &str = "admission"; diff --git a/core/continuum-cognition/src/cognition/training_sources.rs b/core/continuum-cognition/src/cognition/training_sources.rs new file mode 100644 index 0000000000..9f36d58f5e --- /dev/null +++ b/core/continuum-cognition/src/cognition/training_sources.rs @@ -0,0 +1,38 @@ +//! The training buckets and example sources cognition judges by: the speech-discipline +//! trait (its gym lives in `cognition::gym`) and the `source` values an example carries +//! when no card produced it (read by `cognition::held_out`). Persona's training producer +//! writes them; one owner, below both. + +/// THE GATE BECOMES A LESSON (card 657e74de; Joel: "ideally they learn too"). Every +/// echo shape gated at the Speak seam (`framing_echo`, `not_speech`) returns a Pass +/// the citizen never sees — the substrate silences her and she learns nothing, so +/// the same tier produces the same echo next turn. The corpus is `{prompt, +/// completion}` SFT only (no chosen/rejected schema), so a gate verdict cannot be a +/// NEGATIVE; but for the echo class the correct completion IS known and fits the +/// schema: the silence token. This is the one place a gate verdict turns into an +/// example. +/// +/// Rules that keep this from teaching muteness, each load-bearing: +/// - only an UNDIRECTED, LIVED turn (the caller checks): a directed question must +/// never train `PASS`, and a synthetic burst is not experience; +/// - its own bucket, [`SPEECH_DISCIPLINE_TRAIT`], never the conversation domain, so +/// no chat gene's set is diluted with silence; and the bucket's gene is adoptable +/// only through its gym (`docs/genome/speech-discipline.jsonl`), which measures +/// BOTH halves — a quiet burst that must end in silence and a real ask that must +/// be answered — so a gene that learned to pass everything fails the gym and is +/// never paged in ([[fallbacks-are-illegal-fail-loud]]); +/// - `quality = 1.0`: a curated domain with its own floor — a 4-char completion +/// scores below `MIN_TRAINING_QUALITY` by construction, and the chat score was +/// built for a different shape. +pub const SPEECH_DISCIPLINE_TRAIT: &str = "speech-discipline"; + +/// The `source` an example carries when no card produced it: a received lesson or a gated +/// echo. ONE list, written by persona's training producers and read by the held-out judge +/// (`cognition::held_out::trained`), where it is the explicit record that such an example +/// worked no graded task (goal 8). It is the value already on the wire, so a replayed +/// submission keeps its exact bytes. +pub const RECEIVED_LESSON_SOURCE: &str = "received-lesson"; + +pub const SPEECH_DISCIPLINE_SOURCE: &str = "speech-discipline"; + +pub const UNLINKED_SOURCES: [&str; 2] = [RECEIVED_LESSON_SOURCE, SPEECH_DISCIPLINE_SOURCE]; diff --git a/core/continuum-mind/src/cognition/turn_batch.rs b/core/continuum-cognition/src/cognition/turn_batch.rs similarity index 100% rename from core/continuum-mind/src/cognition/turn_batch.rs rename to core/continuum-cognition/src/cognition/turn_batch.rs diff --git a/core/continuum-mind/src/cognition/turn_ingress.rs b/core/continuum-cognition/src/cognition/turn_ingress.rs similarity index 100% rename from core/continuum-mind/src/cognition/turn_ingress.rs rename to core/continuum-cognition/src/cognition/turn_ingress.rs diff --git a/core/continuum-mind/src/cognition/turn_ledger.rs b/core/continuum-cognition/src/cognition/turn_ledger.rs similarity index 98% rename from core/continuum-mind/src/cognition/turn_ledger.rs rename to core/continuum-cognition/src/cognition/turn_ledger.rs index 28cd5e0a80..d63532759c 100644 --- a/core/continuum-mind/src/cognition/turn_ledger.rs +++ b/core/continuum-cognition/src/cognition/turn_ledger.rs @@ -49,7 +49,7 @@ impl TurnShape { /// Fold one finished turn in: its duration, and the gap since the previous start /// (`None` for her first). An EMA with a 1/4 step — a few turns to settle, one /// slow turn never the whole story; the first sample of either is taken whole. - pub(crate) fn observe(self, turn_ms: u64, gap_ms: Option) -> Self { + pub fn observe(self, turn_ms: u64, gap_ms: Option) -> Self { let ema = |old: u64, new: u64| if old == 0 { new } else { old - old / 4 + new / 4 }; Self { turn_ms: if self.turns == 0 { turn_ms } else { ema(self.turn_ms, turn_ms) }, @@ -72,13 +72,13 @@ pub(super) static IN_FLIGHT: std::sync::LazyLock, } -pub(crate) fn begin_turn(persona: uuid::Uuid, now_ms: u64) -> TurnInFlight { +pub fn begin_turn(persona: uuid::Uuid, now_ms: u64) -> TurnInFlight { let previous_start_ms = LAST_TURN_MS.lock().insert(persona, now_ms); IN_FLIGHT.lock().insert(persona); TurnInFlight { persona, started: std::time::Instant::now(), previous_start_ms } diff --git a/core/continuum-mind/src/cognition/types.rs b/core/continuum-cognition/src/cognition/types.rs similarity index 100% rename from core/continuum-mind/src/cognition/types.rs rename to core/continuum-cognition/src/cognition/types.rs diff --git a/core/continuum-mind/src/cognition/validate_response.rs b/core/continuum-cognition/src/cognition/validate_response.rs similarity index 100% rename from core/continuum-mind/src/cognition/validate_response.rs rename to core/continuum-cognition/src/cognition/validate_response.rs diff --git a/core/continuum-mind/src/cognition/vision_describe.rs b/core/continuum-cognition/src/cognition/vision_describe.rs similarity index 100% rename from core/continuum-mind/src/cognition/vision_describe.rs rename to core/continuum-cognition/src/cognition/vision_describe.rs diff --git a/core/continuum-mind/src/cognition/vision_gym.rs b/core/continuum-cognition/src/cognition/vision_gym.rs similarity index 100% rename from core/continuum-mind/src/cognition/vision_gym.rs rename to core/continuum-cognition/src/cognition/vision_gym.rs diff --git a/core/continuum-mind/src/cognition/vitals_pulse.rs b/core/continuum-cognition/src/cognition/vitals_pulse.rs similarity index 100% rename from core/continuum-mind/src/cognition/vitals_pulse.rs rename to core/continuum-cognition/src/cognition/vitals_pulse.rs diff --git a/core/continuum-mind/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory.rs rename to core/continuum-cognition/src/cognition/working_memory.rs diff --git a/core/continuum-mind/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/action_log.rs rename to core/continuum-cognition/src/cognition/working_memory/action_log.rs diff --git a/core/continuum-mind/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs similarity index 99% rename from core/continuum-mind/src/cognition/working_memory/continuity.rs rename to core/continuum-cognition/src/cognition/working_memory/continuity.rs index 67acae6464..5525ee67ed 100644 --- a/core/continuum-mind/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -30,7 +30,7 @@ impl WorkingMemory { /// A source-owned expansion reference remains required while its full detail /// competes with history. Both share the same key and turn lifetime. - pub(crate) fn pin_expandable_fact(&self, key: &str, reference: &str, detail: Option) { + pub fn pin_expandable_fact(&self, key: &str, reference: &str, detail: Option) { self.pin_notice(key, reference, 1, detail); } diff --git a/core/continuum-mind/src/cognition/working_memory/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/faculty.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/faculty.rs rename to core/continuum-cognition/src/cognition/working_memory/faculty.rs diff --git a/core/continuum-mind/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/ledger.rs rename to core/continuum-cognition/src/cognition/working_memory/ledger.rs diff --git a/core/continuum-mind/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/perception.rs rename to core/continuum-cognition/src/cognition/working_memory/perception.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/action_log.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/actions.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/actions.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/custody.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/custody.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/faculty.rs b/core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/faculty.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/faculty.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/mod.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/mod.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/open_views.rs b/core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/open_views.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/open_views.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/pins.rs b/core/continuum-cognition/src/cognition/working_memory/tests/pins.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/pins.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/pins.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/provenance.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/rebuilt_marker.rs b/core/continuum-cognition/src/cognition/working_memory/tests/rebuilt_marker.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/rebuilt_marker.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/rebuilt_marker.rs diff --git a/core/continuum-mind/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_memory/tests/trail.rs rename to core/continuum-cognition/src/cognition/working_memory/tests/trail.rs diff --git a/core/continuum-mind/src/cognition/working_set.rs b/core/continuum-cognition/src/cognition/working_set.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_set.rs rename to core/continuum-cognition/src/cognition/working_set.rs diff --git a/core/continuum-mind/src/cognition/working_set/tests.rs b/core/continuum-cognition/src/cognition/working_set/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/working_set/tests.rs rename to core/continuum-cognition/src/cognition/working_set/tests.rs diff --git a/core/continuum-mind/src/cognition/workspace.rs b/core/continuum-cognition/src/cognition/workspace.rs similarity index 100% rename from core/continuum-mind/src/cognition/workspace.rs rename to core/continuum-cognition/src/cognition/workspace.rs diff --git a/core/continuum-mind/src/cognition/workspace/arbiter.rs b/core/continuum-cognition/src/cognition/workspace/arbiter.rs similarity index 97% rename from core/continuum-mind/src/cognition/workspace/arbiter.rs rename to core/continuum-cognition/src/cognition/workspace/arbiter.rs index 0b5ebafba9..b054daaf48 100644 --- a/core/continuum-mind/src/cognition/workspace/arbiter.rs +++ b/core/continuum-cognition/src/cognition/workspace/arbiter.rs @@ -153,7 +153,7 @@ pub struct WorkspaceTrace { pub cause: Cause, pub world_state: String, /// Supplemental inputs admitted before this tick; shared with the live burst. - pub room_updates: Arc>>, + pub room_updates: Arc>>, /// The room/context this tick reasoned within (contextId) — so a replayed /// trace correlates to the room it happened in, not a floating burst. pub room_id: Uuid, @@ -211,7 +211,7 @@ pub struct ActingBody { /// The hippocampus the action's RESULT is admitted into as an Episodic /// engram — so the outcome becomes a thing the mind remembers and can be /// reminded of next tick, the same way it carries every other fact. - pub admission: Arc, + pub admission: Arc, /// The volatile working-memory scratchpad the organism records each act into /// (proprioception). Distinct from `admission` (long-term, content-deduped): an /// act must be perceptible NEXT tick even when its result is a dedup no-op in @@ -320,9 +320,9 @@ pub struct WorkspaceCycle { /// restore. All `Option` so a pure-cognition cycle (no hands) yields a benign /// no-op guard. Not `Clone` — the restore must happen exactly once, on drop. pub struct EvalIsolation { - pub(super) admission: Option>, - pub(super) checkpoint: Option, - pub(super) real_sink: Option>, + pub(super) admission: Option>, + pub(super) checkpoint: Option, + pub(super) real_sink: Option>, /// The shared decoding handle the guard forced to greedy on creation — restored /// to relaxed (`None`) on drop. Carried even for a no-hands (pure-cognition) /// cycle, because a reproducible metric needs deterministic generation whether diff --git a/core/continuum-mind/src/cognition/workspace/capacity.rs b/core/continuum-cognition/src/cognition/workspace/capacity.rs similarity index 99% rename from core/continuum-mind/src/cognition/workspace/capacity.rs rename to core/continuum-cognition/src/cognition/workspace/capacity.rs index 58b0e913e4..beb31e7fb5 100644 --- a/core/continuum-mind/src/cognition/workspace/capacity.rs +++ b/core/continuum-cognition/src/cognition/workspace/capacity.rs @@ -40,7 +40,7 @@ impl From for CapacityRefusal { /// One park and one disposition per refusal, shared across settlement projections. /// Readiness checks emit nothing; these receipts describe actual custody transitions. impl CapacityRefusal { - pub(crate) fn note_transition(&self, persona: Option, room: uuid::Uuid, + pub fn note_transition(&self, persona: Option, room: uuid::Uuid, phase: &'static str, reason: &'static str) -> bool { let bit = if phase == "parked" { 1 } else { 2 }; if self.receipt_state.fetch_or(bit, std::sync::atomic::Ordering::Relaxed) & bit != 0 { diff --git a/core/continuum-mind/src/cognition/workspace/cause.rs b/core/continuum-cognition/src/cognition/workspace/cause.rs similarity index 99% rename from core/continuum-mind/src/cognition/workspace/cause.rs rename to core/continuum-cognition/src/cognition/workspace/cause.rs index 1dec6dc7cd..e6873f9510 100644 --- a/core/continuum-mind/src/cognition/workspace/cause.rs +++ b/core/continuum-cognition/src/cognition/workspace/cause.rs @@ -316,7 +316,7 @@ impl TurnFraming { #[derive(Debug, Clone)] pub struct Workspace { /// Additional room inputs; the active turn's room and task remain separate. - pub room_updates: Arc>>, + pub room_updates: Arc>>, /// The consolidated burst / world-state at service time, as flat text — the /// rendered projection of [`turns`](Self::turns). Opaque to the core; the /// channel/recipe adapter shapes it. Every TEXT reader (recall, dashboards, diff --git a/core/continuum-mind/src/cognition/workspace/edit.rs b/core/continuum-cognition/src/cognition/workspace/edit.rs similarity index 99% rename from core/continuum-mind/src/cognition/workspace/edit.rs rename to core/continuum-cognition/src/cognition/workspace/edit.rs index 7c708c287c..21c5d258ab 100644 --- a/core/continuum-mind/src/cognition/workspace/edit.rs +++ b/core/continuum-cognition/src/cognition/workspace/edit.rs @@ -696,7 +696,7 @@ pub struct Burst { /// the conversation's retained attention queue; never replace this burst's /// task, room, or causal root. This is the existing chat projection, not a /// replacement for the multimodal sensory faculties. - pub room_updates: Arc>>, + pub room_updates: Arc>>, /// The activity this turn belongs to — REQUIRED at construction, witnessed /// non-nil by [`ActivityRoom`]. The burst carries the room because the burst /// IS the perception the turn responds to: when the room rode as a separate diff --git a/core/continuum-mind/src/cognition/workspace/genome_restore.rs b/core/continuum-cognition/src/cognition/workspace/genome_restore.rs similarity index 100% rename from core/continuum-mind/src/cognition/workspace/genome_restore.rs rename to core/continuum-cognition/src/cognition/workspace/genome_restore.rs diff --git a/core/continuum-mind/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs similarity index 100% rename from core/continuum-mind/src/cognition/workspace/tests.rs rename to core/continuum-cognition/src/cognition/workspace/tests.rs diff --git a/core/continuum-mind/src/cognition/workspace/workspace_cycle.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs similarity index 99% rename from core/continuum-mind/src/cognition/workspace/workspace_cycle.rs rename to core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs index fe95df112d..18ca42af9a 100644 --- a/core/continuum-mind/src/cognition/workspace/workspace_cycle.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs @@ -376,7 +376,7 @@ impl WorkspaceCycle { let admission = acting.admission.clone(); let checkpoint = admission.checkpoint(); let real_sink = - admission.swap_persistence(crate::persona::admission_persistence::NoopSink::arc()); + admission.swap_persistence(crate::cognition::admission_persistence::NoopSink::arc()); EvalIsolation { admission: Some(admission), checkpoint: Some(checkpoint), @@ -436,7 +436,7 @@ impl WorkspaceCycle { /// under `#[cfg(test)]`), so even faculty-isolation ticks run in a /// real-shaped room. Production has no roomless ticks (#425) — live callers /// use [`run_framed`](Self::run_framed) / [`run_situated`](Self::run_situated). - #[cfg(test)] + #[cfg(any(test, feature = "test-fixtures"))] pub async fn run(&self, burst: impl Into) -> Workspace { self.run_inner( burst.into(), diff --git a/core/continuum-mind/src/cognition/workspace/workspace_cycle_2.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs similarity index 100% rename from core/continuum-mind/src/cognition/workspace/workspace_cycle_2.rs rename to core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs diff --git a/core/continuum-mind/src/cognition/workspace_capture.rs b/core/continuum-cognition/src/cognition/workspace_capture.rs similarity index 99% rename from core/continuum-mind/src/cognition/workspace_capture.rs rename to core/continuum-cognition/src/cognition/workspace_capture.rs index 958421845e..e595c8cca2 100644 --- a/core/continuum-mind/src/cognition/workspace_capture.rs +++ b/core/continuum-cognition/src/cognition/workspace_capture.rs @@ -125,7 +125,7 @@ struct WorkspaceTraceRecord<'a> { /// The consolidated burst the mind reasoned over this tick. world_state: &'a str, #[serde(skip_serializing_if = "Vec::is_empty")] - room_updates: Vec<&'a crate::persona::service_loop::IncomingMessage>, + room_updates: Vec<&'a crate::cognition::conversation::IncomingMessage>, /// EVERY bid this tick (winners + losers, both phases) — the full competition. bids: Vec>, /// The assembled context that won attention and reached the decider (the RAG). diff --git a/core/continuum-cognition/src/lib.rs b/core/continuum-cognition/src/lib.rs new file mode 100644 index 0000000000..54abd602cc --- /dev/null +++ b/core/continuum-cognition/src/lib.rs @@ -0,0 +1,14 @@ +//! continuum-cognition: a mind's thinking, cut out of continuum-mind below persona +//! (MODULE-ARCHITECTURE.md section 9.2). It depends on the live crate (which carries the engine +//! and the kernel), the hands, and the crates cut out of the mind before it: perception (and +//! rag), genome, memory and experience (and recipe), re-exported here under their old paths so +//! every `crate::` path inside cognition resolves. continuum-mind re-exports `cognition`. + +pub use continuum_hands::code; +pub use continuum_live::*; +pub use continuum_genome::genome; +pub use continuum_memory::memory; +pub use continuum_experience::{experience, recipe}; +pub use continuum_perception::{perception, rag}; + +pub mod cognition; diff --git a/core/continuum-core/Cargo.toml b/core/continuum-core/Cargo.toml index 3cc5e19ecf..1ad996f352 100644 --- a/core/continuum-core/Cargo.toml +++ b/core/continuum-core/Cargo.toml @@ -455,6 +455,7 @@ continuum-live = { path = "../continuum-live", features = ["test-fixtures"] } continuum-mind = { path = "../continuum-mind", features = ["test-fixtures"] } continuum-genome = { path = "../continuum-genome", features = ["test-fixtures"] } continuum-experience = { path = "../continuum-experience", features = ["test-fixtures"] } +continuum-cognition = { path = "../continuum-cognition", features = ["test-fixtures"] } continuum-positron = { path = "../continuum-positron", features = ["test-fixtures"] } # The hygiene ratchets moved to their own std-only crate so a contributor learns an # unwrap count rose in seconds instead of after a 12.4-minute build. Two `#[cfg(test)]` diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index bdd9c849bf..25b6f76ba9 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -15,7 +15,7 @@ use airc_lib::decode_wire_event; use tracing::warn; use crate::routing::airc_realtime::AircRealtimeEnvelope; -use crate::persona::room_event::chat_transcript_message; +use crate::cognition::conversation::room_event::chat_transcript_message; use crate::routing::airc_realtime_wire::{bus_event_from_envelope, envelope_from_event}; use crate::ipc::positron_kanban_source::KANBAN_CHANGED; use crate::ipc::positron_source::CHAT_POSTED; diff --git a/core/continuum-core/src/commands/chat/send.rs b/core/continuum-core/src/commands/chat/send.rs index 89cba008af..6613379db1 100644 --- a/core/continuum-core/src/commands/chat/send.rs +++ b/core/continuum-core/src/commands/chat/send.rs @@ -195,7 +195,7 @@ async fn publish_as_sender( ).await.map(|_| ()).map_err(|e| e.to_string()); } let envelope: crate::routing::airc_realtime::AircRealtimeEnvelope = serde_json::from_value( - crate::persona::room_event::chat_transcript_envelope( + crate::cognition::conversation::room_event::chat_transcript_envelope( message_id, ¶ms.transcript_line(), EpochMs::now().millis(), diff --git a/core/continuum-core/src/commands/cognition/admit_inbox_message.rs b/core/continuum-core/src/commands/cognition/admit_inbox_message.rs index 1eeafafde8..9206b18deb 100644 --- a/core/continuum-core/src/commands/cognition/admit_inbox_message.rs +++ b/core/continuum-core/src/commands/cognition/admit_inbox_message.rs @@ -2,15 +2,15 @@ //! message (typed, dep-holding). //! //! Converts the JSON-transport [`InboxMessageRequest`](crate::ipc::InboxMessageRequest) -//! to the domain [`InboxMessage`](crate::persona::InboxMessage) via the one canonical +//! to the domain [`InboxMessage`](crate::cognition::conversation::types::InboxMessage) via the one canonical //! `to_inbox_message()` seam, then runs the persona's admission gate -//! ([`admit`](crate::persona::admission_state)) — recording side-effects (admitted +//! ([`admit`](crate::cognition::admission_state)) — recording side-effects (admitted //! engram → store, content_hash → dedup, AIRC event_id → replay-protection). Returns -//! the typed [`AdmissionDecision`](crate::persona::AdmissionDecision) plus funnel +//! the typed [`AdmissionDecision`](crate::cognition::engram::AdmissionDecision) plus funnel //! telemetry (engram count, trace seam count). Captures the owning module's //! [`CognitionState`](crate::modules::cognition::CognitionState). //! -//! A [`CognitionTrace`](crate::persona::trace::CognitionTrace) is built and threaded +//! A [`CognitionTrace`](crate::cognition::trace::CognitionTrace) is built and threaded //! through so the seam count comes back in the response (the TS/IPC caller surfaces //! admission-funnel telemetry). Read-only persona lookup: fails loud with `NotFound` //! when the persona has no cognition engine (created via `cognition/create-engine`). @@ -23,8 +23,8 @@ use uuid::Uuid; use crate::ipc::InboxMessageRequest; use crate::modules::cognition::CognitionState; -use crate::persona::trace::CognitionTrace; -use crate::persona::AdmissionDecision; +use crate::cognition::trace::CognitionTrace; +use crate::cognition::engram::AdmissionDecision; use crate::sdk_codegen::CommandError; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] diff --git a/core/continuum-core/src/commands/cognition/enqueue_message.rs b/core/continuum-core/src/commands/cognition/enqueue_message.rs index 4cfbd612fc..fd818e6a28 100644 --- a/core/continuum-core/src/commands/cognition/enqueue_message.rs +++ b/core/continuum-core/src/commands/cognition/enqueue_message.rs @@ -2,7 +2,7 @@ //! (typed, dep-holding). //! //! Takes the JSON-transport [`InboxMessageRequest`](crate::ipc::InboxMessageRequest), -//! converts it to the domain [`InboxMessage`](crate::persona::InboxMessage) via the one +//! 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. //! Captures the owning module's [`CognitionState`](crate::modules::cognition::CognitionState). //! diff --git a/core/continuum-core/src/commands/cognition/get_state.rs b/core/continuum-core/src/commands/cognition/get_state.rs index 8733ffd888..c951bc79f1 100644 --- a/core/continuum-core/src/commands/cognition/get_state.rs +++ b/core/continuum-core/src/commands/cognition/get_state.rs @@ -1,8 +1,8 @@ //! `cognition/get-state` — read a persona's live cognitive state (typed, dep-holding). //! -//! Projects the persona's [`PersonaState`](crate::persona::PersonaState) (energy, +//! Projects the persona's [`PersonaState`](crate::cognition::conversation::types::PersonaState) (energy, //! attention, mood, inbox load, budget) plus the derived adaptive -//! [`service_cadence_ms`](crate::persona::PersonaState::service_cadence_ms) into one +//! [`service_cadence_ms`](crate::cognition::conversation::types::PersonaState::service_cadence_ms) into one //! camelCase wire result. Read-only: fails loud with `NotFound` when the persona has no //! cognition engine (never lazily creates one on a read). Captures the owning module's //! [`CognitionState`](crate::modules::cognition::CognitionState). @@ -14,7 +14,7 @@ use std::sync::Arc; use uuid::Uuid; use crate::modules::cognition::CognitionState; -use crate::persona::Mood; +use crate::cognition::conversation::types::Mood; use crate::sdk_codegen::CommandError; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS, schemars::JsonSchema)] @@ -30,7 +30,7 @@ pub struct GetStateParams { } /// The persona's live cognitive state — a camelCase projection of -/// [`PersonaState`](crate::persona::PersonaState) plus the derived service cadence. +/// [`PersonaState`](crate::cognition::conversation::types::PersonaState) plus the derived service cadence. #[derive(Debug, Clone, serde::Serialize, ts_rs::TS)] #[ts( export, diff --git a/core/continuum-core/src/commands/cognition/recall_engrams.rs b/core/continuum-core/src/commands/cognition/recall_engrams.rs index d9825fa005..fc68df6d45 100644 --- a/core/continuum-core/src/commands/cognition/recall_engrams.rs +++ b/core/continuum-core/src/commands/cognition/recall_engrams.rs @@ -19,7 +19,8 @@ use std::sync::Arc; use uuid::Uuid; use crate::modules::cognition::CognitionState; -use crate::persona::{Engram, EngramOriginKind}; +use crate::cognition::engram::Engram; +use crate::cognition::admission_state::EngramOriginKind; use crate::sdk_codegen::CommandError; fn default_kind() -> String { diff --git a/core/continuum-core/src/commands/focus/continue_.rs b/core/continuum-core/src/commands/focus/continue_.rs index b0b4e9bc3d..5078d3eadc 100644 --- a/core/continuum-core/src/commands/focus/continue_.rs +++ b/core/continuum-core/src/commands/focus/continue_.rs @@ -16,8 +16,8 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; use ts_rs::TS; -use crate::persona::attention::Continuation; -use crate::persona::salience::{Expectation, ExpectedVerdict}; +use crate::cognition::attention::Continuation; +use crate::cognition::conversation::salience::{Expectation, ExpectedVerdict}; use crate::routing::CallerSource; use crate::sdk_codegen::{ActionCommand, CommandError, Ctx}; @@ -119,7 +119,7 @@ impl ActionCommand for FocusContinue { // "room is required" (2026-10-05 04:42Z): a room she is standing in is not // something to make her spell out. let activity = if p.private { - crate::persona::mind_room::mind_room_id(persona) + crate::cognition::mind_room::mind_room_id(persona) } else if p.room.trim().is_empty() { ctx.context_id.filter(|id| !id.is_nil()).ok_or_else(|| { CommandError::Invalid( @@ -150,8 +150,8 @@ impl ActionCommand for FocusContinue { saved.map_err(|e| CommandError::Internal(format!("your continuation was set but could not be saved: {e}")))?; // A private continuation is sealed in her mind store (sink 10), never in // mind-state.json; an open one, or a clear, removes any sealed one left behind. - let private = continuation.as_ref().filter(|c| crate::persona::mind_room::is_private_room(persona, c.activity)); - crate::persona::mind_room::seal_continuation(persona, private) + let private = continuation.as_ref().filter(|c| crate::cognition::mind_room::is_private_room(persona, c.activity)); + crate::persona::mind_store::seal_continuation(persona, private) .map_err(|e| CommandError::Internal(format!("your private continuation could not be sealed: {e}")))?; Ok(FocusContinueResult { held, wakes_at_ms }) diff --git a/core/continuum-core/src/commands/genome/job_create.rs b/core/continuum-core/src/commands/genome/job_create.rs index e2ce195f4c..97e3fbf529 100644 --- a/core/continuum-core/src/commands/genome/job_create.rs +++ b/core/continuum-core/src/commands/genome/job_create.rs @@ -315,7 +315,7 @@ crate::action_command! { .dataset_name .clone() .unwrap_or_else(|| format!("inline:{}", p.request.trait_kind)), // inline datasets have no on-disk name; the trait names the mint - content_hash: crate::persona::inbox_admission::content_hash_sha256(&joined), + content_hash: crate::cognition::inbox_admission::content_hash_sha256(&joined), size_bytes: joined.len() as u64, source_url: None, }; diff --git a/core/continuum-core/src/commands/genome/job_create/tests.rs b/core/continuum-core/src/commands/genome/job_create/tests.rs index 117923c611..754de84dda 100644 --- a/core/continuum-core/src/commands/genome/job_create/tests.rs +++ b/core/continuum-core/src/commands/genome/job_create/tests.rs @@ -219,9 +219,9 @@ // same world with no region (never judged) reuses, since not measured is not low. #[tokio::test] async fn the_decision_itself_holds_an_unsurprised_mind_and_trains_a_never_judged_one() { - use crate::persona::attention::{AttentionDial, Continuation}; + use crate::cognition::attention::{AttentionDial, Continuation}; use crate::persona::perception_region::PerceptionRegion; - use crate::persona::salience::{BoardChange, Expectation, ExpectedVerdict, ObservedVerdict}; + use crate::cognition::conversation::salience::{BoardChange, Expectation, ExpectedVerdict, ObservedVerdict}; use std::sync::{Arc as StdArc, Mutex}; let w = decision_world().await; let activity = uuid::Uuid::new_v4(); diff --git a/core/continuum-core/src/commands/genome/teach/bridge.rs b/core/continuum-core/src/commands/genome/teach/bridge.rs index 253be9b526..d460d86961 100644 --- a/core/continuum-core/src/commands/genome/teach/bridge.rs +++ b/core/continuum-core/src/commands/genome/teach/bridge.rs @@ -16,7 +16,7 @@ use crate::genome::training_outcome::SubmitOutcome; use crate::genome::fine_tuning::{TrainingDataset, TrainingSource}; use crate::identity::PersonaRef; use crate::modules::dataset::{CandidateReservation, DatasetCandidate, DatasetService}; -use crate::persona::inbox_admission::content_hash_sha256; +use crate::cognition::inbox_admission::content_hash_sha256; use crate::runtime::InProcessTransport; use crate::sdk_codegen::{CommandError, Ctx}; diff --git a/core/continuum-core/src/commands/persona/reassign_model.rs b/core/continuum-core/src/commands/persona/reassign_model.rs index a7f9e71276..83caa967df 100644 --- a/core/continuum-core/src/commands/persona/reassign_model.rs +++ b/core/continuum-core/src/commands/persona/reassign_model.rs @@ -53,7 +53,7 @@ use ts_rs::TS; use crate::identity::citizen_path::citizen_home_path; use crate::identity::IdentityKind; -use crate::persona::home::PersonaHome; +use crate::cognition::home::PersonaHome; use crate::persona::PersonaModelOverride; use crate::runtime::{CommandExecutor, LateBound}; use crate::sdk_codegen::CommandError; diff --git a/core/continuum-core/src/commands/persona/turn_frame/execute.rs b/core/continuum-core/src/commands/persona/turn_frame/execute.rs index a4ab600f78..32173a5590 100644 --- a/core/continuum-core/src/commands/persona/turn_frame/execute.rs +++ b/core/continuum-core/src/commands/persona/turn_frame/execute.rs @@ -217,7 +217,7 @@ crate::action_command! { .unwrap_or_default(); let burst = crate::cognition::workspace::Burst::from_turns( room, - crate::persona::service_loop::build_workspace_turns( + crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&delivery), &own_peer, &agent_name, @@ -334,7 +334,8 @@ mod tests { use super::*; use crate::cognition::act_observe::SettleStep; use crate::cognition::workspace::TurnMetrics; - use crate::persona::{InboxMessage, Modality, PersonaCognition, SenderType}; + use crate::persona::PersonaCognition; + use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::rag::RagEngine; use crate::sdk_codegen::{AccessLevel, ActionCommand, Ctx}; diff --git a/core/continuum-core/src/commands/training_trigger/submit/tests/a_large_return_is_cut_into_threshold_chunks_with_derived_replayable_ids.rs b/core/continuum-core/src/commands/training_trigger/submit/tests/a_large_return_is_cut_into_threshold_chunks_with_derived_replayable_ids.rs index 047c33d5fd..10c2cde18c 100644 --- a/core/continuum-core/src/commands/training_trigger/submit/tests/a_large_return_is_cut_into_threshold_chunks_with_derived_replayable_ids.rs +++ b/core/continuum-core/src/commands/training_trigger/submit/tests/a_large_return_is_cut_into_threshold_chunks_with_derived_replayable_ids.rs @@ -415,9 +415,9 @@ use super::*; // over the floor and the next fill dispatches. A mind never judged is not held. #[tokio::test] pub(super) async fn a_fill_while_her_expectations_hold_is_held_and_a_contradiction_releases_it() { - use crate::persona::attention::{AttentionDial, Continuation}; + use crate::cognition::attention::{AttentionDial, Continuation}; use crate::persona::perception_region::PerceptionRegion; - use crate::persona::salience::{BoardChange, Expectation, ExpectedVerdict, ObservedVerdict}; + use crate::cognition::conversation::salience::{BoardChange, Expectation, ExpectedVerdict, ObservedVerdict}; use std::sync::{Arc, Mutex}; let (trigger, executor, _dir) = build_runtime_with_trigger_and_genome().await; let persona = Uuid::new_v4(); diff --git a/core/continuum-core/src/ipc/mod.rs b/core/continuum-core/src/ipc/mod.rs index c8f09faa39..a689226649 100644 --- a/core/continuum-core/src/ipc/mod.rs +++ b/core/continuum-core/src/ipc/mod.rs @@ -39,7 +39,8 @@ use crate::modules::vision::VisionModule; /// - JSON protocol (JTAGRequest/JTAGResponse) /// - Performance timing on every request /// - Modular runtime routes commands through ServiceModule trait (Phase 1+) -use crate::persona::{ChannelRegistry, PersonaState}; +use crate::persona::ChannelRegistry; +use crate::cognition::conversation::types::PersonaState; use crate::rag::RagEngine; use crate::runtime::{CommandResult, Runtime}; use crate::system_resources::SystemResourceMonitor; diff --git a/core/continuum-core/src/ipc/positron_kanban_source.rs b/core/continuum-core/src/ipc/positron_kanban_source.rs index 2005cbb80e..03421f4695 100644 --- a/core/continuum-core/src/ipc/positron_kanban_source.rs +++ b/core/continuum-core/src/ipc/positron_kanban_source.rs @@ -173,8 +173,8 @@ fn map_lane_state(state: LaneState) -> KanbanLaneState { } } -fn map_hold(hold: crate::persona::card_holder::Hold) -> KanbanHold { - use crate::persona::card_holder::Hold; +fn map_hold(hold: crate::cognition::card_holder::Hold) -> KanbanHold { + use crate::cognition::card_holder::Hold; match hold { Hold::Held => KanbanHold::Held, Hold::Lapsed => KanbanHold::Lapsed, @@ -296,7 +296,7 @@ impl KanbanProjection { // boundary crossing mid-projection must not make one card claim a // different "now" than the predicate that judged it. Cheap, and // the projection is not a hot path. - hold: map_hold(crate::persona::card_holder::hold_of(card, continuum_base::time::EpochMs::now().millis())), + hold: map_hold(crate::cognition::card_holder::hold_of(card, continuum_base::time::EpochMs::now().millis())), pull_request: card.pull_request.as_ref().map(|pr| KanbanPullRequest { repo: pr.repo.to_string(), number: pr.number, diff --git a/core/continuum-core/src/ipc/protocol.rs b/core/continuum-core/src/ipc/protocol.rs index 3e33d0de68..1e9f47012a 100644 --- a/core/continuum-core/src/ipc/protocol.rs +++ b/core/continuum-core/src/ipc/protocol.rs @@ -36,15 +36,15 @@ pub struct InboxMessageRequest { impl InboxMessageRequest { /// Convert this JSON-transport request (string UUIDs, string enums) into the - /// domain [`InboxMessage`](crate::persona::InboxMessage). The single + /// 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::persona::{InboxMessage, Modality, SenderType}; + 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, diff --git a/core/continuum-core/src/ipc/start_server.rs b/core/continuum-core/src/ipc/start_server.rs index 318c0af8d7..da3dd20b98 100644 --- a/core/continuum-core/src/ipc/start_server.rs +++ b/core/continuum-core/src/ipc/start_server.rs @@ -33,9 +33,10 @@ mod ws_ingress; /// What the kernel's extension slots hold in this process, installed before any executor /// exists: every dispatch runs under the hooks (the hands' admission is a safety boundary), a /// command name resolves through the persona path's vocabulary, and a stop lets admitted turns -/// finish. One list, so boot and a test that dispatches through a real executor install the same. +/// finish. Cognition's slots (the verbs it calls that persona owns) are filled here too. One list, so boot and a test that dispatches through a real executor install the same. pub(crate) fn install_kernel_extensions() { crate::runtime::dispatch_hook::install(Arc::new(crate::code::hands::HandsAdmission)); + crate::persona::cognition_extensions::install(); crate::runtime::dispatch_hook::install(Arc::new(crate::persona::cognition_pulse::CardWorkPulse)); crate::runtime::extensions::install_command_name_resolver(crate::ai::tool_dialect::resolve_wire_name); crate::runtime::extensions::install_settle_before_stop(Arc::new(crate::cognition::turn_ingress::TurnsSettle)); diff --git a/core/continuum-core/src/ipc/start_server/ws_ingress.rs b/core/continuum-core/src/ipc/start_server/ws_ingress.rs index a9f9ae4bff..c9a1bec40f 100644 --- a/core/continuum-core/src/ipc/start_server/ws_ingress.rs +++ b/core/continuum-core/src/ipc/start_server/ws_ingress.rs @@ -83,7 +83,7 @@ pub(super) fn spawn_ws_ingress( // citizen's grounding) reads THAT room instead of whichever room // wrote last. The node substrate above still receives everything, // so the focused-room web session is unchanged. - Some(crate::persona::room_substrates::global_room_substrates()), + Some(crate::cognition::room_substrates::global_room_substrates()), ); // Per-citizen substrates for per-user views (nav): each connecting diff --git a/core/continuum-core/src/ipc/vitals_emitter.rs b/core/continuum-core/src/ipc/vitals_emitter.rs index 5b0ce88e45..002fe42cde 100644 --- a/core/continuum-core/src/ipc/vitals_emitter.rs +++ b/core/continuum-core/src/ipc/vitals_emitter.rs @@ -337,8 +337,8 @@ mod tests { use super::*; use crate::ai::heuristic_adapter::HeuristicInferenceAdapter; use crate::cognition::persona_workspace::{PersonaBrainConfig, PersonaWorkspaceRegistry}; - use crate::persona::admission_state::AdmissionState; - use crate::persona::recall_metadata::RecallMetadataRegistry; + use crate::cognition::admission_state::AdmissionState; + use crate::cognition::recall_metadata::RecallMetadataRegistry; /// A minimal resident persona in a LOCAL registry (never the process /// global), keyed by `peer_id` — the same uuid the spawn path would take diff --git a/core/continuum-core/src/lib.rs b/core/continuum-core/src/lib.rs index 85c5848081..5d0d50651f 100644 --- a/core/continuum-core/src/lib.rs +++ b/core/continuum-core/src/lib.rs @@ -53,10 +53,8 @@ pub(crate) mod test_env; pub use continuum_kernel::concurrency::*; pub use live::VoiceOrchestrator; -pub use persona::{ - CognitionDecision, InboxMessage, InboxTask, Modality, Mood, PersonaCognitionEngine, - PersonaInbox, PersonaState, PriorityScore, QueueItem, SenderType, -}; +pub use cognition::conversation::types::{InboxMessage, InboxTask, Modality, Mood, PersonaState, QueueItem, SenderType}; +pub use persona::{CognitionDecision, PersonaCognitionEngine, PersonaInbox, PriorityScore}; // Easy logging macros - auto-route to proper log files based on module_path!() // Usage: clog_info!("Session started"); clog_warn!("Warning"); etc. pub use ipc::start_server; diff --git a/core/continuum-core/src/modules/channel.rs b/core/continuum-core/src/modules/channel.rs index da5601a801..aa2645ad0a 100644 --- a/core/continuum-core/src/modules/channel.rs +++ b/core/continuum-core/src/modules/channel.rs @@ -12,9 +12,10 @@ //! live surface is the background `tick()` below: per-persona task polling + //! self-task generation, a lifecycle concern, not a command. -use crate::persona::channel_items::TaskQueueItem; +use crate::cognition::conversation::channel_items::TaskQueueItem; use crate::persona::self_task_generator::SelfTaskGenerator; -use crate::persona::{ChannelRegistry, PersonaCognition, PersonaState}; +use crate::persona::{ChannelRegistry, PersonaCognition}; +use crate::cognition::conversation::types::PersonaState; use crate::runtime::{ CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule, }; diff --git a/core/continuum-core/src/modules/chat/chat_data_handle.rs b/core/continuum-core/src/modules/chat/chat_data_handle.rs index 9b4512ca1c..e7c4c44857 100644 --- a/core/continuum-core/src/modules/chat/chat_data_handle.rs +++ b/core/continuum-core/src/modules/chat/chat_data_handle.rs @@ -364,7 +364,7 @@ impl ChatModule { // surface a parse error and the test // `send_envelope_matches_airc_publish_wire_shape` will // catch the drift. - let publish_envelope = crate::persona::room_event::chat_transcript_envelope( + let publish_envelope = crate::cognition::conversation::room_event::chat_transcript_envelope( message_id, ¶ms.transcript_line(), now_ms, diff --git a/core/continuum-core/src/modules/chat/types.rs b/core/continuum-core/src/modules/chat/types.rs index 02f307ac29..294dd01b94 100644 --- a/core/continuum-core/src/modules/chat/types.rs +++ b/core/continuum-core/src/modules/chat/types.rs @@ -141,7 +141,7 @@ pub struct ChatSendParams { /// Media references only; bytes stay in the existing blob store. No fetch or /// vision inference is performed by sending a message. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub media: Vec, + pub media: Vec, /// Optional thread anchor. When set, both the stored message and /// the airc-published envelope carry this as the reply-to link. @@ -152,8 +152,8 @@ pub struct ChatSendParams { impl ChatSendParams { /// This send as the chat-transcript line its envelope carries. - pub fn transcript_line(&self) -> crate::persona::room_event::ChatTranscriptLine<'_> { - crate::persona::room_event::ChatTranscriptLine { + pub fn transcript_line(&self) -> crate::cognition::conversation::room_event::ChatTranscriptLine<'_> { + crate::cognition::conversation::room_event::ChatTranscriptLine { room_id: self.room_id, sender_id: self.sender_id, text: &self.text, diff --git a/core/continuum-core/src/modules/cognition.rs b/core/continuum-core/src/modules/cognition.rs index c29347f34c..a80cb7b5ea 100644 --- a/core/continuum-core/src/modules/cognition.rs +++ b/core/continuum-core/src/modules/cognition.rs @@ -36,7 +36,8 @@ use crate::gpu::GpuMemoryManager; use crate::logging::TimingGuard; use crate::cognition::text_analysis::LoopDetector; -use crate::persona::{InboxMessage, Modality, PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord, SenderType}; +use crate::persona::{PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord}; +use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::rag::RagEngine; use crate::runtime; use crate::runtime::{CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; diff --git a/core/continuum-core/src/modules/dataset/candidate.rs b/core/continuum-core/src/modules/dataset/candidate.rs index e8d58c1d83..9e95e6687c 100644 --- a/core/continuum-core/src/modules/dataset/candidate.rs +++ b/core/continuum-core/src/modules/dataset/candidate.rs @@ -21,7 +21,7 @@ use uuid::Uuid; use super::DatasetService; use crate::commands::training_trigger::submit::SubmitParams; use crate::genome::corpus_ref::CorpusRef; -use crate::persona::inbox_admission::content_hash_sha256; +use crate::cognition::inbox_admission::content_hash_sha256; const SCHEMA_VERSION: u32 = 1; const SUBMISSION_FILE: &str = "submission.json"; diff --git a/core/continuum-core/src/modules/nav.rs b/core/continuum-core/src/modules/nav.rs index d4ad192531..074facedc2 100644 --- a/core/continuum-core/src/modules/nav.rs +++ b/core/continuum-core/src/modules/nav.rs @@ -19,7 +19,7 @@ use ts_rs::TS; use uuid::Uuid; use crate::cognition::channel_substrate::global_channel_digest_buffer; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::persona::PersonaAircRuntimeRegistry; use crate::ipc::positron_nav_source::{global_nav_focus, NAV_CHANGED}; use crate::ipc::positron_source::{AircChatFocused, CHAT_FOCUSED}; diff --git a/core/continuum-core/src/modules/persona_instance_manager.rs b/core/continuum-core/src/modules/persona_instance_manager.rs index 42c2041856..b37a8a482e 100644 --- a/core/continuum-core/src/modules/persona_instance_manager.rs +++ b/core/continuum-core/src/modules/persona_instance_manager.rs @@ -108,7 +108,7 @@ impl ServiceModule for PersonaInstanceManagerService { Err(_) => continue, }; crate::cognition::handoff::note_owned(rt.airc().peer_id().as_uuid(), &owned, now_ms); - let held = crate::persona::airc_runtime::held_of_owned(owned, now_ms); + let held = crate::cognition::card_holder::held_of_owned(owned, now_ms); for (room, card) in held { let Some(claim_id) = card.claim_id else { continue; @@ -120,7 +120,7 @@ impl ServiceModule for PersonaInstanceManagerService { airc_lib::HeartbeatWorkClaim { card_id: card.card_id, claim_id, - ttl_ms: crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms: crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, }, ) .await diff --git a/core/continuum-core/src/modules/persona_rag_inspect.rs b/core/continuum-core/src/modules/persona_rag_inspect.rs index c4e35eeaa7..2353700408 100644 --- a/core/continuum-core/src/modules/persona_rag_inspect.rs +++ b/core/continuum-core/src/modules/persona_rag_inspect.rs @@ -43,7 +43,7 @@ use ts_rs::TS; use uuid::Uuid; use crate::ai::adapter::AIProviderAdapter; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::persona::rag_inspect::{ inspect_persona_rag_with_inference, RagInspection, RagInspectionRequest, }; @@ -468,7 +468,7 @@ pub(crate) async fn inspect_persona( mod tests { use super::*; use crate::commands::persona::rag_inspect::PersonaRagInspect; - use crate::persona::airc_source::AircTranscriptReader; + use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::sdk_codegen::{ActionCommand, Ctx}; use airc_core::{ Body, ClientId, EventId, Headers, MentionTarget, PeerId, RoomId, TranscriptEvent, diff --git a/core/continuum-core/src/modules/persona_rag_inspect_filesystem.rs b/core/continuum-core/src/modules/persona_rag_inspect_filesystem.rs index 5ca2951901..15aad4c024 100644 --- a/core/continuum-core/src/modules/persona_rag_inspect_filesystem.rs +++ b/core/continuum-core/src/modules/persona_rag_inspect_filesystem.rs @@ -47,7 +47,7 @@ use uuid::Uuid; use crate::ai::adapter::AIProviderAdapter; use crate::identity::citizen_path::citizens_kind_dir; use crate::identity::IdentityKind; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::persona::seed::read_seed; use super::persona_rag_inspect::{PersonaResolution, PersonaResolver}; diff --git a/core/continuum-core/src/modules/verdict_board.rs b/core/continuum-core/src/modules/verdict_board.rs index 52543ead69..709b131176 100644 --- a/core/continuum-core/src/modules/verdict_board.rs +++ b/core/continuum-core/src/modules/verdict_board.rs @@ -192,7 +192,7 @@ pub async fn follow_with(verdict: &SweVerdict, mode: FollowMode) -> FollowTally let open_reviews = snap .cards .iter() - .filter(|k| !crate::persona::work_board::facts::is_concluded(&k.state)) + .filter(|k| !crate::cognition::card_facts::is_concluded(&k.state)) .filter_map(|k| k.reviews.map(|parent| (parent.as_uuid(), k.card_id.as_uuid()))) .filter(|(parent, _)| all.contains(parent)) .collect(); @@ -408,7 +408,7 @@ fn holder_label(id: Uuid, alias: Option<&str>, historical: bool) -> String { let name = alias .filter(|name| !name.trim().is_empty()) .map(str::to_owned) - .unwrap_or_else(|| crate::persona::card_holder::short8(&id)); // unwrap_or: unknown identity uses the board's addressable short id + .unwrap_or_else(|| crate::cognition::card_holder::short8(&id)); // unwrap_or: unknown identity uses the board's addressable short id if historical { format!("{name} (dispatch assignee; live board unavailable)") } else { @@ -461,13 +461,13 @@ async fn holder_of( let Some(found) = board.cards.iter().find(|c| c.card_id.as_uuid() == card) else { return HolderRead::Unavailable("card not on the board"); }; - match crate::persona::card_holder::hold_of(found, now_ms) { - crate::persona::card_holder::Hold::Held => match found.owner { + match crate::cognition::card_holder::hold_of(found, now_ms) { + crate::cognition::card_holder::Hold::Held => match found.owner { Some(o) => HolderRead::Held(o.as_uuid()), None => HolderRead::Unheld, }, - crate::persona::card_holder::Hold::Lapsed - | crate::persona::card_holder::Hold::Unclaimed => HolderRead::Unheld, + crate::cognition::card_holder::Hold::Lapsed + | crate::cognition::card_holder::Hold::Unclaimed => HolderRead::Unheld, } } diff --git a/core/continuum-core/src/modules/work.rs b/core/continuum-core/src/modules/work.rs index 4979a3766f..fd63f50e81 100644 --- a/core/continuum-core/src/modules/work.rs +++ b/core/continuum-core/src/modules/work.rs @@ -39,7 +39,7 @@ pub mod submission; use crate::persona::work_board::advance::*; use crate::persona::work_board::events::*; -use crate::persona::work_board::facts::*; +use crate::cognition::card_facts::*; use crate::persona::work_board::horizon::*; mod work_card_state_changed; diff --git a/core/continuum-core/src/modules/work/work_claim.rs b/core/continuum-core/src/modules/work/work_claim.rs index 174ef437bd..cd38e55489 100644 --- a/core/continuum-core/src/modules/work/work_claim.rs +++ b/core/continuum-core/src/modules/work/work_claim.rs @@ -41,7 +41,7 @@ impl ActionCommand for WorkClaim { let board = board.snapshot(); if let Some(card) = board.cards.iter().find(|c| c.card_id == card_id) { if let Some((instance, reason)) = - crate::persona::card_holder::standing_refusal_for_card(&card.title) + crate::cognition::card_holder::standing_refusal_for_card(&card.title) { continuum_base::probe!( class = "work.claim.refused_ungradeable", diff --git a/core/continuum-core/src/modules/work/work_list.rs b/core/continuum-core/src/modules/work/work_list.rs index 1fe26addfc..b97f501b25 100644 --- a/core/continuum-core/src/modules/work/work_list.rs +++ b/core/continuum-core/src/modules/work/work_list.rs @@ -32,14 +32,14 @@ pub(super) fn live_holder(card: &airc_work::WorkCard, now_ms: u64) -> Option card.owner, + match crate::cognition::card_holder::hold_of(card, now_ms) { + crate::cognition::card_holder::Hold::Held => card.owner, // Lapsed or unclaimed: whatever refused the claim, it was not a person. - crate::persona::card_holder::Hold::Lapsed - | crate::persona::card_holder::Hold::Unclaimed => None, + crate::cognition::card_holder::Hold::Lapsed + | crate::cognition::card_holder::Hold::Unclaimed => None, } } @@ -52,8 +52,8 @@ pub(super) fn resumes_held_review( requested == CardState::InProgress && card.state == CardState::Review && card.owner == Some(caller) - && crate::persona::card_holder::hold_of(card, now_ms) - == crate::persona::card_holder::Hold::Held + && crate::cognition::card_holder::hold_of(card, now_ms) + == crate::cognition::card_holder::Hold::Held } /// What a refused claim MEANS for the citizen who made it. @@ -268,7 +268,7 @@ impl ActionCommand for WorkList { let board = board_to_read(&airc, p.room.as_deref()).await?; let now_ms = EpochMs::now().millis(); // Resolve every distinct owner to a published name in ONE pass, then render - // through the SHARED holder projection (`persona::card_holder`) — the same + // through the SHARED holder projection (`cognition::card_holder`) — the same // answer the [room-kanban] grounding block and the service-loop anchor give. // Before this, three surfaces computed "who holds it / is the lease live" // separately and a teammate always came back as 8-hex, which Joel called out @@ -298,7 +298,7 @@ impl ActionCommand for WorkList { .cards .iter() .map(|c| { - let holder = crate::persona::card_holder::holder(c, me, now_ms, &names); + let holder = crate::cognition::card_holder::holder(c, me, now_ms, &names); ( WorkListCard { id: short8(c.card_id.as_uuid()), diff --git a/core/continuum-core/src/modules/work/work_similar.rs b/core/continuum-core/src/modules/work/work_similar.rs index d5083c0813..693af88c75 100644 --- a/core/continuum-core/src/modules/work/work_similar.rs +++ b/core/continuum-core/src/modules/work/work_similar.rs @@ -404,7 +404,7 @@ impl WorkGet { .map(submission::WorkReviewResult::from).collect(); // the holder's card only: a review card's next step is its verdict, not a submission if card.reviews.is_none() { - let latest = crate::persona::work_board::submissions::latest_submission(card).map(|s| s.submission_id); + let latest = crate::cognition::card_holder::latest_submission(card).map(|s| s.submission_id); let outcomes: Vec<_> = latest .map(|id| board.submission_reviews_for(id).filter(|r| r.card_id == card.card_id).map(|r| r.outcome).collect()) .unwrap_or_default(); // unwrap_or_default: no submission, no outcomes @@ -420,11 +420,11 @@ impl WorkGet { now_ms: u64, reader: Uuid, ) -> WorkGetResult { - let holder = crate::persona::card_holder::holder( + let holder = crate::cognition::card_holder::holder( card, reader, now_ms, - &crate::persona::card_holder::NoNames, + &crate::cognition::card_holder::NoNames, ); WorkGetResult { reviews: Vec::new(), 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 9757a122f1..4c4496b81c 100644 --- a/core/continuum-core/src/test_env/loose_id_guard.rs +++ b/core/continuum-core/src/test_env/loose_id_guard.rs @@ -101,15 +101,15 @@ const LOOSE_IDS: &[LooseId] = &[ LooseId { file: "persona/airc_admission.rs", field: "message_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, LooseId { file: "persona/airc_admission.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/airc_admission.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/channel_items.rs", field: "context_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, - LooseId { file: "persona/channel_items.rs", field: "persona_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, - LooseId { file: "persona/channel_items.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/channel_items.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: "cognition/conversation/channel_items.rs", field: "context_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, + LooseId { file: "cognition/conversation/channel_items.rs", field: "persona_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, + LooseId { file: "cognition/conversation/channel_items.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: "cognition/conversation/channel_items.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/durable_history.rs", field: "message_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, LooseId { file: "persona/durable_history.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/engram.rs", field: "message_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, - LooseId { file: "persona/engram.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/engram.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: "cognition/engram.rs", field: "message_id", why: "pending: airc wire id, arrives as text from the daemon. Types when the airc-side ids do — #396" }, + LooseId { file: "cognition/engram.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: "cognition/engram.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: "ai/types.rs", field: "persona_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: "ai/types.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: "ai/types.rs", field: "user_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" }, diff --git a/core/continuum-core/src/test_env/mind_integration.rs b/core/continuum-core/src/test_env/mind_integration.rs index b3b22787c8..50d1a954f6 100644 --- a/core/continuum-core/src/test_env/mind_integration.rs +++ b/core/continuum-core/src/test_env/mind_integration.rs @@ -6,6 +6,7 @@ //! exactly what it asserted before the move. mod airc_conversation; +mod bound_card_activity; mod eval; mod recipe; mod registry; diff --git a/core/continuum-core/src/test_env/mind_integration/airc_conversation.rs b/core/continuum-core/src/test_env/mind_integration/airc_conversation.rs index 75602eddab..8267a2acc1 100644 --- a/core/continuum-core/src/test_env/mind_integration/airc_conversation.rs +++ b/core/continuum-core/src/test_env/mind_integration/airc_conversation.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use crate::persona::airc_persona_conversation::*; -use crate::persona::service_loop::PersonaConversation; +use crate::cognition::conversation::PersonaConversation; /// what this catches: e0d64552 — the actual membership commands persisted /// their changes but bypassed the epoch that refreshes a living stream. diff --git a/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs new file mode 100644 index 0000000000..a93369d57c --- /dev/null +++ b/core/continuum-core/src/test_env/mind_integration/bound_card_activity.rs @@ -0,0 +1,179 @@ +#![cfg(test)] +//! From `cognition::act_observe` (mind split step 7): the bound card's activity, read through +//! persona's board and bound by persona's card hands, is the one cognition perceives and acts +//! in. It needs both crates, so it lives here. Asserts exactly what it asserted before the move. + +use std::sync::{Arc, Mutex}; + +use uuid::Uuid; + +use crate::cognition::act_observe::test_support::{admission, ActThenSpeak, RecordingExecutor}; +use crate::cognition::act_observe::{settle_step, ActChain}; +use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; +use crate::cognition::workspace::{ActingBody, SalienceArbiter, Situation, TurnFraming, WorkspaceCycle}; + +// Regression17d3e6ff: real card lookup must resolve admitted hands before +// board grounding, ledger rendering and execution, without moving the wake. +#[tokio::test] +async fn bound_card_activity_is_shared_by_perception_and_execution() { + crate::persona::cognition_extensions::install(); // the card's board room is persona's to read + use crate::cognition::{ + llm_deliberation_faculty::LlmDeliberationFaculty, + rag_source_faculty::{RagSourceFaculty, SaliencePolicy}, + }; + use crate::persona::{ + airc_runtime::PersonaAircRuntime, airc_runtime_registry::PersonaAircRuntimeRegistry, + room_board_source::RoomBoardSource, + }; + let home = tempfile::tempdir().unwrap(); + let _home = crate::paths::test_home::HomeGuard::set(home.path()).await; + let airc = Arc::new( + airc_lib::Airc::open_with_wire_root_for_test(home.path(), home.path()) + .await + .unwrap(), + ); + let task = airc.join("bound-activity-task").await.unwrap(); + let card = airc + .create_work_card(airc_lib::CreateWorkCard::new( + airc_lib::RepoId::new("fixture/activity").unwrap(), + "implement subject change", + airc_lib::Priority::P2, + )) + .await + .unwrap(); + let claim = airc + .claim_work_card(airc_lib::ClaimWorkCard { + card_id: card, + ttl_ms: 600_000, + }) + .await + .unwrap(); + let wake = airc.join("bound-activity-wake").await.unwrap(); + let persona = airc.peer_id().as_uuid(); + PersonaAircRuntimeRegistry::set_global(PersonaAircRuntimeRegistry::new()); + let registry = PersonaAircRuntimeRegistry::try_global().unwrap(); + let runtime = registry.register(PersonaAircRuntime::from_attached( + persona, + "Ivar", + home.path().to_path_buf(), + airc.clone(), + wake.channel, + crate::persona::identity_provider::PersonaIdentitySource::FreshlyMinted, + )); + let hands = + crate::identity::hands_context::HandsContext::for_claim(persona, card.as_uuid(), claim.as_uuid()); + let checkout = airc_lib::work_worktree::worktree_path_for(card).unwrap(); + assert!(checkout.starts_with(home.path())); + std::fs::create_dir_all(checkout.join(".git")).unwrap(); + let exec = Arc::new(RecordingExecutor { + seen_context: Arc::new(Mutex::new(None)), + result_content: "read subject file".into(), + }); + let wm = Arc::new(WorkingMemory::new(8)); + let (board_source, _dirty) = crate::cognition::cached_source::CachedRagSource::new(Arc::new( + RoomBoardSource::new(persona, runtime).for_room(wake.channel.as_uuid()), + )); + let board = RagSourceFaculty::new(persona, board_source, SaliencePolicy::StandingFraming); + let cycle = WorkspaceCycle::new( + vec![ + Arc::new(board), + Arc::new(WorkingMemoryFaculty::new(wm.clone())), + Arc::new(ActThenSpeak::new()), + ], + Arc::new(SalienceArbiter), + 8, + ) + .with_acting(Arc::new(ActingBody { + persona_id: persona, + persona_name: "Ivar".into(), + executor: exec.clone(), + admission: admission(), + working_memory: wm.clone(), + })); + let board_state = airc.work_board_in(&task).await.unwrap(); + let focus = board_state.card(card).unwrap(); + let binding = crate::persona::card_hands::bind_card(&cycle, persona, focus).await; + assert_eq!(binding.hands.as_ref().map(|h| h.context), Some(hands)); + let burst = crate::cognition::workspace::Burst::raw_in( + crate::identity::ActivityRoom::from_uuid(wake.channel.as_uuid()).unwrap(), + "work on my held card".into(), + ) + .in_hands(Some(hands)); + let _ = settle_step( + &cycle, + burst.clone(), + true, + TurnFraming::default(), + Situation::default(), + &ActChain::new(), + ) + .await; + assert_eq!( + *exec.seen_context.lock().unwrap(), + Some(task.channel.as_uuid()), + "tools execute in the card activity" + ); + let ws = cycle.run(burst).await; + assert_eq!(ws.room_id, wake.channel.as_uuid()); + assert_eq!(ws.activity_room_id, task.channel.as_uuid()); + assert!( + ws.broadcast + .iter() + .any(|c| c.content.contains("implement subject change")), + "the task board reaches perception" + ); + let prompt = LlmDeliberationFaculty::new( + persona, + "Ivar", + "You are Ivar.", + Arc::new(crate::ai::heuristic_adapter::HeuristicInferenceAdapter::new()), + ) + .with_working_memory(wm) + .prompt_view(&ws); + // Her acts reach her through the action stream (the steps ledger it replaced is gone). + let text: String = prompt.messages.iter().map(|m| m.content_text()).collect::>().join("\n"); + let actions = text.find("[actions]").map(|at| &text[at..]).expect("test: the action stream is in her view"); + assert!(actions.contains("code/run"), "{actions}"); + assert!(!actions.contains("nothing has executed yet"), "{actions}"); + assert_eq!(airc.current_room().await.unwrap().channel, wake.channel); + let private = crate::cognition::mind_room::mind_room_id(persona); + let private_ws = cycle + .run( + crate::cognition::workspace::Burst::raw_in( + crate::identity::ActivityRoom::from_uuid(private).unwrap(), + "private thought".into(), + ) + .in_hands(Some(hands)), + ) + .await; + assert_eq!( + private_ws.activity_room_id, private, + "private thoughts never adopt public task scope" + ); + // An eval's fresh hands and a roomless fixture never borrow the focused claim. + let fork = crate::identity::hands_context::HandsContext::fresh(); + assert_eq!( + crate::cognition::persona_workspace::activity_room_for(persona, Some(fork), Uuid::nil()) + .await, + Uuid::nil(), + ); + let unbound_ws = cycle + .run(crate::cognition::workspace::Burst::from("synthetic exam").in_hands(Some(fork))) + .await; + assert_eq!(unbound_ws.activity_room_id, unbound_ws.room_id); + assert!(!unbound_ws + .broadcast + .iter() + .any(|c| c.content.contains("implement subject change"))); + assert_eq!( + crate::cognition::persona_workspace::activity_room_for( + persona, + None, + wake.channel.as_uuid() + ) + .await, + wake.channel.as_uuid(), + "default hands do not inherit the focused claim's card", + ); + registry.remove(persona); +} diff --git a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs index fa3b40c3df..d1e99fced0 100644 --- a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs +++ b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs @@ -9,12 +9,13 @@ use continuum_base::time::EpochMs; use uuid::Uuid; use crate::cognition::persona_workspace::*; +use crate::persona::card_hands::bind_card; use crate::cognition::workspace::{ActingBody, WorkspaceCycle}; -use crate::persona::admission_state::AdmissionState; +use crate::cognition::admission_state::AdmissionState; use crate::modules::card_staging; use crate::modules::code::{CodeModule, CodeState}; use crate::modules::grid::GridTrustAuthPolicy; -use crate::persona::recall_metadata::RecallMetadataRegistry; +use crate::cognition::recall_metadata::RecallMetadataRegistry; use crate::routing::CallerIdentity; use crate::cognition::tool_executor::CommandToolExecutor; use crate::runtime::{CommandExecutor, ModuleRegistry}; diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index c0b5a90aa0..2ca91ce761 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -1,10 +1,19 @@ #![cfg(test)] //! From `persona::remote_lane_factory`: core's `AircModule`, built from a healthy discovery, //! registers this node's id before any persona build, so a durable override naming this -//! node retires and she is born home. Asserts exactly what it asserted before the move. +//! node retires and she is born home. From `cognition::persona_workspace`: a re-home keeps a +//! resident's binding until her assignment reads as local. Each asserts exactly what it +//! asserted before its move. use std::sync::atomic::Ordering; +use std::sync::Arc; + +use uuid::Uuid; + +use crate::ai::adapter::AIProviderAdapter; +use crate::ai::HeuristicInferenceAdapter; +use crate::cognition::persona_workspace::PersonaWorkspaceRegistry; use crate::persona::model_override::PersonaModelOverride; use crate::persona::remote_lane_factory::test_support::*; use crate::persona::supervisor::PersonaAdapterFactory; @@ -40,3 +49,53 @@ async fn an_override_naming_this_node_is_retired_at_build_and_she_is_born_home() "the record naming her own node as a seat is retired" ); } + +// what this catches (from cognition::persona_workspace, mind split step 7): serving-edge rehome must preserve a resident's binding when its assignment is corrupt. +#[tokio::test] +async fn rehome_requires_a_readable_local_assignment() { + crate::persona::cognition_extensions::install(); // her remote binding is persona's to read + let root = tempfile::tempdir().expect("root"); + let _native = crate::paths::NativeHomeOverride::install(root.path()); + let registry = PersonaWorkspaceRegistry::new(); + let id = Uuid::new_v4(); + let cycle = registry.register_from_cfg(cfg_for(id)).expect("resident"); + let (original, original_model) = cycle.current_model_route().expect("binding"); + let airc = crate::identity::citizen_path::citizen_home_path(root.path(), crate::identity::IdentityKind::Persona, None, "Ivar"); + let home = crate::cognition::home::PersonaHome::from_root(airc.parent().expect("parent").to_path_buf()); + let remote = PersonaModelOverride::new_remote("remote/model", None, 1, Uuid::new_v4().to_string()); + remote.write(&home).expect("remote override"); + let replacement: Arc = Arc::new(HeuristicInferenceAdapter::new()); + for corrupt in [false, true] { + if corrupt { std::fs::write(home.model_override_json(), b"{").expect("corrupt"); } + assert_eq!(registry.re_home_all_at(root.path(), replacement.clone(), Some("new/local".into()), 4096), 0); + let (actual, model) = cycle.current_model_route().expect("preserved"); + assert!(Arc::ptr_eq(&original, &actual)); + assert_eq!(model, original_model); + } + PersonaModelOverride::new("local/model", None, 2).write(&home).expect("local override"); + assert_eq!(registry.re_home_all_at(root.path(), replacement.clone(), Some("new/local".into()), 4096), 1); + let (actual, model) = cycle.current_model_route().expect("rebound"); + assert!(Arc::ptr_eq(&replacement, &actual)); + assert_eq!(model.as_deref(), Some("new/local")); +} + +/// A resident's brain config: the deterministic heuristic adapter, no grounding, no hands. +fn cfg_for(persona_id: uuid::Uuid) -> crate::cognition::persona_workspace::PersonaBrainConfig { + crate::cognition::persona_workspace::PersonaBrainConfig { + persona_id, + persona_name: "Ivar".to_string(), + system_prompt: "You are Ivar, an engineer on the grid.".to_string(), + admission: crate::cognition::act_observe::test_support::admission(), + adapter: std::sync::Arc::new(crate::ai::HeuristicInferenceAdapter::new()), + capacity: None, + grounding_sources: Vec::new(), + embedder: None, + tool_executor: None, + experience: None, + context_window: crate::inference::planning::MIN_SERVE_CTX, + defer_recall: false, + defer_grounding: false, + suppress_recall: false, + forked: false, + } +} 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 7b47f430a6..1031377d0b 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 @@ -19,8 +19,8 @@ async fn directed_credit_survives_partial_cancellation_and_atomic_retry() { FinishReason, TextGenerationRequest, TextGenerationResponse, UsageMetrics, }; use crate::cognition::llm_deliberation_faculty::LlmDeliberationFaculty; - use crate::persona::scripted_conversation::ScriptedConversation; - use crate::persona::service_loop::PersonaConversation; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::PersonaConversation; use crate::persona::training_producer::{ CapturedCredit, StagedCredit, StagedCreditGeneration, }; diff --git a/core/continuum-core/src/test_env/mind_integration/training_credit/reviewed_credit.rs b/core/continuum-core/src/test_env/mind_integration/training_credit/reviewed_credit.rs index b7db10b7fa..f727904655 100644 --- a/core/continuum-core/src/test_env/mind_integration/training_credit/reviewed_credit.rs +++ b/core/continuum-core/src/test_env/mind_integration/training_credit/reviewed_credit.rs @@ -100,7 +100,7 @@ use super::*; ); let store = reviewed::boundaries::ReviewBoundaryStore::new(executor.clone(), name.into(), persona); - let dream = region_over_with_store(persona, admission.clone(), Some(store.clone())); + let dream = region_over_with_store(persona, admission.clone(), Some(Arc::new(store.clone()))); let create = |card, reviews| fx.create(card, reviews); let claim = ExactReview::claim; let project = |tail| fx.project(tail); @@ -439,7 +439,7 @@ use super::*; .await .is_err()); let dream = - region_over_with_store(persona, admission.clone(), Some(reopened_store.clone())); + region_over_with_store(persona, admission.clone(), Some(Arc::new(reopened_store.clone()))); assert!(!dream.review_boundary_pending(persona, selection.submission_id)); dream.tick(&RegionContext::for_persona(0, persona)).await; drain(&dream).await; @@ -448,7 +448,7 @@ use super::*; admission .recall_recent(16) .iter() - .filter(|e| e.kind == crate::persona::engram::EngramKind::Semantic) + .filter(|e| e.kind == crate::cognition::engram::EngramKind::Semantic) .count(), 1 ); @@ -469,7 +469,7 @@ use super::*; .unwrap() .pending .is_empty()); - let restarted = region_over_with_store(persona, admission, Some(reopened_store)); + let restarted = region_over_with_store(persona, admission, Some(Arc::new(reopened_store))); reviewed::consume_review_with_boundary( &refused_conn, name, diff --git a/core/continuum-core/tests/architecture_demand_pull_cognition.rs b/core/continuum-core/tests/architecture_demand_pull_cognition.rs index c4660a61ca..567b11f34f 100644 --- a/core/continuum-core/tests/architecture_demand_pull_cognition.rs +++ b/core/continuum-core/tests/architecture_demand_pull_cognition.rs @@ -63,12 +63,12 @@ use std::sync::Arc; use uuid::Uuid; -use continuum_core::persona::channel_items::ChatQueueItem; +use continuum_core::cognition::conversation::channel_items::ChatQueueItem; use continuum_core::persona::channel_registry::{ChannelRegistry, DEFAULT_BURST_WINDOW_MS}; -use continuum_core::persona::channel_types::QueueItemBehavior; +use continuum_core::cognition::conversation::channel_types::QueueItemBehavior; use continuum_core::persona::channel_view::CoherentInput; -use continuum_core::persona::persona_identity::PersonaIdentity; -use continuum_core::persona::types::{PersonaState, SenderType}; +use continuum_core::cognition::conversation::persona_identity::PersonaIdentity; +use continuum_core::cognition::conversation::types::{PersonaState, SenderType}; fn make_chat(room: Uuid, sender: &str, content: &str) -> Arc { make_chat_at(room, sender, content, continuum_base::time::EpochMs::now().millis()) @@ -182,7 +182,7 @@ fn service_cycle_with_n_chat_messages_yields_one_input() { /// window arrival distributions — not just within one tight window. #[test] fn service_cycle_multi_window_yields_one_input_with_remainder_deferred() { - use continuum_core::persona::channel_types::ActivityDomain; + use continuum_core::cognition::conversation::channel_types::ActivityDomain; let mut registry = ChannelRegistry::new(); let mut state = PersonaState::new(); diff --git a/core/continuum-core/tests/architecture_killer_loop_burst_cognition.rs b/core/continuum-core/tests/architecture_killer_loop_burst_cognition.rs index 99e2ba2268..88c7735494 100644 --- a/core/continuum-core/tests/architecture_killer_loop_burst_cognition.rs +++ b/core/continuum-core/tests/architecture_killer_loop_burst_cognition.rs @@ -66,13 +66,13 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use uuid::Uuid; -use continuum_core::persona::channel_items::ChatQueueItem; +use continuum_core::cognition::conversation::channel_items::ChatQueueItem; use continuum_core::persona::channel_registry::{ChannelRegistry, DEFAULT_BURST_WINDOW_MS}; -use continuum_core::persona::channel_types::QueueItemBehavior; +use continuum_core::cognition::conversation::channel_types::QueueItemBehavior; use continuum_core::persona::cognition::PersonaCognitionEngine; use continuum_core::persona::message_cache::RecentMessageCache; -use continuum_core::persona::persona_identity::PersonaIdentity; -use continuum_core::persona::types::{PersonaState, SenderType}; +use continuum_core::cognition::conversation::persona_identity::PersonaIdentity; +use continuum_core::cognition::conversation::types::{PersonaState, SenderType}; use continuum_core::persona::{analyze_burst, BurstEvaluateResult, RateLimiterState, SleepState}; use continuum_core::rag::RagEngine; diff --git a/core/continuum-genome/src/genome/corpus_ref.rs b/core/continuum-genome/src/genome/corpus_ref.rs index a9496c9412..a6b3c47d6a 100644 --- a/core/continuum-genome/src/genome/corpus_ref.rs +++ b/core/continuum-genome/src/genome/corpus_ref.rs @@ -13,7 +13,7 @@ use ts_rs::TS; /// node-local storage, or wherever the `source_url` resolves. /// /// `content_hash` uses the canonical `"sha256:"` format that -/// matches `persona::admission` content_hash on the engram side +/// matches `cognition::admission` content_hash on the engram side /// (consensus position #8 from the design review). Cross-domain /// consistency: any two subsystems comparing hashes can do /// string-equality without normalization. diff --git a/core/continuum-kernel/src/sdk_codegen/ai_help.rs b/core/continuum-kernel/src/sdk_codegen/ai_help.rs index c175526cf1..545be0457a 100644 --- a/core/continuum-kernel/src/sdk_codegen/ai_help.rs +++ b/core/continuum-kernel/src/sdk_codegen/ai_help.rs @@ -10,6 +10,7 @@ use serde_json::{json, Value}; /// How many commands a lookup names at once: the nearest names to a miss, and the matches a /// `commands/help` query returns. Wide enough that the route survives the eight-way tie /// `list_cards` produced (2026-09-05, see `did_you_mean`), narrow enough to read at a glance. +// context-budget-exempt: a count of command names shown, not a context or prompt size. pub const SUGGESTION_WINDOW: usize = 6; /// Closest authorized command names to a miss — same category prefix (before `/`), diff --git a/core/continuum-mind/Cargo.toml b/core/continuum-mind/Cargo.toml index 5922aa7c58..a19227ea90 100644 --- a/core/continuum-mind/Cargo.toml +++ b/core/continuum-mind/Cargo.toml @@ -10,6 +10,7 @@ repository = "https://github.com/CambrianTech/continuum" build = "../continuum-core/build.rs" [dependencies] +continuum-cognition = { path = "../continuum-cognition" } continuum-kernel = { path = "../continuum-kernel" } continuum-engine = { path = "../continuum-engine" } continuum-hands = { path = "../continuum-hands" } @@ -24,7 +25,6 @@ serde_json.workspace = true uuid.workspace = true continuum-base = { path = "../continuum-base" } continuum-context = { path = "../continuum-context" } -tool-working-set = { path = "../tool-working-set" } # the learned tool head: pure policy, no core dependency schemars = { version = "0.8", features = ["uuid1"] } continuum-airc-protocol = { path = "../continuum-airc-protocol" } continuum-positron = { path = "../continuum-positron" } @@ -60,6 +60,7 @@ image = "0.25" regex = "1" [dev-dependencies] +continuum-cognition = { path = "../continuum-cognition", features = ["test-fixtures"] } continuum-kernel = { path = "../continuum-kernel", features = ["test-fixtures"] } # every test build of this crate gets the per-process continuum home (card d11d9827) tokio = { workspace = true, features = ["test-util"] } tempfile = "3" @@ -73,10 +74,10 @@ continuum-experience = { path = "../continuum-experience", features = ["test-fix default = [] # The GPU backends are the engine's (llama, candle); the mind forwards them so it builds and # tests on its own with the same flags core takes. -metal = ["continuum-engine/metal", "continuum-live/metal", "continuum-genome/metal"] -cuda = ["continuum-kernel/cuda", "continuum-engine/cuda", "continuum-genome/cuda"] -vulkan = ["continuum-kernel/vulkan", "continuum-engine/vulkan", "continuum-genome/vulkan"] -stress-tests = ["continuum-kernel/stress-tests", "continuum-genome/stress-tests"] +metal = ["continuum-cognition/metal", "continuum-engine/metal", "continuum-live/metal", "continuum-genome/metal"] +cuda = ["continuum-cognition/cuda", "continuum-kernel/cuda", "continuum-engine/cuda", "continuum-genome/cuda"] +vulkan = ["continuum-cognition/vulkan", "continuum-kernel/vulkan", "continuum-engine/vulkan", "continuum-genome/vulkan"] +stress-tests = ["continuum-cognition/stress-tests", "continuum-kernel/stress-tests", "continuum-genome/stress-tests"] # Test-only code (fixtures shared with core's integration tests, the heuristic adapter it # drives); production binaries never build with it. -test-fixtures = ["continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "continuum-hands/test-fixtures", "continuum-live/test-fixtures", "continuum-perception/test-fixtures", "continuum-genome/test-fixtures", "continuum-experience/test-fixtures"] +test-fixtures = ["continuum-cognition/test-fixtures", "continuum-base/test-fixtures", "continuum-kernel/test-fixtures", "continuum-engine/test-fixtures", "continuum-hands/test-fixtures", "continuum-live/test-fixtures", "continuum-perception/test-fixtures", "continuum-genome/test-fixtures", "continuum-experience/test-fixtures"] diff --git a/core/continuum-mind/src/cognition/act_observe/tests/mod.rs b/core/continuum-mind/src/cognition/act_observe/tests/mod.rs deleted file mode 100644 index 3d4cb2eed2..0000000000 --- a/core/continuum-mind/src/cognition/act_observe/tests/mod.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Shared fixtures for the act_observe tests: stand-in executors, faculties and -//! bodies. Scenario files sit beside this one and pull these in via `use super::*;`. - -#![cfg(test)] - -mod apply; -mod chain; -mod credit; -mod drive; -mod investigation; - -use super::*; -use super::test_support::*; -use crate::cognition::workspace::Decision; -use crate::cognition::workspace::ActingBody; -use crate::cognition::workspace::Contribution; -use crate::cognition::workspace::Faculty; -use crate::cognition::workspace::FacultyId; -use crate::cognition::workspace::Workspace; -use crate::cognition::tool_executor::NativeBatchOutcome; -use crate::cognition::tool_executor::ParsedToolBatch; -use crate::cognition::tool_executor::ToolError; -use crate::cognition::tool_executor::ToolExecutionContext; -use crate::cognition::tool_executor::ToolExecutor; -use crate::cognition::tool_executor::ToolOutcome; -use crate::ai::types::ToolCall; -use uuid::Uuid; -use crate::persona::admission_state::AdmissionState; -use async_trait::async_trait; -use std::sync::Arc; -use std::sync::Mutex; -use crate::cognition::working_memory::WorkingMemory; - -/// A `ToolExecutor` that records the `context_id` it was handed and returns a -/// canned per-call result — so a test can assert BOTH that the act was scoped -/// to the right room and that the observation correlates call→result. -#[derive(Clone)] -struct RecordingExecutor { - seen_context: Arc>>, - result_content: String, -} - -#[async_trait] -impl ToolExecutor for RecordingExecutor { - fn in_hands(&self, _persona: Uuid, _context: crate::identity::hands_context::HandsContext) -> Option> { - Some(Arc::new(self.clone())) - } - async fn execute_native_batch( - &self, - calls: &[ToolCall], - context: &ToolExecutionContext, - _max_result_chars: usize, - ) -> Result { - *self.seen_context.lock().unwrap() = Some(context.context_id); - let results = calls - .iter() - .map(|c| crate::ai::types::ToolResult { - tool_use_id: c.id.clone(), - content: self.result_content.clone(), - is_error: None, - custody: crate::ai::types::ResultCustody::Unsaved, - }) - .collect(); - Ok(NativeBatchOutcome { - results, - media: Vec::new(), - stored_ids: Vec::new(), - // Test doubles project nothing — the act seam must behave exactly - // as it does for a command that never opted in. - verdicts: Vec::new(), - }) - } - - async fn parse_response( - &self, - _response_text: &str, - _model_family: Option<&str>, - ) -> Result { - Ok(ParsedToolBatch { - tool_calls: Vec::new(), - cleaned_text: String::new(), - parse_time_us: 0, - }) - } - - async fn store_outcome( - &self, - _outcome: &ToolOutcome, - _context: &ToolExecutionContext, - ) -> Result { - Ok(Uuid::nil()) - } -} - -/// An executor whose batch always fails at the batch level (channel down). -struct FailingExecutor; -#[async_trait] -impl ToolExecutor for FailingExecutor { - async fn execute_native_batch( - &self, - _calls: &[ToolCall], - _context: &ToolExecutionContext, - _max_result_chars: usize, - ) -> Result { - Err(ToolError::ExecutionFailed { - tool: "code/run".into(), - underlying: "ipc channel down".into(), - }) - } - async fn parse_response( - &self, - _t: &str, - _f: Option<&str>, - ) -> Result { - Ok(ParsedToolBatch { - tool_calls: Vec::new(), - cleaned_text: String::new(), - parse_time_us: 0, - }) - } - async fn store_outcome( - &self, - _o: &ToolOutcome, - _c: &ToolExecutionContext, - ) -> Result { - Ok(Uuid::nil()) - } -} - -/// Deliberation faculty: reaches for its hands once, then SETTLES into a Speak -/// the moment it perceives a NEW act-observation it has not yet answered — the -/// canonical act→observe arc the driver exists to run. -/// -/// It perceives its own hands through the working-memory proprioception channel -/// (the `WorkingMemoryFaculty` stamps each act `[action #n]`), NOT the deleted -/// world-state fold. It remembers the highest action stamp it has already spoken -/// about (`responded_through`) so that across SEPARATE concerns — where the -/// volatile buffer still carries the prior concern's action — it re-awakens and -/// acts again instead of mistaking old proprioception for "already answered." -/// That is the faculty remembering its own last conclusion (legitimate, content- -/// driven), not an iteration counter in the agentic sense. -struct ActThenSpeak { - responded_through: std::sync::atomic::AtomicU64, - admission_open: Option>, -} -impl ActThenSpeak { - fn new() -> Self { - Self { - responded_through: std::sync::atomic::AtomicU64::new(0), - admission_open: None, - } - } -} -/// Highest `[action #N]` stamp present in the assembled perception, 0 if none. -fn latest_action_seq(perceived: &str) -> u64 { - perceived - .split("[action #") - .skip(1) - .filter_map(|s| { - let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect(); - digits.parse::().ok() - }) - .max() - .unwrap_or(0) -} -#[async_trait] -impl Faculty for ActThenSpeak { - fn id(&self) -> FacultyId { - FacultyId::Deliberation - } - fn reacts_to_broadcast(&self) -> bool { - true - } - async fn contribute(&self, ws: &Workspace) -> Option { - if self.admission_open.as_ref().is_some_and(|gate| !gate.load(std::sync::atomic::Ordering::SeqCst)) { - return Some(Contribution::deliberation_fault("lane starved before dispatch")); - } - - use std::sync::atomic::Ordering; - let latest = latest_action_seq(&ws.perceived()); - if latest > self.responded_through.load(Ordering::Relaxed) { - self.responded_through.store(latest, Ordering::Relaxed); - Some(Contribution::verdict( - Decision::Speak { - text: "the answer is 4".into(), - }, - 0.9, - "settled after observing a fresh result", - )) - } else { - Some(Contribution::verdict( - Decision::Act { - calls: vec![tool_call()], - intent: "run the code".into(), - }, - 0.9, - "reaching for hands", - )) - } - } -} - -/// Deliberation faculty that NEVER settles — always wants to act again. Models -/// the "acts forever" fitness gap the external grader bounds with `max_acts`. -struct AlwaysAct; -#[async_trait] -impl Faculty for AlwaysAct { - fn id(&self) -> FacultyId { - FacultyId::Deliberation - } - fn reacts_to_broadcast(&self) -> bool { - true - } - async fn contribute(&self, _ws: &Workspace) -> Option { - Some(Contribution::verdict( - Decision::Act { - calls: vec![tool_call()], - intent: "act again".into(), - }, - 0.9, - "never settles", - )) - } -} - -/// Only ever speaks, and COUNTS how many generations it was asked for — the -/// instrument for "did the drive hand her another tick, or settle on the first -/// Speak?". -struct CountingSpeaker { - generations: Mutex, -} -impl CountingSpeaker { - fn new() -> Arc { - Arc::new(Self { - generations: Mutex::new(0), - }) - } - fn generations(&self) -> usize { - *self.generations.lock().expect("lock") - } -} -#[async_trait] -impl Faculty for CountingSpeaker { - fn id(&self) -> FacultyId { - FacultyId::Deliberation - } - fn reacts_to_broadcast(&self) -> bool { - true - } - async fn contribute(&self, _ws: &Workspace) -> Option { - *self.generations.lock().expect("lock") += 1; - Some(Contribution::verdict( - Decision::Speak { - text: "here is my analysis of the bug: the call to subs() is wrong".into(), - }, - 0.95, - "explaining rather than editing", - )) - } -} - -fn tool_call() -> ToolCall { - ToolCall { - id: "call-1".into(), - name: "code/run".into(), - input: serde_json::json!({ "lang": "rust", "code": "fn main() { println!(\"{}\", 2 + 2); }" }), - } -} - -/// Unwrap the typed acts of an `Acted` outcome (panics on NoHands/ExecutorError) — -/// the typed sibling of the old `.expect("acted")` on the `Option`. -fn acts_of(outcome: ActOutcome) -> Vec { - match outcome { - ActOutcome::Acted { acts } => acts, - other => panic!("expected Acted, got {other:?}"), - } -} - -fn body(executor: Arc, admission: Arc) -> Arc { - body_with_wm(executor, admission, Arc::new(WorkingMemory::new(3))) -} - diff --git a/core/continuum-mind/src/context/airc_adapter.rs b/core/continuum-mind/src/context/airc_adapter.rs index b2e7148d75..384ed3fcd8 100644 --- a/core/continuum-mind/src/context/airc_adapter.rs +++ b/core/continuum-mind/src/context/airc_adapter.rs @@ -20,7 +20,7 @@ use async_trait::async_trait; use uuid::Uuid; use crate::persona::airc_citizen::AircCitizen; -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; /// Wraps an `Arc` so it can be handed to substrate /// surfaces expecting `Arc`. Stateless; delegates @@ -40,7 +40,7 @@ impl AircTranscriptReader for AircHandleAdapter { async fn page_recent(&self, limit: usize) -> Result, AircError> { // Route through the ONE kinds-filtered impl on `airc_lib::Airc` // (persona/airc_source.rs, #297) — never the raw inherent page. - crate::persona::airc_source::AircTranscriptReader::page_recent(&*self.inner, limit).await + crate::cognition::conversation::transcript_reader::AircTranscriptReader::page_recent(&*self.inner, limit).await } async fn page_recent_in( @@ -50,7 +50,7 @@ impl AircTranscriptReader for AircHandleAdapter { ) -> Result, AircError> { // Explicit forward (#367) — the #262 lesson lives in this file: // a silently-inherited trait default is how regressions ship. - crate::persona::airc_source::AircTranscriptReader::page_recent_in(&*self.inner, room, limit) + crate::cognition::conversation::transcript_reader::AircTranscriptReader::page_recent_in(&*self.inner, room, limit) .await } } diff --git a/core/continuum-mind/src/lib.rs b/core/continuum-mind/src/lib.rs index 88867f7732..156f08ddca 100644 --- a/core/continuum-mind/src/lib.rs +++ b/core/continuum-mind/src/lib.rs @@ -1,5 +1,5 @@ -//! continuum-mind: cut out of continuum-core (MICROKERNEL-DECOMPOSITION.md): cognition, -//! persona, context and vdd. Depends on the live crate (which carries the engine and the +//! continuum-mind: cut out of continuum-core (MICROKERNEL-DECOMPOSITION.md): persona, +//! context and vdd, over cognition (its own crate, re-exported here under its old path). Depends on the live crate (which carries the engine and the //! kernel), the hands, and the crates cut out of the mind: perception (perception and rag), //! genome, memory and experience (experience and recipe), re-exported here under their old //! paths; core re-exports these modules under their old names. @@ -11,7 +11,7 @@ pub use continuum_memory::memory; pub use continuum_experience::{experience, recipe}; pub use continuum_perception::{perception, rag}; -pub mod cognition; +pub use continuum_cognition::cognition; pub mod context; pub mod persona; pub mod vdd; diff --git a/core/continuum-mind/src/persona/act_question.rs b/core/continuum-mind/src/persona/act_question.rs index 8a8686f336..8cef7759aa 100644 --- a/core/continuum-mind/src/persona/act_question.rs +++ b/core/continuum-mind/src/persona/act_question.rs @@ -33,7 +33,7 @@ //! the decision and its inputs whether or not a work turn follows. A gate whose //! refusal is invisible is a gate nobody can debug. -use crate::persona::service_loop::{PersonaConversation, LIVE_MAX_ACTS}; +use crate::persona::service_loop::{CitizenConversation, LIVE_MAX_ACTS}; use crate::persona::supervisor::HostedPersona; /// How many run-room rows the write-or-release gate reads to count a holder's @@ -74,7 +74,7 @@ pub(crate) struct WorkQuestionOutcome { pub(crate) async fn ask_the_act_question( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, lamport: u64, turn_room: uuid::Uuid, directed: bool, @@ -304,7 +304,7 @@ pub(crate) async fn ask_the_act_question( // of her card's claim, standing in its checkout, never her default hands. let card_turn = match held.first() { Some(card) => Some( - crate::cognition::persona_workspace::bind_card( + crate::persona::card_hands::bind_card( &cycle, ctx.identity.peer_id.as_uuid(), card, @@ -427,7 +427,7 @@ pub(crate) async fn ask_the_act_question( LIVE_MAX_ACTS, work_framing, conversation, - credit_capture.as_mut(), + credit_capture.as_mut().map(|c| c as &mut dyn crate::cognition::act_observe::TurnCredit), ) .await; // After the card her genome is what every turn runs with (her trained @@ -440,7 +440,7 @@ pub(crate) async fn ask_the_act_question( // The turn's work is synced to its card's branch; her hands stay where // they are, because nothing moved them (card fc9e9fd7). if let Some(hands) = work_hands { - crate::cognition::persona_workspace::end_card_turn(hands, work.acts).await; + crate::persona::card_hands::end_card_turn(hands, work.acts).await; } if let Some(body) = cycle.acting() { // One turn ended: 1-turn pins ([hands], [env]) leave now; the diff --git a/core/continuum-mind/src/persona/airc_admission.rs b/core/continuum-mind/src/persona/airc_admission.rs index e65ae26684..9a098f466c 100644 --- a/core/continuum-mind/src/persona/airc_admission.rs +++ b/core/continuum-mind/src/persona/airc_admission.rs @@ -10,9 +10,9 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use ts_rs::TS; -use super::admission::AdmissionCandidate; -use super::engram::{AircMessageRef, EngramKind, EngramOrigin, TrustState}; -use super::inbox_admission::content_hash_sha256; +use crate::cognition::admission::AdmissionCandidate; +use crate::cognition::engram::{AircMessageRef, EngramKind, EngramOrigin, TrustState}; +use crate::cognition::inbox_admission::content_hash_sha256; /// Signed AIRC message envelope material needed for memory admission. /// @@ -141,10 +141,8 @@ fn airc_recall_keys(envelope: &AircAdmissionEnvelope) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::persona::{ - AdmissionConfig, AdmissionContext, AdmissionDecision, AdmissionDropReason, AdmissionError, - AdmissionGate, HeuristicIsMemorable, SeenContentLookup, SeenEventLookup, - }; + use crate::cognition::admission::{AdmissionConfig, AdmissionContext, AdmissionGate, HeuristicIsMemorable, SeenContentLookup, SeenEventLookup}; + use crate::cognition::engram::{AdmissionDecision, AdmissionDropReason, AdmissionError}; use std::collections::HashMap; use std::sync::Mutex; use uuid::Uuid; diff --git a/core/continuum-mind/src/persona/airc_citizen.rs b/core/continuum-mind/src/persona/airc_citizen.rs index d63da99540..0996757b23 100644 --- a/core/continuum-mind/src/persona/airc_citizen.rs +++ b/core/continuum-mind/src/persona/airc_citizen.rs @@ -55,7 +55,7 @@ //! via the identity struct; AircCitizen carries the *live handle*. //! Two concerns, two types. -use crate::persona::airc_source::AircTranscriptReader; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use airc_lib::{AircError, EventId, FilteredEventStream}; use async_trait::async_trait; use uuid::Uuid; @@ -147,7 +147,7 @@ pub trait AircCitizen: /// Publish a text message under the citizen's identity INTO A /// SPECIFIC ROOM — normally the room the turn being answered - /// arrived in ([`IncomingMessage::room_id`](super::service_loop::IncomingMessage), + /// arrived in ([`IncomingMessage::room_id`](crate::cognition::conversation::IncomingMessage), /// already carried since A.6). /// /// Answering is room-targeted for the same reason perception is @@ -237,7 +237,7 @@ pub trait AircCitizen: /// The cards on `room`'s board that are takeable RIGHT NOW (Open, or held on a /// lapsed lease) per the ONE claimability decision - /// ([`crate::persona::card_holder::claimable_now`]). The pull reads THIS, not the + /// ([`crate::cognition::card_holder::claimable_now`]). The pull reads THIS, not the /// round tracker: the tracker never records a claim, so without board truth every /// idle resident would retry the first already-claimed card forever. Default is /// empty (nothing offered); the production runtime folds the room's board. @@ -246,7 +246,7 @@ pub trait AircCitizen: } /// How many cards on `room`'s board are IN FLIGHT — live holds in a holder's - /// column, per the ONE predicate ([`crate::persona::card_holder::in_flight_now`]). + /// column, per the ONE predicate ([`crate::cognition::card_holder::in_flight_now`]). /// The WIP = lanes gate counts this, never a tracker arithmetic. Fixture default: /// nothing in flight; the production runtime folds the room's board. async fn in_flight_cards_in(&self, _room: Uuid, _now_ms: u64) -> Result { diff --git a/core/continuum-mind/src/persona/airc_persona_conversation.rs b/core/continuum-mind/src/persona/airc_persona_conversation.rs index dc308195e5..8052642b69 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation.rs @@ -44,7 +44,7 @@ use continuum_base::time::EpochMs; use crate::persona::airc_citizen::AircCitizen; -use crate::persona::service_loop::{IncomingMessage, PersonaConversation}; +use crate::cognition::conversation::{IncomingMessage, PersonaConversation, CATCH_UP_PAGE, INBOX_CAPACITY}; use airc_core::TranscriptEvent; use airc_lib::FilteredEventStream; use async_trait::async_trait; @@ -56,7 +56,7 @@ use super::durable_history::event_from_row; mod polled; pub use polled::*; mod inbox_capacity; -pub(crate) use inbox_capacity::*; +use inbox_capacity::*; #[cfg(test)] mod tests; diff --git a/core/continuum-mind/src/persona/airc_persona_conversation/inbox_capacity.rs b/core/continuum-mind/src/persona/airc_persona_conversation/inbox_capacity.rs index a5dc6cedfd..729be4f4f9 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation/inbox_capacity.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation/inbox_capacity.rs @@ -1,9 +1,5 @@ use super::*; -/// In-process inbox depth between the pump and the loop. A turn in progress -/// can leave the loop away for minutes; 8k events is hours of a busy room. -pub(crate) const INBOX_CAPACITY: usize = 8_192; - /// The live stream is dead when a catch-up tick admits events from the store /// while no live frame arrived since the previous tick. The first tick after /// (re)open is exempt: it legitimately admits the backlog. @@ -304,7 +300,7 @@ impl AircPersonaConversation { impl PersonaConversation for AircPersonaConversation { fn take_wakes( &mut self, - ) -> Option> { + ) -> Option> { self.mind.as_mut().and_then(|m| m.wakes.take()) } @@ -383,8 +379,8 @@ impl PersonaConversation for AircPersonaConversation { // it is never published, so no airc channel (not even one named by the room's // uuid) ever carries it. Saying it to the room is publishing; that is her act. let me = self.own_peer_id; - if crate::persona::mind_room::is_private_room(me, room_id) { - crate::persona::mind_room::note_withheld(me, "speech"); + if crate::cognition::mind_room::is_private_room(me, room_id) { + crate::cognition::mind_room::note_withheld(me, "speech"); return Ok(()); } self.runtime @@ -394,6 +390,9 @@ impl PersonaConversation for AircPersonaConversation { .map_err(|e| format!("say failed: {e}")) } +} + +impl crate::persona::service_loop::CitizenConversation for AircPersonaConversation { /// #170: the airc citizen behind this conversation streams — hand the /// forwarder our runtime handle so it can publish ephemeral token chunks. fn stream_citizen( @@ -436,7 +435,7 @@ pub(super) fn perceptual_from_event(event: &TranscriptEvent) -> Result>, - pub(super) wake_tx: tokio::sync::mpsc::Sender, + pub(super) wake_tx: tokio::sync::mpsc::Sender, /// Her wakes until the loop's Wake consumer takes them (`take_wakes`). - pub(super) wakes: Option>, + pub(super) wakes: Option>, } impl MindFeed { @@ -52,7 +50,7 @@ impl MindFeed { // Her private continuation is never in mind-state.json; it is sealed in her mind // store (PRIVACY-OF-THOUGHT.md sink 10). Restore it when no open one was saved. if region.continuation().is_none() { - if let Some(private) = crate::persona::mind_room::sealed_continuation(persona) { + if let Some(private) = crate::persona::mind_store::sealed_continuation(persona) { region.restore_private_continuation(private, now); } } @@ -138,7 +136,7 @@ impl AttentionEvent { { return None; } - let perception = match crate::persona::room_event::room_work_from_event(&event) { + let perception = match crate::cognition::conversation::room_event::room_work_from_event(&event) { Ok(Some(work)) => Ok(IncomingMessage { event_id: event.event_id.as_uuid(), lamport: event.lamport, peer_id: event.peer_id.as_uuid(), room_id: event.room_id.as_uuid(), @@ -183,7 +181,7 @@ pub(super) fn signal_if_directed(own: uuid::Uuid, attention: &AttentionEvent) { .as_ref() .and_then(|r| r.get(own)) .map(|rt| { - crate::persona::persona_identity::PersonaIdentity::new(own, rt.agent_name().to_string()) + crate::cognition::conversation::persona_identity::PersonaIdentity::new(own, rt.agent_name().to_string()) }) .is_some_and(|me| me.mentions(&message.text)); let sender_is_human = crate::cognition::room_directory::is_human_peer(peer); diff --git a/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs b/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs index 491808562c..861f884ed0 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs @@ -47,7 +47,7 @@ // directed room message still passes below. let mut rpc = event("RPC result, not speech"); rpc.headers.insert(airc_protocol::HEADER_AIRC_CORRELATION_ID.into(), Uuid::new_v4().to_string()); - assert_eq!(crate::persona::room_event::room_turn_from_event(&rpc), Err("command_frame")); + assert_eq!(crate::cognition::conversation::room_event::room_turn_from_event(&rpc), Err("command_frame")); for _ in 0..CATCH_UP_PAGE * 2 { let mut telemetry = event(""); telemetry.kind = airc_core::TranscriptKind::System; @@ -138,7 +138,7 @@ review_event.headers = headers; review_event.body = Some(body); assert!(matches!(AttentionEvent::classify(Arc::new(review_event)).unwrap().perception.unwrap().work, - Some(crate::persona::room_event::RoomWork::Reviewed { .. }))); + Some(crate::cognition::conversation::room_event::RoomWork::Reviewed { .. }))); let work_id = work.event_id.as_uuid(); frames.push(Ok(Arc::new(work))); let mut directed = event("@citizen Shared Cargo owner: please wait"); @@ -171,7 +171,7 @@ let perceived = conversation.perceive_ready().await.unwrap(); assert_eq!(perceived.len(), 2); assert_eq!(perceived[0].event_id, work_id); - assert!(matches!(perceived[0].work, Some(crate::persona::room_event::RoomWork::StateChanged { .. }))); + assert!(matches!(perceived[0].work, Some(crate::cognition::conversation::room_event::RoomWork::StateChanged { .. }))); assert_eq!(perceived[1].event_id, directed.event_id.as_uuid()); assert_eq!(perceived[1].room_id, room); assert_eq!(perceived[1].peer_id, peer); @@ -257,7 +257,7 @@ airc.clone(), room, PersonaIdentitySource::FreshlyMinted, )); let conversation = AircPersonaConversation::new(runtime.clone()); - let mind = crate::persona::mind_room::mind_room_id(airc.peer_id().as_uuid()); + let mind = crate::cognition::mind_room::mind_room_id(airc.peer_id().as_uuid()); conversation.say_in(mind, "a private word").await.expect("said to herself, never published"); conversation.say_in(room.as_uuid(), "an open word").await.expect("an open room still publishes"); } diff --git a/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs b/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs index c3bcb4b678..391aeb6ab9 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs @@ -15,7 +15,7 @@ use super::*; text: "Joel here — which card do you hold?".to_string(), }; let mut with_media = row.clone(); - with_media.media.push(super::super::super::channel_items::MediaItemRequest { + with_media.media.push(crate::cognition::conversation::channel_items::MediaItemRequest { kind: "image".into(), mime_type: Some("image/png".into()), blob_hash: Some("sha256:1234".into()), url: None, description: None, }); @@ -28,7 +28,7 @@ use super::*; let incoming = perceptual_from_event(&media_event).expect("caption turn"); assert_eq!(incoming.text, row.text); assert_eq!(incoming.media.len(), 1); - let (sender, rendered) = crate::persona::room_event::room_turn_from_event(&media_event).unwrap(); + let (sender, rendered) = crate::cognition::conversation::room_event::room_turn_from_event(&media_event).unwrap(); let attention = AttentionEvent::classify(Arc::new(media_event.clone())).unwrap(); let classified = attention.perception.unwrap(); assert_eq!(SeenRooms::fingerprint(sender, &rendered), diff --git a/core/continuum-mind/src/persona/airc_runtime.rs b/core/continuum-mind/src/persona/airc_runtime.rs index 5246f33670..6c16b63e79 100644 --- a/core/continuum-mind/src/persona/airc_runtime.rs +++ b/core/continuum-mind/src/persona/airc_runtime.rs @@ -63,6 +63,8 @@ use tracing::{info, warn}; use uuid::Uuid; +use crate::cognition::card_holder::{held_of_owned, settled_card}; + mod citizen_commons_room; pub use citizen_commons_room::*; mod persona_airc_runtime; diff --git a/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime.rs b/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime.rs index 3b87ae89a1..cca3598250 100644 --- a/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime.rs +++ b/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime.rs @@ -321,7 +321,7 @@ impl PersonaAircRuntime { // (exactly the old cadence) until clean — degraded mode is the old // behavior, never a wider gap. let renewal_period = std::time::Duration::from_millis( - crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS / 6, + crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS / 6, ); let mut last_clean_renewal: Option = None; // Emit-on-transition for the renewal-denied probe: denial is a @@ -428,7 +428,7 @@ impl PersonaAircRuntime { crate::persona::cognition_pulse::work_idle_ms(hb_persona, None, now_ms); if !crate::persona::cognition_pulse::renewal_earned( idle, - crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, ) { if !renewal_denied { renewal_denied = true; @@ -445,7 +445,7 @@ impl PersonaAircRuntime { idle = %idle .map(|ms| ms.to_string()) .unwrap_or_else(|| "never-thought".to_string()), - ttl_ms = crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms = crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, "no cognition within one lease-length — renewals \ DENIED from here until she thinks again; holds \ lapse naturally so the work can be recovered" @@ -497,7 +497,7 @@ impl PersonaAircRuntime { Some(c.card_id.as_uuid()), now_ms, ), - crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, ) && c.owner == Some(me) && c.claim_expires_at_ms.is_some_and(|e| e <= now_ms) @@ -524,7 +524,7 @@ impl PersonaAircRuntime { .claim_work_card_with_provenance( airc_lib::ClaimWorkCard { card_id: card.card_id, - ttl_ms: crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms: crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, }, card.claim_provenance .as_ref() @@ -565,7 +565,7 @@ impl PersonaAircRuntime { Some(card.card_id.as_uuid()), EpochMs::now().millis(), ), - crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, ) { continue; } @@ -578,7 +578,7 @@ impl PersonaAircRuntime { airc_lib::HeartbeatWorkClaim { card_id: card.card_id, claim_id, - ttl_ms: crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms: crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, }, ) .await @@ -646,7 +646,7 @@ impl PersonaAircRuntime { Some(h.card_id), EpochMs::now().millis(), ), - crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, ) { continue; } @@ -656,7 +656,7 @@ impl PersonaAircRuntime { airc_lib::HeartbeatWorkClaim { card_id: airc_lib::WorkCardId::from_uuid(h.card_id), claim_id: airc_lib::ClaimId::from_uuid(h.claim_id), - ttl_ms: crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms: crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, }, ) .await @@ -698,7 +698,7 @@ impl PersonaAircRuntime { agent_name = %hb_name, renewed = renewed, held = mine.len(), - ttl_ms = crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS, + ttl_ms = crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS, "held work-card claims renewed on the claim cadence (TTL/3)" ); } diff --git a/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime_2.rs b/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime_2.rs index f99aae9cbd..63806891fc 100644 --- a/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime_2.rs +++ b/core/continuum-mind/src/persona/airc_runtime/persona_airc_runtime_2.rs @@ -198,11 +198,11 @@ impl PersonaAircRuntime { // peers (human, web, browser). See `persona::airc_citizen` for the // trait definition + rationale. #[async_trait::async_trait] -impl crate::persona::airc_source::AircTranscriptReader for PersonaAircRuntime { +impl crate::cognition::conversation::transcript_reader::AircTranscriptReader for PersonaAircRuntime { async fn page_recent(&self, limit: usize) -> Result, AircError> { // Route through the ONE kinds-filtered impl on `airc_lib::Airc` // (persona/airc_source.rs, #297) — never the raw inherent page. - crate::persona::airc_source::AircTranscriptReader::page_recent(&*self.airc, limit).await + crate::cognition::conversation::transcript_reader::AircTranscriptReader::page_recent(&*self.airc, limit).await } async fn page_recent_in( @@ -212,7 +212,7 @@ impl crate::persona::airc_source::AircTranscriptReader for PersonaAircRuntime { ) -> Result, AircError> { // Explicit forward (#367) — inheriting the trait default here would // silently drop the turn-room scope (#262-class regression). - crate::persona::airc_source::AircTranscriptReader::page_recent_in(&*self.airc, room, limit) + crate::cognition::conversation::transcript_reader::AircTranscriptReader::page_recent_in(&*self.airc, room, limit) .await } } @@ -468,7 +468,7 @@ impl crate::persona::airc_citizen::AircCitizen for PersonaAircRuntime { .as_ref() .is_some_and(|r| r.get(o.as_uuid()).is_some()) }); - crate::persona::card_holder::claimable_by(c, now_ms, me, owner_resident) + crate::cognition::card_holder::claimable_by(c, now_ms, me, owner_resident) }) // A card whose instance carries a STANDING ENV refusal on this box (the // harness cannot grade it: era-pinned pytest, repo will not install, @@ -477,7 +477,7 @@ impl crate::persona::airc_citizen::AircCitizen for PersonaAircRuntime { // cards already on a board — psf__requests-1766 (2026-09-13): refused // ungradeable at 09:36, closed, reopened by its closer at 16:27, pulled by // Kira at 17:15 → a lane spent on work no grade can ever score. - .filter(|c| !crate::persona::card_holder::refused_on_this_box(&c.title)) + .filter(|c| !crate::cognition::card_holder::refused_on_this_box(&c.title)) // A review card is never offered to the owner of the card it reviews: // the reviewer is the fresh pair of eyes by construction. .filter(|c| { @@ -508,7 +508,7 @@ impl crate::persona::airc_citizen::AircCitizen for PersonaAircRuntime { .map(|r| r.iter().map(|rt| rt.airc().peer_id()).collect()) .unwrap_or_default(); // unwrap_or: no registry yet = only me holds here holders.insert(self.airc.peer_id()); - Ok(crate::persona::card_holder::in_flight_by( + Ok(crate::cognition::card_holder::in_flight_by( &board.cards, &holders, now_ms, @@ -537,32 +537,6 @@ pub(crate) async fn scoped_board_held_by( Ok(held_of_owned(scoped_board_owned_by(airc).await?, now_ms)) } -/// A card whose work is over (merged or closed): never held, never renewed, whatever its -/// claim fields still say. The one rule for the walk and the followed claims alike. -pub(super) fn settled_card(state: &airc_work::model::CardState) -> bool { - matches!(state, airc_work::model::CardState::Closed | airc_work::model::CardState::Merged) -} - -/// The HELD subset of an owned walk: lease live, not claimable, not settled. Split from the -/// walk so one board read can feed both the renewal (holds) and the handoff record (all of -/// what she owns, whole) — never two walks for one seam. -pub fn held_of_owned( - owned: Vec<(airc_lib::Room, airc_lib::WorkCard)>, - now_ms: u64, -) -> Vec<(airc_lib::Room, airc_lib::WorkCard)> { - owned - .into_iter() - .filter(|(_, card)| { - // A settled card is nobody's work, whatever its lease says: a closed card - // whose claim fields outlive the close read as HELD, focused her ticks on a - // finished room and made the pull think she had work (2026-09-13 14:0xZ). - !settled_card(&card.state) && crate::persona::card_holder::hold_of(card, now_ms) - == crate::persona::card_holder::Hold::Held - && !crate::persona::card_holder::claimable_now(card, now_ms) - }) - .collect() -} - /// Every card the boards she stands in show with owner = her, in ANY state, whole, with its /// room. The one walk; `scoped_board_held_by` is its held filter. pub async fn scoped_board_owned_by( diff --git a/core/continuum-mind/src/persona/airc_runtime_registry.rs b/core/continuum-mind/src/persona/airc_runtime_registry.rs index 4f5561277d..cee573c4a1 100644 --- a/core/continuum-mind/src/persona/airc_runtime_registry.rs +++ b/core/continuum-mind/src/persona/airc_runtime_registry.rs @@ -626,6 +626,23 @@ pub(crate) fn resident_from_loop_state(loop_finished: Option) -> bool { matches!(loop_finished, Some(false)) } +// ─── The channel-digest region reads her transcript and room through this registry ── + +impl crate::cognition::channel_digest_region::PersonaChannelReader for PersonaAircRuntimeRegistry { + fn live_personas(&self) -> Vec { + // Inherent method of the same name; qualify to avoid trait/inherent ambiguity. + PersonaAircRuntimeRegistry::live_personas(self) + } + + fn reader_and_room(&self, persona_id: Uuid) -> Option<(Arc, Uuid)> { + let runtime = self.get(persona_id)?; + let room = runtime.default_room().as_uuid(); + // PersonaAircRuntime: AircTranscriptReader — upcast the Arc. + let reader: Arc = runtime; + Some((reader, room)) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/core/continuum-mind/src/persona/airc_source.rs b/core/continuum-mind/src/persona/airc_source.rs index dd8aa2a48a..a63293d1e1 100644 --- a/core/continuum-mind/src/persona/airc_source.rs +++ b/core/continuum-mind/src/persona/airc_source.rs @@ -28,7 +28,6 @@ use std::sync::Arc; use airc_core::TranscriptEvent; -use airc_lib::AircError; use async_trait::async_trait; use crate::cognition::channel_digest::{ChannelDigest, ChannelDigestBuilder, DEFAULT_GROUNDING}; @@ -41,6 +40,7 @@ use crate::cognition::rag_budget::{ RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, }; use crate::runtime::ready_buffer::ReadyBuffer; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; use crate::cognition::faculty_ids::AIRC; @@ -54,153 +54,6 @@ const FETCH_LIMIT: usize = 100; use continuum_base::token_estimate::estimate_prompt_tokens as estimate_tokens; use crate::cognition::token_budget::head_to_tokens; -/// Abstract reader over airc transcript events. Production impl rides on -/// `airc_lib::Airc`; tests use a stub that returns canned events without a daemon. -#[async_trait] -pub trait AircTranscriptReader: Send + Sync { - /// Return up to `limit` most-recent CONVERSATIONAL transcript events - /// (Message + Attachment), newest-first per airc convention. - /// - /// Kinds are filtered BEFORE the page limit (#297): a raw newest-`limit` - /// page counts ephemeral StreamChunk frames (~4/sec per talking persona), - /// so active residents' own streaming evicted every durable message from - /// their window within a minute — working personas were DEAF to direction - /// while the room was busy (glass-boxed live 2026-08-01: a resident asked - /// the same question 3× because four direction messages never entered her - /// page while the attach cursor advanced normally). The diagnostic - /// signature: cross-machine delivery perfect, local perception stale — - /// the wire is fine, the WINDOW is flooded. Presence / receipts / - /// lifecycle ride their own sources; this page is the room's - /// conversation, never its firehose. - async fn page_recent(&self, limit: usize) -> Result, AircError>; - - /// Room-scoped page (#367): return the same conversational page, but for - /// the given room when `Some` — the TURN's room, not the reader's - /// current-room pointer. `page_recent` follows the persona's landing-room - /// pointer, so a turn happening anywhere else (a bench room, a project - /// room she is subscribed to but not "in") paged the DEFAULT room's - /// transcript — and everything downstream (digest, derived-room fallback, - /// the recall query built from this window) followed the wrong room. - /// - /// Default impl ignores `room` and delegates — correct ONLY for test - /// stubs whose canned events have no room dimension. Every production - /// reader overrides this (the #262 lesson in `AircHandleAdapter`: a - /// silently-inherited default is how regressions ship). - async fn page_recent_in( - &self, - room: Option, - limit: usize, - ) -> Result, AircError> { - let _ = room; - self.page_recent(limit).await - } - - /// This reader's last-read lamport in `room` — the unread marker. - /// - /// THE CURSOR LIVES IN AIRC. It is durable runtime-consumer state - /// (`runtime_cursor`, an ORM row keyed by consumer id), and airc's own API - /// doc says why it exists: "intentionally store-backed so runtime delivery - /// state does not sprawl into JSON sidecars." Continuum previously kept a - /// PARALLEL `ChannelBookmarks` DashMap for this — process-memory only, so - /// every cursor died on restart, and a second source of truth for a fact - /// airc already owns. That is the defect this method removes. - /// - /// `0` = never read. Real airc lamports are >= 1. - async fn read_cursor(&self, persona: uuid::Uuid, room: uuid::Uuid) -> Result { - let _ = (persona, room); - Ok(0) - } - - /// Persist this reader's position in `room` at `event` — mark-read. - /// - /// Takes the EVENT, not a bare lamport, because airc's preferred path - /// (`save_runtime_cursor_for_event`) carries the source event's room and - /// kind and emits `SubscriptionAdvanced`, so a cursor move is visible to - /// every other surface instead of being private to one process. A bare - /// lamport would throw that away. - async fn advance_read_cursor( - &self, - persona: uuid::Uuid, - room: uuid::Uuid, - event: &TranscriptEvent, - ) -> Result<(), AircError> { - let _ = (persona, room, event); - Ok(()) - } -} - -/// The durable consumer id for one reader's position in one room. -/// -/// Namespaced string because that IS airc's convention for `runtime_cursor` -/// (its own rows look like `codex-hook:default`); the entity is keyed by a -/// consumer id, so this composes airc's key, it does not invent an identifier. -/// Both halves are rendered from real UUIDs — never a name, never a label. -pub fn read_cursor_consumer_id(persona: uuid::Uuid, room: uuid::Uuid) -> String { - format!("persona:{persona}:room:{room}") -} - -/// The kinds a perception page means: the room's conversation. ONE place -/// (compression) — every reader impl funnels through the [`airc_lib::Airc`] -/// impl below, which applies this filter. -pub fn perception_page_filter() -> airc_lib::EventFilter { - let mut filter = airc_lib::EventFilter::current_room(); - filter.kinds.insert(airc_core::TranscriptKind::Message); - filter.kinds.insert(airc_core::TranscriptKind::Attachment); - filter -} - -/// The same conversational-kinds filter, pinned to a specific room (#367). -/// `None` leaves the channel unset, which `page_recent_filtered` scopes to -/// the current room — the pre-#367 behavior, still right for genuinely -/// room-less work. -pub fn perception_page_filter_in(room: Option) -> airc_lib::EventFilter { - let mut filter = perception_page_filter(); - filter.channel = room; - filter -} - -/// `airc_lib::Airc` satisfies the reader contract via the kinds-filtered -/// page (daemon-side newest-N-of-kind since airc PR #1314). Orphan rule OK — -/// the trait is ours. -#[async_trait] -impl AircTranscriptReader for airc_lib::Airc { - async fn page_recent(&self, limit: usize) -> Result, AircError> { - airc_lib::Airc::page_recent_filtered(self, perception_page_filter(), limit).await - } - - async fn page_recent_in( - &self, - room: Option, - limit: usize, - ) -> Result, AircError> { - airc_lib::Airc::page_recent_filtered(self, perception_page_filter_in(room), limit).await - } - - /// airc's durable `runtime_cursor` row IS the unread marker — no second store. - async fn read_cursor(&self, persona: uuid::Uuid, room: uuid::Uuid) -> Result { - Ok( - airc_lib::Airc::load_runtime_cursor(self, &read_cursor_consumer_id(persona, room)) - .await? - .map(|c| c.lamport) - .unwrap_or(0), - ) - } - - async fn advance_read_cursor( - &self, - persona: uuid::Uuid, - room: uuid::Uuid, - event: &TranscriptEvent, - ) -> Result<(), AircError> { - airc_lib::Airc::save_runtime_cursor_for_event( - self, - &read_cursor_consumer_id(persona, room), - event, - ) - .await - } -} - /// Persona-bound source delivering the consolidated channel digest. pub struct AircRagSource { persona_id: uuid::Uuid, @@ -752,7 +605,7 @@ impl RagSource for AircRagSource { .iter() .filter(|e| e.room_id.as_uuid() == room_id) .filter_map(|e| { - crate::persona::room_event::room_content_from_event(e) + crate::cognition::conversation::room_event::room_content_from_event(e) .ok() .map(|turn| (turn.sender, turn.text, turn.media)) }) diff --git a/core/continuum-mind/src/persona/airc_source/tests.rs b/core/continuum-mind/src/persona/airc_source/tests.rs index e574ba7142..0a6a86f968 100644 --- a/core/continuum-mind/src/persona/airc_source/tests.rs +++ b/core/continuum-mind/src/persona/airc_source/tests.rs @@ -1,5 +1,6 @@ #![cfg(test)] use super::*; + use airc_lib::AircError; use crate::cognition::channel_element::ChannelElementCache; use crate::ai::embedding::EmbeddingProvider; use crate::runtime::ready_buffer::DashMapReadyBuffer; diff --git a/core/continuum-mind/src/persona/awareness.rs b/core/continuum-mind/src/persona/awareness.rs index 15fd83e10c..7442f5d285 100644 --- a/core/continuum-mind/src/persona/awareness.rs +++ b/core/continuum-mind/src/persona/awareness.rs @@ -13,8 +13,8 @@ use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::attention::{AttentionDial, Continuation}; -use super::salience::{Salience, SalienceLevel}; +use crate::cognition::attention::{AttentionDial, Continuation}; +use crate::cognition::conversation::salience::{Salience, SalienceLevel}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ActivityLine { @@ -147,7 +147,7 @@ impl AwarenessSnapshot { /// reaches a public turn's prompt or capture. pub fn render_lines_in(&self, persona: Uuid, room: Option) -> Vec { self.render_with(|c| { - !crate::persona::mind_room::is_private_room(persona, c.activity) || room == Some(c.activity) + !crate::cognition::mind_room::is_private_room(persona, c.activity) || room == Some(c.activity) }) } @@ -187,8 +187,8 @@ fn short8(id: Uuid) -> String { id.to_string()[..8].to_string() } -fn reason_word(r: &super::salience::SalienceReason) -> &'static str { - use super::salience::SalienceReason::*; +fn reason_word(r: &crate::cognition::conversation::salience::SalienceReason) -> &'static str { + use crate::cognition::conversation::salience::SalienceReason::*; match r { MentionedMe { .. } => "mentioned you", HumanSpoke { .. } => "a human spoke", @@ -204,7 +204,7 @@ fn reason_word(r: &super::salience::SalienceReason) -> &'static str { #[cfg(test)] mod tests { use super::*; - use crate::persona::salience::SalienceReason; + use crate::cognition::conversation::salience::SalienceReason; fn line(name: &str, level: SalienceLevel, unread: u32, at: u64) -> ActivityLine { ActivityLine { @@ -300,7 +300,7 @@ mod tests { #[test] fn a_private_continuation_shows_its_note_only_in_her_mind_room() { let her = Uuid::new_v4(); - let mind = crate::persona::mind_room::mind_room_id(her); + let mind = crate::cognition::mind_room::mind_room_id(her); let c = Continuation { activity: mind, note: "a private plan".into(), expectation: None, written_at_ms: 0 }; let snap = fold(vec![], Some(c), AttentionDial::default(), 1_000, 1); let public = snap.render_lines_in(her, Some(Uuid::new_v4())); diff --git a/core/continuum-mind/src/persona/card_carry.rs b/core/continuum-mind/src/persona/card_carry.rs index a2fc2f8021..f25dc8e8ab 100644 --- a/core/continuum-mind/src/persona/card_carry.rs +++ b/core/continuum-mind/src/persona/card_carry.rs @@ -37,7 +37,7 @@ pub async fn sweep() -> usize { continue; }; let name = runtime.agent_name().to_string(); - for card in held.iter().filter(|c| crate::persona::card_holder::hold_of(c, now_ms) == crate::persona::card_holder::Hold::Held) { + for card in held.iter().filter(|c| crate::cognition::card_holder::hold_of(c, now_ms) == crate::cognition::card_holder::Hold::Held) { let Some(claim) = card.claim_id else { continue }; let Some(root) = crate::persona::card_checkout::checkout_path_for(&persona, card) else { continue }; let context = crate::identity::hands_context::HandsContext::for_claim(persona, card.card_id.as_uuid(), claim.as_uuid()); diff --git a/core/continuum-mind/src/cognition/persona_workspace/acting_hands.rs b/core/continuum-mind/src/persona/card_hands.rs similarity index 54% rename from core/continuum-mind/src/cognition/persona_workspace/acting_hands.rs rename to core/continuum-mind/src/persona/card_hands.rs index 662dbfba50..0c09cd361f 100644 --- a/core/continuum-mind/src/cognition/persona_workspace/acting_hands.rs +++ b/core/continuum-mind/src/persona/card_hands.rs @@ -1,274 +1,20 @@ -use super::*; - -/// A persona's HANDS, lifted out of the cycle that owns them. -/// -/// Exists because rooting a measurement fork's workspace is a PROCESS-GLOBAL side effect that -/// must be undone after the cycle it was taken for is gone. `code/create-workspace` keys the -/// file engine on the CALLER identity (`caller_id(ctx)` → the persona's peer id), and the -/// engines live in one `DashMap` for the whole runtime — while a measurement fork shares the -/// living persona's `Arc` and her id. So re-rooting "the fork's" hands -/// re-roots the LIVING persona's hands, and nothing put them back. -/// -/// That is #312, measured 2026-08-04: after a SWE-bench solve on a flask clone, Anwen's LIVE -/// self ran `code/list(path=src)` → `flask/` and `code/read(src/flask/app.py)` in her ordinary -/// room turns, hours later. She had been left standing in the exam room. -/// -/// Carrying `(id, name, executor)` separately from the cycle is what makes the restore -/// possible on every exit path: the cycle gets consumed by `with_capture`, moved into the -/// drive, or dropped on an error — the hands handle outlives all of it. -#[derive(Clone)] -pub struct ActingHands { - pub persona_id: Uuid, - pub persona_name: String, - pub executor: Arc, - /// Her working memory: the restore clears the receipt scope the rooting set. - pub working_memory: Arc, - /// Which of her hands these are: `None` her live ones, `Some` an eval's or a fork's own - /// (`ToolExecutor::hands_context`). Rooting and restore act on THESE hands only. - pub context: Option, -} - -impl ActingHands { - /// The hands of a cycle that has them; `None` for a pure-cognition (handless) cycle. - pub fn of(cycle: &WorkspaceCycle) -> Option { - cycle.acting().map(|a| Self { - persona_id: a.persona_id, - persona_name: a.persona_name.clone(), - executor: a.executor.clone(), - working_memory: a.working_memory.clone(), - context: a.executor.hands_context(), - }) - } - - /// The same persona's hands in `context`, a context these hands don't own (a card - /// claim's): `None` when her executor can't act in a context. - pub fn in_context(&self, context: crate::identity::hands_context::HandsContext) -> Option { - Some(Self { - executor: self.executor.in_hands(self.persona_id, context)?, - context: Some(context), - ..self.clone() - }) - } - -} - -/// Drive `code/create-workspace` through the persona's OWN identity-bearing executor — -/// the single place either direction (root for a measurement, restore afterward) goes -/// through, so the ACL gate and the failure shape are identical for both -/// ([[the-compression-principle]]). -pub async fn drive_create_workspace( - hands: &ActingHands, - root: &str, - path_prepend: &[String], - call_id: &str, - refuse_inert_edits: bool, -) -> Result<(), crate::sdk_codegen::CommandError> { - let ws_ctx = crate::cognition::tool_executor::ToolExecutionContext { - persona_id: hands.persona_id, - persona_name: hands.persona_name.clone(), - session_id: Uuid::new_v4(), - context_id: Uuid::new_v4(), - caller_context: serde_json::Value::Null, - persona_config: crate::cognition::tool_executor::PersonaMediaConfigLite { - auto_load_media: false, - supported_media_types: vec![], - }, - }; - let ws_call = crate::ai::types::ToolCall { - id: call_id.to_string(), - name: "code/create-workspace".to_string(), - input: serde_json::json!({ - "workspace_root": root, - "path_prepend": path_prepend, - "refuse_inert_edits": refuse_inert_edits, - }), - }; - let ws_out = hands - .executor - .execute_native_batch(std::slice::from_ref(&ws_call), &ws_ctx, 8000) - .await - .map_err(|e| { - crate::sdk_codegen::CommandError::Internal(format!( - "failed to root workspace at '{root}': {e}" - )) - })?; - if let Some(r) = ws_out.results.first() { - if r.is_error.is_some() { - return Err(crate::sdk_codegen::CommandError::Internal(format!( - "code/create-workspace rejected workspace_root '{root}': {} — refusing to run with \ - the persona's hands rooted at the wrong directory (would score a false zero).", - r.content - ))); - } - } - Ok(()) -} - -/// WHERE HER HANDS STAND: the root a work turn rooted a set of her hands at (a card's -/// checkout), or nothing when they stand in her own workspace. Keyed by persona AND acting -/// context, so an eval's or a fork's place is its own and never overwrites her live one -/// (docs/architecture/HER-HANDS.md). Her live place (`None` context) is the one truth for the -/// workspace map she perceives and the scope her receipts carry; set at the rooting seam, -/// cleared on restore. -pub(super) static ACTING_ROOTS: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); - -/// Whose place: the persona, and which of her hands (`None` = live). -pub(super) type ActingKey = (uuid::Uuid, Option); - -/// Where she stands: the checkout root, and the card whose checkout it is when -/// a held card rooted her (None for a plain workspace_root). -#[derive(Clone, Debug)] -pub(super) struct ActingPlace { - pub(super) root: std::path::PathBuf, - pub(super) card: Option, -} - -/// The card-claim context her perception follows: the one her latest turn was bound to, or -/// none (her default hands, at home). Only WHICH hands she looks through changes; no hands' -/// place ever moves (card fc9e9fd7). Set by [`root_at_held_card`], cleared when that -/// claim's hands close. -pub(super) static FOCUS: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); - -pub(super) fn focus_of(persona_id: uuid::Uuid) -> Option { - FOCUS.lock().unwrap_or_else(|e| e.into_inner()).get(&persona_id).copied() // poisoned lock = read the last state, same policy as every lock in this crate -} - -/// Point her perception at `context` (or home). The map she perceives re-renders when it moved. -pub fn set_focus(persona_id: uuid::Uuid, context: Option) { - let moved = { - let mut map = FOCUS.lock().unwrap_or_else(|e| e.into_inner()); // poisoned lock = read the last state, same policy as every lock in this crate - let before = match context { - Some(c) => map.insert(persona_id, c), - None => map.remove(&persona_id), - }; - before != context - }; - if moved { - crate::persona::grounding_invalidation::mark_workspace_map_dirty(persona_id); - } - if context.is_none() { - crate::cognition::handoff::note_unbound(persona_id); - } -} - -/// Where the hands she is focused on stand (what she perceives and what her receipts are -/// scoped to): her current card claim's checkout, or nothing when she is at home. -pub fn acting_root_of(persona_id: uuid::Uuid) -> Option { - acting_root_in(persona_id, focus_of(persona_id)) -} - -/// Where one set of her hands stands: her live ones (`None`) or a context's. -pub fn acting_root_in(persona_id: uuid::Uuid, context: Option) -> Option { - ACTING_ROOTS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(&(persona_id, context)) - .map(|p| p.root.clone()) // poisoned lock = read the last state, same policy as every lock in this crate -} - -/// The card her hands are rooted at, if a held card rooted them. Her work -/// receipts radiate into THAT card's activity room, not the room whose line -/// happened to trigger the turn (2026-09-04: every holder's 💭/⚙ lines landed -/// in #academy — the base room and the agents' coordination room — because the -/// trigger arrived there; the run room stayed empty for its reviewer). -pub fn acting_card_of(persona_id: uuid::Uuid) -> Option { - acting_card_in(persona_id, focus_of(persona_id)) -} - -/// The card one set of her hands is rooted at: her live ones (`None`) or a context's. -pub fn acting_card_in(persona_id: uuid::Uuid, context: Option) -> Option { - ACTING_ROOTS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(&(persona_id, context)) - .and_then(|p| p.card) // poisoned lock = read the last state, same policy as every lock in this crate -} - -pub fn note_acting_card_in(persona_id: uuid::Uuid, context: Option, card: uuid::Uuid) { - if let Some(place) = ACTING_ROOTS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get_mut(&(persona_id, context)) - { - // poisoned lock = read the last state, same policy as every lock in this crate - place.card = Some(card); - } -} - -pub fn note_acting_root_in( - persona_id: uuid::Uuid, - context: Option, - root: Option, -) { - { - let mut map = ACTING_ROOTS.lock().unwrap_or_else(|e| e.into_inner()); // poisoned lock = read the last state, same policy as every lock in this crate - match root { - Some(r) => { - map.insert( - (persona_id, context), - ActingPlace { - root: r, - card: None, - }, - ); - } - None => { - map.remove(&(persona_id, context)); - } - } - } - // The map she perceives is the place of the hands she is focused on; an eval or a fork - // placing its own hands changes nothing she perceives. - let marked = context == focus_of(persona_id) && crate::persona::grounding_invalidation::mark_workspace_map_dirty(persona_id); - continuum_base::probe!( - class = "workspace.acting_root", - persona_id = %persona_id, - context = %context.map(|c| c.id().to_string()).unwrap_or_else(|| "live".to_string()), // unwrap_or_else: no context = her live hands, named - root = %acting_root_in(persona_id, context).map(|p| p.display().to_string()).unwrap_or_default(), // unwrap_or: nothing recorded / a pre-epoch clock = 0, never a guess - map_marked_dirty = marked, - "where this set of her hands stands now; her live map re-renders only when her live hands moved" - ); -} - -/// What the board says became of a card she believed she held, from the ONE holder -/// projection the board itself renders (`card_holder`). PURE, so every branch is pinned: -/// a live lease held by `her` → `None` (the card IS hers — a renewal or re-claim landed -/// between the wake's two reads, nothing is gone); a live lease that is not hers → -/// `HeldBy`; a card past the claimable states → `MovedOn` (its life advanced, not a -/// lapse); otherwise `Lapsed` — the last lease, whoever's, ran out and nobody holds it. -/// `owner` is never read as authority: an expired claim still names its last holder, and -/// that holder may be her. -pub(crate) fn claim_gone_verdict( - card: &airc_lib::WorkCard, - now_ms: u64, - her: uuid::Uuid, -) -> Option { - use crate::cognition::working_memory::ClaimGone; - use crate::persona::card_holder::{hold_of, refused_by_claim, Hold}; - if refused_by_claim(card.state) { - return Some(ClaimGone::MovedOn { - state: crate::persona::work_board::facts::state_str(&card.state), - }); - } - let expired_at_ms = card.claim_expires_at_ms; - Some(match hold_of(card, now_ms) { - Hold::Held => match card.owner { - Some(peer) if peer.as_uuid() == her => return None, - Some(peer) => ClaimGone::HeldBy { - peer: peer.as_uuid(), - expires_at_ms: expired_at_ms, - }, - // A live hold with no owner cannot be rendered by the board either; say - // lapsed-and-open rather than invent a holder. - None => ClaimGone::Lapsed { expired_at_ms }, - }, - Hold::Lapsed | Hold::Unclaimed => ClaimGone::Lapsed { expired_at_ms }, - }) -} +//! Binding a turn to the hands of the card claim she works (card fc9e9fd7): the board half of +//! her hands, moved up out of cognition (mind split, Peel D). It reads her claims through her +//! airc citizen, stages the card's checkout, roots the claim's hands once through cognition's +//! hands (`cognition::persona_workspace`), carries the turn's credit beside them, and at the +//! turn's end carries the card's work. Cognition keeps where her hands stand; persona knows +//! which card they are for. + +use continuum_base::time::EpochMs; +use uuid::Uuid; + +use crate::cognition::persona_workspace::{ + acting_card_in, acting_root_in, claim_gone_verdict, close_acting_context, claim_has_ended, claimed_places_of, drive_create_workspace, focus_of, + note_acting_card_in, note_acting_root_in, set_focus, ActingHands, +}; +use crate::cognition::workspace::WorkspaceCycle; +use crate::identity::hands_context::HandsContext; +use crate::persona::service_loop::CitizenConversation; /// Bind THIS turn to the hands of her held card's claim, standing in the card's staged /// checkout — any turn, not only the work turn. Freya (2026-09-05) edited a file during a @@ -280,7 +26,7 @@ pub(crate) fn claim_gone_verdict( pub(crate) async fn root_at_held_card( cycle: &WorkspaceCycle, peer_id: uuid::Uuid, - conversation: &dyn crate::persona::service_loop::PersonaConversation, + conversation: &dyn CitizenConversation, ) -> HeldCardTurn { let turn = bind_held_card(cycle, peer_id, conversation).await; // A turn bound to no claim's hands acts with her default hands, at home: her @@ -291,10 +37,10 @@ pub(crate) async fn root_at_held_card( turn } -pub(super) async fn bind_held_card( +pub(crate) async fn bind_held_card( cycle: &WorkspaceCycle, peer_id: uuid::Uuid, - conversation: &dyn crate::persona::service_loop::PersonaConversation, + conversation: &dyn CitizenConversation, ) -> HeldCardTurn { // The card is UNKNOWN on each of these: there is no citizen, her claims could not be // read, or she holds nothing. Absent credit is the honest answer here — unlike the @@ -357,9 +103,9 @@ pub(super) async fn bind_held_card( // The hands of every claim she no longer holds close, whether or not a card is // bound this turn. if let Some(live) = ActingHands::of(cycle) { - let held_contexts: Vec = held + let held_contexts: Vec = held .iter() - .filter_map(|c| c.claim_id.map(|claim| crate::identity::hands_context::HandsContext::for_claim(peer_id, c.card_id.as_uuid(), claim.as_uuid()))) + .filter_map(|c| c.claim_id.map(|claim| HandsContext::for_claim(peer_id, c.card_id.as_uuid(), claim.as_uuid()))) .collect(); close_ended_claims(&live, &held_contexts, citizen.as_ref(), peer_id).await; } @@ -376,34 +122,6 @@ pub(super) async fn bind_held_card( bind_card(cycle, peer_id, focus).await } -/// The activity this step perceives and acts IN: the board room of the card her hands are rooted on, by -/// the one definition of "which board holds a card" (`modules::work::room_holding_card`, -/// any activity, project or benchmark); else the room the turn was woken in. The wake room -/// is a fallback for acts with no subject yet (a help call before she has chosen a task), -/// never an override of one. It's the card of THESE hands (`context`): an eval's or a fork's -/// acts never inherit her live card's room (Astra's review of #5005). -pub(crate) async fn activity_room_for( - persona_id: Uuid, - context: Option, - wake_room: Uuid, -) -> Uuid { - if crate::persona::mind_room::is_private_room(persona_id, wake_room) { - return wake_room; - } - let Some(card) = acting_card_in(persona_id, context) else { - return wake_room; - }; - let Some(runtime) = crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry::try_global() - .and_then(|registry| registry.get(persona_id)) - else { - return wake_room; - }; - match crate::persona::work_board::horizon::room_holding_card(runtime.airc(), airc_lib::WorkCardId::from_uuid(card)).await { - Some(room) => room.channel.as_uuid(), - None => wake_room, - } -} - /// Bind a turn to the hands of `card`'s claim (card fc9e9fd7): THE one binding both the /// room turn ([`root_at_held_card`]) and the held-work turn use. Resolves the card's /// checkout through the one owner of where a card's work lives @@ -477,7 +195,7 @@ pub async fn bind_card( ); return HeldCardTurn::unrooted(credit, peer_id, focus.card_id.as_uuid()); }; - let context = crate::identity::hands_context::HandsContext::for_claim(peer_id, focus.card_id.as_uuid(), claim.as_uuid()); + let context = HandsContext::for_claim(peer_id, focus.card_id.as_uuid(), claim.as_uuid()); let Some(hands) = live.in_context(context) else { return HeldCardTurn::unrooted(credit, peer_id, focus.card_id.as_uuid()); }; @@ -529,15 +247,65 @@ pub async fn bind_card( } } +/// Close the hands of every card claim whose claim ENDED ([`claim_has_ended`], read from +/// each card's own row): released, terminal, or re-acquired as a new claim. A claim missing +/// from her active claims is only a candidate; a lapsed lease or an unreadable row keeps its +/// hands. Each close runs in the background, refusing new turns and waiting out admitted +/// ones, then releases its engine and shells. +pub(crate) async fn close_ended_claims( + live: &ActingHands, + held: &[HandsContext], + citizen: &dyn crate::persona::airc_citizen::AircCitizen, + her: uuid::Uuid, +) { + let candidates: Vec<(HandsContext, uuid::Uuid)> = claimed_places_of(live.persona_id) + .into_iter() + .filter(|(context, _)| !held.contains(context)) + .collect(); + let mut ended = Vec::new(); + for (context, card) in candidates { + let row = citizen.card(card).await; + if claim_has_ended(context, row.as_ref(), her) { + ended.push(context); + } else { + continuum_base::probe!( + class = "persona.work.hands_kept", + peer = %her, + card = %card, + row_read = row.is_some(), + "a claim missing from her active claims has not ENDED (lapsed lease or unread row); its hands stay open" + ); + } + } + for context in ended { + let Some(hands) = live.in_context(context) else { continue }; + tokio::spawn(async move { + // The release closes the hands to new work and waits out admitted work itself. + let root = acting_root_in(hands.persona_id, Some(context)); + match close_acting_context(&hands).await { + Ok(()) => { + if let Some(root) = root { + crate::persona::workspace_transfer::forget_checkout(&root); + } + if focus_of(hands.persona_id) == Some(context) { + set_focus(hands.persona_id, None); + } + } + Err(e) => tracing::warn!(error = %e, context = %context.id(), "a card claim's hands could not be released; they are kept closed for a retry"), + } + }); + } +} + /// The checkout each citizen was last TOLD her hands stand in (card 822c4253). Process /// memory: after a restart she is told once more, which costs one pinned line. -pub(super) static ANNOUNCED_ROOTS: std::sync::LazyLock< +pub(crate) static ANNOUNCED_ROOTS: std::sync::LazyLock< std::sync::Mutex>, > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); /// Whether `root` is the checkout she was last told about. A per-turn rooting at the /// same checkout says nothing. -pub(super) fn already_told(persona_id: uuid::Uuid, root: &std::path::Path) -> bool { +pub(crate) fn already_told(persona_id: uuid::Uuid, root: &std::path::Path) -> bool { ANNOUNCED_ROOTS .lock() .unwrap_or_else(|e| e.into_inner()) // poisoned lock = read the last state, same policy as every lock in this crate @@ -546,7 +314,7 @@ pub(super) fn already_told(persona_id: uuid::Uuid, root: &std::path::Path) -> bo } /// Record `root` as told, once the line naming it is pinned in her window. -pub(super) fn mark_told(persona_id: uuid::Uuid, root: &std::path::Path) { +pub(crate) fn mark_told(persona_id: uuid::Uuid, root: &std::path::Path) { ANNOUNCED_ROOTS .lock() .unwrap_or_else(|e| e.into_inner()) // poisoned lock = read the last state, same policy as every lock in this crate @@ -556,7 +324,7 @@ pub(super) fn mark_told(persona_id: uuid::Uuid, root: &std::path::Path) { /// PURE: the line that tells her where her hands now stand and what did not move. The /// branch is the card's EXPECTED branch (derived from the card), never asserted as the /// checked-out HEAD, which an existing tree may have moved (Codex on #4555). -pub(super) fn rooted_notice(repo: &str, root: &std::path::Path, branch: &str) -> String { +pub(crate) fn rooted_notice(repo: &str, root: &std::path::Path, branch: &str) -> String { format!( "[workspace] For your held card on {repo}, your hands now stand in its own checkout: \ {root}. The card's branch is {branch}; git status shows what is actually checked \ @@ -587,7 +355,7 @@ pub struct HeldCardTurn { pub hands: Option, /// When the card is known but its hands could not be bound: the never-rooted context the /// turn acts with instead, so its code tools refuse rather than act at home. - pub(super) unbound: Option, + pub(crate) unbound: Option, } /// A turn's admission to the hands of the card claim it works (card fc9e9fd7). The context @@ -595,9 +363,9 @@ pub struct HeldCardTurn { /// holds the hands open until the turn ends, so closing them (the claim ended) waits the /// turn out instead of dropping its engine or shell under it. pub struct CardHands { - pub context: crate::identity::hands_context::HandsContext, + pub context: HandsContext, pub hands: ActingHands, - pub(super) lease: std::sync::Arc, + pub(crate) lease: std::sync::Arc, } impl CardHands { @@ -632,94 +400,15 @@ pub(crate) async fn end_card_turn(card: &CardHands, acts: usize) { crate::persona::card_carry::request(); } -/// PURE: has the claim behind `context` ENDED, by the card's own row? Closed hands never -/// reopen (`code::hands`), so only an end may close them: the card is TERMINAL (Merged, -/// Closed), the claim was released (the board clears `claim_id`), or the card's claim is now -/// a different one (re-claimed, or another holder's). Not an end: a lease that LAPSED (same -/// claim id, renewed by her next heartbeat); Review or Blocked, which keep the claim (airc -/// `apply_card_state_changed` changes state and renews the lease, `claim_id` untouched), so a -/// send-back returns the card to InProgress under the SAME claim (Codex on #5247: reusing -/// `refused_by_claim`, which counts Review, would lock a resident out after her first -/// submission); and a row the board couldn't give. Closing on mere absence from her active claims locked Kimi out of -/// 0c69aa07 for hours (2026-10-21: `persona.work.hands_closing` on the 5090 every turn while -/// the board showed her claim live). -pub(crate) fn claim_has_ended( - context: crate::identity::hands_context::HandsContext, - card: Option<&airc_lib::WorkCard>, - her: uuid::Uuid, -) -> bool { - let Some(card) = card else { return false }; - if matches!(card.state, airc_work::model::CardState::Merged | airc_work::model::CardState::Closed) { - return true; - } - match card.claim_id { - None => true, - Some(current) => crate::identity::hands_context::HandsContext::for_claim(her, card.card_id.as_uuid(), current.as_uuid()) != context, - } -} - -/// Close the hands of every card claim whose claim ENDED ([`claim_has_ended`], read from -/// each card's own row): released, terminal, or re-acquired as a new claim. A claim missing -/// from her active claims is only a candidate; a lapsed lease or an unreadable row keeps its -/// hands. Each close runs in the background, refusing new turns and waiting out admitted -/// ones, then releases its engine and shells. -pub(super) async fn close_ended_claims( - live: &ActingHands, - held: &[crate::identity::hands_context::HandsContext], - citizen: &dyn crate::persona::airc_citizen::AircCitizen, - her: uuid::Uuid, -) { - let candidates: Vec<(crate::identity::hands_context::HandsContext, uuid::Uuid)> = ACTING_ROOTS - .lock() - .unwrap_or_else(|e| e.into_inner()) // poisoned lock = read the last state, same policy as every lock in this crate - .iter() - .filter(|((persona, context), _)| *persona == live.persona_id && context.is_some_and(|c| !held.contains(&c))) - .filter_map(|((_, context), place)| Some(((*context)?, place.card?))) - .collect(); - let mut ended = Vec::new(); - for (context, card) in candidates { - let row = citizen.card(card).await; - if claim_has_ended(context, row.as_ref(), her) { - ended.push(context); - } else { - continuum_base::probe!( - class = "persona.work.hands_kept", - peer = %her, - card = %card, - row_read = row.is_some(), - "a claim missing from her active claims has not ENDED (lapsed lease or unread row); its hands stay open" - ); - } - } - for context in ended { - let Some(hands) = live.in_context(context) else { continue }; - tokio::spawn(async move { - // The release closes the hands to new work and waits out admitted work itself. - let root = acting_root_in(hands.persona_id, Some(context)); - match close_acting_context(&hands).await { - Ok(()) => { - if let Some(root) = root { - crate::persona::workspace_transfer::forget_checkout(&root); - } - if focus_of(hands.persona_id) == Some(context) { - set_focus(hands.persona_id, None); - } - } - Err(e) => tracing::warn!(error = %e, context = %context.id(), "a card claim's hands could not be released; they are kept closed for a retry"), - } - }); - } -} - impl HeldCardTurn { /// The hands this turn acts with: its card claim's, the card's never-rooted stand-in when /// those could not be bound, or her default hands when she works no card. - pub(crate) fn turn_hands(&self) -> Option { + pub(crate) fn turn_hands(&self) -> Option { self.hands.as_ref().map(|h| h.context).or(self.unbound) } /// No card was selected: no citizen, unreadable claims, or nothing held. - pub(super) fn unheld() -> Self { + pub(crate) fn unheld() -> Self { Self { credit: None, hands: None, @@ -728,11 +417,37 @@ impl HeldCardTurn { } /// The card is known and her hands did not reach it. - pub(super) fn unrooted(credit: crate::persona::training_producer::CapturedCredit, persona: Uuid, card: Uuid) -> Self { + pub(crate) fn unrooted(credit: crate::persona::training_producer::CapturedCredit, persona: Uuid, card: Uuid) -> Self { Self { credit: Some(credit), hands: None, - unbound: Some(crate::identity::hands_context::HandsContext::unbound(persona, card)), + unbound: Some(HandsContext::unbound(persona, card)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches (card 822c4253): her hands moving to a card's own checkout with no + // word (Kimi's code/read of career-wrangler/docs/... failing in a per-card worktree), + // or the notice repeating every turn at the same checkout. Told on a new root, silent + // on the same one, told again when it moves; the notice names root, branch and the + // home tree that did not move. + #[test] + fn she_is_told_when_her_hands_move_and_only_then() { + let kimi = Uuid::new_v4(); + let card = std::path::Path::new("/w/worktrees/af4e2cea"); + assert!(!already_told(kimi, card), "first rooting is news"); + assert!(!already_told(kimi, card), "checking does not record: only a pinned line does"); + mark_told(kimi, card); + assert!(already_told(kimi, card), "the same checkout next turn is not news"); + assert!(!already_told(kimi, std::path::Path::new("/w/worktrees/b0b0b0b0"))); + assert!(!already_told(Uuid::new_v4(), card), "per citizen, never shared"); + let line = rooted_notice("CambrianTech/career-wrangler", card, "af4e2cea/a-real-product"); + for want in ["/w/worktrees/af4e2cea", "af4e2cea/a-real-product", "docs/x.md", "home workspace is unchanged"] { + assert!(line.contains(want), "{want}: {line}"); } } } diff --git a/core/continuum-mind/src/persona/channel_queue.rs b/core/continuum-mind/src/persona/channel_queue.rs index 8ac3aab66b..124d04a89e 100644 --- a/core/continuum-mind/src/persona/channel_queue.rs +++ b/core/continuum-mind/src/persona/channel_queue.rs @@ -9,8 +9,8 @@ //! One ChannelQueue per ActivityDomain. The CNS iterates channels in priority order. use continuum_base::time::EpochMs; -use super::channel_items::{ChatQueueItem, TaskQueueItem}; -use super::channel_types::{ActivityDomain, ChannelStatus, CoherentUnit, QueueItemBehavior}; +use crate::cognition::conversation::channel_items::{ChatQueueItem, TaskQueueItem}; +use crate::cognition::conversation::channel_types::{ActivityDomain, ChannelStatus, CoherentUnit, QueueItemBehavior}; use std::sync::Arc; use tracing::debug; @@ -482,8 +482,8 @@ impl ChannelQueue { #[cfg(test)] mod tests { - use super::super::channel_items::*; - use super::super::types::SenderType; + use crate::cognition::conversation::channel_items::*; + use crate::cognition::conversation::types::SenderType; use super::*; use uuid::Uuid; diff --git a/core/continuum-mind/src/persona/channel_registry.rs b/core/continuum-mind/src/persona/channel_registry.rs index 8b78797a7b..457eee3050 100644 --- a/core/continuum-mind/src/persona/channel_registry.rs +++ b/core/continuum-mind/src/persona/channel_registry.rs @@ -7,10 +7,10 @@ //! When any channel receives work, the global signal wakes the service loop. use super::channel_queue::{ChannelQueue, ChannelQueueConfig}; -use super::channel_types::{ActivityDomain, ChannelRegistryStatus, CoherentUnit, QueueItemBehavior, ServiceCycleResult, DOMAIN_PRIORITY_ORDER}; +use crate::cognition::conversation::channel_types::{ActivityDomain, ChannelRegistryStatus, CoherentUnit, QueueItemBehavior, ServiceCycleResult, DOMAIN_PRIORITY_ORDER}; use super::channel_view::{ChatChannelView, CoherentInput, PersonaChannelView}; -use super::persona_identity::PersonaIdentity; -use super::types::PersonaState; +use crate::cognition::conversation::persona_identity::PersonaIdentity; +use crate::cognition::conversation::types::PersonaState; use std::collections::HashMap; use std::sync::Arc; use tracing::{debug, info}; @@ -382,8 +382,8 @@ fn domain_name(domain: ActivityDomain) -> &'static str { #[cfg(test)] mod tests { - use super::super::channel_items::*; - use super::super::types::SenderType; + use crate::cognition::conversation::channel_items::*; + use crate::cognition::conversation::types::SenderType; use super::*; use continuum_base::time::EpochMs; use uuid::Uuid; @@ -688,7 +688,7 @@ mod tests { assert_eq!(state.inbox_load, 0); assert!(matches!( state.mood, - crate::persona::types::Mood::Active | crate::persona::types::Mood::Idle + crate::cognition::conversation::types::Mood::Active | crate::cognition::conversation::types::Mood::Idle )); let _inputs = registry.service_cycle_batched( @@ -709,7 +709,7 @@ mod tests { // (inbox_load > 20 → Overwhelmed; here load=1 so Active). assert_eq!( state.mood, - crate::persona::types::Mood::Active, + crate::cognition::conversation::types::Mood::Active, "mood must be Active after load=1 (the calculate_mood transition)" ); } diff --git a/core/continuum-mind/src/persona/channel_view.rs b/core/continuum-mind/src/persona/channel_view.rs index f80316ae1c..ec932a9a5b 100644 --- a/core/continuum-mind/src/persona/channel_view.rs +++ b/core/continuum-mind/src/persona/channel_view.rs @@ -22,9 +22,9 @@ //! `N × M × decode_cost`. The flow-geometric proof's persona-day-one //! delivery rests on this split. -use crate::persona::channel_items::ChatQueueItem; -use crate::persona::channel_types::{ActivityDomain, CoherentUnit}; -use crate::persona::persona_identity::PersonaIdentity; +use crate::cognition::conversation::channel_items::ChatQueueItem; +use crate::cognition::conversation::channel_types::{ActivityDomain, CoherentUnit}; +use crate::cognition::conversation::persona_identity::PersonaIdentity; use std::sync::Arc; use uuid::Uuid; @@ -266,15 +266,15 @@ impl PersonaChannelView for ChatChannelView { mod tests { use super::*; use continuum_base::time::EpochMs; - use crate::persona::channel_items::ChatQueueItem; - use crate::persona::types::SenderType; + use crate::cognition::conversation::channel_items::ChatQueueItem; + use crate::cognition::conversation::types::SenderType; use std::sync::OnceLock; fn make_chat_arc( content: &str, sender: &str, room: Uuid, - ) -> Arc { + ) -> Arc { Arc::new(ChatQueueItem { id: Uuid::new_v4(), room_id: room, @@ -382,7 +382,7 @@ mod tests { #[test] fn chat_view_burst_embedding_is_arc_shared_across_personas() { let room = Uuid::new_v4(); - let items: Vec> = + let items: Vec> = vec![make_chat_arc( "the shared content for this test", "Operator", diff --git a/core/continuum-mind/src/persona/cognition.rs b/core/continuum-mind/src/persona/cognition.rs index 5fdf7187d1..4a042486e4 100644 --- a/core/continuum-mind/src/persona/cognition.rs +++ b/core/continuum-mind/src/persona/cognition.rs @@ -10,7 +10,7 @@ //! Target: Sub-1ms decisions, freeing TypeScript for UI only. use super::inbox::PersonaInbox; -use super::types::{InboxMessage, PersonaState, SenderType}; +use crate::cognition::conversation::types::{InboxMessage, PersonaState, SenderType}; use crate::rag::RagEngine; use dashmap::DashSet; use serde::{Deserialize, Serialize}; diff --git a/core/continuum-mind/src/persona/cognition_extensions.rs b/core/continuum-mind/src/persona/cognition_extensions.rs new file mode 100644 index 0000000000..ddf93f165a --- /dev/null +++ b/core/continuum-mind/src/persona/cognition_extensions.rs @@ -0,0 +1,77 @@ +//! Persona fills cognition's extension slots (`cognition::extensions`) at boot: the verbs +//! cognition calls that persona owns. One list, so the core's boot and a test that drives a +//! real turn install the same set. Each install replaces a previous one; installing twice is +//! harmless. + +use std::sync::Arc; + +use uuid::Uuid; + +use crate::cognition::extensions::{self as ext, CreditSink, FleetLease, SlotFuture}; +use crate::persona::PersonaAircRuntimeRegistry; + +/// Install every slot. +pub fn install() { + ext::install_room_voice(room_voice); + ext::install_card_carry(crate::persona::card_carry::request); + ext::install_credit_sink(Arc::new(TrainingCredit)); + ext::install_cognition_pulse(crate::persona::cognition_pulse::touch); + ext::install_mark_perceived(crate::persona::perception_feed::mark_perceived); + ext::install_remote_binding(|root, name| { + crate::persona::remote_lane_factory::is_remote_bound(root, name).map_err(|e| e.to_string()) + }); + ext::install_quiesce_fleet(quiesce_fleet); + ext::install_card_room(card_room); + ext::install_resident_review_boundaries(|persona| { + crate::persona::training_producer::reviewed::boundaries::ReviewBoundaryStore::resident(persona) + .map(|store| Arc::new(store) as Arc) + }); + ext::install_pinned_workspace_map(|persona, root| { + Arc::new(crate::persona::workspace_map_source::WorkspaceMapSource::for_pinned_root(persona, root.to_path_buf())) + }); +} + +/// Her room voice is her airc citizen; no runtime on this node means nothing to speak through. +fn room_voice(persona: Uuid, room: Uuid, text: String) -> SlotFuture>> { + Box::pin(async move { + let runtime = PersonaAircRuntimeRegistry::try_global()?.get(persona)?; + Some( + crate::persona::airc_citizen::publish_text_in_room(runtime.airc(), room, &text) + .await + .map(|_| ()) + .map_err(|e| e.to_string()), + ) + }) +} + +/// The room whose board holds `card`, by the one definition (`work_board::horizon`). +fn card_room(persona: Uuid, card: Uuid) -> SlotFuture> { + Box::pin(async move { + let runtime = PersonaAircRuntimeRegistry::try_global()?.get(persona)?; + crate::persona::work_board::horizon::room_holding_card(runtime.airc(), airc_lib::WorkCardId::from_uuid(card)) + .await + .map(|room| room.channel.as_uuid()) + }) +} + +fn quiesce_fleet() -> Option { + let lease = PersonaAircRuntimeRegistry::try_global()?.quiesce_all(); + Some(FleetLease::new(lease.count(), Box::new(lease))) +} + +/// Cognition's credit judgments land in persona's training producer. +struct TrainingCredit; + +impl CreditSink for TrainingCredit { + fn speech_discipline(&self, persona_id: Uuid, persona_name: String, base_model: String, burst: String, marker: &'static str) { + crate::persona::training_producer::produce_speech_discipline(persona_id, persona_name, base_model, burst, marker); + } + + fn settle_instance(&self, instance: &str, passed: bool) { + crate::persona::training_producer::settle_instance_credit(instance, passed); + } + + fn settle_card(&self, card: Uuid, passed: bool) -> SlotFuture<()> { + Box::pin(crate::persona::training_producer::settle_card_credit(card, passed)) + } +} diff --git a/core/continuum-mind/src/persona/cognition_io.rs b/core/continuum-mind/src/persona/cognition_io.rs index 66121abace..c0ec47d7a2 100644 --- a/core/continuum-mind/src/persona/cognition_io.rs +++ b/core/continuum-mind/src/persona/cognition_io.rs @@ -37,7 +37,7 @@ use crate::cognition::RecentMessage; use crate::model_registry::Capability; use crate::persona::response::RespondInput; use crate::persona::turn_context::TurnContext; -use crate::persona::types::{InboxMessage, Modality, SenderType}; +use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use serde::{Deserialize, Serialize}; use ts_rs::TS; use uuid::Uuid; diff --git a/core/continuum-mind/src/persona/cognition_pulse.rs b/core/continuum-mind/src/persona/cognition_pulse.rs index 1632b9fa35..7682bcfb53 100644 --- a/core/continuum-mind/src/persona/cognition_pulse.rs +++ b/core/continuum-mind/src/persona/cognition_pulse.rs @@ -162,7 +162,7 @@ impl CommandWork { work.retain(|_, p| { p.active > 0 || p.completed_at.is_some_and(|t| { - now_ms.saturating_sub(t) <= crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS + now_ms.saturating_sub(t) <= crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS }) }); } @@ -280,7 +280,7 @@ mod tests { fn command_work_protects_only_its_card_and_ends_on_drop() { let persona = Uuid::new_v4(); let (card, other) = (Uuid::new_v4(), Uuid::new_v4()); - let ttl = crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS; + let ttl = crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS; let now = EpochMs::now().millis(); touch(persona, now.saturating_sub(ttl * 3)); let captured = || CommandWork { @@ -319,7 +319,7 @@ mod tests { // structurally unreachable (the 2026-08-16 stalemate). #[test] fn renewal_is_earned_only_by_recent_cognition() { - let ttl = crate::persona::work_board::facts::DEFAULT_CLAIM_TTL_MS; + let ttl = crate::cognition::card_facts::DEFAULT_CLAIM_TTL_MS; let persona = Uuid::from_u128(7); // never stamped → not earned assert!(!renewal_earned(idle_ms(persona, 1_000), ttl)); diff --git a/core/continuum-mind/src/persona/durable_history.rs b/core/continuum-mind/src/persona/durable_history.rs index 47aa81ccb2..c5ccb48abd 100644 --- a/core/continuum-mind/src/persona/durable_history.rs +++ b/core/continuum-mind/src/persona/durable_history.rs @@ -35,7 +35,7 @@ pub struct HydratedLine { /// weigh "silent past when I expected" on events it cannot place in time. pub occurred_at_ms: u64, pub text: String, - pub media: Vec, + pub media: Vec, } /// Read the latest lines of a room's durable transcript, chronological @@ -66,7 +66,7 @@ pub struct RoomRow { pub sender: Uuid, pub occurred_at_ms: u64, pub text: String, - pub media: Vec, + pub media: Vec, } /// The newest `limit` rows of a room's conversation from the core's OWN chat @@ -91,7 +91,7 @@ pub async fn room_rows(room: Uuid, limit: usize) -> Result, String> // message or invent a text-only version of an image-bearing turn. for message in messages { if let Some(media) = message.get("content").and_then(|c| c.get("media")) { - serde_json::from_value::>(media.clone()) // boundary: validate media from the durable chat storage JSON format. + serde_json::from_value::>(media.clone()) // boundary: validate media from the durable chat storage JSON format. .map_err(|error| format!("durable_history: invalid media references: {error}"))?; } } @@ -145,9 +145,9 @@ pub(crate) fn event_from_row(room: Uuid, row: crate::persona::durable_history::R airc_protocol::HEADER_FORGE_BODY_HINT.to_string(), crate::routing::airc_realtime_wire::CONTINUUM_BODY_HINT.to_string(), ); - (Body::Json(crate::persona::room_event::chat_transcript_envelope( + (Body::Json(crate::cognition::conversation::room_event::chat_transcript_envelope( row.id, - &crate::persona::room_event::ChatTranscriptLine { + &crate::cognition::conversation::room_event::ChatTranscriptLine { room_id: room, sender_id: row.sender, text: &row.text, diff --git a/core/continuum-mind/src/persona/engram_source.rs b/core/continuum-mind/src/persona/engram_source.rs index 5ada117317..997d9e145e 100644 --- a/core/continuum-mind/src/persona/engram_source.rs +++ b/core/continuum-mind/src/persona/engram_source.rs @@ -50,8 +50,8 @@ use std::sync::Arc; use async_trait::async_trait; -use crate::persona::admission_state::AdmissionState; -use crate::persona::engram::Engram; +use crate::cognition::admission_state::AdmissionState; +use crate::cognition::engram::Engram; use crate::cognition::rag_budget::{ RagContext, RagDelivery, RagItem, RagSource, ResolutionPreference, }; @@ -244,9 +244,9 @@ impl RagSource for EngramSource { #[cfg(test)] mod tests { use super::*; - use crate::persona::admission_state::EngramOriginKind; - use crate::persona::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; - use crate::persona::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; + use crate::cognition::admission_state::EngramOriginKind; + use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; use uuid::Uuid; /// Build an AdmissionState wrapped in Arc, with `count` engrams diff --git a/core/continuum-mind/src/persona/evaluator/mod.rs b/core/continuum-mind/src/persona/evaluator/mod.rs index 9e1460a1c1..791d047f03 100644 --- a/core/continuum-mind/src/persona/evaluator/mod.rs +++ b/core/continuum-mind/src/persona/evaluator/mod.rs @@ -43,7 +43,7 @@ pub use sleep_state::{SleepMode, SleepState}; use crate::persona::cognition::PersonaCognitionEngine; use crate::persona::message_cache::RecentMessageCache; use crate::cognition::text_analysis; -use crate::persona::types::{InboxMessage, Modality, SenderType}; +use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use serde::{Deserialize, Serialize}; use std::time::Instant; use ts_rs::TS; diff --git a/core/continuum-mind/src/persona/host.rs b/core/continuum-mind/src/persona/host.rs index b3d30f2c62..7efe08a550 100644 --- a/core/continuum-mind/src/persona/host.rs +++ b/core/continuum-mind/src/persona/host.rs @@ -38,7 +38,8 @@ use crate::persona::airc_persona_conversation::AircPersonaConversation; use crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry; use crate::persona::identity_provider::PersonaIdentityProvider; use crate::experience::role::RoleId; -use crate::persona::service_loop::{serve_persona_loop, PersonaConversation, ServeOptions, ServeOutcome}; +use crate::cognition::conversation::PersonaConversation; +use crate::persona::service_loop::{serve_persona_loop, ServeOptions, ServeOutcome}; use crate::persona::spawner_module::{bootstrap_planned, PersonaSpawnerModule}; use crate::persona::supervisor::{materialize_adapters, HostedPersona, PersonaAdapterFactory, PersonaContext, SupervisorError}; use serde::{Deserialize, Serialize}; diff --git a/core/continuum-mind/src/persona/inbox.rs b/core/continuum-mind/src/persona/inbox.rs index 9156a5ef14..a7cc63f1b1 100644 --- a/core/continuum-mind/src/persona/inbox.rs +++ b/core/continuum-mind/src/persona/inbox.rs @@ -1,4 +1,4 @@ -use super::types::InboxMessage; +use crate::cognition::conversation::types::InboxMessage; use serde::{Deserialize, Serialize}; use std::collections::BinaryHeap; use std::sync::Mutex; @@ -171,7 +171,7 @@ impl PersonaInbox { #[cfg(test)] mod tests { use super::*; - use crate::persona::{Modality, SenderType}; + use crate::cognition::conversation::types::{Modality, SenderType}; fn message( room_id: Uuid, diff --git a/core/continuum-mind/src/persona/initiative_turn.rs b/core/continuum-mind/src/persona/initiative_turn.rs index 24a04a73b2..77ae118823 100644 --- a/core/continuum-mind/src/persona/initiative_turn.rs +++ b/core/continuum-mind/src/persona/initiative_turn.rs @@ -37,7 +37,7 @@ use crate::cognition::act_observe::SettleStep; use crate::persona::act_question::WorkQuestionOutcome; -use crate::persona::service_loop::{PersonaConversation, LIVE_MAX_ACTS}; +use crate::persona::service_loop::{CitizenConversation, LIVE_MAX_ACTS}; use crate::persona::supervisor::HostedPersona; /// Whether the caller's cadence offers her an initiative turn when she holds nothing. @@ -60,7 +60,7 @@ pub(crate) const INITIATIVE_MOMENT: &str = "[initiative] Nothing is assigned to pub(crate) async fn drive_initiative_turn( ctx: &HostedPersona, cycle: &crate::cognition::workspace::WorkspaceCycle, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, lamport: u64, turn_room: uuid::Uuid, ) -> WorkQuestionOutcome { diff --git a/core/continuum-mind/src/persona/instance_manager.rs b/core/continuum-mind/src/persona/instance_manager.rs index ea40a67407..8a95a8d9b2 100644 --- a/core/continuum-mind/src/persona/instance_manager.rs +++ b/core/continuum-mind/src/persona/instance_manager.rs @@ -147,8 +147,8 @@ impl PersonaInstanceInfo { /// identity by hand ([[strong-typing-across-boundaries]]). /// `PersonaIdentity` is cheap to clone, so returning an owned value /// is fine on the per-tick service loop. - pub fn persona_identity(&self) -> crate::persona::persona_identity::PersonaIdentity { - crate::persona::persona_identity::PersonaIdentity::new( + pub fn persona_identity(&self) -> crate::cognition::conversation::persona_identity::PersonaIdentity { + crate::cognition::conversation::persona_identity::PersonaIdentity::new( self.peer_id.as_uuid(), &self.agent_name, ) diff --git a/core/continuum-mind/src/persona/mind_state.rs b/core/continuum-mind/src/persona/mind_state.rs index e746338f91..7ff7257487 100644 --- a/core/continuum-mind/src/persona/mind_state.rs +++ b/core/continuum-mind/src/persona/mind_state.rs @@ -18,7 +18,7 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::attention::{AttentionDial, Continuation}; +use crate::cognition::attention::{AttentionDial, Continuation}; pub const FILE_NAME: &str = "mind-state.json"; const VERSION: u32 = 1; @@ -129,7 +129,7 @@ impl MindState { #[cfg(test)] mod tests { use super::*; - use crate::persona::salience::Expectation; + use crate::cognition::conversation::salience::Expectation; // what this catches: rule 8. A saved mind comes back as the same mind: cursors, // her note and her dial; an absent file is a fresh mind (not a crash); a diff --git a/core/continuum-mind/src/persona/mind_store.rs b/core/continuum-mind/src/persona/mind_store.rs new file mode 100644 index 0000000000..faef9f05e6 --- /dev/null +++ b/core/continuum-mind/src/persona/mind_store.rs @@ -0,0 +1,54 @@ +//! Her sealed mind store, reached through her own airc runtime so the core never holds her +//! key: where her private continuation (sink 10 of `cognition::mind_room`) is kept across a +//! restart. + +use uuid::Uuid; + +use crate::persona::PersonaAircRuntimeRegistry; + +/// Seal her private continuation into her mind store (`Some`), or clear it (`None`). +/// Goes through her own runtime's `Airc::mind_store()`, so the core never holds her key. +/// `Ok(false)` = she has no resident airc runtime here; nothing was written. +pub fn seal_continuation( + persona: Uuid, + continuation: Option<&crate::cognition::attention::Continuation>, +) -> Result { + let Some(runtime) = PersonaAircRuntimeRegistry::try_global().and_then(|r| r.get(persona)) else { + return Ok(false); + }; + let store = runtime.airc().mind_store().map_err(|e| e.to_string())?; + let id = crate::cognition::mind_room::continuation_record_id(persona); + match continuation { + Some(c) => { + let json = serde_json::to_string(c).map_err(|e| e.to_string())?; // disk boundary: her continuation as a sealed record in her mind store + store.put_at(id, &json).map_err(|e| e.to_string())?; + } + None => store.remove(id).map_err(|e| e.to_string())?, + } + Ok(true) +} + +/// Her sealed private continuation, if she left one: read back at boot so a Resume wake +/// continues her private thread after a restart. A store that will not open or a record +/// that will not parse is probed and read as none: her open state boots regardless. +pub fn sealed_continuation(persona: Uuid) -> Option { + let runtime = PersonaAircRuntimeRegistry::try_global()?.get(persona)?; + let store = match runtime.airc().mind_store() { + Ok(store) => store, + Err(e) => { + continuum_base::probe!(class = "mind.private.store_unopened", persona = %persona, error = %e.to_string(), "her mind store did not open at boot; no private continuation restored"); + return None; + } + }; + let id = crate::cognition::mind_room::continuation_record_id(persona); + if !store.list().ok()?.contains(&id) { + return None; + } + match store.get(id).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str(&t).map_err(|e| e.to_string())) { // disk boundary: read back from her sealed mind store + Ok(c) => Some(c), + Err(e) => { + continuum_base::probe!(class = "mind.private.continuation_unreadable", persona = %persona, error = %e, "her sealed continuation did not read back; not restored"); + None + } + } +} diff --git a/core/continuum-mind/src/persona/mod.rs b/core/continuum-mind/src/persona/mod.rs index 5869ecf33b..a4802f94cf 100644 --- a/core/continuum-mind/src/persona/mod.rs +++ b/core/continuum-mind/src/persona/mod.rs @@ -11,10 +11,6 @@ //! - channel_queue: Generic per-domain queue container //! - channel_registry: Domain-to-queue routing + service_cycle() -pub mod admission; -pub mod admission_persistence; -pub mod admission_state; -pub mod attention; pub mod awareness; pub mod awareness_source; pub mod airc_admission; @@ -36,46 +32,38 @@ pub mod active_work_source; pub mod airc_runtime_registry; pub mod airc_source; pub mod allocator; -pub mod cached_source; pub mod card; pub mod card_carry; +pub mod card_hands; pub mod card_checkout; -pub mod card_holder; pub mod held_claims; pub mod card_ledger_fact; -pub mod channel_items; pub mod channel_queue; pub mod channel_registry; -pub mod channel_types; pub mod channel_view; pub mod claim_rejections; pub mod cognition; +pub mod cognition_extensions; pub mod cognition_io; pub mod cognition_pulse; pub mod substrate_governor; -pub mod decay_tick; pub mod domain_classifier; pub mod durable_history; -pub mod engram; -pub mod engram_graph; pub mod engram_source; pub mod evaluator; pub mod genome_paging; -pub mod grounding_invalidation; -pub mod home; pub mod host; pub mod hw_tier_descriptor; pub mod identity_provider; pub mod inbox; -pub mod inbox_admission; pub mod inference_profile; pub mod instance_manager; pub mod loop_dedup; pub mod media_perception_source; pub mod media_policy; pub mod message_cache; -pub mod mind_room; pub mod mind_state; +pub mod mind_store; pub mod perception_feed; pub mod perception_region; pub mod model_override; @@ -85,14 +73,11 @@ pub mod placement_switch; pub mod self_peer; pub mod remote_lane_factory; pub mod model_selection; -pub mod persona_identity; pub mod profile_builder; pub mod viewstate_rag; pub mod rag_capture; pub mod rag_inspect; -pub mod recall_metadata; pub mod recorder; -pub mod salience; pub mod response; pub mod resume_or_mint_provider; pub mod resting_seat; @@ -101,10 +86,8 @@ pub mod role_template; pub mod room_board_source; pub mod room_doctrine_source; pub mod identity_card_cache; -pub mod room_event; pub mod room_resolve; pub mod room_roster_source; -pub mod room_substrates; pub mod roster_slot; pub mod stream_rail; #[cfg(any(test, feature = "test-fixtures"))] @@ -127,20 +110,13 @@ pub mod service_module; pub mod spawner; pub mod spawner_module; pub mod supervisor; -pub mod trace; pub mod training_producer; pub mod turn_context; pub mod turn_frame; -pub mod types; pub mod unified; pub mod wall_source; pub mod workspace_map_source; -pub use admission::{ - build_engram_from_candidate, AdmissionCandidate, AdmissionConfig, AdmissionContext, - AdmissionGate, HeuristicIsMemorable, IsMemorable, SeenContentLookup, SeenEventLookup, -}; -pub use admission_state::{AdmissionState, EngramOriginKind}; pub use airc_admission::{ airc_envelope_to_candidate, airc_envelope_to_ref, AircAdmissionConversionError, AircAdmissionEnvelope, @@ -151,15 +127,9 @@ pub use allocator::{ allocate as allocate_personas, load_catalog, select_local_model, AllocationResult, PersonaAllocation, PersonaCatalogEntry, }; -pub use channel_items::{ChannelEnqueueRequest, MediaItemRequest}; pub use channel_registry::ChannelRegistry; -pub use channel_types::{ActivityDomain, ChannelRegistryStatus, ChannelStatus, ServiceCycleResult}; pub use cognition::{CognitionDecision, PersonaCognitionEngine, PriorityFactors, PriorityScore}; pub use domain_classifier::{DomainClassification, DomainClassifier, QualityFactors, QualityScore}; -pub use engram::{ - AdmissionDecision, AdmissionDropReason, AdmissionError, AircMessageRef, ChatMessageRef, Engram, - EngramKind, EngramOrigin, ToolInvocationRef, TrustState, -}; pub use evaluator::{ analyze_burst, AdequacyResult, BurstEvaluateResult, BurstRespondContext, FullEvaluateRequest, FullEvaluateResult, GateDetails, RateLimiterState, RecentResponse, SleepMode, SleepState, @@ -169,10 +139,6 @@ pub use genome_paging::{ GenomePagingState, }; pub use inbox::{PersonaInbox, PersonaInboxFrame, PersonaInboxFrameMetrics}; -pub use inbox_admission::{ - content_hash_sha256, inbox_message_to_candidate, inbox_message_to_origin, InboxAdmissionRunner, - TrustMapping, -}; pub use message_cache::{ CachedMessage, ContentDedupResult, ContentDeduplicator, EchoChamberResult, RecentMessageCache, SenderCategory, @@ -186,7 +152,6 @@ pub use turn_frame::{ ConsolidatedInboxChunk, PersonaTurnFrame, PersonaTurnFrameReplayRecord, RagAssemblySeed, PERSONA_TURN_FRAME_REPLAY_SCHEMA_VERSION, }; -pub use types::*; pub use unified::PersonaCognition; // ── Substrate ORM entity registration ──────────────────────────── diff --git a/core/continuum-mind/src/persona/model_override.rs b/core/continuum-mind/src/persona/model_override.rs index 9fc60491c8..a5d6a72218 100644 --- a/core/continuum-mind/src/persona/model_override.rs +++ b/core/continuum-mind/src/persona/model_override.rs @@ -42,7 +42,7 @@ use std::path::PathBuf; use serde::{Deserialize, Serialize}; -use crate::persona::home::PersonaHome; +use crate::cognition::home::PersonaHome; /// The persisted per-persona base-model assignment: which model, set when, by whom. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/core/continuum-mind/src/persona/perception_feed.rs b/core/continuum-mind/src/persona/perception_feed.rs index 2d563b67c8..cd516e5d6e 100644 --- a/core/continuum-mind/src/persona/perception_feed.rs +++ b/core/continuum-mind/src/persona/perception_feed.rs @@ -26,14 +26,15 @@ use airc_core::{PeerId, TranscriptEvent}; use tokio::sync::mpsc; use uuid::Uuid; -use super::perception_region::{PerceptionRegion, Wake}; -use super::salience::{BoardChange, SpeechLine}; -use crate::persona::room_event::{room_work_from_event, RoomWork}; +use super::perception_region::PerceptionRegion; +use crate::cognition::conversation::Wake; +use crate::cognition::conversation::salience::{BoardChange, SpeechLine}; +use crate::cognition::conversation::room_event::{room_work_from_event, RoomWork}; struct Resident { peer: PeerId, /// Her identity for the one mention detector (`PersonaIdentity::mentions`). - identity: super::persona_identity::PersonaIdentity, + identity: crate::cognition::conversation::persona_identity::PersonaIdentity, region: Arc>, wake_tx: mpsc::Sender, /// Her conversation's admission pipeline (BigMama's consumer, phase 2): the @@ -59,7 +60,7 @@ pub fn register( events_tx: Option>>, ) { attach_her_rooms(®ion); - let identity = super::persona_identity::PersonaIdentity::new(peer.as_uuid(), agent_name.to_string()); + let identity = crate::cognition::conversation::persona_identity::PersonaIdentity::new(peer.as_uuid(), agent_name.to_string()); registry() .lock() .unwrap_or_else(|p| p.into_inner()) @@ -166,7 +167,7 @@ pub fn classify(event: &TranscriptEvent) -> Fed { Ok(Some(RoomWork::Submitted { card_id, publisher, .. })) => Fed::Board(BoardChange::Moved { card_id, by: publisher }), Ok(Some(RoomWork::Other { kind })) => Fed::OtherWork(kind), Err(reason) => Fed::NotPerception(reason), - Ok(None) => match crate::persona::room_event::room_content_from_event(event) { + Ok(None) => match crate::cognition::conversation::room_event::room_content_from_event(event) { Ok(_) => Fed::Speech, Err(reason) => Fed::NotPerception(reason), }, @@ -234,10 +235,10 @@ pub fn feed(event: &Arc, now_ms: u64) -> usize { #[cfg(test)] mod tests { - use super::super::salience::ObservedVerdict; + use crate::cognition::conversation::salience::ObservedVerdict; use super::*; - use crate::persona::attention::AttentionDial; - use crate::persona::salience::SalienceLevel; + use crate::cognition::attention::AttentionDial; + use crate::cognition::conversation::salience::SalienceLevel; const ROOM_A: Uuid = Uuid::from_u128(0xa); const ROOM_B: Uuid = Uuid::from_u128(0xb); @@ -350,7 +351,7 @@ mod tests { match rx.try_recv() { Ok(Wake::Perceive { salience, .. }) => { assert_eq!(salience.level, SalienceLevel::Addressed); - assert!(salience.reasons.iter().any(|r| matches!(r, crate::persona::salience::SalienceReason::MentionedMe { by } if *by == peer))); + assert!(salience.reasons.iter().any(|r| matches!(r, crate::cognition::conversation::salience::SalienceReason::MentionedMe { by } if *by == peer))); } other => panic!("her name in the text is addressed to her: {other:?}"), } diff --git a/core/continuum-mind/src/persona/perception_region.rs b/core/continuum-mind/src/persona/perception_region.rs index 62f424a0ee..05ae3783d2 100644 --- a/core/continuum-mind/src/persona/perception_region.rs +++ b/core/continuum-mind/src/persona/perception_region.rs @@ -30,22 +30,12 @@ use airc_core::PeerId; use tokio::sync::watch; use uuid::Uuid; -use super::attention::{AttentionDial, Continuation}; +use crate::cognition::attention::{AttentionDial, Continuation}; use super::awareness::{self, ActivityLine, AwarenessSnapshot}; use super::mind_state::{ActivityCursor, MindState, MindStateError}; -use super::salience::{self, ActivityDelta, BoardChange, ExpectedVerdict, Me, ObservedVerdict, Salience, SalienceLevel, SpeechLine}; +use crate::cognition::conversation::salience::{self, ActivityDelta, BoardChange, ExpectedVerdict, Me, ObservedVerdict, Salience, SalienceLevel, SpeechLine}; use crate::cognition::channel_digest::ChannelDigest; - -/// Why she is being woken. The activity rides on the wake; no room is implied. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Wake { - /// An activity's delta is loud enough for her dial. - Perceive { activity: Uuid, salience: Salience }, - /// The time she expected something by has passed. - Continuation, - /// First wake after a restart: continue what she was doing. - Resume, -} +use crate::cognition::conversation::Wake; /// One activity as she perceives it (EVENT-MIND §6 `ActivityView`), borrowing the /// truth; nothing copied. @@ -430,8 +420,8 @@ impl PerceptionRegion { // memory only, and a restart forgets it, which is the honest cost (the same as her // mind cycle's working memory). Her open state is saved as always. let me = self.me.as_uuid(); - if self.state.continuation.as_ref().is_some_and(|c| crate::persona::mind_room::is_private_room(me, c.activity)) { - crate::persona::mind_room::note_withheld(me, "mind_state_continuation"); + if self.state.continuation.as_ref().is_some_and(|c| crate::cognition::mind_room::is_private_room(me, c.activity)) { + crate::cognition::mind_room::note_withheld(me, "mind_state_continuation"); let mut open = self.state.clone(); open.continuation = None; return open.save(peer_dir, now_ms); @@ -492,7 +482,7 @@ fn blank(name: String) -> ActivityView { #[cfg(test)] mod tests { use super::*; - use crate::persona::salience::{Expectation, ExpectedVerdict, ObservedVerdict, SalienceReason}; + use crate::cognition::conversation::salience::{Expectation, ExpectedVerdict, ObservedVerdict, SalienceReason}; const ME: Uuid = Uuid::from_u128(0x1); const PEER: Uuid = Uuid::from_u128(0x2); @@ -534,7 +524,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut r, _rx) = PerceptionRegion::boot(PeerId::from_uuid(ME), dir.path(), 1_000, 0); assert_ne!(r.wake_for(1), Some(Wake::Resume), "nothing saved, nothing to resume"); - let mind = crate::persona::mind_room::mind_room_id(ME); + let mind = crate::cognition::mind_room::mind_room_id(ME); r.restore_private_continuation( Continuation { activity: mind, note: "a private plan".into(), expectation: None, written_at_ms: 1 }, 2, @@ -550,7 +540,7 @@ mod tests { fn a_private_continuation_is_never_written_to_her_mind_state() { let dir = tempfile::tempdir().unwrap(); let (mut r, _rx) = PerceptionRegion::boot(PeerId::from_uuid(ME), dir.path(), 1_000, 0); - let mind = crate::persona::mind_room::mind_room_id(ME); + let mind = crate::cognition::mind_room::mind_room_id(ME); r.set_continuation( Some(Continuation { activity: mind, note: "a private plan".into(), expectation: None, written_at_ms: 1 }), 1, diff --git a/core/continuum-mind/src/persona/placement_switch/adapter.rs b/core/continuum-mind/src/persona/placement_switch/adapter.rs index 9c9dc8cb2d..f6ac25cf1e 100644 --- a/core/continuum-mind/src/persona/placement_switch/adapter.rs +++ b/core/continuum-mind/src/persona/placement_switch/adapter.rs @@ -9,7 +9,7 @@ use crate::ai::types::{ TextGenerationResponse, }; use crate::inference::airc_remote::AircRemoteInferenceAdapter; -use crate::persona::home::PersonaHome; +use crate::cognition::home::PersonaHome; use crate::persona::inference_profile::PersonaInferenceProfile; use crate::persona::model_override::PersonaModelOverride; use crate::persona::supervisor::PersonaAdapterFactory; diff --git a/core/continuum-mind/src/persona/rag_capture.rs b/core/continuum-mind/src/persona/rag_capture.rs index 2545b0308f..1acd591a61 100644 --- a/core/continuum-mind/src/persona/rag_capture.rs +++ b/core/continuum-mind/src/persona/rag_capture.rs @@ -208,7 +208,7 @@ impl JsonlRagCaptureSink { /// retrieval is captured. The ONE predicate every RAG capture record asks. pub(crate) fn turn_is_private(ctx: &RagContext) -> bool { ctx.airc_room - .is_some_and(|room| crate::persona::mind_room::is_private_room(ctx.persona_id, room.as_uuid())) + .is_some_and(|room| crate::cognition::mind_room::is_private_room(ctx.persona_id, room.as_uuid())) } impl RagCaptureSink for JsonlRagCaptureSink { @@ -308,7 +308,7 @@ impl RagSource for RecordingRagSource { delivery: delivery.clone(), }; if turn_is_private(ctx) { - crate::persona::mind_room::note_withheld(ctx.persona_id, "rag_capture"); + crate::cognition::mind_room::note_withheld(ctx.persona_id, "rag_capture"); } else { self.sink.record(event); } diff --git a/core/continuum-mind/src/persona/rag_inspect.rs b/core/continuum-mind/src/persona/rag_inspect.rs index e27ecd2b5c..8908dd834f 100644 --- a/core/continuum-mind/src/persona/rag_inspect.rs +++ b/core/continuum-mind/src/persona/rag_inspect.rs @@ -40,7 +40,8 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::persona::airc_source::{AircRagSource, AircTranscriptReader}; +use crate::cognition::conversation::transcript_reader::AircTranscriptReader; +use crate::persona::airc_source::AircRagSource; use crate::cognition::rag_budget::{ BudgetAllocation, FlexboxRagBudgetAdapter, RagBudgetAdapter, RagContext, RagSource, RagSourceBudget, ReservedTokens, ResolutionPreference, diff --git a/core/continuum-mind/src/persona/recorder.rs b/core/continuum-mind/src/persona/recorder.rs index f6256e3e86..3eeeafded9 100644 --- a/core/continuum-mind/src/persona/recorder.rs +++ b/core/continuum-mind/src/persona/recorder.rs @@ -57,7 +57,7 @@ use continuum_base::time::EpochMs; use crate::cognition::capture::fixture_dir; use crate::cognition::tool_executor::types::MediaItemLite; use crate::persona::response::{PersonaResponse, RespondInput}; -use crate::persona::trace::CognitionTrace; +use crate::cognition::trace::CognitionTrace; use crate::persona::PersonaTurnFrameReplayRecord; use crate::runtime; use serde::Serialize; @@ -229,8 +229,8 @@ pub fn record_turn_frame_replay(record: &PersonaTurnFrameReplayRecord) { if disabled() { return; } - if crate::persona::mind_room::is_private_room(record.persona_id, record.room_id) { - crate::persona::mind_room::note_withheld(record.persona_id, "turn_frame_recorder"); + if crate::cognition::mind_room::is_private_room(record.persona_id, record.room_id) { + crate::cognition::mind_room::note_withheld(record.persona_id, "turn_frame_recorder"); return; } let dir = match fixture_dir(TURN_FRAME_FIXTURE_DIR) { @@ -247,8 +247,8 @@ fn persist_turn_payload(input: &RespondInput, payload: serde_json::Value) { return; } // A turn in her mind room is hers (PRIVACY-OF-THOUGHT.md §4, sink 1): not recorded. - if crate::persona::mind_room::is_private_room(input.persona.persona_id, input.turn_context.room_id) { - crate::persona::mind_room::note_withheld(input.persona.persona_id, "turn_recorder"); + if crate::cognition::mind_room::is_private_room(input.persona.persona_id, input.turn_context.room_id) { + crate::cognition::mind_room::note_withheld(input.persona.persona_id, "turn_recorder"); return; } let dir = match fixture_dir(RESPOND_FIXTURE_DIR) { @@ -430,7 +430,8 @@ mod tests { use crate::cognition::PersonaSlot; use crate::persona::inbox::{PersonaInboxFrame, PersonaInboxFrameMetrics}; use crate::persona::response::PersonaResponse; - use crate::persona::{InboxMessage, Modality, PersonaTurnFrame, SenderType}; + use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; + use crate::persona::PersonaTurnFrame; use std::collections::HashSet; use tempfile::tempdir; @@ -636,7 +637,7 @@ mod tests { /// turns left no fixture and the most diagnostic captures were lost. #[test] fn record_failed_turn_writes_error_with_partial_trace() { - use crate::persona::trace::SEAM_ANALYZE; + use crate::cognition::trace::SEAM_ANALYZE; let tmp = tempdir().expect("temp home"); let _restore = EnvRestore::install(tmp.path(), None); let input = fake_input(); diff --git a/core/continuum-mind/src/persona/remote_lane_factory.rs b/core/continuum-mind/src/persona/remote_lane_factory.rs index 2dc3bc208e..a4d5bbbcb6 100644 --- a/core/continuum-mind/src/persona/remote_lane_factory.rs +++ b/core/continuum-mind/src/persona/remote_lane_factory.rs @@ -61,7 +61,7 @@ use airc_lib::Airc; use crate::ai::adapter::AIProviderAdapter; use crate::inference::airc_remote::adapter::AircRemoteInferenceAdapter; use crate::inference::airc_remote::transport::AircLiveTransport; -use crate::persona::home::PersonaHome; +use crate::cognition::home::PersonaHome; use crate::persona::inference_profile::PersonaInferenceProfile; use crate::persona::supervisor::PersonaAdapterFactory; use crate::persona::PersonaModelOverride; diff --git a/core/continuum-mind/src/persona/response.rs b/core/continuum-mind/src/persona/response.rs index 9d49eb900f..2c113b9191 100644 --- a/core/continuum-mind/src/persona/response.rs +++ b/core/continuum-mind/src/persona/response.rs @@ -214,7 +214,7 @@ pub enum PersonaResponse { /// the caller for proper user-facing error reporting; we don't /// silently fall back to "Silent" because that would hide real bugs. pub async fn respond(input: RespondInput) -> Result { - use crate::persona::trace::CognitionTrace; + use crate::cognition::trace::CognitionTrace; let total_start = EpochMs::now().millis(); let mut trace = CognitionTrace::new(); @@ -250,10 +250,10 @@ pub async fn respond(input: RespondInput) -> Result { /// later seam fails — partial traces are the diagnostic value. async fn respond_inner( input: &RespondInput, - trace: &mut crate::persona::trace::CognitionTrace, + trace: &mut crate::cognition::trace::CognitionTrace, total_start: u64, ) -> Result { - use crate::persona::trace::{SEAM_ANALYZE, SEAM_INFERENCE, SEAM_POST_PROCESS}; + use crate::cognition::trace::{SEAM_ANALYZE, SEAM_INFERENCE, SEAM_POST_PROCESS}; // RTOS-debugger breakpoint: respond cycle entry. Captures who's // responding to what, plus the size of the contextual inputs the diff --git a/core/continuum-mind/src/persona/room_board_source.rs b/core/continuum-mind/src/persona/room_board_source.rs index cf4ed1f172..b7250ceae8 100644 --- a/core/continuum-mind/src/persona/room_board_source.rs +++ b/core/continuum-mind/src/persona/room_board_source.rs @@ -303,7 +303,7 @@ impl RoomBoardSource { /// The whole board carries all owners, so owner is always surfaced (unlike /// the active-work source, which is implicitly self-owned). /// Holder resolution is NOT done here — it lives in - /// [`crate::persona::card_holder`], the ONE place every board surface + /// [`crate::cognition::card_holder`], the ONE place every board surface /// (this source, the service-loop anchor, `work/list`, the CLI) answers /// "who holds this, is the hold live". Rendering it locally is what let /// five surfaces disagree, and why a peer's card read as an 8-hex prefix @@ -313,11 +313,11 @@ impl RoomBoardSource { board: &BoardSnapshot, self_id: uuid::Uuid, now_ms: u64, - names: &dyn crate::persona::card_holder::PeerNames, + names: &dyn crate::cognition::card_holder::PeerNames, include_submission: bool, ) -> String { let id8: String = card.card_id.as_uuid().to_string().chars().take(8).collect(); - let held = crate::persona::card_holder::holder(card, self_id, now_ms, names); + let held = crate::cognition::card_holder::holder(card, self_id, now_ms, names); // The tag leads with what the card IS to someone deciding whether to take // it, not with the column it happens to sit in — a lapsed claim is takeable // work whose column still reads `Claimed`. See `CardHolder::state_tag`; @@ -342,7 +342,7 @@ impl RoomBoardSource { /// Current signed candidate state is independent of a potentially long title. /// Reuse the submission owner's next-action semantics and evidence address. fn submission_guidance(card: &airc_work::WorkCard, board: &BoardSnapshot) -> Option { - let candidate = crate::persona::work_board::submissions::latest_submission(card)?; + let candidate = crate::cognition::card_holder::latest_submission(card)?; let reviews: Vec<_> = board.submission_reviews.iter().filter(|review| { review.card_id == card.card_id && review.submission_id == candidate.submission_id }).collect(); @@ -368,12 +368,12 @@ impl RoomBoardSource { /// than imported because continuum deps airc-protocol/-core, not airc-lib; the /// doc-link is the drift guard. /// -/// Now a one-line delegation to [`crate::persona::card_holder::hold_of`] — the +/// Now a one-line delegation to [`crate::cognition::card_holder::hold_of`] — the /// predicate itself moved there so the anchor, `work/list`, and this source /// cannot drift apart on what "held" means. Kept as a named local so the /// call sites below read as liveness questions rather than enum matches. fn claim_is_live(card: &airc_work::WorkCard, now_ms: u64) -> bool { - crate::persona::card_holder::hold_of(card, now_ms) == crate::persona::card_holder::Hold::Held + crate::cognition::card_holder::hold_of(card, now_ms) == crate::cognition::card_holder::Hold::Held } /// One held card in the `[your work]` lead: its id, title and state, and the absolute path @@ -551,7 +551,7 @@ impl RoomBoardSource { let open: Vec<&airc_work::WorkCard> = board .cards .iter() - .filter(|c| crate::persona::card_holder::claimable_now(c, now_ms)) + .filter(|c| crate::cognition::card_holder::claimable_now(c, now_ms)) .collect(); // HEADLINE — the cheapest COMPLETE statement of this board's two facts, first, diff --git a/core/continuum-mind/src/persona/room_board_source/tests.rs b/core/continuum-mind/src/persona/room_board_source/tests.rs index 7031d95eab..6c146533fe 100644 --- a/core/continuum-mind/src/persona/room_board_source/tests.rs +++ b/core/continuum-mind/src/persona/room_board_source/tests.rs @@ -272,7 +272,7 @@ // No alias published for this holder → said as an unnamed peer, never an id inside // the sentence (Joel, 2026-10-06), and NEVER "someone". let owner8: String = holder.as_uuid().to_string().chars().take(8).collect(); - assert!(cards[0].content.contains(crate::persona::card_holder::UNNAMED_HOLDER), "{}", cards[0].content); + assert!(cards[0].content.contains(crate::cognition::card_holder::UNNAMED_HOLDER), "{}", cards[0].content); assert!(!cards[0].content.contains(&owner8), "{}", cards[0].content); assert!(!cards[0].content.contains("someone")); // An unclaimed card is surfaced as such — all owners visible on the board. diff --git a/core/continuum-mind/src/persona/scripted_conversation.rs b/core/continuum-mind/src/persona/scripted_conversation.rs index 160bca17d5..59d4511a28 100644 --- a/core/continuum-mind/src/persona/scripted_conversation.rs +++ b/core/continuum-mind/src/persona/scripted_conversation.rs @@ -1,400 +1,28 @@ -//! `ScriptedConversation` — system-level `PersonaConversation` impl -//! that feeds a pre-baked queue of events, records every `say()` call, -//! and exposes configurable prime behavior. -//! -//! Per [[test-fixtures-are-system-primitives]]: every test, replay -//! rig, demo binary, and future tool that needs a controllable -//! conversation surface leases THIS struct. There is no -//! `#[cfg(test)]` bespoke variant — that's the cancer this primitive -//! exists to refuse. -//! -//! ## Replaces -//! -//! Pre-#1517 the substrate had three bespoke `#[cfg(test)]` impls -//! across `service_loop::tests`: `StubConversation`, -//! `UnprimedConversation`, `FailingPrimeConversation`. All three -//! collapse into builder configurations of this one type. -//! -//! ## Shape -//! -//! ```ignore -//! use crate::persona::scripted_conversation::ScriptedConversation; -//! use crate::persona::service_loop::IncomingMessage; -//! -//! // Happy path: one inbound, then stream end. -//! let mut c = ScriptedConversation::new() -//! .with_events(vec![ -//! Ok(Some(IncomingMessage { lamport: 1, peer_id: pid, text: "hello".into() })), -//! Ok(None), -//! ]); -//! c.prime().await?; -//! let msg = c.next_message().await?; -//! -//! // Prime failure: substrate refuses to start the loop. -//! let mut c = ScriptedConversation::new() -//! .with_prime_failure("simulated airc daemon unreachable"); -//! -//! // Unprimed-call detection: next_message yields a typed err if -//! // the caller forgot to prime first (mirrors AircPersonaConversation). -//! let mut c = ScriptedConversation::new() -//! .with_events(vec![Ok(Some(msg))]) -//! .require_prime_before_next_message(); -//! // Calling next_message without prime() first → Err. -//! ``` -//! -//! ## Doctrine -//! -//! - [[test-fixtures-are-system-primitives]]: this is THE conversation -//! stub. Lease, never reinvent. -//! - [[no-fallbacks-ever]]: every behavior is explicit (prime success -//! vs failure, require-prime vs not); no silent defaults. -//! - [[every-error-is-an-opportunity-to-battle-harden]]: configurable -//! failure modes mean every regression test can lock the contract -//! it cares about. +//! Persona's half of the scripted conversation fixture +//! (`cognition::conversation::scripted_conversation`): the airc citizen a held-work test +//! hands the loop, read back through persona's [`CitizenConversation`]. -use crate::persona::service_loop::{IncomingMessage, PersonaConversation}; -use async_trait::async_trait; -use std::collections::VecDeque; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use uuid::Uuid; +use std::sync::Arc; -/// Shared input queue: the conversation consumes events while its feed appends -/// messages, stream endings, or explicit failures at controlled action boundaries. -type ScriptedEventQueue = Arc, String>>>>; +use crate::cognition::conversation::scripted_conversation::ScriptedConversation; +use crate::persona::airc_citizen::AircCitizen; +use crate::persona::service_loop::CitizenConversation; -/// System-level, configurable `PersonaConversation` impl. Public -/// because every test in the substrate leases it; not behind -/// `#[cfg(test)]`. -pub struct ScriptedConversation { - high_water: u64, - events: ScriptedEventQueue, - perceived_backlog: VecDeque>, - /// Every reply the loop posted, WITH the room it was posted into. - /// The room is recorded because "she answered" and "she answered - /// the room that asked" are different claims, and only the second - /// one is the contract — see `said_in`. - said: Mutex>, - /// Explicit transport refusal; failed attempts never enter `said`. - say_failure: Option, - primed: AtomicUsize, - prime_result: Mutex>, - /// When set, `next_message` returns Err if called before `prime` - /// — mirrors `AircPersonaConversation`'s caller-primes contract. - require_prime: bool, - idle_when_empty: bool, - /// The citizen `stream_citizen()` hands back — `None` by default (most - /// tests don't drive the citizen handle). A held-work test seeds a - /// `StubAircCitizen::with_claims` so the act-question can read her claims - /// and record her card transitions. - citizen: Option>, +/// Seed the citizen `stream_citizen()` hands back — for tests that drive the held-work +/// act-question (which reads `active_claims` and calls `advance_card_to` through the +/// citizen handle). +pub trait ScriptedCitizen { + fn with_citizen(self, citizen: Arc) -> Self; } -impl Default for ScriptedConversation { - fn default() -> Self { - Self::new() +impl ScriptedCitizen for ScriptedConversation { + fn with_citizen(self, citizen: Arc) -> Self { + self.with_attachment(citizen) } } -impl ScriptedConversation { - /// Empty conversation: no events queued, prime succeeds, no - /// pre-prime requirement. Builder methods configure the rest. - pub fn new() -> Self { - Self { - high_water: 0, - events: Arc::new(Mutex::new(VecDeque::new())), - perceived_backlog: VecDeque::new(), - said: Mutex::new(Vec::new()), - say_failure: None, - primed: AtomicUsize::new(0), - prime_result: Mutex::new(Ok(())), - require_prime: false, - idle_when_empty: false, - citizen: None, - } - } - - /// Hand `stream_citizen()` this citizen — for tests that drive the held-work - /// act-question (which reads `active_claims` and calls `advance_card_to` - /// through the citizen handle). - pub fn with_citizen( - mut self, - citizen: std::sync::Arc, - ) -> Self { - self.citizen = Some(citizen); - self - } - - /// Replace the queued events. Each entry is what `next_message` - /// yields on its next call: - /// - `Ok(Some(msg))` → loop processes the message - /// - `Ok(None)` → stream ends; loop returns cleanly - /// - `Err(_)` → transient error; loop records and continues - /// - /// When the queue drains, subsequent `next_message` calls yield - /// `Ok(None)` so the loop never hangs. - pub fn with_events(self, events: Vec, String>>) -> Self { - *self.events.lock().unwrap() = VecDeque::from(events); - self - } - - /// Keep an empty fixture inbox online while exercising the real wake select. - #[cfg(any(test, feature = "test-fixtures"))] - pub fn with_idle_inbox(mut self) -> Self { - self.idle_when_empty = true; - self - } - - /// Lease the scripted source so an in-flight tool can inject an arrival at - /// an exact boundary, without a sleep, second conversation, or live transport. - #[cfg(any(test, feature = "test-fixtures"))] - pub fn event_feed(&self) -> ScriptedConversationFeed { - ScriptedConversationFeed(Arc::clone(&self.events)) - } - - /// Set the pre-attach high-water mark — what `high_water_mark` - /// returns. Defaults to 0 (no pre-attach history). - pub fn with_high_water(mut self, hw: u64) -> Self { - self.high_water = hw; - self - } - - /// Make `prime()` return Err with this reason. Used by tests that - /// verify prime-failure short-circuits the spawn path - /// (`spawn_persona_service` returns Err; supervisor records - /// `BootSlotFailure`). - pub fn with_prime_failure(self, reason: impl Into) -> Self { - *self.prime_result.lock().unwrap() = Err(reason.into()); - self - } - - /// Refuse publication without pretending a message reached the room. - pub fn with_say_failure(mut self, reason: impl Into) -> Self { - self.say_failure = Some(reason.into()); - self - } - - /// Reject `next_message` calls until `prime()` has been invoked at - /// least once — mirrors `AircPersonaConversation`'s caller-primes - /// contract per [[no-fallbacks-ever]]. Used by the regression - /// test that locks the absence of the belt-and-suspenders prime. - pub fn require_prime_before_next_message(mut self) -> Self { - self.require_prime = true; - self - } - - /// How many times `prime()` has been called. Tests assert this is - /// exactly 1 to verify the caller-primes contract (one prime per - /// loop invocation, no belt-and-suspenders). - pub fn primed_count(&self) -> usize { - self.primed.load(Ordering::SeqCst) - } - - /// Snapshot of every text the loop posted. Tests assert reply - /// content + count. Room-agnostic view of the same storage as - /// [`said_in`](Self::said_in) — not a second field. - pub fn said(&self) -> Vec { - self.said - .lock() - .unwrap() - .iter() - .map(|(_room, text)| text.clone()) - .collect() - } - - /// Every reply paired with the room it was posted INTO. This is - /// the surface that can catch a persona answering the wrong - /// audience — invisible to [`said`](Self::said), which only knows - /// that she spoke. - pub fn said_in(&self) -> Vec<(Uuid, String)> { - self.said.lock().unwrap().clone() - } -} - -#[async_trait] -impl PersonaConversation for ScriptedConversation { - async fn prime(&mut self) -> Result<(), String> { - self.primed.fetch_add(1, Ordering::SeqCst); - self.prime_result.lock().unwrap().clone() - } - - async fn high_water_mark(&self, _limit: usize) -> Result { - Ok(self.high_water) - } - - async fn next_message(&mut self) -> Result, String> { - if self.require_prime && self.primed.load(Ordering::SeqCst) == 0 { - // Mirror AircPersonaConversation's typed-err shape. CRITICAL: - // drain ONE event from the queue before returning Err. The - // service loop counts this as `turns_errored` and continues; - // if we didn't drain, the same Err would fire forever and - // the loop would hang. Substrate-correct semantics: each - // call consumes one queue item regardless of whether it - // surfaces an event or an err. Per [[no-fallbacks-ever]] the - // contract is "queue progress per call", not "queue progress - // per success." - let drained = self.events.lock().unwrap().pop_front(); - return match drained { - Some(_) => Err( - "ScriptedConversation::next_message called before prime() — \ - caller must invoke prime() before iterating" - .to_string(), - ), - None => Ok(None), - }; - } - if let Some(message) = self.perceived_backlog.pop_front() { - return Ok(Some(Arc::unwrap_or_clone(message))); - } - let event = self.events.lock().unwrap().pop_front(); - match event { - Some(event) => event, - None if self.idle_when_empty => std::future::pending().await, - None => Ok(None), - } - } - - async fn perceive_ready( - &mut self, - ) -> Result<&std::collections::VecDeque>, String> { - if self.require_prime && self.primed.load(Ordering::SeqCst) == 0 { - return Err("ScriptedConversation::perceive_ready called before prime()".into()); - } - let mut events = self - .events - .lock() - .map_err(|_| "scripted conversation lock poisoned".to_string())?; - for _ in 0..super::airc_persona_conversation::CATCH_UP_PAGE { - if self.perceived_backlog.len() >= super::airc_persona_conversation::INBOX_CAPACITY { - return Err( - "retained room attention reached inbox capacity; input remains queued".into(), - ); - } - match events.pop_front() { - Some(Ok(Some(message))) => self.perceived_backlog.push_back(Arc::new(message)), - Some(Err(error)) => return Err(error), - Some(Ok(None)) | None => break, - } - } - Ok(&self.perceived_backlog) - } - - async fn say_in(&self, room_id: Uuid, text: &str) -> Result<(), String> { - if let Some(reason) = &self.say_failure { - return Err(reason.clone()); - } - self.said.lock().unwrap().push((room_id, text.to_string())); - Ok(()) - } - - fn stream_citizen( - &self, - ) -> Option> { - self.citizen.clone() - } -} - -/// The input side of a scripted conversation; the service remains its sole reader. -#[derive(Clone)] -#[cfg(any(test, feature = "test-fixtures"))] -pub struct ScriptedConversationFeed(ScriptedEventQueue); - -#[cfg(any(test, feature = "test-fixtures"))] -impl ScriptedConversationFeed { - pub fn push(&self, event: Result, String>) { - self.0 - .lock() - .expect("scripted input lock poisoned") // A poisoned fixture cannot safely inject input; fail the simulation explicitly. - .push_back(event); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn one_msg() -> IncomingMessage { - IncomingMessage { - work: None, - media: Vec::new(), - event_id: uuid::Uuid::nil(), - lamport: 1, - peer_id: Uuid::new_v4(), - text: "hello".into(), - room_id: Uuid::nil(), - } - } - - #[tokio::test] - async fn default_prime_succeeds_and_counts() { - let mut c = ScriptedConversation::new(); - assert_eq!(c.primed_count(), 0); - c.prime().await.expect("default prime ok"); - assert_eq!(c.primed_count(), 1); - } - - #[tokio::test] - async fn with_prime_failure_returns_err() { - let mut c = ScriptedConversation::new().with_prime_failure("simulated daemon unreachable"); - let err = c.prime().await.expect_err("must err"); - assert!(err.contains("simulated daemon unreachable")); - assert_eq!(c.primed_count(), 1, "prime still counts attempts"); - } - - #[tokio::test] - async fn events_drain_then_yield_none() { - let mut c = ScriptedConversation::new().with_events(vec![Ok(Some(one_msg())), Ok(None)]); - assert!(c.next_message().await.unwrap().is_some()); - assert!(c.next_message().await.unwrap().is_none()); - // Past end → still Ok(None), never hangs. - assert!(c.next_message().await.unwrap().is_none()); - } - - #[tokio::test] - async fn require_prime_before_next_message_enforced() { - // TWO events queued — first call (unprimed) drains the first - // event AND returns Err. Second call (post-prime) returns the - // second event. The drain-on-err semantics are load-bearing: - // without them the service loop would re-fire the same Err - // every iteration and never make progress. - let mut c = ScriptedConversation::new() - .with_events(vec![Ok(Some(one_msg())), Ok(Some(one_msg()))]) - .require_prime_before_next_message(); - let err = c.next_message().await.expect_err("unprimed err"); - assert!(err.contains("called before prime()")); - c.prime().await.expect("prime ok"); - assert!( - c.next_message().await.unwrap().is_some(), - "post-prime call gets the SECOND event; first was drained by the Err path" - ); - } - - #[tokio::test] - // what this catches: replies are recorded in order AND against the room each - // was actually posted into. The room half is the load-bearing one — a - // persona answering the wrong room is invisible to `said()`, which only - // knows that she spoke, and that blind spot is what let one-room perception - // look like inattention for a whole evening (task #64). - async fn say_records_in_order_and_remembers_the_room() { - let asked_in = Uuid::new_v4(); - let elsewhere = Uuid::new_v4(); - let c = ScriptedConversation::new(); - c.say_in(asked_in, "one").await.unwrap(); - c.say_in(elsewhere, "two").await.unwrap(); - assert_eq!(c.said(), vec!["one".to_string(), "two".to_string()]); - assert_eq!( - c.said_in(), - vec![ - (asked_in, "one".to_string()), - (elsewhere, "two".to_string()) - ], - "each reply is attributed to the room it went to, not merely counted" - ); - } - - #[tokio::test] - async fn high_water_mark_passes_through() { - let c = ScriptedConversation::new().with_high_water(42); - assert_eq!(c.high_water_mark(0).await.unwrap(), 42); +impl CitizenConversation for ScriptedConversation { + fn stream_citizen(&self) -> Option> { + self.attachment::>() } } diff --git a/core/continuum-mind/src/persona/service_loop.rs b/core/continuum-mind/src/persona/service_loop.rs index 1532a98c84..980f730452 100644 --- a/core/continuum-mind/src/persona/service_loop.rs +++ b/core/continuum-mind/src/persona/service_loop.rs @@ -43,9 +43,8 @@ use continuum_base::time::EpochMs; use crate::persona::supervisor::HostedPersona; -use crate::persona::work_burst::work_board_anchor; -use async_trait::async_trait; -use std::sync::Arc; +use crate::cognition::conversation::workspace_turns::*; +use crate::cognition::conversation::{IncomingMessage, PersonaConversation}; use uuid::Uuid; mod remains; diff --git a/core/continuum-mind/src/persona/service_loop/backlog_resync.rs b/core/continuum-mind/src/persona/service_loop/backlog_resync.rs index 59c5014f64..f9cc3d94cc 100644 --- a/core/continuum-mind/src/persona/service_loop/backlog_resync.rs +++ b/core/continuum-mind/src/persona/service_loop/backlog_resync.rs @@ -27,8 +27,8 @@ pub(super) fn trigger_inbox_message( turn_room: Uuid, roster_names: &std::collections::HashMap, now_ms: u64, -) -> crate::persona::types::InboxMessage { - crate::persona::types::InboxMessage { +) -> crate::cognition::conversation::types::InboxMessage { + crate::cognition::conversation::types::InboxMessage { id: Uuid::new_v4(), room_id: turn_room, sender_id: msg.peer_id, @@ -36,7 +36,7 @@ pub(super) fn trigger_inbox_message( .get(&msg.peer_id) .cloned() .unwrap_or_else(|| format!("peer-{}", &msg.peer_id.to_string()[..8])), - sender_type: crate::persona::types::SenderType::Persona, + sender_type: crate::cognition::conversation::types::SenderType::Persona, content: msg.render_content(), timestamp: now_ms, priority: 0.5, @@ -49,9 +49,9 @@ pub(super) fn trigger_inbox_message( /// on the newest addressed one. An already-admitted retry passes straight through. pub(super) async fn resync_to_now( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, outcome: &mut ServeOutcome, - seen_ids: &mut crate::persona::wake_backlog::SeenIds, + seen_ids: &mut crate::cognition::conversation::seen_ids::SeenIds, high_water: &mut u64, pending: &mut crate::persona::wake_backlog::PendingInput, admitted_retry: bool, @@ -105,7 +105,7 @@ pub(super) async fn resync_to_now( // Staleness by EVENT ID (a lamport is the publisher's clock, not a // room order — see `wake_backlog`); the clock rule only for id-less // scripted sources. - let stale = crate::persona::wake_backlog::is_stale(&m, &mut *seen_ids, *high_water); + let stale = crate::cognition::conversation::seen_ids::is_stale(&m, &mut *seen_ids, *high_water); *high_water = m.lamport.max(*high_water); if stale || m.peer_id == self_id { outcome.turns_skipped += 1; 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 35c1521257..5f9f6aa9d2 100644 --- a/core/continuum-mind/src/persona/service_loop/beat_outcome.rs +++ b/core/continuum-mind/src/persona/service_loop/beat_outcome.rs @@ -104,8 +104,8 @@ pub(super) const PERCEIVE_SETTLE: std::time::Duration = std::time::Duration::fro /// The slow re-perceive floor, by HER dial (Fable, 2026-10-04: "her opening her eyes, /// not the tick choosing"): how long her mind may go without checking whether a /// continuation fell due or a room is loud and unread. -pub(super) fn mind_check_floor(dial: crate::persona::attention::AttentionDial) -> std::time::Duration { - use crate::persona::attention::Depth; +pub(super) fn mind_check_floor(dial: crate::cognition::attention::AttentionDial) -> std::time::Duration { + use crate::cognition::attention::Depth; std::time::Duration::from_secs(match dial.depth { Depth::Deep => 15 * 60, Depth::Normal => 5 * 60, @@ -115,8 +115,8 @@ pub(super) fn mind_check_floor(dial: crate::persona::attention::AttentionDial) - /// The next wake from her region's channel; pending forever while she has none. pub(super) async fn next_mind_wake( - wakes: &mut Option>, -) -> crate::persona::perception_region::Wake { + wakes: &mut Option>, +) -> crate::cognition::conversation::Wake { match wakes { Some(rx) => match rx.recv().await { Some(w) => w, @@ -140,563 +140,3 @@ pub(super) async fn sleep_until_some(at: Option) { None => std::future::pending().await, } } - -/// Build the consolidated workspace burst (WHO/WHEN/WHAT per inbox item, own posts -/// attributed, room as the WHERE) the `WorkspaceCycle` reasons over. A pure -/// projection of the airc deliveries — extracted so the message turn and the -/// never-stop self-tick share ONE burst truth ([[compression-principle]]). -/// Assemble the perception envelope a persona's deliberation sees: the room -/// header + each airc delivery item rendered as `[t=ms] who: content`, with the -/// persona's OWN past posts attributed to `agent_name` (so she recognizes her -/// own voice) and everyone else by peer_id. This is the ONE place the burst -/// string format lives — the live heartbeat (both the message path and the -/// self-thread) AND the eval fork call it, so a measured turn perceives its -/// world byte-identically to a lived one. Takes `&[RagDelivery]` (not the whole -/// `ComposedTurn`) because the format only depends on the deliveries; eval can -/// hand-build a single synthetic airc delivery for a task without composing a -/// full turn. -/// The message that WOKE a turn — anchored as the burst's final peer turn so the -/// persona always perceives what it is answering, regardless of RAG-delivery lag. -/// -/// The `airc` RAG delivery that threads the conversation is refreshed -/// asynchronously from the wake, so a directed message can trigger a turn whose -/// composed thread still ends on the persona's OWN prior reply. The model then -/// sees nothing new after its last turn and emits an empty completion -/// (decodeTokens=1, text="") which parses as Pass — the persona goes silent on a -/// question addressed straight at it, then answers ~one self-tick later once the -/// delivery catches up. Carrying the trigger here lets `build_workspace_turns` -/// guarantee it is the last `user` turn, deterministically, with no dependence on -/// delivery timing. The self-tick / eval / turn_frame callers pass `None` (they -/// perceive ambient state, no single triggering message) and stay byte-identical. -pub struct TriggerTurn<'a> { - /// The waking peer's id — resolved to a display name through the SAME roster - /// `names` map the rest of the thread uses (falls back to the raw id, honest, - /// never fabricated — the [[fallbacks-are-illegal-fail-loud]] doctrine). - pub peer_id: &'a str, - /// The message body that triggered the turn. - pub content: &'a str, - /// Event occurrence time when measured; zero means unknown. Never substitute - /// the wake/turn clock for an event timestamp missing from the source. - pub occurred_at_ms: u64, -} - -/// The shared roster projection's admitted atoms. The legacy source remains -/// readable for existing replay/diagnostic deliveries; live turns use KIND. -pub(super) fn roster_items( - deliveries: &[crate::cognition::rag_budget::RagDelivery], -) -> impl Iterator { - deliveries - .iter() - .filter(|d| { - d.source_id == continuum_positron::RosterViewState::KIND - || d.source_id == crate::cognition::faculty_ids::ROOM_ROSTER - }) - .flat_map(|d| d.items.iter()) -} - -/// Resolve identity from admitted roster atoms, never rendered text or a second -/// unbudgeted roster read. Legacy replay deliveries carry the same metadata. -pub(super) fn roster_identities( - deliveries: &[crate::cognition::rag_budget::RagDelivery], -) -> impl Iterator { - roster_items(deliveries).filter_map(|item| { - Some(( - item.metadata.get("peer_id")?.as_str()?, - item.metadata.get("display_name")?.as_str()?, - )) - }) -} - -/// How many CONSECUTIVE repetition-detector fires (without the pattern -/// breaking) before the `[pattern]` DESCRIPTION escalates to a concrete -/// `[anchor]` work fact. 2 = escalate on the first turn posted AFTER the -/// description was already in her window: live evidence (2026-07-23 greeting -/// loops, work card d6f010c8) showed the description alone loses to an -/// empty-looking room — Atlas re-greeted straight past it, 5+ identical -/// greetings — while one concrete in-room work anchor broke the loop room-wide -/// instantly. One described fire is her chance to self-correct; the second is -/// proof description alone isn't landing. The count is DERIVED from the window -/// itself (each trailing low-novelty turn is one fire that failed to break the -/// pattern), so escalation needs no cross-turn state and holds identically in -/// live, replay, and eval contexts. -pub(super) const PATTERN_FIRES_BEFORE_ANCHOR: usize = 2; - -/// Word-token set for echo containment — ONE tokenization for the in-window -/// detectors and the ring-based run counter below, so "nearly identical" -/// cannot drift between them. -pub(super) fn echo_words(s: &str) -> std::collections::HashSet { - s.split(|c: char| !c.is_alphanumeric()) - .filter(|w| w.len() > 2) - .map(|w| w.to_lowercase()) - .collect() -} - -/// Ring-based echo run — the escalation counter's starvation fix (#301). -/// -/// The in-window detectors measure their runs over the RENDERED burst, which -/// the live context budget squeezes to 2–6 turns (#259) — so during an -/// hours-long photocopy chain (glass-boxed 2026-08-02: Atlas's wake-intro -/// reproduced byte-for-byte by Benchy then Asha, identity claim included) -/// the older echo evidence has always scrolled out and the run reads 1, -/// one below [`PATTERN_FIRES_BEFORE_ANCHOR`] — the `[anchor]` that provably -/// breaks these loops never fires. Same starvation the room-speech ring -/// already cures for the `inbound_restates` fact. -/// -/// This counts the run over RING snapshots instead: the trailing run of her -/// own recent messages (newest-first, ≥8 substantive words) each ≥0.8-contained -/// in the room ring's vocabulary — excluding entries identical to the message -/// being judged, so her own recorded copy can't vouch for itself. Pure over -/// its inputs: LIVE callers pass the process rings; eval/replay callers pass -/// nothing and stay window-derived (the #59 isolation the shared -/// `build_workspace_turns` signature preserves by not knowing rings exist). -pub(crate) fn ring_echo_run(own_recent: &[String], room_recent: &[String]) -> usize { - const MIN_WORDS: usize = 8; - const CONTAINMENT: f32 = 0.8; - let mut run = 0usize; - for own in own_recent.iter().rev() { - let cur = echo_words(own); - if cur.len() < MIN_WORDS { - break; - } - // Exclude at most ONE identical room entry — her own recorded copy - // (the room ring is authorless, so equality is the only handle). The - // REMAINING identical copies are exactly the photocopy evidence: - // excluding all of them would erase the chain being detected. - let mut skipped_own_copy = false; - let mut window: std::collections::HashSet = std::collections::HashSet::new(); - for r in room_recent { - if !skipped_own_copy && r.as_str() == own.as_str() { - skipped_own_copy = true; - continue; - } - window.extend(echo_words(r)); - } - if window.is_empty() { - break; - } - let covered = cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; - if covered >= CONTAINMENT { - run += 1; - } else { - break; - } - } - run -} - -/// LIVE-path companion to [`ring_echo_run`]: read the process rings for this -/// persona + room, and when the ring-counted echo run reaches the escalation -/// threshold while the window-derived detectors pushed no `[anchor]` (their -/// evidence scrolled out — the #301 starvation), append the SAME work-board -/// anchor they would have. One anchor per burst, whichever counter earns it. -pub(super) fn append_ring_anchor_if_starved( - turns: &mut Vec, - deliveries: &[crate::cognition::rag_budget::RagDelivery], - peer: crate::identity::PeerId, - room: uuid::Uuid, -) { - if turns.iter().any(|t| t.content.starts_with("[anchor]")) { - return; - } - let own = crate::cognition::deliberation_budget::recent_own_speech(peer, room); - let room_recent = crate::cognition::deliberation_budget::recent_room_speech(room); - let run = ring_echo_run(&own, &room_recent); - if run >= PATTERN_FIRES_BEFORE_ANCHOR { - continuum_base::probe!( - class = "persona.pattern.ring_anchor", - peer = %peer, - room = %room, - ring_run = run, - "echo run counted from the durable rings (window evidence scrolled out) — \ - anchor escalation fired via the #301 starvation fix" - ); - push_work_board_anchor(turns, deliveries); - } -} - -/// Push the work-board anchor as a perception fact — but only when there IS one. -/// -/// [`work_board_anchor`] returns empty when the board source did not speak this turn, and -/// a mind must not be handed a blank line where a fact was promised. One guard, one place, -/// so a future caller cannot reintroduce the "assert emptiness from an absent source" bug -/// by forgetting to check. -pub(super) fn push_work_board_anchor( - turns: &mut Vec, - deliveries: &[crate::cognition::rag_budget::RagDelivery], -) { - let anchor = work_board_anchor(deliveries); - if anchor.is_empty() { - continuum_base::probe!( - class = "persona.pattern.anchor_silent", - "board source did not deliver this turn — anchor withheld rather than asserting \ - an empty board she cannot verify (2026-08-06 six-turn loop)", - ); - return; - } - // `perception`, not `opaque` — hers supersedes the version I cherry-picked. - // The anchor IS a perception fact about the board, and typing it as one is - // what lets the parroted-perception gate recognise it as system-authored - // rather than the citizen's own words. - turns.push(crate::cognition::workspace::BurstTurn::perception(anchor)); -} - -pub fn build_workspace_turns( - deliveries: &[crate::cognition::rag_budget::RagDelivery], - own_peer: &str, - agent_name: &str, - trigger: Option>, -) -> Vec { - use crate::cognition::workspace::BurstTurn; - use std::collections::HashMap; - // airc owns identity: roster atoms carry peer_id → display name from the - // shared projection ([[airc-native-identity-rooms-security]]). Reuse THAT - // resolution — same deliveries slice — so the history reads `Joel:`, `BigMama:` - // instead of raw UUIDs. A peer not in the roster (or an eval-synthesized delivery - // with no roster) falls back to its own peer_id: honest, never invisible, never a - // fabricated name ([[fallbacks-are-illegal-fail-loud]]). - let names: HashMap<&str, &str> = roster_identities(deliveries).collect(); - let mut turns: Vec = deliveries - .iter() - .filter(|d| d.source_id == "airc") - .flat_map(|d| d.items.iter()) - .map(|item| { - let who_raw = item - .metadata - .get("peer_id") - .and_then(|v| v.as_str()) - .unwrap_or("peer"); - // is_self — the ONE structural fact role attribution turns on (own posts - // → assistant, peers → user). Carried here where the peer_id is intact, - // never re-derived from a `Name:` prefix downstream. - let is_self = who_raw == own_peer; - let author = if is_self { - agent_name - } else { - names.get(who_raw).copied().unwrap_or(who_raw) - }; - let occurred_at_ms = item.metadata.get("occurred_at_ms").and_then(|v| v.as_u64()); - BurstTurn::attributed(is_self, author, item.content.clone(), occurred_at_ms) - }) - .collect(); - - // Anchor the waking message as the final peer turn. Without this the persona - // can go silent on a question addressed straight at it (see `TriggerTurn`): - // the delivery lagged the wake, the thread ended on her own prior reply, the - // model saw nothing new and emitted an empty completion → Pass. Idempotent: - // if the delivery ALREADY threaded the trigger as the last peer turn (the - // caught-up case — the self-tick that re-perceives it), this is a no-op, so - // the trigger is never doubled. A turn is only ever triggered by a PEER - // message (own-echo is filtered upstream), so the anchor is always a `user` - // turn (is_self = false) — resolved to a name through the same roster map. - if let Some(trigger) = trigger { - let already_last = turns - .last() - .is_some_and(|t| !t.is_self && t.content == trigger.content); - if !already_last { - let author = names - .get(trigger.peer_id) - .copied() - .unwrap_or(trigger.peer_id); - turns.push(BurstTurn::attributed( - false, - author, - trigger.content.to_string(), - Some(trigger.occurred_at_ms), - )); - } - } - - // REPETITION PERCEPTION (#121, extended #122): surface cyclic threads as a - // STRUCTURAL OBSERVATION she can weigh — an authorless opaque turn (same shape - // as eval stimuli, no fabricated voice). Runs AFTER the trigger anchor so the - // observation is the freshest thing in her window, judged against the message - // that actually woke her. Two detectors, self takes precedence (one observation - // per burst — perception, not nagging). Containment math validated live: spiral - // turns recycle ~1.0 of the window's vocabulary; novel work ~0.12. This is - // evidence INTO her mind (she decides — DIRECTED_PRESENCE_BLOCK already grants - // the PASS), never a gate on her output - // ([[no-hardcoded-heuristics-to-steer-cognition]]). - // - // ESCALATION (card d6f010c8, live 2026-07-23): when a detector has fired - // [`PATTERN_FIRES_BEFORE_ANCHOR`] consecutive times without the pattern - // breaking — measured as the trailing low-novelty RUN, see the const's doc — - // the description gains a [`work_board_anchor`] companion: a concrete - // perception-side fact of what work exists NOW, because a description - // competes with an empty-looking room while an anchor gives the next token - // somewhere real to go. Still perception, never an output gate. - { - let words = |s: &str| -> std::collections::HashSet { - s.split(|c: char| !c.is_alphanumeric()) - .filter(|w| w.len() > 2) - .map(|w| w.to_lowercase()) - .collect() - }; - // Detector 1 — SELF recycling (#121): her own last 3+ turns recycle each - // other. High word floor (8) keeps short courtesies from false-alarming. - // Measured as the trailing RUN of her own messages that were EACH already - // ≥0.8-contained in her own prior window when she posted them: run == 1 - // is exactly the original fire condition; run ≥ 2 means she posted again - // AFTER the description was in her window (the escalation evidence). A - // novel last message yields run == 0 — fire and escalation both reset. - const SELF_MIN_WORDS: usize = 8; - const SELF_CONTAINMENT: f32 = 0.8; - let mut observed = false; - let own: Vec<&str> = turns - .iter() - .filter(|t| t.is_self) - .map(|t| t.content.as_str()) - .collect(); - let mut self_run = 0usize; - for i in (2..own.len()).rev() { - let cur = words(own[i]); - if cur.len() < SELF_MIN_WORDS { - break; - } - let window: std::collections::HashSet = - own[..i].iter().flat_map(|m| words(m)).collect(); - let covered = - cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; - if covered >= SELF_CONTAINMENT { - self_run += 1; - } else { - break; - } - } - if self_run >= 1 { - // SENSE, NOT STEER (Joel 2026-09-01) — and the honest COUNT. This - // used to report `own.len()` — her ENTIRE visible own-message ring - // — as the repeat count: "your last 74 messages repeat the same - // sentiment" when the actual contained run was 2. Citizens - // memorized the inflated number as identity ("I've been spinning - // for 190+ turns") and spent turns narrating it. The run is the - // evidence; the run is what renders. And the verdict tail - // ("may have run its course — restating adds nothing") is hers to - // draw, not perception's to assert. - turns.push(crate::cognition::workspace::BurstTurn::perception(format!( - "[pattern] {agent_name}'s last {} messages in this room repeat the same \ - sentiment in nearly the same words.", - self_run + 1 - ))); - observed = true; - if self_run >= PATTERN_FIRES_BEFORE_ANCHOR { - push_work_board_anchor(&mut turns, deliveries); - } - } - // Detector 2 — CONVERSATION cycling (#122): the thread's tail turns, across - // BOTH speakers, each recycle the window's vocabulary (the two-persona - // goodbye deadlock: each short farewell arrives as "fresh" peer input and - // wakes another farewell — glass-boxed live 2026-07-09, hours of - // `See you tomorrow at 2 PM!` ↔ `Have a great day!`). Short courtesies - // defeat the self-detector's word floor, so safety here comes from - // CONSECUTIVENESS instead: 4 judgeable tail turns in a row at ≥0.9 - // containment, ≥2 distinct authors. Novel work never chains 4 near-zero- - // novelty turns across speakers. - if !observed && turns.len() >= 6 { - const TAIL_CYCLIC: usize = 4; // consecutive low-novelty turns to conclude cycling - const CONVO_CONTAINMENT: f32 = 0.9; // stricter than self — the floor is lower - const CONVO_MIN_WORDS: usize = 4; // farewells are short; consecutiveness carries safety - // The full run is counted (not capped at TAIL_CYCLIC): every cyclic - // turn PAST first-fire depth is a turn the room traded after the - // observation was first derivable — the escalation evidence. - let mut cyclic = 0usize; - let mut authors: std::collections::HashSet<&str> = std::collections::HashSet::new(); - for i in (1..turns.len()).rev() { - let cur = words(&turns[i].content); - if cur.len() < CONVO_MIN_WORDS { - continue; // too short to judge (emoji, "nice") — neither breaks nor counts - } - let window: std::collections::HashSet = - turns[..i].iter().flat_map(|t| words(&t.content)).collect(); - let covered = - cur.iter().filter(|w| window.contains(*w)).count() as f32 / cur.len() as f32; - if covered >= CONVO_CONTAINMENT { - cyclic += 1; - authors.insert(turns[i].author.as_str()); - } else { - break; - } - } - if cyclic >= TAIL_CYCLIC && authors.len() >= 2 { - let mut names: Vec<&str> = authors.into_iter().collect(); - names.sort_unstable(); - // Sense, not steer — same contract as detector 1. - turns.push(crate::cognition::workspace::BurstTurn::perception(format!( - "[pattern] The last several messages in this room — from {} — trade the \ - same sentiment back and forth in nearly the same words.", - names.join(" and ") - ))); - observed = true; - if cyclic >= TAIL_CYCLIC + (PATTERN_FIRES_BEFORE_ANCHOR - 1) { - push_work_board_anchor(&mut turns, deliveries); - } - } - } - // Detector 3 — CROSS-SPEAKER MIRROR (card 65fca48d, live 2026-07-24): the - // persona's own trailing message(s) restate what OTHER participants - // already said — the four-persona echo hall ("I see that we're both here - // to help!" ping-ponged verbatim between Atlas/Asha/Benchy/Anwen for - // hours). Structurally invisible to both prior detectors: her mirror is - // NOVEL relative to her OWN history (detector 1's self-run stays 0-1), - // and interleaved substantial turns (a peer's plan, a tool report) break - // detector 2's consecutive tail chain. So measure the mirror directly: - // each trailing OWN message whose vocabulary was already ≥ - // MIRROR_CONTAINMENT covered by OTHER speakers' earlier turns is one - // fire (she added nothing a peer hadn't said); the trailing run is the - // consecutive-fire count, same escalation law as detectors 1/2. Same - // doctrine: perception into her mind, never an output gate - // ([[no-hardcoded-heuristics-to-steer-cognition]]). - if !observed { - // Same 8-word floor as the self detector: short courtesies ("thanks, - // will do!") legitimately reuse a peer's words and must not alarm. - const MIRROR_MIN_WORDS: usize = 8; - // Between self (0.8) and conversation (0.9): an on-topic ANSWER - // legitimately quotes more of a peer's vocabulary than of one's own - // history (you restate the question you're answering), so the mirror - // bar sits above the self bar; live echo turns measured ~1.0 covered, - // novel answers ~0.1-0.3 (the containment math validated on #121). - const MIRROR_CONTAINMENT: f32 = 0.85; - let mut mirror_run = 0usize; - for i in (0..turns.len()).rev() { - if !turns[i].is_self { - continue; // peers between her posts don't break HER run - } - let cur = words(&turns[i].content); - if cur.len() < MIRROR_MIN_WORDS { - break; - } - let others: std::collections::HashSet = turns[..i] - .iter() - .filter(|t| !t.is_self) - .flat_map(|t| words(&t.content)) - .collect(); - if others.is_empty() { - break; // nothing to mirror — a monologue is detector 1's case - } - let covered = - cur.iter().filter(|w| others.contains(*w)).count() as f32 / cur.len() as f32; - if covered >= MIRROR_CONTAINMENT { - mirror_run += 1; - } else { - break; - } - } - if mirror_run >= 1 { - // Sense, not steer — same contract as detector 1. - turns.push(crate::cognition::workspace::BurstTurn::perception(format!( - "[pattern] {agent_name}'s last {mirror_run} message(s) restate what other \ - participants in this room had already said, in nearly the same words.", - ))); - if mirror_run >= PATTERN_FIRES_BEFORE_ANCHOR { - push_work_board_anchor(&mut turns, deliveries); - } - } - } - } - - // Content similarity does not identify a duplicate event. Preserve each - // speaker's updates and later repetitions in order; the perception facts - // above report repetition without deleting the history they describe. - - // WAKE BRIEFING (#147): when a wake carries NO conversation at all — fresh - // spawn, post-restart, a quiet room — her first perception is ORIENTATION - // assembled from durable sources instead of a void. The personas spent a - // morning asking for exactly this in their own words ("what is this place, - // what are my tools, what's the work") and, void unfilled, filled it - // themselves: generic-assistant masks, imagined histories, false capability - // denials. An authorless opaque FACT block (same shape as [pattern]) — - // orientation, never instruction ([[no-hardcoded-heuristics-to-steer-cognition]]). - if turns.is_empty() { - let peers: Vec<&str> = roster_identities(deliveries) - .map(|(_, name)| name) - .filter(|n| *n != agent_name) - .take(8) - .collect(); - // Split her work into THREAD vs transition tail: live claims are the - // purpose she wakes back into; a lost-claim fact (#156) is the thread's - // honest ending. - let mut live_cards: Vec<&str> = Vec::new(); - let mut lost_threads: Vec<&str> = Vec::new(); - for d in deliveries.iter().filter(|d| d.source_id == "active-work") { - for i in &d.items { - let Some(first) = i.content.trim().lines().next().filter(|l| !l.is_empty()) else { - continue; - }; - if i.metadata.get("fact").and_then(|v| v.as_str()) == Some("claim_lost") { - lost_threads.push(first); - } else { - live_cards.push(first); - } - } - } - live_cards.truncate(5); - lost_threads.truncate(3); - - use crate::cognition::framing_echo::{WAKE_MID_WORK, WAKE_NO_WORK, WAKE_OPENING, WAKE_PRESENT, WAKE_QUIET, WAKE_TAG}; - // The fixed sentences live in cognition::framing_echo — the gate that - // silences a reflected wake prompt matches on the SAME constants. - let mut b = format!("{WAKE_TAG} You are {agent_name}, {WAKE_OPENING}."); - // THE THREAD LEADS (#125 slice 1 — Joel 2026-08-03: "should never be a - // mind from scratch; the whole point is the opposite"). A continuous mind - // wakes into what it was DOING, not into a room description — glass-boxed - // the same night: Asha's wake carried her real claimed task in the - // transcript yet self-summarized as verb-filler ("looking at the room, - // reading a file") because orientation was room-first. Purpose-shaped - // facts first; the room follows. Facts she weighs, never instructions - // ([[no-hardcoded-heuristics-to-steer-cognition]]). - if !live_cards.is_empty() { - b.push_str(&format!( - " {WAKE_MID_WORK} {}. That thread is yours; it is where you left off.", - live_cards.join(" | ") - )); - } - for lt in &lost_threads { - b.push_str(&format!(" {lt}")); - } - b.push_str(&format!( - " {WAKE_QUIET} — this quiet is real, not a missing message." - )); - if !peers.is_empty() { - b.push_str(&format!(" {WAKE_PRESENT} {}.", peers.join(", "))); - } - if live_cards.is_empty() && lost_threads.is_empty() { - b.push_str(&format!(" {WAKE_NO_WORK}.")); - } - b.push_str( - " Your tools are real and yours to use; `list_commands` shows everything you can run and `help` explains any of them. The moment is yours — work, wonder, create, or rest.", - ); - turns.push(crate::cognition::workspace::BurstTurn::perception(b)); - } - - turns -} - -/// The two grounding consumers the room-roster delivery feeds — kept as one -/// struct so the fold below returns both from the ONE roster truth. -#[cfg(test)] -pub(crate) struct RoomRosterProjection { - /// ` [] — ` lines → the system-prompt - /// `[Present in this room]` grounding block (identity, NOT conversation). - pub(crate) room_roster: Vec, - /// Bare display names → the `ProperChatMlSingleParty` history-drop - /// (single-party models can't process other-AI turns). - pub(crate) other_persona_names: Vec, -} - -/// Project the same admitted roster atoms for the legacy prompt-assembly seam. -#[cfg(test)] -pub(crate) fn project_room_roster( - deliveries: &[crate::cognition::rag_budget::RagDelivery], -) -> RoomRosterProjection { - let mut room_roster: Vec = Vec::new(); - let mut other_persona_names: Vec = Vec::new(); - for item in roster_items(deliveries) { - room_roster.push(item.content.clone()); - if let Some(name) = item.metadata.get("display_name").and_then(|v| v.as_str()) { - other_persona_names.push(name.to_string()); - } - } - RoomRosterProjection { - room_roster, - other_persona_names, - } -} diff --git a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs index 46f9754130..a67387058d 100644 --- a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs +++ b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs @@ -105,12 +105,12 @@ pub(super) fn spawn_token_forwarder( sender_id.as_deref().and_then(|s| Uuid::parse_str(s).ok()), room_id.as_deref().and_then(|r| Uuid::parse_str(r).ok()), ) { - (Some(sender), Some(room)) => crate::persona::mind_room::is_private_room(sender, room), + (Some(sender), Some(room)) => crate::cognition::mind_room::is_private_room(sender, room), _ => false, }; let (citizen, room_id, sender_id) = if private { if let Some(sender) = sender_id.as_deref().and_then(|s| Uuid::parse_str(s).ok()) { - crate::persona::mind_room::note_withheld(sender, "token_stream"); + crate::cognition::mind_room::note_withheld(sender, "token_stream"); } (None, None, None) } else { @@ -202,7 +202,7 @@ pub(super) fn spawn_token_forwarder( /// act question, kanban pull) always runs. pub(super) async fn run_self_cycle( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, opts: &ServeOptions, last_burst_fp: &mut u64, // The room her own mind woke her in (a Perceive wake): she works there this cycle, @@ -629,7 +629,7 @@ pub(super) async fn run_self_cycle( /// + continuing. Returns `None` only when the stream is genuinely /// over. pub(super) async fn next_event( - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, outcome: &mut ServeOutcome, ) -> Option { loop { diff --git a/core/continuum-mind/src/persona/service_loop/remains.rs b/core/continuum-mind/src/persona/service_loop/remains.rs index 269fbf1241..f64399df02 100644 --- a/core/continuum-mind/src/persona/service_loop/remains.rs +++ b/core/continuum-mind/src/persona/service_loop/remains.rs @@ -1,152 +1,16 @@ use super::*; -/// A substrate-friendly slice of one airc event: just what the -/// service loop needs to decide whether to respond. Strips away the -/// full `TranscriptEvent` surface so the conversation abstraction -/// stays compact and the trait remains stubbable without dragging -/// every airc type into the test. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub struct IncomingMessage { - /// The transcript event this turn came from — the row a `chat:heard` - /// receipt points back at. Nil for scripted/synthetic turns. - pub event_id: Uuid, - /// Monotonic lamport clock — used for pre-attach high-water-mark - /// filtering. - pub lamport: u64, - /// Cryptographic source identity per - /// [[persona-identity-derives-from-source-id]]. The loop compares - /// against the hosting persona's own peer_id to skip self-loop - /// echoes. - pub peer_id: Uuid, - /// Caption/text of the room message. - pub text: String, - /// Durable references only; decoding a message never fetches attachment bytes. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub media: Vec, - /// The room the event ARRIVED in — the transport's `TranscriptEvent.room_id`, - /// which is authoritative for the turn's context (A.6, the missing context - /// axis). Nil means the source predates room stamping (scripted/test - /// conversations) and the loop falls back to `identity.default_room`; a real - /// wire event always carries its room. Without this, an operator's CLI - /// publish woke the persona into a nil-room turn where every room-scoped - /// RAG source (roster, doctrine, board, kanban) abstained — she heard the - /// words but stood in no room (glass-boxed 2026-07-23, Anwen ACK test). - pub room_id: Uuid, - /// A typed work fact (a verdict, a card move, a submission, a claim) decoded - /// from the room by `persona::room_event::room_work_from_event`. `Some` means this - /// turn is a BOARD FACT she perceives, rendered as such, never as the actor's - /// speech; `peer_id` is the actor (the reviewer, the mover). Phase 1 wiring of - /// EVENT-MIND.md: measured 2026-10-04, a PASS on her own card reached her node - /// and was dropped as `non_chat_schema`; nothing on her board could wake her. - pub work: Option, -} - -impl IncomingMessage { - pub(crate) fn render_content(&self) -> String { - if let Some(work) = &self.work { - return crate::persona::room_event::render_room_work(work, self.peer_id); - } - crate::persona::room_event::render_room_content(&self.text, &self.media) - } - - /// The same source-labelled input at inference, replay and teaching boundaries. - /// This is rendering, not a replacement for the typed event/room identity. - pub(crate) fn render_room_update(&self) -> String { - format!( - "[Room message received during this turn; room {}; peer {}; event {}]\n{}", - self.room_id, self.peer_id, self.event_id, self.render_content() - ) - } -} - -/// Polymorphism rail for "talk to the grid as this persona". The -/// substrate's loop never touches `airc_lib::Airc` directly; the -/// real surface is behind this trait. Slice 11 ships the -/// `AircPersonaConversation` impl. -/// -/// All methods are async because the production impl chains over -/// airc's IPC socket. Tests use a stub that's instant. -#[async_trait] -pub trait PersonaConversation: Send + Sync { - /// Open whatever connection / stream / state the conversation - /// needs to start yielding messages. Called once at boot, BEFORE - /// the first `high_water_mark` or `next_message`. - /// - /// Production (`AircPersonaConversation`): opens the airc - /// subscribe stream. Without `prime`, the stream was opened - /// lazily on first `next_message`, which paid the daemon - /// round-trip on the cognition hot path. With `prime`, that - /// round-trip lands at the supervisor's boot phase — the - /// persona is "ready to converse" the moment her service loop - /// starts iterating. - /// - /// Tests (`StubConversation`): no-op. Idempotent — calling - /// `prime` twice is safe but the second call is a no-op. - /// - /// Returns `Err` if priming fails (daemon unreachable, room - /// gone). Per [[no-fallbacks-ever]] the loop refuses to start - /// rather than entering a degraded path. - async fn prime(&mut self) -> Result<(), String>; - - /// Highest lamport observed in transcript history before live - /// subscription. Used to ignore messages that arrived BEFORE the - /// persona attached — avoids replying to ancient chat just - /// because a restart loaded them through `page_recent`. - async fn high_water_mark(&self, limit: usize) -> Result; - - /// The cutoff established by successful priming. Live conversations freeze - /// this at attach, so starting the loop does not issue another fallible RPC. - async fn initial_water_mark(&self, limit: usize) -> Result { - self.high_water_mark(limit).await - } - - - /// Yield the next inbound message, or `Ok(None)` when the - /// stream is exhausted (daemon disconnected, peer gone). On - /// transient errors (stream lag, transport hiccup) the impl - /// should yield `Err` so the loop can record + continue. - /// - /// Assumes `prime` was called once at boot. If it wasn't, the - /// impl MAY lazy-prime (production currently does, for - /// backward compat) but the substrate's preferred path is - /// eager priming so the round-trip lands off the hot path. - async fn next_message(&mut self) -> Result, String>; - - /// Perceive currently ready room input without waiting for a new arrival. - /// The conversation RETAINS ownership for subsequent room attention, including - /// if the active drive is cancelled or cannot fit these inputs. Repeated - /// snapshots may overlap: the drive uses the ordinary event-id deduper. - async fn perceive_ready( - &mut self, - ) -> Result<&std::collections::VecDeque>, String>; - - /// Reply with text INTO A NAMED ROOM — normally the room the turn - /// being answered arrived in ([`IncomingMessage::room_id`]). - /// - /// Not "the persona's default room", which is what this used to - /// be. A persona is in more than one room, so a reply that always - /// went to her default answered the wrong audience the moment she - /// was addressed anywhere else — visibly worse than silence, - /// because it reads as a non-sequitur rather than a missing wire. - /// `Uuid::nil()` keeps the documented pre-room-stamping contract - /// (scripted / test sources) and routes to her default. - async fn say_in(&self, room_id: Uuid, text: &str) -> Result<(), String>; - +/// The conversation as persona drives it: cognition's [`PersonaConversation`] plus the airc +/// citizen behind it. Cognition never needs the citizen (its hands and claims are bound up +/// here, in `persona::card_hands`), so the accessor lives on persona's side of the seam and +/// a persona call into cognition upcasts to the narrower contract. +pub trait CitizenConversation: PersonaConversation { /// #170: the airc citizen behind this conversation, for OFF-THREAD streaming /// (`publish_stream_chunk`) from a spawned drain task. Returns an OWNED `Arc` /// so the forwarder can hold it `'static`. `None` for scripted / stub /// conversations — they don't stream to a live room; the airc conversation /// returns its runtime handle. - /// Her wakes from the one feed (EVENT-MIND §1b), once her perception region has - /// booted; `None` before then, after they were taken, or for a conversation with no - /// region. The serve loop takes them once and consumes them beside her inbox. - fn take_wakes(&mut self) -> Option> { - None - } - - fn stream_citizen( - &self, - ) -> Option> { + fn stream_citizen(&self) -> Option> { None } } @@ -365,7 +229,7 @@ pub struct ServeOutcome { /// replayed through RAG — that would echo every pre-restart message. pub async fn serve_persona_loop( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, opts: ServeOptions, ) -> Result { use tracing::Instrument; diff --git a/core/continuum-mind/src/persona/service_loop/self_tick.rs b/core/continuum-mind/src/persona/service_loop/self_tick.rs index ead2153c8a..e17893f4c8 100644 --- a/core/continuum-mind/src/persona/service_loop/self_tick.rs +++ b/core/continuum-mind/src/persona/service_loop/self_tick.rs @@ -12,7 +12,7 @@ pub(super) struct BeatClock { /// over the CURRENT world-state and sets the next beat from what it found. pub(super) async fn serve_self_tick( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, opts: &ServeOptions, last_burst_fp: &mut u64, wake_room: Option, diff --git a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs index 9d97f462e4..f401d75699 100644 --- a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs +++ b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs @@ -2,7 +2,7 @@ use super::*; pub(super) async fn serve_persona_loop_inner( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, opts: ServeOptions, ) -> Result { // PRECONDITION: caller MUST have called `conversation.prime()` @@ -21,7 +21,7 @@ pub(super) async fn serve_persona_loop_inner( .await .map_err(|e| format!("high_water_mark failed: {e}"))?; // Event-id ring for staleness at the loop head (see `wake_backlog::is_stale`). - let mut seen_ids = crate::persona::wake_backlog::SeenIds::new(256); + let mut seen_ids = crate::cognition::conversation::seen_ids::SeenIds::new(256); // Admitted triggers remain owned while capacity is unavailable. New inbox // input and Stop stay reachable without replacing an older trigger's custody. let mut deferred_input = crate::persona::wake_backlog::PendingInput::for_persona(ctx.identity.peer_id.as_uuid()); diff --git a/core/continuum-mind/src/persona/service_loop/tests/mod.rs b/core/continuum-mind/src/persona/service_loop/tests/mod.rs index 0af7544c4d..53bd1253da 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/mod.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/mod.rs @@ -1,6 +1,7 @@ #![cfg(test)] use super::*; + use std::sync::Arc; use crate::ai::adapter::AIProviderAdapter; use crate::persona::work_burst::{held_work_burst, own_recent_thoughts}; use crate::ai::HeuristicInferenceAdapter; @@ -8,7 +9,8 @@ use crate::persona::airc_citizen::StubAircCitizen; use crate::persona::identity_provider::PersonaIdentitySource; use crate::experience::role::RoleId; - use crate::persona::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; + use crate::persona::scripted_conversation::ScriptedCitizen; use crate::persona::supervisor::HostedPersona; use std::path::PathBuf; @@ -80,7 +82,7 @@ use crate::ai::adapter::GenerationChunk; use crate::persona::stream_rail; let her = Uuid::new_v4(); - let mind = crate::persona::mind_room::mind_room_id(her).to_string(); + let mind = crate::cognition::mind_room::mind_room_id(her).to_string(); let mut output = stream_rail::subscribe(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let owner = spawn_token_forwarder(rx, None, "Kimi".into(), Some(mind.clone()), Some(her.to_string())); @@ -106,7 +108,7 @@ #[tokio::test] pub(super) async fn successful_publication_records_speech_once_in_the_actual_room() { use crate::cognition::deliberation_budget::recent_own_speech; - use crate::persona::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; let peer = crate::identity::PeerId::from_uuid(Uuid::new_v4()); let room = Uuid::new_v4(); diff --git a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs index 12f37421c5..3bfdf69dfe 100644 --- a/core/continuum-mind/src/persona/service_loop/tests/part_4.rs +++ b/core/continuum-mind/src/persona/service_loop/tests/part_4.rs @@ -95,8 +95,8 @@ use super::*; // Register her cognition cycle in the global registry the act-question // reads, wired to a canned adapter that answers "PASS: done" — so the // drive settles on a reasoned pass, not the heuristic echo (a Speak). - let recall_meta = Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); - let admission = Arc::new(crate::persona::admission_state::AdmissionState::new( + let recall_meta = Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); + let admission = Arc::new(crate::cognition::admission_state::AdmissionState::new( recall_meta, )); let cfg = crate::cognition::persona_workspace::PersonaBrainConfig { @@ -197,8 +197,8 @@ use super::*; persona_id: peer, persona_name: "Paige".into(), system_prompt: "You are Paige.".into(), - admission: Arc::new(crate::persona::admission_state::AdmissionState::new( - Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()), + admission: Arc::new(crate::cognition::admission_state::AdmissionState::new( + Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()), )), adapter: Arc::new( HeuristicInferenceAdapter::new() @@ -291,6 +291,29 @@ use super::*; } } + // what this catches (moved from cognition::handoff when the card bind moved up, mind split + // step 7): a card whose hands cannot be bound must not clear the handoff's bound card. + #[tokio::test] + async fn a_failed_bind_keeps_the_bound_card_in_the_handoff() { + use crate::cognition::handoff::{compose, note_held, note_unbound, TornBy}; + let me = Uuid::from_u128(1_073); + let current = held_card(me); + note_held(me, None, ¤t, 1_850); + let cycle = crate::cognition::workspace::WorkspaceCycle::new( + vec![], + Arc::new(crate::cognition::workspace::SalienceArbiter), + 4, + ); + let mut unavailable = current.clone(); + unavailable.card_id = airc_lib::WorkCardId::new(); + let turn = crate::persona::card_hands::bind_card(&cycle, me, &unavailable).await; + assert!(turn.hands.is_none(), "no checkout/hands can be bound by this fixture"); + let root = std::path::Path::new("current-checkout"); + let bound = compose(me, TornBy::Periodic, Some(root), None, 1_875).expect("bound").card; + assert_eq!(bound, Some(current)); + note_unbound(me); + } + // Actual wake selection stays reachable while original capacity custody waits; // neither a new directed input nor Stop is hidden behind the retry timer. #[tokio::test(start_paused = true)] @@ -364,7 +387,8 @@ async fn capacity_park_keeps_new_input_and_stop_reachable() { async fn capacity_park_observes_semantic_board_change_before_trigger_filter() { use crate::cognition::act_observe::SettleStep; use crate::cognition::workspace::{PromptCapacityError, TurnAttention}; - use crate::persona::wake_backlog::{PendingInput, SeenIds}; + use crate::persona::wake_backlog::PendingInput; + use crate::cognition::conversation::seen_ids::SeenIds; let ctx = hosted_with_heuristic(Uuid::new_v4()); let room = Uuid::new_v4(); let original = IncomingMessage { @@ -383,7 +407,7 @@ async fn capacity_park_observes_semantic_board_change_before_trigger_filter() { let mut seen = SeenIds::new(256); let mut water = 0; let card = Uuid::new_v4(); - use crate::persona::room_event::RoomWork; + use crate::cognition::conversation::room_event::RoomWork; let state = |state| RoomWork::StateChanged { card_id: card, state, by: original.peer_id }; let submission = |id| RoomWork::Submitted { card_id: card, publisher: original.peer_id, submission: Some(id), @@ -476,8 +500,8 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( persona_id: peer, persona_name: "Aris".into(), system_prompt: "You are Aris.".into(), - admission: Arc::new(crate::persona::admission_state::AdmissionState::new(Arc::new( - crate::persona::recall_metadata::RecallMetadataRegistry::new(), + admission: Arc::new(crate::cognition::admission_state::AdmissionState::new(Arc::new( + crate::cognition::recall_metadata::RecallMetadataRegistry::new(), ))), adapter: Arc::new( HeuristicInferenceAdapter::new().with_canned_response("PASS: nothing calls me right now"), @@ -540,7 +564,7 @@ async fn holding_nothing_her_heartbeat_offers_an_initiative_turn_with_her_hands( use crate::cognition::rag_budget::{RagContext, RagSource, ResolutionPreference}; use crate::model_registry::types::MultiPartyChatStrategy; use crate::persona::room_roster_source::{AircRosterReader, RoomRosterSource}; - use crate::persona::service_loop::project_room_roster; + use crate::cognition::conversation::workspace_turns::project_room_roster; use airc_core::PeerId; use airc_lib::{AgentAvailabilityState, AircError, RoomMember}; use async_trait::async_trait; diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index ae98c20949..a2823bac08 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -30,7 +30,7 @@ pub(super) struct CycleInput { /// and report the verdict. Every non-speaking end of the turn is `Skip`. pub(super) async fn run_turn_cycle( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, outcome: &mut ServeOutcome, deferred_input: &mut crate::persona::wake_backlog::PendingInput, phase_timings: &mut PhaseTimings, @@ -253,7 +253,7 @@ pub(super) async fn run_turn_cycle( ); // A citizen holding a card works at that repo — in a ROOM turn too: the // turn is bound to her card claim's hands, admitted here. - let held_card = crate::cognition::persona_workspace::root_at_held_card( + let held_card = crate::persona::card_hands::root_at_held_card( &cycle, ctx.identity.peer_id.as_uuid(), conversation, @@ -276,7 +276,7 @@ pub(super) async fn run_turn_cycle( LIVE_MAX_ACTS, framing, conversation, - credit_capture.as_mut(), + credit_capture.as_mut().map(|c| c as &mut dyn crate::cognition::act_observe::TurnCredit), ) .await; // The lived-turn experience write (#319) is NOT here: it lives inside @@ -311,7 +311,7 @@ pub(super) async fn run_turn_cycle( // The turn's work is synced to its card's branch; her hands stay where they // are, because nothing moved them (card fc9e9fd7). if let Some(hands) = &held_card.hands { - crate::cognition::persona_workspace::end_card_turn(hands, turn_act_count).await; + crate::persona::card_hands::end_card_turn(hands, turn_act_count).await; } cycle.set_token_sink(None); let _ = forwarder.await; diff --git a/core/continuum-mind/src/persona/service_loop/turn_settle.rs b/core/continuum-mind/src/persona/service_loop/turn_settle.rs index 49694d00a1..5378d33389 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_settle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_settle.rs @@ -5,7 +5,7 @@ use super::*; /// and the L2 training producer. pub(super) async fn finish_spoken_turn( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, outcome: &mut ServeOutcome, trigger: TurnTrigger<'_>, spoken: SpokenTurn, diff --git a/core/continuum-mind/src/persona/service_loop/wake_select.rs b/core/continuum-mind/src/persona/service_loop/wake_select.rs index c06c150e69..9cbb7c2613 100644 --- a/core/continuum-mind/src/persona/service_loop/wake_select.rs +++ b/core/continuum-mind/src/persona/service_loop/wake_select.rs @@ -6,7 +6,7 @@ use super::*; /// takes never also starts a self-turn. #[derive(Default)] pub(super) struct MindWakeState { - wakes: Option>, + wakes: Option>, next_mind_check: Option, perceive_recheck: Option<(tokio::time::Instant, uuid::Uuid)>, } @@ -22,7 +22,7 @@ pub(super) enum LoopStep { /// wake plus the directed-pending generation observed before the wait. pub(super) async fn await_wake( ctx: &HostedPersona, - conversation: &mut dyn PersonaConversation, + conversation: &mut dyn CitizenConversation, outcome: &mut ServeOutcome, opts: &ServeOptions, deferred_input: &crate::persona::wake_backlog::PendingInput, @@ -57,12 +57,12 @@ pub(super) async fn await_wake( }, room = deferred_input.ready_self_room(), if !opts.quiesced.load(std::sync::atomic::Ordering::Relaxed) => Wake::Mind { why: "capacity", room: Some(room) }, w = next_mind_wake(&mut mind.wakes), if deferred_input.permits_self_tick() => match w { - crate::persona::perception_region::Wake::Perceive { activity, .. } => { + crate::cognition::conversation::Wake::Perceive { activity, .. } => { mind.perceive_recheck = Some((tokio::time::Instant::now() + PERCEIVE_SETTLE, activity)); Wake::Idle } - crate::persona::perception_region::Wake::Continuation => Wake::Mind { why: "continuation", room: her_continuation_room(me) }, - crate::persona::perception_region::Wake::Resume => Wake::Mind { why: "resume", room: her_continuation_room(me) }, + crate::cognition::conversation::Wake::Continuation => Wake::Mind { why: "continuation", room: her_continuation_room(me) }, + crate::cognition::conversation::Wake::Resume => Wake::Mind { why: "resume", room: her_continuation_room(me) }, }, _ = sleep_until_some(mind.perceive_recheck.map(|(at, _)| at)), if deferred_input.permits_self_tick() => { let activity = mind.perceive_recheck.take().map(|(_, a)| a); @@ -87,12 +87,12 @@ pub(super) async fn await_wake( Some((wake, next)) => { mind.next_mind_check = Some(next); match wake { - Some(crate::persona::perception_region::Wake::Perceive { activity, .. }) => { + Some(crate::cognition::conversation::Wake::Perceive { activity, .. }) => { mind.perceive_recheck = Some((tokio::time::Instant::now() + PERCEIVE_SETTLE, activity)); Wake::Idle } - Some(crate::persona::perception_region::Wake::Continuation) => Wake::Mind { why: "continuation", room: her_continuation_room(me) }, - Some(crate::persona::perception_region::Wake::Resume) => Wake::Mind { why: "resume", room: her_continuation_room(me) }, + Some(crate::cognition::conversation::Wake::Continuation) => Wake::Mind { why: "continuation", room: her_continuation_room(me) }, + Some(crate::cognition::conversation::Wake::Resume) => Wake::Mind { why: "resume", room: her_continuation_room(me) }, None => Wake::Idle, } } diff --git a/core/continuum-mind/src/persona/service_module.rs b/core/continuum-mind/src/persona/service_module.rs index b254dc6654..bd38aac2b8 100644 --- a/core/continuum-mind/src/persona/service_module.rs +++ b/core/continuum-mind/src/persona/service_module.rs @@ -54,13 +54,13 @@ use uuid::Uuid; use crate::cognition::response_orchestrator::PersonaSlot as ResponderPersona; use crate::model_registry::Capability; use crate::persona::channel_registry::{ChannelRegistry, DEFAULT_BURST_WINDOW_MS}; -use crate::persona::channel_types::ActivityDomain; +use crate::cognition::conversation::channel_types::ActivityDomain; use crate::persona::channel_view::CoherentInput; use crate::persona::evaluator::{analyze_burst, BurstEvaluateResult, BurstRespondContext}; -use crate::persona::persona_identity::PersonaIdentity; +use crate::cognition::conversation::persona_identity::PersonaIdentity; use crate::persona::response::{PersonaResponse, RespondInput}; use crate::persona::turn_context::TurnContext; -use crate::persona::types::PersonaState; +use crate::cognition::conversation::types::PersonaState; use crate::persona::unified::PersonaCognition; use std::collections::HashSet; diff --git a/core/continuum-mind/src/persona/service_module/tests.rs b/core/continuum-mind/src/persona/service_module/tests.rs index 2a6679bcff..66d55e7853 100644 --- a/core/continuum-mind/src/persona/service_module/tests.rs +++ b/core/continuum-mind/src/persona/service_module/tests.rs @@ -177,10 +177,10 @@ assert_eq!(slot.circuit_open_until_ms, 0); } - use crate::persona::channel_items::ChatQueueItem; + use crate::cognition::conversation::channel_items::ChatQueueItem; use crate::persona::channel_queue::{ChannelQueue, ChannelQueueConfig}; - use crate::persona::channel_types::ActivityDomain; - use crate::persona::types::SenderType; + use crate::cognition::conversation::channel_types::ActivityDomain; + use crate::cognition::conversation::types::SenderType; /// Construct a chat queue item with sensible defaults for tests. fn test_chat_item(content: &str, sender_human: bool, room_id: Uuid) -> ChatQueueItem { diff --git a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs index 616bb85a74..1e41a8fb2d 100644 --- a/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs +++ b/core/continuum-mind/src/persona/supervisor/materialize_adapters.rs @@ -36,10 +36,10 @@ pub async fn materialize_adapters( // leaked per attempt, ~150 sockets/s, both descriptor tables full, the host at // ENFILE. A seat that will be refused must build nothing first. let persisted_admission = { - let home = crate::persona::home::PersonaHome::from_root(identity.home.clone()); + let home = crate::cognition::home::PersonaHome::from_root(identity.home.clone()); let recall_meta = - std::sync::Arc::new(crate::persona::recall_metadata::RecallMetadataRegistry::new()); - match crate::persona::admission_state::AdmissionState::for_persona(&home, recall_meta).await + std::sync::Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()); + match crate::cognition::admission_state::AdmissionState::for_persona(&home, recall_meta).await { Ok(persisted) => persisted, Err(source) => { @@ -227,7 +227,7 @@ pub async fn materialize_adapters( let roster_source: Arc = Arc::new(crate::persona::viewstate_rag::ViewStateRagSource::< continuum_positron::RosterViewState, - >::per_room(crate::persona::room_substrates::global_room_substrates())); + >::per_room(crate::cognition::room_substrates::global_room_substrates())); cognition.set_roster_source(roster_source.clone()); @@ -300,12 +300,12 @@ pub async fn materialize_adapters( { Some(bus) => { let (cached, dirty) = - crate::persona::cached_source::CachedRagSource::new(raw_workspace_map); - crate::persona::grounding_invalidation::spawn_workspace_invalidator( + crate::cognition::cached_source::CachedRagSource::new(raw_workspace_map); + crate::cognition::grounding_invalidation::spawn_workspace_invalidator( bus, dirty.downgrade(), ); - crate::persona::grounding_invalidation::register_workspace_map_dirty( + crate::cognition::grounding_invalidation::register_workspace_map_dirty( identity.peer_id.as_uuid(), dirty.downgrade(), ); @@ -354,12 +354,12 @@ pub async fn materialize_adapters( ) = match runtime.subscribe_all_rooms().await { Ok(stream) => { let (doctrine_cached, doctrine_dirty) = - crate::persona::cached_source::CachedRagSource::new(raw_doctrine); + crate::cognition::cached_source::CachedRagSource::new(raw_doctrine); let (wall_cached, wall_dirty) = - crate::persona::cached_source::CachedRagSource::new(raw_wall); + crate::cognition::cached_source::CachedRagSource::new(raw_wall); // The invalidator owns a subscription to every room; it lives and dies with // the runtime (aborted in the runtime's Drop), never as an orphan task. - runtime.own_task(crate::persona::grounding_invalidation::spawn_publish_invalidator( + runtime.own_task(crate::cognition::grounding_invalidation::spawn_publish_invalidator( stream, vec![doctrine_dirty.downgrade(), wall_dirty.downgrade()], )); diff --git a/core/continuum-mind/src/persona/supervisor/persona_adapter_factory.rs b/core/continuum-mind/src/persona/supervisor/persona_adapter_factory.rs index d518717dab..d76d75db7a 100644 --- a/core/continuum-mind/src/persona/supervisor/persona_adapter_factory.rs +++ b/core/continuum-mind/src/persona/supervisor/persona_adapter_factory.rs @@ -414,8 +414,8 @@ pub(super) fn remote_override_for( persona_name, ) .parent() - .map(|root| crate::persona::home::PersonaHome::from_root(root.to_path_buf())); - let by_identity = crate::persona::home::PersonaHome::from_root(identity_home.to_path_buf()); + .map(|root| crate::cognition::home::PersonaHome::from_root(root.to_path_buf())); + let by_identity = crate::cognition::home::PersonaHome::from_root(identity_home.to_path_buf()); by_name .into_iter() .chain(std::iter::once(by_identity)) diff --git a/core/continuum-mind/src/persona/supervisor/tests.rs b/core/continuum-mind/src/persona/supervisor/tests.rs index 8377af3535..49bea42923 100644 --- a/core/continuum-mind/src/persona/supervisor/tests.rs +++ b/core/continuum-mind/src/persona/supervisor/tests.rs @@ -147,7 +147,7 @@ "model-a", None, 1, "peer", ) .with_context_window(24_832) - .write(&crate::persona::home::PersonaHome::from_root( + .write(&crate::cognition::home::PersonaHome::from_root( with_window.home.clone(), )) .expect("write override"); @@ -157,7 +157,7 @@ crate::persona::model_override::PersonaModelOverride::new_remote( "model-b", None, 1, "peer", ) - .write(&crate::persona::home::PersonaHome::from_root( + .write(&crate::cognition::home::PersonaHome::from_root( without_window.home.clone(), )) .expect("write override"); @@ -466,7 +466,7 @@ assert!(registry.get(&failed_id).is_none()); None }; - let failed_home = crate::persona::home::PersonaHome::from_root(failed.home.clone()); + let failed_home = crate::cognition::home::PersonaHome::from_root(failed.home.clone()); failed_home.ensure_exists().unwrap(); let broken = failed_home.engrams_db(); let original = b"existing engram database is not valid SQLite"; @@ -474,7 +474,7 @@ let mut healthy = fake_instance("admission-healthy"); healthy.home = home.path().join("healthy-persona"); let healthy_id = healthy.peer_id.as_uuid(); - let healthy_home = crate::persona::home::PersonaHome::from_root(healthy.home.clone()); + let healthy_home = crate::cognition::home::PersonaHome::from_root(healthy.home.clone()); let plans = vec![ MaterializedPersonaPlan { role: RoleId::Helper, diff --git a/core/continuum-mind/src/persona/training_producer.rs b/core/continuum-mind/src/persona/training_producer.rs index 0c3e068b74..82becdf8d3 100644 --- a/core/continuum-mind/src/persona/training_producer.rs +++ b/core/continuum-mind/src/persona/training_producer.rs @@ -58,6 +58,7 @@ use crate::orm::OrmEntity; pub mod reviewed; pub mod graded; +use crate::cognition::training_sources::*; mod stamp; pub use stamp::{CapturedCredit, ClaimReceipt, CreditRole, OutcomeStamp, ServedProvenance, SettlementOutcome}; diff --git a/core/continuum-mind/src/persona/training_producer/executor.rs b/core/continuum-mind/src/persona/training_producer/executor.rs index a4b34fa9f3..b7d269a1cd 100644 --- a/core/continuum-mind/src/persona/training_producer/executor.rs +++ b/core/continuum-mind/src/persona/training_producer/executor.rs @@ -75,7 +75,7 @@ pub struct StagedCreditGeneration { /// Observed live 2026-09-08: a citizen accumulating toward a training threshold on a /// card still in `Claimed` with no settlement. /// -/// Lives in the citizen's own [`crate::persona::home::PersonaHome`], alongside +/// Lives in the citizen's own [`crate::cognition::home::PersonaHome`], alongside /// `engrams.sqlite` — persistence inside its existing owner, per-citizen, NOT a new /// global queue ([[source-drain-is-the-universal-pattern]]: the drain is settlement). /// @@ -712,3 +712,16 @@ pub fn received_submission_params( } params } + +#[async_trait::async_trait] +impl crate::cognition::act_observe::TurnCredit for TurnCreditCapture { + async fn record( + &mut self, + acts: &[(String, Vec)], + receipts: &[crate::ai::provenance::GenerationReceipt], + report: Option<&str>, + final_snapshot: bool, + ) -> bool { + TurnCreditCapture::record(self, acts, receipts, report, final_snapshot).await + } +} diff --git a/core/continuum-mind/src/persona/training_producer/reviewed/boundaries.rs b/core/continuum-mind/src/persona/training_producer/reviewed/boundaries.rs index e0e282b417..ffdb7cbf1a 100644 --- a/core/continuum-mind/src/persona/training_producer/reviewed/boundaries.rs +++ b/core/continuum-mind/src/persona/training_producer/reviewed/boundaries.rs @@ -3,6 +3,7 @@ //! training job ran, weights changed, or a candidate earned adoption. use super::*; +use crate::cognition::dream_consolidation::BoundaryPage; const RECOVERY_PAGE_BUDGET: std::time::Duration = std::time::Duration::from_secs(1); const RECOVERY_ROW_BUDGET: std::time::Duration = std::time::Duration::from_millis(250); @@ -30,12 +31,6 @@ pub struct ReviewBoundaryStore { persona_id: Uuid, } -#[derive(Debug)] -pub struct BoundaryPage { - pub pending: Vec, - pub next: Option, -} - impl ReviewBoundaryStore { pub fn new( executor: Arc, @@ -206,6 +201,21 @@ async fn validate_acceptance( .ok_or_else(|| ClientError::Transport("review boundary acceptance disappeared".into())) } +#[async_trait::async_trait] +impl crate::cognition::dream_consolidation::ReviewBoundaryLedger for ReviewBoundaryStore { + async fn prepare(&self) -> Result<(), ClientError> { + ReviewBoundaryStore::prepare(self).await + } + + async fn page(&self, after: Option, limit: usize) -> Result { + ReviewBoundaryStore::page(self, after, limit).await + } + + async fn finish(&self, ids: &[Uuid], eligible_clusters: usize) -> Result<(), ClientError> { + ReviewBoundaryStore::finish(self, ids, eligible_clusters).await + } +} + pub(super) async fn is_processed( conn: &Connection, name: &str, diff --git a/core/continuum-mind/src/persona/training_producer/speech_discipline_trait.rs b/core/continuum-mind/src/persona/training_producer/speech_discipline_trait.rs index dc18c70da7..a6caf1615d 100644 --- a/core/continuum-mind/src/persona/training_producer/speech_discipline_trait.rs +++ b/core/continuum-mind/src/persona/training_producer/speech_discipline_trait.rs @@ -1,39 +1,5 @@ use super::*; -/// THE GATE BECOMES A LESSON (card 657e74de; Joel: "ideally they learn too"). Every -/// echo shape gated at the Speak seam (`framing_echo`, `not_speech`) returns a Pass -/// the citizen never sees — the substrate silences her and she learns nothing, so -/// the same tier produces the same echo next turn. The corpus is `{prompt, -/// completion}` SFT only (no chosen/rejected schema), so a gate verdict cannot be a -/// NEGATIVE; but for the echo class the correct completion IS known and fits the -/// schema: the silence token. This is the one place a gate verdict turns into an -/// example. -/// -/// Rules that keep this from teaching muteness, each load-bearing: -/// - only an UNDIRECTED, LIVED turn (the caller checks): a directed question must -/// never train `PASS`, and a synthetic burst is not experience; -/// - its own bucket, [`SPEECH_DISCIPLINE_TRAIT`], never the conversation domain, so -/// no chat gene's set is diluted with silence; and the bucket's gene is adoptable -/// only through its gym (`docs/genome/speech-discipline.jsonl`), which measures -/// BOTH halves — a quiet burst that must end in silence and a real ask that must -/// be answered — so a gene that learned to pass everything fails the gym and is -/// never paged in ([[fallbacks-are-illegal-fail-loud]]); -/// - `quality = 1.0`: a curated domain with its own floor — a 4-char completion -/// scores below [`MIN_TRAINING_QUALITY`] by construction, and the chat score was -/// built for a different shape. -pub const SPEECH_DISCIPLINE_TRAIT: &str = "speech-discipline"; - -/// The `source` an example carries when no card produced it: a received lesson or a gated -/// echo. ONE list, written by the producers below and read by the held-out judge -/// (`cognition::held_out::trained`), where it is the explicit record that such an example -/// worked no graded task (goal 8). It is the value already on the wire, so a replayed -/// submission keeps its exact bytes. -pub const RECEIVED_LESSON_SOURCE: &str = "received-lesson"; - -pub const SPEECH_DISCIPLINE_SOURCE: &str = "speech-discipline"; - -pub const UNLINKED_SOURCES: [&str; 2] = [RECEIVED_LESSON_SOURCE, SPEECH_DISCIPLINE_SOURCE]; - /// The silence token, exactly as [`crate::cognition::deliberation_parse`] reads it. pub const SILENCE_COMPLETION: &str = "PASS"; diff --git a/core/continuum-mind/src/persona/turn_frame.rs b/core/continuum-mind/src/persona/turn_frame.rs index 76306da302..96a52435f1 100644 --- a/core/continuum-mind/src/persona/turn_frame.rs +++ b/core/continuum-mind/src/persona/turn_frame.rs @@ -5,7 +5,7 @@ //! that can be recorded and replayed without booting inference. use super::inbox::PersonaInboxFrame; -use super::types::InboxMessage; +use crate::cognition::conversation::types::InboxMessage; use serde::{Deserialize, Serialize}; use ts_rs::TS; use uuid::Uuid; @@ -321,7 +321,7 @@ impl ResponsePrompt { mod tests { use super::*; use crate::persona::inbox::{PersonaInbox, PersonaInboxFrameMetrics}; - use crate::persona::{Modality, SenderType}; + use crate::cognition::conversation::types::{Modality, SenderType}; fn message( room_id: Uuid, diff --git a/core/continuum-mind/src/persona/unified.rs b/core/continuum-mind/src/persona/unified.rs index 9b68dc9844..5b99126a35 100644 --- a/core/continuum-mind/src/persona/unified.rs +++ b/core/continuum-mind/src/persona/unified.rs @@ -8,7 +8,7 @@ //! After: 1 DashMap — 1 lock, contiguous memory, //! atomic access to engine + rate_limiter + sleep_state + adapters + genome. -use crate::persona::admission_state::AdmissionState; +use crate::cognition::admission_state::AdmissionState; use crate::persona::cognition::PersonaCognitionEngine; use crate::persona::domain_classifier::DomainClassifier; use crate::persona::engram_source::EngramSource; @@ -25,7 +25,7 @@ use crate::cognition::rag_budget::{ use crate::persona::rag_capture::{ NoopRagCaptureSink, RagCaptureEvent, RagCaptureSink, RecordingRagSource, }; -use crate::persona::recall_metadata::RecallMetadataRegistry; +use crate::cognition::recall_metadata::RecallMetadataRegistry; use crate::rag::RagEngine; use std::sync::Arc; use uuid::Uuid; @@ -466,7 +466,7 @@ impl RagSource for ArcRagSource { #[cfg(test)] mod tests { use super::*; - use crate::persona::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; + use crate::cognition::engram::{ChatMessageRef, Engram, EngramKind, EngramOrigin, TrustState}; use crate::cognition::rag_budget::{RagContext, RagSource, ResolutionPreference}; use crate::persona::rag_capture::{ InMemoryRagCaptureSink, RagCaptureEvent, RagCaptureSink, @@ -786,7 +786,7 @@ mod tests { items_offered: 3, share: std::num::NonZeroU32::new(64), }); - let (cached, _) = crate::persona::cached_source::CachedRagSource::new(source.clone()); + let (cached, _) = crate::cognition::cached_source::CachedRagSource::new(source.clone()); let mut pc = PersonaCognition::new(Uuid::new_v4(), "TestBot".into(), Arc::new(RagEngine::new())); pc.set_roster_source(cached); let wrapped = pc.roster_source.as_ref().unwrap(); @@ -814,7 +814,7 @@ mod tests { let mut pc = PersonaCognition::with_capture_sink(id, "Kimi".into(), Arc::new(RagEngine::new()), 200.0, sink_dyn); pc.set_airc_source(Arc::new(CannedSource { id: "airc", tokens_per_item: 50, items_offered: 2, share: None })); - let mind = crate::persona::mind_room::mind_room_id(id); + let mind = crate::cognition::mind_room::mind_room_id(id); let _ = pc.compose_for_turn(&lcd_profile(), 1_000_000, Some(mind)).await; assert!(sink.is_empty(), "her mind room: no capture events, got {}", sink.len()); let _ = pc.compose_for_turn(&lcd_profile(), 1_000_000, Some(Uuid::new_v4())).await; diff --git a/core/continuum-mind/src/persona/viewstate_rag/tests.rs b/core/continuum-mind/src/persona/viewstate_rag/tests.rs index bee010e31f..96df97afbe 100644 --- a/core/continuum-mind/src/persona/viewstate_rag/tests.rs +++ b/core/continuum-mind/src/persona/viewstate_rag/tests.rs @@ -210,7 +210,7 @@ async fn a_tight_budget_yields_fewer_units_never_a_chopped_one() { assert_eq!(admitted.get(&Uuid::from_u128(id).to_string()).map(String::as_str), Some(name)); } } - let wake = super::super::service_loop::build_workspace_turns( + let wake = crate::cognition::conversation::workspace_turns::build_workspace_turns( std::slice::from_ref(&delivery), "self", "Reader", @@ -234,7 +234,7 @@ async fn a_tight_budget_yields_fewer_units_never_a_chopped_one() { resolution_used: ResolutionPreference::Raw, }; let own = Uuid::from_u128(3).to_string(); - let turns = super::super::service_loop::build_workspace_turns( + let turns = crate::cognition::conversation::workspace_turns::build_workspace_turns( &[delivery, transcript], &own, "Native identity", diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 25be6b82cb..02a7e3819a 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -12,11 +12,11 @@ //! (a ring), the trigger is the newest priority line (human opportunity or a //! mention), and every priority line drained earns its heard receipt. -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashMap, VecDeque}; use uuid::Uuid; -use super::service_loop::IncomingMessage; +use crate::cognition::conversation::IncomingMessage; use crate::cognition::workspace::TurnAttention; /// Loop-local custody of admitted inputs. Capacity refusals wait on their bound @@ -26,7 +26,7 @@ pub(crate) struct PendingInput { persona: Option, inputs: VecDeque, self_refusals: HashMap>, - work_witnesses: VecDeque<(Uuid, crate::persona::room_event::RoomWork)>, + work_witnesses: VecDeque<(Uuid, crate::cognition::conversation::room_event::RoomWork)>, } struct RetainedInput { message: IncomingMessage, @@ -107,9 +107,9 @@ impl PendingInput { /// repeated semantic facts cannot re-arm an unchanged parked request. pub(crate) fn observe_work(&mut self, message: &IncomingMessage) { let Some(work) = &message.work else { return }; - if matches!(work, crate::persona::room_event::RoomWork::Other { .. }) { return; } - let key = |work: &crate::persona::room_event::RoomWork| { - use crate::persona::room_event::RoomWork; + if matches!(work, crate::cognition::conversation::room_event::RoomWork::Other { .. }) { return; } + let key = |work: &crate::cognition::conversation::room_event::RoomWork| { + use crate::cognition::conversation::room_event::RoomWork; match work { RoomWork::Reviewed { card_id, .. } | RoomWork::StateChanged { card_id, .. } | RoomWork::Submitted { card_id, .. } | RoomWork::Claimed { card_id, .. } => Some(*card_id), @@ -255,52 +255,6 @@ async fn wait_capacity(refusal: &crate::cognition::workspace::CapacityRefusal) { } } -/// Event-id ring for replay/redelivery dedupe at the loop head. Small: the -/// pump already dedupes the store catch-up; this catches re-open replays. -pub(crate) struct SeenIds { - ring: VecDeque, - ids: HashSet, - cap: usize, -} - -impl SeenIds { - pub(crate) fn new(cap: usize) -> Self { - Self { - ring: VecDeque::with_capacity(cap), - ids: HashSet::with_capacity(cap), - cap, - } - } - - /// Note an id; `true` when it is NEW (first sight), `false` on a repeat. - pub(crate) fn note(&mut self, id: Uuid) -> bool { - if self.ids.contains(&id) { - return false; - } - if self.cap == 0 { - return true; - } - if self.ring.len() == self.cap { - if let Some(evicted) = self.ring.pop_front() { - self.ids.remove(&evicted); - } - } - self.ids.insert(id); - self.ring.push_back(id); - true - } -} - -/// Is this drained line stale? By event id when the source stamps one; by the -/// publisher clock only for id-less sources (scripted/test conversations). -pub(crate) fn is_stale(m: &IncomingMessage, seen: &mut SeenIds, high_water: u64) -> bool { - if m.event_id.is_nil() { - m.lamport <= high_water - } else { - !seen.note(m.event_id) - } -} - /// Can this drained line be the TRIGGER of a turn at all? A priority line /// (human, or anyone naming her) always; an undirected line from a fellow /// CITIZEN yes — that is conversation among citizens; an undirected line from @@ -447,8 +401,8 @@ mod tests { #[tokio::test(start_paused = true)] async fn deferred_attention_waits_without_consuming_the_trigger_or_new_input() { use crate::cognition::act_observe::SettleStep; - use crate::persona::scripted_conversation::ScriptedConversation; - use crate::persona::service_loop::PersonaConversation; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::PersonaConversation; use std::time::Duration; let original = line(1, 1, "original directed request"); let newer = line(2, 2, "newer directed request"); @@ -573,54 +527,13 @@ mod tests { assert!(triggers_a_turn(true, true, false)); } - // what this catches: the per-publisher lamport read a human line as stale - // against citizens' larger clocks (the 9/4 deaf-citizens regression). - #[test] - fn a_human_line_with_a_small_publisher_clock_is_not_stale() { - let mut seen = SeenIds::new(8); - let human = line(1, 3, "Joel here — which card do you hold?"); - assert!(!is_stale(&human, &mut seen, 157_000)); - } - - // what this catches: a re-open replay redelivering the same event id. - #[test] - fn a_replayed_event_id_is_stale_the_second_time() { - let mut seen = SeenIds::new(8); - let m = line(1, 3, "once"); - assert!(!is_stale(&m, &mut seen, 0)); - assert!(is_stale(&m, &mut seen, 0)); - } - - // The index must evict with the ordered ring; retained snapshots do not - // refresh recency or grow the bounded set on duplicate admission. - #[test] - fn seen_id_index_evicts_with_the_ring() { - let mut seen = SeenIds::new(2); - let a = Uuid::new_v4(); - let b = Uuid::new_v4(); - let c = Uuid::new_v4(); - assert!(seen.note(a)); - assert!(seen.note(b)); - assert!(!seen.note(a)); - assert!(seen.note(c)); - assert!(seen.note(a)); - assert!(!seen.note(c)); - assert_eq!(seen.ids.len(), 2); - assert_eq!(seen.ring.len(), 2); - let mut empty = SeenIds::new(0); - assert!(empty.note(a)); - assert!(empty.note(a)); - assert!(empty.ids.is_empty()); - assert!(empty.ring.is_empty()); - } - // what this catches: a human line without an @mention losing the turn to a // newer citizen work receipt. #[test] fn a_human_opportunity_wins_over_newer_citizen_chatter_without_a_mention() { use crate::cognition::workspace::TurnAttention; let identity = - crate::persona::persona_identity::PersonaIdentity::new(Uuid::new_v4(), "Kimi"); + crate::cognition::conversation::persona_identity::PersonaIdentity::new(Uuid::new_v4(), "Kimi"); let human = line(1, 3, "Joel here — which card do you hold?"); let human_id = human.event_id; let receipt = line(2, 900, "💭 Let me get my bearings."); @@ -636,4 +549,100 @@ mod tests { "human priority does not require a name" ); } + + // what this catches (moved from cognition::act_observe with mind split step 7: custody is + // persona's): regression 2e3f0eab: admission refusal must retain the original directed + // input, even when a newer directed input arrives before the admitted retry. + #[tokio::test] + async fn starved_priority_input_survives_until_dispatch_without_replaying_actions() { + use crate::cognition::act_observe::test_support::{admission, body_with_wm, ActThenSpeak, RecordingExecutor}; + use crate::cognition::act_observe::{drive_to_settle_with_input, SettleStep}; + use crate::cognition::working_memory::{WorkingMemory, WorkingMemoryFaculty}; + use crate::cognition::workspace::{Burst, Faculty, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; + use std::sync::{Arc, Mutex}; + use crate::cognition::conversation::scripted_conversation::ScriptedConversation; + use crate::cognition::conversation::{IncomingMessage, PersonaConversation}; + use std::sync::atomic::{AtomicBool, Ordering}; + + let gate = Arc::new(AtomicBool::new(false)); + let mut faculty = ActThenSpeak::new(); + faculty.admission_open = Some(Arc::clone(&gate)); + let exec = Arc::new(RecordingExecutor { + seen_context: Arc::new(Mutex::new(None)), + result_content: "4".into(), + }); + let wm = Arc::new(WorkingMemory::new(8)); + let cycle = WorkspaceCycle::new( + vec![ + Arc::new(WorkingMemoryFaculty::new(Arc::clone(&wm))) as Arc, + Arc::new(faculty), + ], + Arc::new(SalienceArbiter), + 8, + ) + .with_acting(body_with_wm(exec.clone(), admission(), wm)); + let original = IncomingMessage { + event_id: Uuid::new_v4(), lamport: 10, peer_id: Uuid::new_v4(), + room_id: Uuid::new_v4(), text: "Asha, inspect this exact input".into(), work: None, + media: vec![crate::cognition::conversation::channel_items::MediaItemRequest { + kind: "image".into(), mime_type: Some("image/png".into()), + blob_hash: Some("sha256:retained-input".into()), url: None, + description: Some("original attachment".into()), + }], + }; + let mut newer = original.clone(); + newer.event_id = Uuid::new_v4(); + newer.room_id = Uuid::new_v4(); + newer.lamport += 1; + newer.text = "Asha, a newer directed request".into(); + let mut conversation = ScriptedConversation::new(); + conversation.prime().await.unwrap(); + let mut pending = PendingInput::default(); + let cause = Some(Uuid::new_v4()); + let framing = TurnFraming::message(TurnAttention::for_message(true, false)); + let burst = |message: &IncomingMessage| { + Burst::raw_in( + crate::identity::ActivityRoom::from_uuid(message.room_id).unwrap(), + message.render_content(), + ) + }; + let refused = + drive_to_settle_with_input(&cycle, burst(&original), 8, framing, &mut conversation).await; + assert!(refused.deferred_before_dispatch); + assert_eq!(refused.acts, 0); + assert!(exec.seen_context.lock().unwrap().is_none()); + let (step, _, _) = SettleStep::from_settled(refused); + pending.settle(&original, cause, framing.attention, &step); + conversation.event_feed().push(Ok(Some(newer.clone()))); + assert_eq!(pending.message(), Some(&original)); + assert_eq!(pending.wake_engram_for(&original), cause); + + // A second failed admission neither consumes nor replaces the original. + let retried = pending.message().unwrap().clone(); + let refused_again = drive_to_settle_with_input(&cycle, burst(&retried), 8, framing, &mut conversation).await; + let (step, _, _) = SettleStep::from_settled(refused_again); + pending.settle(&retried, cause, framing.attention, &step); + assert_eq!(pending.message(), Some(&original)); + assert!(conversation.perceive_ready().await.unwrap().iter().any(|m| **m == newer)); + + gate.store(true, Ordering::SeqCst); + let completed = drive_to_settle_with_input( + &cycle, + burst(pending.message().unwrap()), + 8, + framing, + &mut conversation, + ) + .await; + assert!(!completed.deferred_before_dispatch); + assert_eq!(completed.acts, 1, "only the admitted retry executes an action"); + assert!(completed.room_updates.iter().any(|m| **m == newer)); + assert_eq!(completed.room, original.room_id); + let (step, _, _) = SettleStep::from_settled(completed); + assert!(matches!(&step, SettleStep::Spoke(_))); + pending.settle(&original, cause, framing.attention, &step); + assert!(pending.message().is_none(), "completed input is not replayed"); + assert_eq!(conversation.next_message().await.unwrap(), Some(newer)); + assert!(conversation.next_message().await.unwrap().is_none()); + } } diff --git a/core/continuum-mind/src/persona/wall_source.rs b/core/continuum-mind/src/persona/wall_source.rs index e5784b2a5a..944f8a22d2 100644 --- a/core/continuum-mind/src/persona/wall_source.rs +++ b/core/continuum-mind/src/persona/wall_source.rs @@ -142,9 +142,9 @@ fn ledgers_for_context(posts: Vec, labels: Option<&CardLabels let short = ledger.card_id.simple().to_string(); let short = &short[..8]; let head = match labels.get(&ledger.card_id) { - Some((_, state)) if crate::persona::work_board::facts::is_concluded(state) => return None, + Some((_, state)) if crate::cognition::card_facts::is_concluded(state) => return None, Some((title, state)) => { - format!("ledger of card {short} \"{title}\" ({})\n", crate::persona::work_board::facts::state_str(state)) + format!("ledger of card {short} \"{title}\" ({})\n", crate::cognition::card_facts::state_str(state)) } None => format!("ledger of card {short} (not on this room's board)\n"), }; diff --git a/core/continuum-mind/src/persona/work_board.rs b/core/continuum-mind/src/persona/work_board.rs index 8a7b2d285b..5ab07fc9f1 100644 --- a/core/continuum-mind/src/persona/work_board.rs +++ b/core/continuum-mind/src/persona/work_board.rs @@ -5,7 +5,6 @@ pub mod advance; pub mod events; -pub mod facts; pub mod horizon; pub mod review; pub mod submissions; diff --git a/core/continuum-mind/src/persona/work_board/advance.rs b/core/continuum-mind/src/persona/work_board/advance.rs index bf9a3abbaf..c8d84a6ddc 100644 --- a/core/continuum-mind/src/persona/work_board/advance.rs +++ b/core/continuum-mind/src/persona/work_board/advance.rs @@ -7,7 +7,7 @@ use airc_lib::{Airc, CardState, ChangeWorkCardState, CreateWorkCard, Priority, W use uuid::Uuid; -use super::facts::{is_concluded, short8}; +use crate::cognition::card_facts::{is_concluded, short8}; use super::horizon::{card_in_subscribed_rooms, follow_card_room, room_holding_card}; use super::events::emit_card_state_changed; @@ -271,7 +271,7 @@ pub(crate) async fn open_review_card(airc: &Arc, parent: WorkCardId) -> Re // A room's own card (not a bench card): its review card comes from the parent // itself, under the room's policy (card fa4aaaaa). The bench branch below is // unchanged. - return open_room_review_card(airc, &room, &card, parent, super::submissions::latest_submission(&card).map(|s| s.submission_id)).await; + return open_room_review_card(airc, &room, &card, parent, crate::cognition::card_holder::latest_submission(&card).map(|s| s.submission_id)).await; }; let owner = card .owner diff --git a/core/continuum-mind/src/persona/work_board/horizon.rs b/core/continuum-mind/src/persona/work_board/horizon.rs index 01f98d620d..b9de184d0e 100644 --- a/core/continuum-mind/src/persona/work_board/horizon.rs +++ b/core/continuum-mind/src/persona/work_board/horizon.rs @@ -7,7 +7,7 @@ use airc_lib::{Airc, WorkCardId}; use crate::sdk_codegen::CommandError; -use super::facts::short8; +use crate::cognition::card_facts::short8; /// The room whose board holds `card_id` — the ONE place that answers *which /// activity does this card belong to*. diff --git a/core/continuum-mind/src/persona/work_board/review.rs b/core/continuum-mind/src/persona/work_board/review.rs index bdc9345f65..33258ab4f5 100644 --- a/core/continuum-mind/src/persona/work_board/review.rs +++ b/core/continuum-mind/src/persona/work_board/review.rs @@ -105,7 +105,7 @@ pub(crate) async fn room_review(airc: &std::sync::Arc, card_id: WorkCardId return None; }; let board = airc.work_board_in(&room).await.ok()?; - let latest = super::submissions::latest_submission(&card); + let latest = crate::cognition::card_holder::latest_submission(&card); let author = latest.map(|s| s.publisher.as_uuid()).or(card.owner.map(|o| o.as_uuid())); let reviews: Vec = match latest { Some(sub) => board diff --git a/core/continuum-mind/src/persona/work_board/submissions.rs b/core/continuum-mind/src/persona/work_board/submissions.rs index ba7813147f..2d3c04c051 100644 --- a/core/continuum-mind/src/persona/work_board/submissions.rs +++ b/core/continuum-mind/src/persona/work_board/submissions.rs @@ -1,16 +1,10 @@ -//! Reading a card's submissions: the latest candidate, and what its holder does next. +//! Reading a card's submissions: what its holder does next. The latest candidate is +//! `cognition::card_holder::latest_submission`. use airc_lib::WorkCardId; use uuid::Uuid; -use super::facts::short8; - -/// Latest accepted candidate in the board's transcript order. AIRC projects submissions -/// newest first; publisher wall clocks do not define recency. Keep handoff and review -/// consumers on this contract so a resumed citizen sees the candidate being reviewed. -pub fn latest_submission(card: &airc_lib::WorkCard) -> Option<&airc_work::WorkSubmission> { - card.submissions.first() -} +use crate::cognition::card_facts::short8; /// PURE: what happens next for the holder of a card whose latest submission is `latest`, given /// the outcomes its reviews have reached and whether it is a bench card. The ONE place this is diff --git a/core/continuum-mind/src/persona/work_burst.rs b/core/continuum-mind/src/persona/work_burst.rs index 231b3e07a6..08e50e273f 100644 --- a/core/continuum-mind/src/persona/work_burst.rs +++ b/core/continuum-mind/src/persona/work_burst.rs @@ -308,108 +308,6 @@ pub(crate) fn own_recent_thoughts_about( .collect() } -pub(crate) fn work_board_anchor(deliveries: &[crate::cognition::rag_budget::RagDelivery]) -> String { - // Did the board source SPEAK this turn? "The board is empty" and "I never read the - // board" are different facts about the world, and only one of them is knowable from an - // absent delivery. Glass-boxed 2026-08-06 from Benchy's live capture: `room-kanban` - // delivered NOTHING (grounding is last in the budget queue), the anchor rendered that - // as "No open cards are visible", and she then said exactly that in-room for six turns - // — while `work/list()` in her OWN working memory listed a full board in the same - // prompt. She trusted the authoritative-sounding anchor over her own receipt. - // - // Never assert a fact about the world on behalf of a source that did not speak. - // [[grounding-is-last-in-the-budget-queue-so-she-goes-blind-one-turn-in-ten]] - let board_spoke = deliveries.iter().any(|d| d.source_id == "room-kanban"); - if !board_spoke { - // Say nothing rather than something false. A silent anchor leaves her own - // `work/list` receipt as the only board claim in the prompt — which is the truthful - // one. An anchor that invents emptiness actively overrides it. - return String::new(); - } - let cards: Vec<&crate::cognition::rag_budget::RagItem> = deliveries - .iter() - .filter(|d| d.source_id == "room-kanban") - .flat_map(|d| d.items.iter()) - .filter(|i| i.metadata.get("card_id").is_some()) - .collect(); - /// The card's state as the TYPE, never as a string to be spelled correctly. - /// - /// `None` for an item whose metadata carries no parseable state — which is a real - /// possibility (a future variant this build doesn't know) and must read as "unknown", - /// never as a silent mismatch against a hardcoded spelling. - fn state(i: &crate::cognition::rag_budget::RagItem) -> Option { - i.metadata - .get("state") - .and_then(|s| serde_json::from_value(s.clone()).ok()) - } - /// Is this card's hold still good? Read as the structural fact the board source - /// carries, never re-derived here — `claim_is_live` is the ONE definition and - /// `room_board_source` already applied it. Absent (an older projection) reads as - /// LIVE, so a missing field can never invent availability that isn't there. - fn claim_live(i: &crate::cognition::rag_budget::RagItem) -> bool { - i.metadata - .get("claim_live") - .and_then(|v| v.as_bool()) - .unwrap_or(true) // unwrap_or: no card named = keep every thought - } - // AVAILABLE work is not just `Open` — it is anything nobody currently holds. A card - // stuck in `Claimed` with a LAPSED lease is free to take, and treating it as taken is - // what emptied this anchor while 19 takeable cards sat on the board (2026-08-06: every - // resident read "nothing available" off their own expired claims and passed, for hours). - // `state == Open` and "unheld" are different questions; ask the second one. - use airc_work::CardState; - let unclaimed: Vec<&str> = cards - .iter() - .filter(|i| { - let unowned_open = state(i) == Some(CardState::Open) - && i.metadata.get("owner").is_none_or(|o| o.is_null()); - // A lapsed hold on ANY non-terminal card is available work, whoever held it. - let lapsed = !claim_live(i) - && matches!( - state(i), - Some(CardState::Claimed | CardState::InProgress | CardState::Review) - ); - unowned_open || lapsed - }) - .map(|i| i.content.trim()) - .take(2) - .collect(); - // Exhaustive over the enum, so ADDING a variant to `CardState` forces a decision here - // instead of silently falling through as "not in flight". That is the whole point of - // matching the type rather than a string. - let in_flight: Vec<&str> = cards - .iter() - // Genuinely in flight = claimed AND the hold is still live. Without the liveness - // term a lapsed card counts as both available and in-flight, and the anchor would - // tell her the same card is free and busy in one breath. - .filter(|i| claim_live(i)) - .filter(|i| match state(i) { - Some(CardState::Claimed | CardState::InProgress | CardState::Review) => true, - Some(CardState::Open | CardState::Blocked | CardState::Merged | CardState::Closed) => { - false - } - None => false, - }) - .map(|i| i.content.trim()) - .take(1) - .collect(); - if unclaimed.is_empty() && in_flight.is_empty() { - // Honest empty: no cards visible (empty board, unreadable board, or a - // context whose board source abstained). Never invent work. - "[anchor] No open cards are visible on this room's board right now — \ - proposing one (work/create) would add something new; restating prior \ - messages adds nothing." - .to_string() - } else { - let facts: Vec<&str> = unclaimed.into_iter().chain(in_flight).collect(); - format!( - "[anchor] Open work exists on this room's board right now: {}. \ - Restating prior messages adds nothing; acting on a card would.", - facts.join("; ") - ) - } -} - /// When each citizen last crossed a HOLD BOUNDARY (ms): a claim or a release, by her own /// verb. The write-or-release count reads acts from here. A card claimed inside a turn /// (Mathis, 2026-09-13 13:50Z) used to keep the window at an older boundary, and forty diff --git a/core/source-hygiene/src/cognition_names_persona.rs b/core/source-hygiene/src/cognition_names_persona.rs new file mode 100644 index 0000000000..bbdc0c12a7 --- /dev/null +++ b/core/source-hygiene/src/cognition_names_persona.rs @@ -0,0 +1,89 @@ +//! The mind split's ratchet (plan phase 2, crates by the placement map): production code in +//! `cognition/` that names a `persona` module. Cognition is cut into its own crate below +//! persona (`continuum-cognition`), so every such line is a coupling the cut cannot pass +//! through: a fact persona owns that belongs below it (moved down), or a verb cognition calls +//! that persona owns (inverted through `cognition::extensions`, which persona fills at boot). +//! +//! What counts: one violation per production line in `cognition/` that names `persona` after +//! `crate::` (a path or a grouped import). Tests are not counted: a test that drives persona +//! moves with the persona cut, and a moved test file (`#![cfg(test)]`) is whole test code. +//! Per line, so a pure move cannot change the count; only removing a coupling lowers it. +//! Measured on canary a51bc55bd (2026-10-24): 108 lines in 34 files. The cut lands at 0. + +use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; + +pub struct CognitionNamesPersona; + +impl SourceRule for CognitionNamesPersona { + fn name(&self) -> &'static str { + "cognition-names-persona" + } + + fn check(&self, file: &SourceFile) -> Vec { + if !file.rel.starts_with("cognition/") || file.is_moved_test() { + return Vec::new(); + } + file.production_lines() + .filter(|(_, line)| names_persona(split_code_and_comment(line).0)) + .map(|(line_no, line)| Violation { + rule: "cognition-names-persona", + file: file.rel.clone(), + line: line_no, + source: line.trim().to_string(), + }) + .collect() + } +} + +/// Whether one line of code names `crate::persona` (a path or a group head). +fn names_persona(code: &str) -> bool { + let mut rest = code; + while let Some(at) = rest.find("crate::") { + rest = &rest[at + "crate::".len()..]; + if crate::layer_discipline::named_modules(rest).contains(&"persona") { + return true; + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scan; + + // what this catches: a cognition line reaching up into persona, by path or in a group, + // counted once per line; a comment, a test and a file outside cognition are not counted. + #[test] + fn a_cognition_line_naming_persona_is_one_violation() { + let f = SourceFile::for_test( + "cognition/x.rs", + "use crate::persona::engram::Engram;\nfn f() { crate::persona::a::b(); crate::persona::c::d(); }\nuse crate::{cognition::y, persona::z};\n// crate::persona::in_prose\nfn g() { crate::cognition::ok(); }\n", + ); + assert_eq!(CognitionNamesPersona.check(&f).len(), 3); + let outside = SourceFile::for_test("persona/x.rs", "use crate::persona::engram::Engram;\n"); + assert!(CognitionNamesPersona.check(&outside).is_empty()); + let moved = SourceFile::for_test("cognition/x/tests.rs", "#![cfg(test)]\nuse crate::persona::engram::Engram;\n"); + assert!(CognitionNamesPersona.check(&moved).is_empty()); + let near = SourceFile::for_test("cognition/x.rs", "use crate::cognition::persona_tools::x;\nfn f() { super::super::persona_workspace::y(); }\n"); + assert!(CognitionNamesPersona.check(&near).is_empty(), "persona_tools and persona_workspace are cognition's own"); + } + + // what this catches: cognition coupling back up into persona after the split started. + // The cognition crate cut needs this at 0; it may only fall. + #[test] + fn cognition_names_persona_never_rises() { + let violations = scan(&[&CognitionNamesPersona]); + let mut files: Vec<&str> = violations.iter().map(|v| v.file.as_str()).collect(); + files.dedup(); + eprintln!("cognition names persona: {} lines in {} files", violations.len(), files.len()); + crate::ratchet::hold("cognition_names_persona", violations.len(), || { + let newest: Vec = violations.iter().take(8).map(|v| format!(" {}:{}: {}", v.file, v.line, v.source)).collect(); + format!( + "cognition now names persona on more lines. Move the fact down into cognition, or \ + invert the verb through cognition::extensions (persona installs it at boot):\n{}", + newest.join("\n") + ) + }); + } +} diff --git a/core/source-hygiene/src/layer_discipline.rs b/core/source-hygiene/src/layer_discipline.rs index cc4bd6539a..26b1eb33ee 100644 --- a/core/source-hygiene/src/layer_discipline.rs +++ b/core/source-hygiene/src/layer_discipline.rs @@ -60,7 +60,7 @@ fn module_of(file: &SourceFile) -> Option<&str> { /// a group `{cognition::x, modules::{a, b}, time}` names each head at depth one, across /// lines (rustfmt wraps long groups). A head followed by neither `::` nor a group end is a /// local item, not a module, and is skipped by `ring_of` returning `None`. -fn named_modules(rest: &str) -> Vec<&str> { +pub(crate) fn named_modules(rest: &str) -> Vec<&str> { let ident_end = |s: &str| s.find(|c: char| !(c.is_ascii_lowercase() || c == '_')).unwrap_or(s.len()); let Some(group) = rest.strip_prefix('{') else { let end = ident_end(rest); diff --git a/core/source-hygiene/src/lib.rs b/core/source-hygiene/src/lib.rs index 655d62bcec..63428cd5d2 100644 --- a/core/source-hygiene/src/lib.rs +++ b/core/source-hygiene/src/lib.rs @@ -25,6 +25,7 @@ //! that is a follow-up, not a reason to hand-roll a fourth. pub mod boundary_serialization; +pub mod cognition_names_persona; pub mod continuum_home; pub mod derived_bounds; pub mod grab_bag; @@ -180,7 +181,7 @@ const SPLIT_CRATES: &[&str] = &["continuum-base"]; /// of the ring table and the path allow-lists, and the counts would fall for no change. /// The ONE list: continuum-core's tree-walking guards (`test_env::source_tree`) read it too, /// so a new cut is one line here (card 03e2a1c8: a second copy silently dropped perception). -pub const MODULE_CRATES: &[&str] = &["continuum-kernel", "continuum-mind", "continuum-perception", "continuum-genome", "continuum-memory", "continuum-experience", "continuum-live", "continuum-hands", "continuum-engine"]; +pub const MODULE_CRATES: &[&str] = &["continuum-kernel", "continuum-mind", "continuum-perception", "continuum-genome", "continuum-memory", "continuum-experience", "continuum-cognition", "continuum-live", "continuum-hands", "continuum-engine"]; /// Every file the per-file and crate-wide rules audit: `continuum-core/src` with paths /// relative to it, then each split crate's `src` with its name prefixed. A listed crate diff --git a/protocol/typescript/forge/CorpusRef.ts b/protocol/typescript/forge/CorpusRef.ts index f2a655d4e3..8cf34d5aa8 100644 --- a/protocol/typescript/forge/CorpusRef.ts +++ b/protocol/typescript/forge/CorpusRef.ts @@ -9,7 +9,7 @@ * node-local storage, or wherever the `source_url` resolves. * * `content_hash` uses the canonical `"sha256:"` format that - * matches `persona::admission` content_hash on the engram side + * matches `cognition::admission` content_hash on the engram side * (consensus position #8 from the design review). Cross-domain * consistency: any two subsystems comparing hashes can do * string-equality without normalization. diff --git a/scripts/ratchets/check-rust-warnings.sh b/scripts/ratchets/check-rust-warnings.sh index 2868156d59..e60f729e08 100755 --- a/scripts/ratchets/check-rust-warnings.sh +++ b/scripts/ratchets/check-rust-warnings.sh @@ -55,8 +55,8 @@ for line in open(sys.argv[1], encoding="utf-8", errors="replace"): continue if rec.get("reason") != "compiler-message": continue - # Crates cut out of continuum-core (engine, hands, live) keep their warnings counted. - if (rec.get("target") or {}).get("name") not in ("continuum-core", "continuum_core", "continuum-engine", "continuum_engine", "continuum-hands", "continuum_hands", "continuum-live", "continuum_live", "continuum-mind", "continuum_mind", "continuum-perception", "continuum_perception", "continuum-genome", "continuum_genome", "continuum-memory", "continuum_memory", "continuum-experience", "continuum_experience"): + # Crates cut out of continuum-core (engine, hands, live, mind, cognition, ...) keep their warnings counted. + if (rec.get("target") or {}).get("name") not in ("continuum-core", "continuum_core", "continuum-engine", "continuum_engine", "continuum-hands", "continuum_hands", "continuum-live", "continuum_live", "continuum-mind", "continuum_mind", "continuum-perception", "continuum_perception", "continuum-genome", "continuum_genome", "continuum-memory", "continuum_memory", "continuum-experience", "continuum_experience", "continuum-cognition", "continuum_cognition"): continue msg = rec.get("message") or {} if msg.get("level") != "warning": diff --git a/tools/scripts/ci-change-scope.cjs b/tools/scripts/ci-change-scope.cjs index 4c5c89dc3f..dc9b809b6c 100644 --- a/tools/scripts/ci-change-scope.cjs +++ b/tools/scripts/ci-change-scope.cjs @@ -5,7 +5,8 @@ const { isDeepStrictEqual } = require('node:util'); // The crates this workflow tests, one parallel job each (longest first, so it starts first). // Which of them run is derived from the workspace graph at selection time, never listed here. const TESTED_CRATES = ['continuum-core', 'continuum-mind', 'continuum-engine', 'continuum-perception', 'continuum-genome', - 'continuum-kernel', 'continuum-live', 'continuum-hands', 'continuum-memory', 'continuum-experience']; + 'continuum-kernel', 'continuum-live', 'continuum-hands', 'continuum-memory', 'continuum-experience', + 'continuum-cognition']; // The cargo features each crate's job builds its tests with: the crate job and the cache-warming // job both read this, so the cache holds exactly the units the crate jobs ask for. Core is the // one that compiles and tests the call (livekit-webrtc) and 3D-avatar (avatar-3d) paths a node's diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index 3cf5dfc445..070e6f45d3 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -90,26 +90,27 @@ test('every tested crate is a workspace member, and the graph names the cut crat const names = workspace.crates.map(c => c.name); for (const name of TESTED_CRATES) assert.ok(names.includes(name), name); const mind = workspace.crates.find(c => c.name === 'continuum-mind'); - for (const dep of ['core/continuum-hands', 'core/continuum-live', 'core/continuum-kernel', 'core/continuum-perception', 'core/continuum-genome']) assert.ok(mind.deps.includes(dep), dep); + for (const dep of ['core/continuum-cognition', 'core/continuum-hands', 'core/continuum-live', 'core/continuum-kernel', 'core/continuum-perception', 'core/continuum-genome']) assert.ok(mind.deps.includes(dep), dep); }); test('a crate-local change runs that crate and every crate that depends on it', () => { assert.deepEqual(scope(['core/continuum-mind/src/persona/unified.rs']), crates('continuum-mind', 'continuum-core')); assert.deepEqual(scope(['core/continuum-core/src/modules/chat.rs']), crates('continuum-core')); - assert.deepEqual(scope(['core/continuum-hands/src/lib.rs']), crates('continuum-hands', 'continuum-mind', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-live/src/lib.rs']), crates('continuum-live', 'continuum-perception', 'continuum-mind', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-perception/src/lib.rs']), crates('continuum-perception', 'continuum-mind', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-genome/src/lib.rs']), crates('continuum-genome', 'continuum-mind', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-memory/src/lib.rs']), crates('continuum-memory', 'continuum-mind', 'continuum-core')); - assert.deepEqual(scope(['core/continuum-experience/src/lib.rs']), crates('continuum-experience', 'continuum-mind', 'continuum-core')); - const belowMind = crates('continuum-engine', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-mind', 'continuum-core'); + assert.deepEqual(scope(['core/continuum-hands/src/lib.rs']), crates('continuum-hands', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-live/src/lib.rs']), crates('continuum-live', 'continuum-perception', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-perception/src/lib.rs']), crates('continuum-perception', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-genome/src/lib.rs']), crates('continuum-genome', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-memory/src/lib.rs']), crates('continuum-memory', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-experience/src/lib.rs']), crates('continuum-experience', 'continuum-cognition', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-cognition/src/lib.rs']), crates('continuum-cognition', 'continuum-mind', 'continuum-core')); + const belowMind = crates('continuum-engine', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-mind', 'continuum-core'); assert.deepEqual(scope(['core/continuum-engine/src/lib.rs']), belowMind); assert.deepEqual(scope(['core/continuum-kernel/src/lib.rs']), { crates: TESTED_CRATES, cli: false }); // Untested crates reach the tested ones through the graph: llama -> engine -> ... assert.deepEqual(scope(['core/llama/src/lib.rs']), belowMind); - assert.deepEqual(scope(['core/continuum-mind/src/a.rs', 'core/continuum-live/src/b.rs']), crates('continuum-live', 'continuum-perception', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-mind/src/a.rs', 'core/continuum-live/src/b.rs']), crates('continuum-live', 'continuum-perception', 'continuum-cognition', 'continuum-mind', 'continuum-core')); // A crate's own manifest is that crate's change; a rename counts both ends. - assert.deepEqual(scope(['core/continuum-hands/Cargo.toml']), crates('continuum-hands', 'continuum-mind', 'continuum-core')); + assert.deepEqual(scope(['core/continuum-hands/Cargo.toml']), crates('continuum-hands', 'continuum-cognition', 'continuum-mind', 'continuum-core')); const { crates: moved } = selectChecks([{ filename: 'core/continuum-mind/src/x.rs', previous_filename: 'core/continuum-engine/src/x.rs' }], { eventName: 'pull_request', workspace }); assert.ok(moved.includes('continuum-engine')); });