Skip to main content

agentmux_srv/server/
memory_delivery_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The endpoints Claude Code's `SessionStart` hook calls to deliver an agent's
5//! memory (docs/specs/SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2). The
6//! composition and the part rules are `backend::memory::delivery`.
7//!
8//! - `POST /api/v1/agent/memory/session-start/part` — one part. Each of the
9//!   [`HOOK_PARTS`](delivery::HOOK_PARTS) hook commands asks for its
10//!   own part number. They run in parallel, so the first request for a
11//!   (block, session, reason) composes the delivery and caches it, and every
12//!   other part comes from that same composition.
13//! - `POST /api/v1/agent/memory/session-start/ack` — a hook wrote its part to
14//!   Claude. Once every part is acknowledged the delivery is complete: the pane
15//!   gets one persisted `agentmux_memory_injected` frame naming each entry and
16//!   its size (owner decision D11). A part fetched but never acknowledged (the
17//!   hook crashed or timed out) leaves the delivery incomplete, and no notice
18//!   claims otherwise.
19//!
20//! The agent comes from the request's credential (`X-Agent-Token` →
21//! [`Caller::Agent`](super::caller::Caller)): its Personal Memory is that
22//! agent's. Without a token only Global Memory is delivered.
23
24use agentmux_common::tokens::{estimate_tokens, tokens_for_chars};
25
26use axum::extract::State;
27use axum::http::StatusCode;
28use axum::response::{IntoResponse, Response};
29use axum::Json;
30use serde::{Deserialize, Serialize};
31
32use crate::backend::container::credential::ContainerGrant;
33use crate::backend::memory::delivery::{self, Entry, Reason, Tier};
34use crate::backend::memory::fit;
35use crate::backend::memory::index;
36use crate::backend::memory::delivery_state::{
37    state_lock, Delivery, DeliveryKey, EntrySize, FallbackClaim, FallbackDelivery, StartupDetail,
38    PARKED_NOTICE_WAIT, PENDING_POLL, PENDING_WAIT,
39};
40
41use super::caller::Caller;
42use super::AppState;
43
44#[derive(Debug, Deserialize)]
45pub(crate) struct PartRequest {
46    block_id: String,
47    session_id: String,
48    /// The hook's `source` (`startup`, `resume`, `clear`, `compact`, `fork`).
49    source: String,
50    /// 1-based.
51    part: usize,
52    /// The session's working directory and Claude's config dir, from the
53    /// hook (its stdin `cwd`, its env `CLAUDE_CONFIG_DIR`): where the CLI
54    /// looked for its startup files. Empty from an older hook binary.
55    #[serde(default)]
56    cwd: String,
57    #[serde(default)]
58    config_dir: String,
59}
60
61#[derive(Debug, Serialize, PartialEq, Eq)]
62pub(crate) struct PartResponse {
63    /// This part's text, or `None` when there is none to deliver (no memory,
64    /// a source that gets no delivery, or a part number past the last).
65    text: Option<String>,
66    part: usize,
67    of: usize,
68}
69
70#[derive(Debug, Deserialize)]
71pub(crate) struct AckRequest {
72    block_id: String,
73    session_id: String,
74    source: String,
75    part: usize,
76}
77
78/// A container agent asks for its own block's delivery only. Its block is the
79/// grant's (an empty one is filled in); another block's is refused, since the
80/// delivery is cached and composed per block, and a compaction summary is a
81/// block's own conversation.
82fn bind_to_grant(grant: Option<&ContainerGrant>, block_id: &mut String) -> Result<(), Response> {
83    let Some(grant) = grant else { return Ok(()) };
84    if block_id.is_empty() {
85        block_id.clone_from(&grant.block_id);
86    }
87    if *block_id != grant.block_id {
88        tracing::warn!(granted = %grant.block_id, asked = %block_id, "container agent asked for another block's memory delivery: refused");
89        return Err((StatusCode::FORBIDDEN, Json(serde_json::json!({"error": "this container token is for another block"}))).into_response());
90    }
91    Ok(())
92}
93
94/// `POST /api/v1/agent/memory/session-start/part`
95pub(crate) async fn handle_session_start_part(
96    State(state): State<AppState>,
97    caller: Option<axum::Extension<Caller>>,
98    grant: Option<axum::Extension<ContainerGrant>>,
99    Json(mut req): Json<PartRequest>,
100) -> Response {
101    if let Err(refused) = bind_to_grant(grant.as_deref(), &mut req.block_id) {
102        return refused;
103    }
104    session_start_part(state, caller, req, grant.is_some()).await.into_response()
105}
106
107/// `from_container`: the request's `cwd` and `config_dir` are paths inside the
108/// container, so nothing is read from the host for them. The startup files are
109/// the ones in the block's own mounted workspace, as the CLI there read them.
110async fn session_start_part(state: AppState, caller: Option<axum::Extension<Caller>>, req: PartRequest, from_container: bool) -> Json<PartResponse> {
111    let Some(reason) = Reason::from_hook_source(&req.source) else {
112        return Json(PartResponse { text: None, part: req.part, of: 0 });
113    };
114    let key = DeliveryKey { block_id: req.block_id.clone(), session_id: req.session_id.clone(), reason };
115    let now = agentmux_common::time::now_ms();
116
117    let cached = {
118        let mut st = state_lock();
119        st.prune(now);
120        // The frontend's fallback already delivered this event: stand down.
121        if st.fallback_claimed(&req.block_id, reason) {
122            tracing::info!(block_id = %req.block_id, reason = reason.as_str(), part = req.part, "memory delivery: part stood down, the fallback claimed the event");
123            return Json(PartResponse { text: None, part: req.part, of: 0 });
124        }
125        if st.composed_nothing.contains_key(&key) {
126            return Json(PartResponse { text: None, part: req.part, of: 0 });
127        }
128        st.deliveries.get(&key).cloned()
129    };
130    let delivery = match cached {
131        Some(d) => d,
132        None => {
133            let gate = state_lock().compose_gates.entry(key.clone()).or_default().clone();
134            let _composing = gate.lock().await;
135            // Dropped on every way out, a cancelled request included, so the
136            // gate never outlives the part that took it.
137            let _gate_entry = GateEntry(key.clone());
138            // A part that held the gate before this one may have composed it, or
139            // the fallback may have claimed the event while this one waited.
140            let (composed_meanwhile, claimed, nothing_meanwhile) = {
141                let st = state_lock();
142                (st.deliveries.get(&key).cloned(), st.fallback_claimed(&req.block_id, reason), st.composed_nothing.contains_key(&key))
143            };
144            if nothing_meanwhile {
145                return Json(PartResponse { text: None, part: req.part, of: 0 });
146            }
147            if claimed {
148                tracing::info!(block_id = %req.block_id, reason = reason.as_str(), part = req.part, "memory delivery: part stood down, the fallback claimed the event");
149                return Json(PartResponse { text: None, part: req.part, of: 0 });
150            }
151            if let Some(d) = composed_meanwhile {
152                return finish_part(&state, &key, d, req.part);
153            }
154            let uid = caller.as_ref().and_then(|c| c.uid()).map(str::to_string);
155            let launch = if from_container { LaunchDirs::of_container_block(&state, &req.block_id) } else { LaunchDirs::from_request(&req) };
156            let composed = {
157                let state = state.clone();
158                let block_id = req.block_id.clone();
159                tokio::task::spawn_blocking(move || {
160                    compose_delivery(&state, &block_id, uid.as_deref(), reason, launch.as_ref(), now)
161                })
162                    .await
163            };
164            // A failed compose is not "nothing to deliver": the next part tries again.
165            let composed = match composed {
166                Ok(composed) => composed,
167                Err(e) => {
168                    tracing::warn!(error = %e, "memory delivery: composing failed");
169                    return Json(PartResponse { text: None, part: req.part, of: 0 });
170                }
171            };
172            let Some(composed) = composed else {
173                state_lock().composed_nothing.insert(key.clone(), now);
174                tracing::info!(block_id = %req.block_id, session_id = %req.session_id, reason = reason.as_str(), part = req.part, cwd_known = !req.cwd.is_empty(), "memory delivery: nothing to deliver for this session start");
175                return Json(PartResponse { text: None, part: req.part, of: 0 });
176            };
177            tracing::info!(
178                block_id = %req.block_id, session_id = %req.session_id, reason = reason.as_str(),
179                parts = composed.parts.len(), items = composed.entries.len(), "memory delivery: composed"
180            );
181            // A concurrent part may have composed first: keep that one, so
182            // every part of this session start is from the same composition.
183            // And the fallback may have claimed the event meanwhile.
184            let mut st = state_lock();
185            if st.fallback_claimed(&req.block_id, reason) {
186                return Json(PartResponse { text: None, part: req.part, of: 0 });
187            }
188            st.deliveries.entry(key.clone()).or_insert(composed).clone()
189        }
190    };
191    finish_part(&state, &key, delivery, req.part)
192}
193
194/// Removes a delivery's compose gate when the part that took it is done.
195struct GateEntry(DeliveryKey);
196
197impl Drop for GateEntry {
198    fn drop(&mut self) {
199        state_lock().compose_gates.remove(&self.0);
200    }
201}
202
203/// The reply for one part of a composed delivery. A delivery with nothing for
204/// the hook to carry still gets its card, on the first part asked for.
205fn finish_part(state: &AppState, key: &DeliveryKey, delivery: Delivery, part: usize) -> Json<PartResponse> {
206    if delivery.parts.is_empty() {
207        send_partless_notice(state, key);
208    }
209    Json(part_response(&delivery, part))
210}
211
212/// A delivery with nothing for the hook to carry (its Global Memory is in the
213/// startup file, and there's no Personal Memory) still has a card: written on
214/// the first part request, exactly once, since no part will be acknowledged.
215fn send_partless_notice(state: &AppState, key: &DeliveryKey) {
216    let frame = {
217        let mut st = state_lock();
218        match st.deliveries.get_mut(key) {
219            Some(d) if d.parts.is_empty() && !d.notice_sent && !d.entries.is_empty() => {
220                d.notice_sent = true;
221                let (frame, created_ms) = (notice_frame(key, d), d.created_ms);
222                st.note_completed(key, created_ms);
223                frame
224            }
225            _ => return,
226        }
227    };
228    crate::backend::cli_notice::append_to_pane(&state.broker, &state.filestore, &state.mstore, &key.block_id, &frame);
229}
230
231/// `POST /api/v1/agent/memory/session-start/ack`
232pub(crate) async fn handle_session_start_ack(
233    State(state): State<AppState>,
234    grant: Option<axum::Extension<ContainerGrant>>,
235    Json(mut req): Json<AckRequest>,
236) -> Response {
237    if let Err(refused) = bind_to_grant(grant.as_deref(), &mut req.block_id) {
238        return refused;
239    }
240    session_start_ack(state, req).await.into_response()
241}
242
243async fn session_start_ack(state: AppState, req: AckRequest) -> Json<serde_json::Value> {
244    let Some(reason) = Reason::from_hook_source(&req.source) else {
245        return Json(serde_json::json!({ "complete": false }));
246    };
247    let key = DeliveryKey { block_id: req.block_id.clone(), session_id: req.session_id.clone(), reason };
248    let (complete, write_now, parked_at) = {
249        let mut st = state_lock();
250        let done = st.deliveries.get_mut(&key).and_then(|d| acknowledge(d, req.part).then(|| (notice_frame(&key, d), d.created_ms)));
251        match done {
252            None => (false, None, None),
253            Some((frame, created_ms)) => {
254                st.note_completed(&key, created_ms);
255                let line = frame.to_string();
256                if reason == Reason::Compact {
257                    let now = st.park_compaction_notice(&req.block_id, created_ms, line);
258                    let parked = now.is_none().then_some(created_ms);
259                    (true, now, parked)
260                } else {
261                    (true, Some(line), None)
262                }
263            }
264        }
265    };
266    if complete {
267        let tokens = agentmux_srv_core::backend::context_reading::tokens_now(&req.block_id);
268        tracing::info!(block_id = %req.block_id, reason = reason.as_str(), tokens, parked = parked_at.is_some(), "memory delivery: complete, notice sent");
269    }
270    if let Some(line) = write_now {
271        append_notice(&state, &req.block_id, &line);
272    }
273    // The boundary hasn't been written yet: the stdout reader writes the card
274    // after it. If no boundary comes, write it anyway.
275    if let Some(created_ms) = parked_at {
276        let block_id = req.block_id.clone();
277        tokio::spawn(async move {
278            tokio::time::sleep(PARKED_NOTICE_WAIT).await;
279            let left = state_lock().take_parked(&block_id, Some(created_ms));
280            for line in left {
281                tracing::warn!(block_id = %block_id, "memory delivery: no compaction boundary came; card written without it");
282                append_notice(&state, &block_id, &line);
283            }
284        });
285    }
286    Json(serde_json::json!({ "complete": complete }))
287}
288
289/// Appends one notice line to the block's output and its transcript zone.
290fn append_notice(state: &AppState, block_id: &str, line: &str) {
291    crate::backend::cli_notice::append_line_to_pane(&state.broker, &state.filestore, &state.mstore, block_id, line);
292}
293
294/// The event a frontend reinjection reason stands for: a compaction, or a
295/// fresh session (a spawn without `--resume`, whose hook `source` is
296/// `startup`). `None` for anything else.
297fn reason_for_fallback(reason: &str) -> Option<Reason> {
298    match reason {
299        "compaction" => Some(Reason::Compact),
300        "fresh_session" => Some(Reason::Startup),
301        _ => None,
302    }
303}
304
305/// Whether the frontend's hidden-reinjection fallback should deliver this
306/// event (`true`) or stand down because the `SessionStart` hook delivered it
307/// (`false`). Waits out a hook delivery still in flight for up to
308/// [`PENDING_WAIT`], then lets the fallback deliver, so a hook that died
309/// part-way never leaves the agent without its memory. With a
310/// `boundary_uuid`, only the block whose CLI compacted can deliver. With
311/// `event_at_ms` (a fresh session's time), the hook's delivery for that
312/// session counts however late the claim comes.
313pub(crate) async fn claim_fallback(block_id: &str, reason: &str, boundary_uuid: Option<&str>, event_at_ms: Option<i64>) -> ClaimResult {
314    let Some(reason) = reason_for_fallback(reason) else { return ClaimResult { deliver: true, foreign: false } };
315    let deadline = tokio::time::Instant::now() + PENDING_WAIT;
316    let boundary_uuid = boundary_uuid.filter(|u| !u.is_empty());
317    loop {
318        let now = agentmux_common::time::now_ms();
319        let claim = {
320            let mut st = state_lock();
321            st.prune(now);
322            match (boundary_uuid, event_at_ms) {
323                (None, Some(event_at)) => st.claim_event(block_id, reason, event_at, now),
324                _ => st.claim_boundary(block_id, reason, boundary_uuid, now),
325            }
326        };
327        match claim {
328            FallbackClaim::Deliver => return ClaimResult { deliver: true, foreign: false },
329            FallbackClaim::Skip => {
330                tracing::info!(block_id, reason = reason.as_str(), "memory delivery: the hook delivered; fallback stands down");
331                return ClaimResult { deliver: false, foreign: false };
332            }
333            FallbackClaim::Foreign => {
334                tracing::info!(block_id, reason = reason.as_str(), "memory delivery: not this block's compaction; fallback stands down");
335                return ClaimResult { deliver: false, foreign: true };
336            }
337            FallbackClaim::Pending if tokio::time::Instant::now() >= deadline => {
338                tracing::warn!(block_id, reason = reason.as_str(), "memory delivery: hook still unfinished; fallback delivers instead");
339                state_lock().take_over_from_hook(block_id, reason, agentmux_common::time::now_ms());
340                return ClaimResult { deliver: true, foreign: false };
341            }
342            FallbackClaim::Pending => tokio::time::sleep(PENDING_POLL).await,
343        }
344    }
345}
346
347/// What a fallback's claim found: `deliver`, or stand down because the hook
348/// delivered, or because the event was another block's (`foreign`).
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350pub(crate) struct ClaimResult {
351    pub deliver: bool,
352    pub foreign: bool,
353}
354
355/// Registers `memorydelivery:claim_fallback` — the frontend's hidden memory
356/// reinjection asks it right before it would fire — and
357/// `memorydelivery:compose`, which composes what it sends.
358pub(crate) fn register_memory_delivery_handlers(
359    engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>,
360    state: &AppState,
361) {
362    use crate::backend::rpc_types::{
363        CommandMemoryDeliveryClaimFallbackData, CommandMemoryDeliveryComposeData, MemoryDeliveryClaimFallbackResult,
364        MemoryDeliveryComposeResult, COMMAND_MEMORY_DELIVERY_CLAIM_FALLBACK, COMMAND_MEMORY_DELIVERY_COMPOSE,
365    };
366    engine.register_typed(
367        COMMAND_MEMORY_DELIVERY_CLAIM_FALLBACK,
368        |req: CommandMemoryDeliveryClaimFallbackData, _ctx| async move {
369            Ok::<_, String>({
370                let r = claim_fallback(&req.block_id, &req.reason, req.boundary_uuid.as_deref(), req.event_at_ms).await;
371                MemoryDeliveryClaimFallbackResult { deliver: r.deliver, foreign: r.foreign.then_some(true) }
372            })
373        },
374    );
375    let state = state.clone();
376    engine.register_typed(COMMAND_MEMORY_DELIVERY_COMPOSE, move |req: CommandMemoryDeliveryComposeData, _ctx| {
377        let state = state.clone();
378        async move {
379            let now = agentmux_common::time::now_ms();
380            if req.catch_up.unwrap_or(false) {
381                let kind = delivery::CatchUpKind::from_wire(&req.reason)
382                    .ok_or_else(|| format!("memorydelivery:compose: unknown reason {:?}", req.reason))?;
383                let memory_reason = kind.memory_reason().filter(|_| req.memory.unwrap_or(true));
384                let block_id = req.block_id.clone();
385                let composed = match memory_reason {
386                    Some(reason) => tokio::task::spawn_blocking(move || compose_fallback_delivery(&state, &block_id, reason, now))
387                        .await
388                        .map_err(|e| format!("memorydelivery:compose: {e}"))?,
389                    None => None,
390                };
391                return Ok::<_, String>(match composed {
392                    Some(mut f) => {
393                        f.text = delivery::compose_catch_up(kind, Some(&f.text));
394                        let reply = MemoryDeliveryComposeResult {
395                            delivery_id: Some(f.delivery_id.clone()),
396                            text: Some(f.text.clone()),
397                            frame: Some(f.frame.clone()),
398                        };
399                        let mut st = state_lock();
400                        st.prune(now);
401                        st.fallbacks.insert(f.delivery_id.clone(), f);
402                        reply
403                    }
404                    // No memory to deliver (the hook did, or the phase has
405                    // none): the catch-up block alone, and no card.
406                    None => MemoryDeliveryComposeResult {
407                        delivery_id: None,
408                        text: Some(delivery::compose_catch_up(kind, None)),
409                        frame: None,
410                    },
411                });
412            }
413            let reason = delivery::FallbackReason::from_wire(&req.reason)
414                .ok_or_else(|| format!("memorydelivery:compose: unknown reason {:?}", req.reason))?;
415            let composed = tokio::task::spawn_blocking(move || compose_fallback_delivery(&state, &req.block_id, reason, now))
416                .await
417                .map_err(|e| format!("memorydelivery:compose: {e}"))?;
418            Ok::<_, String>(match composed {
419                Some(f) => {
420                    let reply = MemoryDeliveryComposeResult {
421                        delivery_id: Some(f.delivery_id.clone()),
422                        text: Some(f.text.clone()),
423                        frame: Some(f.frame.clone()),
424                    };
425                    let mut st = state_lock();
426                    st.prune(now);
427                    st.fallbacks.insert(f.delivery_id.clone(), f);
428                    reply
429                }
430                None => MemoryDeliveryComposeResult::default(),
431            })
432        }
433    });
434}
435
436/// Composes the fallback's hidden message from the same memory the hook
437/// delivers (`global_entries`, `personal_entries`), and the card that will
438/// stand for it. `None` when there is no memory.
439fn compose_fallback_delivery(
440    state: &AppState,
441    block_id: &str,
442    reason: delivery::FallbackReason,
443    now: i64,
444) -> Option<FallbackDelivery> {
445    let global = global_entries(state, block_id);
446    let uid = crate::backend::spawn_env::block_identity::persisted_agent_identity(&state.mstore, block_id).map(|i| i.uid);
447    // A new session or a compaction whose startup file carries a current Global section doesn't get it a
448    // second time, as the hook doesn't send it (LC3); only the sections newer than the file are sent.
449    let files = uid.as_deref().map(latest_startup_files).unwrap_or_default();
450    let (newer, carry) = global_against_startup_files(&files, &global);
451    let personal = uid.as_deref().map(personal_entries).unwrap_or_default();
452    let fitted = fit::fit(newer.iter().cloned().chain(personal).collect(), fit::NO_CAP, 0, false, &modified_ms_of, now);
453    let entries = fitted.kept.clone();
454    let tool_only = block_is_container(state, block_id);
455    let layout = delivery::Layout {
456        carry,
457        index: index::IndexPlan { files: &fitted.indexed, over_limit: &fitted.over_limit, always: fitted.always, tool_only },
458        tail: fitted.tail.as_deref(),
459    };
460    let composed = delivery::compose_fallback_layout(&entries, reason, &layout)?;
461    let mut items = carried_items(&global, &newer);
462    items.extend(delivery_items(&entries, &composed, composed.text.chars().count()));
463    items.extend(indexed_items(&fitted, tool_only));
464    items.extend(fitted.skipped.iter().map(global_left_out_item));
465    // A compaction's running summary rides along: srv's input handler appends
466    // it to this same message (`continuity_state::with_state_after_compaction`).
467    let summary = (reason == delivery::FallbackReason::Compaction)
468        .then(|| crate::backend::continuity_state::running_summary_section(&state.mstore, block_id))
469        .flatten();
470    if let Some(summary) = &summary {
471        let (size, tokens) = (summary.len(), estimate_tokens(summary) as usize);
472        items.push(EntrySize::running_summary(size, tokens, "full", size, tokens));
473    }
474    let delivery_id = format!("fb-{}", uuid::Uuid::new_v4());
475    let frame = fallback_frame(&delivery_id, reason, &items, summary.as_ref().map_or(0, |s| s.len()), now);
476    Some(FallbackDelivery { delivery_id, block_id: block_id.to_string(), text: composed.text, frame, created_ms: now })
477}
478
479/// The card for a fallback re-delivery: the hook notice's shape, under the
480/// delivery's own id. `fallback: true` tells replay that the hidden message
481/// right after it is this delivery's echo, not a second one.
482fn fallback_frame(
483    delivery_id: &str,
484    reason: delivery::FallbackReason,
485    entries: &[EntrySize],
486    summary_bytes: usize,
487    now: i64,
488) -> serde_json::Value {
489    card_frame(
490        format!("memory-injected-{delivery_id}"),
491        match reason {
492            delivery::FallbackReason::Compaction => "compact",
493            delivery::FallbackReason::FreshSession => "resume_fresh",
494        },
495        entries,
496        summary_bytes,
497        now,
498        serde_json::json!({ "fallback": true, "delivery_id": delivery_id }),
499    )
500}
501
502/// The `agentmux_memory_injected` frame both delivery routes write: the
503/// fields the card reads, then `extra` (the route's own: the hook's session
504/// and part count, the fallback's delivery id).
505fn card_frame(
506    id: String,
507    reason: &str,
508    entries: &[EntrySize],
509    summary_bytes: usize,
510    at_ms: i64,
511    extra: serde_json::Value,
512) -> serde_json::Value {
513    let mut frame = serde_json::json!({
514        "type": "system",
515        "subtype": "agentmux_memory_injected",
516        "id": id,
517        "reason": reason,
518        "entries": entries,
519        "summary_bytes": summary_bytes,
520        "timestamp": chrono::DateTime::from_timestamp_millis(at_ms).unwrap_or_default().to_rfc3339(),
521    });
522    if let (Some(fields), serde_json::Value::Object(more)) = (frame.as_object_mut(), extra) {
523        fields.extend(more);
524    }
525    frame
526}
527
528/// The card of the fallback delivery `delivery_id`, taken once, when its
529/// hidden message reaches srv. `None` for an unknown or expired id, or one
530/// composed for another block.
531pub(crate) fn take_fallback_frame(block_id: &str, delivery_id: &str) -> Option<serde_json::Value> {
532    let mut st = state_lock();
533    st.prune(agentmux_common::time::now_ms());
534    match st.fallbacks.remove(delivery_id) {
535        Some(f) if f.block_id == block_id => Some(f.frame),
536        Some(f) => {
537            tracing::warn!(block_id, delivery_block = %f.block_id, "memory delivery: a fallback delivery id from another block");
538            None
539        }
540        None => None,
541    }
542}
543
544/// A Global Memory entry that reached the agent through its startup file:
545/// listed in the card, sized 0 (the file's own row counts it).
546fn in_startup_file_item(e: &Entry) -> EntrySize {
547    EntrySize {
548        label: e.label.clone(),
549        source: "global",
550        size_bytes: 0,
551        tokens: 0,
552        kind: "global_memory",
553        name: e.name.clone(),
554        tier: Some(if e.system { "system" } else { "workspace" }),
555        bundle_id: e.bundle_id.clone(),
556        path: None,
557        delivered: "full",
558        source_size_bytes: e.text.len(),
559        source_tokens: estimate_tokens(&e.text) as usize,
560        startup: None,
561        via: Some("startup_file"),
562        reason: None,
563    }
564}
565
566/// Where a session's CLI looked for its startup files.
567#[derive(Debug, Clone)]
568struct LaunchDirs {
569    cwd: std::path::PathBuf,
570    config_dir: Option<std::path::PathBuf>,
571    /// A container agent: only the mounted workspace's own startup files count,
572    /// not the host's parent folders or the user's host `~/.claude`.
573    workspace_only: bool,
574}
575
576impl LaunchDirs {
577    fn from_request(req: &PartRequest) -> Option<Self> {
578        let cwd = req.cwd.trim();
579        (!cwd.is_empty()).then(|| Self {
580            cwd: cwd.into(),
581            config_dir: Some(req.config_dir.trim()).filter(|c| !c.is_empty()).map(Into::into),
582            workspace_only: false,
583        })
584    }
585
586    /// A container's: the workspace srv mounted for the block, which is where its
587    /// CLI reads the startup files. The paths the container reports are its own.
588    fn of_container_block(state: &AppState, block_id: &str) -> Option<Self> {
589        let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
590        let cwd = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
591        (!cwd.trim().is_empty()).then(|| Self { cwd: cwd.trim().into(), config_dir: None, workspace_only: true })
592    }
593}
594
595/// The files the CLI read by itself at session start.
596fn startup_files(launch: &LaunchDirs) -> Vec<crate::backend::startup_files::StartupFile> {
597    if launch.workspace_only {
598        return crate::backend::startup_files::workspace_startup_files(&launch.cwd);
599    }
600    let home = dirs::home_dir();
601    crate::backend::startup_files::host_startup_files(&launch.cwd, launch.config_dir.as_deref(), home.as_deref())
602}
603
604/// Which current Global sections the CLI already got from a startup file: one AgentMux wrote that holds
605/// the section byte for byte. Returns the sections newer than the files (absent, or held in an older form,
606/// which the CLI never saw in its current form), and how much of the Global Memory the files carry. A foreign
607/// file doesn't count, or the hook would drop current entries the agent never saw.
608fn global_against_startup_files(files: &[crate::backend::startup_files::StartupFile], global: &[Entry]) -> (Vec<Entry>, delivery::StartupCarry) {
609    let owned: Vec<&crate::backend::startup_files::StartupFile> =
610        files.iter().filter(|f| f.owner == crate::backend::startup_files::Owner::Agentmux).collect();
611    let newer: Vec<Entry> = global.iter().filter(|e| !owned.iter().any(|f| f.text.contains(&e.text))).cloned().collect();
612    let carry = if global.is_empty() || newer.len() == global.len() {
613        delivery::StartupCarry::None
614    } else if newer.is_empty() {
615        delivery::StartupCarry::All
616    } else {
617        delivery::StartupCarry::Partly
618    };
619    (newer, carry)
620}
621
622/// The startup files of the agent's latest Claude spawn, from where its continuity segment says the CLI
623/// started: the fallback has no hook request to read them from.
624fn latest_startup_files(agent_uid: &str) -> Vec<crate::backend::startup_files::StartupFile> {
625    let Some(fs) = crate::backend::agent_session::global_transcript_store() else { return Vec::new() };
626    let Some(latest) = crate::backend::continuity_segments::segments(fs.as_ref(), agent_uid)
627        .into_iter()
628        .filter(|s| s.start.provider == "claude" && !s.start.cwd.is_empty())
629        .max_by_key(|s| s.start.started_at_ms)
630    else {
631        return Vec::new();
632    };
633    let launch = LaunchDirs { cwd: latest.start.cwd.into(), config_dir: latest.start.config_dir.filter(|c| !c.is_empty()).map(Into::into), workspace_only: false };
634    startup_files(&launch)
635}
636
637/// Whether the pane is a container agent's: its host folders aren't readable from inside, so an index line
638/// names the `Memory` tool's form only.
639fn block_is_container(state: &AppState, block_id: &str) -> bool {
640    state
641        .mstore
642        .get::<crate::backend::obj::Block>(block_id)
643        .ok()
644        .flatten()
645        .is_some_and(|b| crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&b.meta).is_container())
646}
647
648/// The card's rows for the Global entries the startup file carried (every one that is not in `newer`): listed,
649/// sized 0 (the file's row counts them).
650fn carried_items(global: &[Entry], newer: &[Entry]) -> Vec<EntrySize> {
651    global.iter().filter(|g| !newer.iter().any(|n| n.text == g.text)).map(in_startup_file_item).collect()
652}
653
654fn startup_items_of(files: Vec<crate::backend::startup_files::StartupFile>) -> Vec<EntrySize> {
655    files
656        .into_iter()
657        .map(|f| {
658            let (size_bytes, tokens) = (f.text.len(), estimate_tokens(&f.text) as usize);
659            EntrySize {
660                label: f.name.clone(),
661                source: "startup",
662                size_bytes,
663                tokens,
664                kind: "startup_file",
665                name: f.name,
666                tier: None,
667                bundle_id: None,
668                path: Some(f.path.to_string_lossy().into_owned()),
669                delivered: "full",
670                source_size_bytes: size_bytes,
671                source_tokens: tokens,
672                startup: Some(StartupDetail { role: f.role, owner: f.owner.as_str(), count: f.count, contains: f.contains }),
673                via: None,
674                reason: None,
675            }
676        })
677        .collect()
678}
679
680/// Reads the memory and composes the delivery. `None` when there is nothing
681/// to deliver. A new session's delivery also lists the startup files the CLI
682/// loaded from `launch` (`startup_items_of`), ahead of the memory items.
683fn compose_delivery(
684    state: &AppState,
685    block_id: &str,
686    agent_uid: Option<&str>,
687    reason: Reason,
688    launch: Option<&LaunchDirs>,
689    now: i64,
690) -> Option<Delivery> {
691    // The startup files the CLI read: they decide which Global sections the hook leaves out, on every reason
692    // (a compaction and /clear reload them too). Only a new session lists them on the card.
693    let files = launch.map(startup_files).unwrap_or_default();
694    let global = global_entries(state, block_id);
695    let (newer, carry) = global_against_startup_files(&files, &global);
696    let mut items = if reason == Reason::Startup { startup_items_of(files) } else { Vec::new() };
697    let personal = agent_uid.map(personal_entries).unwrap_or_default();
698    items.extend(carried_items(&global, &newer));
699    let mut entries = newer;
700    entries.extend(personal);
701    let summary = (reason == Reason::Compact)
702        .then(|| crate::backend::continuity_state::running_summary_section(&state.mstore, block_id))
703        .flatten();
704    // Nothing left for the hook to carry is still a delivery when there are
705    // startup items to show: it has no parts, and its card goes out at once.
706    let tool_only = launch.is_some_and(|l| l.workspace_only) || block_is_container(state, block_id);
707    let (parts, delivered) = match fit_and_compose(entries, summary.as_deref(), reason, carry, tool_only, &modified_ms_of, now) {
708        Some((fitted, composed, parts, delivered_chars)) => {
709            let mut delivered = delivery_items(&fitted.kept, &composed, delivered_chars);
710            delivered.extend(indexed_items(&fitted, tool_only));
711            delivered.extend(fitted.skipped.iter().map(global_left_out_item));
712            (parts, delivered)
713        }
714        None if !items.is_empty() => (Vec::new(), Vec::new()),
715        None => return None,
716    };
717    let acked = vec![false; parts.len()];
718    items.extend(delivered);
719    Some(Delivery {
720        entries: items,
721        summary_bytes: summary.map_or(0, |s| s.len()),
722        parts,
723        acked,
724        created_ms: now,
725        notice_sent: false,
726    })
727}
728
729/// Global Memory as the startup file carries it — its sections, Operator
730/// Config first (`globalmemory:sections`, P1).
731fn global_entries(state: &AppState, block_id: &str) -> Vec<Entry> {
732    // The same entries the pane's startup file got: Operator Config targeted
733    // at another agent kind is left out.
734    let bundles = crate::backend::operator_config_seed::global_bundles_for_agent(
735        state.id_store.bundle_list_global().unwrap_or_default(),
736        &crate::backend::operator_config_seed::agent_mode_of_block(&state.mstore, block_id),
737    );
738    crate::backend::storage::global_bundle_sections(&bundles)
739        .into_iter()
740        .map(|s| Entry {
741            label: format!("{} {}", if s.is_system { "[AgentMux System]" } else { "[Workspace]" }, s.name),
742            tier: Tier::Global,
743            text: s.text,
744            name: s.name,
745            system: s.is_system,
746            bundle_id: Some(s.id),
747            path: None,
748        })
749        .collect()
750}
751
752/// The agent's Personal Memory files from its latest spawn's memory folder,
753/// by name, without the `MEMORY.md` index (the CLI's own table of contents).
754fn personal_entries(agent_uid: &str) -> Vec<Entry> {
755    let Some(dir) = crate::server::native_memory_handlers::memory_dir_from_spawn(agent_uid) else { return Vec::new() };
756    personal_entries_in(&dir)
757}
758
759fn personal_entries_in(dir: &std::path::Path) -> Vec<Entry> {
760    let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };
761    let mut files: Vec<(String, std::path::PathBuf)> = read
762        .flatten()
763        .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
764        .filter_map(|e| Some((e.file_name().into_string().ok()?, e.path())))
765        .filter(|(name, _)| name.ends_with(".md") && name != "MEMORY.md")
766        .collect();
767    files.sort();
768    let mut entries: Vec<Entry> = files
769        .into_iter()
770        .filter_map(|(name, path)| {
771            let text = std::fs::read_to_string(&path).ok()?;
772            (!text.trim().is_empty()).then_some(Entry {
773                label: name.clone(),
774                tier: Tier::Personal,
775                text,
776                name,
777                system: false,
778                bundle_id: None,
779                path: Some(path.to_string_lossy().into_owned()),
780            })
781        })
782        .collect();
783    // Most recently modified first (the sort is stable, so equal times keep name order), so what a cut
784    // delivery drops is the oldest, not whatever sorts last by name.
785    entries.sort_by_cached_key(|e| std::cmp::Reverse(modified_ms_of(e).unwrap_or(0)));
786    entries
787}
788
789/// The delivery's entries sorted by what each gets (`fit::fit`), composed and split the way the hooks will
790/// carry them. The character budget is only a guess at how the parts break at line ends, so when the real
791/// split still cuts (the notes at the end are what can tip it), a little more room is kept back and the fit is
792/// redone, so the reserved summary and the notes are never the part that is lost.
793fn fit_and_compose(
794    entries: Vec<Entry>,
795    summary: Option<&str>,
796    reason: Reason,
797    carry: delivery::StartupCarry,
798    tool_only: bool,
799    modified_ms: &dyn Fn(&Entry) -> Option<i64>,
800    now_ms: i64,
801) -> Option<(fit::Fitted, delivery::Composed, Vec<String>, usize)> {
802    const STEP: usize = 2_000;
803    const LAST: usize = 40_000;
804    let reserve = summary.map_or(0, |s| s.chars().count());
805    let mut slack = 0;
806    loop {
807        let fitted = fit::fit(entries.clone(), delivery::HOOK_PARTS * delivery::MAX_PART_CHARS, reserve + slack, reason == Reason::Compact, modified_ms, now_ms);
808        let layout = delivery::Layout {
809            carry,
810            index: index::IndexPlan { files: &fitted.indexed, over_limit: &fitted.over_limit, always: fitted.always, tool_only },
811            tail: fitted.tail.as_deref(),
812        };
813        let composed = delivery::compose_items_tail(&fitted.kept, reason, summary, &layout)?;
814        let (parts, delivered_chars) = delivery::split_into_parts_counted(&composed.text, delivery::MAX_PART_CHARS, delivery::HOOK_PARTS);
815        if delivered_chars >= composed.text.chars().count() || slack >= LAST {
816            return Some((fitted, composed, parts, delivered_chars));
817        }
818        slack += STEP;
819    }
820}
821
822/// When a Personal Memory file was last modified, in Unix ms: its `modified` frontmatter when it has one that
823/// parses, else the file's mtime.
824fn modified_ms_of(e: &Entry) -> Option<i64> {
825    if let Some(v) = fit::frontmatter_value(&e.text, "modified") {
826        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&v) {
827            return Some(t.timestamp_millis());
828        }
829    }
830    let mtime = std::fs::metadata(e.path.as_deref()?).ok()?.modified().ok()?;
831    i64::try_from(mtime.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis()).ok()
832}
833
834/// The card's rows for the Personal files listed in the index: each sized by its index line, not "0 B".
835fn indexed_items(fitted: &fit::Fitted, tool_only: bool) -> Vec<EntrySize> {
836    let plan = index::IndexPlan { files: &fitted.indexed, over_limit: &fitted.over_limit, always: fitted.always, tool_only };
837    let lines = index::lines(&plan);
838    fitted
839        .indexed
840        .iter()
841        .map(|e| {
842            let listed = lines.iter().find(|(n, _)| *n == e.name);
843            let line = listed.map_or("", |(_, l)| l.as_str());
844            // Past the index's budget a file has no line: the pane says so, and the delivery counted it.
845            let (delivered, reason) = match listed {
846                Some(_) => (
847                    delivery::Delivered::Indexed,
848                    fitted.over_limit.contains(&e.name).then(|| "marked always, over the limit of 5 files and 6,000 characters".to_string()),
849                ),
850                None => (delivery::Delivered::Omitted, Some("too many files for the index; list them with the Memory tool (action list, scope personal)".to_string())),
851            };
852            EntrySize {
853                label: e.label.clone(),
854                source: e.tier.as_str(),
855                size_bytes: line.len(),
856                tokens: estimate_tokens(line) as usize,
857                kind: "personal_memory",
858                name: e.name.clone(),
859                tier: None,
860                bundle_id: e.bundle_id.clone(),
861                path: e.path.clone(),
862                delivered: delivered.as_str(),
863                source_size_bytes: e.text.len(),
864                source_tokens: estimate_tokens(&e.text) as usize,
865                startup: None,
866                via: None,
867                reason,
868            }
869        })
870        .collect()
871}
872
873/// The card's row for a Global Memory entry left out of the delivery whole because it was full.
874fn global_left_out_item(e: &Entry) -> EntrySize {
875    EntrySize {
876        label: e.label.clone(),
877        source: e.tier.as_str(),
878        size_bytes: 0,
879        tokens: 0,
880        kind: "global_memory",
881        name: e.name.clone(),
882        tier: Some(if e.system { "system" } else { "workspace" }),
883        bundle_id: e.bundle_id.clone(),
884        path: None,
885        delivered: delivery::Delivered::Omitted.as_str(),
886        source_size_bytes: e.text.len(),
887        source_tokens: estimate_tokens(&e.text) as usize,
888        startup: None,
889        via: None,
890        reason: Some("the delivery was full; its name and how to read it were in the delivery".to_string()),
891    }
892}
893
894/// The notice's items, in delivery order, sized by what the parts carried.
895fn delivery_items(entries: &[Entry], composed: &delivery::Composed, delivered_chars: usize) -> Vec<EntrySize> {
896    let chars: Vec<char> = composed.text.chars().collect();
897    composed
898        .spans
899        .iter()
900        .map(|span| {
901            let delivered = delivery::Delivered::of(span, delivered_chars);
902            let slice: String = chars[span.start..span.end.min(delivered_chars).max(span.start)].iter().collect();
903            let (size_bytes, tokens) = (slice.len(), estimate_tokens(&slice) as usize);
904            let whole: String = chars[span.start..span.end].iter().collect();
905            let (source_size_bytes, source_tokens) = (whole.len(), tokens_for_chars((span.end - span.start) as u64) as usize);
906            match span.entry.map(|i| &entries[i]) {
907                Some(e) => EntrySize {
908                    label: e.label.clone(),
909                    source: e.tier.as_str(),
910                    size_bytes,
911                    tokens,
912                    kind: match e.tier {
913                        Tier::Global => "global_memory",
914                        Tier::Personal => "personal_memory",
915                    },
916                    name: e.name.clone(),
917                    tier: (e.tier == Tier::Global).then_some(if e.system { "system" } else { "workspace" }),
918                    bundle_id: e.bundle_id.clone(),
919                    path: e.path.clone(),
920                    delivered: delivered.as_str(),
921                    source_size_bytes,
922                    source_tokens,
923                    startup: None,
924                    via: None,
925                    reason: None,
926                },
927                None => EntrySize::running_summary(size_bytes, tokens, delivered.as_str(), source_size_bytes, source_tokens),
928            }
929        })
930        .collect()
931}
932
933fn part_response(d: &Delivery, part: usize) -> PartResponse {
934    let text = part.checked_sub(1).and_then(|i| d.parts.get(i)).cloned();
935    PartResponse { text, part, of: d.parts.len() }
936}
937
938/// Marks `part` written. True exactly once: when this makes every part
939/// written and no notice has gone out yet.
940fn acknowledge(d: &mut Delivery, part: usize) -> bool {
941    if let Some(slot) = part.checked_sub(1).and_then(|i| d.acked.get_mut(i)) {
942        *slot = true;
943    }
944    if d.notice_sent || !d.acked.iter().all(|a| *a) {
945        return false;
946    }
947    d.notice_sent = true;
948    true
949}
950
951/// The persisted notice (D11): which memory was delivered, and each entry's
952/// size. `id` is stable for the delivery, so a live frame and a replay of the
953/// same line render once.
954fn notice_frame(key: &DeliveryKey, d: &Delivery) -> serde_json::Value {
955    card_frame(
956        format!("memory-injected-{}-{}-{}", key.session_id, key.reason.as_str(), d.created_ms),
957        key.reason.as_str(),
958        &d.entries,
959        d.summary_bytes,
960        d.created_ms,
961        serde_json::json!({ "session_id": key.session_id, "parts": d.parts.len() }),
962    )
963}
964
965#[cfg(test)]
966mod tests;