Skip to main content

agentmux_srv_core/backend/transcript/
append.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Writing an agent's transcript: the line appends to the block's `output` and
5//! the agent's global zone, the order lock that keeps one block's events in line
6//! order, and the announcements of a replaced or deleted transcript.
7//!
8//! These lived in `blockcontroller/shell/file_ops.rs` next to the terminal output
9//! path, which made the store-lock warnings (`site=`) and a reader's search for
10//! "where does a transcript get written" point at the terminal code. Terminal
11//! output (`handle_append_block_file` for `term`) stays in `shell/`.
12
13use std::sync::Arc;
14
15use base64::Engine as _;
16
17use super::{live, origin_sig, withhold};
18use crate::backend::message_origin::RecordOrigin;
19use crate::backend::mps;
20use crate::backend::storage::filestore::{AppendPos, FileStore};
21
22use crate::backend::blockcontroller::shell::handle_append_block_file;
23
24// A defined agent's transcript is written to the agent's zone in the global store only, not also to the
25// block's own store (SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md §3 row 2, SPEC_AGENT_TRANSCRIPT_SINGLE_COPY_2026_10_19.md).
26// There is no setting: the per-channel copy is not written for new data. Copies that already exist are not touched here.
27
28/// Whether `zone` is a defined agent's own zone (`agent:<id>:current`), whose
29/// transcript is one conversation, and not a quick-launch provider's, which
30/// every pane of that provider shares.
31fn is_defined_agent_zone(zone: &str) -> bool {
32    zone.strip_prefix("agent:")
33        .and_then(|z| z.strip_suffix(":current"))
34        .is_some_and(|id| crate::backend::providers::get_provider(id).is_none())
35}
36
37/// Persist a user message the controller wrote to the agent's stdin, so
38/// `parseHistoryLines` can reconstruct its `user_message` node on reopen.
39///
40/// A transcript record like any other (Phase 5a-3c): written to the block's
41/// file and the global zone with positions, and published — so a pane reading
42/// the stream by line never sees a gap where this record sits — but marked
43/// `echo: "stdin"`, because the pane already shows the message (its
44/// `agent-message-accepted` node) and must not add a second one. Before 5a-3c
45/// this write published nothing at all.
46///
47/// A message a paired device sent is the exception: no pane typed it, so it
48/// is stored with who sent it (`viewer::origin`) and published as a plain
49/// record, which the open pane shows.
50pub fn persist_user_line(
51    broker: Option<&mps::Broker>,
52    block_id: &str,
53    data: &[u8],
54    filestore: Option<&Arc<FileStore>>,
55    global_output_zone: Option<&str>,
56    record: Option<&RecordOrigin>,
57) {
58    persist_user_line_as(broker, block_id, data, filestore, global_output_zone, true, record);
59}
60
61/// [`persist_user_line`] for a message no pane typed (a jekt, a broadcast, a
62/// schedule, the app API): the record is published as a plain one, which an
63/// open pane shows, because no `agent-message-accepted` node stands for it.
64pub fn persist_injected_user_line(
65    broker: Option<&mps::Broker>,
66    block_id: &str,
67    data: &[u8],
68    filestore: Option<&Arc<FileStore>>,
69    global_output_zone: Option<&str>,
70    record: Option<&RecordOrigin>,
71) {
72    persist_user_line_as(broker, block_id, data, filestore, global_output_zone, false, record);
73}
74
75fn persist_user_line_as(
76    broker: Option<&mps::Broker>,
77    block_id: &str,
78    data: &[u8],
79    filestore: Option<&Arc<FileStore>>,
80    global_output_zone: Option<&str>,
81    shown_by_pane: bool,
82    record: Option<&RecordOrigin>,
83) {
84    // A message sent again (a retry, a usage limit's resend) is already in the transcript from its first send: one copy.
85    if record.is_some_and(|r| r.resend) {
86        return;
87    }
88    // What srv holds secret is never stored, and the record is signed over what is stored (below).
89    let data = withhold::lines(data);
90    let data: &[u8] = &data;
91    let global = global_output_zone.and_then(|zone| {
92        crate::backend::agent_session::global_transcript_store().map(|gfs| (gfs, zone))
93    });
94    // A message a paired device sent says so (`viewer::origin`); every one
95    // says where it came from and which notes went with it.
96    let from_device = crate::backend::viewer::origin::stamp(block_id, data);
97    let echo = if from_device.is_none() && shown_by_pane { Some("stdin") } else { None };
98    let data = from_device.as_deref().unwrap_or(data);
99    let stamped;
100    let data = match record {
101        Some(record) => {
102            stamped = crate::backend::message_origin::stamp_bytes(data, record);
103            stamped.as_slice()
104        }
105        None => data,
106    };
107    // Signed last, over everything in the `amx`, for the agent (or block) the record belongs to.
108    let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
109    let signed = origin_sig::sign_line(owner, data, agentmux_common::time::now_ms());
110    let data = signed.as_slice();
111    append_transcript(broker, block_id, data, filestore, global, global_output_zone.is_some(), echo);
112}
113
114/// `line` stored as the record of a prompt srv delivered, when it is the provider echoing one: with
115/// the origin the ledger holds, signed. The echo's own `amx`, if it has one, is dropped first: only
116/// srv says where a message came from (a paired device that sent it, `viewer::origin`, among it).
117fn origin_of_echo(block_id: &str, line: &str, global_output_zone: Option<&str>) -> Option<String> {
118    let text = origin_sig::echoed_prompt(line)?;
119    let record = super::origin_ledger::take(block_id, &text)?;
120    let mut value: serde_json::Value = serde_json::from_str(line).ok()?;
121    value.as_object_mut()?.remove("amx");
122    crate::backend::viewer::origin::stamp_record(block_id, &mut value, &text);
123    let stored = format!("{value}\n");
124    let stamped = crate::backend::message_origin::stamp_bytes(withhold::text(&stored).as_bytes(), &record);
125    let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
126    String::from_utf8(origin_sig::sign_line(owner, &stamped, agentmux_common::time::now_ms())).ok()
127}
128
129/// Appends one NDJSON stdout line, plus the newline the frontend's line
130/// splitter needs, to the block's `output` file and `global_output_zone`.
131///
132/// A line that is the provider echoing a prompt srv delivered (`origin_ledger`) is stored with
133/// that message's origin, signed like a record srv writes itself; any other line is stored as it is.
134pub fn append_output_line(
135    broker: &mps::Broker,
136    block_id: &str,
137    line: &str,
138    filestore: Option<&Arc<FileStore>>,
139    global_output_zone: Option<&str>,
140) {
141    append_output_line_by(broker, block_id, line, filestore, global_output_zone, None);
142}
143
144/// [`append_output_line`] for a line an agent's process wrote: besides an echo's origin, it is stored with which
145/// runtime wrote it (`origin_sig::stamp_writer`), so a reader decides what the message may name by who wrote it.
146pub fn append_agent_output_line(
147    broker: &mps::Broker,
148    block_id: &str,
149    line: &str,
150    filestore: Option<&Arc<FileStore>>,
151    global_output_zone: Option<&str>,
152    runtime: origin_sig::WriterRuntime,
153) {
154    append_output_line_by(broker, block_id, line, filestore, global_output_zone, Some(runtime));
155}
156
157fn append_output_line_by(
158    broker: &mps::Broker,
159    block_id: &str,
160    line: &str,
161    filestore: Option<&Arc<FileStore>>,
162    global_output_zone: Option<&str>,
163    writer: Option<origin_sig::WriterRuntime>,
164) {
165    // The echo is looked up by the words as the provider wrote them; what is stored, and signed, has nothing srv holds secret.
166    let line_with_newline = origin_of_echo(block_id, line, global_output_zone)
167        .or_else(|| {
168            let owner = origin_sig::owner_of_zone(global_output_zone.unwrap_or(block_id));
169            let stamped = origin_sig::stamp_writer(owner, &withhold::text(line), writer?, agentmux_common::time::now_ms())?;
170            Some(format!("{stamped}\n"))
171        })
172        .unwrap_or_else(|| format!("{}\n", withhold::text(line)));
173    handle_append_block_file(
174        broker,
175        block_id,
176        crate::backend::agent_session::OUTPUT_FILE,
177        line_with_newline.as_bytes(),
178        filestore,
179        global_output_zone,
180    );
181}
182
183/// Append `data` to the global transcript zone's `output` file, creating it
184/// lazily on first write, and return where it landed. Mirrors the
185/// per-channel write-through in [`crate::backend::blockcontroller::shell::handle_append_block_file`]; all errors are
186/// logged and swallowed (`None`) so the hot stdout path is never blocked by
187/// the global store.
188pub(crate) fn mirror_append_to_global(gfs: &Arc<FileStore>, zone: &str, data: &[u8]) -> Option<AppendPos> {
189    use crate::backend::agent_session::OUTPUT_FILE;
190    // Global zones are agent transcripts by construction — always stamp
191    // (§4.4), keyed at the offset this append actually landed at (codex P2 on
192    // PR #2508), in the same transaction as the append.
193    let landed = append_transcript_lines(gfs, zone, OUTPUT_FILE, data, true, "global transcripts", true);
194    if landed.is_some() {
195        // The History pane's agent list: its size and last-active time moved.
196        crate::backend::history_changed::mark();
197    }
198    landed
199}
200
201/// Lines moved into an agent's global zone from another copy of the conversation, with the receive times they had
202/// there (`(offset in `data`, ms)`), for an agent that has no conversation in the store: decided in the transaction
203/// that writes, `Ok(None)` when its current zone or an archive holds a line by then, and nothing is written.
204pub(crate) fn mirror_seed_with_stamps(gfs: &Arc<FileStore>, def: &str, data: &[u8], stamps: &[(i64, i64)]) -> Result<Option<AppendPos>, String> {
205    use crate::backend::agent_session::{agent_current_zone, OUTPUT_FILE, TSIDX_FILE};
206    use crate::backend::storage::error::StoreError;
207    use crate::backend::storage::filestore::{FileMeta, FileOpts};
208    let zone = agent_current_zone(def);
209    let archives = format!("agent:{def}:archive:");
210    let seed = || gfs.append_lines_with_stamps_if_unused(&zone, OUTPUT_FILE, data, TSIDX_FILE, stamps, &archives);
211    let landed = match seed() {
212        Err(StoreError::NotFound) => {
213            match gfs.make_file(&zone, OUTPUT_FILE, FileMeta::default(), FileOpts::default()) {
214                Ok(()) | Err(StoreError::AlreadyExists) => {}
215                Err(e) => return Err(format!("make_file: {e}")),
216            }
217            seed()
218        }
219        other => other,
220    }
221    .map_err(|e| format!("seed: {e}"))?;
222    if landed.is_some() {
223        crate::backend::history_changed::mark();
224    }
225    Ok(landed)
226}
227
228/// `append_lines` on a transcript file, creating it on first write (or if
229/// another instance deleted it since). Whole non-blank lines only: a torn
230/// last line is closed, not continued (`filestore/counter.rs`). With `stamp`,
231/// the `output.tsidx` receive-time record is written in the same transaction
232/// (one commit, not two). Errors are logged and swallowed.
233///
234/// `shared` is a write to the shared store's zone: one found corrupt (here or
235/// by a reader) is not written to again in this process
236/// ([`damage`](crate::backend::transcript::damage)), and the first corrupt error
237/// is an incident, not only a WARN line.
238fn append_transcript_lines(fs: &Arc<FileStore>, zone: &str, name: &str, data: &[u8], stamp: bool, what: &str, shared: bool) -> Option<AppendPos> {
239    use crate::backend::agent_session::TSIDX_FILE;
240    let append = || {
241        if stamp {
242            fs.append_lines_stamped(zone, name, data, TSIDX_FILE)
243        } else {
244            fs.append_lines(zone, name, data)
245        }
246    };
247    append_transcript_with(fs, zone, name, what, shared, &append)
248}
249
250/// [`append_transcript_lines`] with the write itself given: it is made, and made again once the file exists.
251fn append_transcript_with(
252    fs: &Arc<FileStore>,
253    zone: &str,
254    name: &str,
255    what: &str,
256    shared: bool,
257    append: &dyn Fn() -> Result<AppendPos, crate::backend::storage::error::StoreError>,
258) -> Option<AppendPos> {
259    use crate::backend::storage::error::StoreError;
260    use crate::backend::transcript::damage;
261    if shared && damage::is_damaged(zone) {
262        return None;
263    }
264    let failed = |e: &StoreError| {
265        if shared && damage::note_corrupt(zone, "append", e) {
266            return;
267        }
268        tracing::warn!(zone = %zone, error = %e, "{what}: append failed");
269    };
270    match append() {
271        Ok(pos) => return Some(pos),
272        Err(StoreError::NotFound) => {}
273        Err(e) => {
274            failed(&e);
275            return None;
276        }
277    }
278    if let Err(e) = fs.make_file(
279        zone,
280        name,
281        std::collections::HashMap::new(),
282        crate::backend::storage::filestore::FileOpts::default(),
283    ) {
284        if !matches!(e, StoreError::AlreadyExists) {
285            if !(shared && damage::note_corrupt(zone, "append", &e)) {
286                tracing::warn!(zone = %zone, error = %e, "{what}: make_file failed; skipping write");
287            }
288            return None;
289        }
290    }
291    append().map_err(|e| failed(&e)).ok()
292}
293
294/// The agent-transcript half of [`crate::backend::blockcontroller::shell::handle_append_block_file`] (Phase 5a-3,
295/// SPEC_AGENT_PANE_BOUNDED_LIVE_WINDOW_MIGRATION_2026_09_23.md §6.3.7 item 5).
296///
297/// The block's `output` and the agent's global zone are written FIRST, and
298/// the event goes out after, carrying where the records landed in each stream
299/// (`pos`) and the exact byte offset in the block's file. The block's order
300/// lock is held from the first write to the publish, so one block's events
301/// leave in line order. Only transcripts come here: publishing after a
302/// database write would add that write to every terminal keystroke echo.
303///
304/// `stamp_tsidx` is whether this is an agent stream (it has a global zone,
305/// even if no global store is installed) — as before, only those get the
306/// receive-time sidecar.
307///
308/// A defined agent's line goes to the global zone only. The block's own copy is
309/// still written when there is no global write to rely on: a fenced writer (it
310/// passes no global zone), a quick-launch pane (a provider's shared zone), or a
311/// global write that failed (the line must not be lost).
312pub(crate) fn append_transcript(
313    broker: Option<&mps::Broker>,
314    block_id: &str,
315    data: &[u8],
316    filestore: Option<&Arc<FileStore>>,
317    global: Option<(&Arc<FileStore>, &str)>,
318    stamp_tsidx: bool,
319    echo: Option<&str>,
320) {
321    // The records exactly as they are written (`append_lines` normalizes to
322    // complete, non-blank lines): the event carries these bytes, and its
323    // `offset` is where they landed, so a consumer can match the event to a
324    // byte range read back from the file (review of #3635). Nothing to write,
325    // nothing to announce.
326    // The last guard, for a writer that did not go through the ones above: a line already withheld has nothing to change,
327    // so a signed record stays as it was signed.
328    let data = withhold::lines(data);
329    let records = crate::backend::storage::filestore::normalized_records(&data);
330    if records.is_empty() {
331        return;
332    }
333    let _order = transcript_order_lock(block_id);
334    if !stamp_tsidx {
335        append_lines_run(broker, block_id, &records, filestore, global, stamp_tsidx, echo);
336        return;
337    }
338    // An agent stream: the fragments of a reply in progress are held in `output.live`, not in `output`.
339    let global_only = global.is_some_and(|(_, zone)| is_defined_agent_zone(zone));
340    let targets = live::targets(block_id, filestore, global);
341    if let Some(left) = live::recover_once(block_id, &targets, global_only) {
342        if !left.is_empty() {
343            append_lines_run(broker, block_id, &left, filestore, global, stamp_tsidx, None);
344        }
345    }
346    for run in live::plan(block_id, &records) {
347        match run {
348            live::Run::Lines(lines) => append_lines_run(broker, block_id, &lines, filestore, global, stamp_tsidx, echo),
349            live::Run::Fragments(lines) => {
350                live::append_fragments(block_id, &targets, &lines, global_only);
351                publish_fragments(broker, block_id, &lines);
352            }
353            live::Run::ClearLive => {
354                live::clear(&targets);
355                live::clear_held_live(block_id);
356            }
357        }
358    }
359}
360
361/// Tell the block's panes of fragment lines held in the live file. The event names no position: the
362/// pane's cursor takes an event it cannot place as it did before positions, so the feed is as it was.
363fn publish_fragments(broker: Option<&mps::Broker>, block_id: &str, records: &[u8]) {
364    let Some(broker) = broker else { return };
365    let event_data = mps::WSFileEventData {
366        zoneid: block_id.to_string(),
367        filename: crate::backend::agent_session::OUTPUT_FILE.to_string(),
368        fileop: mps::FILE_OP_APPEND.to_string(),
369        data64: base64::engine::general_purpose::STANDARD.encode(records),
370        offset: None,
371        pos: Vec::new(),
372        echo: None,
373    };
374    broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
375}
376
377/// Write complete lines to the block's `output` and the agent's global zone, then announce them with
378/// where they landed. The caller holds the block's order lock and has put the lines in order.
379#[allow(clippy::too_many_arguments)]
380fn append_lines_run(
381    broker: Option<&mps::Broker>,
382    block_id: &str,
383    records: &[u8],
384    filestore: Option<&Arc<FileStore>>,
385    global: Option<(&Arc<FileStore>, &str)>,
386    stamp_tsidx: bool,
387    echo: Option<&str>,
388) {
389    use crate::backend::agent_session::OUTPUT_FILE;
390    let mut offset = None;
391    let mut pos = Vec::new();
392    // Whether any copy was written (a copy in a file that isn't counted has no position).
393    let mut stored = false;
394    // The agent's zone first; the block's copy only if that failed.
395    let global_only = global.is_some_and(|(_, zone)| is_defined_agent_zone(zone));
396    let mut global_pos = None;
397    if global_only {
398        if let Some((gfs, zone)) = global {
399            // Lines only the block's own copy holds (an earlier shared append failed) go to the shared transcript
400            // first, in order, so it is never missing a line the block's copy has once it takes appends again.
401            let mut held = live::take_unshared(block_id);
402            let mut caught_up = true;
403            if !held.is_empty() {
404                caught_up = mirror_append_to_global(gfs, zone, &held).is_some();
405                if caught_up {
406                    held.clear();
407                }
408            }
409            global_pos = Some(if caught_up { mirror_append_to_global(gfs, zone, &records) } else { None });
410            if global_pos.as_ref().is_some_and(Option::is_none) {
411                // The block's own copy takes this line below.
412                held.extend_from_slice(&records);
413            }
414            live::put_unshared(block_id, gfs, zone, held);
415        }
416    }
417    let write_block_copy = !global_only || global_pos.as_ref().is_some_and(Option::is_none);
418    if let Some(fs) = filestore.filter(|_| write_block_copy) {
419        if let Some(p) = append_transcript_lines(fs, block_id, OUTPUT_FILE, &records, stamp_tsidx, "filestore", false) {
420            // Past the `\n` that closed a torn last line, if one was written.
421            offset = Some(p.records_offset.max(0) as u64);
422            stored = true;
423            if let Some(c) = p.counted {
424                pos.push(mps::StreamPos { stream: format!("b:{block_id}"), gen: c.gen, line: c.first_line, lines: c.lines });
425            }
426        }
427    }
428    if let Some((gfs, zone)) = global {
429        let landed = match global_pos {
430            Some(done) => done,
431            None => mirror_append_to_global(gfs, zone, &records),
432        };
433        // The Audit's index of tool calls and turns, for what the agent wrote (not srv's echo of a message it sent).
434        if echo.is_none() {
435            let at = landed.as_ref().map(|p| p.records_offset.max(0) as u64);
436            crate::backend::audit_activity::note_records(block_id, zone, &records, at);
437            // What its calls used, against the task it held (the per-task token ledger).
438            crate::backend::token_ledger::note_records(zone, &records);
439        } else {
440            // A prompt srv delivered: its origin is the cause of the call that answers it.
441            crate::backend::token_ledger::note_prompt(zone, &records);
442        }
443        stored |= landed.is_some();
444        if let Some(c) = landed.and_then(|p| p.counted) {
445            pos.push(mps::StreamPos { stream: format!("g:{zone}"), gen: c.gen, line: c.first_line, lines: c.lines });
446        }
447    }
448    // A paired device's message gets its Audit row, with where its line landed.
449    crate::backend::viewer::audit::note_landed(block_id, &records, &pos, stored);
450
451    let event_data = mps::WSFileEventData {
452        zoneid: block_id.to_string(),
453        filename: OUTPUT_FILE.to_string(),
454        fileop: mps::FILE_OP_APPEND.to_string(),
455        data64: base64::engine::general_purpose::STANDARD.encode(&records),
456        offset,
457        pos,
458        echo: echo.map(str::to_string),
459    };
460    // No broker (a controller built without one): written, not announced.
461    if let Some(broker) = broker {
462        broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
463    }
464}
465
466/// Run `f` holding `block_id`'s transcript order lock — the lock every append
467/// holds from its first write to its publish (see [`append_transcript`]).
468/// A replace or delete of the block's transcript, and its announcement
469/// ([`publish_transcript_changed`]), run inside it, so no append's write and
470/// event can interleave with them and one block's events stay in order
471/// (review of #3636). `f` must not append to the same block: the lock isn't
472/// reentrant.
473pub fn with_transcript_order<T>(block_id: &str, f: impl FnOnce() -> T) -> T {
474    let _order = transcript_order_lock(block_id);
475    f()
476}
477
478/// Tell a block's panes that its transcript `output` was replaced or deleted
479/// as a whole (Phase 5a-3), so an open pane resyncs at once instead of on its
480/// next read. `fileop` is [`mps::FILE_OP_REPLACE`] — with the new generation
481/// and line count read from `filestore` — or [`mps::FILE_OP_DELETE`]. Call it,
482/// with the replace or delete itself, inside [`with_transcript_order`].
483pub fn publish_transcript_changed(
484    broker: &mps::Broker,
485    block_id: &str,
486    fileop: &str,
487    filestore: &FileStore,
488    mstore: &crate::backend::storage::store::Store,
489) {
490    let source = crate::backend::transcript::source::TranscriptSource::resolve(filestore, mstore, block_id);
491    publish_transcript_changed_from(broker, block_id, fileop, filestore, &source);
492}
493
494/// [`publish_transcript_changed`] with the transcript's source resolved. The
495/// position names the block's own stream when it has a counted copy, the
496/// agent's zone otherwise (a defined agent written to the zone only, which is
497/// the stream its pane follows).
498pub(crate) fn publish_transcript_changed_from(
499    broker: &mps::Broker,
500    block_id: &str,
501    fileop: &str,
502    filestore: &FileStore,
503    source: &crate::backend::transcript::source::TranscriptSource<'_>,
504) {
505    use crate::backend::agent_session::OUTPUT_FILE;
506    let pos_in = |fs: &FileStore, zone: &str, stream: String| match fs.line_state(zone, OUTPUT_FILE) {
507        Ok(Some(state)) => state
508            .counted
509            .map(|c| vec![mps::StreamPos { stream, gen: c.gen, line: 0, lines: c.lines }])
510            .unwrap_or_default(),
511        _ => Vec::new(),
512    };
513    let mut pos = pos_in(filestore, block_id, format!("b:{block_id}"));
514    if pos.is_empty() && source.global {
515        pos = pos_in(source.fs, &source.zone, format!("g:{}", source.zone));
516    }
517    let event_data = mps::WSFileEventData {
518        zoneid: block_id.to_string(),
519        filename: OUTPUT_FILE.to_string(),
520        fileop: fileop.to_string(),
521        data64: String::new(),
522        offset: None,
523        pos,
524        echo: None,
525    };
526    broker.publish_event::<crate::backend::mps_events::BlockFile>(&event_data, vec![format!("block:{block_id}")], 0);
527}
528
529/// Serializes one block's transcript appends with their publish (see
530/// [`append_transcript`]). Striped rather than per block: bounded memory and
531/// nothing to clean up; two blocks that share a stripe only wait for each
532/// other's append.
533fn transcript_order_lock(block_id: &str) -> std::sync::MutexGuard<'static, ()> {
534    use std::hash::{Hash, Hasher};
535    const STRIPES: usize = 64;
536    static LOCKS: [std::sync::Mutex<()>; STRIPES] = [const { std::sync::Mutex::new(()) }; STRIPES];
537    let mut h = std::collections::hash_map::DefaultHasher::new();
538    block_id.hash(&mut h);
539    LOCKS[(h.finish() % STRIPES as u64) as usize]
540        .lock()
541        .unwrap_or_else(|poisoned| poisoned.into_inner())
542}
543
544/// Resolve a block's GLOBAL transcript zone (`agent:<defId>:current`) from its
545/// `agentId` meta, looking the block up in `mstore`. Returns `None` for
546/// non-agent blocks, when there's no store, or when the block can't be loaded —
547/// the caller then passes `None` and no global mirror happens. Shared by the
548/// subprocess / persistent / acp agent controllers.
549pub fn resolve_global_output_zone(
550    mstore: &Option<Arc<crate::backend::storage::store::Store>>,
551    block_id: &str,
552) -> Option<String> {
553    let store = mstore.as_ref()?;
554    let block = store
555        .must_get::<crate::backend::obj::Block>(block_id)
556        .ok()?;
557    crate::backend::agent_session::agent_zone_for_block_meta(&block.meta)
558}
559
560#[cfg(test)]
561mod damage_tests {
562    use super::*;
563    use crate::backend::storage::filestore::{FileMeta, FileOpts};
564    use crate::backend::transcript::damage::{self, test_support};
565
566    const LINE: &[u8] = b"{\"type\":\"user\"}
567";
568
569    fn own_copy(own: &FileStore, block: &str) -> Vec<u8> {
570        own.read_file(block, "output").unwrap().unwrap_or_default()
571    }
572
573    #[test]
574    fn a_corrupt_error_on_the_shared_zone_marks_it_and_the_blocks_copy_keeps_the_line() {
575        for n in [1, 2] {
576            let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
577            test_support::corrupt(&gfs);
578            let (block, zone) = (format!("blk-damage-append-{n}"), format!("agent:damage-append-{n}:current"));
579            assert!(!damage::is_damaged(&zone));
580            append_transcript(None, &block, LINE, Some(&own), Some((&gfs, zone.as_str())), true, None);
581            assert!(damage::is_damaged(&zone), "attempt {n}: the first corrupt error marks the zone");
582            assert_eq!(own_copy(&own, &block), LINE, "attempt {n}: the block's copy has the line, so nothing is lost");
583        }
584    }
585
586    #[test]
587    fn a_damaged_zone_is_not_written_to_again_but_the_blocks_copy_is() {
588        let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
589        let (block, zone) = ("blk-damage-append-3", "agent:damage-append-3:current");
590        // The shared store is healthy again (or was never what failed): the zone stays out of it.
591        damage::note_corrupt(zone, "append", &StoreError::Sqlite(rusqlite::Error::SqliteFailure(
592            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT),
593            None,
594        )));
595        use crate::backend::storage::error::StoreError;
596        append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
597        append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
598        assert!(gfs.stat(zone, "output").unwrap().is_none(), "nothing was sent to the shared store");
599        assert_eq!(own_copy(&own, block), [LINE, LINE].concat());
600        assert!(mirror_append_to_global(&gfs, zone, LINE).is_none());
601    }
602
603    #[test]
604    fn a_zone_that_is_not_damaged_is_written_as_before() {
605        let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
606        let (block, zone) = ("blk-damage-append-4", "agent:damage-append-4:current");
607        gfs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
608        append_transcript(None, block, LINE, Some(&own), Some((&gfs, zone)), true, None);
609        assert_eq!(gfs.read_file(zone, "output").unwrap().unwrap(), LINE);
610        assert!(!damage::is_damaged(zone));
611    }
612}
613
614/// The canary: a value srv holds secret is seeded, written every way srv writes a transcript line, and read back.
615#[cfg(test)]
616mod withhold_tests {
617    use super::*;
618    use crate::backend::message_origin::{MessageOrigin, RecordOrigin};
619    use crate::backend::storage::store::Store;
620    use serde_json::json;
621
622    const KEY: &str = "canary-instance-key-7741-QzXw";
623    const TOKEN: &str = "canary-agent-token-9082-LmNo";
624    const VAULT: &str = "canary-vault-value-5513-RsTu";
625
626    fn seed() {
627        for value in [KEY, TOKEN, VAULT] {
628            withhold::register(value);
629        }
630    }
631
632    fn user_line(text: &str) -> Vec<u8> {
633        format!("{}\n", json!({ "type": "user", "message": { "role": "user", "content": text } })).into_bytes()
634    }
635
636    fn stored(fs: &FileStore, zone: &str) -> String {
637        String::from_utf8(fs.read_file(zone, "output").unwrap().unwrap_or_default()).unwrap()
638    }
639
640    #[test]
641    fn nothing_srv_holds_secret_reaches_a_stored_transcript_by_any_writer() {
642        seed();
643        let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
644        let (block, zone) = ("blk-withhold-all", "agent:withhold-all:current");
645        let broker = mps::Broker::new();
646        // The agent's process: a tool result that printed its environment, its own text, a streamed delta.
647        for line in [
648            json!({ "type": "user", "message": { "role": "user", "content": [{ "type": "tool_result", "tool_use_id": "t1", "content": format!("AUTH={KEY}\nAGENT={TOKEN}") }] } }),
649            json!({ "type": "assistant", "message": { "content": [{ "type": "text", "text": format!("the key is {VAULT}") }] } }),
650            json!({ "type": "stream_event", "event": { "delta": { "text": VAULT } } }),
651        ] {
652            append_agent_output_line(&broker, block, &line.to_string(), Some(&own), Some(zone), origin_sig::WriterRuntime::Host);
653        }
654        // What srv writes for a person: a typed message and an injected one.
655        let origin = RecordOrigin::new(MessageOrigin::user());
656        persist_user_line(None, block, &user_line(&format!("use {KEY}")), Some(&own), Some(zone), Some(&origin));
657        persist_injected_user_line(None, block, &user_line(&format!("note {TOKEN}")), Some(&own), Some(zone), Some(&origin));
658        // A writer that goes straight to the append, and the agent's zone.
659        append_transcript(None, block, &user_line(&format!("raw {VAULT}")), Some(&own), Some((&gfs, zone)), true, None);
660
661        for (what, text) in [("the block's copy", stored(&own, block)), ("the agent's zone", stored(&gfs, zone))] {
662            for canary in [KEY, TOKEN, VAULT] {
663                assert!(!text.contains(canary), "{what} holds {canary}");
664            }
665        }
666        let text = stored(&gfs, zone);
667        assert!(text.contains(withhold::MARK), "the agent's zone has the marks: {text}");
668    }
669
670    #[test]
671    fn a_record_srv_signed_still_verifies_with_a_value_withheld_from_its_words() {
672        seed();
673        let (fs, ms) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(Store::open_in_memory().unwrap()));
674        let block = "blk-withhold-sig";
675        let record = RecordOrigin::new(MessageOrigin::from_sender("agent1"));
676        persist_injected_user_line(None, block, &user_line(&format!("note {TOKEN}")), Some(&fs), None, Some(&record));
677        let read = crate::backend::transcript::tail::tail_lines(&ms, &fs, block, 10).unwrap().lines;
678        assert_eq!(read.len(), 1);
679        let line: serde_json::Value = serde_json::from_str(&read[0]).unwrap();
680        assert_eq!(line["amx"]["verified"], true, "the signature covers what is stored: {line}");
681        assert_eq!(line["message"]["content"], format!("note {}", withhold::MARK));
682    }
683
684    #[test]
685    fn a_line_with_nothing_to_withhold_is_stored_byte_for_byte() {
686        seed();
687        let (own, gfs) = (Arc::new(FileStore::open_in_memory().unwrap()), Arc::new(FileStore::open_in_memory().unwrap()));
688        let (block, zone) = ("blk-withhold-none", "agent:withhold-none:current");
689        let line = b"{\"type\":\"assistant\",\"message\":{\"content\":\"nothing secret\"}}\n";
690        append_transcript(None, block, line, Some(&own), Some((&gfs, zone)), true, None);
691        assert_eq!(stored(&own, block), "", "a defined agent's line is not also written to the block");
692        assert_eq!(stored(&gfs, zone).as_bytes(), line);
693    }
694}