self-session-live: a brief is closed Recorded by the result that answers it; the briefs a closed run claimed are closed at session start
Lands the parked closure (eureka-body/self-session-live-closure-parked 13de7f0) on the Recorded outcome of ruling brief-closure-recorded.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fb0ae7540d
commit
be44185c67
6 changed files with 189 additions and 40 deletions
|
|
@ -17,8 +17,9 @@
|
|||
//! her mind (the `inbox` module): an open follow-up with owner `self-run` is a
|
||||
//! brief not yet answered. The actuator polls for briefs and tells them to the
|
||||
//! session, between tool calls through the PostToolBatch hook and between turns
|
||||
//! as a user line. The session ends where its cache would be evicted, near the
|
||||
//! unit's cap, at the context ceiling, or after the flush each of those asks.
|
||||
//! as a user line; a result closes every brief told to that turn. The session
|
||||
//! ends where its cache would be evicted, near the unit's cap, at the context
|
||||
//! ceiling, or after the flush each of those asks.
|
||||
//!
|
||||
//! Every timing decision is one pure function, `decide` (the `decide` module,
|
||||
//! ruling `eureka-body:ruling:self-run-decider`). `carry` is the loop that turns
|
||||
|
|
@ -36,7 +37,7 @@
|
|||
//! `RuntimeMaxSec` and the context-ceiling flush. The grant carries the plan usage
|
||||
//! windows, which go to the child in its start message.
|
||||
//!
|
||||
//! The actuator admits only closures of Self runs, nothing else. Every exit of
|
||||
//! The actuator admits run closures and brief closures, nothing else. Every exit of
|
||||
//! `carry` that leaves her run open resolves it Recorded exactly once (the
|
||||
//! child's result in the rationale, or that it gave none in the reason). It reads neither the
|
||||
//! brake nor the environment and stops no unit: the gate and the brake hold own those.
|
||||
|
|
@ -126,7 +127,7 @@ const POLL: StdDuration = StdDuration::from_secs(INBOX_POLL_S as u64);
|
|||
/// skill: it names the skill, the instance and the run id.
|
||||
pub fn start_message(instance: &Slug, run: &PipelineRef, plan_quota: &[PlanQuota], now_ms: u64) -> String {
|
||||
format!(
|
||||
"Use the eureka skill. You are Self for the instance `{}`; your run is `{}`. Admit as faculty SelfFaculty, agent {AGENT}.\n\nThis session stays open after you answer: briefs from your Persona arrive while you work and between tasks. Work you take on beyond an answer is a follow-up of your own.\n\n{}",
|
||||
"Use the eureka skill. You are Self for the instance `{}`; your run is `{}`. Admit as faculty SelfFaculty, agent {AGENT}.\n\nThis session stays open after you answer: briefs from your Persona arrive while you work and between tasks, and each answer you give closes the brief it answers. Work you take on beyond an answer is a follow-up of your own.\n\n{}",
|
||||
instance.0,
|
||||
run.id.0,
|
||||
render_plan(plan_quota, now_ms)
|
||||
|
|
@ -394,6 +395,11 @@ impl Heard {
|
|||
}
|
||||
}
|
||||
|
||||
/// The label of a run: the name its closure and its briefs' closures are admitted under.
|
||||
fn session_label(run: &PipelineRef) -> &str {
|
||||
run.id.0.rsplit(':').next().unwrap_or(&run.id.0)
|
||||
}
|
||||
|
||||
fn unix_ms(at: DateTime<Utc>) -> u64 {
|
||||
u64::try_from(at.timestamp_millis()).unwrap_or(0)
|
||||
}
|
||||
|
|
@ -464,7 +470,9 @@ fn withdraw_misconfigured(mind: &dyn MindPort, clock: &dyn Clock, run: &Pipeline
|
|||
pub fn carry(mind: &dyn MindPort, clock: &dyn Clock, lender: &dyn Lender, spawner: &dyn Spawner, run_cap_s: u64, out: &mut dyn Write) -> Result<SelfRunOutcome> {
|
||||
let Some((run, claims)) = her_run(mind)? else { return Ok(SelfRunOutcome::NoRun) };
|
||||
let hooks = spawner.hooks();
|
||||
// The briefs a closed run claimed were answered by that run: closed now, before anything is told.
|
||||
inbox::reset(&hooks.spool)?;
|
||||
inbox::close_past(mind, clock.now(), session_label(&run))?;
|
||||
let mut task = task_section(mind, &claims)?;
|
||||
let open = inbox::derive(mind, &hooks.spool)?;
|
||||
let also: Vec<&Brief> = open.iter().filter(|brief| !claims.iter().any(|claim| claim.id.0 == brief.id)).collect();
|
||||
|
|
@ -555,6 +563,28 @@ fn write_result(line: &str, out: &mut dyn Write) -> std::io::Result<()> {
|
|||
writeln!(out, "{}", describe_result(&event, RESULT_TEXT_LIMIT))
|
||||
}
|
||||
|
||||
/// What a brief's closing resolution says when the result had no text.
|
||||
const NO_ANSWER_TEXT: &str = "The turn ended with no answer text.";
|
||||
|
||||
/// Resolves Recorded every brief told to the session that this result answers.
|
||||
/// A failed close leaves them told: the next result tries again.
|
||||
fn close_told(mind: &dyn MindPort, clock: &dyn Clock, hooks: &Hooks, session: &str, heard: &Heard, out: &mut dyn Write) -> Result<usize> {
|
||||
let rationale = heard.concluded.as_ref().map(|(_, text)| text.as_str()).filter(|text| !text.is_empty()).unwrap_or(NO_ANSWER_TEXT);
|
||||
let closed = inbox::told(&hooks.spool).and_then(|told| {
|
||||
let answered: Vec<(Brief, String)> = told.iter().map(|brief| (brief.clone(), rationale.to_string())).collect();
|
||||
let count = inbox::close(mind, clock.now(), session, &answered, "answered by the turn's result")?;
|
||||
inbox::forget(&hooks.spool, &told);
|
||||
Ok(count)
|
||||
});
|
||||
match closed {
|
||||
Ok(count) => Ok(count),
|
||||
Err(_) => {
|
||||
writeln!(out, "briefs could not be closed: the next result tries again")?;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The loop: facts in, one clock read per fact, actions out.
|
||||
#[allow(clippy::too_many_arguments, reason = "the loop's ports and the run's facts, passed on whole")]
|
||||
fn drive(
|
||||
|
|
@ -572,6 +602,7 @@ fn drive(
|
|||
inbox::write_plan(&hooks.spool, &plan)?;
|
||||
child.write_line(&user_line(&format!("{}{task}", start_message(mind.instance(), run, plan_quota, now_ms))));
|
||||
|
||||
let session = session_label(run);
|
||||
let mut now = clock.now();
|
||||
let mut state = State::started(now, run_cap_s);
|
||||
let mut polled = now;
|
||||
|
|
@ -619,6 +650,7 @@ fn drive(
|
|||
if state.requests != counted {
|
||||
writeln!(out, "request {} prefix {}", state.requests, state.prefix)?;
|
||||
}
|
||||
let mut briefs_closed = 0;
|
||||
match &action {
|
||||
Action::None => {}
|
||||
Action::WriteFlush => child.write_line(&user_line(FLUSH_MESSAGE)),
|
||||
|
|
@ -633,6 +665,7 @@ fn drive(
|
|||
events.push_front(Event::Inbox { pending: false });
|
||||
}
|
||||
},
|
||||
Action::CloseBriefs => briefs_closed = close_told(mind, clock, hooks, session, heard, out)?,
|
||||
Action::CloseStdin => {
|
||||
child.close_input();
|
||||
closed = true;
|
||||
|
|
@ -642,7 +675,7 @@ fn drive(
|
|||
}
|
||||
if !matches!(action, Action::None | Action::Finish(_)) {
|
||||
let idle = idle_s.map_or_else(|| "working".to_string(), |seconds| seconds.to_string());
|
||||
writeln!(out, "decision {action:?} prefix {} ttl_s {ttl_s} idle_s {idle} inbox {inbox}", state.prefix)?;
|
||||
writeln!(out, "decision {action:?} prefix {} ttl_s {ttl_s} idle_s {idle} inbox {inbox} briefs_closed {briefs_closed}", state.prefix)?;
|
||||
}
|
||||
if let Action::Finish(outcome) = action {
|
||||
return Ok(outcome);
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@
|
|||
//! At most one action comes out of an event; a deadline that is already due
|
||||
//! yields its action at the next event, and `next_deadline` says it is now.
|
||||
//!
|
||||
//! A result ends a turn, never the session: it marks the session idle. A brief
|
||||
//! waiting while idle is told.
|
||||
//! A result ends a turn, never the session: it marks the session idle and asks
|
||||
//! for the briefs it answered to be closed. A brief waiting while idle is told.
|
||||
//! The session ends where its cache would be evicted (ruling
|
||||
//! `eureka-body:ruling:live-session-floor-cache-evicts`): at the last request's
|
||||
//! cache TTL less a margin, while no brief waits, the flush is asked, and stdin
|
||||
|
|
@ -61,6 +61,8 @@ pub(super) enum Action {
|
|||
WriteFlush,
|
||||
/// Claim the spool and write its briefs as one user line (the session is idle).
|
||||
WriteTells,
|
||||
/// Resolve the briefs told up to this result.
|
||||
CloseBriefs,
|
||||
CloseStdin,
|
||||
/// To the child's whole process group.
|
||||
Signal(Stop),
|
||||
|
|
@ -229,6 +231,7 @@ pub(super) fn decide(mut state: State, event: Event, now: DateTime<Utc>) -> (Sta
|
|||
if state.flush.as_mut().is_some_and(|flush| !std::mem::replace(&mut flush.turn_begun, true)) {
|
||||
state.busy = true;
|
||||
}
|
||||
action = Action::CloseBriefs;
|
||||
}
|
||||
Event::Inbox { pending } => state.inbox = pending,
|
||||
Event::Told => {
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ fn the_flush_is_asked_once_at_the_ceiling_and_never_after_a_result_or_an_exit_or
|
|||
#[test]
|
||||
fn a_result_ends_a_turn_and_never_closes_the_input_while_a_brief_waits_or_the_cache_is_warm() {
|
||||
// The result asks for its briefs to be closed and nothing else; the next pass has nothing to do.
|
||||
assert_eq!(last(vec![(RESULT, 0)]), Action::None);
|
||||
assert_eq!(last(vec![(RESULT, 0)]), Action::CloseBriefs);
|
||||
assert_eq!(last(vec![(RESULT, 0), (Event::Tick, 0)]), Action::None);
|
||||
assert_eq!(last(vec![(RESULT, 0), (Event::Tick, 3000)]), Action::None);
|
||||
// A waiting brief is told, however long the session has been idle, and the input stays open.
|
||||
|
|
@ -111,7 +111,8 @@ fn the_session_ends_where_the_cache_would_be_evicted_with_a_flush_and_closes_aft
|
|||
let flushed = vec![(RESULT, 0), (Event::Tick, TTL_1H_S - TTL_MARGIN_S)];
|
||||
assert_eq!(last([flushed.clone(), vec![(Event::Tick, TTL_1H_S)]].concat()), Action::None);
|
||||
let ended_turn = [flushed, vec![(SHORT_RESULT, TTL_1H_S)]].concat();
|
||||
assert_eq!(last(ended_turn), Action::CloseStdin);
|
||||
assert_eq!(last(ended_turn.clone()), Action::CloseBriefs);
|
||||
assert_eq!(last([ended_turn, vec![(Event::Tick, TTL_1H_S)]].concat()), Action::CloseStdin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -320,6 +321,7 @@ fn check_step(oracle: &mut Oracle, event: &Event, now: i64, action: &Action) {
|
|||
assert!(!oracle.finished || *action == Action::None, "an action after the run ended: {action:?} on {event:?}");
|
||||
let flush_before = oracle.flush;
|
||||
let was_exited = oracle.exited.is_some();
|
||||
let was_idle = oracle.idle;
|
||||
match event {
|
||||
Event::Request { id, prefix } => {
|
||||
if !oracle.ids.contains(id) {
|
||||
|
|
@ -367,12 +369,13 @@ fn check_step(oracle: &mut Oracle, event: &Event, now: i64, action: &Action) {
|
|||
Action::WriteTells => {
|
||||
assert!(oracle.idle && oracle.inbox && !oracle.closed && !was_exited, "a tell outside idle with a brief waiting");
|
||||
}
|
||||
Action::CloseBriefs => assert!(matches!(event, Event::Result { .. }), "briefs closed on {event:?}"),
|
||||
Action::CloseStdin => {
|
||||
oracle.closes += 1;
|
||||
oracle.closed = true;
|
||||
let flushed = oracle.flush.is_some() && oracle.boundary;
|
||||
let rotation = now >= i64::try_from(CAP_S).unwrap() - ROTATE_MARGIN_S;
|
||||
assert!(oracle.idle && !was_exited && (flushed || rotation), "closed on {event:?} flushed {flushed} rotation {rotation}");
|
||||
assert!(was_idle && !was_exited && (flushed || rotation), "closed on {event:?} idle {was_idle} flushed {flushed} rotation {rotation}");
|
||||
}
|
||||
Action::Signal(how) => {
|
||||
let (flushed_at, _) = flush_before.expect("a signal before the flush was written");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Her Self's inbox: the briefs her Persona has given her Self, derived from the
|
||||
//! mind, spooled for the session, and claimed exactly once.
|
||||
//! mind, spooled for the session, claimed exactly once, and closed by the answer.
|
||||
//!
|
||||
//! The mind owns what her Self is asked: an in-force follow-up with owner
|
||||
//! `self-run` is a brief not yet answered. `derive` lists those that no closed
|
||||
|
|
@ -7,18 +7,23 @@
|
|||
//! `<spool>/<ordinal>-<label>.json`. A claim renames entries into `<spool>/told/`
|
||||
//! and returns them: the rename is the exactly-once point, so the PostToolBatch
|
||||
//! hook (`inject`) and the actuator's idle tell race safely, and `told/` is the
|
||||
//! record of what this session has heard. Everything here is derived or a cache:
|
||||
//! record of what this session has heard. A brief is closed by the result that
|
||||
//! answers it (`close`), and the same rule closes, at session start, the briefs
|
||||
//! a closed run claimed (`close_past`). Everything here is derived or a cache:
|
||||
//! the spool is lost with the unit and rebuilt from the mind.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use eureka_pipeline::PipelineKind;
|
||||
use huginn_mind::{PipelineFacts, PipelineStatusSummary};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::{DateTime, Utc};
|
||||
use eureka_pipeline::{PipelineDocument, PipelineKind, PipelineRef, ResolutionOutcome};
|
||||
use huginn_mind::{PipelineAdmissionOutcome, PipelineFacts, PipelineStatusSummary};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::AGENT;
|
||||
use crate::launch::closure;
|
||||
use crate::queue::{MindPort, any_of, headers, in_force, of_kind};
|
||||
|
||||
/// The owner a follow-up names when it is a brief for her Self.
|
||||
|
|
@ -45,6 +50,10 @@ pub struct Brief {
|
|||
}
|
||||
|
||||
impl Brief {
|
||||
fn follow_up(&self) -> PipelineRef {
|
||||
PipelineRef { kind: PipelineKind::FollowUp, id: self.id.as_str().into() }
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
let label = self.id.rsplit(':').next().unwrap_or(&self.id);
|
||||
format!("{:020}-{label}.json", self.ordinal)
|
||||
|
|
@ -178,6 +187,18 @@ pub fn claim(spool: &Path) -> Result<Vec<Brief>> {
|
|||
Ok(taken)
|
||||
}
|
||||
|
||||
/// The briefs this session has heard and not yet closed.
|
||||
pub fn told(spool: &Path) -> Result<Vec<Brief>> {
|
||||
entries(&spool.join(TOLD))
|
||||
}
|
||||
|
||||
/// Forgets heard briefs once they are closed.
|
||||
pub fn forget(spool: &Path, briefs: &[Brief]) {
|
||||
for brief in briefs {
|
||||
let _ = std::fs::remove_file(spool.join(TOLD).join(brief.file_name()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the spool empty: a session hears only what it is told after it starts.
|
||||
pub fn reset(spool: &Path) -> Result<()> {
|
||||
match std::fs::remove_dir_all(spool) {
|
||||
|
|
@ -200,7 +221,7 @@ pub fn render(briefs: &[Brief], plan: &str) -> String {
|
|||
.iter()
|
||||
.map(|brief| {
|
||||
format!(
|
||||
"A brief from your Persona: follow-up {} (campaign {}, repo {}): {}. Work you take on beyond this answer is a follow-up of your own.",
|
||||
"A brief from your Persona: follow-up {} (campaign {}, repo {}): {}. Your answer closes it; work you take on beyond this answer is a follow-up of your own.",
|
||||
brief.id, brief.campaign, brief.repo, brief.item
|
||||
)
|
||||
})
|
||||
|
|
@ -211,6 +232,39 @@ pub fn render(briefs: &[Brief], plan: &str) -> String {
|
|||
blocks.join("\n\n")
|
||||
}
|
||||
|
||||
/// Resolves Recorded each of `briefs` that is still in force, in one admission:
|
||||
/// a brief her Self resolved herself is left as it is. Returns how many.
|
||||
pub fn close(mind: &dyn MindPort, now: DateTime<Utc>, session: &str, briefs: &[(Brief, String)], reason: &str) -> Result<usize> {
|
||||
let standing: HashSet<String> = headers(mind, &in_force(of_kind(PipelineKind::FollowUp)))?.into_iter().map(|summary| summary.id.id.0).collect();
|
||||
let mut documents: Vec<PipelineDocument> = Vec::new();
|
||||
for (brief, rationale) in briefs.iter().filter(|(brief, _)| standing.contains(&brief.id)) {
|
||||
documents.push(closure(mind, &brief.follow_up(), now, ResolutionOutcome::Recorded { reason: reason.into() }, rationale)?);
|
||||
}
|
||||
let count = documents.len();
|
||||
if count == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
match mind.admit(AGENT, session, documents)? {
|
||||
PipelineAdmissionOutcome::Committed { .. } => Ok(count),
|
||||
_ => Err(anyhow!("the briefs could not be closed")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule applied to the past: every open brief that a closed run claims is
|
||||
/// resolved Recorded, naming that run, whose closure holds the result.
|
||||
pub fn close_past(mind: &dyn MindPort, now: DateTime<Utc>, session: &str) -> Result<usize> {
|
||||
let claimed = claimed_by_closed(mind)?;
|
||||
let answered: Vec<(Brief, String)> = open_briefs(mind)?
|
||||
.into_iter()
|
||||
.filter_map(|brief| {
|
||||
let run = claimed.get(&brief.id)?;
|
||||
let rationale = format!("Claimed by run {run}, which has closed; its closure holds the result.");
|
||||
Some((brief, rationale))
|
||||
})
|
||||
.collect();
|
||||
close(mind, now, session, &answered, "answered by a closed run")
|
||||
}
|
||||
|
||||
/// What a hook prints, and the status it exits with.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Injection {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
//! The inbox over a real spool directory and a mind in memory: what is derived,
|
||||
//! the exactly-once claim, and the hook that prints it.
|
||||
|
||||
use eureka_pipeline::{PipelineDocument, PipelineKind as K, PipelineRef, RunOperator, RunTurn};
|
||||
use eureka_pipeline::{PipelineDocument, PipelineKind as K, RunOperator, RunTurn};
|
||||
|
||||
use super::*;
|
||||
use crate::testkit::{TestMind, close as closing, follow_up, id, recorded, reference, run, run_ref, spec, spec_ref, withdrawn};
|
||||
use crate::testkit::{TestMind, at, close as closing, follow_up, id, recorded, reference, run, run_ref, spec, spec_ref};
|
||||
|
||||
fn spool_dir() -> tempfile::TempDir {
|
||||
tempfile::tempdir().unwrap()
|
||||
|
|
@ -36,7 +36,7 @@ fn entry(n: u64) -> Brief {
|
|||
fn the_inbox_is_the_open_self_run_briefs_that_no_closed_run_claims_and_the_session_does_not_hold() {
|
||||
let mind = mind_with(vec![brief_doc("open", OWNER), brief_doc("claimed-by-old", OWNER), brief_doc("someone-elses", "Hands"), brief_doc("answered", OWNER), brief_doc("held", OWNER)]);
|
||||
mind.committed(vec![run("old", RunTurn::SelfRun, RunOperator::Mind, &[brief_ref("claimed-by-old")])]);
|
||||
mind.committed(vec![closing(run_ref("old"), recorded()), closing(brief_ref("answered"), withdrawn())]);
|
||||
mind.committed(vec![closing(run_ref("old"), recorded()), closing(brief_ref("answered"), recorded())]);
|
||||
let spool = spool_dir();
|
||||
mark_told(spool.path(), &[Brief { id: brief_ref("held").id.0, ..entry(9) }]).unwrap();
|
||||
let derived: Vec<String> = derive(&mind, spool.path()).unwrap().into_iter().map(|brief| brief.id).collect();
|
||||
|
|
@ -54,7 +54,9 @@ fn spooled_entries_are_claimed_in_order_and_hand_back_what_was_written() {
|
|||
let claimed = claim(spool.path()).unwrap();
|
||||
assert_eq!(claimed, vec![entry(1), entry(2)], "oldest first");
|
||||
assert!(!pending(spool.path()).unwrap() && claim(spool.path()).unwrap().is_empty(), "a claim empties the spool");
|
||||
assert_eq!(entries(&spool.path().join("told")).unwrap(), vec![entry(1), entry(2)], "the claimed entries are the session's record");
|
||||
assert_eq!(told(spool.path()).unwrap(), vec![entry(1), entry(2)]);
|
||||
forget(spool.path(), &claimed[..1]);
|
||||
assert_eq!(told(spool.path()).unwrap(), vec![entry(2)]);
|
||||
}
|
||||
|
||||
fn spool_briefs(dir: &Path, briefs: &[Brief]) {
|
||||
|
|
@ -95,7 +97,7 @@ fn the_hook_prints_data_only_and_only_for_the_main_thread() {
|
|||
let output: Value = serde_json::from_str(&printed.stdout).unwrap();
|
||||
assert_eq!(output["hookSpecificOutput"]["hookEventName"], "PostToolBatch");
|
||||
let context = output["hookSpecificOutput"]["additionalContext"].as_str().unwrap();
|
||||
for needle in ["eureka-body:follow_up:b1", "campaign eureka-body", "repo GameCult/Huginn", "Item 1.", "Plan usage: unobserved."] {
|
||||
for needle in ["eureka-body:follow_up:b1", "campaign eureka-body", "repo GameCult/Huginn", "Item 1.", "Your answer closes it", "Plan usage: unobserved."] {
|
||||
assert!(context.contains(needle), "{needle}: {context}");
|
||||
}
|
||||
assert_eq!(inject(spool.path(), "{}", false).unwrap().stdout, "", "claimed once");
|
||||
|
|
@ -123,3 +125,22 @@ fn the_settings_name_the_two_hooks_with_absolute_quoted_commands() {
|
|||
assert_eq!(compact["matcher"], "auto");
|
||||
assert_eq!(compact["hooks"][0]["command"].as_str().unwrap(), format!("{tell} --pre-compact"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_resolves_only_the_briefs_still_in_force_in_one_admission() {
|
||||
let mind = mind_with(vec![brief_doc("a", OWNER), brief_doc("b", OWNER)]);
|
||||
mind.committed(vec![closing(brief_ref("b"), recorded())]);
|
||||
let briefs = [(Brief { id: brief_ref("a").id.0, ..entry(1) }, "The answer.".to_string()), (Brief { id: brief_ref("b").id.0, ..entry(2) }, "Ignored.".to_string())];
|
||||
let now = at(0);
|
||||
assert_eq!(close(&mind, now, "selfrun-a", &briefs, "answered").unwrap(), 1);
|
||||
let rationales: Vec<String> = mind
|
||||
.ids(K::Resolution)
|
||||
.iter()
|
||||
.filter_map(|resolution| match mind.view(K::Resolution, resolution)?.document {
|
||||
PipelineDocument::Resolution(document) if document.subject == brief_ref("a") => Some(document.rationale.0),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(rationales, vec!["The answer.".to_string()]);
|
||||
assert_eq!(close(&mind, now, "selfrun-a", &briefs[..1], "answered").unwrap(), 0, "already closed");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1483,6 +1483,8 @@ fn a_run_without_claims_gets_the_identity_lines_alone() {
|
|||
|
||||
// ---- the live session -----------------------------------------------------
|
||||
|
||||
use eureka_pipeline::PipelineResolution;
|
||||
|
||||
const NO_SIGNALS: &[Stop] = &[];
|
||||
|
||||
fn live_mind() -> Rc<TestMind> {
|
||||
|
|
@ -1509,6 +1511,21 @@ fn admits(mind: &Rc<TestMind>, seconds: i64, documents: Vec<PipelineDocument>) -
|
|||
Step::Do(seconds, Rc::new(move || mind.committed(documents.clone())))
|
||||
}
|
||||
|
||||
fn resolutions_of(mind: &TestMind, subject: &PipelineRef) -> Vec<PipelineResolution> {
|
||||
mind.ids(K::Resolution)
|
||||
.iter()
|
||||
.filter_map(|resolution| match mind.view(K::Resolution, resolution)?.document {
|
||||
PipelineDocument::Resolution(document) if document.subject == *subject => Some(document),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text of the probe's result line: what a brief's closure carries.
|
||||
fn answer_text() -> String {
|
||||
serde_json::from_str::<Value>(&result_line()).unwrap()["result"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn five_minute_request(id: &str, prefix: u64) -> String {
|
||||
let mut event: Value = serde_json::from_str(&at(id, prefix)).unwrap();
|
||||
event["message"]["usage"]["cache_creation"] = json!({"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 100});
|
||||
|
|
@ -1527,7 +1544,7 @@ fn a_result_never_ends_the_session_the_child_ends_it_or_the_cache_does() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn a_brief_to_a_working_self_is_told_once_between_turns() {
|
||||
fn a_brief_to_a_working_self_is_told_once_between_turns_and_closed_by_the_result_that_answers_it() {
|
||||
let mind = live_mind();
|
||||
let steps = vec![
|
||||
Out(at("m1", 10)),
|
||||
|
|
@ -1544,13 +1561,17 @@ fn a_brief_to_a_working_self_is_told_once_between_turns() {
|
|||
let told = tells(&ran);
|
||||
assert_eq!(told.len(), 1, "{:?}", ran.written());
|
||||
assert!(told[0].contains(&brief_ref("b1").id.0) && told[0].contains("Survey the noise functions."), "{}", told[0]);
|
||||
assert!(told[0].contains("Plan usage"), "the plan line ends a tell: {}", told[0]);
|
||||
assert!(told[0].contains("Your answer closes it"), "{}", told[0]);
|
||||
assert_eq!(ran.count(&Event::InputClosed), 0);
|
||||
let closures = resolutions_of(&mind, &brief_ref("b1"));
|
||||
assert_eq!(closures.len(), 1, "closed once");
|
||||
assert!(matches!(closures[0].outcome, ResolutionOutcome::Recorded { .. }));
|
||||
assert_eq!(closures[0].rationale.0, answer_text());
|
||||
assert!(!inbox::pending(&ran.hooks.spool).unwrap(), "nothing left to tell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brief_told_mid_turn_by_the_hook_is_never_told_again_by_the_actuator() {
|
||||
fn a_brief_told_mid_turn_by_the_hook_is_closed_by_that_turns_result_and_never_told_twice() {
|
||||
let mind = live_mind();
|
||||
let hooks = test_hooks();
|
||||
let printed: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
|
||||
|
|
@ -1558,31 +1579,39 @@ fn a_brief_told_mid_turn_by_the_hook_is_never_told_again_by_the_actuator() {
|
|||
let (spool, printed) = (hooks.spool.clone(), printed.clone());
|
||||
Step::Do(0, Rc::new(move || printed.borrow_mut().push(inbox::inject(&spool, "{\"hook_event_name\":\"PostToolBatch\"}", false).unwrap().stdout)))
|
||||
};
|
||||
let steps = vec![Out(at("m1", 10)), admits(&mind, 31, vec![brief("b2", "Wire the shader uniforms.")]), fire.clone(), fire, Out(result_line()), Idle(1), Idle(31)];
|
||||
let steps = vec![Out(at("m1", 10)), admits(&mind, 31, vec![brief("b2", "Wire the shader uniforms.")]), fire.clone(), fire, Out(result_line()), Idle(1)];
|
||||
let ran = carry_hooked(&Seen::of(&mind), steps, (Some(0), None, NO_SIGNALS, false), hooks);
|
||||
let printed = printed.borrow();
|
||||
assert!(printed[0].contains(&brief_ref("b2").id.0) && printed[0].contains("Wire the shader uniforms."), "{printed:?}");
|
||||
assert_eq!(printed[1], "", "the second call finds nothing: each brief enters once");
|
||||
assert_eq!(ran.written().len(), 1, "the hook told it; the actuator wrote nothing but the start: {:?}", ran.written());
|
||||
assert!(tells(&ran).is_empty(), "the hook told it; the actuator did not: {:?}", ran.written());
|
||||
let closures = resolutions_of(&mind, &brief_ref("b2"));
|
||||
assert_eq!((closures.len(), closures[0].rationale.0.as_str()), (1, answer_text().as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brief_the_run_claims_is_told_once_in_the_start_message_and_not_listed_again() {
|
||||
let mind = TestMind::seeded();
|
||||
mind.committed(vec![spec("x")]);
|
||||
mind.committed(vec![brief("c1", "Claimed work."), brief("c2", "Other work.")]);
|
||||
let PipelineDocument::Run(mut document) = self_run("selfrun-a", "5") else { unreachable!() };
|
||||
document.claims = vec![brief_ref("c1")];
|
||||
mind.committed(vec![PipelineDocument::Run(document)]);
|
||||
let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false);
|
||||
let start = &ran.written()[0];
|
||||
assert_eq!(start.matches("Claimed work.").count(), 1, "{start}");
|
||||
let (task, also) = start.split_once("Also open for you").expect("the other brief is listed");
|
||||
assert!(task.contains("Claimed work.") && also.contains("Other work.") && !also.contains("Claimed work."), "{start}");
|
||||
fn a_brief_her_self_resolved_is_not_resolved_again_and_one_not_yet_told_stays_open_past_the_result() {
|
||||
let mind = live_mind();
|
||||
let hooks = test_hooks();
|
||||
let claim_and_resolve = {
|
||||
let (spool, mind) = (hooks.spool.clone(), mind.clone());
|
||||
Step::Do(
|
||||
0,
|
||||
Rc::new(move || {
|
||||
inbox::inject(&spool, "{}", false).unwrap();
|
||||
mind.committed(vec![close(brief_ref("b3"), recorded())]);
|
||||
}),
|
||||
)
|
||||
};
|
||||
let steps = vec![Out(at("m1", 10)), admits(&mind, 31, vec![brief("b3", "Mine.")]), claim_and_resolve, admits(&mind, 31, vec![brief("b4", "Later.")]), Out(result_line())];
|
||||
let ran = carry_hooked(&Seen::of(&mind), steps, (Some(0), None, NO_SIGNALS, false), hooks);
|
||||
assert_eq!(resolutions_of(&mind, &brief_ref("b3")).len(), 1, "her own resolution stands alone");
|
||||
assert!(resolutions_of(&mind, &brief_ref("b4")).is_empty(), "spooled, never told: this result did not answer it");
|
||||
assert!(tells(&ran).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_closed_run_claimed_is_never_told_and_what_nobody_claimed_is() {
|
||||
fn the_past_is_closed_at_session_start_and_only_what_no_closed_run_claimed_is_told() {
|
||||
let mind = TestMind::seeded();
|
||||
mind.committed(vec![spec("x")]);
|
||||
mind.committed(vec![brief("p1", "Stale."), brief("p2", "Still open.")]);
|
||||
|
|
@ -1590,9 +1619,15 @@ fn what_a_closed_run_claimed_is_never_told_and_what_nobody_claimed_is() {
|
|||
mind.committed(vec![close(run_ref("old"), recorded())]);
|
||||
mind.committed(vec![self_run("selfrun-a", "5")]);
|
||||
let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false);
|
||||
let closures = resolutions_of(&mind, &brief_ref("p1"));
|
||||
assert_eq!(closures.len(), 1);
|
||||
assert!(matches!(closures[0].outcome, ResolutionOutcome::Recorded { .. }));
|
||||
assert!(closures[0].rationale.0.contains(&run_ref("old").id.0), "names the run that answered it: {}", closures[0].rationale.0);
|
||||
let start = &ran.written()[0];
|
||||
assert!(start.contains("Also open for you") && start.contains(&brief_ref("p2").id.0) && start.contains("Still open."), "{start}");
|
||||
assert!(!start.contains(&brief_ref("p1").id.0), "never told: {start}");
|
||||
// The unclaimed one was told in the start message, so the first result answers it.
|
||||
assert_eq!(resolutions_of(&mind, &brief_ref("p2")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1603,7 +1638,7 @@ fn the_session_ends_where_the_cache_would_be_evicted_with_a_flush_and_a_waiting_
|
|||
let flush_at = hour.events.iter().position(|event| matches!(event, Event::Wrote(line) if line.contains(FLUSH_MESSAGE))).unwrap();
|
||||
let closed_at = hour.events.iter().position(|event| *event == Event::InputClosed).unwrap();
|
||||
assert!(flush_at < closed_at && hour.count(&Event::InputClosed) == 1, "{:?}", hour.events);
|
||||
assert!(hour.out.contains("decision WriteFlush prefix 10 ttl_s 3600 idle_s 3540 inbox false
|
||||
assert!(hour.out.contains("decision WriteFlush prefix 10 ttl_s 3600 idle_s 3540 inbox false briefs_closed 0
|
||||
"), "{}", hour.out);
|
||||
// Five minutes' cache: the flush at 240 s.
|
||||
let short = go(vec![Out(five_minute_request("m1", 10)), Out(result_line()), Idle(239), Idle(1), Out(result_line()), Idle(1)]);
|
||||
|
|
|
|||
Loading…
Reference in a new issue