agentmux_srv_core/backend/transcript/
attribution.rs1use 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
29pub 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
38fn 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
52pub 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": "" } });
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 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}