From 41431a4dfd57ace89e6c877f0bfb915386f8ada8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 31 Oct 2026 21:08:39 +0100 Subject: [PATCH 01/19] heartbeat: the beat gives a Self run to a Mind whose Self holds briefs; an open breaker question blocks its brief Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 63 ++++++++++--- crates/mind-body/src/heartbeat/tests.rs | 116 ++++++++++++++++++++++++ 2 files changed, 168 insertions(+), 11 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 2d46291..a897478 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -9,8 +9,13 @@ //! waited, bent by the urgency she declared for herself, a member addressing her //! and (a later cut) topics she subscribed to. Two things launch a Persona off //! the beat: the operator tagging or naming her, once per message, and her own -//! Self run having ended since her last turn. Nothing is metered here: no -//! meter and no model call. +//! Self run having ended since her last turn. A beat's launch for a Mind whose +//! Self holds briefs (`inbox::derive`) is a Self run claiming them, in place of +//! her Persona turn: a session that ended with a brief open, or a brief admitted +//! after its flush, is never an orphan, and a Self start takes the beat like any +//! launch. A brief with an open question raised in it (the repetition breaker's +//! trip) is not claimed until that question is answered. Nothing is metered here: +//! no meter and no model call. //! //! The heartbeat owns `heartbeat.cc` and is its only writer; Persona units read //! it. The brakes stay the operator's and are read on every poll. Busy and idle @@ -21,6 +26,7 @@ //! A held swarm brake ends the poll before the mind or the mouth is touched. use std::fmt; +use std::collections::HashSet; use std::net::SocketAddr; use std::path::PathBuf; @@ -34,7 +40,8 @@ use huginn_mind::{PipelineDocumentSummary, PipelineFacts, PipelinePageItems}; use crate::chat_client::{Chat, ChatDelivery}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, LaunchOutcome, LaunchRequest, Launcher, Ports, holders, open_and_launch}; -use crate::queue::{MindPort, any_of, citing, headers, of_kind}; +use crate::queue::{MindPort, any_of, citing, headers, in_force, of_kind}; +use crate::self_run::inbox; use crate::tempo::{self, Standing}; /// The admitting agent's name on every run the heartbeat opens. @@ -548,12 +555,13 @@ enum Launched { Refused(String), } -/// The one way the heartbeat starts a Persona turn: the same brake read and the -/// same opener for a beat, an operator mention and a Self run that ended. -fn launch(organs: &Organs, row: &Row) -> Result { +/// The one way the heartbeat starts a run: the same brake read and the same +/// opener for a Persona turn (a beat, an operator mention, a Self run that ended) +/// and for the Self run a beat gives to the briefs her Self holds. +fn launch(organs: &Organs, row: &Row, turn: RunTurn, claims: Vec) -> Result { let Effective::Released(grant) = organs.control.effective(row.slug()) else { return Ok(Launched::Refused("the brake is held".into())) }; let ports = Ports { mind: row.seat.mind, launcher: organs.launcher, clock: organs.clock, host: organs.host }; - let request = LaunchRequest { turn: RunTurn::PersonaTurn, claims: vec![], agent: AGENT.into(), grant }; + let request = LaunchRequest { turn, claims, agent: AGENT.into(), grant }; Ok(match open_and_launch(&ports, request) { Ok(LaunchOutcome::Launched { run }) => Launched::Run(label_of(&run)), Ok(LaunchOutcome::Busy { .. }) => Launched::Busy, @@ -562,6 +570,33 @@ fn launch(organs: &Organs, row: &Row) -> Result { }) } +/// The most briefs one Self run claims. +const BRIEFS_PER_SELF_RUN: usize = 64; + +/// The briefs a Self run would claim for this Mind: those in force that no live +/// Self run holds and that no open question blocks. A question raised in a brief +/// is the repetition breaker's trip; it stays blocking until it is answered or +/// withdrawn, so a trip is a stop and never a fresh count. +fn claimable(row: &Row) -> Result> { + let mind = row.seat.mind; + if !holders(mind, row.slug(), RunTurn::SelfRun)?.is_empty() { + return Ok(Vec::new()); + } + let blocked: Vec = headers(mind, &in_force(of_kind(PipelineKind::Question)))? + .into_iter() + .filter_map(|header| match header.facts { + PipelineFacts::Question { raised_in: Some(item), .. } => Some(item), + _ => None, + }) + .collect(); + Ok(inbox::derive(mind, &HashSet::new())? + .into_iter() + .map(|brief| PipelineRef { kind: PipelineKind::FollowUp, id: brief.id.as_str().into() }) + .filter(|claim| !blocked.contains(claim)) + .take(BRIEFS_PER_SELF_RUN) + .collect()) +} + /// One poll. pub fn poll(organs: &Organs, config: &Config) -> Result { if let SwarmEffective::Held(reason) = organs.control.envelope() { @@ -626,7 +661,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { if mentioned.is_none() && !self_ended { continue; } - match launch(organs, row)? { + match launch(organs, row, RunTurn::PersonaTurn, vec![])? { Launched::Run(label) => { if let Some(key) = mentioned { state.handled_mentions.push(key); @@ -664,15 +699,21 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // one failing Mind never starves the others; a launch ends the beat. let mut passed: Vec = standings.clone(); while due && let Some(winner) = tempo::pick(&passed, beat_s) { - match launch(organs, &rows[winner])? { + // Her Self holds briefs: the beat is a Self run for them; otherwise a Persona turn. + let claims = claimable(&rows[winner]).unwrap_or_else(|error| { + rows[winner].note = format!("briefs: {error}"); + Vec::new() + }); + let turn = if claims.is_empty() { RunTurn::PersonaTurn } else { RunTurn::SelfRun }; + match launch(organs, &rows[winner], turn, claims)? { Launched::Run(label) => { state.last_beat_at = now; - rows[winner].busy = true; + rows[winner].busy = turn == RunTurn::PersonaTurn; launches.push(label); launched.push(rows[winner].slug().clone()); break; } - Launched::Busy => rows[winner].busy = true, + Launched::Busy => rows[winner].busy = turn == RunTurn::PersonaTurn, Launched::Refused(why) => rows[winner].note = why, } passed[winner].eligible = false; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 5e10aab..4203827 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -780,3 +780,119 @@ fn every_newest_read_asks_for_exactly_one_header() { let queries = rig.calls[ANN].get(); assert!(queries >= 3, "the poll did read her mind ({queries} queries)"); } + +// ---- the beat gives a Self run to a Mind whose Self holds briefs ---------------------- + +use eureka_pipeline::PipelineDocument; + +/// A self-run follow-up for `who`, admitted under `agent`'s receipt. +fn brief_by(rig: &Rig, who: usize, agent: &str, label: &str, source: &PipelineRef) { + let PipelineDocument::FollowUp(mut document) = crate::testkit::follow_up(label, source) else { unreachable!() }; + document.owner = "self-run".into(); + let outcome = rig.minds[who].admit(agent, "session-a", vec![PipelineDocument::FollowUp(document)]).unwrap(); + assert!(matches!(outcome, huginn_mind::PipelineAdmissionOutcome::Committed { .. }), "{outcome:?}"); +} + +/// Two Minds that have both acted, ann longest ago, and a Persona turn of hers to cite. +fn rig_with_a_persona_turn() -> (Box, PipelineRef) { + let rig = Rig::new(); + let label = rig.turn(ANN, 3000); + rig.turn(BOB, 1000); + let source = reference(K::Run, &format!("ann:run:{label}")); + (rig, source) +} + +fn self_runs(rig: &Rig, who: usize) -> Vec { + rig.minds[who] + .ids(K::Run) + .iter() + .filter_map(|id| match rig.minds[who].view(K::Run, id)?.document { + PipelineDocument::Run(run) if run.turn == RunTurn::SelfRun => Some(run), + _ => None, + }) + .collect() +} + +#[test] +fn the_beat_won_by_a_mind_whose_self_holds_briefs_is_one_self_run_claiming_them_and_the_outcome_says_so() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "first", &source); + brief_by(&rig, ANN, crate::persona::AGENT, "second", &source); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "the launch is in the outcome, not only the trace"); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), 1, "one Self run for both briefs"); + let claimed: Vec = runs[0].claims.iter().map(|claim| claim.id.0.clone()).collect(); + assert_eq!(claimed, vec!["eureka-body:follow_up:first".to_string(), "eureka-body:follow_up:second".to_string()]); + assert_eq!(rig.launcher.started.borrow().iter().filter(|(_, turn)| *turn == RunTurn::SelfRun).count(), 1); + assert!(self_runs(&rig, BOB).is_empty(), "bob holds no brief"); + assert_eq!(rig.store.traces.borrow().last().unwrap().launches.len(), 1); +} + +#[test] +fn a_self_run_waits_for_the_beat_like_any_launch() { + let (rig, source) = rig_with_a_persona_turn(); + rig.poll(); + brief_by(&rig, ANN, crate::persona::AGENT, "waiting", &source); + rig.end_run(ANN); + rig.advance(60); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the beat has not passed: no Self run starts"); + assert!(self_runs(&rig, ANN).is_empty()); + rig.advance(900); + let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; + assert_eq!(launched.len(), 1, "one launch for the beat"); +} + +#[test] +fn a_live_self_run_holds_the_briefs_and_the_beat_is_a_persona_turn() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "taken", &source); + rig.poll(); + assert_eq!(self_runs(&rig, ANN).len(), 1); + rig.advance(1000); + rig.poll(); + assert_eq!(self_runs(&rig, ANN).len(), 1, "a live Self run is never given a second"); +} + +#[test] +fn a_follow_up_her_persona_did_not_admit_launches_no_self_run_whatever_source_it_names() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::self_run::AGENT, "hers", &source); + brief_by(&rig, ANN, "test", "by-hand", &source); + rig.poll(); + assert!(self_runs(&rig, ANN).is_empty()); +} + +#[test] +fn a_braked_mind_launches_no_self_run() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "waiting", &source); + rig.control.braked.borrow_mut().push("ann".into()); + rig.poll(); + assert!(self_runs(&rig, ANN).is_empty()); +} + +#[test] +fn a_brief_that_keeps_failing_trips_once_and_a_trip_is_a_stop_until_the_question_is_answered() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "stuck", &source); + let item = reference(K::FollowUp, "eureka-body:follow_up:stuck"); + // Three Self runs have ended on it, each leaving nothing. + for n in 0..3 { + let label = format!("failed-{n}"); + rig.minds[ANN].committed(vec![run_in("ann", &label, RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); + rig.minds[ANN].committed(vec![close(reference(K::Run, &format!("ann:run:{label}")), recorded())]); + } + let before = self_runs(&rig, ANN).len(); + // Beat after beat, whoever launches: no new Self run on the brief, and the breaker asks once. + for _ in 0..8 { + rig.advance(1000); + rig.poll(); + for who in [ANN, BOB] { + if rig.minds[who].ids(K::Run).last().is_some_and(|id| rig.minds[who].view(K::Run, id).is_some_and(|view| matches!(view.status, huginn_mind::PipelineStatus::InForce))) { + rig.end_run(who); + } + } + } + assert_eq!(self_runs(&rig, ANN).len(), before, "no Self run after the trip"); + assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "the breaker asked once; an open question is not asked again nor a fresh count"); +} From d1e3e1dbec4d947ef2acd15c8943c920601d7649 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 31 Oct 2026 21:35:36 +0100 Subject: [PATCH 02/19] heartbeat tests: a Self run leaves her Persona idle, a Persona turn marks her busy (mutants) Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 2 +- crates/mind-body/src/heartbeat/tests.rs | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index a897478..774b1e8 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -713,7 +713,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { launched.push(rows[winner].slug().clone()); break; } - Launched::Busy => rows[winner].busy = turn == RunTurn::PersonaTurn, + Launched::Busy => rows[winner].busy = true, Launched::Refused(why) => rows[winner].note = why, } passed[winner].eligible = false; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 4203827..1234be1 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -825,7 +825,17 @@ fn the_beat_won_by_a_mind_whose_self_holds_briefs_is_one_self_run_claiming_them_ assert_eq!(claimed, vec!["eureka-body:follow_up:first".to_string(), "eureka-body:follow_up:second".to_string()]); assert_eq!(rig.launcher.started.borrow().iter().filter(|(_, turn)| *turn == RunTurn::SelfRun).count(), 1); assert!(self_runs(&rig, BOB).is_empty(), "bob holds no brief"); - assert_eq!(rig.store.traces.borrow().last().unwrap().launches.len(), 1); + let trace = rig.store.traces.borrow().last().cloned().unwrap(); + assert_eq!(trace.launches.len(), 1); + assert!(!trace.instances[ANN].busy, "a Self run is not her Persona's turn: she is not busy"); +} + +#[test] +fn a_beat_won_by_a_mind_with_no_brief_is_a_persona_turn_and_marks_her_busy() { + let (rig, _source) = rig_with_a_persona_turn(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + assert!(self_runs(&rig, ANN).is_empty()); + assert!(rig.store.traces.borrow().last().unwrap().instances[ANN].busy); } #[test] From 2fb2608249c276d6e2f84689fba279ff44c63dff Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 01:20:28 +0100 Subject: [PATCH 03/19] heartbeat: a successor trip is the Mind's stop, one question per cause, not one per brief A Self run claims up to 64 briefs and each empty run counts against all of them, so one cause tripped the briefs in turn, one question per brief per beat. claimable now returns nothing while a question is open in any follow-up of the Mind; the answer reopens the briefs with a fresh count. Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 20 ++++----- crates/mind-body/src/heartbeat/tests.rs | 57 +++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 774b1e8..3e34836 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -574,25 +574,25 @@ fn launch(organs: &Organs, row: &Row, turn: RunTurn, claims: Vec) - const BRIEFS_PER_SELF_RUN: usize = 64; /// The briefs a Self run would claim for this Mind: those in force that no live -/// Self run holds and that no open question blocks. A question raised in a brief -/// is the repetition breaker's trip; it stays blocking until it is answered or -/// withdrawn, so a trip is a stop and never a fresh count. +/// Self run holds. None while a question is open in a brief of hers. A Self run +/// claims up to `BRIEFS_PER_SELF_RUN` briefs and every run it ends empty counts +/// against all of them, so one cause trips them together; a trip is the Mind's +/// stop, one question for the cause, not one per brief. It lasts until the +/// operator answers or withdraws that question, and the count starts afresh. fn claimable(row: &Row) -> Result> { let mind = row.seat.mind; if !holders(mind, row.slug(), RunTurn::SelfRun)?.is_empty() { return Ok(Vec::new()); } - let blocked: Vec = headers(mind, &in_force(of_kind(PipelineKind::Question)))? + let tripped = headers(mind, &in_force(of_kind(PipelineKind::Question)))? .into_iter() - .filter_map(|header| match header.facts { - PipelineFacts::Question { raised_in: Some(item), .. } => Some(item), - _ => None, - }) - .collect(); + .any(|header| matches!(header.facts, PipelineFacts::Question { raised_in: Some(item), .. } if item.kind == PipelineKind::FollowUp)); + if tripped { + return Ok(Vec::new()); + } Ok(inbox::derive(mind, &HashSet::new())? .into_iter() .map(|brief| PipelineRef { kind: PipelineKind::FollowUp, id: brief.id.as_str().into() }) - .filter(|claim| !blocked.contains(claim)) .take(BRIEFS_PER_SELF_RUN) .collect()) } diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 1234be1..6950823 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -906,3 +906,60 @@ fn a_brief_that_keeps_failing_trips_once_and_a_trip_is_a_stop_until_the_question assert_eq!(self_runs(&rig, ANN).len(), before, "no Self run after the trip"); assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "the breaker asked once; an open question is not asked again nor a fresh count"); } + +/// Three Self runs that each claimed every one of `items` and ended leaving nothing. +fn fail_bundle(rig: &Rig, items: &[PipelineRef]) { + for n in 0..3 { + let label = format!("failed-{n}"); + rig.minds[ANN].committed(vec![run_in("ann", &label, RunTurn::SelfRun, RunOperator::Mind, items)]); + rig.minds[ANN].committed(vec![close(reference(K::Run, &format!("ann:run:{label}")), recorded())]); + } +} + +/// Beats on which every live run ends at once; the Self runs and questions the Mind has after them. +fn beats(rig: &Rig, count: usize) { + for _ in 0..count { + rig.advance(1000); + rig.poll(); + for who in [ANN, BOB] { + if rig.minds[who].ids(K::Run).last().is_some_and(|id| rig.minds[who].view(K::Run, id).is_some_and(|view| matches!(view.status, huginn_mind::PipelineStatus::InForce))) { + rig.end_run(who); + } + } + } +} + +#[test] +fn one_cause_failing_a_bundle_of_briefs_is_one_question_not_one_per_brief() { + let (rig, source) = rig_with_a_persona_turn(); + let labels = ["a", "b", "c", "d", "e"]; + let items: Vec = labels.iter().map(|label| reference(K::FollowUp, &format!("eureka-body:follow_up:{label}"))).collect(); + for label in labels { + brief_by(&rig, ANN, crate::persona::AGENT, label, &source); + } + fail_bundle(&rig, &items); + let before = self_runs(&rig, ANN).len(); + beats(&rig, 10); + assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "five briefs, one cause, one question on the desk"); + assert_eq!(self_runs(&rig, ANN).len(), before, "and no Self run launches while it is open"); + assert!(rig.minds[BOB].ids(K::Question).is_empty(), "another Mind is not stopped"); +} + +#[test] +fn a_trip_stops_the_minds_successor_for_a_fresh_brief_too_and_the_answer_resumes_it() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "stuck", &source); + fail_bundle(&rig, &[reference(K::FollowUp, "eureka-body:follow_up:stuck")]); + beats(&rig, 2); + let question = rig.minds[ANN].ids(K::Question).pop().expect("the trip asked"); + let stopped = self_runs(&rig, ANN).len(); + brief_by(&rig, ANN, crate::persona::AGENT, "fresh", &source); + beats(&rig, 4); + assert_eq!(self_runs(&rig, ANN).len(), stopped, "a brief that arrives while the question is open waits for the answer"); + rig.minds[ANN].committed(vec![crate::testkit::ruling("answer", Some((&question, "reopen")))]); + beats(&rig, 1); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), stopped + 1, "answered, the successor launches again"); + let claimed: Vec = runs.last().unwrap().claims.iter().map(|claim| claim.id.0.clone()).collect(); + assert_eq!(claimed.len(), 2, "both briefs, the stuck one reopened: {claimed:?}"); +} From 1b19180555bb212ee85e6d2cac41cdfd0e45ba76 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:09:49 +0100 Subject: [PATCH 04/19] queue: one owner of the hold; a trip belongs to the run whose end tripped it and its question holds that run's claims Cut claimable's Mind-wide stop on any follow-up question and queue's inline blocked loop. queue::on_hold is the one reader of what an in-force question holds (a question raised in a run holds that run's claims, anything else holds itself); queue, inbox::derive and the open_and_launch gate read it. Breaker::Trip names the newest ended counted run; the breaker question is raised in that run; the boundary is the newest of a question raised in the item and a run claiming it that a question is raised in, so an answer or withdrawal gives every claim of the run a fresh count. The trip and the held-brief wait are written to the heartbeat trace. Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 46 ++++--- crates/mind-body/src/launch.rs | 67 +++++++--- crates/mind-body/src/queue.rs | 152 ++++++++++++++++++---- crates/mind-body/src/self_run/inbox.rs | 16 ++- crates/mind-body/tests/public_surface.txt | 6 +- 5 files changed, 217 insertions(+), 70 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 3e34836..013d9b2 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -13,8 +13,10 @@ //! Self holds briefs (`inbox::derive`) is a Self run claiming them, in place of //! her Persona turn: a session that ended with a brief open, or a brief admitted //! after its flush, is never an orphan, and a Self start takes the beat like any -//! launch. A brief with an open question raised in it (the repetition breaker's -//! trip) is not claimed until that question is answered. Nothing is metered here: +//! launch. A brief an open question holds (raised in it, or in a run that claims it: +//! the repetition breaker's trip holds the claims of the run it belongs to) is +//! neither claimed nor told until that question is answered or withdrawn; other +//! briefs are. Nothing is metered here: //! no meter and no model call. //! //! The heartbeat owns `heartbeat.cc` and is its only writer; Persona units read @@ -40,7 +42,7 @@ use huginn_mind::{PipelineDocumentSummary, PipelineFacts, PipelinePageItems}; use crate::chat_client::{Chat, ChatDelivery}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, LaunchOutcome, LaunchRequest, Launcher, Ports, holders, open_and_launch}; -use crate::queue::{MindPort, any_of, citing, headers, in_force, of_kind}; +use crate::queue::{MindPort, any_of, citing, claims_of, headers, in_force, of_kind}; use crate::self_run::inbox; use crate::tempo::{self, Standing}; @@ -565,6 +567,10 @@ fn launch(organs: &Organs, row: &Row, turn: RunTurn, claims: Vec) - Ok(match open_and_launch(&ports, request) { Ok(LaunchOutcome::Launched { run }) => Launched::Run(label_of(&run)), Ok(LaunchOutcome::Busy { .. }) => Launched::Busy, + Ok(LaunchOutcome::Tripped { run, question }) => { + let held = claims_of(row.seat.mind, &run).map_or(0, |claims| claims.len()); + Launched::Refused(format!("tripped: {} holds the {held} claims of {}", question.id.0, run.id.0)) + } Ok(_) => Launched::Refused("launch refused".into()), Err(error) => Launched::Refused(format!("launch failed: {error}")), }) @@ -574,27 +580,24 @@ fn launch(organs: &Organs, row: &Row, turn: RunTurn, claims: Vec) - const BRIEFS_PER_SELF_RUN: usize = 64; /// The briefs a Self run would claim for this Mind: those in force that no live -/// Self run holds. None while a question is open in a brief of hers. A Self run -/// claims up to `BRIEFS_PER_SELF_RUN` briefs and every run it ends empty counts -/// against all of them, so one cause trips them together; a trip is the Mind's -/// stop, one question for the cause, not one per brief. It lasts until the -/// operator answers or withdraws that question, and the count starts afresh. -fn claimable(row: &Row) -> Result> { +/// Self run holds and no open question holds, and how many an open question +/// holds. A Self run claims up to `BRIEFS_PER_SELF_RUN` briefs and every run it +/// ends empty counts against all of them, so one cause trips them together; a +/// trip holds the claims of its run, not the Mind, until the operator answers +/// or withdraws its question, and the count starts afresh. `inbox::derive` +/// reads `queue::on_hold`; nothing here decides what is held. +fn claimable(row: &Row) -> Result<(Vec, usize)> { let mind = row.seat.mind; if !holders(mind, row.slug(), RunTurn::SelfRun)?.is_empty() { - return Ok(Vec::new()); + return Ok((Vec::new(), 0)); } - let tripped = headers(mind, &in_force(of_kind(PipelineKind::Question)))? - .into_iter() - .any(|header| matches!(header.facts, PipelineFacts::Question { raised_in: Some(item), .. } if item.kind == PipelineKind::FollowUp)); - if tripped { - return Ok(Vec::new()); - } - Ok(inbox::derive(mind, &HashSet::new())? + let (free, held) = inbox::derive_counting_held(mind, &HashSet::new())?; + let claims = free .into_iter() .map(|brief| PipelineRef { kind: PipelineKind::FollowUp, id: brief.id.as_str().into() }) .take(BRIEFS_PER_SELF_RUN) - .collect()) + .collect(); + Ok((claims, held)) } /// One poll. @@ -700,10 +703,13 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { let mut passed: Vec = standings.clone(); while due && let Some(winner) = tempo::pick(&passed, beat_s) { // Her Self holds briefs: the beat is a Self run for them; otherwise a Persona turn. - let claims = claimable(&rows[winner]).unwrap_or_else(|error| { + let (claims, held) = claimable(&rows[winner]).unwrap_or_else(|error| { rows[winner].note = format!("briefs: {error}"); - Vec::new() + (Vec::new(), 0) }); + if held > 0 { + rows[winner].note = format!("{held} briefs held by open questions"); + } let turn = if claims.is_empty() { RunTurn::PersonaTurn } else { RunTurn::SelfRun }; match launch(organs, &rows[winner], turn, claims)? { Launched::Run(label) => { diff --git a/crates/mind-body/src/launch.rs b/crates/mind-body/src/launch.rs index c4828f6..cd99fc2 100644 --- a/crates/mind-body/src/launch.rs +++ b/crates/mind-body/src/launch.rs @@ -3,8 +3,9 @@ //! `open_and_launch` is the whole path, in this order: (0) the in-force runs of //! hers of the request's turn are read, a live one (its unit active, or //! admitted within `START_GRACE_S`) answers Busy and a dead one is to be closed -//! Recorded; (1) every cut-spec claim must be in the queue; (2) no claim may -//! trip the repetition breaker; (3) the run is admitted, in the one batch that +//! Recorded; (1) every cut-spec claim must be in the queue; (2) no claim may be held by an open question, and none may +//! trip the repetition breaker (a trip raises one question in the run whose end +//! tripped it, which holds that run's claims); (3) the run is admitted, in the one batch that //! closes the dead holders, so liveness is decided by the in-force record alone //! and the unit table is only the evidence for a close; (4) the unit is started, //! only after that batch commits. The run is the grant (target invariant @@ -28,7 +29,7 @@ use eureka_pipeline::{ use huginn_mind::{MindRefusal, PipelineAdmissionOutcome, PipelineDocumentSummary, PipelineFacts}; use crate::control::Grant; -use crate::queue::{Breaker, MindPort, any_of, breaker, citing, headers, in_force, of_kind, queue}; +use crate::queue::{Breaker, MindPort, any_of, breaker, citing, claims_of, headers, in_force, of_kind, on_hold, queue}; /// How long a run just admitted may have no active unit before its slot is /// treated as dead: `systemctl start --no-block` returns before the unit runs. @@ -245,8 +246,9 @@ pub enum LaunchOutcome { NotQueued { item: PipelineRef, }, + /// The trip belongs to `run`, the run whose end tripped it; `question` is raised in it. Tripped { - item: PipelineRef, + run: PipelineRef, question: PipelineRef, }, /// The live holder of the request's turn, from step 0 or from admission. @@ -344,16 +346,18 @@ pub fn open_and_launch(ports: &Ports, request: LaunchRequest) -> Result LaunchOutcome::Tripped { item: item.clone(), question: id }, + Ok(()) => LaunchOutcome::Tripped { run, question: id }, Err(declined) => LaunchOutcome::Refused(declined), }); } @@ -429,22 +433,24 @@ fn breaker_label(label: &Label) -> Label { Label(format!("breaker-{}", label.0)) } -/// The question a tripped item raises, in the item's own campaign. -fn breaker_question(item: &PipelineRef, label: &Label, now: DateTime) -> PipelineQuestion { +/// The question a trip raises, in the campaign of the claim that tripped: one +/// per trip, raised in `run` and holding the `held` claims it claimed. +fn breaker_question(claim: &PipelineRef, run: &PipelineRef, held: usize, label: &Label, now: DateTime) -> PipelineQuestion { PipelineQuestion { - campaign: Slug(root_of(item).to_string()), + campaign: Slug(root_of(claim).to_string()), label: breaker_label(label), - title: "Repeated runs on one item admitted nothing".into(), - question: - "The last runs on this item left nothing that cites it, so it launches no more. Answering this reopens the item and starts a fresh count." - .into(), + title: "Repeated runs on the same work admitted nothing".into(), + question: format!( + "Run {} and the runs before it left nothing that cites the work it held (claims held: {held}), so none of it launches again. Answering or withdrawing this reopens every claim of that run with a fresh count.", + run.id.0 + ), options: vec![ - QuestionOption { label: "reopen".into(), text: "Rule on the item, which reopens it.".into() }, - QuestionOption { label: "retire".into(), text: "Resolve the item so it is no longer worked.".into() }, + QuestionOption { label: "reopen".into(), text: "Answer to reopen every claim of the run with a fresh count.".into() }, + QuestionOption { label: "retire".into(), text: "Resolve the claims so they are no longer worked, and answer with this option.".into() }, ], recommended: "reopen".into(), depends: vec![], - raised_in: Some(item.clone()), + raised_in: Some(run.clone()), asked_on: date(now), } } @@ -853,12 +859,13 @@ mod tests { let before = rig.runs(); let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); let question = id("question", "breaker-mind-20261009T131500000Z"); - assert_eq!(outcome, LaunchOutcome::Tripped { item: spec_ref("x"), question: reference(K::Question, &question) }); + assert_eq!(outcome, LaunchOutcome::Tripped { run: run_ref("h2"), question: reference(K::Question, &question) }); assert_eq!((rig.runs(), rig.started()), (before, 0)); assert_eq!(rig.mind.ids(K::Question), vec![question.clone()]); let view = rig.mind.view(K::Question, &question).unwrap(); let PipelineDocument::Question(asked) = &view.document else { panic!("not a question") }; - assert_eq!((asked.raised_in.clone(), asked.campaign.0.as_str()), (Some(spec_ref("x")), CAMPAIGN)); + assert_eq!((asked.raised_in.clone(), asked.campaign.0.as_str()), (Some(run_ref("h2")), CAMPAIGN), "raised in the run whose end tripped it"); + assert!(asked.question.contains(&run_ref("h2").id.0) && asked.question.contains("claims held: 1"), "{}", asked.question); assert_eq!(view.admission.provenance.session.0, "mind-20261009T131500000Z"); // Open, the question blocks the item. assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::NotQueued { item: spec_ref("x") }); @@ -918,9 +925,29 @@ mod tests { let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); assert!(matches!(outcome, LaunchOutcome::Tripped { .. }), "{outcome:?}"); assert!(!rig.in_force("dead"), "the trip's batch closes the dead run too"); + let question = rig.mind.ids(K::Question).pop().expect("the trip asked"); + let PipelineDocument::Question(asked) = rig.mind.view(K::Question, &question).unwrap().document else { panic!("not a question") }; + assert_eq!(asked.raised_in, Some(run_ref("dead")), "the dead holder, closed in the same batch, is the run the question is raised in"); assert_eq!((rig.runs(), rig.started()), (3, 0)); } + #[test] + fn the_gate_refuses_a_claim_an_open_question_holds_whatever_its_kind() { + let rig = Rig::new(); + rig.mind.committed(vec![spec("x"), follow_up("brief", &spec_ref("x"))]); + let brief = reference(K::FollowUp, &id("follow_up", "brief")); + // A question raised in a run holds the follow-up that run claimed, though the follow-up is no cut spec. + rig.mind.committed(vec![run("failed", RunTurn::SelfRun, RunOperator::Mind, &[brief.clone(), spec_ref("x")])]); + rig.mind.committed(vec![close(run_ref("failed"), recorded())]); + rig.mind.committed(vec![question_in("fork", &run_ref("failed"))]); + let runs = rig.runs(); + assert_eq!(rig.launch(RunTurn::SelfRun, std::slice::from_ref(&brief)), LaunchOutcome::NotQueued { item: brief.clone() }); + assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::NotQueued { item: spec_ref("x") }, "a cut spec held by a run-raised question"); + assert_eq!((rig.runs(), rig.started()), (runs, 0), "nothing admitted, nothing started"); + rig.mind.committed(vec![close(reference(K::Question, &id("question", "fork")), withdrawn())]); + assert!(matches!(rig.launch(RunTurn::SelfRun, &[brief]), LaunchOutcome::Launched { .. }), "withdrawn, the hold lifts"); + } + /// The one source of every drawn case: splitmix64 from a fixed seed, so a /// failure names a case that runs again. struct Draw(u64); diff --git a/crates/mind-body/src/queue.rs b/crates/mind-body/src/queue.rs index 526c6b4..bf6e69f 100644 --- a/crates/mind-body/src/queue.rs +++ b/crates/mind-body/src/queue.rs @@ -162,27 +162,55 @@ pub(crate) fn live_claims(mind: &dyn MindPort, instance: &Slug, ending: &[Pipeli Ok(claims) } +/// The claims of the run `run`, resolved or not (a citation outlives its +/// resolution). Empty when the mind has no such run. +pub(crate) fn claims_of(mind: &dyn MindPort, run: &PipelineRef) -> Result> { + let one = Selection { keys: Some(vec![run.id.0.clone()]), ..of_kind(PipelineKind::Run) }; + Ok(headers(mind, &one)? + .into_iter() + .flat_map(|header| match header.facts { + PipelineFacts::Run { claims, .. } => claims, + _ => Vec::new(), + }) + .collect()) +} + +/// The items an in-force question holds: the one owner of the stop. A question +/// raised in a run holds every claim of that run, the set that failed together; +/// a question raised in anything else holds that item. The question's text is +/// display only, and a held item is released by answering or withdrawing it. +pub fn on_hold(mind: &dyn MindPort) -> Result> { + let mut held: Vec = Vec::new(); + for header in headers(mind, &in_force(of_kind(PipelineKind::Question)))? { + if let PipelineFacts::Question { raised_in: Some(item), .. } = header.facts { + if item.kind == PipelineKind::Run { + held.extend(claims_of(mind, &item)?); + } else { + held.push(item); + } + } + } + Ok(held) +} + /// What may be worked, oldest first: the cut specs in force that no report -/// answers, that no open question blocks, and that no live run claims. A run in +/// answers, that no open question holds, and that no live run claims. A run in /// `ending` is one the caller closes in the same admission that opens the next, /// so it claims nothing here. pub fn queue(mind: &dyn MindPort, instance: &Slug, ending: &[PipelineRef]) -> Result> { let unreported = Selection { cited: Some(Incoming { role: "cut_spec".into(), exists: false }), ..in_force(of_kind(PipelineKind::CutSpec)) }; - let mut blocked: Vec = Vec::new(); - for header in headers(mind, &in_force(of_kind(PipelineKind::Question)))? { - if let PipelineFacts::Question { raised_in: Some(item), .. } = header.facts { - blocked.push(item); - } - } + let blocked = on_hold(mind)?; let claimed = live_claims(mind, instance, ending)?; Ok(headers(mind, &unreported)?.into_iter().map(|header| header.id).filter(|spec| !blocked.contains(spec) && !claimed.contains(spec)).collect()) } /// Whether an item may still be launched on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum Breaker { Clear, - Trip, + /// Tripped, and the trip belongs to `run`: the newest ended counted run on + /// the item, the run whose end completed the streak or the share. + Trip { run: PipelineRef }, } /// The repetition breaker, derived from the documents that cite the item. @@ -196,29 +224,34 @@ pub enum Breaker { /// withdrawn run never ran and is no run here. A counted run is ended when /// resolved or listed in `ending`, and is empty when no document of the set /// other than a run was admitted from its own admission up to the next counted -/// run's (or to now). Trip when the last `CONSECUTIVE` ended runs are empty, or +/// run's (or to now). Trip, naming the newest ended counted run, when the last `CONSECUTIVE` ended runs are empty, or /// `EMPTY_SHARE` of the last `WINDOW`. What else the mind admitted, such as a /// Persona turn's run or an unrelated ruling, cites nothing here and counts for /// nothing. pub fn breaker(mind: &dyn MindPort, item: &PipelineRef, ending: &[PipelineRef]) -> Result { let mut set = headers(mind, &Selection { cites: Some(citing(item, None)), ..Selection::default() })?; set.sort_by_key(|header| header.admission.ordinal); - let boundary = set + let asked_in_item = set .iter() .filter(|header| matches!(&header.facts, PipelineFacts::Question { raised_in: Some(raised), .. } if raised == item)) - .map(|header| header.admission.ordinal) - .max(); + .map(|header| header.admission.ordinal); + let asked_in_run = Selection { + cites: Some(citing(item, Some("claims"))), + cited: Some(Incoming { role: "raised_in".into(), exists: true }), + ..of_kind(PipelineKind::Run) + }; + let boundary = asked_in_item.chain(headers(mind, &asked_in_run)?.into_iter().map(|run| run.admission.ordinal)).max(); let after = |header: &&PipelineDocumentSummary| boundary.is_none_or(|boundary| header.admission.ordinal > boundary); let withdrawn = |run: &PipelineDocumentSummary| matches!(run.status, PipelineStatusSummary::Resolved { outcome: ResolutionOutcome::Withdrawn { .. }, .. }); - // (admission ordinal, ended) of each counted run, oldest first. - let ran: Vec<(u64, bool)> = set + // (admission ordinal, ended, ref) of each counted run, oldest first. + let ran: Vec<(u64, bool, PipelineRef)> = set .iter() .filter(after) .filter(|header| { matches!(header.facts, PipelineFacts::Run { turn: RunTurn::SelfRun, operated_by: RunOperator::Mind, .. }) && !withdrawn(header) }) - .map(|run| (run.admission.ordinal, matches!(run.status, PipelineStatusSummary::Resolved { .. }) || ending.contains(&run.id))) + .map(|run| (run.admission.ordinal, matches!(run.status, PipelineStatusSummary::Resolved { .. }) || ending.contains(&run.id), run.id.clone())) .collect(); let ended: Vec = (0..ran.len()).filter(|index| ran[*index].1).collect(); let considered: Vec = ended.iter().rev().take(WINDOW).copied().collect(); @@ -235,7 +268,10 @@ pub fn breaker(mind: &dyn MindPort, item: &PipelineRef, ending: &[PipelineRef]) .collect(); let consecutive = empty.len() >= CONSECUTIVE && empty[..CONSECUTIVE].iter().all(|empty| *empty); let share = empty.iter().filter(|empty| **empty).count() >= EMPTY_SHARE; - Ok(if consecutive || share { Breaker::Trip } else { Breaker::Clear }) + Ok(match ended.last() { + Some(newest) if consecutive || share => Breaker::Trip { run: ran[*newest].2.clone() }, + _ => Breaker::Clear, + }) } #[cfg(test)] @@ -262,7 +298,7 @@ mod tests { fn tripped(runs: &[bool]) -> bool { let (mind, item) = worked(runs); - breaker(&mind, &item, &[]).unwrap() == Breaker::Trip + matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }) } #[test] @@ -307,7 +343,7 @@ mod tests { mind.committed(vec![close(run_ref("third"), recorded())]); breaker(&mind, &item, &[]).unwrap() }; - assert_eq!(after_a_run_by(RunOperator::Mind), Breaker::Trip, "hers, the third empty one"); + assert!(matches!(after_a_run_by(RunOperator::Mind), Breaker::Trip { .. }), "hers, the third empty one"); assert_eq!(after_a_run_by(RunOperator::Operator), Breaker::Clear, "his, counted for nothing"); } @@ -362,7 +398,7 @@ mod tests { ended_run(&mind, &item, "h", n, false); mind.committed(vec![close(run_ref(&format!("p{n}")), recorded())]); } - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip); + assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. })); } #[test] @@ -370,7 +406,7 @@ mod tests { let (mind, item) = worked(&[E, E]); mind.committed(vec![run("dying", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "open, it is not yet ended"); - assert_eq!(breaker(&mind, &item, &[run_ref("dying")]).unwrap(), Breaker::Trip); + assert!(matches!(breaker(&mind, &item, &[run_ref("dying")]).unwrap(), Breaker::Trip { .. })); let instance = Slug(INSTANCE.into()); assert!(queue(&mind, &instance, &[]).unwrap().iter().all(|spec| *spec != item), "it claims the item"); assert!(queue(&mind, &instance, &[run_ref("dying")]).unwrap().contains(&item), "an ending run claims nothing"); @@ -387,7 +423,7 @@ mod tests { assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "the tenth empty run, but nine of them are before the question"); ended_run(&mind, &item, "g", 1, false); ended_run(&mind, &item, "g", 2, false); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip, "three empty runs after it"); + assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }), "three empty runs after it"); } #[test] @@ -403,7 +439,7 @@ mod tests { ended_run(&mind, &item, "h", 2, false); breaker(&mind, &item, &[]).unwrap() }; - assert_eq!(withdrawn_between(false), Breaker::Trip, "the withdrawn run is neither counted nor does it break the streak"); + assert!(matches!(withdrawn_between(false), Breaker::Trip { .. }), "the withdrawn run is neither counted nor does it break the streak"); assert_eq!(withdrawn_between(true), Breaker::Clear, "a document after the withdrawn run still lands in the first run's window"); } @@ -417,7 +453,7 @@ mod tests { let (mind, item) = worked(&[E, E, E]); mind.committed(vec![run("live", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), follow_up("with-next", &item)]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip, "the next run's batch is not the previous run's window"); + assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }), "the next run's batch is not the previous run's window"); } /// The adapter over the wire vocabulary, answered by a real mind. @@ -469,7 +505,7 @@ mod tests { history_as(&mind, &spec_ref("x"), "x", &[E, E]); history_as(&mind, &spec_ref("y"), "y", &[E, E, E]); assert_eq!(breaker(&mind, &spec_ref("x"), &[]).unwrap(), Breaker::Clear); - assert_eq!(breaker(&mind, &spec_ref("y"), &[]).unwrap(), Breaker::Trip); + assert!(matches!(breaker(&mind, &spec_ref("y"), &[]).unwrap(), Breaker::Trip { .. })); } #[test] @@ -502,6 +538,72 @@ mod tests { assert_eq!(queue(&mind, &other, &[]).unwrap().len(), 3, "claims are read for the instance asked"); } + #[test] + fn a_trip_names_the_newest_ended_counted_run() { + let (mind, item) = worked(&[E, E, E, E]); + assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h3") }); + mind.committed(vec![run("live", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); + assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h3") }, "a run still open is not ended"); + assert_eq!(breaker(&mind, &item, &[run_ref("live")]).unwrap(), Breaker::Trip { run: run_ref("live") }, "a run in ending is"); + } + + /// Two items claimed together by every run of a history; the last one ended empty. + fn bundle() -> (TestMind, PipelineRef, PipelineRef) { + let mind = TestMind::seeded(); + mind.committed(vec![spec("a"), spec("b")]); + let (a, b) = (spec_ref("a"), spec_ref("b")); + for n in 0..3 { + mind.committed(vec![run(&format!("f{n}"), RunTurn::SelfRun, RunOperator::Mind, &[a.clone(), b.clone()])]); + mind.committed(vec![close(run_ref(&format!("f{n}")), recorded())]); + } + (mind, a, b) + } + + #[test] + fn a_question_raised_in_a_run_holds_every_claim_of_it_until_answered_or_withdrawn() { + for withdraw in [false, true] { + let (mind, a, b) = bundle(); + assert!(on_hold(&mind).unwrap().is_empty()); + mind.committed(vec![question_in("fork", &run_ref("f2"))]); + let held = on_hold(&mind).unwrap(); + assert!(held.contains(&a) && held.contains(&b) && held.len() == 2, "{held:?}: the claims of the resolved run"); + assert_eq!(queue(&mind, &Slug(INSTANCE.into()), &[]).unwrap(), Vec::::new(), "queue reads the same hold"); + let question = id("question", "fork"); + if withdraw { + mind.committed(vec![close(reference(PipelineKind::Question, &question), withdrawn())]); + } else { + mind.committed(vec![ruling("answer", Some((&question, "A")))]); + } + assert!(on_hold(&mind).unwrap().is_empty(), "answered or withdrawn, nothing is held (withdrawn: {withdraw})"); + } + } + + #[test] + fn a_question_raised_in_anything_else_holds_that_item_alone() { + let (mind, a, b) = bundle(); + mind.committed(vec![question_in("fork", &a)]); + assert_eq!(on_hold(&mind).unwrap(), vec![a], "the legacy shape: raised in the item, it holds the item and no claimant"); + assert!(!on_hold(&mind).unwrap().contains(&b)); + } + + #[test] + fn answering_a_question_in_the_run_gives_every_claim_of_it_a_fresh_count() { + let (mind, a, b) = bundle(); + assert_eq!(breaker(&mind, &a, &[]).unwrap(), Breaker::Trip { run: run_ref("f2") }); + assert_eq!(breaker(&mind, &b, &[]).unwrap(), Breaker::Trip { run: run_ref("f2") }); + mind.committed(vec![question_in("fork", &run_ref("f2"))]); + mind.committed(vec![ruling("answer", Some((&id("question", "fork"), "A")))]); + for item in [&a, &b] { + assert_eq!(breaker(&mind, item, &[]).unwrap(), Breaker::Clear, "counts only runs after f2"); + } + for n in 0..3 { + mind.committed(vec![run(&format!("g{n}"), RunTurn::SelfRun, RunOperator::Mind, &[a.clone(), b.clone()])]); + mind.committed(vec![close(run_ref(&format!("g{n}")), recorded())]); + let expected = if n == 2 { Breaker::Trip { run: run_ref("g2") } } else { Breaker::Clear }; + assert_eq!(breaker(&mind, &b, &[]).unwrap(), expected, "b has no question of its own and trips after three fresh empty runs, never before"); + } + } + /// A daemon that is not there: the failure names no input, endpoint or /// instance. #[test] diff --git a/crates/mind-body/src/self_run/inbox.rs b/crates/mind-body/src/self_run/inbox.rs index 61bad3b..9744502 100644 --- a/crates/mind-body/src/self_run/inbox.rs +++ b/crates/mind-body/src/self_run/inbox.rs @@ -18,7 +18,7 @@ use eureka_pipeline::PipelineKind; use huginn_mind::{PipelineFacts, PipelineStatusSummary}; use crate::persona; -use crate::queue::{MindPort, any_of, headers, in_force, of_kind}; +use crate::queue::{MindPort, any_of, headers, in_force, of_kind, on_hold}; /// The owner a follow-up names when it is a brief for her Self. pub const OWNER: &str = "self-run"; @@ -65,9 +65,19 @@ fn open_briefs(mind: &dyn MindPort) -> Result> { Ok(briefs) } -/// Her briefs in force that the session has not been told. +/// Her briefs in force that the session has not been told and no open question +/// holds: a held brief is neither claimed nor told until its question is +/// answered or withdrawn. pub fn derive(mind: &dyn MindPort, told: &HashSet) -> Result> { - Ok(open_briefs(mind)?.into_iter().filter(|brief| !told.contains(&brief.id)).collect()) + Ok(derive_counting_held(mind, told)?.0) +} + +/// `derive`, and how many of her briefs in force an open question holds. +pub fn derive_counting_held(mind: &dyn MindPort, told: &HashSet) -> Result<(Vec, usize)> { + let holds = on_hold(mind)?; + let (held, free): (Vec, Vec) = + open_briefs(mind)?.into_iter().partition(|brief| holds.iter().any(|item| item.kind == PipelineKind::FollowUp && item.id.0 == brief.id)); + Ok((free.into_iter().filter(|brief| !told.contains(&brief.id)).collect(), held.len())) } /// Her briefs in force that a closed run claimed, with that run's id: a list for diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 02f8d4d..a53aa33 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -114,7 +114,7 @@ mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq mind_body::heartbeat: struct PollTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[at: DateTime < Utc >, tempo_s: u32, instances: Vec < InstanceTrace >, launches: Vec < String >] mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat] mind_body::launch: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Declined { Admission (MindRefusal) , Conflict , AlreadyAdmitted , StartFailed , GrantForOtherInstance , PersonaRunTakesNoClaims , } -mind_body::launch: # [derive (Clone , Debug , PartialEq , Eq)] pub enum LaunchOutcome { Launched { run : PipelineRef , } , NotQueued { item : PipelineRef , } , Tripped { item : PipelineRef , question : PipelineRef , } , Busy { run : PipelineRef , } , Refused (Declined) , } +mind_body::launch: # [derive (Clone , Debug , PartialEq , Eq)] pub enum LaunchOutcome { Launched { run : PipelineRef , } , NotQueued { item : PipelineRef , } , Tripped { run : PipelineRef , question : PipelineRef , } , Busy { run : PipelineRef , } , Refused (Declined) , } mind_body::launch: const START_GRACE_S : i64 mind_body::launch: fn open_and_launch (ports : & Ports , request : LaunchRequest) -> Result < LaunchOutcome > mind_body::launch: fn run_label (now : DateTime < Utc >) -> Label @@ -195,11 +195,12 @@ mind_body::persona: struct StartSelfRun # [derive (Clone , Debug , PartialEq , E mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String] mind_body::persona: struct TurnRequest # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[caller: String, request_id: String, instructions: String, input: String, output_schema_json: String] mind_body::persona: struct TurnTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[run: String, turn: u32, at: DateTime < Utc >, inputs: Vec < TraceItem >, outputs: Vec < TraceItem >, outcome: String] -mind_body::queue: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Breaker { Clear , Trip , } +mind_body::queue: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Breaker { Clear , Trip { run : PipelineRef , } , } mind_body::queue: const CONSECUTIVE : usize mind_body::queue: const EMPTY_SHARE : usize mind_body::queue: const WINDOW : usize mind_body::queue: fn breaker (mind : & dyn MindPort , item : & PipelineRef , ending : & [PipelineRef]) -> Result < Breaker > +mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Vec < PipelineRef > > mind_body::queue: fn queue (mind : & dyn MindPort , instance : & Slug , ending : & [PipelineRef]) -> Result < Vec < PipelineRef > > mind_body::queue: impl HuginnMind < 'static > mind_body::queue: impl HuginnMind < 'static >: fn new (client : HuginnClient) -> Self @@ -259,6 +260,7 @@ mind_body::self_run::decide: impl State mind_body::self_run::inbox: const OWNER : & str mind_body::self_run::inbox: fn backlog (mind : & dyn MindPort) -> Result < Vec < (Brief , String) > > mind_body::self_run::inbox: fn derive (mind : & dyn MindPort , told : & HashSet < String >) -> Result < Vec < Brief > > +mind_body::self_run::inbox: fn derive_counting_held (mind : & dyn MindPort , told : & HashSet < String >) -> Result < (Vec < Brief > , usize) > mind_body::self_run::inbox: fn render (briefs : & [Brief] , plan : & str) -> String mind_body::self_run::inbox: fn resolving_sentence (id : & str) -> String mind_body::self_run::inbox: struct Brief # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[id: String, campaign: String, repo: String, item: String, ordinal: u64] From 345c61eb1bbfff9953c81f2e6b3168b4a9643c57 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:09:49 +0100 Subject: [PATCH 05/19] heartbeat tests: one question per cause, an answer or withdrawal reopens the bundle, a hold reaches only its claims Replaces the Mind-wide fresh-brief-waits test with the scenarios of the run-scoped hold; fail_bundle and beats stay. Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat/tests.rs | 160 +++++++++++++++++++++--- 1 file changed, 144 insertions(+), 16 deletions(-) diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 6950823..a216f6f 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -943,23 +943,151 @@ fn one_cause_failing_a_bundle_of_briefs_is_one_question_not_one_per_brief() { assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "five briefs, one cause, one question on the desk"); assert_eq!(self_runs(&rig, ANN).len(), before, "and no Self run launches while it is open"); assert!(rig.minds[BOB].ids(K::Question).is_empty(), "another Mind is not stopped"); + let question = rig.minds[ANN].ids(K::Question).pop().unwrap(); + assert_eq!(question_raised_in(&rig, &question), Some(reference(K::Run, "ann:run:failed-2")), "raised in the run whose end tripped it, not in a brief"); +} + +/// Five briefs a..e of ann's Self, and the three Self runs that each claimed all of them and ended empty. +fn failed_bundle(rig: &Rig, source: &PipelineRef) -> Vec { + let items: Vec = ["a", "b", "c", "d", "e"].iter().map(|label| brief_ref(label)).collect(); + for label in ["a", "b", "c", "d", "e"] { + brief_by(rig, ANN, crate::persona::AGENT, label, source); + } + fail_bundle(rig, &items); + items +} + +fn brief_ref(label: &str) -> PipelineRef { + reference(K::FollowUp, &format!("eureka-body:follow_up:{label}")) +} + +fn question_raised_in(rig: &Rig, question: &str) -> Option { + let PipelineDocument::Question(asked) = rig.minds[ANN].view(K::Question, question)?.document else { return None }; + asked.raised_in +} + +fn claims_of_run(run: &eureka_pipeline::PipelineRun) -> Vec { + run.claims.iter().map(|claim| claim.id.0.clone()).collect() +} + +/// Beats until `done`, at most `limit`; which beat a Mind wins is not the test's business. +fn beats_until(rig: &Rig, limit: usize, done: impl Fn() -> bool) { + for _ in 0..limit { + if done() { + return; + } + beats(rig, 1); + } +} + +/// Answers a breaker question of ann by a ruling, or closes it Withdrawn. +fn lift(rig: &Rig, question: &str, withdraw: bool) { + let outcome = if withdraw { + close(reference(K::Question, question), crate::testkit::withdrawn()) + } else { + crate::testkit::ruling("answer", Some((question, "reopen"))) + }; + rig.minds[ANN].committed(vec![outcome]); } #[test] -fn a_trip_stops_the_minds_successor_for_a_fresh_brief_too_and_the_answer_resumes_it() { - let (rig, source) = rig_with_a_persona_turn(); - brief_by(&rig, ANN, crate::persona::AGENT, "stuck", &source); - fail_bundle(&rig, &[reference(K::FollowUp, "eureka-body:follow_up:stuck")]); - beats(&rig, 2); - let question = rig.minds[ANN].ids(K::Question).pop().expect("the trip asked"); - let stopped = self_runs(&rig, ANN).len(); - brief_by(&rig, ANN, crate::persona::AGENT, "fresh", &source); - beats(&rig, 4); - assert_eq!(self_runs(&rig, ANN).len(), stopped, "a brief that arrives while the question is open waits for the answer"); - rig.minds[ANN].committed(vec![crate::testkit::ruling("answer", Some((&question, "reopen")))]); - beats(&rig, 1); - let runs = self_runs(&rig, ANN); - assert_eq!(runs.len(), stopped + 1, "answered, the successor launches again"); - let claimed: Vec = runs.last().unwrap().claims.iter().map(|claim| claim.id.0.clone()).collect(); - assert_eq!(claimed.len(), 2, "both briefs, the stuck one reopened: {claimed:?}"); +fn an_answer_or_a_withdrawal_reopens_the_whole_bundle_with_a_fresh_count() { + for withdraw in [false, true] { + let (rig, source) = rig_with_a_persona_turn(); + let items = failed_bundle(&rig, &source); + beats(&rig, 3); + let question = rig.minds[ANN].ids(K::Question).pop().expect("the trip asked"); + assert_eq!(self_runs(&rig, ANN).len(), 3, "the trip launched nothing"); + lift(&rig, &question, withdraw); + // The next Self run claims all five; three empty ones after the boundary trip once more, never before. + beats_until(&rig, 12, || self_runs(&rig, ANN).len() == 4); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), 4, "one Self run after the answer (withdrawn: {withdraw})"); + assert_eq!(claims_of_run(&runs[3]), items.iter().map(|item| item.id.0.clone()).collect::>(), "all five in one run"); + beats_until(&rig, 24, || self_runs(&rig, ANN).len() == 6); + assert_eq!((self_runs(&rig, ANN).len(), rig.minds[ANN].ids(K::Question).len()), (6, 1), "three empty runs since the answer, and no second question yet"); + beats_until(&rig, 24, || rig.minds[ANN].ids(K::Question).len() == 2); + beats(&rig, 6); + assert_eq!((self_runs(&rig, ANN).len(), rig.minds[ANN].ids(K::Question).len()), (6, 2), "the fourth launch trips once more, once, and launches nothing"); + } +} + +#[test] +fn an_open_question_raised_elsewhere_stops_no_brief() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "b1", &source); + brief_by(&rig, ANN, crate::persona::AGENT, "b2", &source); + // A follow-up that is no brief, a cut spec, and a run that claimed only other items. + rig.minds[ANN].committed(vec![crate::testkit::follow_up("plain", &source), crate::testkit::spec("c1")]); + rig.minds[ANN].committed(vec![run_in("ann", "other", RunTurn::SelfRun, RunOperator::Mind, &[crate::testkit::spec_ref("c1")])]); + rig.minds[ANN].committed(vec![close(reference(K::Run, "ann:run:other"), recorded())]); + for (label, place) in [("q1", reference(K::FollowUp, "eureka-body:follow_up:plain")), ("q2", crate::testkit::spec_ref("c1")), ("q3", reference(K::Run, "ann:run:other"))] { + rig.minds[ANN].committed(vec![crate::testkit::question_in(label, &place)]); + } + let before = self_runs(&rig, ANN).len(); + beats_until(&rig, 6, || self_runs(&rig, ANN).len() > before); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), before + 1, "the successor launches as usual"); + assert_eq!(claims_of_run(runs.last().unwrap()), vec![brief_ref("b1").id.0, brief_ref("b2").id.0], "both briefs"); +} + +#[test] +fn a_question_raised_in_one_brief_holds_only_that_brief() { + let (rig, source) = rig_with_a_persona_turn(); + for label in ["b1", "b2", "b3"] { + brief_by(&rig, ANN, crate::persona::AGENT, label, &source); + } + rig.minds[ANN].committed(vec![crate::testkit::question_in("fork", &brief_ref("b2"))]); + let told: Vec = inbox::derive(&rig.minds[ANN], &HashSet::new()).unwrap().into_iter().map(|brief| brief.id).collect(); + assert_eq!(told, vec![brief_ref("b1").id.0, brief_ref("b3").id.0], "derive omits b2"); + beats_until(&rig, 6, || !self_runs(&rig, ANN).is_empty()); + assert_eq!(claims_of_run(&self_runs(&rig, ANN)[0]), vec![brief_ref("b1").id.0, brief_ref("b3").id.0]); +} + +#[test] +fn a_resolved_tripped_brief_drops_out_and_the_question_holds_the_rest_and_nothing_new() { + let (rig, source) = rig_with_a_persona_turn(); + let items = failed_bundle(&rig, &source); + beats(&rig, 3); + assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1); + rig.minds[ANN].committed(vec![close(items[0].clone(), recorded())]); + assert!(inbox::derive(&rig.minds[ANN], &HashSet::new()).unwrap().is_empty(), "the rest stay held and untold"); + for item in &items[1..] { + rig.minds[ANN].committed(vec![close(item.clone(), recorded())]); + } + brief_by(&rig, ANN, crate::persona::AGENT, "new", &source); + beats_until(&rig, 6, || self_runs(&rig, ANN).len() > 3); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), 4, "a new brief launched"); + assert_eq!(claims_of_run(&runs[3]), vec![brief_ref("new").id.0], "no Self run claims any of the five"); + beats(&rig, 6); + assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "the question stays in force and no second is asked"); +} + +#[test] +fn a_brief_admitted_while_a_question_is_open_is_claimed_and_told_alone() { + let (rig, source) = rig_with_a_persona_turn(); + failed_bundle(&rig, &source); + beats(&rig, 3); + brief_by(&rig, ANN, crate::persona::AGENT, "fresh", &source); + let told: Vec = inbox::derive(&rig.minds[ANN], &HashSet::new()).unwrap().into_iter().map(|brief| brief.id).collect(); + assert_eq!(told, vec![brief_ref("fresh").id.0], "the start tell and the mid-session tells read this: none of the held briefs"); + beats_until(&rig, 6, || self_runs(&rig, ANN).len() > 3); + let runs = self_runs(&rig, ANN); + assert_eq!(runs.len(), 4); + assert_eq!(claims_of_run(&runs[3]), vec![brief_ref("fresh").id.0], "claimed alone"); +} + +#[test] +fn a_trip_and_a_wait_say_so_in_the_trace() { + let (rig, source) = rig_with_a_persona_turn(); + failed_bundle(&rig, &source); + let notes = || rig.store.traces.borrow().iter().flat_map(|trace| trace.instances.iter().map(|instance| instance.note.clone())).collect::>(); + beats_until(&rig, 6, || !rig.minds[ANN].ids(K::Question).is_empty()); + let question = rig.minds[ANN].ids(K::Question).pop().unwrap(); + let expected = format!("tripped: {question} holds the 5 claims of ann:run:failed-2"); + assert!(notes().contains(&expected), "{:?}", notes()); + let waiting = "5 briefs held by open questions".to_string(); + beats_until(&rig, 12, || notes().contains(&waiting)); + assert!(notes().contains(&waiting), "{:?}", notes()); } From 801151619805e9694c91e54a33f8d3cd7f7180e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:27:11 +0100 Subject: [PATCH 06/19] launch, heartbeat: fix the trip question's text type and an unused import Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 2 +- crates/mind-body/src/launch.rs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 013d9b2..7b246e0 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -42,7 +42,7 @@ use huginn_mind::{PipelineDocumentSummary, PipelineFacts, PipelinePageItems}; use crate::chat_client::{Chat, ChatDelivery}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, LaunchOutcome, LaunchRequest, Launcher, Ports, holders, open_and_launch}; -use crate::queue::{MindPort, any_of, citing, claims_of, headers, in_force, of_kind}; +use crate::queue::{MindPort, any_of, citing, claims_of, headers, of_kind}; use crate::self_run::inbox; use crate::tempo::{self, Standing}; diff --git a/crates/mind-body/src/launch.rs b/crates/mind-body/src/launch.rs index cd99fc2..6d0618d 100644 --- a/crates/mind-body/src/launch.rs +++ b/crates/mind-body/src/launch.rs @@ -443,7 +443,8 @@ fn breaker_question(claim: &PipelineRef, run: &PipelineRef, held: usize, label: question: format!( "Run {} and the runs before it left nothing that cites the work it held (claims held: {held}), so none of it launches again. Answering or withdrawing this reopens every claim of that run with a fresh count.", run.id.0 - ), + ) + .into(), options: vec![ QuestionOption { label: "reopen".into(), text: "Answer to reopen every claim of the run with a fresh count.".into() }, QuestionOption { label: "retire".into(), text: "Resolve the claims so they are no longer worked, and answer with this option.".into() }, @@ -865,7 +866,7 @@ mod tests { let view = rig.mind.view(K::Question, &question).unwrap(); let PipelineDocument::Question(asked) = &view.document else { panic!("not a question") }; assert_eq!((asked.raised_in.clone(), asked.campaign.0.as_str()), (Some(run_ref("h2")), CAMPAIGN), "raised in the run whose end tripped it"); - assert!(asked.question.contains(&run_ref("h2").id.0) && asked.question.contains("claims held: 1"), "{}", asked.question); + assert!(asked.question.0.contains(&run_ref("h2").id.0) && asked.question.0.contains("claims held: 1"), "{}", asked.question.0); assert_eq!(view.admission.provenance.session.0, "mind-20261009T131500000Z"); // Open, the question blocks the item. assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::NotQueued { item: spec_ref("x") }); From fdf4eb77382f5693b7df5ffe45a708efd293224b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:27:59 +0100 Subject: [PATCH 07/19] launch: build the trip question's text from a &str Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/launch.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/mind-body/src/launch.rs b/crates/mind-body/src/launch.rs index 6d0618d..63a5306 100644 --- a/crates/mind-body/src/launch.rs +++ b/crates/mind-body/src/launch.rs @@ -444,6 +444,7 @@ fn breaker_question(claim: &PipelineRef, run: &PipelineRef, held: usize, label: "Run {} and the runs before it left nothing that cites the work it held (claims held: {held}), so none of it launches again. Answering or withdrawing this reopens every claim of that run with a fresh count.", run.id.0 ) + .as_str() .into(), options: vec![ QuestionOption { label: "reopen".into(), text: "Answer to reopen every claim of the run with a fresh count.".into() }, From 5a6b458c578d33580a6e4ca7352914faf94018a4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:31:43 +0100 Subject: [PATCH 08/19] mind-body: public surface spells the Trip variant as the tool prints it; a new brief's own empty runs are not the five's Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat/tests.rs | 2 +- crates/mind-body/tests/public_surface.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index a216f6f..0145bf7 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -1060,7 +1060,7 @@ fn a_resolved_tripped_brief_drops_out_and_the_question_holds_the_rest_and_nothin let runs = self_runs(&rig, ANN); assert_eq!(runs.len(), 4, "a new brief launched"); assert_eq!(claims_of_run(&runs[3]), vec![brief_ref("new").id.0], "no Self run claims any of the five"); - beats(&rig, 6); + beats(&rig, 2); assert_eq!(rig.minds[ANN].ids(K::Question).len(), 1, "the question stays in force and no second is asked"); } diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index a53aa33..8af9420 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -195,7 +195,7 @@ mind_body::persona: struct StartSelfRun # [derive (Clone , Debug , PartialEq , E mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String] mind_body::persona: struct TurnRequest # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[caller: String, request_id: String, instructions: String, input: String, output_schema_json: String] mind_body::persona: struct TurnTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[run: String, turn: u32, at: DateTime < Utc >, inputs: Vec < TraceItem >, outputs: Vec < TraceItem >, outcome: String] -mind_body::queue: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Breaker { Clear , Trip { run : PipelineRef , } , } +mind_body::queue: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Breaker { Clear , Trip { run : PipelineRef } , } mind_body::queue: const CONSECUTIVE : usize mind_body::queue: const EMPTY_SHARE : usize mind_body::queue: const WINDOW : usize From 9faeb940355d8177afebf8e36d2875ac928cee2d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 02:55:43 +0100 Subject: [PATCH 09/19] queue, heartbeat tests: a question in another item's run is no boundary; no held brief, no held note Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat/tests.rs | 9 +++++++++ crates/mind-body/src/queue.rs | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 0145bf7..5ab34d6 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -1091,3 +1091,12 @@ fn a_trip_and_a_wait_say_so_in_the_trace() { beats_until(&rig, 12, || notes().contains(&waiting)); assert!(notes().contains(&waiting), "{:?}", notes()); } + +#[test] +fn a_beat_with_no_held_brief_writes_no_held_note() { + let (rig, source) = rig_with_a_persona_turn(); + brief_by(&rig, ANN, crate::persona::AGENT, "free", &source); + rig.poll(); + let notes: Vec = rig.store.traces.borrow().iter().flat_map(|trace| trace.instances.iter().map(|instance| instance.note.clone())).collect(); + assert!(notes.iter().all(|note| !note.contains("held")), "{notes:?}"); +} diff --git a/crates/mind-body/src/queue.rs b/crates/mind-body/src/queue.rs index bf6e69f..d68ce30 100644 --- a/crates/mind-body/src/queue.rs +++ b/crates/mind-body/src/queue.rs @@ -604,6 +604,15 @@ mod tests { } } + #[test] + fn a_question_in_a_run_that_did_not_claim_the_item_is_no_boundary() { + let (mind, item) = worked(&[E, E, E]); + mind.committed(vec![spec("y")]); + mind.committed(vec![run("other", RunTurn::SelfRun, RunOperator::Mind, &[spec_ref("y")])]); + mind.committed(vec![question_in("fork", &run_ref("other"))]); + assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h2") }, "the question holds y's run, not x's count"); + } + /// A daemon that is not there: the failure names no input, endpoint or /// instance. #[test] From 3e48e122af8df885e502c15d6e196a83eb586fe1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 1 Nov 2026 04:11:38 +0100 Subject: [PATCH 10/19] hold: one decider of what a question holds, read once per launch; a dead Self holder no longer stalls the successor; retire is read s5 findings of cut-self-session-live: - blocked-recipe-misses-run-held-spec: eureka_state::hold is the one decider (a question holds the item it is raised in, or every claim of the run it is raised in; an answer of retire keeps holding the claims still in force). queue::on_hold and `huginn blocked` both read it. - hold-read-not-one-snapshot: on_hold returns a Held snapshot that the request carries; claimable, queue and the gate read it, none reads it again. - dead-self-holder-stalls-successor: launch::slot is the one reader of whether a holder lives; claimable asks it, a dead holder is closed by the launch and the beat's trace says so. - retire-answer-reopens: launch::retire_answered resolves the claims of an answered-retire question Withdrawn; the beat runs it before reading briefs. - held-note-threshold-unpinned: a test pins the note for exactly one held brief. Co-Authored-By: Claude Sonnet 5.5 --- crates/eureka-state/src/bin/huginn/main.rs | 95 +++++- crates/eureka-state/src/bin/huginn/recipes.rs | 33 +- crates/eureka-state/src/hold.rs | 173 ++++++++++ crates/eureka-state/src/lib.rs | 2 + crates/eureka-state/tests/cli.rs | 147 ++++++++- crates/mind-body/src/control/tests.rs | 2 +- crates/mind-body/src/heartbeat.rs | 135 ++++++-- crates/mind-body/src/heartbeat/tests.rs | 141 +++++++++ crates/mind-body/src/launch.rs | 263 ++++++++++++++-- crates/mind-body/src/persona.rs | 4 +- crates/mind-body/src/persona/tests.rs | 2 +- crates/mind-body/src/queue.rs | 296 +++++++++++++----- crates/mind-body/src/self_run/inbox.rs | 14 +- crates/mind-body/src/testkit.rs | 9 +- 14 files changed, 1142 insertions(+), 174 deletions(-) create mode 100644 crates/eureka-state/src/hold.rs diff --git a/crates/eureka-state/src/bin/huginn/main.rs b/crates/eureka-state/src/bin/huginn/main.rs index 4a5d159..d144797 100644 --- a/crates/eureka-state/src/bin/huginn/main.rs +++ b/crates/eureka-state/src/bin/huginn/main.rs @@ -22,13 +22,17 @@ mod render; mod schema; mod trouble; +use std::cell::{Cell, RefCell}; use std::io::Write; use std::process::ExitCode; use std::sync::OnceLock; use clap::{CommandFactory, FromArgMatches, Parser, Subcommand}; use cultnet_rs::{PROJECTION_DOCUMENT, Selection}; -use huginn_mind::eureka_pipeline::{Line, PipelineDocument, PipelineRef, Short, Slug, pipeline_key}; +use eureka_state::hold; +use huginn_mind::eureka_pipeline::{ + Line, PipelineDocument, PipelineKind, PipelineRef, Short, Slug, pipeline_key, +}; use huginn_mind::{ BATCH_MAX, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome, PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery, @@ -182,7 +186,15 @@ fn run(settings: &Settings, command: Command) -> Result { let semantic = near.map(|text| SemanticQuery { text: Line(text), top_k: top_k.unwrap_or(DEFAULT_TOP_K) }); query(settings, selection, semantic, None, documents) } - Command::Sources { text, repo, top_k, json } => sources(settings, text, repo, top_k, json), + Command::Sources { + text, + repo, + top_k, + json, + } => sources(settings, text, repo, top_k, json), + Command::Recipe(Recipe::Blocked { spec_id, page }) => { + blocked(settings, &spec_id, page.cursor, page.documents) + } Command::Recipe(recipe) => { let ask = recipe.ask()?; query(settings, door::selection_value(&ask.selection)?, ask.semantic, ask.page.cursor, ask.page.documents) @@ -264,9 +276,82 @@ fn query( } } -fn sources(settings: &Settings, text: String, repo: Option, top_k: Option, json: bool) -> Result { - let query = SourceQuery { text: Line(text), top_k: top_k.unwrap_or(DEFAULT_TOP_K), repo: repo.map(Short) }; - match settings.ask(|instance| HuginnMindRequest::SearchSources { instance: instance.clone(), query })? { +/// The open questions that hold a spec, and the answered-`retire` ones whose +/// claims are not yet resolved: `eureka_state::hold`'s answer, the one the +/// heartbeat's gate reads, printed as a selection of those questions. +fn blocked( + settings: &Settings, + spec_id: &str, + cursor: Option, + documents: bool, +) -> Result { + let spec = PipelineRef { + kind: door::kind_of(spec_id)?, + id: Short(spec_id.to_string()), + }; + let failure: RefCell> = RefCell::new(None); + let as_of = Cell::new(0); + let ask = |selection: &Selection| -> anyhow::Result { + let selection = selection.clone(); + match settings.ask(|instance| HuginnMindRequest::Query { + instance: instance.clone(), + selection, + semantic: None, + }) { + Ok(HuginnMindResponse::Query(page)) => { + as_of.set(page.as_of); + Ok(page) + } + Ok(_) => Err(anyhow::anyhow!( + "the mind answered a query with something else" + )), + Err(trouble) => { + *failure.borrow_mut() = Some(trouble); + Err(anyhow::anyhow!("the mind could not be asked")) + } + } + }; + let holding = match hold::holds(&ask) { + Ok(holds) => holds, + Err(error) => { + return Err(failure + .take() + .unwrap_or_else(|| Trouble::Internal(error.to_string()))); + } + }; + let keys: Vec = holding + .iter() + .filter(|held| held.items.contains(&spec)) + .map(|held| held.question.id.id.0.clone()) + .collect(); + if keys.is_empty() { + say(format_args!("matched 0 as_of {} next -", as_of.get())); + return Ok(0); + } + let selection = Selection { + schemas: Some(vec![PipelineKind::Question.type_id().to_string()]), + keys: Some(keys), + ..Selection::default() + }; + query(settings, selection, None, cursor, documents) +} + +fn sources( + settings: &Settings, + text: String, + repo: Option, + top_k: Option, + json: bool, +) -> Result { + let query = SourceQuery { + text: Line(text), + top_k: top_k.unwrap_or(DEFAULT_TOP_K), + repo: repo.map(Short), + }; + match settings.ask(|instance| HuginnMindRequest::SearchSources { + instance: instance.clone(), + query, + })? { HuginnMindResponse::Sources(found) => { if json { say(serde_json::to_string_pretty(&found).map_err(|error| Trouble::Internal(error.to_string()))?); diff --git a/crates/eureka-state/src/bin/huginn/recipes.rs b/crates/eureka-state/src/bin/huginn/recipes.rs index 78bf092..8bcc46e 100644 --- a/crates/eureka-state/src/bin/huginn/recipes.rs +++ b/crates/eureka-state/src/bin/huginn/recipes.rs @@ -1,6 +1,8 @@ //! The campaign progress view as named subcommands. Each recipe is exactly the //! selection `references/campaign-state.md` gives (Eureka 278b881, "Recipes"), //! built per call and never cached. Each one's `--help` prints its selection. +//! The one exception is `blocked`, which asks what a question holds and so +//! reads through `eureka_state::hold`, the decider the heartbeat's gate reads. use clap::{Args, Subcommand}; use huginn_mind::SemanticQuery; @@ -66,7 +68,7 @@ pub enum Recipe { #[command(flatten)] page: Paging, }, - /// Open questions raised in a spec: the spec waits on the operator. + /// Questions that hold a spec, answered-retire ones included: the spec waits on the operator. Blocked { spec_id: String, #[command(flatten)] @@ -125,7 +127,12 @@ impl Recipe { Self::Open { campaigns, page } => (open(&campaigns), None, page), Self::Findings { campaign, blocking, page } => (findings(&campaign, blocking), None, page), Self::Unreported { campaign, page } => (unreported(&campaign), None, page), - Self::Blocked { spec_id, page } => (blocked(&spec_id), None, page), + // Several selections, not one: `main` answers it through `eureka_state::hold`. + Self::Blocked { .. } => { + return Err(Trouble::Internal( + "blocked is answered by the hold, not by one selection".into(), + )); + } Self::Unjudged { campaign, page } => (unjudged(&campaign), None, page), Self::History { id, page } => (history(door::kind_of(&id)?.type_id(), &id), None, page), Self::Cut { campaign, label, page } => (cut(&campaign, &label), None, page), @@ -198,14 +205,6 @@ fn unreported(campaign: &str) -> Value { }) } -fn blocked(spec_id: &str) -> Value { - json!({ - "schemas": [schema(PipelineKind::Question)], - "fields": [in_force()], - "cites": { "target": { "schemaId": schema(PipelineKind::CutSpec), "recordKey": spec_id }, "role": "raised_in" }, - }) -} - fn unjudged(campaign: &str) -> Value { json!({ "schemas": [schema(PipelineKind::CutReport)], @@ -257,6 +256,18 @@ fn gaps() -> Value { }) } +/// `blocked` is not one selection: it reads the in-force questions and, for each, +/// what it holds, by `eureka_state::hold`, the decider the heartbeat's gate reads. +fn blocked_help() -> String { + let questions = json!({ "schemas": [schema(PipelineKind::Question)], "fields": [in_force()] }); + format!( + "selection (first of several): +{} +A question holds the item it is raised in, or every claim of the run it is raised in; one answered `retire` keeps holding the claims still in force. The recipe prints the questions that hold .", + serde_json::to_string_pretty(&questions).unwrap_or_default() + ) +} + /// Each recipe's `--help` addendum: its selection with placeholders in the /// arguments' places. The same builders as execution, so help cannot drift /// from what runs. @@ -276,7 +287,7 @@ pub fn help() -> Vec<(&'static str, String)> { ("open", selection(open(&[c()]))), ("findings", findings_help), ("unreported", selection(unreported(&c()))), - ("blocked", selection(blocked(""))), + ("blocked", blocked_help()), ("unjudged", selection(unjudged(&c()))), ("history", selection(history("epiphany.pipeline..v2", ""))), ("cut", selection(cut(&c(), "