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 record_metadata(
107 session_dir,
108 "transcript_path",
109 serde_json::Value::String(transcript_path.to_string()),
110 )
111}
112
113pub(crate) fn session_metadata(session_dir: &Path) -> serde_json::Value {
115 fs::read_to_string(session_dir.join("metadata.json"))
116 .ok()
117 .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
118 .filter(serde_json::Value::is_object)
119 .unwrap_or_else(|| serde_json::json!({}))
120}
121
122fn record_metadata(
126 session_dir: &Path,
127 key: &str,
128 value: serde_json::Value,
129) -> Result<(), io::Error> {
130 let mut meta = session_metadata(session_dir);
131 if meta.get(key) == Some(&value) {
132 return Ok(());
133 }
134 meta[key] = value;
135 let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
136 fs::write(&tmp, meta.to_string())?;
137 fs::rename(&tmp, session_dir.join("metadata.json")).inspect_err(|_| {
138 let _ = fs::remove_file(&tmp);
139 })
140}
141
142fn attribution_record(attribution: &Attribution) -> serde_json::Value {
144 match attribution {
145 Attribution::Repo { repo_id, project } => {
146 serde_json::json!({"repo_id": repo_id, "project_id": project})
147 }
148 Attribution::ProjectOnly { project_id } => {
149 serde_json::json!({"repo_id": null, "project_id": project_id})
150 }
151 }
152}
153
154pub(crate) fn catch_up_may_send(recorded: Option<&serde_json::Value>, now: &Attribution) -> bool {
162 match recorded {
163 Some(recorded) => *recorded == attribution_record(now),
164 None => matches!(now, Attribution::Repo { .. }),
165 }
166}
167
168pub fn record_inline_tool_calls(
175 session_dir: &Path,
176 records: &[serde_json::Value],
177) -> Result<(), io::Error> {
178 let lines: String = records
179 .iter()
180 .flat_map(crate::transcript::tool_call_names)
181 .map(|name| {
182 let record = serde_json::json!({
183 "type": "message",
184 "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
185 });
186 format!("{record}\n")
187 })
188 .collect();
189 if lines.is_empty() {
190 return Ok(());
191 }
192 let log_path = session_dir.join("tool_calls.jsonl");
193 OpenOptions::new()
194 .create(true)
195 .append(true)
196 .open(&log_path)?
197 .write_all(lines.as_bytes())?;
198 record_transcript_path(session_dir, &log_path.to_string_lossy())
199}
200
201pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
202 let mut file = OpenOptions::new()
203 .create(true)
204 .append(true)
205 .open(pending_path)?;
206 writeln!(file, "{json}")?;
207 Ok(())
208}
209
210pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
211 if !pending_path.exists() {
212 return Ok(vec![]);
213 }
214 let content = fs::read_to_string(pending_path)?;
215 let lines: Vec<String> = content
216 .lines()
217 .filter(|l| !l.trim().is_empty())
218 .map(String::from)
219 .collect();
220 fs::remove_file(pending_path)?;
221 Ok(lines)
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
234pub(crate) enum Attribution {
235 Repo {
238 repo_id: String,
239 project: Option<uuid::Uuid>,
240 },
241 ProjectOnly { project_id: uuid::Uuid },
244}
245
246impl Attribution {
247 pub(crate) fn pending_file_name(&self) -> String {
256 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
257 match self {
258 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
259 Self::ProjectOnly { project_id } => {
260 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
261 }
262 }
263 }
264}
265
266pub(crate) fn attribution_for(
286 binding: Option<&crate::session_state::RepoBinding>,
287 project: Option<uuid::Uuid>,
288) -> Option<Attribution> {
289 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
290 Some(b) => Some(Attribution::Repo {
291 repo_id: b.repo_id.clone(),
292 project,
293 }),
294 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
295 }
296}
297
298fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
300 session_dir.join(attribution.pending_file_name())
301}
302
303pub fn resolve_session_paths(
316 hook_cwd: &Path,
317 session_id: &str,
318) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
319 let resolved = crate::paths::resolve_project_root(hook_cwd);
320 let session_dir = resolved
321 .root
322 .join(".tracevault")
323 .join("sessions")
324 .join(session_id);
325 (resolved, session_dir)
326}
327
328pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
336 uuid::Uuid::parse_str(repo_id).is_ok()
337}
338
339pub(crate) fn resolve_stream_binding(
343 session: &crate::session_state::SessionState,
344 worktree: &str,
345 bound: Option<crate::session_state::RepoBinding>,
346 user_default: Option<crate::session_state::RepoBinding>,
347) -> Option<crate::session_state::RepoBinding> {
348 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
349 repo_flag: None,
350 session,
351 worktree_path: Some(worktree),
352 bound,
353 user_default,
354 })
355 .map(|(b, _)| b)
356}
357
358pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
366 let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
367 let raw = raw.trim();
368 let parsed = raw.parse::<uuid::Uuid>().ok()?;
369 Some(crate::session_state::ProjectBinding {
370 project_id: parsed.to_string(),
371 project_name: String::new(),
372 updated_at: String::new(),
373 forced_until: None,
374 })
375}
376
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
399pub(crate) struct AttributionForce {
400 pub(crate) env: bool,
403 pub(crate) binding: bool,
407}
408
409impl AttributionForce {
410 pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
413 if self.env || self.binding {
414 crate::api_client::AttributionMode::Explicit
415 } else {
416 crate::api_client::AttributionMode::Derived
417 }
418 }
419}
420
421pub(crate) fn attribution_mode(
473 effective: Option<&crate::session_state::ProjectBinding>,
474) -> crate::api_client::AttributionMode {
475 attribution_force(effective).mode()
476}
477
478pub(crate) fn attribution_force(
485 effective: Option<&crate::session_state::ProjectBinding>,
486) -> AttributionForce {
487 AttributionForce {
488 env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
489 .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
490 .unwrap_or(false),
491 binding: effective
492 .and_then(|b| b.forced_until.as_deref())
493 .is_some_and(|s| {
494 matches!(
495 crate::session_state::force_status(s),
496 crate::session_state::ForceStatus::Live(_)
497 )
498 }),
499 }
500}
501
502pub(crate) fn capture_binding(
522 session: &crate::session_state::SessionState,
523 worktree_path: Option<&str>,
524) -> Option<crate::session_state::ProjectBinding> {
525 use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
526 let (binding, _) = capture_project_binding(&CaptureProjectInputs {
527 project_flag: None,
528 env_project: env_project_binding(),
529 session,
530 worktree_path,
531 user_default: crate::user_project_default::load(),
532 })?;
533 capture_project_id(&binding)?;
538 Some(binding)
539}
540
541pub(crate) fn capture_project(
551 session: &crate::session_state::SessionState,
552 worktree_path: Option<&str>,
553) -> Option<uuid::Uuid> {
554 capture_binding(session, worktree_path)
555 .as_ref()
556 .and_then(crate::resolution::capture_project_id)
557}
558
559fn undeliverable_warning(pid: uuid::Uuid) -> String {
562 format!(
563 "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
564 repo binding, so there is nothing to attribute these events to and they are being \
565 DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
566 that exists."
567 )
568}
569
570#[derive(Debug, PartialEq, Eq)]
591pub(crate) enum ClientErrorKind {
592 Forbidden,
594 Scoping,
596}
597
598pub(crate) fn refused_error(
629 pid: uuid::Uuid,
630 kind: &ClientErrorKind,
631 force: AttributionForce,
632) -> String {
633 let base = match kind {
634 ClientErrorKind::Forbidden => format!(
640 "tracevault: error: the server refused to attribute this event to active project \
641 {pid} (403). Either that project does not apply to this repo (not a member, or \
642 no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
643 binding is the machine-wide default in `user_project.toml`) — or this account has \
644 no `tracevault` grant in Control Plane at all, which an administrator must grant. \
645 The event was NOT re-attributed elsewhere; it has been queued and will be retried \
646 once the binding or the grant is fixed."
647 ),
648 ClientErrorKind::Scoping => format!(
649 "tracevault: error: active project {pid} does not apply to this repo (not a member, \
650 missing permission, or the project no longer exists). The event was NOT \
651 re-attributed elsewhere; it has been queued and will be retried once the binding is \
652 fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
653 machine-wide default in `user_project.toml`) to update it."
654 ),
655 };
656 if force.mode() == crate::api_client::AttributionMode::Explicit
657 && matches!(kind, ClientErrorKind::Forbidden)
658 {
659 return format!(
660 "{base} This send declared `explicit` attribution, so the refusal may be of the \
661 FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
662 identity (a `tvk_` API key can never force). If membership attribution is what \
663 you want, {}",
664 force_remediation(force)
665 );
666 }
667 base
668}
669
670fn force_remediation(force: AttributionForce) -> String {
687 let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
688 process-wide and never expires, so no switch clears it)";
689 let binding_fix = "run `tracevault project switch <name>` WITHOUT \
690 `--project-attribution explicit` (add `--user` if the forced binding \
691 is the machine-wide default in `user_project.toml`)";
692 match (force.env, force.binding) {
693 (true, false) => format!("{env_fix}."),
694 (false, true) => format!("{binding_fix}."),
695 (true, true) => {
697 format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
698 }
699 (false, false) => format!("{env_fix}, or {binding_fix}."),
700 }
701}
702
703pub(crate) fn deterministic_client_error_kind(
704 e: &dyn std::error::Error,
705) -> Option<ClientErrorKind> {
706 let s = e.to_string();
707 if s.contains("(403 ") {
714 return Some(ClientErrorKind::Forbidden);
715 }
716 if ["(400 ", "(404 ", "(409 "]
717 .iter()
718 .any(|marker| s.contains(marker))
719 {
720 return Some(ClientErrorKind::Scoping);
721 }
722 None
723}
724
725async fn send_stream_event(
778 client: &crate::api_client::ApiClient,
779 attribution: &Attribution,
780 force: AttributionForce,
781 req: &StreamEventRequest,
782 warned: &mut bool,
783) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
784{
785 let (repo_id, capture_pid) = match attribution {
786 Attribution::ProjectOnly { project_id } => {
804 let attempt = client
805 .stream_event_for_project(*project_id, None, force.mode(), req)
806 .await;
807 return match attempt {
808 Ok(r) => Ok(Some(r)),
809 Err(e) => match deterministic_client_error_kind(e.as_ref()) {
810 Some(ClientErrorKind::Scoping) => {
811 if !*warned {
812 eprintln!("{}", undeliverable_warning(*project_id));
813 *warned = true;
814 }
815 Ok(None)
816 }
817 _ => Err(e),
818 },
819 };
820 }
821 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
822 };
823 match capture_pid {
824 None => client.stream_event(repo_id, req).await.map(Some),
825 Some(pid) => {
826 let attempt = client
827 .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
828 .await;
829 let kind = match &attempt {
830 Ok(_) => None,
831 Err(e) => deterministic_client_error_kind(e.as_ref()),
832 };
833 match (attempt, kind) {
834 (Ok(r), _) => Ok(Some(r)),
835 (Err(e), Some(kind)) => {
836 if !*warned {
837 eprintln!("{}", refused_error(pid, &kind, force));
845 *warned = true;
846 }
847 Err(e)
853 }
854 (Err(e), None) => Err(e),
856 }
857 }
858 }
859}
860
861pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
867 (start_offset, start_offset + records_len)
868}
869
870pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
886 if req.serialized_len() <= MAX_REQUEST_BYTES {
887 return vec![req];
888 }
889 let lines = req.transcript_lines.take().unwrap_or_default();
890 let batch_offset = req.transcript_offset.unwrap_or(0);
891 req.truncate_large_fields();
894
895 let sizes: Vec<usize> = lines
897 .iter()
898 .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
899 .collect();
900 let envelope = |r: &StreamEventRequest| {
901 let mut r = r.clone();
902 r.transcript_lines = Some(vec![]);
903 r.serialized_len()
904 };
905
906 let mut tail_start = lines.len();
908 let mut used = envelope(&req);
909 while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
910 tail_start -= 1;
911 used += sizes[tail_start];
912 }
913
914 let transcript_template = transcript_template(&req);
915 let transcript_envelope = envelope(&transcript_template);
916
917 let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
919 let mut start = 0;
920 while start < tail_start {
921 let mut end = start + 1;
922 let mut used = transcript_envelope + sizes[start];
923 while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
924 used += sizes[end];
925 end += 1;
926 }
927 groups.push(start..end);
928 start = end;
929 }
930 groups.push(tail_start..lines.len());
931
932 let last = groups.len() - 1;
933 let mut lines = lines.into_iter();
934 groups
935 .into_iter()
936 .enumerate()
937 .map(|(n, range)| {
938 let mut part = if n == last {
939 req.clone()
940 } else {
941 transcript_template.clone()
942 };
943 let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
944 part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
945 part.transcript_offset = Some(batch_offset + range.start as i64);
946 part
947 })
948 .collect()
949}
950
951pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
956 StreamEventRequest {
957 protocol_version: req.protocol_version,
958 tool: req.tool.clone(),
959 event_type: StreamEventType::Transcript,
960 session_id: req.session_id.clone(),
961 timestamp: req.timestamp,
962 hook_event_name: req.hook_event_name.clone(),
963 tool_name: None,
964 tool_use_id: None,
965 tool_input: None,
966 tool_response: None,
967 tool_is_error: None,
968 event_index: None,
969 event_uuid: None,
970 transcript_lines: None,
971 transcript_offset: req.transcript_offset,
972 model: req.model.clone(),
973 cwd: req.cwd.clone(),
974 final_stats: None,
975 flow_id: req.flow_id.clone(),
976 labels: req.labels.clone(),
977 params: req.params.clone(),
978 billing_mode: req.billing_mode,
979 }
980}
981
982#[allow(clippy::too_many_arguments)]
1003async fn deliver_subagent_transcripts(
1004 client: &crate::api_client::ApiClient,
1005 attribution: &Attribution,
1006 force: AttributionForce,
1007 template: &StreamEventRequest,
1008 transcript_path: &Path,
1009 session_dir: &Path,
1010 pending_path: &Path,
1011 mut send_failed: bool,
1012 deadline: std::time::Instant,
1013 wait_for_lock: Option<std::time::Instant>,
1014 warned: &mut bool,
1015) -> Result<(), Box<dyn std::error::Error>> {
1016 for file in crate::subagents::transcripts(transcript_path) {
1017 let offset_path = crate::subagents::offset_path(session_dir, &file);
1018 let lock = loop {
1020 match crate::subagents::try_lock(&offset_path) {
1021 Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
1022 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1023 }
1024 other => break other,
1025 }
1026 };
1027 let _lock = match lock {
1028 Ok(Some(lock)) => lock,
1029 Ok(None) => {
1030 if wait_for_lock.is_some() {
1031 eprintln!(
1032 "tracevault: warning: skipping subagent transcript {}: \
1033 another hook is still sending it",
1034 file.display()
1035 );
1036 }
1037 continue;
1038 }
1039 Err(e) => {
1040 eprintln!(
1041 "tracevault: warning: skipping subagent transcript {}: cannot lock: {e}",
1042 file.display()
1043 );
1044 continue;
1045 }
1046 };
1047 let (lines, start, end) = match crate::subagents::read_new_lines(&file, &offset_path) {
1048 Ok(read) => read,
1049 Err(e) => {
1050 eprintln!(
1051 "tracevault: warning: skipping subagent transcript {}: {e}",
1052 file.display()
1053 );
1054 continue;
1055 }
1056 };
1057 if end == start {
1058 continue;
1059 }
1060 let mut accepted = true;
1062 if !lines.is_empty() {
1063 let mut req = template.clone();
1064 req.transcript_lines = Some(lines);
1065 req.transcript_offset = Some(start);
1066 accepted = deliver_parts(
1067 client,
1068 attribution,
1069 force,
1070 split_into_parts(req),
1071 pending_path,
1072 send_failed,
1073 deadline,
1074 warned,
1075 )
1076 .await?;
1077 send_failed |= !accepted;
1078 }
1079 if accepted {
1080 crate::subagents::write_offset(&offset_path, end)?;
1081 }
1082 }
1083 Ok(())
1084}
1085
1086pub fn resolve_transcript_source(
1092 inline_records: Option<Vec<serde_json::Value>>,
1093 prior_offset: i64,
1094 file_result: (Vec<serde_json::Value>, i64, i64),
1095) -> (Vec<serde_json::Value>, i64, i64) {
1096 match inline_records {
1097 Some(records) => {
1098 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1099 (records, send, next)
1100 }
1101 None => file_result,
1102 }
1103}
1104
1105pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1111 lines.iter().find_map(|line| {
1112 let msg = line.get("message")?;
1113 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1114 Some(
1115 msg.get("isError")
1116 .and_then(|v| v.as_bool())
1117 .unwrap_or(false),
1118 )
1119 } else {
1120 None
1121 }
1122 })
1123}
1124
1125pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1129 req.tool = Some(agent.tool_name().to_string());
1130 req.protocol_version = agent.protocol_version() as u32;
1131}
1132
1133const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1139
1140pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1145
1146const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1153
1154#[allow(clippy::too_many_arguments)]
1162async fn deliver_parts(
1163 client: &crate::api_client::ApiClient,
1164 attribution: &Attribution,
1165 force: AttributionForce,
1166 parts: Vec<StreamEventRequest>,
1167 pending_path: &Path,
1168 mut send_failed: bool,
1169 deadline: std::time::Instant,
1170 warned: &mut bool,
1171) -> Result<bool, Box<dyn std::error::Error>> {
1172 let mut all_accepted = true;
1173 for part in parts {
1174 send_failed = send_failed || std::time::Instant::now() >= deadline;
1175 if !send_failed {
1176 let send = send_stream_event(client, attribution, force, &part, warned);
1177 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1178 Ok(Ok(_)) => continue,
1179 Ok(Err(_)) | Err(_) => send_failed = true,
1180 }
1181 }
1182 all_accepted = false;
1183 append_pending(pending_path, &serde_json::to_string(&part)?)?;
1184 }
1185 Ok(all_accepted)
1186}
1187
1188pub async fn run_stream(
1189 event_type: &str,
1190 agent: crate::agent::Agent,
1191) -> Result<(), Box<dyn std::error::Error>> {
1192 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1194 let mut input = String::new();
1195 io::stdin().read_to_string(&mut input)?;
1196 let hook_event = parse_hook_event(&input)?;
1197
1198 let hook_cwd = Path::new(&hook_event.cwd);
1214 let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1215 if resolved.source == crate::paths::ProjectRootSource::Fallback {
1216 eprintln!(
1221 "tracevault: warning: could not resolve a git project root from {}; \
1222 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1223 that it runs inside the repository to keep sessions under the repo root.",
1224 hook_cwd.display()
1225 );
1226 }
1227 let project_root = resolved.root;
1228
1229 fs::create_dir_all(&session_dir)?;
1231
1232 let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
1238
1239 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1244 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1245
1246 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1250 if let Some(records) = &hook_event.transcript_records {
1255 let _ = record_inline_tool_calls(&session_dir, records);
1256 }
1257
1258 let target = SessionTarget {
1259 project_root,
1260 session_dir,
1261 worktree_top,
1262 };
1263 stream_event(
1264 hook_event,
1265 event_type,
1266 agent,
1267 &target,
1268 deadline,
1269 Sender::Hook,
1270 )
1271 .await?;
1272
1273 let response = HookResponse::allow();
1275 println!("{}", serde_json::to_string(&response)?);
1276
1277 Ok(())
1278}
1279
1280pub fn stream_event_type(event_type: &str) -> StreamEventType {
1282 match event_type {
1283 "notification" => StreamEventType::SessionStart,
1284 "stop" => StreamEventType::SessionEnd,
1286 "session-end" => StreamEventType::Transcript,
1290 _ => StreamEventType::ToolUse,
1291 }
1292}
1293
1294pub(crate) struct SessionTarget {
1298 pub project_root: std::path::PathBuf,
1299 pub session_dir: std::path::PathBuf,
1301 pub worktree_top: String,
1303}
1304
1305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1307pub(crate) enum Sender {
1308 Hook,
1311 CatchUp,
1316}
1317
1318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1320pub(crate) enum Sent {
1321 Accepted,
1323 Queued,
1325 Skipped,
1328}
1329
1330pub(crate) async fn stream_event(
1334 mut hook_event: tracevault_protocol::hooks::HookEvent,
1335 event_type: &str,
1336 agent: crate::agent::Agent,
1337 target: &SessionTarget,
1338 deadline: std::time::Instant,
1339 sender: Sender,
1340) -> Result<Sent, Box<dyn std::error::Error>> {
1341 let SessionTarget {
1342 project_root,
1343 session_dir,
1344 worktree_top,
1345 } = target;
1346 let hook_cwd = Path::new(&hook_event.cwd);
1347
1348 let event_uuid = uuid::Uuid::now_v7();
1353
1354 let transcript_path = Path::new(&hook_event.transcript_path);
1356 let offset_path = session_dir.join(".stream_offset");
1357 let sends_main = event_type != "subagent-stop";
1364 let (transcript_lines, start_offset, new_offset) = if sends_main {
1365 read_new_transcript_lines(transcript_path, &offset_path)?
1366 } else {
1367 (vec![], 0, 0)
1368 };
1369
1370 let is_inline = hook_event.transcript_records.is_some();
1387 let (transcript_lines, start_offset, new_offset) = if is_inline {
1388 let prior_offset: i64 = if offset_path.exists() {
1395 let content = fs::read_to_string(&offset_path)?;
1396 content
1397 .trim()
1398 .parse::<i64>()
1399 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1400 .max(0)
1401 } else {
1402 0
1403 };
1404 resolve_transcript_source(
1408 hook_event.transcript_records.take(),
1409 prior_offset,
1410 (transcript_lines, start_offset, new_offset),
1411 )
1412 } else {
1413 (transcript_lines, start_offset, new_offset)
1414 };
1415 let stream_event_type = stream_event_type(event_type);
1417
1418 let tool_is_error = hook_event
1423 .tool_use_id
1424 .as_deref()
1425 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1426 .or_else(|| inline_tool_is_error(&transcript_lines));
1427
1428 let config = crate::config::TracevaultConfig::try_load(project_root);
1438 let repo_uc = config
1442 .as_ref()
1443 .ok()
1444 .and_then(|opt| opt.as_ref())
1445 .and_then(|c| c.user_context.clone());
1446 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1447
1448 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1454 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1455
1456 let mut req = StreamEventRequest {
1457 protocol_version: 1,
1458 tool: Some("claude-code".to_string()),
1459 event_type: stream_event_type,
1460 session_id: hook_event.session_id.clone(),
1461 timestamp: chrono::Utc::now(),
1462 hook_event_name: Some(hook_event.hook_event_name.clone()),
1463 tool_name: hook_event.tool_name.clone(),
1464 tool_use_id: hook_event.tool_use_id.clone(),
1465 tool_input: hook_event.tool_input.clone(),
1466 tool_response: hook_event.tool_response.clone(),
1467 tool_is_error,
1468 event_index: None,
1469 event_uuid: Some(event_uuid),
1470 transcript_lines: None,
1471 transcript_offset: Some(start_offset),
1472 model: None,
1473 cwd: Some(hook_event.cwd.clone()),
1474 final_stats: None,
1475 flow_id: ctx_flow_id,
1476 labels: ctx_labels,
1477 params: ctx_params,
1478 billing_mode: (sender == Sender::Hook)
1479 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1480 };
1481
1482 stamp_agent(&mut req, agent);
1483 let subagent_template = transcript_template(&req);
1485 if !transcript_lines.is_empty() {
1486 req.transcript_lines = Some(transcript_lines);
1487 }
1488
1489 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
1491
1492 if let Err(e) = &config {
1501 return Err(format!("malformed .tracevault/config.toml: {e}").into());
1502 }
1503
1504 let session = crate::session_state::load(&hook_event.session_id);
1509 let bound = config
1510 .as_ref()
1511 .ok()
1512 .and_then(|opt| opt.as_ref())
1513 .and_then(crate::resolution::binding_from_config);
1514 let user_default = crate::user_default::load();
1515 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
1516 let client = server_url
1521 .as_deref()
1522 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1523 if binding.is_none() {
1524 if let Some(client) = &client {
1525 let auto =
1526 crate::auto_bind::bind_session(&hook_event.session_id, hook_cwd, client, deadline)
1527 .await;
1528 if let Some(notice) = auto.notice {
1529 eprintln!("{notice}");
1530 }
1531 binding = auto.binding;
1532 }
1533 }
1534 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1544 let capture_pid = capture_binding
1545 .as_ref()
1546 .and_then(crate::resolution::capture_project_id);
1547 let force = attribution_force(capture_binding.as_ref());
1554
1555 let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1563 return Ok(Sent::Skipped);
1564 };
1565 match sender {
1569 Sender::Hook => {
1570 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
1571 }
1572 Sender::CatchUp => {
1573 let meta = session_metadata(session_dir);
1574 if !catch_up_may_send(meta.get("attribution"), &attribution) {
1575 return Ok(Sent::Skipped);
1576 }
1577 }
1578 }
1579
1580 let client = client.ok_or("server_url not configured")?;
1582
1583 let pending_path = pending_path_for(session_dir, &attribution);
1585 let pending_events = drain_pending(&pending_path)?;
1586
1587 let mut send_failed = false;
1588 let mut warned = false;
1592
1593 for (i, pending_json) in pending_events.iter().enumerate() {
1597 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1598 if std::time::Instant::now() >= deadline
1602 || !matches!(
1603 tokio::time::timeout_at(
1604 (deadline + IN_FLIGHT_GRACE).into(),
1605 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1606 )
1607 .await,
1608 Ok(Ok(_))
1609 )
1610 {
1611 for evt in &pending_events[i..] {
1618 append_pending(&pending_path, evt)?;
1619 }
1620 send_failed = true;
1621 break;
1622 }
1623 }
1624 }
1625
1626 let sends_event = sends_main
1631 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
1632 let all_accepted = if sends_event {
1633 deliver_parts(
1634 &client,
1635 &attribution,
1636 force,
1637 split_into_parts(req),
1638 &pending_path,
1639 send_failed,
1640 deadline,
1641 &mut warned,
1642 )
1643 .await?
1644 } else {
1645 true
1646 };
1647 if sends_main && (all_accepted || is_inline) {
1660 crate::subagents::write_offset(&offset_path, new_offset)?;
1661 }
1662
1663 if sender == Sender::Hook && agent == crate::agent::Agent::ClaudeCode {
1668 deliver_subagent_transcripts(
1669 &client,
1670 &attribution,
1671 force,
1672 &subagent_template,
1673 transcript_path,
1674 session_dir,
1675 &pending_path,
1676 send_failed || !all_accepted,
1677 deadline,
1678 matches!(event_type, "stop" | "subagent-stop" | "session-end")
1679 .then(|| deadline + FINAL_LOCK_WAIT),
1680 &mut warned,
1681 )
1682 .await?;
1683 }
1684
1685 Ok(if !send_failed && all_accepted {
1686 Sent::Accepted
1687 } else {
1688 Sent::Queued
1689 })
1690}
1691
1692#[cfg(test)]
1693mod tests {
1694 use super::*;
1695 use crate::api_client::AttributionMode;
1696 use crate::config::UserContext;
1697 use crate::context::{Context, EffectiveContext};
1698 use std::collections::BTreeMap;
1699
1700 #[test]
1701 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
1702 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
1703 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
1704 project,
1705 };
1706 let a = uuid::Uuid::from_u128(0xa);
1707 let b = uuid::Uuid::from_u128(0xb);
1708 let only = |project_id| Attribution::ProjectOnly { project_id };
1709
1710 let recorded = attribution_record(&repo(Some(a)));
1711 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
1712 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
1713 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
1714 let recorded = attribution_record(&only(a));
1715 assert!(catch_up_may_send(Some(&recorded), &only(a)));
1716 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
1717 assert!(catch_up_may_send(None, &repo(Some(b))));
1720 assert!(!catch_up_may_send(None, &only(a)));
1721 }
1722
1723 #[test]
1724 fn record_metadata_keeps_the_other_keys() {
1725 let dir = tempfile::tempdir().unwrap();
1726 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
1727 record_metadata(
1728 dir.path(),
1729 "attribution",
1730 serde_json::json!({"repo_id": "r"}),
1731 )
1732 .unwrap();
1733 let meta = session_metadata(dir.path());
1734 assert_eq!(meta["transcript_path"], "/t.jsonl");
1735 assert_eq!(meta["attribution"]["repo_id"], "r");
1736 }
1737
1738 #[test]
1739 fn hook_events_map_to_server_events() {
1740 assert_eq!(
1741 stream_event_type("notification"),
1742 StreamEventType::SessionStart
1743 );
1744 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
1747 assert_eq!(
1748 stream_event_type("session-end"),
1749 StreamEventType::Transcript
1750 );
1751 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
1752 assert_eq!(
1753 stream_event_type(event),
1754 StreamEventType::ToolUse,
1755 "{event}"
1756 );
1757 }
1758 }
1759
1760 #[test]
1763 fn disabled_user_context_resolves_to_none() {
1764 assert!(UserContext::Toggle(false).resolve().is_none());
1768 }
1769
1770 #[test]
1771 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1772 let dir = tempfile::tempdir().unwrap();
1776 let effective = Context::effective(dir.path(), None);
1777 assert_eq!(effective, EffectiveContext::default());
1778 }
1779
1780 #[test]
1783 fn apply_context_stamps_all_fields() {
1784 let dir = tempfile::tempdir().unwrap();
1785 let mut params = BTreeMap::new();
1786 params.insert("env".to_string(), "prod".to_string());
1787 params.insert("region".to_string(), "eu-west-1".to_string());
1788
1789 let ctx = EffectiveContext {
1790 flow_id: Some("flow-xyz".to_string()),
1791 labels: vec!["backend".to_string(), "urgent".to_string()],
1792 params,
1793 };
1794
1795 let (flow_id, labels, params_out) = apply_context(ctx);
1796
1797 assert_eq!(flow_id, Some("flow-xyz".to_string()));
1798 assert_eq!(
1799 labels,
1800 Some(vec!["backend".to_string(), "urgent".to_string()])
1801 );
1802 let p = params_out.expect("params should be Some");
1803 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1804 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1805
1806 let written = Context {
1809 flow_id: Some("flow-xyz".to_string()),
1810 labels: vec!["backend".to_string(), "urgent".to_string()],
1811 params: {
1812 let mut m = BTreeMap::new();
1813 m.insert("env".to_string(), Some("prod".to_string()));
1814 m.insert("region".to_string(), Some("eu-west-1".to_string()));
1815 m
1816 },
1817 };
1818 let ctx_path = dir.path().join(".tracevault").join("context.json");
1819 written.save_to(&ctx_path).unwrap();
1820 let loaded = Context::load_from(&ctx_path);
1821 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1822 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1823 assert!(labels2.is_some());
1824 assert!(params2.is_some());
1825 }
1826
1827 #[test]
1830 fn apply_context_missing_file_all_none() {
1831 let dir = tempfile::tempdir().unwrap();
1832 let missing_path = dir.path().join(".tracevault").join("context.json");
1833 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1835 assert!(flow_id.is_none(), "flow_id should be None");
1836 assert!(labels.is_none(), "labels should be None");
1837 assert!(params.is_none(), "params should be None");
1838 }
1839
1840 #[test]
1843 fn apply_context_empty_collections_are_none() {
1844 let ctx = EffectiveContext {
1845 flow_id: None,
1846 labels: vec![],
1847 params: BTreeMap::new(),
1848 };
1849 let (flow_id, labels, params) = apply_context(ctx);
1850 assert!(flow_id.is_none());
1851 assert!(
1852 labels.is_none(),
1853 "empty labels should be None, not Some([])"
1854 );
1855 assert!(
1856 params.is_none(),
1857 "empty params should be None, not Some({{}})"
1858 );
1859 }
1860
1861 #[test]
1864 fn apply_context_flow_id_only() {
1865 let ctx = EffectiveContext {
1866 flow_id: Some("my-flow".to_string()),
1867 labels: vec![],
1868 params: BTreeMap::new(),
1869 };
1870 let (flow_id, labels, params) = apply_context(ctx);
1871 assert_eq!(flow_id, Some("my-flow".to_string()));
1872 assert!(labels.is_none());
1873 assert!(params.is_none());
1874 }
1875
1876 use crate::test_helpers::{add_worktree, init_git_repo};
1883
1884 #[test]
1887 fn resolve_session_paths_primary_checkout() {
1888 let tmp = tempfile::tempdir().unwrap();
1889 let repo = tmp.path().join("repo");
1890 std::fs::create_dir_all(&repo).unwrap();
1891 init_git_repo(&repo);
1892 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1894
1895 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1896 let project_root = resolved.root;
1897
1898 assert_eq!(
1899 project_root.canonicalize().unwrap(),
1900 repo.canonicalize().unwrap(),
1901 "primary checkout: project_root must be repo root"
1902 );
1903 assert_eq!(
1904 session_dir.canonicalize().unwrap_or(session_dir.clone()),
1905 repo.join(".tracevault")
1906 .join("sessions")
1907 .join("sess-primary-123"),
1908 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1909 );
1910 assert!(
1912 session_dir.starts_with(&repo),
1913 "session_dir must be under the primary repo root"
1914 );
1915 }
1916
1917 #[test]
1921 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1922 let tmp = tempfile::tempdir().unwrap();
1923 let repo = tmp.path().join("repo");
1924 let wt = tmp.path().join("sibling-wt");
1926
1927 std::fs::create_dir_all(&repo).unwrap();
1928 init_git_repo(&repo);
1929 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1931 add_worktree(&repo, &wt);
1932
1933 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1934 let project_root = resolved.root;
1935
1936 assert_eq!(
1938 project_root.canonicalize().unwrap(),
1939 repo.canonicalize().unwrap(),
1940 "sibling worktree: project_root must be primary repo root (not worktree dir)"
1941 );
1942 assert!(
1944 session_dir.starts_with(&repo),
1945 "sibling worktree: session_dir must be under the PRIMARY repo root"
1946 );
1947 assert!(
1948 !session_dir.starts_with(&wt),
1949 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1950 );
1951 assert!(
1952 session_dir.ends_with(
1953 std::path::Path::new(".tracevault")
1954 .join("sessions")
1955 .join("sess-sibling-456")
1956 ),
1957 "session_dir must end with .tracevault/sessions/<session_id>"
1958 );
1959 }
1960
1961 #[test]
1964 fn resolve_session_paths_non_git_fallback() {
1965 let tmp = tempfile::tempdir().unwrap();
1966 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1968 let project_root = resolved.root;
1969
1970 assert_eq!(
1971 project_root,
1972 tmp.path(),
1973 "non-git: project_root must fall back to hook_cwd"
1974 );
1975 assert_eq!(
1976 session_dir,
1977 tmp.path()
1978 .join(".tracevault")
1979 .join("sessions")
1980 .join("sess-fallback-789"),
1981 "non-git: session_dir must be relative to the fallback root"
1982 );
1983 }
1984
1985 #[test]
1990 fn origin_marker_written_in_session_dir() {
1991 let tmp = tempfile::tempdir().unwrap();
1992 let repo = tmp.path().join("repo");
1993 std::fs::create_dir_all(&repo).unwrap();
1994 init_git_repo(&repo);
1995
1996 let session_dir = repo
1997 .join(".tracevault")
1998 .join("sessions")
1999 .join("test-sess-001");
2000 std::fs::create_dir_all(&session_dir).unwrap();
2001
2002 let hook_cwd = &repo;
2003 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2004 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2005
2006 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2007 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2008 assert_eq!(
2009 origin_content.trim(),
2010 expected.as_str(),
2011 "origin marker must contain the canonicalized worktree toplevel"
2012 );
2013 }
2014
2015 fn metadata(session_dir: &Path) -> serde_json::Value {
2016 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2017 .unwrap()
2018 }
2019
2020 #[test]
2021 fn record_transcript_path_writes_metadata_for_check() {
2022 let tmp = tempfile::tempdir().unwrap();
2023 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2024 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2025 }
2026
2027 #[test]
2028 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2029 let tmp = tempfile::tempdir().unwrap();
2030 std::fs::write(
2031 tmp.path().join("metadata.json"),
2032 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2033 )
2034 .unwrap();
2035 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2036 let m = metadata(tmp.path());
2037 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2038 assert_eq!(m["model"], "m");
2039 let leftovers = std::fs::read_dir(tmp.path())
2040 .unwrap()
2041 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2042 .count();
2043 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2044 }
2045
2046 #[test]
2047 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2048 let tmp = tempfile::tempdir().unwrap();
2049 record_transcript_path(tmp.path(), "").unwrap();
2050 assert!(!tmp.path().join("metadata.json").exists());
2051
2052 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2053 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2054 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2055 }
2056
2057 use crate::session_state::{RepoBinding, SessionState};
2060
2061 fn binding(id: &str) -> RepoBinding {
2062 RepoBinding {
2063 repo_id: id.into(),
2064 git_url: None,
2065 remote_id: None,
2066 codebase_name: None,
2067 updated_at: "t".into(),
2068 }
2069 }
2070
2071 #[test]
2074 fn resolve_stream_binding_uses_session_active_when_unbound() {
2075 let session = SessionState {
2076 active: Some(binding("session-repo")),
2077 subagents: HashMap::new(),
2078 ..Default::default()
2079 };
2080 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2081 assert_eq!(got.unwrap().repo_id, "session-repo");
2082 }
2083
2084 #[test]
2087 fn resolve_stream_binding_falls_back_to_bound_config() {
2088 let session = SessionState::default();
2089 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2090 assert_eq!(got.unwrap().repo_id, "bound-repo");
2091 }
2092
2093 #[test]
2096 fn resolve_stream_binding_none_when_nothing_resolves() {
2097 let session = SessionState::default();
2098 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2099 assert!(got.is_none());
2100 }
2101
2102 #[test]
2105 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2106 let session = SessionState {
2107 active: Some(binding("session-repo")),
2108 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2109 ..Default::default()
2110 };
2111 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2112 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2113 }
2114
2115 #[test]
2119 fn resolve_stream_binding_falls_back_to_user_default() {
2120 let session = SessionState::default();
2121 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2122 assert_eq!(got.unwrap().repo_id, "userdef");
2123 }
2124
2125 #[test]
2128 fn resolve_stream_binding_prefers_bound_over_user_default() {
2129 let session = SessionState::default();
2130 let got = resolve_stream_binding(
2131 &session,
2132 "/wt/x",
2133 Some(binding("bound")),
2134 Some(binding("userdef")),
2135 );
2136 assert_eq!(got.unwrap().repo_id, "bound");
2137 }
2138
2139 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2142 crate::session_state::RepoBinding {
2143 repo_id: repo_id.into(),
2144 git_url: None,
2145 remote_id: None,
2146 codebase_name: None,
2147 updated_at: String::new(),
2148 }
2149 }
2150
2151 #[test]
2155 fn attribution_falls_back_to_project_when_no_repo_binds() {
2156 let pid = uuid::Uuid::new_v4();
2157 assert_eq!(
2158 attribution_for(None, Some(pid)),
2159 Some(Attribution::ProjectOnly { project_id: pid })
2160 );
2161 }
2162
2163 #[test]
2165 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2166 assert_eq!(attribution_for(None, None), None);
2167 }
2168
2169 #[test]
2172 fn attribution_uses_repo_with_no_project_overlay() {
2173 let repo = uuid::Uuid::new_v4().to_string();
2174 let b = binding_with(&repo);
2175 assert_eq!(
2176 attribution_for(Some(&b), None),
2177 Some(Attribution::Repo {
2178 repo_id: repo,
2179 project: None
2180 })
2181 );
2182 }
2183
2184 #[test]
2187 fn attribution_overlays_project_on_repo() {
2188 let repo = uuid::Uuid::new_v4().to_string();
2189 let pid = uuid::Uuid::new_v4();
2190 let b = binding_with(&repo);
2191 assert_eq!(
2192 attribution_for(Some(&b), Some(pid)),
2193 Some(Attribution::Repo {
2194 repo_id: repo,
2195 project: Some(pid)
2196 })
2197 );
2198 }
2199
2200 #[test]
2203 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2204 let pid = uuid::Uuid::new_v4();
2205 let b = binding_with("../../escape");
2206 assert_eq!(
2207 attribution_for(Some(&b), Some(pid)),
2208 Some(Attribution::ProjectOnly { project_id: pid })
2209 );
2210 }
2211
2212 #[test]
2215 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2216 let b = binding_with("../../escape");
2217 assert_eq!(attribution_for(Some(&b), None), None);
2218 }
2219
2220 #[test]
2225 fn pending_file_name_for_a_repo_is_unchanged() {
2226 let repo = uuid::Uuid::new_v4().to_string();
2227 assert_eq!(
2228 Attribution::Repo {
2229 repo_id: repo.clone(),
2230 project: Some(uuid::Uuid::new_v4())
2231 }
2232 .pending_file_name(),
2233 format!("pending-{repo}.jsonl")
2234 );
2235 }
2236
2237 #[test]
2240 fn pending_file_name_for_a_project_is_distinct() {
2241 let pid = uuid::Uuid::new_v4();
2242 assert_eq!(
2243 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2244 format!("pending-project-{pid}.jsonl")
2245 );
2246 }
2247
2248 #[test]
2251 fn binding_repo_id_is_valid_accepts_real_uuid() {
2252 assert!(binding_repo_id_is_valid(
2253 "550e8400-e29b-41d4-a716-446655440000"
2254 ));
2255 }
2256
2257 #[test]
2258 fn binding_repo_id_is_valid_rejects_path_traversal() {
2259 assert!(!binding_repo_id_is_valid("../evil"));
2260 }
2261
2262 #[test]
2263 fn binding_repo_id_is_valid_rejects_empty() {
2264 assert!(!binding_repo_id_is_valid(""));
2265 }
2266
2267 #[test]
2268 fn binding_repo_id_is_valid_rejects_non_uuid() {
2269 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2270 }
2271
2272 #[test]
2275 fn stamp_agent_sets_tool_and_version() {
2276 use crate::agent::Agent;
2277 let mut req = StreamEventRequest {
2278 protocol_version: 1,
2279 tool: Some("claude-code".to_string()),
2280 event_type: StreamEventType::ToolUse,
2281 session_id: "s".into(),
2282 timestamp: chrono::Utc::now(),
2283 hook_event_name: None,
2284 tool_name: None,
2285 tool_use_id: None,
2286 tool_input: None,
2287 tool_response: None,
2288 tool_is_error: None,
2289 event_index: None,
2290 event_uuid: None,
2291 transcript_lines: None,
2292 transcript_offset: None,
2293 model: None,
2294 cwd: None,
2295 final_stats: None,
2296 flow_id: None,
2297 labels: None,
2298 params: None,
2299 billing_mode: None,
2300 };
2301 stamp_agent(&mut req, Agent::Codex);
2302 assert_eq!(req.tool.as_deref(), Some("codex"));
2303 assert_eq!(req.protocol_version, 2);
2304
2305 stamp_agent(&mut req, Agent::ClaudeCode);
2306 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2307 assert_eq!(req.protocol_version, 1);
2308 }
2309
2310 fn repo_attr(repo_id: &str) -> Attribution {
2313 Attribution::Repo {
2314 repo_id: repo_id.into(),
2315 project: None,
2316 }
2317 }
2318
2319 #[test]
2320 fn pending_path_is_repo_scoped() {
2321 let dir = std::path::Path::new("/tmp/sess");
2322 assert_eq!(
2323 pending_path_for(dir, &repo_attr("repo-a")),
2324 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2325 );
2326 assert_ne!(
2327 pending_path_for(dir, &repo_attr("repo-a")),
2328 pending_path_for(dir, &repo_attr("repo-b")),
2329 );
2330 }
2331
2332 #[test]
2335 fn pending_path_for_a_project_never_collides_with_a_repo() {
2336 let dir = std::path::Path::new("/tmp/sess");
2337 let pid = uuid::Uuid::from_u128(9);
2338 assert_eq!(
2339 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2340 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2341 );
2342 assert_ne!(
2343 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2344 pending_path_for(dir, &repo_attr(&pid.to_string())),
2345 );
2346 }
2347
2348 #[test]
2351 fn read_new_transcript_lines_empty_path_is_noop() {
2352 let dir = tempfile::tempdir().unwrap();
2356 let offset_path = dir.path().join(".stream_offset");
2357 let (lines, start_offset, end_offset) =
2358 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2359 assert!(
2360 lines.is_empty(),
2361 "empty path must yield no transcript lines"
2362 );
2363 assert_eq!(start_offset, 0);
2364 assert_eq!(end_offset, 0);
2365 }
2366
2367 #[test]
2371 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2372 let dir = tempfile::tempdir().unwrap();
2373 let transcript_path = dir.path().join("transcript.jsonl");
2374 let offset_path = dir.path().join(".stream_offset");
2375
2376 fs::write(
2377 &transcript_path,
2378 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2379 )
2380 .unwrap();
2381
2382 let (lines, start_offset, end_offset) =
2383 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2384 assert_eq!(lines.len(), 2);
2385 assert_eq!(start_offset, 0, "first read starts at byte 0");
2386 assert!(end_offset > 0);
2387
2388 fs::write(&offset_path, end_offset.to_string()).unwrap();
2389
2390 let mut f = OpenOptions::new()
2391 .append(true)
2392 .open(&transcript_path)
2393 .unwrap();
2394 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2395 drop(f);
2396
2397 let (lines2, start_offset2, end_offset2) =
2398 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2399 assert_eq!(lines2.len(), 1);
2400 assert_eq!(
2401 start_offset2, end_offset,
2402 "second read's start_offset must equal the first read's persisted end_offset"
2403 );
2404 assert!(end_offset2 > start_offset2);
2405 }
2406
2407 #[tokio::test]
2425 async fn capture_project_precedence_local_only() {
2426 use crate::session_state::{ProjectBinding, SessionState};
2427 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2428 let tmp = tempfile::tempdir().unwrap();
2429 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2430 _guard.set("XDG_CONFIG_HOME", tmp.path());
2431 _guard.set("HOME", tmp.path());
2432 _guard.remove("TRACEVAULT_PROJECT");
2433
2434 let pb = |id: &str| ProjectBinding {
2435 project_id: id.into(),
2436 project_name: "n".into(),
2437 updated_at: "".into(),
2438 forced_until: None,
2439 };
2440 let u = uuid::Uuid::from_u128;
2441 let s = SessionState {
2443 active_project: Some(pb(&u(2).to_string())),
2444 ..Default::default()
2445 };
2446 assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
2447 let mut s = s;
2449 s.subagent_projects
2450 .insert("/wt".into(), pb(&u(1).to_string()));
2451 assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
2452 assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
2454 assert_eq!(capture_project(&SessionState::default(), None), None);
2456 let bad = SessionState {
2458 active_project: Some(pb("not-a-uuid")),
2459 ..Default::default()
2460 };
2461 assert_eq!(capture_project(&bad, None), None);
2462 let path = crate::user_project_default::default_project_path().unwrap();
2464 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2465 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2466 assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
2467 }
2468
2469 #[test]
2480 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2481 use crate::session_state::{ProjectBinding, SessionState};
2482 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2483 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2484 _guard.remove("TRACEVAULT_PROJECT");
2485 let pid = uuid::Uuid::from_u128(2);
2486 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2487 let s = SessionState {
2488 active_project: Some(ProjectBinding {
2489 project_id: pid.to_string(),
2490 project_name: "n".into(),
2491 updated_at: "".into(),
2492 forced_until: Some(future.clone()),
2493 }),
2494 ..Default::default()
2495 };
2496 let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
2497 assert_eq!(got.forced_until, Some(future));
2498 }
2499
2500 #[test]
2505 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2506 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2510
2511 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2512 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2513
2514 _guard.set("TRACEVAULT_PROJECT", uuid);
2515 let got = env_project_binding().expect("uuid form is honoured");
2516 assert_eq!(got.project_id, uuid);
2517
2518 _guard.set("TRACEVAULT_PROJECT", "my-project");
2519 assert!(
2520 env_project_binding().is_none(),
2521 "a name is ignored on the network-free capture path"
2522 );
2523
2524 _guard.remove("TRACEVAULT_PROJECT");
2525 assert!(env_project_binding().is_none());
2526 }
2527
2528 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2536 crate::session_state::ProjectBinding {
2537 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2538 project_name: "p".into(),
2539 updated_at: chrono::Utc::now().to_rfc3339(),
2540 forced_until: forced_until.map(str::to_string),
2541 }
2542 }
2543
2544 #[test]
2545 fn env_force_is_explicit_and_needs_no_expiry() {
2546 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2547 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2548 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2549
2550 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2551 }
2552
2553 #[test]
2554 fn absent_or_unrecognised_env_is_derived() {
2555 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2556 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2557
2558 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2559 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2560
2561 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2566 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2567 }
2568
2569 #[test]
2575 fn live_binding_force_is_explicit_without_env() {
2576 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2577 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2578 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2579
2580 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2581 let binding = forced_binding(Some(&future));
2582
2583 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2584 }
2585
2586 #[test]
2593 fn lapsed_binding_force_is_derived_without_env() {
2594 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2595 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2596 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2597
2598 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2599 let binding = forced_binding(Some(&past));
2600
2601 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2602 }
2603
2604 #[test]
2609 fn unparseable_forced_until_is_derived() {
2610 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2611 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2612 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2613
2614 let binding = forced_binding(Some("not-a-timestamp"));
2615
2616 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2617 }
2618
2619 #[test]
2626 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2627 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2628 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2629 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2630
2631 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2632 let binding = forced_binding(Some(&past));
2633
2634 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2635 }
2636
2637 #[tokio::test]
2650 async fn session_scoped_force_is_honoured_on_the_wire() {
2651 use crate::session_state::{ProjectBinding, SessionState};
2652
2653 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2654 let tmp = tempfile::tempdir().unwrap();
2655 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2656 _guard.set("XDG_CONFIG_HOME", tmp.path());
2660 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2661 _guard.remove("TRACEVAULT_PROJECT");
2665
2666 let pid = uuid::Uuid::from_u128(321);
2667 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2668 let session = SessionState {
2669 active_project: Some(ProjectBinding {
2670 project_id: pid.to_string(),
2671 project_name: "proj".into(),
2672 updated_at: "".into(),
2673 forced_until: Some(future),
2674 }),
2675 ..Default::default()
2676 };
2677 let capture_binding = capture_binding(&session, None);
2678
2679 let resp = ok_stream_response();
2680 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2681 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2682 let req = sample_stream_event_request();
2683 let mut warned = false;
2684
2685 let got = send_stream_event(
2686 &client,
2687 &Attribution::ProjectOnly { project_id: pid },
2688 attribution_force(capture_binding.as_ref()),
2689 &req,
2690 &mut warned,
2691 )
2692 .await
2693 .expect("send_stream_event must succeed");
2694 assert_eq!(
2695 got.expect("a successful send returns a response").status,
2696 "accepted"
2697 );
2698
2699 let captured = rx
2700 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2701 .expect("no request captured");
2702 assert!(
2703 captured
2704 .to_lowercase()
2705 .contains("x-tracevault-project-attribution: explicit"),
2706 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2707 );
2708 }
2709
2710 #[test]
2719 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2720 use crate::session_state::{ProjectBinding, SessionState};
2721
2722 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2723 let tmp = tempfile::tempdir().unwrap();
2724 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2725 _guard.set("XDG_CONFIG_HOME", tmp.path());
2726 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2727
2728 let project_a = uuid::Uuid::from_u128(1);
2729 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2730 crate::user_project_default::save(&ProjectBinding {
2731 project_id: project_a.to_string(),
2732 project_name: "a".into(),
2733 updated_at: chrono::Utc::now().to_rfc3339(),
2734 forced_until: Some(future),
2735 })
2736 .unwrap();
2737
2738 let project_b = uuid::Uuid::from_u128(2);
2739 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2740
2741 let capture_binding = capture_binding(&SessionState::default(), None);
2742 assert_eq!(
2743 capture_binding.as_ref().map(|b| b.project_id.as_str()),
2744 Some(project_b.to_string()).as_deref(),
2745 "TRACEVAULT_PROJECT must outrank the user-level default"
2746 );
2747
2748 assert_eq!(
2749 attribution_mode(capture_binding.as_ref()),
2750 AttributionMode::Derived,
2751 "a force on the user-default project must not leak onto a DIFFERENT, \
2752 higher-precedence project that never asked to be forced"
2753 );
2754 }
2755
2756 use std::io::BufReader;
2759 use std::net::TcpListener;
2760 use std::sync::mpsc;
2761 use std::thread;
2762 use std::time::{Duration, Instant};
2763
2764 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2769
2770 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2775 let deadline = Instant::now() + ACCEPT_DEADLINE;
2776 loop {
2777 match listener.accept() {
2778 Ok((stream, _)) => {
2779 let _ = stream.set_nonblocking(false);
2784 return Some(stream);
2785 }
2786 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2787 if Instant::now() >= deadline {
2788 return None;
2789 }
2790 thread::sleep(Duration::from_millis(20));
2791 }
2792 Err(_) => return None,
2793 }
2794 }
2795 }
2796
2797 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2801
2802 fn capture_request_and_respond(
2822 stream: std::net::TcpStream,
2823 tx: &mpsc::Sender<String>,
2824 response: &str,
2825 ) {
2826 let mut reader = BufReader::new(stream);
2827 let mut captured = String::new();
2828 let _ = reader.read_line(&mut captured);
2829 loop {
2830 let mut header = String::new();
2831 if reader.read_line(&mut header).unwrap_or(0) == 0 {
2832 break;
2833 }
2834 if header.trim().is_empty() {
2835 break;
2836 }
2837 captured.push_str(&header);
2838 }
2839 let _ = tx.send(captured);
2840 let mut stream = reader.into_inner();
2841 let _ = stream.write_all(response.as_bytes());
2842 let _ = stream.flush();
2843 }
2844
2845 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2850 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2851 listener.set_nonblocking(true).unwrap();
2852 let addr = listener.local_addr().unwrap();
2853 let (tx, rx) = mpsc::channel();
2854 thread::spawn(move || {
2855 if let Some(stream) = accept_with_deadline(&listener) {
2856 capture_request_and_respond(stream, &tx, response);
2857 }
2858 });
2859 (format!("http://{addr}"), rx)
2860 }
2861
2862 fn ok_stream_response() -> String {
2863 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2864 session_db_id: uuid::Uuid::nil(),
2865 event_db_id: Some(uuid::Uuid::nil()),
2866 status: "accepted".to_string(),
2867 })
2868 .unwrap();
2869 format!(
2870 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2871 body.len(),
2872 body
2873 )
2874 }
2875
2876 fn sample_stream_event_request() -> StreamEventRequest {
2877 StreamEventRequest {
2878 protocol_version: 2,
2879 tool: Some("claude-code".to_string()),
2880 event_type: StreamEventType::ToolUse,
2881 session_id: "sess-1".into(),
2882 timestamp: chrono::Utc::now(),
2883 hook_event_name: Some("PostToolUse".into()),
2884 tool_name: None,
2885 tool_use_id: None,
2886 tool_input: None,
2887 tool_response: None,
2888 tool_is_error: None,
2889 event_index: None,
2890 event_uuid: None,
2891 transcript_lines: None,
2892 transcript_offset: None,
2893 model: None,
2894 cwd: None,
2895 final_stats: None,
2896 flow_id: None,
2897 labels: None,
2898 params: None,
2899 billing_mode: None,
2900 }
2901 }
2902
2903 #[tokio::test]
2908 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2909 use crate::session_state::{ProjectBinding, SessionState};
2910
2911 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2915 let tmp = tempfile::tempdir().unwrap();
2916 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2917 _guard.set("XDG_CONFIG_HOME", tmp.path());
2918 _guard.remove("TRACEVAULT_PROJECT");
2923 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2924
2925 let pid = uuid::Uuid::from_u128(99);
2926 let session = SessionState {
2927 active_project: Some(ProjectBinding {
2928 project_id: pid.to_string(),
2929 project_name: "proj".into(),
2930 updated_at: "".into(),
2931 forced_until: None,
2932 }),
2933 ..Default::default()
2934 };
2935 let capture_binding = capture_binding(&session, None);
2936 let capture_pid = capture_binding
2937 .as_ref()
2938 .and_then(crate::resolution::capture_project_id);
2939 assert_eq!(capture_pid, Some(pid));
2940
2941 let resp = ok_stream_response();
2942 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2943 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2944 let req = sample_stream_event_request();
2945
2946 let mut warned = false;
2947 let got = send_stream_event(
2948 &client,
2949 &Attribution::Repo {
2950 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2951 project: capture_pid,
2952 },
2953 attribution_force(capture_binding.as_ref()),
2954 &req,
2955 &mut warned,
2956 )
2957 .await
2958 .expect("send_stream_event must succeed");
2959 assert_eq!(
2960 got.expect("a successful send returns a response").status,
2961 "accepted"
2962 );
2963
2964 let line = rx
2965 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2966 .expect("no request captured");
2967 assert!(
2968 line.starts_with(&format!(
2969 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2970 )),
2971 "an active project binding must route to the project-scoped endpoint, got: {line}"
2972 );
2973 assert!(
2979 line.to_lowercase()
2980 .contains("x-tracevault-project-attribution: derived"),
2981 "got: {line}"
2982 );
2983 }
2984
2985 #[tokio::test]
2990 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2991 use crate::session_state::SessionState;
2992
2993 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2994 let tmp = tempfile::tempdir().unwrap();
2995 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2996 _guard.set("XDG_CONFIG_HOME", tmp.path());
3001 _guard.remove("TRACEVAULT_PROJECT");
3002
3003 let capture_binding = capture_binding(&SessionState::default(), None);
3004 assert_eq!(capture_binding, None);
3005
3006 let resp = ok_stream_response();
3007 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3008 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3009 let req = sample_stream_event_request();
3010
3011 let mut warned = false;
3012 let got = send_stream_event(
3013 &client,
3014 &Attribution::Repo {
3015 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3016 project: None,
3017 },
3018 attribution_force(capture_binding.as_ref()),
3019 &req,
3020 &mut warned,
3021 )
3022 .await
3023 .expect("send_stream_event must succeed");
3024 assert_eq!(
3025 got.expect("a successful send returns a response").status,
3026 "accepted"
3027 );
3028
3029 let line = rx
3030 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3031 .expect("no request captured");
3032 assert!(
3033 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3034 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3035 );
3036 }
3037
3038 fn spawn_n_capturing_requests(
3049 responses: Vec<&'static str>,
3050 ) -> (String, mpsc::Receiver<String>) {
3051 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3052 listener.set_nonblocking(true).unwrap();
3053 let addr = listener.local_addr().unwrap();
3054 let (tx, rx) = mpsc::channel();
3055 thread::spawn(move || {
3056 for response in responses {
3057 let Some(stream) = accept_with_deadline(&listener) else {
3062 break;
3063 };
3064 capture_request_and_respond(stream, &tx, response);
3065 }
3066 });
3071 (format!("http://{addr}"), rx)
3072 }
3073
3074 #[tokio::test]
3081 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3082 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3083 let resp_400 = format!(
3084 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3085 body_400.len(),
3086 body_400
3087 );
3088 let resp_200 = ok_stream_response();
3089
3090 let (base, rx) = spawn_n_capturing_requests(vec![
3091 Box::leak(resp_400.into_boxed_str()),
3092 Box::leak(resp_200.into_boxed_str()),
3093 ]);
3094 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3095 let req = sample_stream_event_request();
3096 let pid = uuid::Uuid::from_u128(42);
3097
3098 let mut warned = false;
3099 let err = send_stream_event(
3100 &client,
3101 &Attribution::Repo {
3102 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3103 project: Some(pid),
3104 },
3105 attribution_force(None),
3106 &req,
3107 &mut warned,
3108 )
3109 .await
3110 .expect_err("a refused declared project must be an error, not a silent fallback");
3111 assert!(
3112 err.to_string().contains("400"),
3113 "propagated error must reflect the status, got: {err}"
3114 );
3115 assert!(
3116 warned,
3117 "the refusal must be printed (gated on `warned`) so it is visible"
3118 );
3119
3120 let first = rx
3121 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3122 .expect("no first request captured");
3123 assert!(
3124 first.contains(&format!("/projects/{pid}/stream")),
3125 "first request must hit the project-scoped endpoint, got: {first}"
3126 );
3127 assert!(
3128 first.contains("repo_id="),
3129 "first request must carry repo_id, got: {first}"
3130 );
3131
3132 assert!(
3133 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3134 "no second (repo-scoped fallback) request must be sent"
3135 );
3136 }
3137
3138 #[tokio::test]
3141 async fn send_stream_event_errors_on_403_without_fallback() {
3142 let body_403 = "forbidden";
3143 let resp_403 = format!(
3144 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3145 body_403.len(),
3146 body_403
3147 );
3148 let resp_200 = ok_stream_response();
3149
3150 let (base, rx) = spawn_n_capturing_requests(vec![
3151 Box::leak(resp_403.into_boxed_str()),
3152 Box::leak(resp_200.into_boxed_str()),
3153 ]);
3154 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3155 let req = sample_stream_event_request();
3156 let pid = uuid::Uuid::from_u128(43);
3157
3158 let mut warned = false;
3159 let err = send_stream_event(
3160 &client,
3161 &Attribution::Repo {
3162 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3163 project: Some(pid),
3164 },
3165 attribution_force(None),
3166 &req,
3167 &mut warned,
3168 )
3169 .await
3170 .expect_err("a refused declared project must be an error, not a silent fallback");
3171 assert!(
3172 err.to_string().contains("403"),
3173 "propagated error must reflect the status, got: {err}"
3174 );
3175 assert!(
3176 warned,
3177 "the refusal must be printed (gated on `warned`) so it is visible"
3178 );
3179
3180 let first = rx
3181 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3182 .expect("no first request captured");
3183 assert!(
3184 first.contains(&format!("/projects/{pid}/stream")),
3185 "first request must hit the project-scoped endpoint, got: {first}"
3186 );
3187 assert!(
3188 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3189 "no second (repo-scoped fallback) request must be sent"
3190 );
3191 }
3192
3193 #[tokio::test]
3198 async fn refused_error_is_printed_once_per_invocation() {
3199 let body_400 = "not a member";
3200 let resp_400 = || {
3201 format!(
3202 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3203 body_400.len(),
3204 body_400
3205 )
3206 };
3207 let (base, _rx) = spawn_n_capturing_requests(vec![
3208 Box::leak(resp_400().into_boxed_str()),
3209 Box::leak(resp_400().into_boxed_str()),
3210 ]);
3211 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3212 let req = sample_stream_event_request();
3213 let pid = uuid::Uuid::from_u128(44);
3214 let attribution = Attribution::Repo {
3215 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3216 project: Some(pid),
3217 };
3218
3219 let mut warned = false;
3220 assert!(
3221 send_stream_event(
3222 &client,
3223 &attribution,
3224 attribution_force(None),
3225 &req,
3226 &mut warned
3227 )
3228 .await
3229 .is_err(),
3230 "a refused declared project must be an error"
3231 );
3232 assert!(warned, "the flag must be set after the first refusal");
3233
3234 assert!(
3235 send_stream_event(
3236 &client,
3237 &attribution,
3238 attribution_force(None),
3239 &req,
3240 &mut warned
3241 )
3242 .await
3243 .is_err(),
3244 "a second refusal must also be an error"
3245 );
3246 assert!(warned, "the flag stays set across the shared invocation");
3247 }
3248
3249 #[tokio::test]
3261 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3262 let body_403 = "forbidden";
3263 let resp_403 = format!(
3264 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3265 body_403.len(),
3266 body_403
3267 );
3268 let resp_200 = ok_stream_response();
3269
3270 let (base, rx) = spawn_n_capturing_requests(vec![
3271 Box::leak(resp_403.into_boxed_str()),
3272 Box::leak(resp_200.into_boxed_str()),
3273 ]);
3274 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3275 let req = sample_stream_event_request();
3276 let pid = uuid::Uuid::from_u128(42);
3277
3278 let forced = crate::session_state::ProjectBinding {
3281 project_id: pid.to_string(),
3282 project_name: "forced".into(),
3283 updated_at: "".into(),
3284 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3285 };
3286
3287 let mut warned = false;
3288 let err = send_stream_event(
3289 &client,
3290 &Attribution::Repo {
3291 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3292 project: Some(pid),
3293 },
3294 attribution_force(Some(&forced)),
3295 &req,
3296 &mut warned,
3297 )
3298 .await
3299 .expect_err("a refused force must be an error, not a silent fallback");
3300 assert!(
3301 err.to_string().contains("403"),
3302 "propagated error must reflect the status, got: {err}"
3303 );
3304 assert!(warned, "the refusal must be printed exactly once");
3305
3306 let first = rx
3307 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3308 .expect("no first request captured");
3309 assert!(
3310 first.contains(&format!("/projects/{pid}/stream")),
3311 "first request must hit the project-scoped endpoint, got: {first}"
3312 );
3313 assert!(
3314 first
3315 .to_lowercase()
3316 .contains("x-tracevault-project-attribution: explicit"),
3317 "the refused send must have DECLARED explicit — this is the mode \
3318 `refused_error` is handed: {first}"
3319 );
3320
3321 assert!(
3322 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3323 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3324 );
3325 }
3326
3327 #[tokio::test]
3336 async fn send_stream_event_project_only_omits_repo_id() {
3337 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3338 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3339 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3340
3341 let resp = ok_stream_response();
3342 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3343 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3344 let req = sample_stream_event_request();
3345 let pid = uuid::Uuid::from_u128(11);
3346
3347 let mut warned = false;
3348 let got = send_stream_event(
3349 &client,
3350 &Attribution::ProjectOnly { project_id: pid },
3351 attribution_force(None),
3352 &req,
3353 &mut warned,
3354 )
3355 .await
3356 .expect("a repo-less project send must succeed");
3357 assert_eq!(
3358 got.expect("a successful send returns a response").status,
3359 "accepted"
3360 );
3361
3362 let line = rx
3363 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3364 .expect("no request captured");
3365 assert!(
3366 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3367 "expected a bare project path with no query string, got: {line}"
3368 );
3369 assert!(
3370 line.to_lowercase()
3371 .contains("x-tracevault-project-attribution: derived"),
3372 "with no forced binding, the header must declare `derived`, got: {line}"
3373 );
3374 assert!(
3375 !warned,
3376 "a repo-less send has no fallback and must not warn about one"
3377 );
3378 }
3379
3380 #[tokio::test]
3387 async fn send_stream_event_project_only_drops_on_scoping_4xx() {
3388 let body = "no such project";
3389 let resp_404 = format!(
3390 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3391 body.len(),
3392 body
3393 );
3394 let (base, rx) = spawn_n_capturing_requests(vec![
3401 Box::leak(resp_404.clone().into_boxed_str()),
3402 Box::leak(resp_404.into_boxed_str()),
3403 ]);
3404 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3405 let req = sample_stream_event_request();
3406 let pid = uuid::Uuid::from_u128(12);
3407
3408 let mut warned = false;
3409 let got = send_stream_event(
3410 &client,
3411 &Attribution::ProjectOnly { project_id: pid },
3412 attribution_force(None),
3413 &req,
3414 &mut warned,
3415 )
3416 .await
3417 .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
3418 assert!(
3419 got.is_none(),
3420 "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
3421 );
3422 assert!(
3423 warned,
3424 "dropping data silently is the failure mode to avoid"
3425 );
3426
3427 let first = rx
3428 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3429 .expect("no request captured");
3430 assert!(
3431 first.contains(&format!("/projects/{pid}/stream")),
3432 "must hit the project-scoped endpoint, got: {first}"
3433 );
3434 assert!(
3435 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3436 "a repo-less send must make exactly one request — no fallback exists"
3437 );
3438 }
3439
3440 #[tokio::test]
3444 async fn send_stream_event_project_only_buffers_on_403() {
3445 let body = "forbidden";
3446 let resp_403 = format!(
3447 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3448 body.len(),
3449 body
3450 );
3451 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
3452 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3453 let req = sample_stream_event_request();
3454
3455 let mut warned = false;
3456 let err = send_stream_event(
3457 &client,
3458 &Attribution::ProjectOnly {
3459 project_id: uuid::Uuid::from_u128(13),
3460 },
3461 attribution_force(None),
3462 &req,
3463 &mut warned,
3464 )
3465 .await
3466 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
3467 assert!(
3468 err.to_string().contains("403"),
3469 "propagated error must reflect the status, got: {err}"
3470 );
3471 }
3472
3473 #[tokio::test]
3478 async fn send_stream_event_does_not_fall_back_on_transient_503() {
3479 let body_503 = "internal error";
3480 let resp_503 = format!(
3481 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3482 body_503.len(),
3483 body_503
3484 );
3485 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
3486 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3487 let req = sample_stream_event_request();
3488 let pid = uuid::Uuid::from_u128(7);
3489
3490 let mut warned = false;
3491 let err = send_stream_event(
3492 &client,
3493 &Attribution::Repo {
3494 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3495 project: Some(pid),
3496 },
3497 attribution_force(None),
3498 &req,
3499 &mut warned,
3500 )
3501 .await
3502 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
3503 assert!(
3504 err.to_string().contains("503"),
3505 "propagated error must reflect the transient status, got: {err}"
3506 );
3507 assert!(
3508 deterministic_client_error_kind(err.as_ref()).is_none(),
3509 "a 503 must not be classified as a deterministic client error"
3510 );
3511
3512 let first = rx
3513 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3514 .expect("no request captured");
3515 assert!(
3516 first.contains(&format!("/projects/{pid}/stream")),
3517 "must hit the project-scoped endpoint, got: {first}"
3518 );
3519
3520 assert!(
3527 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3528 "no second (fallback) request should have been sent for a transient error"
3529 );
3530 }
3531
3532 #[test]
3536 fn a_403_is_classified_apart_from_the_scoping_statuses() {
3537 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3538 assert_eq!(
3539 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3540 Some(ClientErrorKind::Forbidden)
3541 );
3542 for scoping in [
3543 "Stream failed (400 Bad Request): {}",
3544 "Stream failed (404 Not Found): {}",
3545 "Stream failed (409 Conflict): {}",
3546 ] {
3547 assert_eq!(
3548 deterministic_client_error_kind(err(scoping).as_ref()),
3549 Some(ClientErrorKind::Scoping),
3550 "{scoping}"
3551 );
3552 }
3553 for transient in [
3556 "Stream failed (401 Unauthorized): {}",
3557 "Stream failed (503 Service Unavailable): {}",
3558 "error sending request for url (http://x/stream)",
3559 ] {
3560 assert_eq!(
3561 deterministic_client_error_kind(err(transient).as_ref()),
3562 None,
3563 "{transient}"
3564 );
3565 }
3566 }
3567
3568 #[test]
3573 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3574 let pid = uuid::Uuid::from_u128(7);
3575
3576 let forbidden = refused_error(
3577 pid,
3578 &ClientErrorKind::Forbidden,
3579 AttributionForce::default(),
3580 );
3581 assert!(forbidden.contains("403"), "{forbidden}");
3582 assert!(
3583 forbidden.contains("no `tracevault` grant in Control Plane"),
3584 "must offer the missing-role explanation: {forbidden}"
3585 );
3586 assert!(
3587 forbidden.contains("no `Operator` role on it"),
3588 "must still offer the project explanation: {forbidden}"
3589 );
3590 assert!(
3591 forbidden.starts_with("tracevault: error:"),
3592 "a refusal is an error, not a warning: {forbidden}"
3593 );
3594 assert!(forbidden.contains(&pid.to_string()));
3595
3596 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3599 assert!(scoping.contains("project switch"), "{scoping}");
3600 assert!(
3601 !scoping.contains("`tracevault` grant"),
3602 "the scoping case must not mention the `tracevault` grant: {scoping}"
3603 );
3604
3605 for s in [&forbidden, &scoping] {
3606 assert!(s.contains("--user"), "must name the --user fix: {s}");
3609 assert!(
3610 s.contains("user_project.toml"),
3611 "must name the machine-wide default's file: {s}"
3612 );
3613 assert!(
3614 !s.contains("repo deduction"),
3615 "must never describe re-attribution to another project: {s}"
3616 );
3617 assert!(
3618 !s.contains("Attributing via"),
3619 "must never claim the event was re-attributed: {s}"
3620 );
3621 }
3622 }
3623
3624 #[test]
3635 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3636 let pid = uuid::Uuid::from_u128(7);
3637
3638 let explicit = refused_error(
3639 pid,
3640 &ClientErrorKind::Forbidden,
3641 AttributionForce {
3642 env: false,
3643 binding: true,
3644 },
3645 );
3646 assert!(
3647 explicit.contains("FORCE"),
3648 "the refusal of the force itself must be named: {explicit}"
3649 );
3650 assert!(
3651 explicit.contains("Operator"),
3652 "must name the grant forcing requires: {explicit}"
3653 );
3654 assert!(
3655 explicit.contains("Control Plane"),
3656 "must name the identity forcing requires: {explicit}"
3657 );
3658 assert!(
3662 explicit.contains("`tracevault` grant")
3663 && explicit.contains("no `Operator` role on it"),
3664 "the membership causes must still be named: {explicit}"
3665 );
3666 assert!(
3669 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3670 "must never claim the event was re-attributed: {explicit}"
3671 );
3672
3673 let derived = refused_error(
3678 pid,
3679 &ClientErrorKind::Forbidden,
3680 AttributionForce::default(),
3681 );
3682 assert!(
3683 !derived.contains("FORCE"),
3684 "a `derived` send never forced anything: {derived}"
3685 );
3686 }
3687
3688 #[test]
3693 fn an_explicit_scoping_failure_does_not_blame_the_force() {
3694 let pid = uuid::Uuid::from_u128(7);
3695 let scoping = refused_error(
3696 pid,
3697 &ClientErrorKind::Scoping,
3698 AttributionForce {
3699 env: true,
3700 binding: true,
3701 },
3702 );
3703 assert!(!scoping.contains("FORCE"), "{scoping}");
3704 assert_eq!(
3705 scoping,
3706 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3707 "the scoping wording does not depend on the mode"
3708 );
3709 }
3710
3711 #[test]
3731 fn the_403_remediation_names_the_force_source_actually_in_effect() {
3732 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3733 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3734 let pid = uuid::Uuid::from_u128(7);
3735 let live = forced_binding(Some(
3736 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3737 ));
3738 let never_forced = forced_binding(None);
3739
3740 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3744 let env_only = refused_error(
3745 pid,
3746 &ClientErrorKind::Forbidden,
3747 attribution_force(Some(&never_forced)),
3748 );
3749 assert!(
3750 env_only.contains("FORCE"),
3751 "an env-sourced force is still a force: {env_only}"
3752 );
3753 assert!(
3754 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3755 "must name the variable that is doing the forcing: {env_only}"
3756 );
3757 assert!(
3758 !env_only.contains("--project-attribution"),
3759 "must NOT tell the operator to drop a flag that would change \
3760 nothing here — this is the bug: {env_only}"
3761 );
3762
3763 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3767 let binding_only = refused_error(
3768 pid,
3769 &ClientErrorKind::Forbidden,
3770 attribution_force(Some(&live)),
3771 );
3772 assert!(
3773 binding_only.contains("--project-attribution"),
3774 "a persisted force IS cleared by switching without the flag: {binding_only}"
3775 );
3776 assert!(
3777 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3778 "must not send the operator after an unset variable: {binding_only}"
3779 );
3780
3781 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3785 let both = refused_error(
3786 pid,
3787 &ClientErrorKind::Forbidden,
3788 attribution_force(Some(&live)),
3789 );
3790 assert!(
3791 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3792 && both.contains("--project-attribution"),
3793 "both sources are in effect and both must be named: {both}"
3794 );
3795 assert!(
3796 both.contains("BOTH"),
3797 "must say that removing only one is not enough: {both}"
3798 );
3799 }
3800
3801 #[test]
3806 fn no_force_means_no_remediation_clause() {
3807 let pid = uuid::Uuid::from_u128(7);
3808 let none = refused_error(
3809 pid,
3810 &ClientErrorKind::Forbidden,
3811 AttributionForce::default(),
3812 );
3813 assert!(
3814 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3815 && !none.contains("--project-attribution"),
3816 "a derived send has no force to remove: {none}"
3817 );
3818 }
3819
3820 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
3825 let path = dir.join("transcript.jsonl");
3826 let mut body = String::new();
3827 for i in 0..n {
3828 let line = serde_json::json!({
3829 "type": "user",
3830 "n": i,
3831 "message": {"content": "x".repeat(line_bytes)},
3832 });
3833 body.push_str(&line.to_string());
3834 body.push('\n');
3835 }
3836 fs::write(&path, body).unwrap();
3837 path
3838 }
3839
3840 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
3842 StreamEventRequest {
3843 tool_name: Some("Bash".into()),
3844 tool_use_id: Some("toolu_1".into()),
3845 tool_input: Some(serde_json::json!({"command": "ls"})),
3846 event_uuid: Some(uuid::Uuid::now_v7()),
3847 transcript_lines: Some(lines),
3848 transcript_offset: Some(offset),
3849 ..sample_stream_event_request()
3850 }
3851 }
3852
3853 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
3854 part.transcript_lines.clone().unwrap_or_default()
3855 }
3856
3857 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
3860 parts
3861 .iter()
3862 .flat_map(|p| {
3863 let offset = p.transcript_offset.unwrap();
3864 part_lines(p)
3865 .into_iter()
3866 .enumerate()
3867 .map(move |(i, l)| (offset + i as i64, l))
3868 })
3869 .collect()
3870 }
3871
3872 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
3874 (0..n)
3875 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
3876 .collect()
3877 }
3878
3879 #[test]
3880 fn split_leaves_a_request_under_the_cap_unchanged() {
3881 let req = event_with_lines(big_lines(3, 100), 0);
3882
3883 let parts = split_into_parts(req.clone());
3884
3885 assert_eq!(parts.len(), 1);
3886 assert_eq!(
3887 serde_json::to_value(&parts[0]).unwrap(),
3888 serde_json::to_value(&req).unwrap()
3889 );
3890 }
3891
3892 #[test]
3896 fn split_carries_every_line_of_a_batch_over_the_cap() {
3897 let dir = tempfile::tempdir().unwrap();
3898 let transcript = write_transcript(dir.path(), 300, 5_000);
3900 let (lines, start, _) =
3901 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
3902 let req = event_with_lines(lines.clone(), start);
3903 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
3904
3905 let parts = split_into_parts(req.clone());
3906
3907 assert!(parts.len() >= 3, "got {} parts", parts.len());
3908 for part in &parts {
3909 assert!(
3910 part.serialized_len() <= MAX_REQUEST_BYTES,
3911 "part of {} bytes exceeds the cap",
3912 part.serialized_len()
3913 );
3914 }
3915 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3916 assert_eq!(sent, lines, "every line, once, in order");
3917
3918 let (event, transcript_parts) = parts.split_last().unwrap();
3920 assert_eq!(event.event_type, StreamEventType::ToolUse);
3921 assert_eq!(event.event_uuid, req.event_uuid);
3922 assert_eq!(event.tool_input, req.tool_input);
3923 for part in transcript_parts {
3924 assert_eq!(part.event_type, StreamEventType::Transcript);
3925 assert!(part.event_uuid.is_none());
3926 assert!(part.tool_input.is_none());
3927 assert!(part.tool_name.is_none());
3928 }
3929 assert!(
3930 !part_lines(event).is_empty(),
3931 "the event keeps the lines that fit beside it"
3932 );
3933 }
3934
3935 #[test]
3939 fn split_keeps_each_lines_unsplit_chunk_index() {
3940 let lines = big_lines(300, 5_000);
3941 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
3942
3943 let expected: Vec<_> = lines
3944 .into_iter()
3945 .enumerate()
3946 .map(|(i, l)| (1_000 + i as i64, l))
3947 .collect();
3948 assert_eq!(chunk_indexes(&parts), expected);
3949 }
3950
3951 #[test]
3956 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
3957 let lines = big_lines(10, 200_000);
3958 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
3959 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
3960
3961 for (index, line) in &short {
3962 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
3963 assert_eq!(in_long.0, *index, "line {line} indexed differently");
3964 }
3965 }
3966
3967 #[test]
3970 fn split_sends_a_single_oversized_line_alone() {
3971 let lines = vec![
3972 serde_json::json!({"n": 0}),
3973 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
3974 serde_json::json!({"n": 2}),
3975 ];
3976
3977 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
3978
3979 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3980 assert_eq!(sent, lines);
3981 let big = parts
3982 .iter()
3983 .find(|p| part_lines(p).contains(&lines[1]))
3984 .unwrap();
3985 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
3986 assert_eq!(big.transcript_offset, Some(1));
3987 }
3988
3989 fn far_deadline() -> std::time::Instant {
3990 std::time::Instant::now() + Duration::from_secs(60)
3991 }
3992
3993 fn captured_body(captured: &str) -> StreamEventRequest {
3994 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
3995 serde_json::from_str(body).expect("request body is a StreamEventRequest")
3996 }
3997
3998 #[tokio::test]
4000 async fn deliver_parts_sends_every_part() {
4001 let dir = tempfile::tempdir().unwrap();
4002 let pending_path = dir.path().join("pending.jsonl");
4003 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4004 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4005 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4006
4007 let all_accepted = deliver_parts(
4008 &client,
4009 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4010 AttributionForce::default(),
4011 parts.clone(),
4012 &pending_path,
4013 false,
4014 far_deadline(),
4015 &mut false,
4016 )
4017 .await
4018 .unwrap();
4019
4020 assert!(all_accepted);
4021 for part in &parts {
4022 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4023 assert_eq!(got.transcript_offset, part.transcript_offset);
4024 assert_eq!(got.transcript_lines, part.transcript_lines);
4025 }
4026 assert!(drain_pending(&pending_path).unwrap().is_empty());
4027 }
4028
4029 #[tokio::test]
4033 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4034 let dir = tempfile::tempdir().unwrap();
4035 let pending_path = dir.path().join("pending.jsonl");
4036 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4037 assert!(parts.len() >= 3);
4038 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4039 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4040 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4041
4042 let all_accepted = deliver_parts(
4043 &client,
4044 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4045 AttributionForce::default(),
4046 parts.clone(),
4047 &pending_path,
4048 false,
4049 far_deadline(),
4050 &mut false,
4051 )
4052 .await
4053 .unwrap();
4054
4055 assert!(!all_accepted);
4056 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4057 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4058 assert!(
4059 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4060 "nothing is sent after the first failure"
4061 );
4062 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4063 .unwrap()
4064 .iter()
4065 .map(|j| serde_json::from_str(j).unwrap())
4066 .collect();
4067 assert_eq!(queued.len(), parts.len() - 1);
4068 for (q, part) in queued.iter().zip(&parts[1..]) {
4069 assert_eq!(q.transcript_offset, part.transcript_offset);
4070 assert_eq!(q.transcript_lines, part.transcript_lines);
4071 }
4072 }
4073
4074 #[tokio::test]
4077 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4078 let dir = tempfile::tempdir().unwrap();
4079 let pending_path = dir.path().join("pending.jsonl");
4080 let parts = split_into_parts(sample_stream_event_request());
4081 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4082
4083 let all_accepted = deliver_parts(
4084 &client,
4085 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4086 AttributionForce::default(),
4087 parts,
4088 &pending_path,
4089 true,
4090 far_deadline(),
4091 &mut false,
4092 )
4093 .await
4094 .unwrap();
4095
4096 assert!(!all_accepted);
4097 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4098 }
4099
4100 #[tokio::test]
4103 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
4104 let dir = tempfile::tempdir().unwrap();
4105 let pending_path = dir.path().join("pending.jsonl");
4106 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4107 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4108 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4109
4110 let all_accepted = deliver_parts(
4111 &client,
4112 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4113 AttributionForce::default(),
4114 parts.clone(),
4115 &pending_path,
4116 false,
4117 std::time::Instant::now(),
4118 &mut false,
4119 )
4120 .await
4121 .unwrap();
4122
4123 assert!(!all_accepted);
4124 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
4125 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
4126 }
4127
4128 #[tokio::test]
4133 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
4134 let dir = tempfile::tempdir().unwrap();
4135 let pending_path = dir.path().join("pending.jsonl");
4136 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
4137 let base = format!("http://{}", listener.local_addr().unwrap());
4138 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4140 let started = Instant::now();
4141
4142 let all_accepted = deliver_parts(
4143 &client,
4144 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4145 AttributionForce::default(),
4146 vec![event_with_lines(big_lines(1, 10), 0)],
4147 &pending_path,
4148 false,
4149 started + Duration::from_millis(100),
4150 &mut false,
4151 )
4152 .await
4153 .unwrap();
4154
4155 assert!(!all_accepted);
4156 assert!(started.elapsed() < Duration::from_secs(10));
4157 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4158 drop(listener);
4159 }
4160
4161 const PARENT_SESSION: &str = "parent-session";
4164 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
4165
4166 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
4170 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
4171 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4172 let subagents = dir.join(PARENT_SESSION).join("subagents");
4173 fs::create_dir_all(&subagents).unwrap();
4174 let session_dir = dir.join("tv-session");
4175 fs::create_dir_all(&session_dir).unwrap();
4176 (main, subagents, session_dir)
4177 }
4178
4179 fn subagent_line(agent: &str, n: usize) -> String {
4180 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
4181 }
4182
4183 fn append_raw(path: &Path, text: &str) {
4184 let mut f = fs::OpenOptions::new()
4185 .create(true)
4186 .append(true)
4187 .open(path)
4188 .unwrap();
4189 f.write_all(text.as_bytes()).unwrap();
4190 }
4191
4192 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
4193 let path = subagents.join(format!("agent-{agent}.jsonl"));
4194 for n in ns {
4195 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
4196 }
4197 }
4198
4199 async fn sweep(
4203 responses: Vec<String>,
4204 main: &Path,
4205 session_dir: &Path,
4206 pending_path: &Path,
4207 ) -> Vec<StreamEventRequest> {
4208 sweep_waiting(responses, main, session_dir, pending_path, None).await
4209 }
4210
4211 async fn sweep_waiting(
4214 responses: Vec<String>,
4215 main: &Path,
4216 session_dir: &Path,
4217 pending_path: &Path,
4218 wait_for_lock: Option<Instant>,
4219 ) -> Vec<StreamEventRequest> {
4220 let expected = responses.len();
4221 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4222 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4223 let event = StreamEventRequest {
4224 session_id: PARENT_SESSION.into(),
4225 ..sample_stream_event_request()
4226 };
4227 deliver_subagent_transcripts(
4228 &client,
4229 &repo_attr(SUBAGENT_REPO),
4230 AttributionForce::default(),
4231 &transcript_template(&event),
4232 main,
4233 session_dir,
4234 pending_path,
4235 false,
4236 Instant::now() + Duration::from_secs(60),
4237 wait_for_lock,
4238 &mut false,
4239 )
4240 .await
4241 .unwrap();
4242 (0..expected)
4243 .map(|_| {
4244 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4245 assert!(
4246 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4247 "{captured}"
4248 );
4249 let body = captured.splitn(3, " | ").nth(2).unwrap();
4250 serde_json::from_str(body).unwrap()
4251 })
4252 .collect()
4253 }
4254
4255 fn agent_of(line: &serde_json::Value) -> &str {
4256 line["agentId"].as_str().unwrap()
4257 }
4258
4259 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4263 for req in reqs {
4264 assert_eq!(req.event_type, StreamEventType::Transcript);
4265 assert_eq!(req.session_id, PARENT_SESSION);
4266 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4267 let lines = part_lines(req);
4268 let agent = agent_of(&lines[0]);
4269 assert!(
4270 lines.iter().all(|l| agent_of(l) == agent),
4271 "a request mixes subagent files: {lines:?}"
4272 );
4273 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4274 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4275 assert_eq!(req.transcript_offset, Some(first));
4276 }
4277 }
4278
4279 #[tokio::test]
4280 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4281 let dir = tempfile::tempdir().unwrap();
4282 let (main, subagents, session_dir) = claude_session(dir.path());
4283 let pending = session_dir.join("pending.jsonl");
4284 let ok = ok_stream_response;
4285 let mut all = Vec::new();
4286
4287 append_subagent_lines(&subagents, "a1", 0..2);
4289 append_subagent_lines(&subagents, "b2", 0..1);
4290 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4291 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4292 assert_eq!(reqs.len(), 2);
4293 all.extend(reqs);
4294
4295 append_subagent_lines(&subagents, "a1", 2..3);
4297 append_subagent_lines(&subagents, "b2", 1..2);
4298 let partial = subagent_line("b2", 2);
4299 let (head, tail) = partial.split_at(10);
4300 append_raw(&subagents.join("agent-b2.jsonl"), head);
4301 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4302 assert_eq!(reqs.len(), 2);
4303 all.extend(reqs);
4304
4305 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4307 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4308 assert_eq!(reqs.len(), 1);
4309 all.extend(reqs);
4310
4311 assert!(sweep(vec![], &main, &session_dir, &pending)
4313 .await
4314 .is_empty());
4315 assert!(!pending.exists(), "nothing may have failed and been queued");
4316
4317 assert_one_file_per_request(&subagents, &all);
4318 let mut sent: Vec<(String, u64)> = all
4319 .iter()
4320 .flat_map(part_lines)
4321 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4322 .collect();
4323 sent.sort();
4324 let expected: Vec<(String, u64)> = [
4325 ("a1", 0),
4326 ("a1", 1),
4327 ("a1", 2),
4328 ("b2", 0),
4329 ("b2", 1),
4330 ("b2", 2),
4331 ]
4332 .into_iter()
4333 .map(|(a, n)| (a.to_string(), n))
4334 .collect();
4335 assert_eq!(sent, expected, "each line exactly once");
4336 }
4337
4338 #[tokio::test]
4339 async fn a_session_without_subagents_sends_nothing_extra() {
4340 let dir = tempfile::tempdir().unwrap();
4341 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4342 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4343 let session_dir = dir.path().join("tv-session");
4344 fs::create_dir_all(&session_dir).unwrap();
4345 let pending = session_dir.join("pending.jsonl");
4346
4347 assert!(sweep(vec![], &main, &session_dir, &pending)
4348 .await
4349 .is_empty());
4350 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4351 }
4352
4353 #[tokio::test]
4358 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4359 let dir = tempfile::tempdir().unwrap();
4360 let (main, subagents, session_dir) = claude_session(dir.path());
4361 let pending = session_dir.join("pending.jsonl");
4362 append_subagent_lines(&subagents, "a1", 0..2);
4363 append_subagent_lines(&subagents, "b2", 0..1);
4364
4365 let error =
4366 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4367 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4368 assert_eq!(failed.len(), 1);
4369 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4370 .unwrap()
4371 .iter()
4372 .map(|j| serde_json::from_str(j).unwrap())
4373 .collect();
4374 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4375
4376 let resent = sweep(
4377 vec![ok_stream_response(), ok_stream_response()],
4378 &main,
4379 &session_dir,
4380 &pending,
4381 )
4382 .await;
4383 assert_one_file_per_request(&subagents, &resent);
4384 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4385 assert_eq!(
4386 resent.iter().map(key).collect::<Vec<_>>(),
4387 queued.iter().map(key).collect::<Vec<_>>()
4388 );
4389 assert!(sweep(vec![], &main, &session_dir, &pending)
4390 .await
4391 .is_empty());
4392 }
4393
4394 #[tokio::test]
4397 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
4398 let dir = tempfile::tempdir().unwrap();
4399 let (main, subagents, session_dir) = claude_session(dir.path());
4400 let pending = session_dir.join("pending.jsonl");
4401 append_subagent_lines(&subagents, "a1", 0..2);
4402 append_subagent_lines(&subagents, "b2", 0..1);
4403 let a1_offset =
4404 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4405 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4406
4407 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4408 assert_eq!(reqs.len(), 1);
4409 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
4410 assert!(!a1_offset.exists());
4411
4412 drop(held);
4413 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4414 assert_eq!(reqs.len(), 1);
4415 assert_eq!(part_lines(&reqs[0]).len(), 2);
4416 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
4417 }
4418
4419 #[tokio::test]
4422 async fn a_final_hook_waits_for_a_busy_subagent_file() {
4423 let dir = tempfile::tempdir().unwrap();
4424 let (main, subagents, session_dir) = claude_session(dir.path());
4425 let pending = session_dir.join("pending.jsonl");
4426 append_subagent_lines(&subagents, "a1", 0..2);
4427 let a1_offset =
4428 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4429 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4430 let release = thread::spawn(move || {
4431 thread::sleep(Duration::from_millis(300));
4432 drop(held);
4433 });
4434
4435 let reqs = sweep_waiting(
4436 vec![ok_stream_response()],
4437 &main,
4438 &session_dir,
4439 &pending,
4440 Some(Instant::now() + Duration::from_secs(10)),
4441 )
4442 .await;
4443 release.join().unwrap();
4444 assert_eq!(reqs.len(), 1);
4445 assert_eq!(part_lines(&reqs[0]).len(), 2);
4446 }
4447
4448 #[tokio::test]
4452 async fn a_large_subagent_batch_is_split_within_its_file() {
4453 let dir = tempfile::tempdir().unwrap();
4454 let (main, subagents, session_dir) = claude_session(dir.path());
4455 let pending = session_dir.join("pending.jsonl");
4456 let big = subagents.join("agent-a1.jsonl");
4457 for n in 0..300 {
4458 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
4459 append_raw(&big, &format!("{line}\n"));
4460 }
4461 append_subagent_lines(&subagents, "b2", 0..1);
4462
4463 let scratch = dir.path().join("scratch-offset");
4464 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
4465 let unsplit = StreamEventRequest {
4466 transcript_lines: Some(lines.clone()),
4467 transcript_offset: Some(start),
4468 ..transcript_template(&sample_stream_event_request())
4469 };
4470 let a1_parts = split_into_parts(unsplit).len();
4471 assert!(a1_parts > 1, "the batch must exceed the cap");
4472
4473 let reqs = sweep(
4474 vec![ok_stream_response(); a1_parts + 1],
4475 &main,
4476 &session_dir,
4477 &pending,
4478 )
4479 .await;
4480 assert!(!pending.exists());
4481 let (a1, b2) = reqs.split_at(a1_parts);
4482 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
4483 assert_eq!(
4484 chunk_indexes(a1),
4485 lines
4486 .into_iter()
4487 .enumerate()
4488 .map(|(i, l)| (start + i as i64, l))
4489 .collect::<Vec<_>>()
4490 );
4491 assert_eq!(b2.len(), 1);
4492 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
4493 assert_eq!(b2[0].transcript_offset, Some(0));
4494 }
4495}