1use std::collections::HashMap;
2use std::fs::{self, OpenOptions};
3use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
4use std::path::Path;
5
6use tracevault_protocol::hooks::{parse_hook_event, HookResponse};
7use tracevault_protocol::streaming::{
8 extract_is_error_from_transcript, StreamEventRequest, StreamEventType, MAX_REQUEST_BYTES,
9};
10
11#[allow(clippy::type_complexity)]
21pub fn apply_context(
22 ctx: crate::context::EffectiveContext,
23) -> (
24 Option<String>,
25 Option<Vec<String>>,
26 Option<HashMap<String, String>>,
27) {
28 let flow_id = ctx.flow_id;
29 let labels = if ctx.labels.is_empty() {
30 None
31 } else {
32 Some(ctx.labels)
33 };
34 let params = if ctx.params.is_empty() {
35 None
36 } else {
37 Some(ctx.params.into_iter().collect())
38 };
39 (flow_id, labels, params)
40}
41
42pub fn read_new_transcript_lines(
51 transcript_path: &Path,
52 offset_path: &Path,
53) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
54 if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
60 return Ok((vec![], 0, 0));
61 }
62
63 let offset: i64 = if offset_path.exists() {
64 let content = fs::read_to_string(offset_path)?;
65 content
66 .trim()
67 .parse::<i64>()
68 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
69 } else {
70 0
71 };
72
73 let mut file = fs::File::open(transcript_path)?;
74 file.seek(SeekFrom::Start(offset as u64))?;
75
76 let reader = io::BufReader::new(file);
77 let mut lines = Vec::new();
78 let mut bytes_read = offset;
79
80 for line_result in reader.lines() {
81 let line = line_result?;
82 bytes_read += line.len() as i64 + 1;
84 if line.trim().is_empty() {
85 continue;
86 }
87 if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
88 lines.push(value);
89 }
90 }
91
92 Ok((lines, offset, bytes_read))
93}
94
95pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
103 if transcript_path.is_empty() {
104 return Ok(());
105 }
106 let meta_path = session_dir.join("metadata.json");
107 let mut meta = fs::read_to_string(&meta_path)
108 .ok()
109 .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
110 .filter(serde_json::Value::is_object)
111 .unwrap_or_else(|| serde_json::json!({}));
112 if meta.get("transcript_path").and_then(|v| v.as_str()) == Some(transcript_path) {
113 return Ok(());
114 }
115 meta["transcript_path"] = serde_json::Value::String(transcript_path.to_string());
116 let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
117 fs::write(&tmp, meta.to_string())?;
118 fs::rename(&tmp, &meta_path).inspect_err(|_| {
119 let _ = fs::remove_file(&tmp);
120 })
121}
122
123pub fn record_inline_tool_calls(
130 session_dir: &Path,
131 records: &[serde_json::Value],
132) -> Result<(), io::Error> {
133 let lines: String = records
134 .iter()
135 .flat_map(crate::transcript::tool_call_names)
136 .map(|name| {
137 let record = serde_json::json!({
138 "type": "message",
139 "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
140 });
141 format!("{record}\n")
142 })
143 .collect();
144 if lines.is_empty() {
145 return Ok(());
146 }
147 let log_path = session_dir.join("tool_calls.jsonl");
148 OpenOptions::new()
149 .create(true)
150 .append(true)
151 .open(&log_path)?
152 .write_all(lines.as_bytes())?;
153 record_transcript_path(session_dir, &log_path.to_string_lossy())
154}
155
156pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
157 let mut file = OpenOptions::new()
158 .create(true)
159 .append(true)
160 .open(pending_path)?;
161 writeln!(file, "{json}")?;
162 Ok(())
163}
164
165pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
166 if !pending_path.exists() {
167 return Ok(vec![]);
168 }
169 let content = fs::read_to_string(pending_path)?;
170 let lines: Vec<String> = content
171 .lines()
172 .filter(|l| !l.trim().is_empty())
173 .map(String::from)
174 .collect();
175 fs::remove_file(pending_path)?;
176 Ok(lines)
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
189pub(crate) enum Attribution {
190 Repo {
193 repo_id: String,
194 project: Option<uuid::Uuid>,
195 },
196 ProjectOnly { project_id: uuid::Uuid },
199}
200
201impl Attribution {
202 pub(crate) fn pending_file_name(&self) -> String {
211 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
212 match self {
213 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
214 Self::ProjectOnly { project_id } => {
215 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
216 }
217 }
218 }
219}
220
221pub(crate) fn attribution_for(
241 binding: Option<&crate::session_state::RepoBinding>,
242 project: Option<uuid::Uuid>,
243) -> Option<Attribution> {
244 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
245 Some(b) => Some(Attribution::Repo {
246 repo_id: b.repo_id.clone(),
247 project,
248 }),
249 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
250 }
251}
252
253fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
255 session_dir.join(attribution.pending_file_name())
256}
257
258pub fn resolve_session_paths(
271 hook_cwd: &Path,
272 session_id: &str,
273) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
274 let resolved = crate::paths::resolve_project_root(hook_cwd);
275 let session_dir = resolved
276 .root
277 .join(".tracevault")
278 .join("sessions")
279 .join(session_id);
280 (resolved, session_dir)
281}
282
283pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
291 uuid::Uuid::parse_str(repo_id).is_ok()
292}
293
294pub(crate) fn resolve_stream_binding(
298 session: &crate::session_state::SessionState,
299 worktree: &str,
300 bound: Option<crate::session_state::RepoBinding>,
301 user_default: Option<crate::session_state::RepoBinding>,
302) -> Option<crate::session_state::RepoBinding> {
303 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
304 repo_flag: None,
305 session,
306 worktree_path: Some(worktree),
307 bound,
308 user_default,
309 })
310 .map(|(b, _)| b)
311}
312
313pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
321 let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
322 let raw = raw.trim();
323 let parsed = raw.parse::<uuid::Uuid>().ok()?;
324 Some(crate::session_state::ProjectBinding {
325 project_id: parsed.to_string(),
326 project_name: String::new(),
327 updated_at: String::new(),
328 forced_until: None,
329 })
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
354pub(crate) struct AttributionForce {
355 pub(crate) env: bool,
358 pub(crate) binding: bool,
362}
363
364impl AttributionForce {
365 pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
368 if self.env || self.binding {
369 crate::api_client::AttributionMode::Explicit
370 } else {
371 crate::api_client::AttributionMode::Derived
372 }
373 }
374}
375
376pub(crate) fn attribution_mode(
428 effective: Option<&crate::session_state::ProjectBinding>,
429) -> crate::api_client::AttributionMode {
430 attribution_force(effective).mode()
431}
432
433pub(crate) fn attribution_force(
440 effective: Option<&crate::session_state::ProjectBinding>,
441) -> AttributionForce {
442 AttributionForce {
443 env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
444 .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
445 .unwrap_or(false),
446 binding: effective
447 .and_then(|b| b.forced_until.as_deref())
448 .is_some_and(|s| {
449 matches!(
450 crate::session_state::force_status(s),
451 crate::session_state::ForceStatus::Live(_)
452 )
453 }),
454 }
455}
456
457pub(crate) fn capture_binding(
477 session: &crate::session_state::SessionState,
478 worktree_path: Option<&str>,
479) -> Option<crate::session_state::ProjectBinding> {
480 use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
481 let (binding, _) = capture_project_binding(&CaptureProjectInputs {
482 project_flag: None,
483 env_project: env_project_binding(),
484 session,
485 worktree_path,
486 user_default: crate::user_project_default::load(),
487 })?;
488 capture_project_id(&binding)?;
493 Some(binding)
494}
495
496pub(crate) fn capture_project(
506 session: &crate::session_state::SessionState,
507 worktree_path: Option<&str>,
508) -> Option<uuid::Uuid> {
509 capture_binding(session, worktree_path)
510 .as_ref()
511 .and_then(crate::resolution::capture_project_id)
512}
513
514fn undeliverable_warning(pid: uuid::Uuid) -> String {
517 format!(
518 "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
519 repo binding, so there is nothing to attribute these events to and they are being \
520 DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
521 that exists."
522 )
523}
524
525#[derive(Debug, PartialEq, Eq)]
546pub(crate) enum ClientErrorKind {
547 Forbidden,
549 Scoping,
551}
552
553pub(crate) fn refused_error(
584 pid: uuid::Uuid,
585 kind: &ClientErrorKind,
586 force: AttributionForce,
587) -> String {
588 let base = match kind {
589 ClientErrorKind::Forbidden => format!(
595 "tracevault: error: the server refused to attribute this event to active project \
596 {pid} (403). Either that project does not apply to this repo (not a member, or \
597 no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
598 binding is the machine-wide default in `user_project.toml`) — or this account has \
599 no `tracevault` grant in Control Plane at all, which an administrator must grant. \
600 The event was NOT re-attributed elsewhere; it has been queued and will be retried \
601 once the binding or the grant is fixed."
602 ),
603 ClientErrorKind::Scoping => format!(
604 "tracevault: error: active project {pid} does not apply to this repo (not a member, \
605 missing permission, or the project no longer exists). The event was NOT \
606 re-attributed elsewhere; it has been queued and will be retried once the binding is \
607 fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
608 machine-wide default in `user_project.toml`) to update it."
609 ),
610 };
611 if force.mode() == crate::api_client::AttributionMode::Explicit
612 && matches!(kind, ClientErrorKind::Forbidden)
613 {
614 return format!(
615 "{base} This send declared `explicit` attribution, so the refusal may be of the \
616 FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
617 identity (a `tvk_` API key can never force). If membership attribution is what \
618 you want, {}",
619 force_remediation(force)
620 );
621 }
622 base
623}
624
625fn force_remediation(force: AttributionForce) -> String {
642 let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
643 process-wide and never expires, so no switch clears it)";
644 let binding_fix = "run `tracevault project switch <name>` WITHOUT \
645 `--project-attribution explicit` (add `--user` if the forced binding \
646 is the machine-wide default in `user_project.toml`)";
647 match (force.env, force.binding) {
648 (true, false) => format!("{env_fix}."),
649 (false, true) => format!("{binding_fix}."),
650 (true, true) => {
652 format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
653 }
654 (false, false) => format!("{env_fix}, or {binding_fix}."),
655 }
656}
657
658pub(crate) fn deterministic_client_error_kind(
659 e: &dyn std::error::Error,
660) -> Option<ClientErrorKind> {
661 let s = e.to_string();
662 if s.contains("(403 ") {
669 return Some(ClientErrorKind::Forbidden);
670 }
671 if ["(400 ", "(404 ", "(409 "]
672 .iter()
673 .any(|marker| s.contains(marker))
674 {
675 return Some(ClientErrorKind::Scoping);
676 }
677 None
678}
679
680async fn send_stream_event(
733 client: &crate::api_client::ApiClient,
734 attribution: &Attribution,
735 force: AttributionForce,
736 req: &StreamEventRequest,
737 warned: &mut bool,
738) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
739{
740 let (repo_id, capture_pid) = match attribution {
741 Attribution::ProjectOnly { project_id } => {
759 let attempt = client
760 .stream_event_for_project(*project_id, None, force.mode(), req)
761 .await;
762 return match attempt {
763 Ok(r) => Ok(Some(r)),
764 Err(e) => match deterministic_client_error_kind(e.as_ref()) {
765 Some(ClientErrorKind::Scoping) => {
766 if !*warned {
767 eprintln!("{}", undeliverable_warning(*project_id));
768 *warned = true;
769 }
770 Ok(None)
771 }
772 _ => Err(e),
773 },
774 };
775 }
776 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
777 };
778 match capture_pid {
779 None => client.stream_event(repo_id, req).await.map(Some),
780 Some(pid) => {
781 let attempt = client
782 .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
783 .await;
784 let kind = match &attempt {
785 Ok(_) => None,
786 Err(e) => deterministic_client_error_kind(e.as_ref()),
787 };
788 match (attempt, kind) {
789 (Ok(r), _) => Ok(Some(r)),
790 (Err(e), Some(kind)) => {
791 if !*warned {
792 eprintln!("{}", refused_error(pid, &kind, force));
800 *warned = true;
801 }
802 Err(e)
808 }
809 (Err(e), None) => Err(e),
811 }
812 }
813 }
814}
815
816pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
822 (start_offset, start_offset + records_len)
823}
824
825pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
841 if req.serialized_len() <= MAX_REQUEST_BYTES {
842 return vec![req];
843 }
844 let lines = req.transcript_lines.take().unwrap_or_default();
845 let batch_offset = req.transcript_offset.unwrap_or(0);
846 req.truncate_large_fields();
849
850 let sizes: Vec<usize> = lines
852 .iter()
853 .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
854 .collect();
855 let envelope = |r: &StreamEventRequest| {
856 let mut r = r.clone();
857 r.transcript_lines = Some(vec![]);
858 r.serialized_len()
859 };
860
861 let mut tail_start = lines.len();
863 let mut used = envelope(&req);
864 while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
865 tail_start -= 1;
866 used += sizes[tail_start];
867 }
868
869 let transcript_template = transcript_template(&req);
870 let transcript_envelope = envelope(&transcript_template);
871
872 let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
874 let mut start = 0;
875 while start < tail_start {
876 let mut end = start + 1;
877 let mut used = transcript_envelope + sizes[start];
878 while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
879 used += sizes[end];
880 end += 1;
881 }
882 groups.push(start..end);
883 start = end;
884 }
885 groups.push(tail_start..lines.len());
886
887 let last = groups.len() - 1;
888 let mut lines = lines.into_iter();
889 groups
890 .into_iter()
891 .enumerate()
892 .map(|(n, range)| {
893 let mut part = if n == last {
894 req.clone()
895 } else {
896 transcript_template.clone()
897 };
898 let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
899 part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
900 part.transcript_offset = Some(batch_offset + range.start as i64);
901 part
902 })
903 .collect()
904}
905
906pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
911 StreamEventRequest {
912 protocol_version: req.protocol_version,
913 tool: req.tool.clone(),
914 event_type: StreamEventType::Transcript,
915 session_id: req.session_id.clone(),
916 timestamp: req.timestamp,
917 hook_event_name: req.hook_event_name.clone(),
918 tool_name: None,
919 tool_use_id: None,
920 tool_input: None,
921 tool_response: None,
922 tool_is_error: None,
923 event_index: None,
924 event_uuid: None,
925 transcript_lines: None,
926 transcript_offset: req.transcript_offset,
927 model: req.model.clone(),
928 cwd: req.cwd.clone(),
929 final_stats: None,
930 flow_id: req.flow_id.clone(),
931 labels: req.labels.clone(),
932 params: req.params.clone(),
933 billing_mode: req.billing_mode,
934 }
935}
936
937#[allow(clippy::too_many_arguments)]
958async fn deliver_subagent_transcripts(
959 client: &crate::api_client::ApiClient,
960 attribution: &Attribution,
961 force: AttributionForce,
962 template: &StreamEventRequest,
963 transcript_path: &Path,
964 session_dir: &Path,
965 pending_path: &Path,
966 mut send_failed: bool,
967 deadline: std::time::Instant,
968 wait_for_lock: Option<std::time::Instant>,
969 warned: &mut bool,
970) -> Result<(), Box<dyn std::error::Error>> {
971 for file in crate::subagents::transcripts(transcript_path) {
972 let offset_path = crate::subagents::offset_path(session_dir, &file);
973 let lock = loop {
975 match crate::subagents::try_lock(&offset_path) {
976 Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
977 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
978 }
979 other => break other,
980 }
981 };
982 let _lock = match lock {
983 Ok(Some(lock)) => lock,
984 Ok(None) => {
985 if wait_for_lock.is_some() {
986 eprintln!(
987 "tracevault: warning: skipping subagent transcript {}: \
988 another hook is still sending it",
989 file.display()
990 );
991 }
992 continue;
993 }
994 Err(e) => {
995 eprintln!(
996 "tracevault: warning: skipping subagent transcript {}: cannot lock: {e}",
997 file.display()
998 );
999 continue;
1000 }
1001 };
1002 let (lines, start, end) = match crate::subagents::read_new_lines(&file, &offset_path) {
1003 Ok(read) => read,
1004 Err(e) => {
1005 eprintln!(
1006 "tracevault: warning: skipping subagent transcript {}: {e}",
1007 file.display()
1008 );
1009 continue;
1010 }
1011 };
1012 if end == start {
1013 continue;
1014 }
1015 let mut accepted = true;
1017 if !lines.is_empty() {
1018 let mut req = template.clone();
1019 req.transcript_lines = Some(lines);
1020 req.transcript_offset = Some(start);
1021 accepted = deliver_parts(
1022 client,
1023 attribution,
1024 force,
1025 split_into_parts(req),
1026 pending_path,
1027 send_failed,
1028 deadline,
1029 warned,
1030 )
1031 .await?;
1032 send_failed |= !accepted;
1033 }
1034 if accepted {
1035 crate::subagents::write_offset(&offset_path, end)?;
1036 }
1037 }
1038 Ok(())
1039}
1040
1041pub fn resolve_transcript_source(
1047 inline_records: Option<Vec<serde_json::Value>>,
1048 prior_offset: i64,
1049 file_result: (Vec<serde_json::Value>, i64, i64),
1050) -> (Vec<serde_json::Value>, i64, i64) {
1051 match inline_records {
1052 Some(records) => {
1053 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1054 (records, send, next)
1055 }
1056 None => file_result,
1057 }
1058}
1059
1060pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1066 lines.iter().find_map(|line| {
1067 let msg = line.get("message")?;
1068 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1069 Some(
1070 msg.get("isError")
1071 .and_then(|v| v.as_bool())
1072 .unwrap_or(false),
1073 )
1074 } else {
1075 None
1076 }
1077 })
1078}
1079
1080pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1084 req.tool = Some(agent.tool_name().to_string());
1085 req.protocol_version = agent.protocol_version() as u32;
1086}
1087
1088const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1094
1095const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1100
1101const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1108
1109#[allow(clippy::too_many_arguments)]
1117async fn deliver_parts(
1118 client: &crate::api_client::ApiClient,
1119 attribution: &Attribution,
1120 force: AttributionForce,
1121 parts: Vec<StreamEventRequest>,
1122 pending_path: &Path,
1123 mut send_failed: bool,
1124 deadline: std::time::Instant,
1125 warned: &mut bool,
1126) -> Result<bool, Box<dyn std::error::Error>> {
1127 let mut all_accepted = true;
1128 for part in parts {
1129 send_failed = send_failed || std::time::Instant::now() >= deadline;
1130 if !send_failed {
1131 let send = send_stream_event(client, attribution, force, &part, warned);
1132 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1133 Ok(Ok(_)) => continue,
1134 Ok(Err(_)) | Err(_) => send_failed = true,
1135 }
1136 }
1137 all_accepted = false;
1138 append_pending(pending_path, &serde_json::to_string(&part)?)?;
1139 }
1140 Ok(all_accepted)
1141}
1142
1143pub async fn run_stream(
1144 event_type: &str,
1145 agent: crate::agent::Agent,
1146) -> Result<(), Box<dyn std::error::Error>> {
1147 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1149 let mut input = String::new();
1150 io::stdin().read_to_string(&mut input)?;
1151 let mut hook_event = parse_hook_event(&input)?;
1152
1153 let hook_cwd = Path::new(&hook_event.cwd);
1169 let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1170 if resolved.source == crate::paths::ProjectRootSource::Fallback {
1171 eprintln!(
1176 "tracevault: warning: could not resolve a git project root from {}; \
1177 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1178 that it runs inside the repository to keep sessions under the repo root.",
1179 hook_cwd.display()
1180 );
1181 }
1182 let project_root = resolved.root;
1183
1184 fs::create_dir_all(&session_dir)?;
1186
1187 let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
1193
1194 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1199 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1200
1201 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1205 if let Some(records) = &hook_event.transcript_records {
1210 let _ = record_inline_tool_calls(&session_dir, records);
1211 }
1212
1213 let event_uuid = uuid::Uuid::now_v7();
1218
1219 let transcript_path = Path::new(&hook_event.transcript_path);
1221 let offset_path = session_dir.join(".stream_offset");
1222 let sends_main = event_type != "subagent-stop";
1229 let (transcript_lines, start_offset, new_offset) = if sends_main {
1230 read_new_transcript_lines(transcript_path, &offset_path)?
1231 } else {
1232 (vec![], 0, 0)
1233 };
1234
1235 let is_inline = hook_event.transcript_records.is_some();
1252 let (transcript_lines, start_offset, new_offset) = if is_inline {
1253 let prior_offset: i64 = if offset_path.exists() {
1260 let content = fs::read_to_string(&offset_path)?;
1261 content
1262 .trim()
1263 .parse::<i64>()
1264 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1265 .max(0)
1266 } else {
1267 0
1268 };
1269 resolve_transcript_source(
1273 hook_event.transcript_records.take(),
1274 prior_offset,
1275 (transcript_lines, start_offset, new_offset),
1276 )
1277 } else {
1278 (transcript_lines, start_offset, new_offset)
1279 };
1280 let stream_event_type = match event_type {
1282 "notification" => StreamEventType::SessionStart,
1283 "stop" => StreamEventType::SessionEnd,
1284 _ => StreamEventType::ToolUse,
1285 };
1286
1287 let tool_is_error = hook_event
1292 .tool_use_id
1293 .as_deref()
1294 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1295 .or_else(|| inline_tool_is_error(&transcript_lines));
1296
1297 let config = crate::config::TracevaultConfig::try_load(&project_root);
1307 let repo_uc = config
1311 .as_ref()
1312 .ok()
1313 .and_then(|opt| opt.as_ref())
1314 .and_then(|c| c.user_context.clone());
1315 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1316
1317 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1323 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1324
1325 let mut req = StreamEventRequest {
1326 protocol_version: 1,
1327 tool: Some("claude-code".to_string()),
1328 event_type: stream_event_type,
1329 session_id: hook_event.session_id.clone(),
1330 timestamp: chrono::Utc::now(),
1331 hook_event_name: Some(hook_event.hook_event_name.clone()),
1332 tool_name: hook_event.tool_name.clone(),
1333 tool_use_id: hook_event.tool_use_id.clone(),
1334 tool_input: hook_event.tool_input.clone(),
1335 tool_response: hook_event.tool_response.clone(),
1336 tool_is_error,
1337 event_index: None,
1338 event_uuid: Some(event_uuid),
1339 transcript_lines: None,
1340 transcript_offset: Some(start_offset),
1341 model: None,
1342 cwd: Some(hook_event.cwd.clone()),
1343 final_stats: None,
1344 flow_id: ctx_flow_id,
1345 labels: ctx_labels,
1346 params: ctx_params,
1347 billing_mode: Some(crate::billing::detect_current(
1348 agent,
1349 hook_cwd,
1350 &hook_event.transcript_path,
1351 )),
1352 };
1353
1354 stamp_agent(&mut req, agent);
1355 let subagent_template = transcript_template(&req);
1357 if !transcript_lines.is_empty() {
1358 req.transcript_lines = Some(transcript_lines);
1359 }
1360
1361 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
1363
1364 if let Err(e) = &config {
1373 return Err(format!("malformed .tracevault/config.toml: {e}").into());
1374 }
1375
1376 let session = crate::session_state::load(&hook_event.session_id);
1381 let bound = config
1382 .as_ref()
1383 .ok()
1384 .and_then(|opt| opt.as_ref())
1385 .and_then(crate::resolution::binding_from_config);
1386 let user_default = crate::user_default::load();
1387 let mut binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
1388 let client = server_url
1393 .as_deref()
1394 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1395 if binding.is_none() {
1396 if let Some(client) = &client {
1397 let auto =
1398 crate::auto_bind::bind_session(&hook_event.session_id, hook_cwd, client, deadline)
1399 .await;
1400 if let Some(notice) = auto.notice {
1401 eprintln!("{notice}");
1402 }
1403 binding = auto.binding;
1404 }
1405 }
1406 let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
1409 let response = HookResponse::allow();
1410 println!("{}", serde_json::to_string(&response)?);
1411 Ok(())
1412 };
1413 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1423 let capture_pid = capture_binding
1424 .as_ref()
1425 .and_then(crate::resolution::capture_project_id);
1426 let force = attribution_force(capture_binding.as_ref());
1433
1434 let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1440 no_op_allow()?;
1441 return Ok(());
1442 };
1443
1444 let client = client.ok_or("server_url not configured")?;
1446
1447 let pending_path = pending_path_for(&session_dir, &attribution);
1449 let pending_events = drain_pending(&pending_path)?;
1450
1451 let mut send_failed = false;
1452 let mut warned = false;
1456
1457 for (i, pending_json) in pending_events.iter().enumerate() {
1461 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1462 if std::time::Instant::now() >= deadline
1466 || !matches!(
1467 tokio::time::timeout_at(
1468 (deadline + IN_FLIGHT_GRACE).into(),
1469 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1470 )
1471 .await,
1472 Ok(Ok(_))
1473 )
1474 {
1475 for evt in &pending_events[i..] {
1482 append_pending(&pending_path, evt)?;
1483 }
1484 send_failed = true;
1485 break;
1486 }
1487 }
1488 }
1489
1490 let all_accepted = if sends_main {
1493 deliver_parts(
1494 &client,
1495 &attribution,
1496 force,
1497 split_into_parts(req),
1498 &pending_path,
1499 send_failed,
1500 deadline,
1501 &mut warned,
1502 )
1503 .await?
1504 } else {
1505 true
1506 };
1507 if sends_main && (all_accepted || is_inline) {
1519 fs::write(&offset_path, new_offset.to_string())?;
1520 }
1521
1522 if agent == crate::agent::Agent::ClaudeCode {
1527 deliver_subagent_transcripts(
1528 &client,
1529 &attribution,
1530 force,
1531 &subagent_template,
1532 transcript_path,
1533 &session_dir,
1534 &pending_path,
1535 send_failed || !all_accepted,
1536 deadline,
1537 matches!(event_type, "stop" | "subagent-stop").then(|| deadline + FINAL_LOCK_WAIT),
1538 &mut warned,
1539 )
1540 .await?;
1541 }
1542
1543 let response = HookResponse::allow();
1545 println!("{}", serde_json::to_string(&response)?);
1546
1547 Ok(())
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552 use super::*;
1553 use crate::api_client::AttributionMode;
1554 use crate::config::UserContext;
1555 use crate::context::{Context, EffectiveContext};
1556 use std::collections::BTreeMap;
1557
1558 #[test]
1561 fn disabled_user_context_resolves_to_none() {
1562 assert!(UserContext::Toggle(false).resolve().is_none());
1566 }
1567
1568 #[test]
1569 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1570 let dir = tempfile::tempdir().unwrap();
1574 let effective = Context::effective(dir.path(), None);
1575 assert_eq!(effective, EffectiveContext::default());
1576 }
1577
1578 #[test]
1581 fn apply_context_stamps_all_fields() {
1582 let dir = tempfile::tempdir().unwrap();
1583 let mut params = BTreeMap::new();
1584 params.insert("env".to_string(), "prod".to_string());
1585 params.insert("region".to_string(), "eu-west-1".to_string());
1586
1587 let ctx = EffectiveContext {
1588 flow_id: Some("flow-xyz".to_string()),
1589 labels: vec!["backend".to_string(), "urgent".to_string()],
1590 params,
1591 };
1592
1593 let (flow_id, labels, params_out) = apply_context(ctx);
1594
1595 assert_eq!(flow_id, Some("flow-xyz".to_string()));
1596 assert_eq!(
1597 labels,
1598 Some(vec!["backend".to_string(), "urgent".to_string()])
1599 );
1600 let p = params_out.expect("params should be Some");
1601 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1602 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1603
1604 let written = Context {
1607 flow_id: Some("flow-xyz".to_string()),
1608 labels: vec!["backend".to_string(), "urgent".to_string()],
1609 params: {
1610 let mut m = BTreeMap::new();
1611 m.insert("env".to_string(), Some("prod".to_string()));
1612 m.insert("region".to_string(), Some("eu-west-1".to_string()));
1613 m
1614 },
1615 };
1616 let ctx_path = dir.path().join(".tracevault").join("context.json");
1617 written.save_to(&ctx_path).unwrap();
1618 let loaded = Context::load_from(&ctx_path);
1619 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1620 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1621 assert!(labels2.is_some());
1622 assert!(params2.is_some());
1623 }
1624
1625 #[test]
1628 fn apply_context_missing_file_all_none() {
1629 let dir = tempfile::tempdir().unwrap();
1630 let missing_path = dir.path().join(".tracevault").join("context.json");
1631 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1633 assert!(flow_id.is_none(), "flow_id should be None");
1634 assert!(labels.is_none(), "labels should be None");
1635 assert!(params.is_none(), "params should be None");
1636 }
1637
1638 #[test]
1641 fn apply_context_empty_collections_are_none() {
1642 let ctx = EffectiveContext {
1643 flow_id: None,
1644 labels: vec![],
1645 params: BTreeMap::new(),
1646 };
1647 let (flow_id, labels, params) = apply_context(ctx);
1648 assert!(flow_id.is_none());
1649 assert!(
1650 labels.is_none(),
1651 "empty labels should be None, not Some([])"
1652 );
1653 assert!(
1654 params.is_none(),
1655 "empty params should be None, not Some({{}})"
1656 );
1657 }
1658
1659 #[test]
1662 fn apply_context_flow_id_only() {
1663 let ctx = EffectiveContext {
1664 flow_id: Some("my-flow".to_string()),
1665 labels: vec![],
1666 params: BTreeMap::new(),
1667 };
1668 let (flow_id, labels, params) = apply_context(ctx);
1669 assert_eq!(flow_id, Some("my-flow".to_string()));
1670 assert!(labels.is_none());
1671 assert!(params.is_none());
1672 }
1673
1674 use crate::test_helpers::{add_worktree, init_git_repo};
1681
1682 #[test]
1685 fn resolve_session_paths_primary_checkout() {
1686 let tmp = tempfile::tempdir().unwrap();
1687 let repo = tmp.path().join("repo");
1688 std::fs::create_dir_all(&repo).unwrap();
1689 init_git_repo(&repo);
1690 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1692
1693 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1694 let project_root = resolved.root;
1695
1696 assert_eq!(
1697 project_root.canonicalize().unwrap(),
1698 repo.canonicalize().unwrap(),
1699 "primary checkout: project_root must be repo root"
1700 );
1701 assert_eq!(
1702 session_dir.canonicalize().unwrap_or(session_dir.clone()),
1703 repo.join(".tracevault")
1704 .join("sessions")
1705 .join("sess-primary-123"),
1706 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1707 );
1708 assert!(
1710 session_dir.starts_with(&repo),
1711 "session_dir must be under the primary repo root"
1712 );
1713 }
1714
1715 #[test]
1719 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1720 let tmp = tempfile::tempdir().unwrap();
1721 let repo = tmp.path().join("repo");
1722 let wt = tmp.path().join("sibling-wt");
1724
1725 std::fs::create_dir_all(&repo).unwrap();
1726 init_git_repo(&repo);
1727 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1729 add_worktree(&repo, &wt);
1730
1731 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1732 let project_root = resolved.root;
1733
1734 assert_eq!(
1736 project_root.canonicalize().unwrap(),
1737 repo.canonicalize().unwrap(),
1738 "sibling worktree: project_root must be primary repo root (not worktree dir)"
1739 );
1740 assert!(
1742 session_dir.starts_with(&repo),
1743 "sibling worktree: session_dir must be under the PRIMARY repo root"
1744 );
1745 assert!(
1746 !session_dir.starts_with(&wt),
1747 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1748 );
1749 assert!(
1750 session_dir.ends_with(
1751 std::path::Path::new(".tracevault")
1752 .join("sessions")
1753 .join("sess-sibling-456")
1754 ),
1755 "session_dir must end with .tracevault/sessions/<session_id>"
1756 );
1757 }
1758
1759 #[test]
1762 fn resolve_session_paths_non_git_fallback() {
1763 let tmp = tempfile::tempdir().unwrap();
1764 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1766 let project_root = resolved.root;
1767
1768 assert_eq!(
1769 project_root,
1770 tmp.path(),
1771 "non-git: project_root must fall back to hook_cwd"
1772 );
1773 assert_eq!(
1774 session_dir,
1775 tmp.path()
1776 .join(".tracevault")
1777 .join("sessions")
1778 .join("sess-fallback-789"),
1779 "non-git: session_dir must be relative to the fallback root"
1780 );
1781 }
1782
1783 #[test]
1788 fn origin_marker_written_in_session_dir() {
1789 let tmp = tempfile::tempdir().unwrap();
1790 let repo = tmp.path().join("repo");
1791 std::fs::create_dir_all(&repo).unwrap();
1792 init_git_repo(&repo);
1793
1794 let session_dir = repo
1795 .join(".tracevault")
1796 .join("sessions")
1797 .join("test-sess-001");
1798 std::fs::create_dir_all(&session_dir).unwrap();
1799
1800 let hook_cwd = &repo;
1801 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1802 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1803
1804 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1805 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1806 assert_eq!(
1807 origin_content.trim(),
1808 expected.as_str(),
1809 "origin marker must contain the canonicalized worktree toplevel"
1810 );
1811 }
1812
1813 fn metadata(session_dir: &Path) -> serde_json::Value {
1814 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
1815 .unwrap()
1816 }
1817
1818 #[test]
1819 fn record_transcript_path_writes_metadata_for_check() {
1820 let tmp = tempfile::tempdir().unwrap();
1821 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1822 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1823 }
1824
1825 #[test]
1826 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
1827 let tmp = tempfile::tempdir().unwrap();
1828 std::fs::write(
1829 tmp.path().join("metadata.json"),
1830 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
1831 )
1832 .unwrap();
1833 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
1834 let m = metadata(tmp.path());
1835 assert_eq!(m["transcript_path"], "/t/new.jsonl");
1836 assert_eq!(m["model"], "m");
1837 let leftovers = std::fs::read_dir(tmp.path())
1838 .unwrap()
1839 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
1840 .count();
1841 assert_eq!(leftovers, 0, "the temp file is renamed into place");
1842 }
1843
1844 #[test]
1845 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
1846 let tmp = tempfile::tempdir().unwrap();
1847 record_transcript_path(tmp.path(), "").unwrap();
1848 assert!(!tmp.path().join("metadata.json").exists());
1849
1850 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
1851 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1852 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1853 }
1854
1855 use crate::session_state::{RepoBinding, SessionState};
1858
1859 fn binding(id: &str) -> RepoBinding {
1860 RepoBinding {
1861 repo_id: id.into(),
1862 git_url: None,
1863 remote_id: None,
1864 codebase_name: None,
1865 updated_at: "t".into(),
1866 }
1867 }
1868
1869 #[test]
1872 fn resolve_stream_binding_uses_session_active_when_unbound() {
1873 let session = SessionState {
1874 active: Some(binding("session-repo")),
1875 subagents: HashMap::new(),
1876 ..Default::default()
1877 };
1878 let got = resolve_stream_binding(&session, "/wt/top", None, None);
1879 assert_eq!(got.unwrap().repo_id, "session-repo");
1880 }
1881
1882 #[test]
1885 fn resolve_stream_binding_falls_back_to_bound_config() {
1886 let session = SessionState::default();
1887 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1888 assert_eq!(got.unwrap().repo_id, "bound-repo");
1889 }
1890
1891 #[test]
1894 fn resolve_stream_binding_none_when_nothing_resolves() {
1895 let session = SessionState::default();
1896 let got = resolve_stream_binding(&session, "/wt/top", None, None);
1897 assert!(got.is_none());
1898 }
1899
1900 #[test]
1903 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1904 let session = SessionState {
1905 active: Some(binding("session-repo")),
1906 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1907 ..Default::default()
1908 };
1909 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1910 assert_eq!(got.unwrap().repo_id, "subagent-repo");
1911 }
1912
1913 #[test]
1917 fn resolve_stream_binding_falls_back_to_user_default() {
1918 let session = SessionState::default();
1919 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1920 assert_eq!(got.unwrap().repo_id, "userdef");
1921 }
1922
1923 #[test]
1926 fn resolve_stream_binding_prefers_bound_over_user_default() {
1927 let session = SessionState::default();
1928 let got = resolve_stream_binding(
1929 &session,
1930 "/wt/x",
1931 Some(binding("bound")),
1932 Some(binding("userdef")),
1933 );
1934 assert_eq!(got.unwrap().repo_id, "bound");
1935 }
1936
1937 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1940 crate::session_state::RepoBinding {
1941 repo_id: repo_id.into(),
1942 git_url: None,
1943 remote_id: None,
1944 codebase_name: None,
1945 updated_at: String::new(),
1946 }
1947 }
1948
1949 #[test]
1953 fn attribution_falls_back_to_project_when_no_repo_binds() {
1954 let pid = uuid::Uuid::new_v4();
1955 assert_eq!(
1956 attribution_for(None, Some(pid)),
1957 Some(Attribution::ProjectOnly { project_id: pid })
1958 );
1959 }
1960
1961 #[test]
1963 fn attribution_is_none_when_neither_repo_nor_project_binds() {
1964 assert_eq!(attribution_for(None, None), None);
1965 }
1966
1967 #[test]
1970 fn attribution_uses_repo_with_no_project_overlay() {
1971 let repo = uuid::Uuid::new_v4().to_string();
1972 let b = binding_with(&repo);
1973 assert_eq!(
1974 attribution_for(Some(&b), None),
1975 Some(Attribution::Repo {
1976 repo_id: repo,
1977 project: None
1978 })
1979 );
1980 }
1981
1982 #[test]
1985 fn attribution_overlays_project_on_repo() {
1986 let repo = uuid::Uuid::new_v4().to_string();
1987 let pid = uuid::Uuid::new_v4();
1988 let b = binding_with(&repo);
1989 assert_eq!(
1990 attribution_for(Some(&b), Some(pid)),
1991 Some(Attribution::Repo {
1992 repo_id: repo,
1993 project: Some(pid)
1994 })
1995 );
1996 }
1997
1998 #[test]
2001 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2002 let pid = uuid::Uuid::new_v4();
2003 let b = binding_with("../../escape");
2004 assert_eq!(
2005 attribution_for(Some(&b), Some(pid)),
2006 Some(Attribution::ProjectOnly { project_id: pid })
2007 );
2008 }
2009
2010 #[test]
2013 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2014 let b = binding_with("../../escape");
2015 assert_eq!(attribution_for(Some(&b), None), None);
2016 }
2017
2018 #[test]
2023 fn pending_file_name_for_a_repo_is_unchanged() {
2024 let repo = uuid::Uuid::new_v4().to_string();
2025 assert_eq!(
2026 Attribution::Repo {
2027 repo_id: repo.clone(),
2028 project: Some(uuid::Uuid::new_v4())
2029 }
2030 .pending_file_name(),
2031 format!("pending-{repo}.jsonl")
2032 );
2033 }
2034
2035 #[test]
2038 fn pending_file_name_for_a_project_is_distinct() {
2039 let pid = uuid::Uuid::new_v4();
2040 assert_eq!(
2041 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2042 format!("pending-project-{pid}.jsonl")
2043 );
2044 }
2045
2046 #[test]
2049 fn binding_repo_id_is_valid_accepts_real_uuid() {
2050 assert!(binding_repo_id_is_valid(
2051 "550e8400-e29b-41d4-a716-446655440000"
2052 ));
2053 }
2054
2055 #[test]
2056 fn binding_repo_id_is_valid_rejects_path_traversal() {
2057 assert!(!binding_repo_id_is_valid("../evil"));
2058 }
2059
2060 #[test]
2061 fn binding_repo_id_is_valid_rejects_empty() {
2062 assert!(!binding_repo_id_is_valid(""));
2063 }
2064
2065 #[test]
2066 fn binding_repo_id_is_valid_rejects_non_uuid() {
2067 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2068 }
2069
2070 #[test]
2073 fn stamp_agent_sets_tool_and_version() {
2074 use crate::agent::Agent;
2075 let mut req = StreamEventRequest {
2076 protocol_version: 1,
2077 tool: Some("claude-code".to_string()),
2078 event_type: StreamEventType::ToolUse,
2079 session_id: "s".into(),
2080 timestamp: chrono::Utc::now(),
2081 hook_event_name: None,
2082 tool_name: None,
2083 tool_use_id: None,
2084 tool_input: None,
2085 tool_response: None,
2086 tool_is_error: None,
2087 event_index: None,
2088 event_uuid: None,
2089 transcript_lines: None,
2090 transcript_offset: None,
2091 model: None,
2092 cwd: None,
2093 final_stats: None,
2094 flow_id: None,
2095 labels: None,
2096 params: None,
2097 billing_mode: None,
2098 };
2099 stamp_agent(&mut req, Agent::Codex);
2100 assert_eq!(req.tool.as_deref(), Some("codex"));
2101 assert_eq!(req.protocol_version, 2);
2102
2103 stamp_agent(&mut req, Agent::ClaudeCode);
2104 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2105 assert_eq!(req.protocol_version, 1);
2106 }
2107
2108 fn repo_attr(repo_id: &str) -> Attribution {
2111 Attribution::Repo {
2112 repo_id: repo_id.into(),
2113 project: None,
2114 }
2115 }
2116
2117 #[test]
2118 fn pending_path_is_repo_scoped() {
2119 let dir = std::path::Path::new("/tmp/sess");
2120 assert_eq!(
2121 pending_path_for(dir, &repo_attr("repo-a")),
2122 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2123 );
2124 assert_ne!(
2125 pending_path_for(dir, &repo_attr("repo-a")),
2126 pending_path_for(dir, &repo_attr("repo-b")),
2127 );
2128 }
2129
2130 #[test]
2133 fn pending_path_for_a_project_never_collides_with_a_repo() {
2134 let dir = std::path::Path::new("/tmp/sess");
2135 let pid = uuid::Uuid::from_u128(9);
2136 assert_eq!(
2137 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2138 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2139 );
2140 assert_ne!(
2141 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2142 pending_path_for(dir, &repo_attr(&pid.to_string())),
2143 );
2144 }
2145
2146 #[test]
2149 fn read_new_transcript_lines_empty_path_is_noop() {
2150 let dir = tempfile::tempdir().unwrap();
2154 let offset_path = dir.path().join(".stream_offset");
2155 let (lines, start_offset, end_offset) =
2156 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2157 assert!(
2158 lines.is_empty(),
2159 "empty path must yield no transcript lines"
2160 );
2161 assert_eq!(start_offset, 0);
2162 assert_eq!(end_offset, 0);
2163 }
2164
2165 #[test]
2169 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2170 let dir = tempfile::tempdir().unwrap();
2171 let transcript_path = dir.path().join("transcript.jsonl");
2172 let offset_path = dir.path().join(".stream_offset");
2173
2174 fs::write(
2175 &transcript_path,
2176 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2177 )
2178 .unwrap();
2179
2180 let (lines, start_offset, end_offset) =
2181 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2182 assert_eq!(lines.len(), 2);
2183 assert_eq!(start_offset, 0, "first read starts at byte 0");
2184 assert!(end_offset > 0);
2185
2186 fs::write(&offset_path, end_offset.to_string()).unwrap();
2187
2188 let mut f = OpenOptions::new()
2189 .append(true)
2190 .open(&transcript_path)
2191 .unwrap();
2192 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2193 drop(f);
2194
2195 let (lines2, start_offset2, end_offset2) =
2196 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2197 assert_eq!(lines2.len(), 1);
2198 assert_eq!(
2199 start_offset2, end_offset,
2200 "second read's start_offset must equal the first read's persisted end_offset"
2201 );
2202 assert!(end_offset2 > start_offset2);
2203 }
2204
2205 #[tokio::test]
2223 async fn capture_project_precedence_local_only() {
2224 use crate::session_state::{ProjectBinding, SessionState};
2225 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2226 let tmp = tempfile::tempdir().unwrap();
2227 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2228 _guard.set("XDG_CONFIG_HOME", tmp.path());
2229 _guard.set("HOME", tmp.path());
2230 _guard.remove("TRACEVAULT_PROJECT");
2231
2232 let pb = |id: &str| ProjectBinding {
2233 project_id: id.into(),
2234 project_name: "n".into(),
2235 updated_at: "".into(),
2236 forced_until: None,
2237 };
2238 let u = uuid::Uuid::from_u128;
2239 let s = SessionState {
2241 active_project: Some(pb(&u(2).to_string())),
2242 ..Default::default()
2243 };
2244 assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
2245 let mut s = s;
2247 s.subagent_projects
2248 .insert("/wt".into(), pb(&u(1).to_string()));
2249 assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
2250 assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
2252 assert_eq!(capture_project(&SessionState::default(), None), None);
2254 let bad = SessionState {
2256 active_project: Some(pb("not-a-uuid")),
2257 ..Default::default()
2258 };
2259 assert_eq!(capture_project(&bad, None), None);
2260 let path = crate::user_project_default::default_project_path().unwrap();
2262 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2263 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2264 assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
2265 }
2266
2267 #[test]
2278 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2279 use crate::session_state::{ProjectBinding, SessionState};
2280 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2281 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2282 _guard.remove("TRACEVAULT_PROJECT");
2283 let pid = uuid::Uuid::from_u128(2);
2284 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2285 let s = SessionState {
2286 active_project: Some(ProjectBinding {
2287 project_id: pid.to_string(),
2288 project_name: "n".into(),
2289 updated_at: "".into(),
2290 forced_until: Some(future.clone()),
2291 }),
2292 ..Default::default()
2293 };
2294 let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
2295 assert_eq!(got.forced_until, Some(future));
2296 }
2297
2298 #[test]
2303 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2304 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2308
2309 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2310 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2311
2312 _guard.set("TRACEVAULT_PROJECT", uuid);
2313 let got = env_project_binding().expect("uuid form is honoured");
2314 assert_eq!(got.project_id, uuid);
2315
2316 _guard.set("TRACEVAULT_PROJECT", "my-project");
2317 assert!(
2318 env_project_binding().is_none(),
2319 "a name is ignored on the network-free capture path"
2320 );
2321
2322 _guard.remove("TRACEVAULT_PROJECT");
2323 assert!(env_project_binding().is_none());
2324 }
2325
2326 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2334 crate::session_state::ProjectBinding {
2335 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2336 project_name: "p".into(),
2337 updated_at: chrono::Utc::now().to_rfc3339(),
2338 forced_until: forced_until.map(str::to_string),
2339 }
2340 }
2341
2342 #[test]
2343 fn env_force_is_explicit_and_needs_no_expiry() {
2344 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2345 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2346 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2347
2348 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2349 }
2350
2351 #[test]
2352 fn absent_or_unrecognised_env_is_derived() {
2353 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2354 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2355
2356 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2357 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2358
2359 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2364 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2365 }
2366
2367 #[test]
2373 fn live_binding_force_is_explicit_without_env() {
2374 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2375 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2376 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2377
2378 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2379 let binding = forced_binding(Some(&future));
2380
2381 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2382 }
2383
2384 #[test]
2391 fn lapsed_binding_force_is_derived_without_env() {
2392 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2393 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2394 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2395
2396 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2397 let binding = forced_binding(Some(&past));
2398
2399 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2400 }
2401
2402 #[test]
2407 fn unparseable_forced_until_is_derived() {
2408 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2409 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2410 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2411
2412 let binding = forced_binding(Some("not-a-timestamp"));
2413
2414 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2415 }
2416
2417 #[test]
2424 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2425 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2426 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2427 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2428
2429 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2430 let binding = forced_binding(Some(&past));
2431
2432 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2433 }
2434
2435 #[tokio::test]
2448 async fn session_scoped_force_is_honoured_on_the_wire() {
2449 use crate::session_state::{ProjectBinding, SessionState};
2450
2451 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2452 let tmp = tempfile::tempdir().unwrap();
2453 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2454 _guard.set("XDG_CONFIG_HOME", tmp.path());
2458 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2459 _guard.remove("TRACEVAULT_PROJECT");
2463
2464 let pid = uuid::Uuid::from_u128(321);
2465 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2466 let session = SessionState {
2467 active_project: Some(ProjectBinding {
2468 project_id: pid.to_string(),
2469 project_name: "proj".into(),
2470 updated_at: "".into(),
2471 forced_until: Some(future),
2472 }),
2473 ..Default::default()
2474 };
2475 let capture_binding = capture_binding(&session, None);
2476
2477 let resp = ok_stream_response();
2478 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2479 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2480 let req = sample_stream_event_request();
2481 let mut warned = false;
2482
2483 let got = send_stream_event(
2484 &client,
2485 &Attribution::ProjectOnly { project_id: pid },
2486 attribution_force(capture_binding.as_ref()),
2487 &req,
2488 &mut warned,
2489 )
2490 .await
2491 .expect("send_stream_event must succeed");
2492 assert_eq!(
2493 got.expect("a successful send returns a response").status,
2494 "accepted"
2495 );
2496
2497 let captured = rx
2498 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2499 .expect("no request captured");
2500 assert!(
2501 captured
2502 .to_lowercase()
2503 .contains("x-tracevault-project-attribution: explicit"),
2504 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2505 );
2506 }
2507
2508 #[test]
2517 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2518 use crate::session_state::{ProjectBinding, SessionState};
2519
2520 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2521 let tmp = tempfile::tempdir().unwrap();
2522 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2523 _guard.set("XDG_CONFIG_HOME", tmp.path());
2524 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2525
2526 let project_a = uuid::Uuid::from_u128(1);
2527 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2528 crate::user_project_default::save(&ProjectBinding {
2529 project_id: project_a.to_string(),
2530 project_name: "a".into(),
2531 updated_at: chrono::Utc::now().to_rfc3339(),
2532 forced_until: Some(future),
2533 })
2534 .unwrap();
2535
2536 let project_b = uuid::Uuid::from_u128(2);
2537 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2538
2539 let capture_binding = capture_binding(&SessionState::default(), None);
2540 assert_eq!(
2541 capture_binding.as_ref().map(|b| b.project_id.as_str()),
2542 Some(project_b.to_string()).as_deref(),
2543 "TRACEVAULT_PROJECT must outrank the user-level default"
2544 );
2545
2546 assert_eq!(
2547 attribution_mode(capture_binding.as_ref()),
2548 AttributionMode::Derived,
2549 "a force on the user-default project must not leak onto a DIFFERENT, \
2550 higher-precedence project that never asked to be forced"
2551 );
2552 }
2553
2554 use std::io::BufReader;
2557 use std::net::TcpListener;
2558 use std::sync::mpsc;
2559 use std::thread;
2560 use std::time::{Duration, Instant};
2561
2562 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2567
2568 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2573 let deadline = Instant::now() + ACCEPT_DEADLINE;
2574 loop {
2575 match listener.accept() {
2576 Ok((stream, _)) => {
2577 let _ = stream.set_nonblocking(false);
2582 return Some(stream);
2583 }
2584 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2585 if Instant::now() >= deadline {
2586 return None;
2587 }
2588 thread::sleep(Duration::from_millis(20));
2589 }
2590 Err(_) => return None,
2591 }
2592 }
2593 }
2594
2595 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2599
2600 fn capture_request_and_respond(
2620 stream: std::net::TcpStream,
2621 tx: &mpsc::Sender<String>,
2622 response: &str,
2623 ) {
2624 let mut reader = BufReader::new(stream);
2625 let mut captured = String::new();
2626 let _ = reader.read_line(&mut captured);
2627 loop {
2628 let mut header = String::new();
2629 if reader.read_line(&mut header).unwrap_or(0) == 0 {
2630 break;
2631 }
2632 if header.trim().is_empty() {
2633 break;
2634 }
2635 captured.push_str(&header);
2636 }
2637 let _ = tx.send(captured);
2638 let mut stream = reader.into_inner();
2639 let _ = stream.write_all(response.as_bytes());
2640 let _ = stream.flush();
2641 }
2642
2643 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2648 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2649 listener.set_nonblocking(true).unwrap();
2650 let addr = listener.local_addr().unwrap();
2651 let (tx, rx) = mpsc::channel();
2652 thread::spawn(move || {
2653 if let Some(stream) = accept_with_deadline(&listener) {
2654 capture_request_and_respond(stream, &tx, response);
2655 }
2656 });
2657 (format!("http://{addr}"), rx)
2658 }
2659
2660 fn ok_stream_response() -> String {
2661 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2662 session_db_id: uuid::Uuid::nil(),
2663 event_db_id: Some(uuid::Uuid::nil()),
2664 status: "accepted".to_string(),
2665 })
2666 .unwrap();
2667 format!(
2668 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2669 body.len(),
2670 body
2671 )
2672 }
2673
2674 fn sample_stream_event_request() -> StreamEventRequest {
2675 StreamEventRequest {
2676 protocol_version: 2,
2677 tool: Some("claude-code".to_string()),
2678 event_type: StreamEventType::ToolUse,
2679 session_id: "sess-1".into(),
2680 timestamp: chrono::Utc::now(),
2681 hook_event_name: Some("PostToolUse".into()),
2682 tool_name: None,
2683 tool_use_id: None,
2684 tool_input: None,
2685 tool_response: None,
2686 tool_is_error: None,
2687 event_index: None,
2688 event_uuid: None,
2689 transcript_lines: None,
2690 transcript_offset: None,
2691 model: None,
2692 cwd: None,
2693 final_stats: None,
2694 flow_id: None,
2695 labels: None,
2696 params: None,
2697 billing_mode: None,
2698 }
2699 }
2700
2701 #[tokio::test]
2706 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2707 use crate::session_state::{ProjectBinding, SessionState};
2708
2709 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2713 let tmp = tempfile::tempdir().unwrap();
2714 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2715 _guard.set("XDG_CONFIG_HOME", tmp.path());
2716 _guard.remove("TRACEVAULT_PROJECT");
2721 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2722
2723 let pid = uuid::Uuid::from_u128(99);
2724 let session = SessionState {
2725 active_project: Some(ProjectBinding {
2726 project_id: pid.to_string(),
2727 project_name: "proj".into(),
2728 updated_at: "".into(),
2729 forced_until: None,
2730 }),
2731 ..Default::default()
2732 };
2733 let capture_binding = capture_binding(&session, None);
2734 let capture_pid = capture_binding
2735 .as_ref()
2736 .and_then(crate::resolution::capture_project_id);
2737 assert_eq!(capture_pid, Some(pid));
2738
2739 let resp = ok_stream_response();
2740 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2741 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2742 let req = sample_stream_event_request();
2743
2744 let mut warned = false;
2745 let got = send_stream_event(
2746 &client,
2747 &Attribution::Repo {
2748 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2749 project: capture_pid,
2750 },
2751 attribution_force(capture_binding.as_ref()),
2752 &req,
2753 &mut warned,
2754 )
2755 .await
2756 .expect("send_stream_event must succeed");
2757 assert_eq!(
2758 got.expect("a successful send returns a response").status,
2759 "accepted"
2760 );
2761
2762 let line = rx
2763 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2764 .expect("no request captured");
2765 assert!(
2766 line.starts_with(&format!(
2767 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2768 )),
2769 "an active project binding must route to the project-scoped endpoint, got: {line}"
2770 );
2771 assert!(
2777 line.to_lowercase()
2778 .contains("x-tracevault-project-attribution: derived"),
2779 "got: {line}"
2780 );
2781 }
2782
2783 #[tokio::test]
2788 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2789 use crate::session_state::SessionState;
2790
2791 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2792 let tmp = tempfile::tempdir().unwrap();
2793 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2794 _guard.set("XDG_CONFIG_HOME", tmp.path());
2799 _guard.remove("TRACEVAULT_PROJECT");
2800
2801 let capture_binding = capture_binding(&SessionState::default(), None);
2802 assert_eq!(capture_binding, None);
2803
2804 let resp = ok_stream_response();
2805 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2806 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2807 let req = sample_stream_event_request();
2808
2809 let mut warned = false;
2810 let got = send_stream_event(
2811 &client,
2812 &Attribution::Repo {
2813 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2814 project: None,
2815 },
2816 attribution_force(capture_binding.as_ref()),
2817 &req,
2818 &mut warned,
2819 )
2820 .await
2821 .expect("send_stream_event must succeed");
2822 assert_eq!(
2823 got.expect("a successful send returns a response").status,
2824 "accepted"
2825 );
2826
2827 let line = rx
2828 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2829 .expect("no request captured");
2830 assert!(
2831 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
2832 "no binding must fall back to the repo-scoped endpoint, got: {line}"
2833 );
2834 }
2835
2836 fn spawn_n_capturing_requests(
2847 responses: Vec<&'static str>,
2848 ) -> (String, mpsc::Receiver<String>) {
2849 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2850 listener.set_nonblocking(true).unwrap();
2851 let addr = listener.local_addr().unwrap();
2852 let (tx, rx) = mpsc::channel();
2853 thread::spawn(move || {
2854 for response in responses {
2855 let Some(stream) = accept_with_deadline(&listener) else {
2860 break;
2861 };
2862 capture_request_and_respond(stream, &tx, response);
2863 }
2864 });
2869 (format!("http://{addr}"), rx)
2870 }
2871
2872 #[tokio::test]
2879 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
2880 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
2881 let resp_400 = format!(
2882 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2883 body_400.len(),
2884 body_400
2885 );
2886 let resp_200 = ok_stream_response();
2887
2888 let (base, rx) = spawn_n_capturing_requests(vec![
2889 Box::leak(resp_400.into_boxed_str()),
2890 Box::leak(resp_200.into_boxed_str()),
2891 ]);
2892 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2893 let req = sample_stream_event_request();
2894 let pid = uuid::Uuid::from_u128(42);
2895
2896 let mut warned = false;
2897 let err = send_stream_event(
2898 &client,
2899 &Attribution::Repo {
2900 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2901 project: Some(pid),
2902 },
2903 attribution_force(None),
2904 &req,
2905 &mut warned,
2906 )
2907 .await
2908 .expect_err("a refused declared project must be an error, not a silent fallback");
2909 assert!(
2910 err.to_string().contains("400"),
2911 "propagated error must reflect the status, got: {err}"
2912 );
2913 assert!(
2914 warned,
2915 "the refusal must be printed (gated on `warned`) so it is visible"
2916 );
2917
2918 let first = rx
2919 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2920 .expect("no first request captured");
2921 assert!(
2922 first.contains(&format!("/projects/{pid}/stream")),
2923 "first request must hit the project-scoped endpoint, got: {first}"
2924 );
2925 assert!(
2926 first.contains("repo_id="),
2927 "first request must carry repo_id, got: {first}"
2928 );
2929
2930 assert!(
2931 rx.recv_timeout(Duration::from_millis(500)).is_err(),
2932 "no second (repo-scoped fallback) request must be sent"
2933 );
2934 }
2935
2936 #[tokio::test]
2939 async fn send_stream_event_errors_on_403_without_fallback() {
2940 let body_403 = "forbidden";
2941 let resp_403 = format!(
2942 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2943 body_403.len(),
2944 body_403
2945 );
2946 let resp_200 = ok_stream_response();
2947
2948 let (base, rx) = spawn_n_capturing_requests(vec![
2949 Box::leak(resp_403.into_boxed_str()),
2950 Box::leak(resp_200.into_boxed_str()),
2951 ]);
2952 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2953 let req = sample_stream_event_request();
2954 let pid = uuid::Uuid::from_u128(43);
2955
2956 let mut warned = false;
2957 let err = send_stream_event(
2958 &client,
2959 &Attribution::Repo {
2960 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2961 project: Some(pid),
2962 },
2963 attribution_force(None),
2964 &req,
2965 &mut warned,
2966 )
2967 .await
2968 .expect_err("a refused declared project must be an error, not a silent fallback");
2969 assert!(
2970 err.to_string().contains("403"),
2971 "propagated error must reflect the status, got: {err}"
2972 );
2973 assert!(
2974 warned,
2975 "the refusal must be printed (gated on `warned`) so it is visible"
2976 );
2977
2978 let first = rx
2979 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2980 .expect("no first request captured");
2981 assert!(
2982 first.contains(&format!("/projects/{pid}/stream")),
2983 "first request must hit the project-scoped endpoint, got: {first}"
2984 );
2985 assert!(
2986 rx.recv_timeout(Duration::from_millis(500)).is_err(),
2987 "no second (repo-scoped fallback) request must be sent"
2988 );
2989 }
2990
2991 #[tokio::test]
2996 async fn refused_error_is_printed_once_per_invocation() {
2997 let body_400 = "not a member";
2998 let resp_400 = || {
2999 format!(
3000 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3001 body_400.len(),
3002 body_400
3003 )
3004 };
3005 let (base, _rx) = spawn_n_capturing_requests(vec![
3006 Box::leak(resp_400().into_boxed_str()),
3007 Box::leak(resp_400().into_boxed_str()),
3008 ]);
3009 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3010 let req = sample_stream_event_request();
3011 let pid = uuid::Uuid::from_u128(44);
3012 let attribution = Attribution::Repo {
3013 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3014 project: Some(pid),
3015 };
3016
3017 let mut warned = false;
3018 assert!(
3019 send_stream_event(
3020 &client,
3021 &attribution,
3022 attribution_force(None),
3023 &req,
3024 &mut warned
3025 )
3026 .await
3027 .is_err(),
3028 "a refused declared project must be an error"
3029 );
3030 assert!(warned, "the flag must be set after the first refusal");
3031
3032 assert!(
3033 send_stream_event(
3034 &client,
3035 &attribution,
3036 attribution_force(None),
3037 &req,
3038 &mut warned
3039 )
3040 .await
3041 .is_err(),
3042 "a second refusal must also be an error"
3043 );
3044 assert!(warned, "the flag stays set across the shared invocation");
3045 }
3046
3047 #[tokio::test]
3059 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3060 let body_403 = "forbidden";
3061 let resp_403 = format!(
3062 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3063 body_403.len(),
3064 body_403
3065 );
3066 let resp_200 = ok_stream_response();
3067
3068 let (base, rx) = spawn_n_capturing_requests(vec![
3069 Box::leak(resp_403.into_boxed_str()),
3070 Box::leak(resp_200.into_boxed_str()),
3071 ]);
3072 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3073 let req = sample_stream_event_request();
3074 let pid = uuid::Uuid::from_u128(42);
3075
3076 let forced = crate::session_state::ProjectBinding {
3079 project_id: pid.to_string(),
3080 project_name: "forced".into(),
3081 updated_at: "".into(),
3082 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3083 };
3084
3085 let mut warned = false;
3086 let err = send_stream_event(
3087 &client,
3088 &Attribution::Repo {
3089 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3090 project: Some(pid),
3091 },
3092 attribution_force(Some(&forced)),
3093 &req,
3094 &mut warned,
3095 )
3096 .await
3097 .expect_err("a refused force must be an error, not a silent fallback");
3098 assert!(
3099 err.to_string().contains("403"),
3100 "propagated error must reflect the status, got: {err}"
3101 );
3102 assert!(warned, "the refusal must be printed exactly once");
3103
3104 let first = rx
3105 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3106 .expect("no first request captured");
3107 assert!(
3108 first.contains(&format!("/projects/{pid}/stream")),
3109 "first request must hit the project-scoped endpoint, got: {first}"
3110 );
3111 assert!(
3112 first
3113 .to_lowercase()
3114 .contains("x-tracevault-project-attribution: explicit"),
3115 "the refused send must have DECLARED explicit — this is the mode \
3116 `refused_error` is handed: {first}"
3117 );
3118
3119 assert!(
3120 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3121 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3122 );
3123 }
3124
3125 #[tokio::test]
3134 async fn send_stream_event_project_only_omits_repo_id() {
3135 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3136 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3137 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3138
3139 let resp = ok_stream_response();
3140 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3141 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3142 let req = sample_stream_event_request();
3143 let pid = uuid::Uuid::from_u128(11);
3144
3145 let mut warned = false;
3146 let got = send_stream_event(
3147 &client,
3148 &Attribution::ProjectOnly { project_id: pid },
3149 attribution_force(None),
3150 &req,
3151 &mut warned,
3152 )
3153 .await
3154 .expect("a repo-less project send must succeed");
3155 assert_eq!(
3156 got.expect("a successful send returns a response").status,
3157 "accepted"
3158 );
3159
3160 let line = rx
3161 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3162 .expect("no request captured");
3163 assert!(
3164 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3165 "expected a bare project path with no query string, got: {line}"
3166 );
3167 assert!(
3168 line.to_lowercase()
3169 .contains("x-tracevault-project-attribution: derived"),
3170 "with no forced binding, the header must declare `derived`, got: {line}"
3171 );
3172 assert!(
3173 !warned,
3174 "a repo-less send has no fallback and must not warn about one"
3175 );
3176 }
3177
3178 #[tokio::test]
3185 async fn send_stream_event_project_only_drops_on_scoping_4xx() {
3186 let body = "no such project";
3187 let resp_404 = format!(
3188 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3189 body.len(),
3190 body
3191 );
3192 let (base, rx) = spawn_n_capturing_requests(vec![
3199 Box::leak(resp_404.clone().into_boxed_str()),
3200 Box::leak(resp_404.into_boxed_str()),
3201 ]);
3202 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3203 let req = sample_stream_event_request();
3204 let pid = uuid::Uuid::from_u128(12);
3205
3206 let mut warned = false;
3207 let got = send_stream_event(
3208 &client,
3209 &Attribution::ProjectOnly { project_id: pid },
3210 attribution_force(None),
3211 &req,
3212 &mut warned,
3213 )
3214 .await
3215 .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
3216 assert!(
3217 got.is_none(),
3218 "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
3219 );
3220 assert!(
3221 warned,
3222 "dropping data silently is the failure mode to avoid"
3223 );
3224
3225 let first = rx
3226 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3227 .expect("no request captured");
3228 assert!(
3229 first.contains(&format!("/projects/{pid}/stream")),
3230 "must hit the project-scoped endpoint, got: {first}"
3231 );
3232 assert!(
3233 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3234 "a repo-less send must make exactly one request — no fallback exists"
3235 );
3236 }
3237
3238 #[tokio::test]
3242 async fn send_stream_event_project_only_buffers_on_403() {
3243 let body = "forbidden";
3244 let resp_403 = format!(
3245 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3246 body.len(),
3247 body
3248 );
3249 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
3250 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3251 let req = sample_stream_event_request();
3252
3253 let mut warned = false;
3254 let err = send_stream_event(
3255 &client,
3256 &Attribution::ProjectOnly {
3257 project_id: uuid::Uuid::from_u128(13),
3258 },
3259 attribution_force(None),
3260 &req,
3261 &mut warned,
3262 )
3263 .await
3264 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
3265 assert!(
3266 err.to_string().contains("403"),
3267 "propagated error must reflect the status, got: {err}"
3268 );
3269 }
3270
3271 #[tokio::test]
3276 async fn send_stream_event_does_not_fall_back_on_transient_503() {
3277 let body_503 = "internal error";
3278 let resp_503 = format!(
3279 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3280 body_503.len(),
3281 body_503
3282 );
3283 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
3284 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3285 let req = sample_stream_event_request();
3286 let pid = uuid::Uuid::from_u128(7);
3287
3288 let mut warned = false;
3289 let err = send_stream_event(
3290 &client,
3291 &Attribution::Repo {
3292 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3293 project: Some(pid),
3294 },
3295 attribution_force(None),
3296 &req,
3297 &mut warned,
3298 )
3299 .await
3300 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
3301 assert!(
3302 err.to_string().contains("503"),
3303 "propagated error must reflect the transient status, got: {err}"
3304 );
3305 assert!(
3306 deterministic_client_error_kind(err.as_ref()).is_none(),
3307 "a 503 must not be classified as a deterministic client error"
3308 );
3309
3310 let first = rx
3311 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3312 .expect("no request captured");
3313 assert!(
3314 first.contains(&format!("/projects/{pid}/stream")),
3315 "must hit the project-scoped endpoint, got: {first}"
3316 );
3317
3318 assert!(
3325 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3326 "no second (fallback) request should have been sent for a transient error"
3327 );
3328 }
3329
3330 #[test]
3334 fn a_403_is_classified_apart_from_the_scoping_statuses() {
3335 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3336 assert_eq!(
3337 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3338 Some(ClientErrorKind::Forbidden)
3339 );
3340 for scoping in [
3341 "Stream failed (400 Bad Request): {}",
3342 "Stream failed (404 Not Found): {}",
3343 "Stream failed (409 Conflict): {}",
3344 ] {
3345 assert_eq!(
3346 deterministic_client_error_kind(err(scoping).as_ref()),
3347 Some(ClientErrorKind::Scoping),
3348 "{scoping}"
3349 );
3350 }
3351 for transient in [
3354 "Stream failed (401 Unauthorized): {}",
3355 "Stream failed (503 Service Unavailable): {}",
3356 "error sending request for url (http://x/stream)",
3357 ] {
3358 assert_eq!(
3359 deterministic_client_error_kind(err(transient).as_ref()),
3360 None,
3361 "{transient}"
3362 );
3363 }
3364 }
3365
3366 #[test]
3371 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3372 let pid = uuid::Uuid::from_u128(7);
3373
3374 let forbidden = refused_error(
3375 pid,
3376 &ClientErrorKind::Forbidden,
3377 AttributionForce::default(),
3378 );
3379 assert!(forbidden.contains("403"), "{forbidden}");
3380 assert!(
3381 forbidden.contains("no `tracevault` grant in Control Plane"),
3382 "must offer the missing-role explanation: {forbidden}"
3383 );
3384 assert!(
3385 forbidden.contains("no `Operator` role on it"),
3386 "must still offer the project explanation: {forbidden}"
3387 );
3388 assert!(
3389 forbidden.starts_with("tracevault: error:"),
3390 "a refusal is an error, not a warning: {forbidden}"
3391 );
3392 assert!(forbidden.contains(&pid.to_string()));
3393
3394 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3397 assert!(scoping.contains("project switch"), "{scoping}");
3398 assert!(
3399 !scoping.contains("`tracevault` grant"),
3400 "the scoping case must not mention the `tracevault` grant: {scoping}"
3401 );
3402
3403 for s in [&forbidden, &scoping] {
3404 assert!(s.contains("--user"), "must name the --user fix: {s}");
3407 assert!(
3408 s.contains("user_project.toml"),
3409 "must name the machine-wide default's file: {s}"
3410 );
3411 assert!(
3412 !s.contains("repo deduction"),
3413 "must never describe re-attribution to another project: {s}"
3414 );
3415 assert!(
3416 !s.contains("Attributing via"),
3417 "must never claim the event was re-attributed: {s}"
3418 );
3419 }
3420 }
3421
3422 #[test]
3433 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3434 let pid = uuid::Uuid::from_u128(7);
3435
3436 let explicit = refused_error(
3437 pid,
3438 &ClientErrorKind::Forbidden,
3439 AttributionForce {
3440 env: false,
3441 binding: true,
3442 },
3443 );
3444 assert!(
3445 explicit.contains("FORCE"),
3446 "the refusal of the force itself must be named: {explicit}"
3447 );
3448 assert!(
3449 explicit.contains("Operator"),
3450 "must name the grant forcing requires: {explicit}"
3451 );
3452 assert!(
3453 explicit.contains("Control Plane"),
3454 "must name the identity forcing requires: {explicit}"
3455 );
3456 assert!(
3460 explicit.contains("`tracevault` grant")
3461 && explicit.contains("no `Operator` role on it"),
3462 "the membership causes must still be named: {explicit}"
3463 );
3464 assert!(
3467 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3468 "must never claim the event was re-attributed: {explicit}"
3469 );
3470
3471 let derived = refused_error(
3476 pid,
3477 &ClientErrorKind::Forbidden,
3478 AttributionForce::default(),
3479 );
3480 assert!(
3481 !derived.contains("FORCE"),
3482 "a `derived` send never forced anything: {derived}"
3483 );
3484 }
3485
3486 #[test]
3491 fn an_explicit_scoping_failure_does_not_blame_the_force() {
3492 let pid = uuid::Uuid::from_u128(7);
3493 let scoping = refused_error(
3494 pid,
3495 &ClientErrorKind::Scoping,
3496 AttributionForce {
3497 env: true,
3498 binding: true,
3499 },
3500 );
3501 assert!(!scoping.contains("FORCE"), "{scoping}");
3502 assert_eq!(
3503 scoping,
3504 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3505 "the scoping wording does not depend on the mode"
3506 );
3507 }
3508
3509 #[test]
3529 fn the_403_remediation_names_the_force_source_actually_in_effect() {
3530 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3531 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3532 let pid = uuid::Uuid::from_u128(7);
3533 let live = forced_binding(Some(
3534 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3535 ));
3536 let never_forced = forced_binding(None);
3537
3538 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3542 let env_only = refused_error(
3543 pid,
3544 &ClientErrorKind::Forbidden,
3545 attribution_force(Some(&never_forced)),
3546 );
3547 assert!(
3548 env_only.contains("FORCE"),
3549 "an env-sourced force is still a force: {env_only}"
3550 );
3551 assert!(
3552 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3553 "must name the variable that is doing the forcing: {env_only}"
3554 );
3555 assert!(
3556 !env_only.contains("--project-attribution"),
3557 "must NOT tell the operator to drop a flag that would change \
3558 nothing here — this is the bug: {env_only}"
3559 );
3560
3561 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3565 let binding_only = refused_error(
3566 pid,
3567 &ClientErrorKind::Forbidden,
3568 attribution_force(Some(&live)),
3569 );
3570 assert!(
3571 binding_only.contains("--project-attribution"),
3572 "a persisted force IS cleared by switching without the flag: {binding_only}"
3573 );
3574 assert!(
3575 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3576 "must not send the operator after an unset variable: {binding_only}"
3577 );
3578
3579 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3583 let both = refused_error(
3584 pid,
3585 &ClientErrorKind::Forbidden,
3586 attribution_force(Some(&live)),
3587 );
3588 assert!(
3589 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3590 && both.contains("--project-attribution"),
3591 "both sources are in effect and both must be named: {both}"
3592 );
3593 assert!(
3594 both.contains("BOTH"),
3595 "must say that removing only one is not enough: {both}"
3596 );
3597 }
3598
3599 #[test]
3604 fn no_force_means_no_remediation_clause() {
3605 let pid = uuid::Uuid::from_u128(7);
3606 let none = refused_error(
3607 pid,
3608 &ClientErrorKind::Forbidden,
3609 AttributionForce::default(),
3610 );
3611 assert!(
3612 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3613 && !none.contains("--project-attribution"),
3614 "a derived send has no force to remove: {none}"
3615 );
3616 }
3617
3618 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
3623 let path = dir.join("transcript.jsonl");
3624 let mut body = String::new();
3625 for i in 0..n {
3626 let line = serde_json::json!({
3627 "type": "user",
3628 "n": i,
3629 "message": {"content": "x".repeat(line_bytes)},
3630 });
3631 body.push_str(&line.to_string());
3632 body.push('\n');
3633 }
3634 fs::write(&path, body).unwrap();
3635 path
3636 }
3637
3638 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
3640 StreamEventRequest {
3641 tool_name: Some("Bash".into()),
3642 tool_use_id: Some("toolu_1".into()),
3643 tool_input: Some(serde_json::json!({"command": "ls"})),
3644 event_uuid: Some(uuid::Uuid::now_v7()),
3645 transcript_lines: Some(lines),
3646 transcript_offset: Some(offset),
3647 ..sample_stream_event_request()
3648 }
3649 }
3650
3651 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
3652 part.transcript_lines.clone().unwrap_or_default()
3653 }
3654
3655 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
3658 parts
3659 .iter()
3660 .flat_map(|p| {
3661 let offset = p.transcript_offset.unwrap();
3662 part_lines(p)
3663 .into_iter()
3664 .enumerate()
3665 .map(move |(i, l)| (offset + i as i64, l))
3666 })
3667 .collect()
3668 }
3669
3670 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
3672 (0..n)
3673 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
3674 .collect()
3675 }
3676
3677 #[test]
3678 fn split_leaves_a_request_under_the_cap_unchanged() {
3679 let req = event_with_lines(big_lines(3, 100), 0);
3680
3681 let parts = split_into_parts(req.clone());
3682
3683 assert_eq!(parts.len(), 1);
3684 assert_eq!(
3685 serde_json::to_value(&parts[0]).unwrap(),
3686 serde_json::to_value(&req).unwrap()
3687 );
3688 }
3689
3690 #[test]
3694 fn split_carries_every_line_of_a_batch_over_the_cap() {
3695 let dir = tempfile::tempdir().unwrap();
3696 let transcript = write_transcript(dir.path(), 300, 5_000);
3698 let (lines, start, _) =
3699 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
3700 let req = event_with_lines(lines.clone(), start);
3701 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
3702
3703 let parts = split_into_parts(req.clone());
3704
3705 assert!(parts.len() >= 3, "got {} parts", parts.len());
3706 for part in &parts {
3707 assert!(
3708 part.serialized_len() <= MAX_REQUEST_BYTES,
3709 "part of {} bytes exceeds the cap",
3710 part.serialized_len()
3711 );
3712 }
3713 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3714 assert_eq!(sent, lines, "every line, once, in order");
3715
3716 let (event, transcript_parts) = parts.split_last().unwrap();
3718 assert_eq!(event.event_type, StreamEventType::ToolUse);
3719 assert_eq!(event.event_uuid, req.event_uuid);
3720 assert_eq!(event.tool_input, req.tool_input);
3721 for part in transcript_parts {
3722 assert_eq!(part.event_type, StreamEventType::Transcript);
3723 assert!(part.event_uuid.is_none());
3724 assert!(part.tool_input.is_none());
3725 assert!(part.tool_name.is_none());
3726 }
3727 assert!(
3728 !part_lines(event).is_empty(),
3729 "the event keeps the lines that fit beside it"
3730 );
3731 }
3732
3733 #[test]
3737 fn split_keeps_each_lines_unsplit_chunk_index() {
3738 let lines = big_lines(300, 5_000);
3739 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
3740
3741 let expected: Vec<_> = lines
3742 .into_iter()
3743 .enumerate()
3744 .map(|(i, l)| (1_000 + i as i64, l))
3745 .collect();
3746 assert_eq!(chunk_indexes(&parts), expected);
3747 }
3748
3749 #[test]
3754 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
3755 let lines = big_lines(10, 200_000);
3756 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
3757 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
3758
3759 for (index, line) in &short {
3760 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
3761 assert_eq!(in_long.0, *index, "line {line} indexed differently");
3762 }
3763 }
3764
3765 #[test]
3768 fn split_sends_a_single_oversized_line_alone() {
3769 let lines = vec![
3770 serde_json::json!({"n": 0}),
3771 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
3772 serde_json::json!({"n": 2}),
3773 ];
3774
3775 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
3776
3777 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3778 assert_eq!(sent, lines);
3779 let big = parts
3780 .iter()
3781 .find(|p| part_lines(p).contains(&lines[1]))
3782 .unwrap();
3783 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
3784 assert_eq!(big.transcript_offset, Some(1));
3785 }
3786
3787 fn far_deadline() -> std::time::Instant {
3788 std::time::Instant::now() + Duration::from_secs(60)
3789 }
3790
3791 fn captured_body(captured: &str) -> StreamEventRequest {
3792 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
3793 serde_json::from_str(body).expect("request body is a StreamEventRequest")
3794 }
3795
3796 #[tokio::test]
3798 async fn deliver_parts_sends_every_part() {
3799 let dir = tempfile::tempdir().unwrap();
3800 let pending_path = dir.path().join("pending.jsonl");
3801 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3802 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3803 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3804
3805 let all_accepted = deliver_parts(
3806 &client,
3807 &repo_attr(&uuid::Uuid::new_v4().to_string()),
3808 AttributionForce::default(),
3809 parts.clone(),
3810 &pending_path,
3811 false,
3812 far_deadline(),
3813 &mut false,
3814 )
3815 .await
3816 .unwrap();
3817
3818 assert!(all_accepted);
3819 for part in &parts {
3820 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
3821 assert_eq!(got.transcript_offset, part.transcript_offset);
3822 assert_eq!(got.transcript_lines, part.transcript_lines);
3823 }
3824 assert!(drain_pending(&pending_path).unwrap().is_empty());
3825 }
3826
3827 #[tokio::test]
3831 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
3832 let dir = tempfile::tempdir().unwrap();
3833 let pending_path = dir.path().join("pending.jsonl");
3834 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3835 assert!(parts.len() >= 3);
3836 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
3837 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
3838 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3839
3840 let all_accepted = deliver_parts(
3841 &client,
3842 &repo_attr(&uuid::Uuid::new_v4().to_string()),
3843 AttributionForce::default(),
3844 parts.clone(),
3845 &pending_path,
3846 false,
3847 far_deadline(),
3848 &mut false,
3849 )
3850 .await
3851 .unwrap();
3852
3853 assert!(!all_accepted);
3854 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3855 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3856 assert!(
3857 rx.recv_timeout(Duration::from_millis(300)).is_err(),
3858 "nothing is sent after the first failure"
3859 );
3860 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
3861 .unwrap()
3862 .iter()
3863 .map(|j| serde_json::from_str(j).unwrap())
3864 .collect();
3865 assert_eq!(queued.len(), parts.len() - 1);
3866 for (q, part) in queued.iter().zip(&parts[1..]) {
3867 assert_eq!(q.transcript_offset, part.transcript_offset);
3868 assert_eq!(q.transcript_lines, part.transcript_lines);
3869 }
3870 }
3871
3872 #[tokio::test]
3875 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
3876 let dir = tempfile::tempdir().unwrap();
3877 let pending_path = dir.path().join("pending.jsonl");
3878 let parts = split_into_parts(sample_stream_event_request());
3879 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
3880
3881 let all_accepted = deliver_parts(
3882 &client,
3883 &repo_attr(&uuid::Uuid::new_v4().to_string()),
3884 AttributionForce::default(),
3885 parts,
3886 &pending_path,
3887 true,
3888 far_deadline(),
3889 &mut false,
3890 )
3891 .await
3892 .unwrap();
3893
3894 assert!(!all_accepted);
3895 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
3896 }
3897
3898 #[tokio::test]
3901 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
3902 let dir = tempfile::tempdir().unwrap();
3903 let pending_path = dir.path().join("pending.jsonl");
3904 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3905 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3906 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3907
3908 let all_accepted = deliver_parts(
3909 &client,
3910 &repo_attr(&uuid::Uuid::new_v4().to_string()),
3911 AttributionForce::default(),
3912 parts.clone(),
3913 &pending_path,
3914 false,
3915 std::time::Instant::now(),
3916 &mut false,
3917 )
3918 .await
3919 .unwrap();
3920
3921 assert!(!all_accepted);
3922 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
3923 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
3924 }
3925
3926 #[tokio::test]
3931 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
3932 let dir = tempfile::tempdir().unwrap();
3933 let pending_path = dir.path().join("pending.jsonl");
3934 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3935 let base = format!("http://{}", listener.local_addr().unwrap());
3936 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3938 let started = Instant::now();
3939
3940 let all_accepted = deliver_parts(
3941 &client,
3942 &repo_attr(&uuid::Uuid::new_v4().to_string()),
3943 AttributionForce::default(),
3944 vec![event_with_lines(big_lines(1, 10), 0)],
3945 &pending_path,
3946 false,
3947 started + Duration::from_millis(100),
3948 &mut false,
3949 )
3950 .await
3951 .unwrap();
3952
3953 assert!(!all_accepted);
3954 assert!(started.elapsed() < Duration::from_secs(10));
3955 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
3956 drop(listener);
3957 }
3958
3959 const PARENT_SESSION: &str = "parent-session";
3962 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
3963
3964 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
3968 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
3969 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
3970 let subagents = dir.join(PARENT_SESSION).join("subagents");
3971 fs::create_dir_all(&subagents).unwrap();
3972 let session_dir = dir.join("tv-session");
3973 fs::create_dir_all(&session_dir).unwrap();
3974 (main, subagents, session_dir)
3975 }
3976
3977 fn subagent_line(agent: &str, n: usize) -> String {
3978 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
3979 }
3980
3981 fn append_raw(path: &Path, text: &str) {
3982 let mut f = fs::OpenOptions::new()
3983 .create(true)
3984 .append(true)
3985 .open(path)
3986 .unwrap();
3987 f.write_all(text.as_bytes()).unwrap();
3988 }
3989
3990 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
3991 let path = subagents.join(format!("agent-{agent}.jsonl"));
3992 for n in ns {
3993 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
3994 }
3995 }
3996
3997 async fn sweep(
4001 responses: Vec<String>,
4002 main: &Path,
4003 session_dir: &Path,
4004 pending_path: &Path,
4005 ) -> Vec<StreamEventRequest> {
4006 sweep_waiting(responses, main, session_dir, pending_path, None).await
4007 }
4008
4009 async fn sweep_waiting(
4012 responses: Vec<String>,
4013 main: &Path,
4014 session_dir: &Path,
4015 pending_path: &Path,
4016 wait_for_lock: Option<Instant>,
4017 ) -> Vec<StreamEventRequest> {
4018 let expected = responses.len();
4019 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4020 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4021 let event = StreamEventRequest {
4022 session_id: PARENT_SESSION.into(),
4023 ..sample_stream_event_request()
4024 };
4025 deliver_subagent_transcripts(
4026 &client,
4027 &repo_attr(SUBAGENT_REPO),
4028 AttributionForce::default(),
4029 &transcript_template(&event),
4030 main,
4031 session_dir,
4032 pending_path,
4033 false,
4034 Instant::now() + Duration::from_secs(60),
4035 wait_for_lock,
4036 &mut false,
4037 )
4038 .await
4039 .unwrap();
4040 (0..expected)
4041 .map(|_| {
4042 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4043 assert!(
4044 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4045 "{captured}"
4046 );
4047 let body = captured.splitn(3, " | ").nth(2).unwrap();
4048 serde_json::from_str(body).unwrap()
4049 })
4050 .collect()
4051 }
4052
4053 fn agent_of(line: &serde_json::Value) -> &str {
4054 line["agentId"].as_str().unwrap()
4055 }
4056
4057 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4061 for req in reqs {
4062 assert_eq!(req.event_type, StreamEventType::Transcript);
4063 assert_eq!(req.session_id, PARENT_SESSION);
4064 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4065 let lines = part_lines(req);
4066 let agent = agent_of(&lines[0]);
4067 assert!(
4068 lines.iter().all(|l| agent_of(l) == agent),
4069 "a request mixes subagent files: {lines:?}"
4070 );
4071 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4072 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4073 assert_eq!(req.transcript_offset, Some(first));
4074 }
4075 }
4076
4077 #[tokio::test]
4078 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4079 let dir = tempfile::tempdir().unwrap();
4080 let (main, subagents, session_dir) = claude_session(dir.path());
4081 let pending = session_dir.join("pending.jsonl");
4082 let ok = ok_stream_response;
4083 let mut all = Vec::new();
4084
4085 append_subagent_lines(&subagents, "a1", 0..2);
4087 append_subagent_lines(&subagents, "b2", 0..1);
4088 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4089 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4090 assert_eq!(reqs.len(), 2);
4091 all.extend(reqs);
4092
4093 append_subagent_lines(&subagents, "a1", 2..3);
4095 append_subagent_lines(&subagents, "b2", 1..2);
4096 let partial = subagent_line("b2", 2);
4097 let (head, tail) = partial.split_at(10);
4098 append_raw(&subagents.join("agent-b2.jsonl"), head);
4099 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4100 assert_eq!(reqs.len(), 2);
4101 all.extend(reqs);
4102
4103 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4105 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4106 assert_eq!(reqs.len(), 1);
4107 all.extend(reqs);
4108
4109 assert!(sweep(vec![], &main, &session_dir, &pending)
4111 .await
4112 .is_empty());
4113 assert!(!pending.exists(), "nothing may have failed and been queued");
4114
4115 assert_one_file_per_request(&subagents, &all);
4116 let mut sent: Vec<(String, u64)> = all
4117 .iter()
4118 .flat_map(part_lines)
4119 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4120 .collect();
4121 sent.sort();
4122 let expected: Vec<(String, u64)> = [
4123 ("a1", 0),
4124 ("a1", 1),
4125 ("a1", 2),
4126 ("b2", 0),
4127 ("b2", 1),
4128 ("b2", 2),
4129 ]
4130 .into_iter()
4131 .map(|(a, n)| (a.to_string(), n))
4132 .collect();
4133 assert_eq!(sent, expected, "each line exactly once");
4134 }
4135
4136 #[tokio::test]
4137 async fn a_session_without_subagents_sends_nothing_extra() {
4138 let dir = tempfile::tempdir().unwrap();
4139 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4140 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4141 let session_dir = dir.path().join("tv-session");
4142 fs::create_dir_all(&session_dir).unwrap();
4143 let pending = session_dir.join("pending.jsonl");
4144
4145 assert!(sweep(vec![], &main, &session_dir, &pending)
4146 .await
4147 .is_empty());
4148 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4149 }
4150
4151 #[tokio::test]
4156 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4157 let dir = tempfile::tempdir().unwrap();
4158 let (main, subagents, session_dir) = claude_session(dir.path());
4159 let pending = session_dir.join("pending.jsonl");
4160 append_subagent_lines(&subagents, "a1", 0..2);
4161 append_subagent_lines(&subagents, "b2", 0..1);
4162
4163 let error =
4164 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4165 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4166 assert_eq!(failed.len(), 1);
4167 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4168 .unwrap()
4169 .iter()
4170 .map(|j| serde_json::from_str(j).unwrap())
4171 .collect();
4172 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4173
4174 let resent = sweep(
4175 vec![ok_stream_response(), ok_stream_response()],
4176 &main,
4177 &session_dir,
4178 &pending,
4179 )
4180 .await;
4181 assert_one_file_per_request(&subagents, &resent);
4182 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4183 assert_eq!(
4184 resent.iter().map(key).collect::<Vec<_>>(),
4185 queued.iter().map(key).collect::<Vec<_>>()
4186 );
4187 assert!(sweep(vec![], &main, &session_dir, &pending)
4188 .await
4189 .is_empty());
4190 }
4191
4192 #[tokio::test]
4195 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
4196 let dir = tempfile::tempdir().unwrap();
4197 let (main, subagents, session_dir) = claude_session(dir.path());
4198 let pending = session_dir.join("pending.jsonl");
4199 append_subagent_lines(&subagents, "a1", 0..2);
4200 append_subagent_lines(&subagents, "b2", 0..1);
4201 let a1_offset =
4202 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4203 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4204
4205 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4206 assert_eq!(reqs.len(), 1);
4207 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
4208 assert!(!a1_offset.exists());
4209
4210 drop(held);
4211 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4212 assert_eq!(reqs.len(), 1);
4213 assert_eq!(part_lines(&reqs[0]).len(), 2);
4214 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
4215 }
4216
4217 #[tokio::test]
4220 async fn a_final_hook_waits_for_a_busy_subagent_file() {
4221 let dir = tempfile::tempdir().unwrap();
4222 let (main, subagents, session_dir) = claude_session(dir.path());
4223 let pending = session_dir.join("pending.jsonl");
4224 append_subagent_lines(&subagents, "a1", 0..2);
4225 let a1_offset =
4226 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4227 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4228 let release = thread::spawn(move || {
4229 thread::sleep(Duration::from_millis(300));
4230 drop(held);
4231 });
4232
4233 let reqs = sweep_waiting(
4234 vec![ok_stream_response()],
4235 &main,
4236 &session_dir,
4237 &pending,
4238 Some(Instant::now() + Duration::from_secs(10)),
4239 )
4240 .await;
4241 release.join().unwrap();
4242 assert_eq!(reqs.len(), 1);
4243 assert_eq!(part_lines(&reqs[0]).len(), 2);
4244 }
4245
4246 #[tokio::test]
4250 async fn a_large_subagent_batch_is_split_within_its_file() {
4251 let dir = tempfile::tempdir().unwrap();
4252 let (main, subagents, session_dir) = claude_session(dir.path());
4253 let pending = session_dir.join("pending.jsonl");
4254 let big = subagents.join("agent-a1.jsonl");
4255 for n in 0..300 {
4256 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
4257 append_raw(&big, &format!("{line}\n"));
4258 }
4259 append_subagent_lines(&subagents, "b2", 0..1);
4260
4261 let scratch = dir.path().join("scratch-offset");
4262 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
4263 let unsplit = StreamEventRequest {
4264 transcript_lines: Some(lines.clone()),
4265 transcript_offset: Some(start),
4266 ..transcript_template(&sample_stream_event_request())
4267 };
4268 let a1_parts = split_into_parts(unsplit).len();
4269 assert!(a1_parts > 1, "the batch must exceed the cap");
4270
4271 let reqs = sweep(
4272 vec![ok_stream_response(); a1_parts + 1],
4273 &main,
4274 &session_dir,
4275 &pending,
4276 )
4277 .await;
4278 assert!(!pending.exists());
4279 let (a1, b2) = reqs.split_at(a1_parts);
4280 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
4281 assert_eq!(
4282 chunk_indexes(a1),
4283 lines
4284 .into_iter()
4285 .enumerate()
4286 .map(|(i, l)| (start + i as i64, l))
4287 .collect::<Vec<_>>()
4288 );
4289 assert_eq!(b2.len(), 1);
4290 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
4291 assert_eq!(b2[0].transcript_offset, Some(0));
4292 }
4293}