Skip to main content

agentmux_srv_core/backend/transcript/
attribution.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which runtime wrote the words of each message a viewer is shown (docs/specs/SPEC_MESSAGES_CARRY_THE_RUNTIME_OF_THEIR_WRITER_2026_11_20.md).
5//!
6//! A viewer decides what a message may open (a path in its text, an image it names) by where its words came
7//! from: words a container wrote may be shown only from the container's own folders. Two kinds of message
8//! carry their writer's runtime to the viewer as `amx.writer.runtime` and no more:
9//!
10//! - A line stamped by srv (`origin_sig::stamp_writer`) already says it, and [`vet_line`](super::origin_sig::vet_line)
11//!   keeps it when the stamp verifies.
12//! - A line with no verified `amx` in a host agent's fork whose copied history was a container's (or whose
13//!   mark does not verify): the words may be a container's, so they are attributed to one.
14//! - A message another agent sent (a jekt, a forwarded message): its words are the sender's. A sender that
15//!   srv has no record of, or one that runs in a container, counts as a container.
16//!
17//! Only ever tightening: a message is never made looser than the viewer's own pane, and nothing here marks a
18//! message as the host's.
19
20use serde_json::{json, Value};
21
22use crate::backend::agent_session::fork_history::{fork_history_cover, runtime_of_agent};
23use crate::backend::agent_session::global_transcript_store;
24use crate::backend::storage::filestore::FileStore;
25use crate::backend::storage::store::Store;
26
27use super::origin_sig::{vet_lines, WriterRuntime};
28
29/// [`vet_lines`], then each message's writer runtime as above, for the lines of `owner`'s transcript read for a viewer.
30/// `block_fs` is the block's own store; a fork's mark is read from the global transcript store when there is one.
31pub fn vet_for_viewer(mstore: &Store, block_fs: &FileStore, owner: &str, lines: &mut [String]) {
32    vet_lines(owner, lines);
33    let gfs = global_transcript_store().map_or(block_fs, |g| g.as_ref());
34    let unstamped_container = unstamped_lines_are_a_containers(mstore, gfs, owner);
35    attribute_lines(unstamped_container, &|from| runtime_of_agent(mstore, from), lines);
36}
37
38/// Whether a line of `owner`'s transcript with no verified `amx` may be a container's: `owner` is a host agent that
39/// is a fork, and where its copied history came from is a container's or is not on record (a mark that is not sealed
40/// or doesn't verify). An agent that runs in a container is not asked: its whole pane is confined already.
41fn unstamped_lines_are_a_containers(mstore: &Store, gfs: &FileStore, owner: &str) -> bool {
42    if runtime_of_agent(mstore, owner) != WriterRuntime::Host {
43        return false;
44    }
45    let zone = crate::backend::agent_session::agent_current_zone(owner);
46    if gfs.read_file(&zone, crate::backend::agent_session::fork_history::FORK_MARK_FILE).ok().flatten().is_none() {
47        return false;
48    }
49    fork_history_cover(gfs, &zone).is_none_or(|cover| cover.runtime == WriterRuntime::Container)
50}
51
52/// Marks, in each of `lines` (already vetted), the messages whose words a container may have written
53/// (`amx.writer.runtime = "container"`, with `attributed: true`). `sender` gives the runtime of the agent a
54/// message names as its sender. A line that is not one of those is left as it is.
55pub fn attribute_lines(unstamped_container: bool, sender: &dyn Fn(&str) -> WriterRuntime, lines: &mut [String]) {
56    for line in lines.iter_mut() {
57        if !(unstamped_container || line.contains("\"kind\":\"agent\"")) || super::origin_sig::is_stream_delta(line.as_bytes()) {
58            continue;
59        }
60        let Ok(mut record) = serde_json::from_str::<Value>(line.trim_end_matches('\n')) else { continue };
61        if !is_a_containers(&record, unstamped_container, sender) {
62            continue;
63        }
64        let Some(map) = record.as_object_mut() else { continue };
65        let mut amx = match map.remove("amx") {
66            Some(Value::Object(amx)) if amx.get("verified") == Some(&Value::Bool(true)) => amx,
67            _ => serde_json::Map::new(),
68        };
69        amx.insert("writer".to_string(), json!({ "runtime": "container", "attributed": true }));
70        map.insert("amx".to_string(), Value::Object(amx));
71        if let Ok(mut out) = serde_json::to_string(&record) {
72            if line.ends_with('\n') {
73                out.push('\n');
74            }
75            *line = out;
76        }
77    }
78}
79
80fn is_a_containers(record: &Value, unstamped_container: bool, sender: &dyn Fn(&str) -> WriterRuntime) -> bool {
81    let amx = record.get("amx").and_then(Value::as_object);
82    let verified = amx.is_some_and(|a| a.get("verified") == Some(&Value::Bool(true)));
83    if !verified {
84        return unstamped_container;
85    }
86    let writer = amx.and_then(|a| a.get("writer")).and_then(|w| w.get("runtime")).and_then(Value::as_str);
87    if writer.is_some() {
88        return false;
89    }
90    let origin = amx.and_then(|a| a.get("origin"));
91    let from_an_agent = origin.and_then(|o| o.get("kind")).and_then(Value::as_str) == Some("agent");
92    match origin.and_then(|o| o.get("from")).and_then(Value::as_str) {
93        Some(from) if from_an_agent => sender(from) == WriterRuntime::Container,
94        _ => false,
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    fn host_but(container: &'static str) -> impl Fn(&str) -> WriterRuntime {
103        move |from| if from == container { WriterRuntime::Container } else { WriterRuntime::Host }
104    }
105
106    fn run(unstamped_container: bool, sender: &dyn Fn(&str) -> WriterRuntime, line: Value) -> Value {
107        let mut lines = [format!("{line}\n")];
108        attribute_lines(unstamped_container, sender, &mut lines);
109        serde_json::from_str(lines[0].trim_end()).unwrap()
110    }
111
112    fn user(from: &str) -> Value {
113        json!({ "type": "user", "message": { "content": "see /x.png" }, "amx": { "v": 1, "verified": true, "origin": { "kind": "agent", "from": from } } })
114    }
115
116    fn runtime(v: &Value) -> Option<&str> {
117        v.pointer("/amx/writer/runtime")?.as_str()
118    }
119
120    #[test]
121    fn a_message_a_container_agent_sent_is_the_containers_and_one_from_a_host_agent_is_not_marked() {
122        let sender = host_but("boxed");
123        let sent = run(false, &sender, user("boxed"));
124        assert_eq!(runtime(&sent), Some("container"));
125        assert_eq!(sent.pointer("/amx/origin/from").unwrap(), "boxed", "the signed origin is kept");
126        assert_eq!(sent.pointer("/amx/verified").unwrap(), true);
127        assert_eq!(runtime(&run(false, &sender, user("hosted"))), None);
128    }
129
130    #[test]
131    fn a_sender_that_is_not_on_record_counts_as_a_container_and_a_service_is_left_alone() {
132        let unknown = |_: &str| WriterRuntime::Container;
133        assert_eq!(runtime(&run(false, &unknown, user("elsewhere"))), Some("container"));
134        let mut service = user("github-consumer");
135        service["amx"]["origin"]["kind"] = json!("service");
136        assert_eq!(runtime(&run(false, &unknown, service)), None);
137    }
138
139    #[test]
140    fn a_line_with_no_verified_amx_in_a_fork_of_a_container_is_the_containers_and_a_verified_one_is_not_touched() {
141        let sender = host_but("none");
142        let bare = json!({ "type": "assistant", "message": { "content": "![](/home/me/secret.png)" } });
143        assert_eq!(runtime(&run(true, &sender, bare.clone())), Some("container"));
144        assert_eq!(runtime(&run(false, &sender, bare)), None, "outside such a fork nothing is added");
145        // A forged stamp the vet dropped leaves no `amx`, so it reads as no stamp at all.
146        let hosted = json!({ "type": "assistant", "amx": { "v": 1, "verified": true, "writer": { "runtime": "host", "agent": "a" } } });
147        assert_eq!(runtime(&run(true, &sender, hosted)), Some("host"), "a verified stamp wins");
148        let typed = json!({ "type": "user", "message": { "content": "hi" }, "amx": { "v": 1, "verified": true, "origin": { "kind": "user" } } });
149        assert_eq!(runtime(&run(true, &sender, typed)), None, "the person's own line");
150    }
151
152    #[test]
153    fn a_streaming_delta_is_never_rewritten_and_a_line_keeps_its_trailing_newline() {
154        let delta = r#"{"type":"stream_event","event":{"x":1}}"#.to_string();
155        let mut lines = [format!("{delta}\n"), "{\"type\":\"assistant\"}".to_string()];
156        attribute_lines(true, &|_| WriterRuntime::Host, &mut lines);
157        assert_eq!(lines[0], format!("{delta}\n"));
158        assert!(lines[1].contains("\"container\"") && !lines[1].ends_with('\n'));
159    }
160
161    #[test]
162    fn a_line_that_is_not_json_is_left_as_it_is() {
163        let mut lines = ["not json".to_string()];
164        attribute_lines(true, &|_| WriterRuntime::Container, &mut lines);
165        assert_eq!(lines[0], "not json");
166    }
167}