Skip to main content

agentmux_srv_core/backend/memory/
delivery_state.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The memory delivery's shared state: the deliveries being composed and cached, the
5//! frontend fallback's claims, the compaction boundaries a block's CLI wrote and the
6//! notices parked behind them. The handlers (`server/memory_delivery_handlers.rs`) drive
7//! it; the stdout readers under `blockcontroller` record the boundaries and take the
8//! parked notices, so it sits below both.
9
10use std::collections::{HashMap, VecDeque};
11use std::sync::{LazyLock, Mutex};
12
13use serde::Serialize;
14
15use super::delivery::Reason;
16
17/// How long a composed delivery stays cached for its remaining parts and
18/// acknowledgements. The hooks of one session start run within seconds.
19pub const DELIVERY_TTL_MS: i64 = 5 * 60_000;
20
21#[derive(Debug, Clone, PartialEq, Eq, Hash)]
22pub struct DeliveryKey {
23    pub block_id: String,
24    pub session_id: String,
25    pub reason: Reason,
26}
27
28#[derive(Debug, Clone)]
29pub struct Delivery {
30    pub parts: Vec<String>,
31    pub entries: Vec<EntrySize>,
32    pub summary_bytes: usize,
33    pub acked: Vec<bool>,
34    pub created_ms: i64,
35    pub notice_sent: bool,
36}
37
38/// One item of a delivery as the notice shows it: one card row
39/// (SPEC_CONTEXT_DELIVERY_2026_09_30 §3.1, §3.4). `label` and `source` are
40/// what older builds read; the rest is per-item detail. Sizes are those of
41/// what was delivered, so an item cut by the part cap reports its slice.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43pub struct EntrySize {
44    pub label: String,
45    /// `global`, `personal`, or `summary` for the running summary.
46    pub source: &'static str,
47    pub size_bytes: usize,
48    pub tokens: usize,
49    /// `global_memory`, `personal_memory` or `running_summary`.
50    pub kind: &'static str,
51    pub name: String,
52    /// Global Memory only: `system` (AgentMux's own) or `workspace`.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub tier: Option<&'static str>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub bundle_id: Option<String>,
57    /// Personal Memory only: the file.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub path: Option<String>,
60    /// `full`, `partial`, `omitted` (left out) or `indexed` (listed in the Personal Memory index).
61    pub delivered: &'static str,
62    /// The whole entry's size, whatever was delivered: what the Personal
63    /// Memory size band measures, so a cut delivery still warns.
64    pub source_size_bytes: usize,
65    pub source_tokens: usize,
66    /// A file the CLI read by itself at startup (`kind: "startup_file"`).
67    #[serde(flatten, skip_serializing_if = "Option::is_none")]
68    pub startup: Option<StartupDetail>,
69    /// `startup_file`: a Global Memory entry the agent got through its
70    /// startup file rather than the hook (LC3), so it carries no size of its
71    /// own (the file's row counts it).
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub via: Option<&'static str>,
74    /// Why a row is not in full when that needs saying: a file marked always over the limit, or a Global entry left out.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub reason: Option<String>,
77}
78
79impl EntrySize {
80    /// The running summary's row: what a compaction delivery carries last.
81    pub fn running_summary(
82        size_bytes: usize,
83        tokens: usize,
84        delivered: &'static str,
85        source_size_bytes: usize,
86        source_tokens: usize,
87    ) -> Self {
88        Self {
89            label: "Running summary".into(),
90            source: "summary",
91            size_bytes,
92            tokens,
93            kind: "running_summary",
94            name: "Running summary (AgentMux)".into(),
95            tier: None,
96            bundle_id: None,
97            path: None,
98            delivered,
99            source_size_bytes,
100            source_tokens,
101            startup: None,
102            via: None,
103            reason: None,
104        }
105    }
106}
107
108/// What a `startup_file` item adds (SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_
109/// STARTUP_FILES_2026_09_30.md §4.1, `backend::startup_files`).
110#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
111pub struct StartupDetail {
112    /// `user_instructions`, `instructions`, `instructions_import`, `skills`
113    /// or `mcp_servers`.
114    pub role: &'static str,
115    /// `agentmux`, `user` or `external`.
116    pub owner: &'static str,
117    /// Skills and MCP servers: how many are listed.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub count: Option<usize>,
120    /// AgentMux sections the file carries: `global_memory`, `skills_index`.
121    #[serde(skip_serializing_if = "Vec::is_empty")]
122    pub contains: Vec<&'static str>,
123}
124
125/// How long a claim on one event (a session start, a compaction) holds: the
126/// hook and the frontend's fallback for the same event arrive within
127/// seconds of each other, and one block has no two such events that close.
128/// Not for a fallback that waited behind a turn: a dated claim
129/// ([`DeliveryState::claim_event`]) covers that.
130pub const CLAIM_WINDOW_MS: i64 = 60_000;
131
132/// A fresh session's `agentmux_session_outcome` frame can be written just
133/// after the respawn it reports (`retry_after_resume_failure`), so a hook
134/// delivery composed up to this long before the frame is still that
135/// session's.
136pub const EVENT_SLACK_MS: i64 = 10_000;
137
138/// How long the fallback waits for a hook delivery still in flight, and how
139/// often it looks. A hook that never finishes must not leave the agent with
140/// no memory, so after this the fallback delivers instead.
141pub const PENDING_WAIT: std::time::Duration = std::time::Duration::from_secs(4);
142pub const PENDING_POLL: std::time::Duration = std::time::Duration::from_millis(200);
143
144/// How many compaction boundaries' origins are remembered. Boundary uuids are
145/// unique across blocks.
146pub const BOUNDARY_ORIGINS_MAX: usize = 256;
147
148/// Deliveries and fallback claims, behind one lock so "who claimed this event
149/// first" is decided atomically.
150#[derive(Default)]
151pub struct DeliveryState {
152    pub deliveries: HashMap<DeliveryKey, Delivery>,
153    /// Events the frontend's hidden-reinjection fallback claimed:
154    /// (block, reason) → when.
155    pub fallback_claims: HashMap<(String, Reason), i64>,
156    /// Re-deliveries srv composed for the frontend's fallback, by
157    /// `delivery_id`, until the hidden message that sends one arrives.
158    pub fallbacks: HashMap<String, FallbackDelivery>,
159    /// Which block's CLI wrote each compaction boundary, and when: (`uuid`,
160    /// block, ms), oldest first.
161    pub boundary_origins: VecDeque<(String, String, i64)>,
162    /// The newest hook delivery each (block, reason) finished: when it was
163    /// composed. Unlike `deliveries` it isn't pruned, so a fallback deferred
164    /// behind a long turn still finds it. One entry per block and reason.
165    pub completed: HashMap<(String, Reason), i64>,
166    /// One gate per delivery being composed. The 8 parts of a session start
167    /// ask at once; the first composes while the rest wait here and then read
168    /// its result, instead of each reading the memory and composing it again.
169    pub compose_gates: HashMap<DeliveryKey, std::sync::Arc<tokio::sync::Mutex<()>>>,
170    /// Session starts that composed to nothing (no memory to deliver), by the
171    /// time they did: the parts that ask after the first answer from here,
172    /// instead of each reading the memory again to find it still empty.
173    pub composed_nothing: HashMap<DeliveryKey, i64>,
174    /// A compaction's notice that finished before this block's stdout showed
175    /// the boundary (the CLI runs its `SessionStart` hooks first): block →
176    /// (delivery composed at, notice line). The stdout reader writes them
177    /// after the boundary and its summary ([`take_parked_notices`]); a timer
178    /// writes any left after [`PARKED_NOTICE_WAIT`]
179    /// (SPEC_CONTEXT_DELIVERY_2026_09_30.md §9 C2).
180    pub parked: HashMap<String, Vec<(i64, String)>>,
181}
182
183/// How long a compaction's notice waits for its boundary before it is written
184/// anyway, so a CLI that never writes one still leaves the card.
185pub const PARKED_NOTICE_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
186
187/// What the fallback's claim found.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum FallbackClaim {
190    /// Nothing delivered this event yet, or the fallback claimed it already:
191    /// the fallback delivers.
192    Deliver,
193    /// The hook delivered this event completely: the fallback stands down.
194    Skip,
195    /// The hook is delivering this event right now.
196    Pending,
197    /// A compaction boundary this block's own CLI did not write: another
198    /// block of the agent reading the shared zone, or another srv instance's.
199    /// Nothing to deliver, and (for a catch-up turn) nothing to catch up on.
200    Foreign,
201}
202
203impl DeliveryState {
204    pub fn prune(&mut self, now: i64) {
205        self.deliveries.retain(|_, d| now - d.created_ms < DELIVERY_TTL_MS);
206        self.composed_nothing.retain(|_, at| now - *at < DELIVERY_TTL_MS);
207        self.fallback_claims.retain(|_, at| now - *at < CLAIM_WINDOW_MS);
208        self.fallbacks.retain(|_, f| now - f.created_ms < FALLBACK_TTL_MS);
209    }
210
211    pub fn fallback_claimed(&self, block_id: &str, reason: Reason) -> bool {
212        self.fallback_claims.contains_key(&(block_id.to_string(), reason))
213    }
214
215    /// The hook's deliveries of this event, newest first: inside the claim
216    /// window and created after `since`.
217    pub(crate) fn hook_deliveries_mut(&mut self, block_id: &str, reason: Reason, now: i64, since: i64) -> Vec<&mut Delivery> {
218        let mut found: Vec<&mut Delivery> = self
219            .deliveries
220            .iter_mut()
221            .filter(|(k, d)| {
222                k.block_id == block_id && k.reason == reason && now - d.created_ms < CLAIM_WINDOW_MS && d.created_ms > since
223            })
224            .map(|(_, d)| d)
225            .collect();
226        found.sort_by_key(|d| std::cmp::Reverse(d.created_ms));
227        found
228    }
229
230    /// The fallback's atomic claim on an event. A `Deliver` for an unclaimed
231    /// event records the claim, so the hook's parts for it come back empty.
232    /// Hook deliveries created at or before `since` belong to an earlier event.
233    pub fn claim_fallback(&mut self, block_id: &str, reason: Reason, now: i64, since: i64) -> FallbackClaim {
234        if self.fallback_claimed(block_id, reason) {
235            return FallbackClaim::Deliver;
236        }
237        let hook = self.hook_deliveries_mut(block_id, reason, now, since).into_iter().next().map(|d| d.notice_sent);
238        match hook {
239            Some(true) => FallbackClaim::Skip,
240            Some(false) => FallbackClaim::Pending,
241            None => {
242                self.fallback_claims.insert((block_id.to_string(), reason), now);
243                FallbackClaim::Deliver
244            }
245        }
246    }
247
248    pub fn record_boundary(&mut self, uuid: &str, block_id: &str, now: i64) {
249        if self.boundary_origins.iter().any(|(u, _, _)| u == uuid) {
250            return;
251        }
252        if self.boundary_origins.len() >= BOUNDARY_ORIGINS_MAX {
253            self.boundary_origins.pop_front();
254        }
255        self.boundary_origins.push_back((uuid.to_string(), block_id.to_string(), now));
256    }
257
258    /// A claim naming its compaction boundary. Only the block whose own CLI
259    /// wrote the boundary may deliver: another block of the agent reads it from
260    /// the shared transcript zone, and its CLI did not compact. A boundary no
261    /// stdout here wrote (another srv instance's) is not this block's either.
262    /// A hook delivery from before the block's previous boundary was that
263    /// compaction's, not this one's.
264    ///
265    /// Dated by when this srv read the boundary, like [`Self::claim_event`]:
266    /// a hook delivery finished after it is this compaction's however late the
267    /// claim comes, so a pane that reads the boundary minutes later (a
268    /// reconnect, a remount reading the gap) doesn't deliver the memory twice
269    /// (SPEC_CONTEXT_DELIVERY_2026_09_30.md §9 B2). The hook's first part can
270    /// reach srv before the stdout reader sees the boundary, hence the slack.
271    pub fn claim_boundary(&mut self, block_id: &str, reason: Reason, boundary_uuid: Option<&str>, now: i64) -> FallbackClaim {
272        let mut since = i64::MIN;
273        if let Some(uuid) = boundary_uuid {
274            let Some(idx) = self.boundary_origins.iter().position(|(u, b, _)| u == uuid && b == block_id) else {
275                return FallbackClaim::Foreign;
276            };
277            if let Some((_, _, at)) = self.boundary_origins.range(..idx).rev().find(|(_, b, _)| b == block_id) {
278                since = *at;
279            }
280            let read_at = self.boundary_origins[idx].2;
281            let this_compaction = since.max(read_at.saturating_sub(EVENT_SLACK_MS));
282            let hook_finished = self.completed.get(&(block_id.to_string(), reason)).is_some_and(|at| *at > this_compaction);
283            if hook_finished && !self.fallback_claimed(block_id, reason) {
284                return FallbackClaim::Skip;
285            }
286        }
287        self.claim_fallback(block_id, reason, now, since)
288    }
289
290    /// A claim dated by its event: a fresh session, at its
291    /// `agentmux_session_outcome` frame's `timestamp` (srv's own clock). A
292    /// hook delivery composed after the event and finished is that event's
293    /// however long ago, so a fallback deferred behind the session's first
294    /// turn stands down even past [`CLAIM_WINDOW_MS`]. One from before it
295    /// was an earlier session's and doesn't count.
296    pub fn claim_event(&mut self, block_id: &str, reason: Reason, event_at: i64, now: i64) -> FallbackClaim {
297        let since = event_at.saturating_sub(EVENT_SLACK_MS);
298        let hook_finished = self.completed.get(&(block_id.to_string(), reason)).is_some_and(|at| *at > since);
299        if hook_finished && !self.fallback_claimed(block_id, reason) {
300            return FallbackClaim::Skip;
301        }
302        self.claim_fallback(block_id, reason, now, since)
303    }
304
305    /// Holds a compaction's notice until this block's stdout shows the
306    /// boundary, so the card lands under "Context compacted", not above it.
307    /// `Some(line)` when the boundary was already written: write it now. A
308    /// boundary from up to [`EVENT_SLACK_MS`] before the delivery was composed
309    /// counts, as the hook can be asked just before the reader sees the line.
310    pub fn park_compaction_notice(&mut self, block_id: &str, created_ms: i64, line: String) -> Option<String> {
311        let since = created_ms.saturating_sub(EVENT_SLACK_MS);
312        if self.boundary_origins.iter().any(|(_, b, at)| b == block_id && *at >= since) {
313            return Some(line);
314        }
315        self.parked.entry(block_id.to_string()).or_default().push((created_ms, line));
316        None
317    }
318
319    /// The notices parked for `block_id`, oldest first, taken once. With
320    /// `created_ms`, only that delivery's (the timer's own).
321    pub fn take_parked(&mut self, block_id: &str, created_ms: Option<i64>) -> Vec<String> {
322        let Some(list) = self.parked.get_mut(block_id) else { return Vec::new() };
323        let (taken, kept): (Vec<_>, Vec<_>) = list.drain(..).partition(|(at, _)| created_ms.map_or(true, |c| c == *at));
324        *list = kept;
325        if list.is_empty() {
326            self.parked.remove(block_id);
327        }
328        taken.into_iter().map(|(_, line)| line).collect()
329    }
330
331    /// The hook finished a delivery: its notice went out.
332    pub fn note_completed(&mut self, key: &DeliveryKey, created_ms: i64) {
333        let at = self.completed.entry((key.block_id.clone(), key.reason)).or_insert(created_ms);
334        *at = (*at).max(created_ms);
335    }
336
337    /// The fallback gave up waiting for the hook: it delivers, and the hook's
338    /// unfinished delivery is closed so a late acknowledgement adds no second
339    /// notice.
340    pub fn take_over_from_hook(&mut self, block_id: &str, reason: Reason, now: i64) {
341        for d in self.hook_deliveries_mut(block_id, reason, now, i64::MIN) {
342            d.notice_sent = true;
343        }
344        self.fallback_claims.insert((block_id.to_string(), reason), now);
345    }
346}
347
348pub(crate) static STATE: LazyLock<Mutex<DeliveryState>> = LazyLock::new(|| Mutex::new(DeliveryState::default()));
349
350pub fn state_lock() -> std::sync::MutexGuard<'static, DeliveryState> {
351    STATE.lock().unwrap_or_else(|e| e.into_inner())
352}
353
354/// How long a composed fallback delivery waits for its hidden message. The
355/// frontend sends it right after composing, unless the pane turned busy.
356pub(crate) const FALLBACK_TTL_MS: i64 = 10 * 60_000;
357
358/// A re-delivery srv composed for the frontend's fallback (CD2b).
359#[derive(Debug, Clone)]
360pub struct FallbackDelivery {
361    pub delivery_id: String,
362    pub block_id: String,
363    pub text: String,
364    /// The card, written to the pane when the hidden message is accepted.
365    pub frame: serde_json::Value,
366    pub created_ms: i64,
367}
368
369/// The compaction notices parked for `block_id`, taken once: its stdout
370/// reader writes them after the boundary and the summary that follows it, so
371/// the card lands under "Context compacted" (SPEC_CONTEXT_DELIVERY_2026_09_30.md
372/// §9 C2).
373pub(crate) fn take_parked_notices(block_id: &str) -> Vec<String> {
374    state_lock().take_parked(block_id, None)
375}
376
377/// Records that `block_id`'s CLI wrote the compaction boundary `uuid`. Called
378/// from its stdout reader, before the line reaches any pane.
379pub(crate) fn record_compaction_boundary(block_id: &str, uuid: &str) {
380    state_lock().record_boundary(uuid, block_id, agentmux_common::time::now_ms());
381}