Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
file_ops.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Block-file append helpers for terminal output. The agent transcript writes
5//! live in `backend/transcript/append.rs`.
6
7use std::sync::Arc;
8
9use base64::Engine as _;
10
11use crate::backend::storage::filestore::FileStore;
12use crate::backend::mps;
13use crate::backend::transcript::append::append_transcript;
14
15use super::term_cap;
16
17/// Current unix time in ms, or 0 if the clock is before the epoch (never in
18/// practice; 0 reads as "unknown" on the consumer side, same as no stamp).
19fn unix_ms_now() -> i64 {
20    agentmux_common::time::now_ms()
21}
22
23/// Append one receive-time record to a zone's `output.tsidx` sidecar:
24/// NDJSON `{"off":<byte offset the batch starts at in output>,"ms":<unix ms>}`.
25/// Batch granularity is deliberate — one flush of one turn's output; sub-batch
26/// precision has no UI meaning
27/// (SPEC_AGENT_PANE_SESSION_SCOPED_SCROLLBACK_AND_AGENT_HISTORY_VIEW_2026_08_09.md §4.4).
28/// Fire-and-forget like every other write on this path: any failure logs at
29/// debug and the transcript append is unaffected. Only called for agent
30/// transcript streams (never PTY `term` data).
31fn append_tsidx_entry(fs: &Arc<FileStore>, zone: &str, batch_start: u64, now_ms: i64) {
32    use crate::backend::agent_session::TSIDX_FILE;
33    use crate::backend::storage::error::StoreError;
34
35    if let Ok(None) = fs.stat(zone, TSIDX_FILE) {
36        if let Err(e) = fs.make_file(
37            zone,
38            TSIDX_FILE,
39            std::collections::HashMap::new(),
40            crate::backend::storage::filestore::FileOpts::default(),
41        ) {
42            if !matches!(e, StoreError::AlreadyExists) {
43                tracing::debug!(zone = %zone, error = %e, "tsidx: make_file failed; skipping stamp");
44                return;
45            }
46        }
47    }
48    let line = format!("{{\"off\":{batch_start},\"ms\":{now_ms}}}\n");
49    if let Err(e) = fs.append_data(zone, TSIDX_FILE, line.as_bytes()) {
50        tracing::debug!(zone = %zone, error = %e, "tsidx: append failed");
51    }
52}
53
54/// Append data to a block's terminal output file, publish a MPS event,
55/// and write-through to FileStore (if provided).
56///
57/// Port of Go's `HandleAppendBlockFile`.
58///
59/// The FileStore write is fire-and-forget: if it fails we emit a warning but
60/// never propagate the error back to the hot stdout-reader path.
61/// Outcome of the up-front `stat()` this function needs regardless (to know
62/// whether to lazily `make_file` before appending) — reused to compute the
63/// chunk's start offset for the broadcast event too, rather than stat-ing
64/// twice. `Error` preserves the original behavior of skipping write-through
65/// entirely (and omitting `offset` from the broadcast) on a stat failure.
66enum ExistingFileStat {
67    NeedsCreate,
68    Exists { size: u64 },
69    Error,
70}
71
72pub fn handle_append_block_file(
73    broker: &mps::Broker,
74    block_id: &str,
75    filename: &str,
76    data: &[u8],
77    filestore: Option<&Arc<FileStore>>,
78    global_output_zone: Option<&str>,
79) {
80    // Agent transcripts are written first and published with their positions
81    // (Phase 5a-3). Everything else — PTY `term` data — keeps publishing
82    // before the write, below.
83    if filename == crate::backend::agent_session::OUTPUT_FILE {
84        let global = global_output_zone.and_then(|zone| {
85            crate::backend::agent_session::global_transcript_store().map(|gfs| (gfs, zone))
86        });
87        append_transcript(Some(broker), block_id, data, filestore, global, global_output_zone.is_some(), None);
88        return;
89    }
90
91    let data64 = base64::engine::general_purpose::STANDARD.encode(data);
92
93    // Stat once, up front — needed both to decide whether make_file() is
94    // required below AND to compute this chunk's start offset (the file's
95    // size immediately before this append) for the broadcast event, so a
96    // client reconnecting mid-stream can reconcile a chunk arriving during
97    // its own reconnect fetch against what that fetch already covers.
98    // Before the write-through fix (§2.1 of the spec below), "term" reads
99    // always 404'd, so this race was latent — a reconnecting TermWrap had
100    // nothing from the fetch to double-count against. Now that reads
101    // return real content, a chunk landing in the subscribe-then-fetch-
102    // then-flush-held-data window could be written twice (once from the
103    // fetch's response, once from the live/held replay), corrupting
104    // ptyOffset for future reconnects.
105    // See SPEC_TERMINAL_SCROLLBACK_PERSISTENCE_2026_07_23.md §2.1 follow-up.
106    let existing_stat = match filestore {
107        None => None,
108        Some(fs) => Some(match fs.stat(block_id, filename) {
109            Ok(None) => ExistingFileStat::NeedsCreate,
110            Ok(Some(info)) => ExistingFileStat::Exists { size: info.size as u64 },
111            Err(e) => {
112                tracing::warn!(
113                    block_id = %block_id,
114                    filename = %filename,
115                    error = %e,
116                    "filestore stat failed; skipping write-through"
117                );
118                ExistingFileStat::Error
119            }
120        }),
121    };
122    let start_offset = match &existing_stat {
123        None | Some(ExistingFileStat::Error) => None,
124        Some(ExistingFileStat::NeedsCreate) => Some(0),
125        Some(ExistingFileStat::Exists { size }) => Some(*size),
126    };
127
128    let event_data = mps::WSFileEventData {
129        zoneid: block_id.to_string(),
130        filename: filename.to_string(),
131        fileop: mps::FILE_OP_APPEND.to_string(),
132        data64,
133        offset: start_offset,
134        pos: Vec::new(),
135        echo: None,
136    };
137
138    broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
139
140    // Write-through to FileStore for persistent history (Phase 1.3).
141    // Create the file lazily on first append; if the file already exists
142    // we skip make_file and go straight to append_data.
143    if let Some(fs) = filestore {
144        let needs_create = match existing_stat {
145            Some(ExistingFileStat::NeedsCreate) => true,
146            Some(ExistingFileStat::Exists { .. }) => false,
147            // Error already warned above; preserve the original
148            // skip-write-through-entirely behavior.
149            Some(ExistingFileStat::Error) | None => return,
150        };
151
152        if needs_create {
153            if let Err(e) = fs.make_file(
154                block_id,
155                filename,
156                std::collections::HashMap::new(),
157                if filename == term_cap::TERM_FILE { term_cap::term_opts() } else { Default::default() },
158            ) {
159                // AlreadyExists is benign (race between two appends); anything
160                // else is worth warning about.
161                use crate::backend::storage::error::StoreError;
162                if !matches!(e, StoreError::AlreadyExists) {
163                    tracing::warn!(
164                        block_id = %block_id,
165                        filename = %filename,
166                        error = %e,
167                        "filestore make_file failed; skipping write-through"
168                    );
169                    return;
170                }
171            }
172        }
173
174        match fs.append_data_at(block_id, filename, data) {
175            Ok(actual_start) => {
176                // Receive-time stamp for this batch (§4.4). Gated on
177                // `global_output_zone` — only agent transcript appends carry
178                // one; PTY `term` data and non-agent blocks never get a
179                // sidecar. Stamped at the offset the append itself reports
180                // (read under the store lock), not the pre-append stat —
181                // codex P2 on PR #2508: the stat can go stale when writers
182                // interleave, and a mis-keyed stamp gives replayed lines
183                // another batch's time. (The broadcast event's `offset`
184                // still uses the pre-append stat — pre-existing contract,
185                // reconcile-only consumer, unchanged here.)
186                if global_output_zone.is_some() {
187                    append_tsidx_entry(fs, block_id, actual_start.max(0) as u64, unix_ms_now());
188                }
189                if filename == term_cap::TERM_FILE && term_cap::after_append(fs, block_id, actual_start, data) {
190                    handle_append_block_file(broker, block_id, filename, term_cap::TRIMMED_NOTICE, filestore, None);
191                }
192            }
193            Err(e) => {
194                tracing::warn!(
195                    block_id = %block_id,
196                    filename = %filename,
197                    error = %e,
198                    "filestore append_data failed"
199                );
200            }
201        }
202        // Note: output.idx is NOT updated incrementally here. It is a lazily-built,
203        // self-validating cache the read path brings up to date whenever output
204        // grows (see `extend_output_idx` in shell/indexing.rs, invoked from the
205        // blockfile:read_range handler in app_api/blockfile.rs). This avoids
206        // every incremental-index failure mode (desync on write failure,
207        // chunk-split lines, blank-line miscounting) at the cost of scanning the
208        // appended bytes on the next read.
209    }
210}
211
212/// Truncate a block's terminal output file and publish a MPS event.
213/// Port of Go's `HandleTruncateBlockFile`.
214#[allow(dead_code)]
215pub fn handle_truncate_block_file(broker: &mps::Broker, block_id: &str, filename: &str) {
216    let event_data = mps::WSFileEventData {
217        zoneid: block_id.to_string(),
218        filename: filename.to_string(),
219        fileop: mps::FILE_OP_TRUNCATE.to_string(),
220        data64: String::new(),
221        offset: None,
222        pos: Vec::new(),
223        echo: None,
224    };
225
226    broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
227}