diff --git a/core/continuum-academy/src/cognition/dream_consolidation/consolidate.rs b/core/continuum-academy/src/cognition/dream_consolidation/consolidate.rs index 296c9d6e68..c60ab69086 100644 --- a/core/continuum-academy/src/cognition/dream_consolidation/consolidate.rs +++ b/core/continuum-academy/src/cognition/dream_consolidation/consolidate.rs @@ -212,40 +212,17 @@ impl DreamConsolidationRegion { let consolidated = Arc::clone(&self.consolidated); let reviewed = Arc::clone(&self.reviewed); let boundaries = Arc::clone(&self.review_boundaries); - let mut boundary_wake = self.review_boundary_wake.subscribe(); #[cfg(test)] let idle_wait = self.idle_wait.clone(); tokio::spawn(async move { let _permit = permit; - // #2561 preemption = paging out: an arriving demand does not queue - // behind a dream — it CANCELS it. The dropped future closes the - // generation stream (the backend abandons the slot on disconnect); - // the half-formed dream is discarded, and it is CHEAP to discard: - // dreams are the lowest-priced resident in the paging economy, - // re-dreamable from the same engrams on the next bored window. - // - // BOREDOM FIRST, THEN THE RACE. The wait used to live inside `dream_pass`, - // so the cancel arm below was armed while the pass was still parked on her - // gate — mid-turn the cancel won instantly, the in-flight slot cleared, and - // the region re-spawned every tick (measured 2026-09-03: 22 `paged_out` per - // citizen at an exact 30s cadence, zero consolidations). A dream arises - // only in her sustained idle; only THEN can wakefulness cancel it. - { - let a = crate::cognition::activity_gate::persona_activity(persona_id); - if !crate::cognition::activity_gate::persona_bored( - a, - crate::inference::measured_hold::subscribe() - .borrow() - .is_some(), - continuum_base::time::EpochMs::now().millis(), - ) { - continuum_base::probe!( - class = "dream.awaiting_boredom", - persona = %persona_id, - "dream pass parked on HER activity gate — arises only in her sustained idle" - ); - } - } + // A dream pass runs while she works (row 6 of MIND-DATAFLOW-OVERHAUL, card a31e72a4): + // it waited for HER sustained idle and her next act cancelled it, so a resident + // who is always engaged never consolidated (the M5, 2026-10-31: dreams 0 in 12 h; + // 2026-09-14: awaiting_boredom x26, paged_out x6, zero consolidations). Its + // generations ask at LanePriority::Ambient inside the non-directed budget + // (distiller.rs), so a directed call keeps its lane; one pass per resident is in + // flight (the permit), and a tick launches one only when fresh episodes exist. if trigger == DreamTrigger::CardBoundary { continuum_base::probe!( class = "dream.card_boundary", @@ -284,45 +261,12 @@ impl DreamConsolidationRegion { } return; } - // A review arriving while idle work is parked must not disappear behind - // its in-flight flag. Retire only the wait; next tick selects fresh - // episodes under the bounded boundary policy, including the finished work. - let bored = async { - #[cfg(test)] - if let Some(wait) = idle_wait { - wait.notified().await; - return; - } - crate::cognition::activity_gate::wait_for_boredom_of(persona_id).await; - }; - tokio::select! { - _ = async { - loop { - if storage_available && boundaries.lock().unwrap().get(&persona_id).is_some_and(|r| !r.pending.is_empty()) { // JUSTIFIED: inspect the owner state without holding its guard across the wait. - return; - } - if boundary_wake.changed().await.is_err() { return; } - } - } => { return; } - _ = bored => {} - } - tokio::select! { - _ = dream_pass( - reflector, - persona_id, - clusters, - fresh, - consolidated, - reviewed, - ) => {} - _ = crate::cognition::activity_gate::wait_for_engagement_of(persona_id) => { - continuum_base::probe!( - class = "dream.paged_out", - persona = %persona_id, - "activity arrived mid-dream — dream cancelled and discarded (re-dreamable)" - ); - } + // A test parks the pass here, before inference, to deliver a review while it is in flight. + #[cfg(test)] + if let Some(wait) = idle_wait { + wait.notified().await; } + dream_pass(reflector, persona_id, clusters, fresh, consolidated, reviewed).await; }); TickOutcome { @@ -385,21 +329,9 @@ impl DreamConsolidationRegion { let reflector = reflector.clone(); tokio::spawn(async move { let _permit = permit; - // HER GAP, NOT BETWEEN HER TURNS (card 07188783): belief hygiene waits for her - // sustained idle, the same gate the idle consolidation pass takes, and her next act - // cancels it; its beliefs stay unreviewed for the next pass. Nothing about it is - // urgent, so it never interleaves with her turns. - crate::cognition::activity_gate::wait_for_boredom_of(persona_id).await; - tokio::select! { - _ = review_pass(reflector, persona_id, beliefs, reviewed) => {} - _ = crate::cognition::activity_gate::wait_for_engagement_of(persona_id) => { - continuum_base::probe!( - class = "dream.review_paged_out", - persona = %persona_id, - "activity arrived mid-review: the review is cancelled and its beliefs stay unreviewed for the next pass" - ); - } - } + // Belief hygiene runs while she works, like every dream pass (card a31e72a4); the + // cooldown above keeps it a trickle, and its generations ask at Ambient priority. + review_pass(reflector, persona_id, beliefs, reviewed).await; }); Some(TickOutcome { published: 0, diff --git a/core/continuum-academy/src/cognition/dream_consolidation/tests/region.rs b/core/continuum-academy/src/cognition/dream_consolidation/tests/region.rs index a592b16095..c62c985663 100644 --- a/core/continuum-academy/src/cognition/dream_consolidation/tests/region.rs +++ b/core/continuum-academy/src/cognition/dream_consolidation/tests/region.rs @@ -8,10 +8,11 @@ use super::*; use crate::runtime::brain_region::RegionContext; -// ce37fbfb: a parked idle owner cannot swallow a reviewed boundary; -// repeated delivery and concurrent ticks must not double inference. +// ce37fbfb, a31e72a4: the idle pass runs while she works (no wait for her idle); a reviewed +// boundary delivered while it is in flight is finished by a later tick, never swallowed by the +// in-flight flag; repeated delivery and concurrent ticks never double inference. #[tokio::test] -async fn reviewed_boundary_wakes_the_idle_owner_and_deduplicates_replay() { +async fn a_reviewed_boundary_during_an_idle_pass_is_finished_once_without_doubling_inference() { use std::sync::atomic::{AtomicUsize, Ordering}; let persona = Uuid::new_v4(); let seeds: Vec<_> = (0..3) @@ -34,30 +35,27 @@ async fn reviewed_boundary_wakes_the_idle_owner_and_deduplicates_replay() { HeuristicInferenceAdapter::new().with_generate_observer(calls.clone()), ), })); - region.idle_wait = Some(Arc::new(tokio::sync::Notify::new())); + let park = Arc::new(tokio::sync::Notify::new()); + region.idle_wait = Some(park.clone()); region.consolidate(persona).await; tokio::task::yield_now().await; - assert!(region.dreaming()); - assert_eq!( - calls.load(Ordering::SeqCst), - 0, - "the actual owner is parked before inference" - ); + assert!(region.dreaming(), "the idle pass is in flight"); let review = Uuid::new_v4(); assert!(region.request_reviewed_boundary(persona, review)); - assert!(!region.request_reviewed_boundary(persona, review)); + assert!(!region.request_reviewed_boundary(persona, review), "repeated delivery queues once"); + park.notify_one(); drain(®ion).await; assert_eq!( calls.load(Ordering::SeqCst), - 0, - "wake retires stale selection; it does not start another task" + 2, + "the idle pass ran to the end while she works: one consolidator and one historian request" ); tokio::join!(region.consolidate(persona), region.consolidate(persona)); drain(®ion).await; assert_eq!( calls.load(Ordering::SeqCst), 2, - "one consolidator and one historian request" + "the boundary finds its episodes already folded: finished, with no second inference" ); assert_eq!( admission @@ -67,7 +65,7 @@ async fn reviewed_boundary_wakes_the_idle_owner_and_deduplicates_replay() { .count(), 1 ); - assert!(!region.request_reviewed_boundary(persona, review)); + assert!(!region.request_reviewed_boundary(persona, review), "a finished boundary is not queued again"); region.consolidate(persona).await; drain(®ion).await; assert_eq!(calls.load(Ordering::SeqCst), 2); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 9a3b832064..7fe19c5003 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -216,9 +216,6 @@ impl LlmDeliberationFaculty { let _admission = self .admit_generation(ws, &request, adapter.generation_admission(), &mut capture) .await?; - // HER task-positive system is engaged from here: the per-citizen boredom gate - // (dreams) reads this stamp, never a room wake. - crate::cognition::activity_gate::persona_engaged(self.persona_id); // COGNITION PULSE per generation, not only per turn start. The claim-renewal // gate reads this stamp, and a single service-loop turn can run many acts: on // the M5 an act takes 7-9 minutes, so a multi-act turn outlives the 30-minute diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index 8cdb71c844..1c9c90c9a6 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -234,10 +234,9 @@ impl ServiceModule for CognitionModule { /// while we tried to save her. /// 2. Wait for the turns already admitted to finish, bounded. /// - /// The count comes from the permits the loops hold, not from `activity_gate`'s - /// `engaged` flag: engagement is stamped at serving-lane acquisition, so a turn that - /// has taken a message and is still composing context is not engaged, and draining on - /// that flag would walk past exactly the turns whose loss leaves no trace. + /// The count comes from the permits the loops hold: a turn that has taken a message and + /// is still composing context holds one before any serving lane, so the drain waits for + /// exactly the turns whose loss would leave no trace. /// /// Returns the number still running when the budget expired — a citizen who is still /// thinking is a fact the receipt reports, not one it waits forever for. 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 d33571ee08..942bef66ae 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 @@ -130,11 +130,8 @@ pub(super) async fn serve_persona_loop_inner( // Taken the moment a wake is produced, BEFORE the match, because the // `Wake::Tick` arm does its self-tick deliberation INLINE and then `continue`s — // it never reaches the code below it. A permit taken after the match would have - // counted inbound turns and silently missed every self-directed one, which is the - // same blindness as draining on `activity_gate`'s `engaged` flag: that one is - // stamped at serving-lane acquisition, so a turn still composing its context does - // not appear there either. Both gaps hide turns that have consumed input and - // written nothing. + // counted inbound turns and silently missed every self-directed one: turns that have + // consumed input and written nothing. // // Held to the end of the loop body, so it is released on EVERY exit path — the // `continue` at the end of the tick arm included. A manual decrement would have to 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 9cbb7c2613..d5c386753b 100644 --- a/core/continuum-mind/src/persona/service_loop/wake_select.rs +++ b/core/continuum-mind/src/persona/service_loop/wake_select.rs @@ -37,12 +37,6 @@ pub(super) async fn await_wake( mind.next_mind_check = Some(tokio::time::Instant::now()); } } - // HER turn boundary: idle whenever the loop is back at its wake select. The - // matching `engaged` stamp is set where a serving lane is actually acquired - // (the deliberation faculty) — a room wake alone is not wakefulness, or a - // busy room would cancel every dream (measured: 290 paged out in 20 min with - // the stamp on the wake itself). - crate::cognition::activity_gate::persona_idle(ctx.identity.peer_id.as_uuid()); // BIASED: a line already in her inbox beats a due self-tick. Without the // order, a directed line that made her yield a parked lane wait could // lose the next wake to the tick again (random branch choice) — a yield diff --git a/core/continuum-vitals/src/activity_gate.rs b/core/continuum-vitals/src/activity_gate.rs index c19090c5e3..50797400fd 100644 --- a/core/continuum-vitals/src/activity_gate.rs +++ b/core/continuum-vitals/src/activity_gate.rs @@ -31,11 +31,10 @@ use continuum_base::time::EpochMs; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{LazyLock, OnceLock}; +use std::sync::OnceLock; use std::time::Duration; use tokio::sync::watch; -use uuid::Uuid; /// Sustained-idle threshold before boredom ARISES. A hysteresis cadence (like a /// monitor tick), not a behavior heuristic: entry is deliberately lazy so a @@ -213,153 +212,10 @@ pub fn spawn_activity_gate() { } -// ── PER-CITIZEN boredom (2026-09-03) ──────────────────────────────────────────── -// -// The organism gate above is ONE state for the whole process: `inflight > 0` -// anywhere means Active everywhere. Measured with 12 citizens working a deck: -// 749 dreams cancelled mid-pass by SOMEONE ELSE'S activity vs 4 consolidations in -// six hours — continual learning was not switched off, it was starved by a gate -// scoped too broadly ([[a-design-fork-is-usually-a-guard-scoped-too-broadly]]). -// A mind's default-mode network fails to arise while ITS OWN task-positive -// systems are engaged, not while a colleague's are. So a dream now waits on the -// citizen's OWN engagement (stamped at her turn boundaries by the service loop) -// plus the one genuinely global input — a measured hold, the exam lease that -// quiets everything. Same asymmetric hysteresis: exit instantly on her activity, -// enter only after [`BOREDOM_AFTER`] of her sustained idle. - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PersonaActivity { - /// She is inside a turn (inbound or self-tick) right now. - pub engaged: bool, - /// Epoch-ms of the last engagement change. - pub since_ms: u64, -} - -static PERSONAS: LazyLock>> = - LazyLock::new(dashmap::DashMap::new); - -fn persona_tx(peer: Uuid) -> watch::Sender { - PERSONAS - .entry(peer) - .or_insert_with(|| { - watch::channel(PersonaActivity { engaged: false, since_ms: EpochMs::now().millis() }).0 - }) - .clone() -} - -/// Stamp `peer` engaged (a turn began). Idempotent; publishes only on change. -pub fn persona_engaged(peer: Uuid) { - set_persona(peer, true); -} - -/// Stamp `peer` idle (her turn ended, the loop is back at its wake select). -pub fn persona_idle(peer: Uuid) { - set_persona(peer, false); -} - -fn set_persona(peer: Uuid, engaged: bool) { - let tx = persona_tx(peer); - let cur = *tx.borrow(); - if cur.engaged != engaged { - // send_replace, never send: the per-persona receiver is not guaranteed alive, and a - // `send` with no receiver drops the value — persona_activity() would then read the - // boot state forever (the gate-wide channel had exactly this bug, see `publish`). - tx.send_replace(PersonaActivity { engaged, since_ms: EpochMs::now().millis() }); - } -} - -/// Her current activity (idle-since is `since_ms` when not engaged). -pub fn persona_activity(peer: Uuid) -> PersonaActivity { - *persona_tx(peer).borrow() -} - -/// PURE: is `peer` bored at `now` — idle for [`BOREDOM_AFTER`] with no measured -/// hold on the box? -pub fn persona_bored(activity: PersonaActivity, hold_active: bool, now: u64) -> bool { - !hold_active - && !activity.engaged - && now.saturating_sub(activity.since_ms) >= BOREDOM_AFTER.as_millis() as u64 -} - -/// Park until `peer` has been idle for [`BOREDOM_AFTER`] and no measured hold is -/// active. Event-driven: parks on her engagement watch and the hold watch; the -/// only timer is the sustained-idle threshold itself, restarted on any change. -pub async fn wait_for_boredom_of(peer: Uuid) { - if !GATE_LIVE.load(Ordering::Acquire) { - return; // gate not running: permissive — the hold-defer seams still guard - } - let tx = persona_tx(peer); - let mut rx = tx.subscribe(); - let mut hold_rx = continuum_engine::inference::measured_hold::subscribe(); - loop { - let activity = *rx.borrow(); - let hold_active = hold_rx.borrow().is_some(); - let now = EpochMs::now().millis(); - if persona_bored(activity, hold_active, now) { - return; - } - if activity.engaged || hold_active { - tokio::select! { - r = rx.changed() => { if r.is_err() { return; } } - r = hold_rx.changed() => { if r.is_err() { return; } } - } - continue; - } - let remaining = BOREDOM_AFTER - .as_millis() - .saturating_sub(now.saturating_sub(activity.since_ms) as u128) as u64; - tokio::select! { - _ = tokio::time::sleep(Duration::from_millis(remaining.max(1))) => {} - r = rx.changed() => { if r.is_err() { return; } } - r = hold_rx.changed() => { if r.is_err() { return; } } - } - } -} - -/// Resolve when `peer` becomes engaged (her own turn) or a measured hold starts — -/// the wakeful demand that cancels HER dream. Never resolves on a colleague's -/// activity, and never spuriously (a dead publisher parks forever). -pub async fn wait_for_engagement_of(peer: Uuid) { - if !GATE_LIVE.load(Ordering::Acquire) { - std::future::pending::<()>().await; - } - let tx = persona_tx(peer); - let mut rx = tx.subscribe(); - let mut hold_rx = continuum_engine::inference::measured_hold::subscribe(); - loop { - if rx.borrow().engaged || hold_rx.borrow().is_some() { - return; - } - tokio::select! { - r = rx.changed() => { if r.is_err() { std::future::pending::<()>().await; } } - r = hold_rx.changed() => { if r.is_err() { std::future::pending::<()>().await; } } - } - } -} - #[cfg(test)] mod tests { use super::*; - // what this catches: the whole boredom decision as arithmetic — activity of - // any kind wins instantly; boredom requires SUSTAINED idle (never a flap on - // a short gap); the directed linger keeps a conversation's inter-turn gaps - // active. Regression guard for #2561's contract before any consumer relies - // on it. - // what this catches: the scope of the gate. A citizen's boredom depends on HER - // idle and the box's measured hold — never on `inflight` elsewhere. Before - // 2026-09-03 a colleague's work cancelled every dream (749 paged out / 4 done). - #[test] - fn a_citizens_boredom_is_her_own_idle_not_the_organisms() { - let t0 = 10_000_000u64; - let idle_long = PersonaActivity { engaged: false, since_ms: t0 - 100_000 }; - let idle_short = PersonaActivity { engaged: false, since_ms: t0 - 10_000 }; - let busy = PersonaActivity { engaged: true, since_ms: t0 - 100_000 }; - assert!(persona_bored(idle_long, false, t0)); - assert!(!persona_bored(idle_short, false, t0), "sustained idle, not a pause"); - assert!(!persona_bored(busy, false, t0), "her own turn is wakefulness"); - assert!(!persona_bored(idle_long, true, t0), "a measured hold quiets everyone"); - } #[test] fn boredom_arises_slowly_and_dies_instantly() { @@ -406,15 +262,4 @@ mod tests { }); assert_eq!(current().state, ActivityState::Active); } - // what this catches: the per-persona channel has the same dropped-receiver shape as - // the gate-wide one — an engaged/idle flip with no subscriber must still be readable. - #[test] - fn a_persona_flip_with_no_subscriber_is_still_readable() { - let peer = Uuid::new_v4(); - assert!(!persona_activity(peer).engaged); - persona_engaged(peer); - assert!(persona_activity(peer).engaged); - persona_idle(peer); - assert!(!persona_activity(peer).engaged); - } } diff --git a/core/continuum-vitals/src/turn_ingress.rs b/core/continuum-vitals/src/turn_ingress.rs index 2b855b1b87..9634102e76 100644 --- a/core/continuum-vitals/src/turn_ingress.rs +++ b/core/continuum-vitals/src/turn_ingress.rs @@ -58,13 +58,11 @@ pub fn in_flight() -> u64 { /// ADMIT a turn, or refuse because the node is stopping. /// -/// # Why not read `activity_gate`'s engaged flag +/// # Why a permit taken at admission /// -/// `persona_engaged` is stamped where a serving LANE is acquired, deliberately — a room -/// wake alone is not wakefulness, or a busy room would cancel every dream. So a turn that -/// has been admitted and is still composing context, or is queued for a lane, is not yet -/// `engaged`. Draining on that flag would walk past exactly the turns that have taken -/// input and not yet written anything, which are the ones whose loss is invisible. +/// A turn that has been admitted and is still composing context, or is waiting for a lane, +/// has taken input and written nothing yet; its loss would be invisible. Admission is the +/// first moment it exists, so the permit counts it from there. #[must_use = "the permit IS the turn's admission; dropping it immediately ends the turn"] pub fn admit() -> Option> { GATE.admit()