Skip to main content

agentmux_srv_core/ambient/
outcome.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One outcome per ambient call, logged and counted.
5//!
6//! The module used to be silent: its failure paths logged at debug, so a rejected,
7//! empty or failed title left no trace, and diagnosing the `(none yet)` swarm row
8//! took a database copy (docs/specs/SPEC_AMBIENT_SWARM_SUMMARY_HARDENING_2026_10_02.md
9//! section 2.1 defect 6, section 5.8). Every call now ends in exactly one
10//! [`Outcome`], written as one structured info line and counted per purpose, and
11//! the counts are readable over the `ambient.outcomes` RPC (the token popover's AgentMux internal row).
12//! The rejected text is logged, truncated, because rejected values are the corpus
13//! the title predicate is tuned with.
14
15use std::collections::BTreeMap;
16use std::sync::{Mutex, OnceLock};
17
18/// How an ambient call ended.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Outcome {
21    /// The reply passed validation and was used.
22    Accepted,
23    /// The model answered `SKIP` (`reply`): nothing to write, or for a title, no
24    /// change. A healthy answer.
25    Skipped,
26    /// No model call: a check in code already showed there is nothing to write
27    /// (for a suggestion, the assistant's last message waits for the user).
28    Gated,
29    /// The reply was refused; the reason says by which rule.
30    Rejected(RejectReason),
31    /// There was nothing to send: no conversation in the digest, or no message
32    /// and no title to work from. No model call was made.
33    EmptyDigest,
34    /// A newer request for the same key replaced this one, before or during the
35    /// call.
36    Superseded,
37    /// The CLI could not be run or failed.
38    CliFailed,
39    /// The CLI ran past its time limit.
40    Timeout,
41    /// Admitted, then given up before any model call: the block or its CLI path
42    /// could not be resolved, or a purpose found nothing to do. Recorded when an
43    /// admitted call is dropped without running (`call::Slot`'s `Drop`).
44    NotRun,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum RejectReason {
49    /// Blank after trimming.
50    Empty,
51    /// Refused by the purpose's own check after a well-formed `ANSWER:` (too
52    /// long, a placeholder title, a risky suggestion).
53    Other,
54    /// Not in the reply format (`reply`): no `ANSWER:` prefix and not `SKIP`.
55    Format,
56}
57
58impl Outcome {
59    /// The stable label used in the log line and the counters.
60    pub fn label(&self) -> &'static str {
61        match self {
62            Outcome::Accepted => "accepted",
63            Outcome::Skipped => "skipped",
64            Outcome::Gated => "gated",
65            Outcome::Rejected(RejectReason::Format) => "rejected:format",
66            Outcome::Rejected(RejectReason::Empty) => "rejected:empty",
67            Outcome::Rejected(RejectReason::Other) => "rejected:other",
68            Outcome::EmptyDigest => "empty_digest",
69            Outcome::Superseded => "superseded",
70            Outcome::CliFailed => "cli_failed",
71            Outcome::Timeout => "timeout",
72            Outcome::NotRun => "not_run",
73        }
74    }
75}
76
77/// Separates an error's own words from the end of the child's stderr that follows it.
78pub const CHILD_OUTPUT_MARK: &str = " | stderr: ";
79
80/// Classify a failed CLI call. `cancelled` is whether the gateway cancelled it
81/// because a newer request superseded it.
82pub fn classify_error(error: &str, cancelled: bool) -> Outcome {
83    if cancelled {
84        return Outcome::Superseded;
85    }
86    // Only our own words decide: what the child wrote to stderr (after `CHILD_OUTPUT_MARK`) cannot change the label.
87    let ours = error.split(CHILD_OUTPUT_MARK).next().unwrap_or(error);
88    let lower = ours.to_ascii_lowercase();
89    if lower.contains("timeout") || lower.contains("timed out") {
90        Outcome::Timeout
91    } else {
92        Outcome::CliFailed
93    }
94}
95
96type Counts = BTreeMap<&'static str, BTreeMap<&'static str, u64>>;
97
98fn counts() -> &'static Mutex<Counts> {
99    static COUNTS: OnceLock<Mutex<Counts>> = OnceLock::new();
100    COUNTS.get_or_init(|| Mutex::new(BTreeMap::new()))
101}
102
103/// How long a call waited and ran, for the outcome line. Both in milliseconds.
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
105pub struct Timing {
106    /// Waiting for a concurrency permit, from admission.
107    pub queued_ms: u64,
108    /// The CLI call itself, spawn to exit (or cancellation, or the time limit).
109    pub run_ms: u64,
110}
111
112/// Record one outcome without timings: count it, and log it at info with the
113/// purpose and entity. See [`record_timed`].
114pub fn record(purpose: &'static str, entity: &str, outcome: Outcome, text: Option<&str>) {
115    record_timed(purpose, entity, outcome, text, None);
116}
117
118/// Record one outcome: count it, and log it at info with the purpose, the entity
119/// and, when the call ran, how long it queued and ran. `text` (the reply, or the
120/// reason a call failed) is logged by its length only: it is model output about a
121/// conversation, and no log level carries that
122/// (`docs/specs/SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 3 row 10).
123pub fn record_timed(purpose: &'static str, entity: &str, outcome: Outcome, text: Option<&str>, timing: Option<Timing>) {
124    if let Ok(mut map) = counts().lock() {
125        *map.entry(purpose)
126            .or_default()
127            .entry(outcome.label())
128            .or_default() += 1;
129    }
130    // The reply is model output about a conversation: its length is logged, never its text.
131    let text_chars = text.map(|t| t.chars().count());
132    let queued_ms = timing.map(|t| t.queued_ms);
133    let run_ms = timing.map(|t| t.run_ms);
134    tracing::info!(
135        purpose,
136        entity,
137        outcome = outcome.label(),
138        text_chars,
139        queued_ms,
140        run_ms,
141        "ambient outcome"
142    );
143}
144
145/// Every count since this srv started, by purpose then outcome label.
146pub fn snapshot() -> BTreeMap<String, BTreeMap<String, u64>> {
147    let Ok(map) = counts().lock() else {
148        return BTreeMap::new();
149    };
150    map.iter()
151        .map(|(purpose, by)| {
152            (
153                purpose.to_string(),
154                by.iter()
155                    .map(|(label, n)| (label.to_string(), *n))
156                    .collect(),
157            )
158        })
159        .collect()
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn a_failure_is_superseded_timed_out_or_a_cli_failure() {
168        assert_eq!(classify_error("cancelled", true), Outcome::Superseded);
169        assert_eq!(
170            classify_error("haiku call timed out after 15s", false),
171            Outcome::Timeout
172        );
173        assert_eq!(
174            classify_error("spawn failed: not found", false),
175            Outcome::CliFailed
176        );
177    }
178
179    #[test]
180    fn what_the_child_wrote_cannot_change_the_label() {
181        let failed = format!("ambient CLI exited with status 1{CHILD_OUTPUT_MARK}request timed out, connection timeout");
182        assert_eq!(classify_error(&failed, false), Outcome::CliFailed);
183        let slow = format!("ambient CLI timed out after 45s{CHILD_OUTPUT_MARK}x");
184        assert_eq!(classify_error(&slow, false), Outcome::Timeout);
185    }
186
187    #[test]
188    fn outcomes_are_counted_per_purpose() {
189        // A purpose no other test uses, so parallel tests cannot disturb it.
190        let p = "test_purpose_outcome_counts";
191        record(p, "b1", Outcome::Accepted, None);
192        record(p, "b1", Outcome::Accepted, None);
193        record(p, "b2", Outcome::Rejected(RejectReason::Format), Some("(none yet)"));
194        record(p, "b3", Outcome::Skipped, Some("SKIP"));
195        let snap = snapshot();
196        let by = &snap[p];
197        assert_eq!(by["accepted"], 2);
198        assert_eq!(by["rejected:format"], 1);
199        assert_eq!(by["skipped"], 1);
200    }
201
202    #[test]
203    fn an_outcome_is_logged_by_the_replys_length_never_by_its_text() {
204        const MARKER: &str = "OUTCOME-MARKER-the-reply-text";
205        for outcome in [Outcome::Accepted, Outcome::Rejected(RejectReason::Format), Outcome::CliFailed, Outcome::Timeout, Outcome::Skipped] {
206            let log = crate::test_support::captured_log(|| {
207                record_timed("test_purpose_outcome_log", "b9", outcome, Some(MARKER), Some(Timing { queued_ms: 1, run_ms: 2 }))
208            });
209            assert!(log.contains("ambient outcome") && log.contains("test_purpose_outcome_log"), "{log}");
210            assert!(log.contains(&format!("text_chars={}", MARKER.chars().count())), "{log}");
211            assert!(!log.contains(MARKER), "{log}");
212        }
213    }
214}