Skip to main content

agentmux_srv_core/backend/blockcontroller/
health.rs

1// Copyright 2025, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-block turn-activity tracking (is a turn currently in flight, and
5//! the last process exit code). Previously part of a larger "agent health"
6//! detector that also did silence-based unresponsive detection; that
7//! detection logic was removed (see
8//! docs/specs/SPEC_REMOVE_AGENT_UNRESPONSIVE_DETECTION_2026_08_25.md) —
9//! this struct keeps only the turn-active bookkeeping, which several other
10//! subsystems depend on independently of the removed detector
11//! (`broker::process::lifecycle_from`, the Swarm pane's running/idle
12//! badge, subagent-watcher reconciliation, `muxspect describe`).
13//!
14//! It also keeps the **turn ledger**: the turn as the user sees it, which
15//! can span several CLI passes (`TurnLedger`,
16//! docs/specs/SPEC_AGENT_TURN_MODEL_AND_LIVE_STATUS_2026_10_08.md §3, §4.3).
17//! `active_turn` stays per pass; the ledger is display data on top of it.
18
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::{Arc, Mutex};
21
22use crate::backend::message_origin::MessageOrigin;
23
24/// Who delivered input to an agent (SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.3).
25#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
26#[ts(export, export_to = "../../../frontend/types/rpc/")]
27#[serde(rename_all = "snake_case")]
28pub enum TurnOrigin {
29    /// The human typing in the agent's own pane.
30    User,
31    /// A jekt, cron, nudge, broadcast, loop, another agent — any automated sender.
32    Automated,
33    /// srv or the frontend on its own behalf: hidden memory reinjection, a
34    /// side question.
35    System,
36}
37
38
39
40/// One input, as told to the tracker by the path that delivers it.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct TurnInput {
43    /// Where the message came from, as the producer set it (`message_origin`): the security class and
44    /// the kind are both read from it, never from the text.
45    pub from: MessageOrigin,
46    /// The message text (kept only for `User`, for the §6.3 quote check).
47    pub text: String,
48    /// The pane flushing a message it held while this turn ran: the turn's
49    /// id, so the message joins that turn instead of starting a new one
50    /// (turn-model spec §4.3, J3). Display only; provenance ignores it.
51    pub joins_turn: Option<u64>,
52}
53
54impl TurnInput {
55    /// The security class of the turn this input starts.
56    pub fn origin(&self) -> TurnOrigin {
57        self.from.turn_origin()
58    }
59}
60
61/// How long after a pass ends a turn that expects more (input arrived
62/// during the pass, or the CLI has a task notification queued) waits for its
63/// next pass before it counts as over (turn-model spec §4.3, J4). The CLI
64/// starts that pass within milliseconds; this is margin.
65pub const TURN_SETTLE_MS: u64 = 2_000;
66
67/// How long after a turn ended the pane's flush of a message it held during
68/// that turn still joins it (§4.3, J3). The flush follows the idle push at
69/// once; this covers a slow round trip.
70pub const HELD_FLUSH_JOIN_MS: u64 = 10_000;
71
72/// At most this many inputs are listed on a turn (`TurnLedger::absorbed`);
73/// `inputs` keeps counting past it.
74pub const ABSORBED_CAP: usize = 20;
75
76/// What kind of thing started, or joined, a turn (turn-model spec §5.2).
77/// Display data next to [`TurnOrigin`], which stays the security class.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
79#[ts(export, export_to = "../../../frontend/types/rpc/")]
80#[serde(rename_all = "snake_case")]
81pub enum TriggerKind {
82    /// The human, in this pane.
83    User,
84    /// The human, by Swarm broadcast.
85    Broadcast,
86    /// A jekt from another agent.
87    Agent,
88    /// A jekt from a service (`*-consumer`: GitHub review notices, …).
89    Service,
90    /// A scheduled delivery (cron, a loop).
91    Schedule,
92    /// The CLI woke for a background task it had started.
93    Task,
94    /// The Swarm Supervisor continued the agent
95    /// (SPEC_SWARM_SUPERVISOR_2026_10_16.md §3.5).
96    Supervisor,
97    /// AgentMux on its own behalf (memory reinjection, a side question).
98    System,
99}
100
101impl TriggerKind {
102    /// Started by something other than the user: another agent, a service, a
103    /// schedule, a background task, the Supervisor (spec §5.2). The one place
104    /// this is decided: srv publishes it on every trigger
105    /// (`TurnTrigger::external`) and the pane and the notification router read
106    /// that.
107    pub fn is_external(self) -> bool {
108        matches!(
109            self,
110            TriggerKind::Agent | TriggerKind::Service | TriggerKind::Schedule | TriggerKind::Task | TriggerKind::Supervisor
111        )
112    }
113}
114
115/// What started, or joined, a turn: its kind, and who or what, for display.
116/// Built by srv from what it wrote itself (the jekt marker it composed, the
117/// CLI's task notification), never from message body text.
118#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
119#[ts(export, export_to = "../../../frontend/types/rpc/")]
120pub struct TurnTrigger {
121    pub kind: TriggerKind,
122    /// The sender (a jekt's `FROM`), or the task's summary. Absent for the user.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    #[ts(optional)]
125    pub from: Option<String>,
126    /// `kind.is_external()`, carried so readers don't keep their own list.
127    #[serde(default)]
128    pub external: bool,
129}
130
131impl TurnTrigger {
132    fn of(kind: TriggerKind, from: Option<&str>) -> Self {
133        TurnTrigger { kind, from: from.map(str::to_string), external: kind.is_external() }
134    }
135
136    /// The trigger of a message from `from`, as the producer set it. Nothing here reads the text: a
137    /// body can't change what started the turn.
138    pub fn from_message(from: &MessageOrigin) -> Self {
139        Self::of(from.kind, from.from.as_deref().filter(|_| from.kind != TriggerKind::User))
140    }
141
142    /// The trigger of a turn whose only known fact is its security class (a queued pass that carries
143    /// no input of its own).
144    pub fn from_turn_origin(origin: TurnOrigin) -> Self {
145        match origin {
146            TurnOrigin::User => Self::of(TriggerKind::User, None),
147            TurnOrigin::System => Self::of(TriggerKind::System, None),
148            TurnOrigin::Automated => Self::of(TriggerKind::Agent, None),
149        }
150    }
151
152    /// The CLI woke for a finished background task; `summary` is the
153    /// notification's own (`Background command "…" completed (exit code 0)`).
154    pub fn task(summary: Option<&str>) -> Self {
155        let summary = summary.map(str::trim).filter(|s| !s.is_empty()).map(|s| {
156            if s.chars().count() > 160 {
157                format!("{}…", s.chars().take(159).collect::<String>())
158            } else {
159                s.to_string()
160            }
161        });
162        TurnTrigger { kind: TriggerKind::Task, from: summary, external: TriggerKind::Task.is_external() }
163    }
164}
165
166/// Why a turn ended.
167#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
168#[ts(export, export_to = "../../../frontend/types/rpc/")]
169#[serde(rename_all = "snake_case")]
170pub enum TurnEnd {
171    /// Its last pass finished and nothing joined it.
172    Completed,
173    /// The agent's process exited.
174    Exited,
175}
176
177/// The turn as the user sees it: from leaving idle to returning to it with
178/// nothing queued, over however many CLI passes that took (turn-model spec
179/// §3.1, §4.3). Published as `agentturn` on every change; the pane's parser is
180/// typed against the generated `frontend/types/rpc/TurnLedger.ts`.
181#[derive(Clone, Debug, PartialEq, serde::Serialize, ts_rs::TS)]
182#[ts(export, export_to = "../../../frontend/types/rpc/")]
183pub struct TurnLedger {
184    /// Unique per block: the start time in ms, bumped past the previous id.
185    #[ts(type = "number")]
186    pub turn_id: u64,
187    /// Bumped on every change, under the tracker's lock. Publishes run after
188    /// the lock is released, so two can land out of order; the pane keeps the
189    /// highest `seq` (#4492).
190    #[ts(type = "number")]
191    pub seq: u64,
192    /// What started the turn; `None` when its first pass was unlabelled.
193    #[serde(skip_serializing_if = "Option::is_none")]
194    #[ts(optional)]
195    pub origin: Option<TurnOrigin>,
196    /// The same, for display: what kind of thing, and who.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    #[ts(optional)]
199    pub trigger: Option<TurnTrigger>,
200    /// The labelled inputs that arrived after the turn started, in order,
201    /// up to [`ABSORBED_CAP`].
202    #[serde(skip_serializing_if = "Vec::is_empty")]
203    #[ts(optional, as = "Option<Vec<TurnTrigger>>")]
204    pub absorbed: Vec<TurnTrigger>,
205    #[ts(type = "number")]
206    pub started_at_ms: u64,
207    /// CLI passes so far, the running one included.
208    pub passes: u32,
209    /// A pass is running now.
210    pub active: bool,
211    /// Inputs that arrived after the turn started (mid-pass, or starting a
212    /// pass that joined).
213    pub inputs: u32,
214    /// Passes whose `result` figures are in the sums below. The pane adds
215    /// its live count for the running pass only while that pass isn't
216    /// counted yet, so a pass is never counted twice.
217    pub counted_passes: u32,
218    /// Summed over the counted passes' `result` frames.
219    #[ts(type = "number")]
220    pub output_tokens: u64,
221    pub cost_usd: f64,
222    /// Model calls (`result.num_turns`, which counts steps, not turns).
223    pub steps: u32,
224    #[ts(type = "number")]
225    pub duration_api_ms: u64,
226    #[serde(skip_serializing_if = "Option::is_none")]
227    #[ts(optional, type = "number")]
228    pub last_pass_ended_at_ms: Option<u64>,
229    /// Between passes, while a next pass is expected: the turn is over if
230    /// none starts by then.
231    #[serde(skip_serializing_if = "Option::is_none")]
232    #[ts(optional, type = "number")]
233    pub settle_until_ms: Option<u64>,
234    #[serde(skip_serializing_if = "Option::is_none")]
235    #[ts(optional, type = "number")]
236    pub ended_at_ms: Option<u64>,
237    #[serde(skip_serializing_if = "Option::is_none")]
238    #[ts(optional)]
239    pub end: Option<TurnEnd>,
240}
241
242impl TurnActivityTrackerInner {
243    /// What a pass cost, given the `total_cost_usd` its `result` reported: the rise over the last
244    /// total. A total below the last is a new process (a restart resumes at zero), so it is all
245    /// this pass's.
246    fn pass_cost(&mut self, total: f64) -> f64 {
247        let cost = if total >= self.session_cost_usd { total - self.session_cost_usd } else { total };
248        self.session_cost_usd = total;
249        cost
250    }
251}
252
253impl TurnLedger {
254    fn absorb(&mut self, trigger: Option<TurnTrigger>) {
255        if let Some(t) = trigger.filter(|_| self.absorbed.len() < ABSORBED_CAP) {
256            self.absorbed.push(t);
257        }
258    }
259
260    fn add_stats(&mut self, stats: PassStats) {
261        self.counted_passes += 1;
262        self.output_tokens += stats.output_tokens;
263        self.cost_usd += stats.cost_usd;
264        self.steps += stats.steps;
265        self.duration_api_ms += stats.duration_api_ms;
266    }
267
268    /// Whether a pass starting at `now` may still join this turn as a
269    /// continuation: no pass running, not ended, and inside the settle window.
270    fn settling_at(&self, now: u64) -> bool {
271        !self.active && self.ended_at_ms.is_none() && self.settle_until_ms.is_some_and(|u| now <= u)
272    }
273
274    /// When the turn ended: its recorded end, or its last pass's end once
275    /// it is done settling with no next pass (nothing writes the end then).
276    /// `None` while a pass runs or a next one is expected.
277    fn ended_at(&self, now: u64) -> Option<u64> {
278        self.ended_at_ms
279            .or_else(|| (!self.active && !self.settling_at(now)).then_some(self.last_pass_ended_at_ms).flatten())
280    }
281
282    /// Record the end of a turn that is over by `ended_at` but has no end
283    /// written yet: one whose settle window ran out.
284    fn close_if_lapsed(&mut self, now: u64) {
285        if self.ended_at_ms.is_none() && !self.active && !self.settling_at(now) {
286            self.ended_at_ms = Some(self.last_pass_ended_at_ms.unwrap_or(now));
287            self.end = Some(TurnEnd::Completed);
288            self.settle_until_ms = None;
289        }
290    }
291}
292
293/// One finished pass's figures, from its `result` frame.
294#[derive(Clone, Copy, Debug, Default, PartialEq)]
295pub struct PassStats {
296    pub output_tokens: u64,
297    pub cost_usd: f64,
298    pub steps: u32,
299    pub duration_api_ms: u64,
300}
301
302impl PassStats {
303    /// Read from a Claude `result` frame; absent fields count as zero.
304    pub fn from_result_frame(frame: &serde_json::Value) -> Self {
305        let u64_at = |v: Option<&serde_json::Value>| v.and_then(|v| v.as_u64()).unwrap_or(0);
306        PassStats {
307            output_tokens: u64_at(frame.pointer("/usage/output_tokens")),
308            cost_usd: frame.get("total_cost_usd").and_then(|v| v.as_f64()).unwrap_or(0.0),
309            steps: u64_at(frame.get("num_turns")) as u32,
310            duration_api_ms: u64_at(frame.get("duration_api_ms")),
311        }
312    }
313}
314
315/// How a pass is starting, for the ledger's join decision (§4.3).
316#[derive(Clone, Copy, Debug, PartialEq, Eq)]
317enum PassStart {
318    /// Input written by srv now: the pane, a jekt, a broadcast …
319    Input { origin: TurnOrigin, joins_turn: Option<u64> },
320    /// Input srv had queued (a spawn's backlog, a retry), or a spawn.
321    Queued,
322    /// The CLI started the pass itself, after a task notification.
323    CliWake,
324}
325
326/// The `agentturn` event's payload (`mps_events::AgentTurn`): the ledger, and its pane.
327#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
328#[ts(export, export_to = "../../../frontend/types/rpc/")]
329pub struct AgentTurnEvent {
330    pub block_id: String,
331    #[serde(flatten)]
332    pub ledger: TurnLedger,
333}
334
335/// Called with the ledger after every change, outside the tracker's lock.
336pub type TurnLedgerPublisher = Arc<dyn Fn(&TurnLedger) + Send + Sync>;
337
338/// A publisher that sends the ledger as the persisted `agentturn` event on
339/// `block:<id>`, so a pane mounting mid-turn gets it at once.
340///
341/// A settling ledger is also published again, closed, when its window lapses
342/// with nothing newer published in between (`closed_when_lapsed`). The
343/// tracker closes it only lazily, at the next pass, and a consumer like the
344/// notification router needs to hear that the turn is over.
345pub fn ledger_publisher(broker: Arc<crate::backend::mps::Broker>, block_id: String) -> TurnLedgerPublisher {
346    let latest_seq = Arc::new(std::sync::atomic::AtomicU64::new(0));
347    let publish = Arc::new(move |ledger: &TurnLedger| {
348        let payload = AgentTurnEvent { block_id: block_id.clone(), ledger: ledger.clone() };
349        broker.publish_event::<crate::backend::mps_events::AgentTurn>(&payload, vec![format!("block:{block_id}")], 1);
350    });
351    Arc::new(move |ledger: &TurnLedger| {
352        latest_seq.store(ledger.seq, std::sync::atomic::Ordering::SeqCst);
353        publish(ledger);
354        if let (Some(closed), Ok(handle)) = (closed_when_lapsed(ledger), tokio::runtime::Handle::try_current()) {
355            let wait = ledger.settle_until_ms.unwrap_or(0).saturating_sub(agentmux_common::time::now_ms_u64()) + 50;
356            let (latest_seq, publish) = (Arc::clone(&latest_seq), Arc::clone(&publish));
357            handle.spawn(async move {
358                tokio::time::sleep(std::time::Duration::from_millis(wait)).await;
359                if latest_seq.load(std::sync::atomic::Ordering::SeqCst) == closed.seq {
360                    publish(&closed);
361                }
362            });
363        }
364    })
365}
366
367/// The change from one published ledger to the next, in words, for the
368/// `[turn]` log: `None` when nothing worth a line changed (stats, `seq`).
369pub fn ledger_transition(before: Option<&TurnLedger>, after: Option<&TurnLedger>) -> Option<&'static str> {
370    let a = after?;
371    let Some(b) = before.filter(|b| b.turn_id == a.turn_id) else {
372        return Some("opened");
373    };
374    if a.passes > b.passes {
375        return Some("next pass joined the turn");
376    }
377    if a.inputs > b.inputs {
378        return Some("input joined the running pass");
379    }
380    if a.end.is_some() && b.end.is_none() {
381        return Some(match a.end {
382            Some(TurnEnd::Exited) => "ended: the process exited",
383            _ => "ended",
384        });
385    }
386    if a.settle_until_ms.is_some() && b.settle_until_ms.is_none() {
387        return Some("pass ended, settling for a next one");
388    }
389    None
390}
391
392/// A settling ledger as it reads once its window lapsed with no next pass:
393/// ended at its last pass. `None` for a ledger that isn't settling. Same `seq`:
394/// it is the same state, only now known to be over.
395pub fn closed_when_lapsed(ledger: &TurnLedger) -> Option<TurnLedger> {
396    let lapsed_at = ledger.settle_until_ms?.saturating_add(1);
397    if ledger.active || ledger.ended_at_ms.is_some() {
398        return None;
399    }
400    let mut closed = ledger.clone();
401    closed.close_if_lapsed(lapsed_at);
402    Some(closed)
403}
404
405/// What started the current turn, and whether anything else got in.
406#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
407pub struct TurnProvenance {
408    pub origin: TurnOrigin,
409    /// Non-user input was delivered into this turn after it started (§6.3:
410    /// a taint, never undone within the turn).
411    pub tainted: bool,
412    /// The user's message that started the turn (origin `User` only).
413    #[serde(skip)]
414    pub user_text: Option<String>,
415    /// The turn was started by the human's Swarm broadcast (`TriggerKind::Broadcast`).
416    pub broadcast: bool,
417}
418
419impl TurnProvenance {
420    fn from_input(input: TurnInput) -> Self {
421        let origin = input.origin();
422        let broadcast = input.from.kind == TriggerKind::Broadcast;
423        let user_text = (origin == TurnOrigin::User).then_some(input.text);
424        TurnProvenance { origin, tainted: false, user_text, broadcast }
425    }
426    /// The turn was started by a Swarm broadcast: the user's own message, sent
427    /// to many panes at once.
428    pub fn is_broadcast(&self) -> bool {
429        self.broadcast
430    }
431    fn absorb(&mut self, origin: TurnOrigin) {
432        if origin != TurnOrigin::User {
433            self.tainted = true;
434        }
435    }
436}
437
438struct TurnActivityTrackerInner {
439    /// The `total_cost_usd` of the last `result` frame. Claude's figure counts the whole
440    /// session (the process), not the pass, so a pass costs the rise since the one before.
441    session_cost_usd: f64,
442    active_turn: bool,
443    exit_code: Option<i32>,
444    /// What started the CURRENT turn. Cleared on every idle→active flip that
445    /// isn't labelled, so a turn only ever carries a provenance its own start
446    /// reported — a stale label can never leak into a later turn.
447    provenance: Option<TurnProvenance>,
448    /// Told ahead of a turn that starts later — a message queued while the
449    /// process spawns. Taken by the next idle→active flip.
450    next_turn: Option<TurnProvenance>,
451    /// The user-facing turn this block is in, or last was in.
452    ledger: Option<TurnLedger>,
453    /// Input was written while the current pass ran: the CLI may answer it
454    /// in a pass of its own straight after this one (J2).
455    input_during_pass: bool,
456    /// The CLI reported a finished background task, so it will start a pass
457    /// by itself to tell the model (J4). Cleared when any pass starts.
458    cli_wake_pending: bool,
459    /// Input reached the CLI during the pass that just ended, which it may
460    /// answer in a pass of its own straight after (J2). Good only while that
461    /// turn settles: a later pass the CLI starts is something else's.
462    continuation_expected: bool,
463    /// What started that pass: a continuation answers the same input, so it
464    /// carries the same provenance (self-quit gate, §6.3).
465    continuation_provenance: Option<TurnProvenance>,
466    /// The turn a held message being sent now should join, and when srv was
467    /// told: for controllers whose pass starts carry no input (`hint_join`).
468    pending_join: Option<(u64, u64)>,
469    /// The last `TurnLedger::seq` stamped, across turns.
470    ledger_seq: u64,
471    /// The trigger of a message queued for the next turn (`hint_next_turn`).
472    next_turn_trigger: Option<TurnTrigger>,
473    /// The task the CLI last reported finished, for the pass it wakes for.
474    pending_task_trigger: Option<TurnTrigger>,
475    /// When the running pass started (tracker clock, ms).
476    pass_started_ms: u64,
477}
478
479impl TurnActivityTrackerInner {
480    /// The ledger to publish after a change: stamped with the next `seq` when
481    /// it differs from `before`.
482    fn stamp(&mut self, before: &Option<TurnLedger>) -> Option<TurnLedger> {
483        if self.ledger != *before {
484            self.ledger_seq += 1;
485            if let Some(l) = self.ledger.as_mut() {
486                l.seq = self.ledger_seq;
487            }
488        }
489        self.ledger.clone()
490    }
491
492    /// idle→active with no label: take the queued hint, if any.
493    fn start_unlabelled(&mut self) {
494        self.provenance = self.next_turn.take();
495    }
496
497    /// Mid-pass input: the turn will expect a next pass when this one ends.
498    fn note_input_during_pass(&mut self, trigger: Option<TurnTrigger>) {
499        self.input_during_pass = true;
500        // A join hint for a message that reached a running pass is spent: it
501        // must not make the next fresh message join this turn.
502        self.pending_join = None;
503        if let Some(l) = self.ledger.as_mut().filter(|l| l.active) {
504            l.inputs += 1;
505            l.absorb(trigger);
506        }
507    }
508
509    /// A pass starts (idle→active): join the current turn or open a new one
510    /// (turn-model spec §4.3).
511    fn begin_pass(&mut self, start: PassStart, trigger: Option<TurnTrigger>, now: u64) {
512        self.pass_started_ms = now;
513        self.input_during_pass = false;
514        self.cli_wake_pending = false;
515        self.continuation_expected = false;
516        self.continuation_provenance = None;
517        // A join hint is good once, and only briefly: it names a message being
518        // sent right now.
519        let hinted = self
520            .pending_join
521            .take()
522            .filter(|(_, at)| now.saturating_sub(*at) <= HELD_FLUSH_JOIN_MS)
523            .map(|(id, _)| id);
524        let trigger = match start {
525            PassStart::Queued => trigger.or_else(|| self.next_turn_trigger.take()),
526            PassStart::CliWake => self.pending_task_trigger.take().or(trigger),
527            PassStart::Input { .. } => trigger,
528        };
529        // A task that lost the race to this pass is not what a later pass
530        // answers: only the CLI's own wake for it may carry it (#4503).
531        self.pending_task_trigger = None;
532        let origin = match start {
533            PassStart::Input { origin, .. } => Some(origin),
534            PassStart::CliWake => Some(TurnOrigin::Automated),
535            PassStart::Queued => self.provenance.as_ref().map(|p| p.origin),
536        };
537        if let Some(ledger) = self.ledger.as_mut() {
538            let settling = ledger.settling_at(now);
539            let recently_ended = ledger.ended_at(now).is_some_and(|e| now.saturating_sub(e) <= HELD_FLUSH_JOIN_MS);
540            let joins = match start {
541                // A fresh message the user typed after the agent stopped is a
542                // new turn, even inside the settle window (D3); only the
543                // pane's flush of a message held during this turn joins it.
544                PassStart::Input { origin: TurnOrigin::User, joins_turn } => {
545                    joins_turn == Some(ledger.turn_id) && (settling || recently_ended)
546                }
547                PassStart::Queued if hinted == Some(ledger.turn_id) => settling || recently_ended,
548                PassStart::Input { .. } | PassStart::Queued | PassStart::CliWake => settling,
549            };
550            if joins {
551                ledger.passes += 1;
552                // New input joined: a message, or a finished task the CLI woke
553                // for (#4503). A plain continuation or a queue drain brings none.
554                let task_wake = matches!(start, PassStart::CliWake) && trigger.is_some();
555                if matches!(start, PassStart::Input { .. }) || task_wake {
556                    ledger.inputs += 1;
557                    ledger.absorb(trigger);
558                }
559                ledger.active = true;
560                ledger.settle_until_ms = None;
561                ledger.ended_at_ms = None;
562                ledger.end = None;
563                return;
564            }
565            ledger.close_if_lapsed(now);
566        }
567        let previous = self.ledger.as_ref().map_or(0, |l| l.turn_id);
568        self.ledger = Some(TurnLedger {
569            turn_id: now.max(previous + 1),
570            seq: 0,
571            origin,
572            // A pass the CLI started with no task to name has no trigger: never
573            // a sender made up from its origin (#4503).
574            trigger: trigger.or_else(|| {
575                (!matches!(start, PassStart::CliWake)).then_some(origin).flatten().map(TurnTrigger::from_turn_origin)
576            }),
577            absorbed: Vec::new(),
578            started_at_ms: now,
579            passes: 1,
580            active: true,
581            inputs: 0,
582            counted_passes: 0,
583            output_tokens: 0,
584            cost_usd: 0.0,
585            steps: 0,
586            duration_api_ms: 0,
587            last_pass_ended_at_ms: None,
588            settle_until_ms: None,
589            ended_at_ms: None,
590            end: None,
591        });
592    }
593
594    /// The running pass ended (active→idle). The turn waits for a next pass
595    /// when one is expected, and is over otherwise.
596    fn end_pass(&mut self, now: u64, provenance: Option<TurnProvenance>) {
597        let expects_more = self.input_during_pass || self.cli_wake_pending;
598        self.continuation_expected = self.input_during_pass;
599        self.continuation_provenance = self.input_during_pass.then_some(provenance).flatten();
600        self.input_during_pass = false;
601        let Some(ledger) = self.ledger.as_mut().filter(|l| l.active) else { return };
602        ledger.active = false;
603        ledger.last_pass_ended_at_ms = Some(now);
604        if expects_more {
605            ledger.settle_until_ms = Some(now + TURN_SETTLE_MS);
606        } else {
607            ledger.ended_at_ms = Some(now);
608            ledger.end = Some(TurnEnd::Completed);
609        }
610    }
611}
612
613/// Per-block turn-activity tracker.
614pub struct TurnActivityTracker {
615    block_id: String,
616    inner: Mutex<TurnActivityTrackerInner>,
617    publisher: Mutex<Option<TurnLedgerPublisher>>,
618    /// Taken before `inner` is released and held through the publish, so
619    /// ledgers go out in `seq` order. The broker keeps the last one for
620    /// replay, so an older one published last would be what a new subscriber
621    /// gets (#4492). Lock order: `inner` → `publish_order`.
622    publish_order: Mutex<()>,
623    clock: Box<dyn Fn() -> u64 + Send + Sync>,
624    /// When the agent's process was last spawned, and when it last wrote
625    /// output (ms; 0 = not yet): the watchdog's runtime and idle limits
626    /// (`watchdog.rs`). Atomics, so a reader task can stamp every line
627    /// without the lock.
628    spawned_ms: AtomicU64,
629    output_ms: AtomicU64,
630    /// When the user's answer to a parked request was delivered (ms; 0 = not
631    /// yet): the time spent waiting for it is not idleness.
632    reply_ms: AtomicU64,
633}
634
635impl TurnActivityTracker {
636    pub fn new(block_id: String) -> Self {
637        Self::with_clock(block_id, Box::new(agentmux_common::time::now_ms_u64))
638    }
639
640    /// A tracker that publishes its turn ledger on `broker`, when there is one.
641    pub fn for_block(block_id: String, broker: Option<&Arc<crate::backend::mps::Broker>>) -> Self {
642        let tracker = Self::new(block_id.clone());
643        if let Some(broker) = broker {
644            tracker.set_ledger_publisher(ledger_publisher(Arc::clone(broker), block_id));
645        }
646        tracker
647    }
648
649    pub(crate) fn with_clock(block_id: String, clock: Box<dyn Fn() -> u64 + Send + Sync>) -> Self {
650        Self {
651            block_id,
652            inner: Mutex::new(TurnActivityTrackerInner {
653                session_cost_usd: 0.0,
654                active_turn: false,
655                exit_code: None,
656                provenance: None,
657                next_turn: None,
658                ledger: None,
659                input_during_pass: false,
660                cli_wake_pending: false,
661                continuation_expected: false,
662                continuation_provenance: None,
663                pending_join: None,
664                ledger_seq: 0,
665                next_turn_trigger: None,
666                pending_task_trigger: None,
667                pass_started_ms: 0,
668            }),
669            publisher: Mutex::new(None),
670            publish_order: Mutex::new(()),
671            clock,
672            spawned_ms: AtomicU64::new(0),
673            output_ms: AtomicU64::new(0),
674            reply_ms: AtomicU64::new(0),
675        }
676    }
677
678    /// Where ledger changes go (the `agentturn` event). Set once by the
679    /// controller that owns this tracker, when it has a broker.
680    pub fn set_ledger_publisher(&self, publisher: TurnLedgerPublisher) {
681        *self.publisher.lock().unwrap() = Some(publisher);
682    }
683
684    /// Release `inner` and publish the ledger if it changed, in `seq` order,
685    /// logging the change as a `[turn]` line (`muxlog`'s answer to "why did
686    /// my timer reset": turn-model spec §7).
687    fn publish_in_order(
688        &self,
689        inner: std::sync::MutexGuard<'_, TurnActivityTrackerInner>,
690        before: Option<TurnLedger>,
691        after: Option<TurnLedger>,
692    ) {
693        if before == after {
694            return;
695        }
696        let _order = self.publish_order.lock().unwrap();
697        drop(inner);
698        if let (Some(what), Some(l)) = (ledger_transition(before.as_ref(), after.as_ref()), after.as_ref()) {
699            tracing::info!(
700                block_id = %self.block_id,
701                turn_id = l.turn_id,
702                passes = l.passes,
703                inputs = l.inputs,
704                trigger = ?l.trigger.as_ref().map(|t| t.kind),
705                "[turn] {what}"
706            );
707        }
708        self.publish_if_changed(before, after);
709    }
710
711    /// Send the ledger to the publisher, if it changed. Called after the
712    /// tracker's lock is released.
713    fn publish_if_changed(&self, before: Option<TurnLedger>, after: Option<TurnLedger>) {
714        if before == after {
715            return;
716        }
717        let Some(ledger) = after else { return };
718        let publisher = self.publisher.lock().unwrap().clone();
719        if let Some(p) = publisher {
720            p(&ledger);
721        }
722    }
723
724    /// Called when a new turn starts (subprocess spawned).
725    pub fn set_active_turn(&self, active: bool) {
726        if !active {
727            return self.end_pass(None);
728        }
729        let now = (self.clock)();
730        let mut inner = self.inner.lock().unwrap();
731        let before = inner.ledger.clone();
732        let was_active = inner.active_turn;
733        inner.active_turn = true;
734        inner.exit_code = None;
735        if !was_active {
736            inner.start_unlabelled();
737            inner.begin_pass(PassStart::Queued, None, now);
738        }
739        let after = inner.stamp(&before);
740        self.publish_in_order(inner, before, after);
741        tracing::info!(block_id = %self.block_id, active, "[health] turn_active flip");
742    }
743
744    /// Atomically marks a turn active and reports whether one was already in
745    /// flight (the pre-call value) — a single lock acquisition, unlike
746    /// calling `is_active_turn()` then `set_active_turn(true)` separately.
747    /// That two-step form is a check-then-act race: `send_message` (user
748    /// input) and `send_user_message` (muxbus delivery) can run concurrently
749    /// on the same block, and both reading `false` before either writes
750    /// `true` lets both decide to spawn a watchdog — the exact duplicate the
751    /// "only re-arm when resuming from idle" logic exists to prevent.
752    pub fn mark_turn_active_returning_was_active(&self) -> bool {
753        self.mark_turn_active_from(None)
754    }
755
756    /// [`Self::mark_turn_active_returning_was_active`], saying who delivered
757    /// the input (turn provenance, SPEC_AGENT_SELF_QUIT §6.3):
758    /// - starting a turn records `input` as what started it — or, unlabelled,
759    ///   whatever was queued for it (else unknown);
760    /// - into a running turn, non-user input — or unlabelled input, which
761    ///   can't be proven to be the user — taints it.
762    pub fn mark_turn_active_from(&self, input: Option<TurnInput>) -> bool {
763        let now = (self.clock)();
764        let mut inner = self.inner.lock().unwrap();
765        let before = inner.ledger.clone();
766        let was_active = inner.active_turn;
767        inner.active_turn = true;
768        inner.exit_code = None;
769        match (was_active, input) {
770            (false, Some(i)) => {
771                let start = PassStart::Input { origin: i.origin(), joins_turn: i.joins_turn };
772                let trigger = TurnTrigger::from_message(&i.from);
773                inner.provenance = Some(TurnProvenance::from_input(i));
774                inner.begin_pass(start, Some(trigger), now);
775            }
776            (false, None) => {
777                inner.start_unlabelled();
778                inner.begin_pass(PassStart::Queued, None, now);
779            }
780            (true, Some(i)) => {
781                if let Some(p) = inner.provenance.as_mut() {
782                    p.absorb(i.origin());
783                }
784                inner.note_input_during_pass(Some(TurnTrigger::from_message(&i.from)));
785            }
786            (true, None) => {
787                if let Some(p) = inner.provenance.as_mut() {
788                    p.tainted = true;
789                }
790                inner.note_input_during_pass(None);
791            }
792        }
793        let after = inner.stamp(&before);
794        self.publish_in_order(inner, before, after);
795        tracing::info!(
796            block_id = %self.block_id,
797            active = true,
798            was_active,
799            "[health] turn_active flip"
800        );
801        was_active
802    }
803
804    /// The CLI reported a finished background task (`system/task_notification`).
805    /// It tells the model in a pass it starts itself: at once if it is idle,
806    /// straight after the running pass otherwise.
807    pub fn note_cli_task_notification(&self, summary: Option<&str>) {
808        let mut inner = self.inner.lock().unwrap();
809        inner.cli_wake_pending = true;
810        inner.pending_task_trigger = Some(TurnTrigger::task(summary));
811    }
812
813    /// The CLI began a pass with no input from srv (`system/init` while idle).
814    /// Marked active only when something explains it (a task notification, or
815    /// input that reached it during the last pass), so a stray line can never
816    /// leave the agent reported busy with nothing to end it.
817    /// Returns whether the pass was marked (the caller then publishes status
818    /// and re-arms the heartbeat).
819    pub fn mark_turn_active_from_cli(&self) -> bool {
820        let now = (self.clock)();
821        let mut inner = self.inner.lock().unwrap();
822        // A continuation only while its turn still settles: after that, the
823        // input it would have answered is long dealt with (#4492).
824        let continuing = inner.continuation_expected && inner.ledger.as_ref().is_some_and(|l| l.settling_at(now));
825        if inner.active_turn || !(inner.cli_wake_pending || continuing) {
826            return false;
827        }
828        let before = inner.ledger.clone();
829        inner.active_turn = true;
830        inner.exit_code = None;
831        // Answering input from the last pass: that pass's provenance (taint and
832        // all). A task woke it, alone or as well: automated, never the user, so
833        // the self-quit gate refuses in it, as for any automated turn.
834        let continued = continuing && !inner.cli_wake_pending;
835        let carried = inner.continuation_provenance.take().filter(|_| continued);
836        inner.provenance = Some(carried.unwrap_or(TurnProvenance {
837            origin: TurnOrigin::Automated,
838            tainted: false,
839            user_text: None,
840            broadcast: false,
841        }));
842        inner.begin_pass(PassStart::CliWake, None, now);
843        let after = inner.stamp(&before);
844        self.publish_in_order(inner, before, after);
845        tracing::info!(block_id = %self.block_id, active = true, "[health] turn_active flip (CLI started a pass)");
846        true
847    }
848
849    /// The CLI's `result`: the running pass is over. Its figures (when the
850    /// frame carries them) go to the turn it belonged to in the same step as
851    /// the idle flip, so input that arrives right after can't take them.
852    pub fn end_pass(&self, stats: Option<PassStats>) {
853        let now = (self.clock)();
854        let mut inner = self.inner.lock().unwrap();
855        let before = inner.ledger.clone();
856        let was_active = inner.active_turn;
857        inner.active_turn = false;
858        let ended = inner.provenance.take();
859        // The session's running total becomes this pass's own cost, whether or not a turn is
860        // open to take it, so the next pass starts from here.
861        let stats = stats.map(|s| PassStats { cost_usd: inner.pass_cost(s.cost_usd), ..s });
862        if let (Some(stats), Some(l)) = (stats, inner.ledger.as_mut().filter(|l| l.active)) {
863            l.add_stats(stats);
864        }
865        if was_active {
866            inner.end_pass(now, ended);
867        }
868        let after = inner.stamp(&before);
869        self.publish_in_order(inner, before, after);
870        tracing::info!(block_id = %self.block_id, active = false, "[health] turn_active flip");
871    }
872
873    /// Add a finished pass's `result` figures to the latest turn.
874    #[cfg(test)]
875    pub fn add_pass_stats(&self, stats: PassStats) {
876        let mut inner = self.inner.lock().unwrap();
877        let before = inner.ledger.clone();
878        if let Some(l) = inner.ledger.as_mut() {
879            l.add_stats(stats);
880        }
881        let after = inner.stamp(&before);
882        self.publish_in_order(inner, before, after);
883    }
884
885    /// A message the pane held while turn `turn_id` ran is about to be sent
886    /// through a controller whose pass start carries no input (ACP, App Server,
887    /// one-shot subprocess): the pass it starts joins that turn, as
888    /// `TurnInput::joins_turn` does for the persistent controller (§4.3, J3).
889    pub fn hint_join(&self, turn_id: u64) {
890        let now = (self.clock)();
891        self.inner.lock().unwrap().pending_join = Some((turn_id, now));
892    }
893
894    /// Drop a join hint whose dispatch failed: no pass will consume it, and
895    /// a later message must not.
896    pub fn clear_join_hint(&self) {
897        self.inner.lock().unwrap().pending_join = None;
898    }
899
900    /// The current turn ledger, if any turn has started.
901    #[cfg(test)]
902    pub fn ledger(&self) -> Option<TurnLedger> {
903        self.inner.lock().unwrap().ledger.clone()
904    }
905
906    /// Called when the subprocess exits.
907    pub fn set_exited(&self, exit_code: i32) {
908        self.set_turn_exited(exit_code, false);
909    }
910
911    /// The process of a one-shot turn (a container exec, a per-turn subprocess) exited, which is how
912    /// every one of its turns ends. With `completed` (a clean exit and no failure) the turn is
913    /// recorded as completed, not as a process that exited under it: the leader of a worker is told
914    /// "stopped: its process exited" for the second, and a job follows it as interrupted.
915    pub fn set_turn_exited(&self, exit_code: i32, completed: bool) {
916        let now = (self.clock)();
917        let mut inner = self.inner.lock().unwrap();
918        let before = inner.ledger.clone();
919        inner.active_turn = false;
920        inner.exit_code = Some(exit_code);
921        inner.provenance = None;
922        inner.next_turn = None;
923        inner.input_during_pass = false;
924        inner.cli_wake_pending = false;
925        inner.continuation_expected = false;
926        inner.continuation_provenance = None;
927        inner.pending_join = None;
928        inner.next_turn_trigger = None;
929        inner.pending_task_trigger = None;
930        if let Some(l) = inner.ledger.as_mut().filter(|l| l.ended_at_ms.is_none()) {
931            if l.active {
932                l.last_pass_ended_at_ms = Some(now);
933            }
934            l.active = false;
935            l.settle_until_ms = None;
936            l.ended_at_ms = Some(now);
937            l.end = Some(if completed { TurnEnd::Completed } else { TurnEnd::Exited });
938        }
939        let after = inner.stamp(&before);
940        self.publish_in_order(inner, before, after);
941        tracing::info!(block_id = %self.block_id, exit_code, "[health] turn_active flip (process exited)");
942    }
943
944    /// Whether there's an active turn in progress.
945    pub fn is_active_turn(&self) -> bool {
946        self.inner.lock().unwrap().active_turn
947    }
948
949    /// A message queued now will start a later turn (it waits for the
950    /// process to spawn). Two queued before that turn starts: the second, if
951    /// not the user's, taints it.
952    pub fn hint_next_turn(&self, input: TurnInput) {
953        let now = (self.clock)();
954        let mut inner = self.inner.lock().unwrap();
955        // A held message queued behind a spawn keeps its join for the pass the
956        // spawn starts (#4492).
957        if let Some(turn_id) = input.joins_turn {
958            inner.pending_join = Some((turn_id, now));
959        }
960        if inner.next_turn.is_none() {
961            inner.next_turn_trigger = Some(TurnTrigger::from_message(&input.from));
962        }
963        match inner.next_turn.as_mut() {
964            None => inner.next_turn = Some(TurnProvenance::from_input(input)),
965            Some(p) => p.absorb(input.origin()),
966        }
967    }
968
969    /// An unlabelled message queued for the next turn: it can't be proven to
970    /// be the user, so a turn already labelled by an earlier queued message is
971    /// tainted. (Queued first, it leaves the turn unknown anyway.)
972    pub fn hint_next_turn_unlabelled(&self) {
973        if let Some(p) = self.inner.lock().unwrap().next_turn.as_mut() {
974            p.tainted = true;
975        }
976    }
977
978    /// The turn is active because messages already accounted for are being
979    /// delivered — the queue drained after a spawn, a retry flush. Not new
980    /// input: an idle tracker starts the turn with whatever was queued for it,
981    /// and a running turn is left as it is (ReAgent P1 on #3789 — the plain
982    /// unlabelled mark tainted every freshly spawned user turn).
983    pub fn mark_turn_active_for_queued(&self) -> bool {
984        let now = (self.clock)();
985        let mut inner = self.inner.lock().unwrap();
986        let before = inner.ledger.clone();
987        let was_active = inner.active_turn;
988        inner.active_turn = true;
989        inner.exit_code = None;
990        if !was_active {
991            inner.start_unlabelled();
992            inner.begin_pass(PassStart::Queued, None, now);
993        }
994        let after = inner.stamp(&before);
995        self.publish_in_order(inner, before, after);
996        tracing::info!(block_id = %self.block_id, active = true, was_active, "[health] turn_active flip (queued delivery)");
997        was_active
998    }
999
1000    /// The agent's process was spawned just now.
1001    pub fn note_spawned(&self) {
1002        self.spawned_ms.store((self.clock)(), Ordering::Relaxed);
1003        // A new process counts its session's cost from zero, whatever the last one reached.
1004        self.inner.lock().unwrap().session_cost_usd = 0.0;
1005    }
1006
1007    /// The agent wrote output just now: a stdout line or a protocol frame.
1008    pub fn note_output(&self) {
1009        self.output_ms.store((self.clock)(), Ordering::Relaxed);
1010    }
1011
1012    /// The user's answer to a parked question or permission request was
1013    /// delivered to the agent just now.
1014    pub fn note_user_reply(&self) {
1015        self.reply_ms.store((self.clock)(), Ordering::Relaxed);
1016    }
1017
1018    /// When the user's last answer to a parked request was delivered (unix ms).
1019    pub fn last_user_reply_ms(&self) -> Option<i64> {
1020        stamp_ms(self.reply_ms.load(Ordering::Relaxed))
1021    }
1022
1023    /// When the agent's process was last spawned (unix ms), if it has been.
1024    pub fn spawned_at_ms(&self) -> Option<i64> {
1025        stamp_ms(self.spawned_ms.load(Ordering::Relaxed))
1026    }
1027
1028    /// When the agent last wrote output (unix ms), if it has.
1029    pub fn last_output_ms(&self) -> Option<i64> {
1030        stamp_ms(self.output_ms.load(Ordering::Relaxed))
1031    }
1032
1033    /// When the pass in flight started (unix ms); `None` between passes.
1034    pub fn pass_started_ms(&self) -> Option<i64> {
1035        let inner = self.inner.lock().unwrap();
1036        if inner.active_turn {
1037            stamp_ms(inner.pass_started_ms)
1038        } else {
1039            None
1040        }
1041    }
1042
1043    /// What started the turn in flight, if one is and it was reported.
1044    pub fn provenance(&self) -> Option<TurnProvenance> {
1045        let inner = self.inner.lock().unwrap();
1046        if inner.active_turn {
1047            inner.provenance.clone()
1048        } else {
1049            None
1050        }
1051    }
1052}
1053
1054/// A stored stamp as unix ms; 0 means it was never set.
1055fn stamp_ms(ms: u64) -> Option<i64> {
1056    (ms != 0).then(|| i64::try_from(ms).unwrap_or(i64::MAX))
1057}
1058
1059#[cfg(test)]
1060mod tests;