wip: live self session

This commit is contained in:
Meta Vens 2026-10-31 14:42:22 +01:00
commit b355bd50d2
8 changed files with 831 additions and 215 deletions

View file

@ -1,3 +1,8 @@
//! `mind-self-run inject --spool <dir> [--pre-compact]` is the hook `claude` runs
//! inside the session: it prints the briefs waiting in the spool as context for
//! the next request, and with `--pre-compact` blocks an auto-compaction (exit 2).
//! It reads the hook's JSON on stdin and the spool, nothing else.
//!
//! `mind-self-run --instance <slug> [--endpoint rudp://<ip>:<port>]`: carries
//! her one open Self run (`mind_body::self_run::carry`) inside
//! `mind-self@<instance>`. This reads the process's arguments and environment,
@ -13,6 +18,8 @@
//! The connector's lease socket is `CLAUDE_LEASE_SOCKET`: the token itself is
//! never in this process's environment, only the descriptor the lease grants.
use std::io::Read;
use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Result, anyhow};
@ -21,6 +28,7 @@ use mind_body::cli::instance_and_endpoint;
use mind_body::launch::SystemClock;
use mind_body::lease_client::{LEASE_SOCKET_VARIABLE, SocketLender};
use mind_body::queue::HuginnMind;
use mind_body::self_run::inbox::inject;
use mind_body::self_run::{ClaudeSpawner, RUN_CAP_VARIABLE, carry};
/// How long one call to the mind may take.
@ -33,6 +41,9 @@ const USAGE: &str = "usage: mind-self-run --instance <slug> [--endpoint rudp://<
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")]
fn run() -> Result<i32> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("inject") {
return hook(&args[1..]);
}
let (instance, address) = instance_and_endpoint(&args, std::env::var("HUGINN_ENDPOINT").ok(), USAGE)?;
let socket = std::env::var_os(LEASE_SOCKET_VARIABLE).ok_or_else(|| anyhow!("{LEASE_SOCKET_VARIABLE} is not set"))?;
let run_cap_s: u64 = std::env::var(RUN_CAP_VARIABLE)
@ -41,11 +52,24 @@ fn run() -> Result<i32> {
.filter(|seconds| *seconds > 0)
.ok_or_else(|| anyhow!("{RUN_CAP_VARIABLE} is not set to the unit's RuntimeMaxSec in seconds"))?;
let mind = HuginnMind::new(HuginnClient::new(address, instance, TIMEOUT));
let outcome = carry(&mind, &SystemClock, &SocketLender::new(socket), &ClaudeSpawner::new(std::env::vars_os())?, run_cap_s, &mut std::io::stdout())?;
let outcome = carry(&mind, &SystemClock, &SocketLender::new(socket), &ClaudeSpawner::new(std::env::vars_os(), std::env::current_exe()?)?, run_cap_s, &mut std::io::stdout())?;
println!("{outcome}");
Ok(outcome.exit_status())
}
/// The hook: the spool named by `--spool`, the hook's input on stdin.
fn hook(args: &[String]) -> Result<i32> {
let spool = args.iter().position(|arg| arg == "--spool").and_then(|at| args.get(at + 1)).map(PathBuf::from).ok_or_else(|| anyhow!("inject needs --spool <dir>"))?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
let injection = inject(&spool, &input, args.iter().any(|arg| arg == "--pre-compact"))?;
if injection.exit == 2 {
eprintln!("compaction blocked: the actuator asks for the flush");
}
print!("{}", injection.stdout);
Ok(injection.exit)
}
fn main() {
match run() {
Ok(status) => std::process::exit(status),

View file

@ -6,13 +6,21 @@
//! stream-json output. It counts the main thread's requests, asks for the flush
//! once when the context prefix reaches the ceiling (ruling
//! `eureka-body:ruling:self-lifecycle-flush-rehydrate`: a Self run admits what
//! the mind lacks and ends, it never summarises), closes the child's input at
//! the first result, and stops a child that outlives its flush: an interrupt
//! the mind lacks and ends, it never summarises), and stops a child that outlives its flush: an interrupt
//! after the grace, or once the requests of the flush's own turn have grown the
//! prefix by the headroom beyond the prefix the flush was asked at (ruling
//! `eureka-body:ruling:flush-always-gets-a-turn`), then SIGTERM and SIGKILL if
//! the child ignores that. Signals go to the child's process group.
//!
//! One run is one live session (ruling `eureka-body:ruling:live-mind-sessions`).
//! A result ends a turn, not the session. What her Self is asked is derived from
//! 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; 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
//! the operating system's facts into events and executes the actions.
@ -29,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.
@ -38,6 +46,7 @@
//! foreign owner's JSON: it is parsed into `serde_json::Value` here and nothing
//! parsed is stored.
use std::collections::VecDeque;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io::{BufRead, BufReader, Write};
@ -47,7 +56,7 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::time::Duration as StdDuration;
use anyhow::{Context, Result, anyhow, bail};
use chrono::{DateTime, Utc};
use chrono::{DateTime, Duration as ChronoDuration, Utc};
use cultnet_rs::Selection;
use eureka_pipeline::{PipelineDocument, PipelineRef, ResolutionOutcome, RunTurn, Slug};
use huginn_mind::{PipelineAdmissionOutcome, PipelinePageItems};
@ -61,6 +70,7 @@ use model_connector::PlanQuota;
use crate::queue::MindPort;
use decide::{Action, Event, State, decide, next_deadline};
use inbox::{Brief, Hooks};
/// The measured Self ceiling: at this prefix the flush is asked for.
pub const CEILING_TOKENS: u64 = 300_000;
@ -74,6 +84,16 @@ pub const ESCALATE_AFTER_S: i64 = 120;
/// How long a stream may stay open after the child has exited (a descendant
/// holding its stdout) before the run is over without it.
pub const EXIT_DRAIN_S: i64 = 2;
/// How long before the unit's cap an idle session is closed for rotation.
pub const ROTATE_MARGIN_S: i64 = 20 * 60;
/// How long before the unit's cap a working session is asked for its flush.
pub const FLUSH_MARGIN_S: i64 = 10 * 60;
/// How often the mind is asked for new briefs.
pub const INBOX_POLL_S: i64 = 30;
/// The prompt cache's lifetimes, and how long before one runs out the session ends.
pub const TTL_1H_S: i64 = 3600;
pub const TTL_5M_S: i64 = 300;
pub const TTL_MARGIN_S: i64 = 60;
/// A backstop `claude` enforces; the ceiling is reached first.
pub const MAX_TURNS: u32 = 500;
/// Names the variable the Self unit sets to its own `RuntimeMaxSec`, in seconds:
@ -101,13 +121,13 @@ pub const AGENT: &str = "mind-self-run";
pub const SESSION_NAMESPACE: Uuid = Uuid::NAMESPACE_OID;
/// The longest the loop waits on the child when no deadline is nearer.
const POLL: StdDuration = StdDuration::from_secs(60);
const POLL: StdDuration = StdDuration::from_secs(INBOX_POLL_S as u64);
/// What the child is told at the start. The contract with the `eureka`
/// 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\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)
@ -160,7 +180,9 @@ pub fn session_id(run: &PipelineRef) -> Uuid {
}
/// The argument list of the child, and nothing else: no resume, continue or
/// fork, no model and no settings of its own belong to this actuator. It fixes
/// fork, no model and no settings of its own belong to this actuator, except the
/// hooks the actuator builds on its own argv (`--settings`, never a file in her
/// sandbox): the tell between tool calls and the block on auto-compaction. It fixes
/// the permission mode: print mode starts in Manual when nothing on the command
/// line sets a mode (the managed `defaultMode` was not applied in print mode,
/// 2026-10-31), and `--permission-prompts none` then denies every tool that
@ -168,7 +190,7 @@ pub fn session_id(run: &PipelineRef) -> Uuid {
/// user's settings load (the fresh configuration directory
/// the seed fills); the working directory's project and local settings, which a
/// run could have written, do not.
pub fn claude_args(session: Uuid) -> Vec<String> {
pub fn claude_args(session: Uuid, hooks: &Hooks) -> Vec<String> {
[
"-p",
"--input-format",
@ -186,6 +208,8 @@ pub fn claude_args(session: Uuid) -> Vec<String> {
"none",
"--setting-sources",
"user",
"--settings",
&hooks.settings(),
]
.map(String::from)
.to_vec()
@ -204,6 +228,18 @@ pub enum Usage {
Unreadable,
}
/// Whether a main-thread request wrote its prompt cache for an hour (the split
/// `cache_creation.ephemeral_1h_input_tokens`), else for five minutes. None for
/// any other line.
pub fn writes_hour_cache(line: &str) -> Option<bool> {
let Ok(Value::Object(event)) = serde_json::from_str::<Value>(line) else { return None };
if event.get("type").and_then(Value::as_str) != Some("assistant") || !event.get("parent_tool_use_id").is_none_or(Value::is_null) {
return None;
}
let hour = event.get("message")?.get("usage")?.get("cache_creation")?.get("ephemeral_1h_input_tokens").and_then(Value::as_u64);
Some(hour.unwrap_or(0) > 0)
}
/// Reads one stream line.
pub fn read_usage(line: &str) -> Usage {
let Ok(Value::Object(event)) = serde_json::from_str::<Value>(line) else { return Usage::Unreadable };
@ -264,6 +300,8 @@ impl Stop {
}
pub trait Spawner {
/// The spool the child's hooks drain and the program they run.
fn hooks(&self) -> Hooks;
/// Starts the child with `token` as its credential descriptor.
fn spawn(&self, args: &[String], token: &TokenFd) -> Result<Box<dyn Child>>;
}
@ -357,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)
}
@ -426,7 +469,23 @@ fn withdraw_misconfigured(mind: &dyn MindPort, clock: &dyn Clock, run: &Pipeline
/// error, and the launch that opens the next run closes the run left open.
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 task = task_section(mind, &claims)?;
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();
if !also.is_empty() {
task.push_str("
Also open for you:");
for brief in also {
task.push_str(&format!("
- follow-up `{}` (campaign `{}`, repo `{}`): {}", brief.id, brief.campaign, brief.repo, brief.item));
}
}
inbox::mark_told(&hooks.spool, &open)?;
let mut heard = Heard::default();
let ran = lend_and_drive(mind, clock, lender, spawner, run_cap_s, out, (&run, &task), &mut heard);
let closed = close_if_open(mind, clock, &run, &ran, &heard);
@ -452,8 +511,9 @@ fn lend_and_drive(mind: &dyn MindPort, clock: &dyn Clock, lender: &dyn Lender, s
}
Lent::Refused(refused) => return close_refused(mind, clock, run, refused.kind),
};
let child = spawner.spawn(&claude_args(session_id(run)), lease.token())?;
drive(mind, clock, child, (run, task), (lease.plan_quota(), started_ms), heard, out)
let hooks = spawner.hooks();
let child = spawner.spawn(&claude_args(session_id(run), &hooks), lease.token())?;
drive(mind, clock, child, &hooks, (run, task), (lease.plan_quota(), started_ms, run_cap_s), heard, out)
}
/// The most of a result's text that reaches the journal.
@ -503,22 +563,65 @@ 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.
fn drive(mind: &dyn MindPort, clock: &dyn Clock, mut child: Box<dyn Child>, (run, task): (&PipelineRef, &str), (plan_quota, now_ms): (&[PlanQuota], u64), heard: &mut Heard, out: &mut dyn Write) -> Result<SelfRunOutcome> {
#[allow(clippy::too_many_arguments, reason = "the loop's ports and the run's facts, passed on whole")]
fn drive(
mind: &dyn MindPort,
clock: &dyn Clock,
mut child: Box<dyn Child>,
hooks: &Hooks,
(run, task): (&PipelineRef, &str),
(plan_quota, now_ms, run_cap_s): (&[PlanQuota], u64, u64),
heard: &mut Heard,
out: &mut dyn Write,
) -> Result<SelfRunOutcome> {
let user_line = |text: &str| json!({"type": "user", "message": {"role": "user", "content": text}}).to_string();
let plan = render_plan(plan_quota, now_ms);
inbox::write_plan(&hooks.spool, &plan)?;
child.write_line(&user_line(&format!("{}{task}", start_message(mind.instance(), run, plan_quota, now_ms))));
let mut state = State::default();
let session = session_label(run);
let mut now = clock.now();
let mut state = State::started(now, run_cap_s);
let mut polled = now;
let mut ttl_1h = false;
let mut closed = false;
loop {
let wait = next_deadline(&state).map_or(POLL, |at| (at - now).to_std().unwrap_or_default().min(POLL));
let poll_due = polled + ChronoDuration::seconds(INBOX_POLL_S);
let wake = next_deadline(&state).into_iter().chain((!closed).then_some(poll_due)).min();
let wait = wake.map_or(POLL, |at| (at - now).to_std().unwrap_or_default().min(POLL));
let fact = match child.next(wait) {
Read::Line(line) => {
heard.hear(&line);
write_result(&line, out)?;
if let Some(hour) = writes_hour_cache(&line) {
ttl_1h = hour;
}
match read_usage(&line) {
Usage::Request { id, prefix } => Event::Request { id, prefix },
Usage::Result => Event::Result,
Usage::Result => Event::Result { ttl_1h },
Usage::Other | Usage::Unreadable => Event::Tick,
}
}
@ -527,20 +630,53 @@ fn drive(mind: &dyn MindPort, clock: &dyn Clock, mut child: Box<dyn Child>, (run
Read::Exited(code) => Event::ChildExited(code),
};
now = clock.now();
let mut event = Some(fact);
while let Some(heard) = event.take() {
let mut events = VecDeque::from([fact]);
if !closed && now >= poll_due {
polled = now;
match inbox::derive(mind, &hooks.spool).and_then(|briefs| inbox::spool(&hooks.spool, &briefs)).and_then(|()| inbox::pending(&hooks.spool)) {
Ok(pending) => events.push_back(Event::Inbox { pending }),
Err(_) => writeln!(out, "inbox poll failed")?,
}
}
if inbox::take_pre_compact(&hooks.spool) {
events.push_back(Event::PreCompact);
}
while let Some(heard_event) = events.pop_front() {
let counted = state.requests;
let (next, action) = decide(state, heard, now);
let (next, action) = decide(state, heard_event, now);
state = next;
if state.requests != counted {
writeln!(out, "request {} prefix {}", state.requests, state.prefix)?;
}
match action {
let mut briefs_closed = 0;
match &action {
Action::None => {}
Action::WriteFlush => child.write_line(&user_line(FLUSH_MESSAGE)),
Action::CloseStdin => child.close_input(),
Action::Signal(how) => event = Some(Event::Signalled { how, delivered: child.stop(how) }),
Action::Finish(outcome) => return Ok(outcome),
Action::WriteTells => match inbox::claim(&hooks.spool) {
Ok(briefs) if !briefs.is_empty() => {
child.write_line(&user_line(&inbox::render(&briefs, &plan)));
events.push_front(Event::Told);
}
Ok(_) => events.push_front(Event::Inbox { pending: false }),
Err(_) => {
writeln!(out, "inbox claim failed")?;
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;
}
Action::Signal(how) => events.push_front(Event::Signalled { how: *how, delivered: child.stop(*how) }),
Action::Finish(_) => {}
}
if !matches!(action, Action::None | Action::Finish(_)) {
let idle = state.idle_s(now).map_or_else(|| "working".to_string(), |seconds| seconds.to_string());
writeln!(out, "decision {action:?} prefix {} ttl_s {} idle_s {idle} inbox {} briefs_closed {briefs_closed}", state.prefix, state.ttl_s, state.inbox)?;
}
if let Action::Finish(outcome) = action {
return Ok(outcome);
}
}
}
@ -555,21 +691,31 @@ pub struct ClaudeSpawner {
unit_environment: Vec<(OsString, OsString)>,
scratch: PathBuf,
seed: Option<PathBuf>,
/// The program the child's hooks run: this actuator's own binary.
injector: PathBuf,
}
impl ClaudeSpawner {
/// From the unit's environment: it must name [`SCRATCH_VARIABLE`], and may name [`SEED_VARIABLE`].
pub fn new(unit_environment: impl IntoIterator<Item = (OsString, OsString)>) -> Result<Self> {
/// `injector` is the absolute path of `mind-self-run`, which the hooks run as `inject`.
pub fn new(unit_environment: impl IntoIterator<Item = (OsString, OsString)>, injector: PathBuf) -> Result<Self> {
let unit_environment: Vec<(OsString, OsString)> = unit_environment.into_iter().collect();
let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value));
// systemd lists several runtime directories colon-separated; the unit names one.
let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?;
let seed = named(SEED_VARIABLE).filter(|path| !path.as_os_str().is_empty());
Ok(Self { unit_environment, scratch, seed })
Ok(Self { unit_environment, scratch, seed, injector })
}
}
/// The directory name of the spool inside the scratch directory.
const SPOOL_DIR_NAME: &str = "inbox";
impl Spawner for ClaudeSpawner {
fn hooks(&self) -> Hooks {
Hooks { spool: self.scratch.join(SPOOL_DIR_NAME), injector: self.injector.clone() }
}
fn spawn(&self, args: &[String], token: &TokenFd) -> Result<Box<dyn Child>> {
let config = FreshConfig::create(&self.scratch, self.seed.as_deref())?;
spawn_program(Path::new("claude"), args, token, &self.unit_environment, config)
@ -778,6 +924,7 @@ impl Child for ClaudeProcess {
}
mod decide;
pub mod inbox;
#[cfg(test)]
mod tests;

View file

@ -1,78 +1,121 @@
//! The Self-run actuator's lifecycle decision, and nothing else.
//!
//! `decide(state, event, now) -> (state, action)` is the one owner of when the
//! flush is asked for, when the stdin closes, when a signal goes out and when
//! the run is over (ruling `eureka-body:ruling:self-run-decider`). It performs
//! no I/O and reads no clock: the loop in `carry` turns operating-system facts
//! into events, reads the clock once per event, and executes the action. A
//! timing rule is pinned here, by tables and by an enumeration of event orders.
//!
//! The flush's turn begins at the first result after the flush was written (the
//! turn already running ends there; the queued flush is the next one). The
//! headroom counts only requests after that boundary, measured from the prefix
//! the flush was written at, and the grace from the flush write (ruling
//! `eureka-body:ruling:flush-always-gets-a-turn`, refined by the decider ruling).
//! At most one action comes out of an event; a deadline that is already due
//! yields its signal at the next event, and `next_deadline` says it is now.
use std::collections::HashSet;
use chrono::{DateTime, Duration, Utc};
use super::{CEILING_TOKENS, Cause, ESCALATE_AFTER_S, EXIT_DRAIN_S, FLUSH_GRACE_S, FLUSH_HEADROOM_TOKENS, SelfRunOutcome, Stop};
/// What the loop saw, already turned into a fact the decision can use.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Event {
/// A request of the main thread: its message id and the context it read.
Request { id: String, prefix: u64 },
Result,
/// `waitpid` returned: the child's exit code, none when a signal ended it.
ChildExited(Option<i32>),
StdoutEof,
/// Time passed, or a line that no rule reads.
Tick,
/// What the operating system said of the signal the last action sent.
Signalled { how: Stop, delivered: bool },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Action {
None,
WriteFlush,
CloseStdin,
/// To the child's whole process group.
Signal(Stop),
Finish(SelfRunOutcome),
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Flush {
/// The prefix at which the flush was written: the headroom's base.
prefix: u64,
written: DateTime<Utc>,
/// A result has come since the write: the flush is the next turn.
turn_begun: bool,
/// A request of the flush's turn reached the headroom.
exhausted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct State {
seen: HashSet<String>,
pub(super) requests: u64,
pub(super) prefix: u64,
result_seen: bool,
flush: Option<Flush>,
/// The last signal attempted and when.
stopping: Option<(Stop, DateTime<Utc>)>,
/// The strongest signal delivered.
delivered: Option<Stop>,
exited: Option<(Option<i32>, DateTime<Utc>)>,
eof: bool,
finished: bool,
}
//! The Self-run actuator's lifecycle decision, and nothing else.
//!
//! `decide(state, event, now) -> (state, action)` is the one owner of when the
//! flush is asked for, when the stdin closes, when a signal goes out and when
//! the run is over (ruling `eureka-body:ruling:self-run-decider`). It performs
//! no I/O and reads no clock: the loop in `carry` turns operating-system facts
//! into events, reads the clock once per event, and executes the action. A
//! timing rule is pinned here, by tables and by an enumeration of event orders.
//!
//! The flush's turn begins at the first result after the flush is written (the
//! turn already running ends there; the queued flush is the next one). The
//! headroom counts only requests after that boundary, measured from the prefix
//! the flush was written at, and the grace from the flush write (ruling
//! `eureka-body:ruling:flush-always-gets-a-turn`, refined by the decider ruling).
//! 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 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
//! closes after the flush's own result. Under the run cap it closes at an idle
//! rotation deadline; the PreCompact hook and the cap's margin ask the same
//! flush the ceiling asks.
use std::collections::HashSet;
use chrono::{DateTime, Duration, Utc};
use super::{
CEILING_TOKENS, Cause, ESCALATE_AFTER_S, EXIT_DRAIN_S, FLUSH_GRACE_S, FLUSH_HEADROOM_TOKENS, FLUSH_MARGIN_S, ROTATE_MARGIN_S, SelfRunOutcome, Stop, TTL_1H_S, TTL_5M_S,
TTL_MARGIN_S,
};
/// What the loop saw, already turned into a fact the decision can use.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Event {
/// A request of the main thread: its message id and the context it read.
Request { id: String, prefix: u64 },
/// A turn ended. `ttl_1h`: the last request wrote its cache for an hour, else for five minutes.
Result { ttl_1h: bool },
/// A poll of the inbox: whether a brief waits in the spool.
Inbox { pending: bool },
/// A user line carrying briefs was written: a turn has begun.
Told,
/// The PreCompact hook blocked an auto-compaction.
PreCompact,
/// `waitpid` returned: the child's exit code, none when a signal ended it.
ChildExited(Option<i32>),
StdoutEof,
/// Time passed, or a line that no rule reads.
Tick,
/// What the operating system said of the signal the last action sent.
Signalled { how: Stop, delivered: bool },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Action {
None,
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),
Finish(SelfRunOutcome),
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Flush {
/// The prefix at which the flush was written: the headroom's base.
prefix: u64,
written: DateTime<Utc>,
/// A result has come since the write: the flush is the next turn.
turn_begun: bool,
/// A request of the flush's turn reached the headroom.
exhausted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct State {
seen: HashSet<String>,
pub(super) requests: u64,
pub(super) prefix: u64,
/// A turn is running or queued: the start message, a tell and the flush begin one; a result ends it.
busy: bool,
last_result_at: Option<DateTime<Utc>>,
/// The cache lifetime the last result left, in seconds.
pub(super) ttl_s: i64,
pub(super) inbox: bool,
/// When the process started and the unit's cap in seconds; none where no cap is known.
cap: Option<(DateTime<Utc>, i64)>,
stdin_closed: bool,
flush: Option<Flush>,
/// The last signal attempted and when.
stopping: Option<(Stop, DateTime<Utc>)>,
/// The strongest signal delivered.
delivered: Option<Stop>,
exited: Option<(Option<i32>, DateTime<Utc>)>,
eof: bool,
finished: bool,
}
impl State {
/// A session whose start message was just written: its first turn is running.
pub(super) fn started(at: DateTime<Utc>, run_cap_s: u64) -> Self {
Self { busy: true, cap: Some((at, i64::try_from(run_cap_s).unwrap_or(i64::MAX))), ..Self::default() }
}
/// Seconds idle since the last result, none while a turn runs.
pub(super) fn idle_s(&self, now: DateTime<Utc>) -> Option<i64> {
(!self.busy).then(|| self.last_result_at.map_or(0, |at| (now - at).num_seconds()))
}
}
fn outcome(state: &State, cause: Cause, code: Option<i32>) -> SelfRunOutcome {
SelfRunOutcome::Ended { cause, code, requests: state.requests, prefix: state.prefix }
}
@ -86,100 +129,173 @@ fn cause(state: &State) -> Cause {
}
}
/// The moment the loop must next be heard at, if any. A moment already past
/// means an action is due now.
pub(super) fn next_deadline(state: &State) -> Option<DateTime<Utc>> {
if state.finished {
return None;
}
if let Some((_, exited)) = state.exited {
return (!state.eof).then(|| exited + Duration::seconds(EXIT_DRAIN_S));
}
match (&state.stopping, &state.flush) {
(Some((_, sent)), _) => Some(*sent + Duration::seconds(ESCALATE_AFTER_S)),
(None, Some(flush)) => Some(flush.written + Duration::seconds(FLUSH_GRACE_S)),
(None, None) => None,
}
}
pub(super) fn decide(mut state: State, event: Event, now: DateTime<Utc>) -> (State, Action) {
if state.finished {
return (state, Action::None);
}
let mut action = Action::None;
match event {
Event::Request { id, prefix } => {
if state.seen.insert(id) {
state.requests += 1;
state.prefix = prefix;
if let Some(flush) = state.flush.as_mut()
&& flush.turn_begun
&& flush.prefix.checked_add(FLUSH_HEADROOM_TOKENS).is_some_and(|limit| prefix >= limit)
{
flush.exhausted = true;
}
if state.flush.is_none() && !state.result_seen && state.exited.is_none() && prefix >= CEILING_TOKENS {
state.flush = Some(Flush { prefix, written: now, turn_begun: false, exhausted: false });
action = Action::WriteFlush;
}
}
}
Event::Result => {
if !state.result_seen {
state.result_seen = true;
if let Some(flush) = state.flush.as_mut() {
flush.turn_begun = true;
}
action = Action::CloseStdin;
}
}
Event::ChildExited(code) => {
state.exited.get_or_insert((code, now));
}
Event::StdoutEof => state.eof = true,
Event::Tick => {}
Event::Signalled { how, delivered } => {
if delivered {
state.delivered = Some(how);
}
}
}
// A child that has exited is never written to or signalled: the run is over
// once its stream has ended, or once the stream has had its drain.
if let Some((code, exited)) = state.exited {
if state.eof || now >= exited + Duration::seconds(EXIT_DRAIN_S) {
state.finished = true;
let outcome = outcome(&state, cause(&state), code);
return (state, Action::Finish(outcome));
}
return (state, Action::None);
}
if action != Action::None {
return (state, action);
}
if let Some((Stop::Kill, sent)) = state.stopping {
// SIGKILL went out and the child still has not been reaped: stop waiting for it.
if now >= sent + Duration::seconds(ESCALATE_AFTER_S) {
state.finished = true;
let cause = if state.delivered == Some(Stop::Kill) { Cause::Signalled(Stop::Kill) } else { Cause::Unstoppable };
let outcome = outcome(&state, cause, None);
return (state, Action::Finish(outcome));
}
return (state, Action::None);
}
let how = match (&state.stopping, &state.flush) {
(Some((last, sent)), _) => (now >= *sent + Duration::seconds(ESCALATE_AFTER_S)).then(|| last.next()),
(None, Some(flush)) => (flush.exhausted || now >= flush.written + Duration::seconds(FLUSH_GRACE_S)).then_some(Stop::Interrupt),
(None, None) => None,
};
match how {
Some(how) => {
state.stopping = Some((how, now));
(state, Action::Signal(how))
}
None => (state, Action::None),
}
}
/// The moment the loop must next be heard at, if any. A moment already past
/// means an action is due now.
pub(super) fn next_deadline(state: &State) -> Option<DateTime<Utc>> {
if state.finished {
return None;
}
if let Some((_, exited)) = state.exited {
return (!state.eof).then(|| exited + Duration::seconds(EXIT_DRAIN_S));
}
let signals = match (&state.stopping, &state.flush) {
(Some((_, sent)), _) => return Some(*sent + Duration::seconds(ESCALATE_AFTER_S)),
(None, Some(flush)) => Some(flush.written + Duration::seconds(FLUSH_GRACE_S)),
(None, None) => None,
};
signals.into_iter().chain(lifecycle_deadline(state)).min()
}
/// The deadline of the next lifecycle action: the flush margin while a turn
/// runs; while idle, now for a pending tell or a finished flush, else the
/// earlier of the rotation and the cache.
fn lifecycle_deadline(state: &State) -> Option<DateTime<Utc>> {
if state.stdin_closed {
return None;
}
let rotation = |margin: i64| state.cap.map(|(started, cap)| started + Duration::seconds(cap - margin));
if state.busy {
return if state.flush.is_none() { rotation(FLUSH_MARGIN_S) } else { None };
}
let last = state.last_result_at?;
if state.flush.as_ref().is_some_and(|flush| flush.turn_begun) || state.inbox {
return Some(last);
}
[rotation(ROTATE_MARGIN_S), Some(last + Duration::seconds(state.ttl_s - TTL_MARGIN_S))].into_iter().flatten().min()
}
/// The flush is asked once, by the ceiling, the PreCompact hook, the cap's
/// margin or the cache's end; never to a child whose input is closed or that has exited.
fn ask_flush(state: &mut State, now: DateTime<Utc>) -> bool {
if state.flush.is_some() || state.stdin_closed || state.exited.is_some() {
return false;
}
// Written while idle, its turn begins at once; written mid-turn, it is the next one.
state.flush = Some(Flush { prefix: state.prefix, written: now, turn_begun: !state.busy, exhausted: false });
state.busy = true;
true
}
/// What the session does next on its own. Mid-turn: the flush at the cap's
/// margin. Idle: close after the flush's own result or at the rotation; tell a
/// waiting brief; ask the flush where the cache would be evicted.
fn lifecycle(state: &mut State, now: DateTime<Utc>) -> Action {
if state.stdin_closed || state.exited.is_some() {
return Action::None;
}
if state.busy {
let due = state.cap.is_some_and(|(started, cap)| now >= started + Duration::seconds(cap - FLUSH_MARGIN_S));
return if due && ask_flush(state, now) { Action::WriteFlush } else { Action::None };
}
let last = state.last_result_at.unwrap_or(now);
let rotate = state.cap.is_some_and(|(started, cap)| now >= started + Duration::seconds(cap - ROTATE_MARGIN_S));
if rotate || state.flush.as_ref().is_some_and(|flush| flush.turn_begun) {
state.stdin_closed = true;
return Action::CloseStdin;
}
if state.inbox {
return Action::WriteTells;
}
if now >= last + Duration::seconds(state.ttl_s - TTL_MARGIN_S) && ask_flush(state, now) {
return Action::WriteFlush;
}
Action::None
}
pub(super) fn decide(mut state: State, event: Event, now: DateTime<Utc>) -> (State, Action) {
if state.finished {
return (state, Action::None);
}
let mut action = Action::None;
match event {
Event::Request { id, prefix } => {
if state.seen.insert(id) {
state.requests += 1;
state.prefix = prefix;
if let Some(flush) = state.flush.as_mut()
&& flush.turn_begun
&& flush.prefix.checked_add(FLUSH_HEADROOM_TOKENS).is_some_and(|limit| prefix >= limit)
{
flush.exhausted = true;
}
if prefix >= CEILING_TOKENS && ask_flush(&mut state, now) {
action = Action::WriteFlush;
}
}
}
Event::Result { ttl_1h } => {
state.busy = false;
state.last_result_at = Some(now);
state.ttl_s = if ttl_1h { TTL_1H_S } else { TTL_5M_S };
// The turn already running ends here; a queued flush is the next one.
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 => {
state.inbox = false;
state.busy = true;
}
Event::PreCompact => {
if ask_flush(&mut state, now) {
action = Action::WriteFlush;
}
}
Event::ChildExited(code) => {
state.exited.get_or_insert((code, now));
}
Event::StdoutEof => state.eof = true,
Event::Tick => {}
Event::Signalled { how, delivered } => {
if delivered {
state.delivered = Some(how);
}
}
}
// A child that has exited is never written to or signalled: the run is over
// once its stream has ended, or once the stream has had its drain.
if let Some((code, exited)) = state.exited {
if state.eof || now >= exited + Duration::seconds(EXIT_DRAIN_S) {
state.finished = true;
let outcome = outcome(&state, cause(&state), code);
return (state, Action::Finish(outcome));
}
return (state, Action::None);
}
if action != Action::None {
return (state, action);
}
if let Some((Stop::Kill, sent)) = state.stopping {
// SIGKILL went out and the child still has not been reaped: stop waiting for it.
if now >= sent + Duration::seconds(ESCALATE_AFTER_S) {
state.finished = true;
let cause = if state.delivered == Some(Stop::Kill) { Cause::Signalled(Stop::Kill) } else { Cause::Unstoppable };
let outcome = outcome(&state, cause, None);
return (state, Action::Finish(outcome));
}
return (state, Action::None);
}
if state.stopping.is_none() {
let next = lifecycle(&mut state, now);
if next != Action::None {
return (state, next);
}
}
let how = match (&state.stopping, &state.flush) {
(Some((last, sent)), _) => (now >= *sent + Duration::seconds(ESCALATE_AFTER_S)).then(|| last.next()),
(None, Some(flush)) => (flush.exhausted || now >= flush.written + Duration::seconds(FLUSH_GRACE_S)).then_some(Stop::Interrupt),
(None, None) => None,
};
match how {
Some(how) => {
state.stopping = Some((how, now));
(state, Action::Signal(how))
}
None => (state, Action::None),
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,305 @@
//! Her Self's inbox: the briefs her Persona has given her Self, derived from the
//! 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
//! run claims and that the session does not hold yet; `spool` writes each as
//! `<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. 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, 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.
pub const OWNER: &str = "self-run";
/// The entries this session has claimed.
const TOLD: &str = "told";
/// The plan line as of the lease grant, which a tell ends with.
const PLAN: &str = "plan.txt";
/// The PreCompact hook's marker: the ceiling is reached by the CLI's own measure.
const PRE_COMPACT: &str = "pre-compact";
/// What the hook event is called when its input does not say.
const DEFAULT_EVENT: &str = "PostToolBatch";
/// One brief from her Persona: a follow-up of the mind, as the session hears it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Brief {
/// The follow-up's full id.
pub id: String,
pub campaign: String,
pub repo: String,
pub item: String,
/// The admission ordinal: the order briefs were given in.
pub ordinal: u64,
}
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)
}
}
/// Where the hooks find the spool and the program they run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hooks {
pub spool: PathBuf,
/// The absolute path of `mind-self-run`.
pub injector: PathBuf,
}
fn quoted(path: &Path) -> String {
format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
}
impl Hooks {
/// The `--settings` JSON: the tell between tool calls, and the block on auto-compaction.
pub fn settings(&self) -> String {
let command = format!("{} inject --spool {}", quoted(&self.injector), quoted(&self.spool));
json!({"hooks": {
"PostToolBatch": [{"hooks": [{"type": "command", "command": command}]}],
"PreCompact": [{"matcher": "auto", "hooks": [{"type": "command", "command": format!("{command} --pre-compact")}]}],
}})
.to_string()
}
}
/// The ids of the follow-ups a closed run claims, with the run each was claimed by.
fn claimed_by_closed(mind: &dyn MindPort) -> Result<HashMap<String, String>> {
let runs = headers(mind, &any_of(of_kind(PipelineKind::Run), "root", &[&mind.instance().0]))?;
let mut claimed = HashMap::new();
for run in runs {
let (PipelineStatusSummary::Resolved { .. }, PipelineFacts::Run { claims, .. }) = (&run.status, &run.facts) else { continue };
for claim in claims.iter().filter(|claim| claim.kind == PipelineKind::FollowUp) {
claimed.insert(claim.id.0.clone(), run.id.id.0.clone());
}
}
Ok(claimed)
}
/// Every in-force follow-up with owner `self-run`, oldest first.
fn open_briefs(mind: &dyn MindPort) -> Result<Vec<Brief>> {
let mut briefs: Vec<Brief> = headers(mind, &in_force(of_kind(PipelineKind::FollowUp)))?
.into_iter()
.filter_map(|summary| match summary.facts {
PipelineFacts::FollowUp { repo, owner, item, .. } if owner.0 == OWNER => {
let campaign = summary.id.id.0.split(':').next().unwrap_or("").to_string();
Some(Brief { id: summary.id.id.0, campaign, repo: repo.0, item: item.0, ordinal: summary.admission.ordinal })
}
_ => None,
})
.collect();
briefs.sort_by_key(|brief| brief.ordinal);
Ok(briefs)
}
/// Her open briefs that no closed run claims and the session does not hold yet.
pub fn derive(mind: &dyn MindPort, spool: &Path) -> Result<Vec<Brief>> {
let held: HashSet<String> = entries(spool)?.into_iter().chain(entries(&spool.join(TOLD))?).map(|brief| brief.id).collect();
let mut open: Vec<Brief> = open_briefs(mind)?.into_iter().filter(|brief| !held.contains(&brief.id)).collect();
if !open.is_empty() {
let claimed = claimed_by_closed(mind)?;
open.retain(|brief| !claimed.contains_key(&brief.id));
}
Ok(open)
}
fn entries(dir: &Path) -> Result<Vec<Brief>> {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error).context("the inbox could not be read"),
};
let mut names: Vec<PathBuf> = read.filter_map(|entry| entry.ok()).filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())).map(|entry| entry.path()).collect();
names.retain(|path| path.extension().is_some_and(|extension| extension == "json") && !path.file_name().is_some_and(|name| name.to_string_lossy().starts_with('.')));
names.sort();
names.iter().filter_map(|path| read_entry(path).transpose()).collect()
}
/// None where another claimer renamed the entry away since it was listed.
fn read_entry(path: &Path) -> Result<Option<Brief>> {
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error).context("an inbox entry could not be read"),
};
serde_json::from_str(&text).map(Some).context("an inbox entry is not a brief")
}
fn write_entry(dir: &Path, brief: &Brief) -> Result<()> {
std::fs::create_dir_all(dir).context("the inbox could not be made")?;
let name = brief.file_name();
// Written under a dot name, then renamed: a claimer never sees half an entry.
let partial = dir.join(format!(".{name}"));
std::fs::write(&partial, serde_json::to_vec(brief)?).context("an inbox entry could not be written")?;
std::fs::rename(&partial, dir.join(name)).context("an inbox entry could not be placed")
}
/// Writes each brief into the spool.
pub fn spool(spool: &Path, briefs: &[Brief]) -> Result<()> {
briefs.iter().try_for_each(|brief| write_entry(spool, brief))
}
/// Records briefs as already heard (the start message carries them).
pub fn mark_told(spool: &Path, briefs: &[Brief]) -> Result<()> {
briefs.iter().try_for_each(|brief| write_entry(&spool.join(TOLD), brief))
}
/// Whether a brief waits in the spool.
pub fn pending(spool: &Path) -> Result<bool> {
Ok(!entries(spool)?.is_empty())
}
/// Takes every waiting entry. A rename into `told/` is the claim: an entry some
/// other claimer renamed first is theirs, and is not returned here.
pub fn claim(spool: &Path) -> Result<Vec<Brief>> {
let told = spool.join(TOLD);
std::fs::create_dir_all(&told).context("the inbox could not be made")?;
let mut taken = Vec::new();
for brief in entries(spool)? {
let name = brief.file_name();
match std::fs::rename(spool.join(&name), told.join(&name)) {
Ok(()) => taken.push(brief),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("an inbox entry could not be claimed"),
}
}
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) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("a stale inbox could not be removed"),
}
std::fs::create_dir_all(spool).context("the inbox could not be made")
}
/// The plan line a tell ends with: as of the lease grant.
pub fn write_plan(spool: &Path, line: &str) -> Result<()> {
std::fs::create_dir_all(spool).context("the inbox could not be made")?;
std::fs::write(spool.join(PLAN), line).context("the plan line could not be written")
}
/// One factual block per brief, then the plan line.
pub fn render(briefs: &[Brief], plan: &str) -> String {
let mut blocks: Vec<String> = briefs
.iter()
.map(|brief| {
format!(
"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
)
})
.collect();
if !plan.is_empty() {
blocks.push(plan.to_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 {
pub stdout: String,
pub exit: i32,
}
/// The hook: data only. It claims the spool and prints what it claimed; with an
/// agent id (a subagent's call) it prints nothing; `pre_compact` writes the
/// marker and exits 2, which blocks the compaction. It reads neither the mind,
/// chat nor the lease, and opens no socket.
pub fn inject(spool: &Path, input: &str, pre_compact: bool) -> Result<Injection> {
if pre_compact {
std::fs::create_dir_all(spool).context("the inbox could not be made")?;
std::fs::write(spool.join(PRE_COMPACT), b"").context("the marker could not be written")?;
return Ok(Injection { stdout: String::new(), exit: 2 });
}
let event: Value = serde_json::from_str(input).unwrap_or(Value::Null);
if event.get("agent_id").is_some_and(|id| !id.is_null()) {
return Ok(Injection { stdout: String::new(), exit: 0 });
}
let briefs = claim(spool)?;
if briefs.is_empty() {
return Ok(Injection { stdout: String::new(), exit: 0 });
}
let plan = std::fs::read_to_string(spool.join(PLAN)).unwrap_or_default();
let name = event.get("hook_event_name").and_then(Value::as_str).unwrap_or(DEFAULT_EVENT);
let stdout = json!({"hookSpecificOutput": {"hookEventName": name, "additionalContext": render(&briefs, &plan)}}).to_string();
Ok(Injection { stdout, exit: 0 })
}
/// Whether the PreCompact hook fired since the last look; the marker is consumed.
pub fn take_pre_compact(spool: &Path) -> bool {
std::fs::remove_file(spool.join(PRE_COMPACT)).is_ok()
}
#[cfg(test)]
mod tests;

View file

@ -181,9 +181,27 @@ struct Fake {
child: RefCell<Option<Scripted>>,
spawns: RefCell<Vec<Vec<String>>>,
refuse: bool,
hooks: Hooks,
}
impl Fake {
fn with(child: Option<Scripted>, refuse: bool) -> Self {
Self { child: RefCell::new(child), spawns: RefCell::new(Vec::new()), refuse, hooks: test_hooks() }
}
}
/// A spool of its own under the system temporary directory, so that tests running side by side share nothing.
fn test_hooks() -> Hooks {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Hooks { spool: std::env::temp_dir().join(format!("mind-self-run-spool-{}-{n}", std::process::id())), injector: PathBuf::from("/opt/mind-self-run") }
}
impl Spawner for Fake {
fn hooks(&self) -> Hooks {
self.hooks.clone()
}
fn spawn(&self, args: &[String], _token: &TokenFd) -> Result<Box<dyn Child>> {
self.spawns.borrow_mut().push(args.to_vec());
if self.refuse {
@ -310,6 +328,7 @@ impl MindPort for Seen<'_> {
}
struct Ran {
hooks: Hooks,
outcome: Result<SelfRunOutcome>,
out: String,
events: Vec<Event>,
@ -370,11 +389,7 @@ fn carry_signalled(seen: &Seen, steps: Vec<Step>, code: Option<i32>, dies_on: Op
fn carry_scripted(seen: &Seen, steps: Vec<Step>, code: Option<i32>, dies_on: Option<Stop>, refuses: &[Stop], hangs: bool) -> Ran {
let log = Rc::new(RefCell::new(Vec::new()));
let clock = Rc::new(Fixed(Cell::new(at_start())));
let fake = Fake {
child: RefCell::new(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code, dies_on, refuses: refuses.to_vec(), hangs, exited: false, eof: false, asked: 0 })),
spawns: RefCell::new(Vec::new()),
refuse: false,
};
let fake = Fake::with(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code, dies_on, refuses: refuses.to_vec(), hangs, exited: false, eof: false, asked: 0 }), false);
let lender = FakeLender::logging(log.clone(), Answer::Grant);
let mut out = Vec::new();
let outcome = carry(seen, &*clock, &lender, &fake, TEST_CAP_S, &mut out);
@ -382,7 +397,7 @@ fn carry_scripted(seen: &Seen, steps: Vec<Step>, code: Option<i32>, dies_on: Opt
// The child's own events; the lease's are in `all`, in order with them.
let events = all.iter().filter(|event| !matches!(event, Event::Lent | Event::Spawned | Event::Abandoned)).cloned().collect();
let spawns = fake.spawns.borrow().clone();
Ran { outcome, out: String::from_utf8(out).unwrap(), events, all, spawns, admits: seen.admits.get(), asked: lender.asked.borrow().clone() }
Ran { hooks: fake.hooks(), outcome, out: String::from_utf8(out).unwrap(), events, all, spawns, admits: seen.admits.get(), asked: lender.asked.borrow().clone() }
}
fn at_start() -> chrono::DateTime<chrono::Utc> {
@ -449,7 +464,7 @@ fn without_exactly_one_open_self_run_of_hers_it_is_no_run_and_no_child_is_spawne
fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_outcome() {
let mind = with_run();
let clock = Rc::new(Fixed(Cell::new(at_start())));
let refusing = Fake { child: RefCell::new(None), spawns: RefCell::new(Vec::new()), refuse: true };
let refusing = Fake::with(RefCell::new(None), true);
assert!(carry(&Seen::of(&mind), &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).is_err());
assert_eq!(refusing.spawns.borrow().len(), 1, "it tried exactly once");
@ -466,7 +481,7 @@ fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_ou
unreachable!()
}
}
let never = Fake { child: RefCell::new(None), spawns: RefCell::new(Vec::new()), refuse: false };
let never = Fake::with(RefCell::new(None), false);
assert!(carry(&Down, &*clock, &FakeLender::new(Answer::Grant), &never, TEST_CAP_S, &mut Vec::new()).is_err());
assert!(never.spawns.borrow().is_empty());
}
@ -476,7 +491,8 @@ fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_ou
#[test]
fn claude_args_is_exactly_the_fixed_list_for_a_session() {
let session = Uuid::parse_str(SESSION_OF_RUN_A).unwrap();
let args = claude_args(session);
let hooks = test_hooks();
let args = claude_args(session, &hooks);
assert_eq!(
args,
[
@ -496,6 +512,8 @@ fn claude_args_is_exactly_the_fixed_list_for_a_session() {
"none",
"--setting-sources",
"user",
"--settings",
hooks.settings().as_str(),
]
);
// Those belong to the run measure or to the unit's managed settings.
@ -523,7 +541,7 @@ fn the_child_is_started_for_her_run_with_the_fixed_list_whatever_the_run_record_
mind.committed(vec![self_run("selfrun-b", budget)]);
let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false);
assert_eq!(ran.spawns.len(), 1, "{budget}");
assert_eq!(ran.spawns[0], claude_args(Uuid::parse_str(SESSION_OF_RUN_B).unwrap()), "{budget}");
assert_eq!(ran.spawns[0], claude_args(Uuid::parse_str(SESSION_OF_RUN_B).unwrap(), &ran.hooks), "{budget}");
}
}
@ -980,7 +998,7 @@ fn the_clock_is_read_once_per_event_so_a_step_of_the_wall_clock_cannot_split_a_p
}
let steps: VecDeque<Step> = vec![Out(at("m1", CEILING_TOKENS)), Out(at("m2", CEILING_TOKENS + 1)), Idle(0)].into();
let child = Scripted { steps, log: log.clone(), clock: Rc::new(Fixed(Cell::new(at_start()))), code: Some(0), dies_on: None, refuses: vec![], hangs: false, exited: false, eof: false, asked: 0 };
let fake = Fake { child: RefCell::new(Some(child)), spawns: RefCell::new(Vec::new()), refuse: false };
let fake = Fake::with(RefCell::new(Some(child)), false);
let outcome = carry(&Seen::of(&mind), &Stepped(clock.clone()), &FakeLender::new(Answer::Grant), &fake, TEST_CAP_S, &mut Vec::new()).unwrap();
let events = log.borrow().clone();
let reads = events.iter().filter(|event| matches!(event, Event::Asked(_))).count() as u32;
@ -1203,6 +1221,9 @@ mod process {
struct Spawn(PathBuf);
impl Spawner for Spawn {
fn hooks(&self) -> Hooks {
test_hooks()
}
fn spawn(&self, args: &[String], token: &TokenFd) -> Result<Box<dyn Child>> {
Ok(Box::new(Prompt(start_with(&self.0, args, token))))
}
@ -1229,6 +1250,9 @@ mod process {
struct Patient(PathBuf);
impl Spawner for Patient {
fn hooks(&self) -> Hooks {
test_hooks()
}
fn spawn(&self, args: &[String], token: &TokenFd) -> Result<Box<dyn Child>> {
Ok(Box::new(Bounded(start_with(&self.0, args, token), std::time::Instant::now())))
}

View file

@ -84,7 +84,7 @@ fn a_child_stopped_by_the_actuator_resolves_the_run_with_how_it_ended() {
fn a_child_that_cannot_start_resolves_the_run_and_the_error_stands() {
let mind = with_run();
let clock = Rc::new(Fixed(Cell::new(at_start())));
let refusing = Fake { child: RefCell::new(None), spawns: RefCell::new(Vec::new()), refuse: true };
let refusing = Fake::with(RefCell::new(None), true);
let error = carry(&Seen::of(&mind), &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).unwrap_err();
assert_eq!(error.to_string(), "refused");
assert!(reason_of(&mind, "selfrun-a").contains("the actuator failed"));
@ -105,7 +105,7 @@ fn an_error_after_the_run_opened_resolves_it() {
let log = Rc::new(RefCell::new(Vec::new()));
let clock = Rc::new(Fixed(Cell::new(at_start())));
let child = Scripted { steps: vec![Out(at("m1", 10))].into(), log: log.clone(), clock: clock.clone(), code: Some(0), dies_on: None, refuses: vec![], hangs: true, exited: false, eof: false, asked: 0 };
let fake = Fake { child: RefCell::new(Some(child)), spawns: RefCell::new(Vec::new()), refuse: false };
let fake = Fake::with(RefCell::new(Some(child)), false);
assert!(carry(&Seen::of(&mind), &*clock, &FakeLender::logging(log, Answer::Grant), &fake, TEST_CAP_S, &mut Broken).is_err());
assert!(reason_of(&mind, "selfrun-a").contains("the actuator failed"));
}
@ -133,7 +133,7 @@ fn a_resolve_that_fails_is_logged_and_tried_once() {
// The same when the run's own error is what is being reported: that error stands.
let clock = Rc::new(Fixed(Cell::new(at_start())));
let refusing = Fake { child: RefCell::new(None), spawns: RefCell::new(Vec::new()), refuse: true };
let refusing = Fake::with(RefCell::new(None), true);
let again = Seen { admit_fails: true, ..Seen::of(&mind) };
let error = carry(&again, &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).unwrap_err();
assert_eq!(error.to_string(), "refused");

View file

@ -7,7 +7,7 @@ use eureka_pipeline::ResolutionOutcome;
use super::*;
fn never_spawns() -> Fake {
Fake { child: RefCell::new(None), spawns: RefCell::new(Vec::new()), refuse: false }
Fake::with(RefCell::new(None), false)
}
#[test]

View file

@ -26,7 +26,7 @@ fn granted_fd_reaches_child_env_var() {
let dir = tempfile::tempdir().unwrap();
let program = script(&dir, READS_ITS_CREDENTIAL);
let token = token_holding("tok-canary-7f3a");
let mut child = start_with(&program, &claude_args(session_id(&run_ref("selfrun-a"))), &token);
let mut child = start_with(&program, &claude_args(session_id(&run_ref("selfrun-a")), &Hooks { spool: PathBuf::from("/run/spool"), injector: PathBuf::from("/bin/x") }), &token);
child.close_input();
let (lines, code) = drain(&mut *child);
assert_eq!(code, Some(0), "{lines:?}");
@ -128,11 +128,11 @@ fn each_run_gets_a_fresh_owner_only_configuration_that_what_it_writes_does_not_o
#[test]
fn the_spawner_needs_the_units_runtime_directory_and_reads_the_seed_from_the_units_environment() {
assert!(ClaudeSpawner::new(Vec::new()).is_err(), "no scratch directory named");
assert!(ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "".into())]).is_err(), "an empty one is none");
let named = ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "/run/mind".into()), ("MIND_SELF_CONFIG_SEED".into(), "/etc/seed".into())]).unwrap();
assert!(ClaudeSpawner::new(Vec::new(), PathBuf::from("/bin/x")).is_err(), "no scratch directory named");
assert!(ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "".into())], PathBuf::from("/bin/x")).is_err(), "an empty one is none");
let named = ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "/run/mind".into()), ("MIND_SELF_CONFIG_SEED".into(), "/etc/seed".into())], PathBuf::from("/bin/x")).unwrap();
assert_eq!((named.scratch.as_path(), named.seed.as_deref()), (Path::new("/run/mind"), Some(Path::new("/etc/seed"))));
let bare = ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "/run/mind".into())]).unwrap();
let bare = ClaudeSpawner::new([("RUNTIME_DIRECTORY".into(), "/run/mind".into())], PathBuf::from("/bin/x")).unwrap();
assert_eq!(bare.seed, None);
}