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> {
1114 lines.iter().find_map(|line| {
1115 let msg = line.get("message")?;
1116 if line.get("type").and_then(|v| v.as_str()) == Some("amp_message") {
1117 return msg
1118 .get("content")?
1119 .as_array()?
1120 .iter()
1121 .find(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result"))
1122 .map(|b| b.get("status").and_then(|v| v.as_str()) == Some("error"));
1123 }
1124 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1125 Some(
1126 msg.get("isError")
1127 .and_then(|v| v.as_bool())
1128 .unwrap_or(false),
1129 )
1130 } else {
1131 None
1132 }
1133 })
1134}
1135
1136pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1140 req.tool = Some(agent.tool_name().to_string());
1141 req.protocol_version = agent.protocol_version() as u32;
1142}
1143
1144const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1150
1151pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1156
1157const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1164
1165#[allow(clippy::too_many_arguments)]
1173async fn deliver_parts(
1174 client: &crate::api_client::ApiClient,
1175 attribution: &Attribution,
1176 force: AttributionForce,
1177 parts: Vec<StreamEventRequest>,
1178 pending_path: &Path,
1179 mut send_failed: bool,
1180 deadline: std::time::Instant,
1181 warned: &mut bool,
1182) -> Result<bool, Box<dyn std::error::Error>> {
1183 let mut all_accepted = true;
1184 for part in parts {
1185 send_failed = send_failed || std::time::Instant::now() >= deadline;
1186 if !send_failed {
1187 let send = send_stream_event(client, attribution, force, &part, warned);
1188 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1189 Ok(Ok(_)) => continue,
1190 Ok(Err(_)) | Err(_) => send_failed = true,
1191 }
1192 }
1193 all_accepted = false;
1194 append_pending(pending_path, &serde_json::to_string(&part)?)?;
1195 }
1196 Ok(all_accepted)
1197}
1198
1199pub async fn run_stream(
1200 event_type: &str,
1201 agent: crate::agent::Agent,
1202) -> Result<(), Box<dyn std::error::Error>> {
1203 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1205 let mut input = String::new();
1206 io::stdin().read_to_string(&mut input)?;
1207 let hook_event = parse_hook_event(&input)?;
1208
1209 let hook_cwd = Path::new(&hook_event.cwd);
1225 let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1226 if resolved.source == crate::paths::ProjectRootSource::Fallback {
1227 eprintln!(
1232 "tracevault: warning: could not resolve a git project root from {}; \
1233 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1234 that it runs inside the repository to keep sessions under the repo root.",
1235 hook_cwd.display()
1236 );
1237 }
1238 let project_root = resolved.root;
1239
1240 fs::create_dir_all(&session_dir)?;
1242
1243 let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
1249
1250 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1255 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1256
1257 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1261 if let Some(records) = &hook_event.transcript_records {
1266 let _ = record_inline_tool_calls(&session_dir, records);
1267 }
1268
1269 let target = SessionTarget {
1270 project_root,
1271 session_dir,
1272 worktree_top,
1273 };
1274 stream_event(
1275 hook_event,
1276 event_type,
1277 agent,
1278 &target,
1279 deadline,
1280 Sender::Hook,
1281 )
1282 .await?;
1283
1284 let response = HookResponse::allow();
1286 println!("{}", serde_json::to_string(&response)?);
1287
1288 Ok(())
1289}
1290
1291pub fn stream_event_type(event_type: &str) -> StreamEventType {
1293 match event_type {
1294 "notification" => StreamEventType::SessionStart,
1295 "stop" => StreamEventType::SessionEnd,
1297 "session-end" => StreamEventType::Transcript,
1301 _ => StreamEventType::ToolUse,
1302 }
1303}
1304
1305pub(crate) struct SessionTarget {
1309 pub project_root: std::path::PathBuf,
1310 pub session_dir: std::path::PathBuf,
1312 pub worktree_top: String,
1314}
1315
1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1318pub(crate) enum Sender {
1319 Hook,
1322 CatchUp,
1327}
1328
1329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1331pub(crate) enum Sent {
1332 Accepted,
1334 Queued,
1336 Skipped,
1339}
1340
1341pub(crate) async fn stream_event(
1345 mut hook_event: tracevault_protocol::hooks::HookEvent,
1346 event_type: &str,
1347 agent: crate::agent::Agent,
1348 target: &SessionTarget,
1349 deadline: std::time::Instant,
1350 sender: Sender,
1351) -> Result<Sent, Box<dyn std::error::Error>> {
1352 let SessionTarget {
1353 project_root,
1354 session_dir,
1355 worktree_top,
1356 } = target;
1357 let hook_cwd = Path::new(&hook_event.cwd);
1358
1359 let event_uuid = uuid::Uuid::now_v7();
1364
1365 let transcript_path = Path::new(&hook_event.transcript_path);
1367 let offset_path = session_dir.join(".stream_offset");
1368 let sends_main = event_type != "subagent-stop";
1375 let (transcript_lines, start_offset, new_offset) = if sends_main {
1376 read_new_transcript_lines(transcript_path, &offset_path)?
1377 } else {
1378 (vec![], 0, 0)
1379 };
1380
1381 let is_inline = hook_event.transcript_records.is_some();
1398 let (transcript_lines, start_offset, new_offset) = if is_inline {
1399 let prior_offset: i64 = if offset_path.exists() {
1406 let content = fs::read_to_string(&offset_path)?;
1407 content
1408 .trim()
1409 .parse::<i64>()
1410 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1411 .max(0)
1412 } else {
1413 0
1414 };
1415 resolve_transcript_source(
1419 hook_event.transcript_records.take(),
1420 prior_offset,
1421 (transcript_lines, start_offset, new_offset),
1422 )
1423 } else {
1424 (transcript_lines, start_offset, new_offset)
1425 };
1426 let stream_event_type = stream_event_type(event_type);
1428
1429 let tool_is_error = hook_event
1434 .tool_use_id
1435 .as_deref()
1436 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1437 .or_else(|| inline_tool_is_error(&transcript_lines));
1438
1439 let config = crate::config::TracevaultConfig::try_load(project_root);
1449 let repo_uc = config
1453 .as_ref()
1454 .ok()
1455 .and_then(|opt| opt.as_ref())
1456 .and_then(|c| c.user_context.clone());
1457 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1458
1459 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1465 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1466
1467 let mut req = StreamEventRequest {
1468 protocol_version: 1,
1469 tool: Some("claude-code".to_string()),
1470 event_type: stream_event_type,
1471 session_id: hook_event.session_id.clone(),
1472 timestamp: chrono::Utc::now(),
1473 hook_event_name: Some(hook_event.hook_event_name.clone()),
1474 tool_name: hook_event.tool_name.clone(),
1475 tool_use_id: hook_event.tool_use_id.clone(),
1476 tool_input: hook_event.tool_input.clone(),
1477 tool_response: hook_event.tool_response.clone(),
1478 tool_is_error,
1479 event_index: None,
1480 event_uuid: Some(event_uuid),
1481 transcript_lines: None,
1482 transcript_offset: Some(start_offset),
1483 model: None,
1484 cwd: Some(hook_event.cwd.clone()),
1485 final_stats: None,
1486 flow_id: ctx_flow_id,
1487 labels: ctx_labels,
1488 params: ctx_params,
1489 billing_mode: (sender == Sender::Hook)
1490 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1491 };
1492
1493 stamp_agent(&mut req, agent);
1494 let subagent_template = transcript_template(&req);
1496 if !transcript_lines.is_empty() {
1497 req.transcript_lines = Some(transcript_lines);
1498 }
1499
1500 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
1502
1503 if let Err(e) = &config {
1512 return Err(format!("malformed .tracevault/config.toml: {e}").into());
1513 }
1514
1515 let session = crate::session_state::load(&hook_event.session_id);
1520 let bound = config
1521 .as_ref()
1522 .ok()
1523 .and_then(|opt| opt.as_ref())
1524 .and_then(crate::resolution::binding_from_config);
1525 let user_default = crate::user_default::load();
1526 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
1527 let client = server_url
1532 .as_deref()
1533 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1534 if binding.is_none() {
1535 if let Some(client) = &client {
1536 let auto =
1537 crate::auto_bind::bind_session(&hook_event.session_id, hook_cwd, client, deadline)
1538 .await;
1539 if let Some(notice) = auto.notice {
1540 eprintln!("{notice}");
1541 }
1542 binding = auto.binding;
1543 }
1544 }
1545 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1555 let capture_pid = capture_binding
1556 .as_ref()
1557 .and_then(crate::resolution::capture_project_id);
1558 let force = attribution_force(capture_binding.as_ref());
1565
1566 let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1574 return Ok(Sent::Skipped);
1575 };
1576 match sender {
1580 Sender::Hook => {
1581 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
1582 }
1583 Sender::CatchUp => {
1584 let meta = session_metadata(session_dir);
1585 if !catch_up_may_send(meta.get("attribution"), &attribution) {
1586 return Ok(Sent::Skipped);
1587 }
1588 }
1589 }
1590
1591 let client = client.ok_or("server_url not configured")?;
1593
1594 let pending_path = pending_path_for(session_dir, &attribution);
1596 let pending_events = drain_pending(&pending_path)?;
1597
1598 let mut send_failed = false;
1599 let mut warned = false;
1603
1604 for (i, pending_json) in pending_events.iter().enumerate() {
1608 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1609 if std::time::Instant::now() >= deadline
1613 || !matches!(
1614 tokio::time::timeout_at(
1615 (deadline + IN_FLIGHT_GRACE).into(),
1616 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1617 )
1618 .await,
1619 Ok(Ok(_))
1620 )
1621 {
1622 for evt in &pending_events[i..] {
1629 append_pending(&pending_path, evt)?;
1630 }
1631 send_failed = true;
1632 break;
1633 }
1634 }
1635 }
1636
1637 let sends_event = sends_main
1642 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
1643 let all_accepted = if sends_event {
1644 deliver_parts(
1645 &client,
1646 &attribution,
1647 force,
1648 split_into_parts(req),
1649 &pending_path,
1650 send_failed,
1651 deadline,
1652 &mut warned,
1653 )
1654 .await?
1655 } else {
1656 true
1657 };
1658 if sends_main && (all_accepted || is_inline) {
1671 crate::subagents::write_offset(&offset_path, new_offset)?;
1672 }
1673
1674 if sender == Sender::Hook && agent == crate::agent::Agent::ClaudeCode {
1679 deliver_subagent_transcripts(
1680 &client,
1681 &attribution,
1682 force,
1683 &subagent_template,
1684 transcript_path,
1685 session_dir,
1686 &pending_path,
1687 send_failed || !all_accepted,
1688 deadline,
1689 matches!(event_type, "stop" | "subagent-stop" | "session-end")
1690 .then(|| deadline + FINAL_LOCK_WAIT),
1691 &mut warned,
1692 )
1693 .await?;
1694 }
1695
1696 Ok(if !send_failed && all_accepted {
1697 Sent::Accepted
1698 } else {
1699 Sent::Queued
1700 })
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705 use super::*;
1706 use crate::api_client::AttributionMode;
1707 use crate::config::UserContext;
1708 use crate::context::{Context, EffectiveContext};
1709 use std::collections::BTreeMap;
1710
1711 #[test]
1712 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
1713 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
1714 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
1715 project,
1716 };
1717 let a = uuid::Uuid::from_u128(0xa);
1718 let b = uuid::Uuid::from_u128(0xb);
1719 let only = |project_id| Attribution::ProjectOnly { project_id };
1720
1721 let recorded = attribution_record(&repo(Some(a)));
1722 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
1723 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
1724 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
1725 let recorded = attribution_record(&only(a));
1726 assert!(catch_up_may_send(Some(&recorded), &only(a)));
1727 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
1728 assert!(catch_up_may_send(None, &repo(Some(b))));
1731 assert!(!catch_up_may_send(None, &only(a)));
1732 }
1733
1734 #[test]
1735 fn record_metadata_keeps_the_other_keys() {
1736 let dir = tempfile::tempdir().unwrap();
1737 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
1738 record_metadata(
1739 dir.path(),
1740 "attribution",
1741 serde_json::json!({"repo_id": "r"}),
1742 )
1743 .unwrap();
1744 let meta = session_metadata(dir.path());
1745 assert_eq!(meta["transcript_path"], "/t.jsonl");
1746 assert_eq!(meta["attribution"]["repo_id"], "r");
1747 }
1748
1749 #[test]
1750 fn hook_events_map_to_server_events() {
1751 assert_eq!(
1752 stream_event_type("notification"),
1753 StreamEventType::SessionStart
1754 );
1755 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
1758 assert_eq!(
1759 stream_event_type("session-end"),
1760 StreamEventType::Transcript
1761 );
1762 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
1763 assert_eq!(
1764 stream_event_type(event),
1765 StreamEventType::ToolUse,
1766 "{event}"
1767 );
1768 }
1769 }
1770
1771 #[test]
1774 fn disabled_user_context_resolves_to_none() {
1775 assert!(UserContext::Toggle(false).resolve().is_none());
1779 }
1780
1781 #[test]
1782 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1783 let dir = tempfile::tempdir().unwrap();
1787 let effective = Context::effective(dir.path(), None);
1788 assert_eq!(effective, EffectiveContext::default());
1789 }
1790
1791 #[test]
1794 fn apply_context_stamps_all_fields() {
1795 let dir = tempfile::tempdir().unwrap();
1796 let mut params = BTreeMap::new();
1797 params.insert("env".to_string(), "prod".to_string());
1798 params.insert("region".to_string(), "eu-west-1".to_string());
1799
1800 let ctx = EffectiveContext {
1801 flow_id: Some("flow-xyz".to_string()),
1802 labels: vec!["backend".to_string(), "urgent".to_string()],
1803 params,
1804 };
1805
1806 let (flow_id, labels, params_out) = apply_context(ctx);
1807
1808 assert_eq!(flow_id, Some("flow-xyz".to_string()));
1809 assert_eq!(
1810 labels,
1811 Some(vec!["backend".to_string(), "urgent".to_string()])
1812 );
1813 let p = params_out.expect("params should be Some");
1814 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1815 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1816
1817 let written = Context {
1820 flow_id: Some("flow-xyz".to_string()),
1821 labels: vec!["backend".to_string(), "urgent".to_string()],
1822 params: {
1823 let mut m = BTreeMap::new();
1824 m.insert("env".to_string(), Some("prod".to_string()));
1825 m.insert("region".to_string(), Some("eu-west-1".to_string()));
1826 m
1827 },
1828 };
1829 let ctx_path = dir.path().join(".tracevault").join("context.json");
1830 written.save_to(&ctx_path).unwrap();
1831 let loaded = Context::load_from(&ctx_path);
1832 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1833 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1834 assert!(labels2.is_some());
1835 assert!(params2.is_some());
1836 }
1837
1838 #[test]
1841 fn apply_context_missing_file_all_none() {
1842 let dir = tempfile::tempdir().unwrap();
1843 let missing_path = dir.path().join(".tracevault").join("context.json");
1844 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1846 assert!(flow_id.is_none(), "flow_id should be None");
1847 assert!(labels.is_none(), "labels should be None");
1848 assert!(params.is_none(), "params should be None");
1849 }
1850
1851 #[test]
1854 fn apply_context_empty_collections_are_none() {
1855 let ctx = EffectiveContext {
1856 flow_id: None,
1857 labels: vec![],
1858 params: BTreeMap::new(),
1859 };
1860 let (flow_id, labels, params) = apply_context(ctx);
1861 assert!(flow_id.is_none());
1862 assert!(
1863 labels.is_none(),
1864 "empty labels should be None, not Some([])"
1865 );
1866 assert!(
1867 params.is_none(),
1868 "empty params should be None, not Some({{}})"
1869 );
1870 }
1871
1872 #[test]
1875 fn apply_context_flow_id_only() {
1876 let ctx = EffectiveContext {
1877 flow_id: Some("my-flow".to_string()),
1878 labels: vec![],
1879 params: BTreeMap::new(),
1880 };
1881 let (flow_id, labels, params) = apply_context(ctx);
1882 assert_eq!(flow_id, Some("my-flow".to_string()));
1883 assert!(labels.is_none());
1884 assert!(params.is_none());
1885 }
1886
1887 use crate::test_helpers::{add_worktree, init_git_repo};
1894
1895 #[test]
1898 fn resolve_session_paths_primary_checkout() {
1899 let tmp = tempfile::tempdir().unwrap();
1900 let repo = tmp.path().join("repo");
1901 std::fs::create_dir_all(&repo).unwrap();
1902 init_git_repo(&repo);
1903 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1905
1906 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1907 let project_root = resolved.root;
1908
1909 assert_eq!(
1910 project_root.canonicalize().unwrap(),
1911 repo.canonicalize().unwrap(),
1912 "primary checkout: project_root must be repo root"
1913 );
1914 assert_eq!(
1915 session_dir.canonicalize().unwrap_or(session_dir.clone()),
1916 repo.join(".tracevault")
1917 .join("sessions")
1918 .join("sess-primary-123"),
1919 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1920 );
1921 assert!(
1923 session_dir.starts_with(&repo),
1924 "session_dir must be under the primary repo root"
1925 );
1926 }
1927
1928 #[test]
1932 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1933 let tmp = tempfile::tempdir().unwrap();
1934 let repo = tmp.path().join("repo");
1935 let wt = tmp.path().join("sibling-wt");
1937
1938 std::fs::create_dir_all(&repo).unwrap();
1939 init_git_repo(&repo);
1940 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1942 add_worktree(&repo, &wt);
1943
1944 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1945 let project_root = resolved.root;
1946
1947 assert_eq!(
1949 project_root.canonicalize().unwrap(),
1950 repo.canonicalize().unwrap(),
1951 "sibling worktree: project_root must be primary repo root (not worktree dir)"
1952 );
1953 assert!(
1955 session_dir.starts_with(&repo),
1956 "sibling worktree: session_dir must be under the PRIMARY repo root"
1957 );
1958 assert!(
1959 !session_dir.starts_with(&wt),
1960 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1961 );
1962 assert!(
1963 session_dir.ends_with(
1964 std::path::Path::new(".tracevault")
1965 .join("sessions")
1966 .join("sess-sibling-456")
1967 ),
1968 "session_dir must end with .tracevault/sessions/<session_id>"
1969 );
1970 }
1971
1972 #[test]
1975 fn resolve_session_paths_non_git_fallback() {
1976 let tmp = tempfile::tempdir().unwrap();
1977 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1979 let project_root = resolved.root;
1980
1981 assert_eq!(
1982 project_root,
1983 tmp.path(),
1984 "non-git: project_root must fall back to hook_cwd"
1985 );
1986 assert_eq!(
1987 session_dir,
1988 tmp.path()
1989 .join(".tracevault")
1990 .join("sessions")
1991 .join("sess-fallback-789"),
1992 "non-git: session_dir must be relative to the fallback root"
1993 );
1994 }
1995
1996 #[test]
2001 fn origin_marker_written_in_session_dir() {
2002 let tmp = tempfile::tempdir().unwrap();
2003 let repo = tmp.path().join("repo");
2004 std::fs::create_dir_all(&repo).unwrap();
2005 init_git_repo(&repo);
2006
2007 let session_dir = repo
2008 .join(".tracevault")
2009 .join("sessions")
2010 .join("test-sess-001");
2011 std::fs::create_dir_all(&session_dir).unwrap();
2012
2013 let hook_cwd = &repo;
2014 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2015 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2016
2017 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2018 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2019 assert_eq!(
2020 origin_content.trim(),
2021 expected.as_str(),
2022 "origin marker must contain the canonicalized worktree toplevel"
2023 );
2024 }
2025
2026 fn metadata(session_dir: &Path) -> serde_json::Value {
2027 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2028 .unwrap()
2029 }
2030
2031 #[test]
2032 fn record_transcript_path_writes_metadata_for_check() {
2033 let tmp = tempfile::tempdir().unwrap();
2034 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2035 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2036 }
2037
2038 #[test]
2039 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2040 let tmp = tempfile::tempdir().unwrap();
2041 std::fs::write(
2042 tmp.path().join("metadata.json"),
2043 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2044 )
2045 .unwrap();
2046 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2047 let m = metadata(tmp.path());
2048 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2049 assert_eq!(m["model"], "m");
2050 let leftovers = std::fs::read_dir(tmp.path())
2051 .unwrap()
2052 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2053 .count();
2054 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2055 }
2056
2057 #[test]
2058 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2059 let tmp = tempfile::tempdir().unwrap();
2060 record_transcript_path(tmp.path(), "").unwrap();
2061 assert!(!tmp.path().join("metadata.json").exists());
2062
2063 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2064 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2065 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2066 }
2067
2068 use crate::session_state::{RepoBinding, SessionState};
2071
2072 fn binding(id: &str) -> RepoBinding {
2073 RepoBinding {
2074 repo_id: id.into(),
2075 git_url: None,
2076 remote_id: None,
2077 codebase_name: None,
2078 updated_at: "t".into(),
2079 }
2080 }
2081
2082 #[test]
2085 fn resolve_stream_binding_uses_session_active_when_unbound() {
2086 let session = SessionState {
2087 active: Some(binding("session-repo")),
2088 subagents: HashMap::new(),
2089 ..Default::default()
2090 };
2091 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2092 assert_eq!(got.unwrap().repo_id, "session-repo");
2093 }
2094
2095 #[test]
2098 fn resolve_stream_binding_falls_back_to_bound_config() {
2099 let session = SessionState::default();
2100 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2101 assert_eq!(got.unwrap().repo_id, "bound-repo");
2102 }
2103
2104 #[test]
2107 fn resolve_stream_binding_none_when_nothing_resolves() {
2108 let session = SessionState::default();
2109 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2110 assert!(got.is_none());
2111 }
2112
2113 #[test]
2116 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2117 let session = SessionState {
2118 active: Some(binding("session-repo")),
2119 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2120 ..Default::default()
2121 };
2122 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2123 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2124 }
2125
2126 #[test]
2130 fn resolve_stream_binding_falls_back_to_user_default() {
2131 let session = SessionState::default();
2132 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2133 assert_eq!(got.unwrap().repo_id, "userdef");
2134 }
2135
2136 #[test]
2139 fn resolve_stream_binding_prefers_bound_over_user_default() {
2140 let session = SessionState::default();
2141 let got = resolve_stream_binding(
2142 &session,
2143 "/wt/x",
2144 Some(binding("bound")),
2145 Some(binding("userdef")),
2146 );
2147 assert_eq!(got.unwrap().repo_id, "bound");
2148 }
2149
2150 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2153 crate::session_state::RepoBinding {
2154 repo_id: repo_id.into(),
2155 git_url: None,
2156 remote_id: None,
2157 codebase_name: None,
2158 updated_at: String::new(),
2159 }
2160 }
2161
2162 #[test]
2166 fn attribution_falls_back_to_project_when_no_repo_binds() {
2167 let pid = uuid::Uuid::new_v4();
2168 assert_eq!(
2169 attribution_for(None, Some(pid)),
2170 Some(Attribution::ProjectOnly { project_id: pid })
2171 );
2172 }
2173
2174 #[test]
2176 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2177 assert_eq!(attribution_for(None, None), None);
2178 }
2179
2180 #[test]
2183 fn attribution_uses_repo_with_no_project_overlay() {
2184 let repo = uuid::Uuid::new_v4().to_string();
2185 let b = binding_with(&repo);
2186 assert_eq!(
2187 attribution_for(Some(&b), None),
2188 Some(Attribution::Repo {
2189 repo_id: repo,
2190 project: None
2191 })
2192 );
2193 }
2194
2195 #[test]
2198 fn attribution_overlays_project_on_repo() {
2199 let repo = uuid::Uuid::new_v4().to_string();
2200 let pid = uuid::Uuid::new_v4();
2201 let b = binding_with(&repo);
2202 assert_eq!(
2203 attribution_for(Some(&b), Some(pid)),
2204 Some(Attribution::Repo {
2205 repo_id: repo,
2206 project: Some(pid)
2207 })
2208 );
2209 }
2210
2211 #[test]
2214 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2215 let pid = uuid::Uuid::new_v4();
2216 let b = binding_with("../../escape");
2217 assert_eq!(
2218 attribution_for(Some(&b), Some(pid)),
2219 Some(Attribution::ProjectOnly { project_id: pid })
2220 );
2221 }
2222
2223 #[test]
2226 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2227 let b = binding_with("../../escape");
2228 assert_eq!(attribution_for(Some(&b), None), None);
2229 }
2230
2231 #[test]
2236 fn pending_file_name_for_a_repo_is_unchanged() {
2237 let repo = uuid::Uuid::new_v4().to_string();
2238 assert_eq!(
2239 Attribution::Repo {
2240 repo_id: repo.clone(),
2241 project: Some(uuid::Uuid::new_v4())
2242 }
2243 .pending_file_name(),
2244 format!("pending-{repo}.jsonl")
2245 );
2246 }
2247
2248 #[test]
2251 fn pending_file_name_for_a_project_is_distinct() {
2252 let pid = uuid::Uuid::new_v4();
2253 assert_eq!(
2254 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2255 format!("pending-project-{pid}.jsonl")
2256 );
2257 }
2258
2259 #[test]
2262 fn binding_repo_id_is_valid_accepts_real_uuid() {
2263 assert!(binding_repo_id_is_valid(
2264 "550e8400-e29b-41d4-a716-446655440000"
2265 ));
2266 }
2267
2268 #[test]
2269 fn binding_repo_id_is_valid_rejects_path_traversal() {
2270 assert!(!binding_repo_id_is_valid("../evil"));
2271 }
2272
2273 #[test]
2274 fn binding_repo_id_is_valid_rejects_empty() {
2275 assert!(!binding_repo_id_is_valid(""));
2276 }
2277
2278 #[test]
2279 fn binding_repo_id_is_valid_rejects_non_uuid() {
2280 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2281 }
2282
2283 #[test]
2286 fn stamp_agent_sets_tool_and_version() {
2287 use crate::agent::Agent;
2288 let mut req = StreamEventRequest {
2289 protocol_version: 1,
2290 tool: Some("claude-code".to_string()),
2291 event_type: StreamEventType::ToolUse,
2292 session_id: "s".into(),
2293 timestamp: chrono::Utc::now(),
2294 hook_event_name: None,
2295 tool_name: None,
2296 tool_use_id: None,
2297 tool_input: None,
2298 tool_response: None,
2299 tool_is_error: None,
2300 event_index: None,
2301 event_uuid: None,
2302 transcript_lines: None,
2303 transcript_offset: None,
2304 model: None,
2305 cwd: None,
2306 final_stats: None,
2307 flow_id: None,
2308 labels: None,
2309 params: None,
2310 billing_mode: None,
2311 };
2312 stamp_agent(&mut req, Agent::Codex);
2313 assert_eq!(req.tool.as_deref(), Some("codex"));
2314 assert_eq!(req.protocol_version, 2);
2315
2316 stamp_agent(&mut req, Agent::ClaudeCode);
2317 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2318 assert_eq!(req.protocol_version, 1);
2319 }
2320
2321 fn repo_attr(repo_id: &str) -> Attribution {
2324 Attribution::Repo {
2325 repo_id: repo_id.into(),
2326 project: None,
2327 }
2328 }
2329
2330 #[test]
2331 fn pending_path_is_repo_scoped() {
2332 let dir = std::path::Path::new("/tmp/sess");
2333 assert_eq!(
2334 pending_path_for(dir, &repo_attr("repo-a")),
2335 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2336 );
2337 assert_ne!(
2338 pending_path_for(dir, &repo_attr("repo-a")),
2339 pending_path_for(dir, &repo_attr("repo-b")),
2340 );
2341 }
2342
2343 #[test]
2346 fn pending_path_for_a_project_never_collides_with_a_repo() {
2347 let dir = std::path::Path::new("/tmp/sess");
2348 let pid = uuid::Uuid::from_u128(9);
2349 assert_eq!(
2350 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2351 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2352 );
2353 assert_ne!(
2354 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2355 pending_path_for(dir, &repo_attr(&pid.to_string())),
2356 );
2357 }
2358
2359 #[test]
2362 fn read_new_transcript_lines_empty_path_is_noop() {
2363 let dir = tempfile::tempdir().unwrap();
2367 let offset_path = dir.path().join(".stream_offset");
2368 let (lines, start_offset, end_offset) =
2369 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2370 assert!(
2371 lines.is_empty(),
2372 "empty path must yield no transcript lines"
2373 );
2374 assert_eq!(start_offset, 0);
2375 assert_eq!(end_offset, 0);
2376 }
2377
2378 #[test]
2382 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2383 let dir = tempfile::tempdir().unwrap();
2384 let transcript_path = dir.path().join("transcript.jsonl");
2385 let offset_path = dir.path().join(".stream_offset");
2386
2387 fs::write(
2388 &transcript_path,
2389 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2390 )
2391 .unwrap();
2392
2393 let (lines, start_offset, end_offset) =
2394 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2395 assert_eq!(lines.len(), 2);
2396 assert_eq!(start_offset, 0, "first read starts at byte 0");
2397 assert!(end_offset > 0);
2398
2399 fs::write(&offset_path, end_offset.to_string()).unwrap();
2400
2401 let mut f = OpenOptions::new()
2402 .append(true)
2403 .open(&transcript_path)
2404 .unwrap();
2405 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2406 drop(f);
2407
2408 let (lines2, start_offset2, end_offset2) =
2409 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2410 assert_eq!(lines2.len(), 1);
2411 assert_eq!(
2412 start_offset2, end_offset,
2413 "second read's start_offset must equal the first read's persisted end_offset"
2414 );
2415 assert!(end_offset2 > start_offset2);
2416 }
2417
2418 #[tokio::test]
2436 async fn capture_project_precedence_local_only() {
2437 use crate::session_state::{ProjectBinding, SessionState};
2438 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2439 let tmp = tempfile::tempdir().unwrap();
2440 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2441 _guard.set("XDG_CONFIG_HOME", tmp.path());
2442 _guard.set("HOME", tmp.path());
2443 _guard.remove("TRACEVAULT_PROJECT");
2444
2445 let pb = |id: &str| ProjectBinding {
2446 project_id: id.into(),
2447 project_name: "n".into(),
2448 updated_at: "".into(),
2449 forced_until: None,
2450 };
2451 let u = uuid::Uuid::from_u128;
2452 let s = SessionState {
2454 active_project: Some(pb(&u(2).to_string())),
2455 ..Default::default()
2456 };
2457 assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
2458 let mut s = s;
2460 s.subagent_projects
2461 .insert("/wt".into(), pb(&u(1).to_string()));
2462 assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
2463 assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
2465 assert_eq!(capture_project(&SessionState::default(), None), None);
2467 let bad = SessionState {
2469 active_project: Some(pb("not-a-uuid")),
2470 ..Default::default()
2471 };
2472 assert_eq!(capture_project(&bad, None), None);
2473 let path = crate::user_project_default::default_project_path().unwrap();
2475 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2476 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2477 assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
2478 }
2479
2480 #[test]
2491 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2492 use crate::session_state::{ProjectBinding, SessionState};
2493 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2494 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2495 _guard.remove("TRACEVAULT_PROJECT");
2496 let pid = uuid::Uuid::from_u128(2);
2497 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2498 let s = SessionState {
2499 active_project: Some(ProjectBinding {
2500 project_id: pid.to_string(),
2501 project_name: "n".into(),
2502 updated_at: "".into(),
2503 forced_until: Some(future.clone()),
2504 }),
2505 ..Default::default()
2506 };
2507 let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
2508 assert_eq!(got.forced_until, Some(future));
2509 }
2510
2511 #[test]
2516 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2517 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2521
2522 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2523 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2524
2525 _guard.set("TRACEVAULT_PROJECT", uuid);
2526 let got = env_project_binding().expect("uuid form is honoured");
2527 assert_eq!(got.project_id, uuid);
2528
2529 _guard.set("TRACEVAULT_PROJECT", "my-project");
2530 assert!(
2531 env_project_binding().is_none(),
2532 "a name is ignored on the network-free capture path"
2533 );
2534
2535 _guard.remove("TRACEVAULT_PROJECT");
2536 assert!(env_project_binding().is_none());
2537 }
2538
2539 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2547 crate::session_state::ProjectBinding {
2548 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2549 project_name: "p".into(),
2550 updated_at: chrono::Utc::now().to_rfc3339(),
2551 forced_until: forced_until.map(str::to_string),
2552 }
2553 }
2554
2555 #[test]
2556 fn env_force_is_explicit_and_needs_no_expiry() {
2557 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2558 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2559 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2560
2561 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2562 }
2563
2564 #[test]
2565 fn absent_or_unrecognised_env_is_derived() {
2566 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2567 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2568
2569 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2570 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2571
2572 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2577 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2578 }
2579
2580 #[test]
2586 fn live_binding_force_is_explicit_without_env() {
2587 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2588 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2589 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2590
2591 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2592 let binding = forced_binding(Some(&future));
2593
2594 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2595 }
2596
2597 #[test]
2604 fn lapsed_binding_force_is_derived_without_env() {
2605 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2606 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2607 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2608
2609 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2610 let binding = forced_binding(Some(&past));
2611
2612 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2613 }
2614
2615 #[test]
2620 fn unparseable_forced_until_is_derived() {
2621 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2622 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2623 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2624
2625 let binding = forced_binding(Some("not-a-timestamp"));
2626
2627 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2628 }
2629
2630 #[test]
2637 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2638 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2639 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2640 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2641
2642 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2643 let binding = forced_binding(Some(&past));
2644
2645 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2646 }
2647
2648 #[tokio::test]
2661 async fn session_scoped_force_is_honoured_on_the_wire() {
2662 use crate::session_state::{ProjectBinding, SessionState};
2663
2664 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2665 let tmp = tempfile::tempdir().unwrap();
2666 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2667 _guard.set("XDG_CONFIG_HOME", tmp.path());
2671 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2672 _guard.remove("TRACEVAULT_PROJECT");
2676
2677 let pid = uuid::Uuid::from_u128(321);
2678 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2679 let session = SessionState {
2680 active_project: Some(ProjectBinding {
2681 project_id: pid.to_string(),
2682 project_name: "proj".into(),
2683 updated_at: "".into(),
2684 forced_until: Some(future),
2685 }),
2686 ..Default::default()
2687 };
2688 let capture_binding = capture_binding(&session, None);
2689
2690 let resp = ok_stream_response();
2691 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2692 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2693 let req = sample_stream_event_request();
2694 let mut warned = false;
2695
2696 let got = send_stream_event(
2697 &client,
2698 &Attribution::ProjectOnly { project_id: pid },
2699 attribution_force(capture_binding.as_ref()),
2700 &req,
2701 &mut warned,
2702 )
2703 .await
2704 .expect("send_stream_event must succeed");
2705 assert_eq!(
2706 got.expect("a successful send returns a response").status,
2707 "accepted"
2708 );
2709
2710 let captured = rx
2711 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2712 .expect("no request captured");
2713 assert!(
2714 captured
2715 .to_lowercase()
2716 .contains("x-tracevault-project-attribution: explicit"),
2717 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2718 );
2719 }
2720
2721 #[test]
2730 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2731 use crate::session_state::{ProjectBinding, SessionState};
2732
2733 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2734 let tmp = tempfile::tempdir().unwrap();
2735 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2736 _guard.set("XDG_CONFIG_HOME", tmp.path());
2737 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2738
2739 let project_a = uuid::Uuid::from_u128(1);
2740 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2741 crate::user_project_default::save(&ProjectBinding {
2742 project_id: project_a.to_string(),
2743 project_name: "a".into(),
2744 updated_at: chrono::Utc::now().to_rfc3339(),
2745 forced_until: Some(future),
2746 })
2747 .unwrap();
2748
2749 let project_b = uuid::Uuid::from_u128(2);
2750 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2751
2752 let capture_binding = capture_binding(&SessionState::default(), None);
2753 assert_eq!(
2754 capture_binding.as_ref().map(|b| b.project_id.as_str()),
2755 Some(project_b.to_string()).as_deref(),
2756 "TRACEVAULT_PROJECT must outrank the user-level default"
2757 );
2758
2759 assert_eq!(
2760 attribution_mode(capture_binding.as_ref()),
2761 AttributionMode::Derived,
2762 "a force on the user-default project must not leak onto a DIFFERENT, \
2763 higher-precedence project that never asked to be forced"
2764 );
2765 }
2766
2767 use std::io::BufReader;
2770 use std::net::TcpListener;
2771 use std::sync::mpsc;
2772 use std::thread;
2773 use std::time::{Duration, Instant};
2774
2775 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2780
2781 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2786 let deadline = Instant::now() + ACCEPT_DEADLINE;
2787 loop {
2788 match listener.accept() {
2789 Ok((stream, _)) => {
2790 let _ = stream.set_nonblocking(false);
2795 return Some(stream);
2796 }
2797 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2798 if Instant::now() >= deadline {
2799 return None;
2800 }
2801 thread::sleep(Duration::from_millis(20));
2802 }
2803 Err(_) => return None,
2804 }
2805 }
2806 }
2807
2808 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2812
2813 fn capture_request_and_respond(
2833 stream: std::net::TcpStream,
2834 tx: &mpsc::Sender<String>,
2835 response: &str,
2836 ) {
2837 let mut reader = BufReader::new(stream);
2838 let mut captured = String::new();
2839 let _ = reader.read_line(&mut captured);
2840 loop {
2841 let mut header = String::new();
2842 if reader.read_line(&mut header).unwrap_or(0) == 0 {
2843 break;
2844 }
2845 if header.trim().is_empty() {
2846 break;
2847 }
2848 captured.push_str(&header);
2849 }
2850 let _ = tx.send(captured);
2851 let mut stream = reader.into_inner();
2852 let _ = stream.write_all(response.as_bytes());
2853 let _ = stream.flush();
2854 }
2855
2856 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2861 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2862 listener.set_nonblocking(true).unwrap();
2863 let addr = listener.local_addr().unwrap();
2864 let (tx, rx) = mpsc::channel();
2865 thread::spawn(move || {
2866 if let Some(stream) = accept_with_deadline(&listener) {
2867 capture_request_and_respond(stream, &tx, response);
2868 }
2869 });
2870 (format!("http://{addr}"), rx)
2871 }
2872
2873 fn ok_stream_response() -> String {
2874 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2875 session_db_id: uuid::Uuid::nil(),
2876 event_db_id: Some(uuid::Uuid::nil()),
2877 status: "accepted".to_string(),
2878 })
2879 .unwrap();
2880 format!(
2881 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2882 body.len(),
2883 body
2884 )
2885 }
2886
2887 fn sample_stream_event_request() -> StreamEventRequest {
2888 StreamEventRequest {
2889 protocol_version: 2,
2890 tool: Some("claude-code".to_string()),
2891 event_type: StreamEventType::ToolUse,
2892 session_id: "sess-1".into(),
2893 timestamp: chrono::Utc::now(),
2894 hook_event_name: Some("PostToolUse".into()),
2895 tool_name: None,
2896 tool_use_id: None,
2897 tool_input: None,
2898 tool_response: None,
2899 tool_is_error: None,
2900 event_index: None,
2901 event_uuid: None,
2902 transcript_lines: None,
2903 transcript_offset: None,
2904 model: None,
2905 cwd: None,
2906 final_stats: None,
2907 flow_id: None,
2908 labels: None,
2909 params: None,
2910 billing_mode: None,
2911 }
2912 }
2913
2914 #[tokio::test]
2919 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2920 use crate::session_state::{ProjectBinding, SessionState};
2921
2922 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2926 let tmp = tempfile::tempdir().unwrap();
2927 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2928 _guard.set("XDG_CONFIG_HOME", tmp.path());
2929 _guard.remove("TRACEVAULT_PROJECT");
2934 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2935
2936 let pid = uuid::Uuid::from_u128(99);
2937 let session = SessionState {
2938 active_project: Some(ProjectBinding {
2939 project_id: pid.to_string(),
2940 project_name: "proj".into(),
2941 updated_at: "".into(),
2942 forced_until: None,
2943 }),
2944 ..Default::default()
2945 };
2946 let capture_binding = capture_binding(&session, None);
2947 let capture_pid = capture_binding
2948 .as_ref()
2949 .and_then(crate::resolution::capture_project_id);
2950 assert_eq!(capture_pid, Some(pid));
2951
2952 let resp = ok_stream_response();
2953 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2954 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2955 let req = sample_stream_event_request();
2956
2957 let mut warned = false;
2958 let got = send_stream_event(
2959 &client,
2960 &Attribution::Repo {
2961 repo_id: "11111111-1111-1111-1111-111111111111".into(),
2962 project: capture_pid,
2963 },
2964 attribution_force(capture_binding.as_ref()),
2965 &req,
2966 &mut warned,
2967 )
2968 .await
2969 .expect("send_stream_event must succeed");
2970 assert_eq!(
2971 got.expect("a successful send returns a response").status,
2972 "accepted"
2973 );
2974
2975 let line = rx
2976 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2977 .expect("no request captured");
2978 assert!(
2979 line.starts_with(&format!(
2980 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2981 )),
2982 "an active project binding must route to the project-scoped endpoint, got: {line}"
2983 );
2984 assert!(
2990 line.to_lowercase()
2991 .contains("x-tracevault-project-attribution: derived"),
2992 "got: {line}"
2993 );
2994 }
2995
2996 #[tokio::test]
3001 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
3002 use crate::session_state::SessionState;
3003
3004 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3005 let tmp = tempfile::tempdir().unwrap();
3006 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3007 _guard.set("XDG_CONFIG_HOME", tmp.path());
3012 _guard.remove("TRACEVAULT_PROJECT");
3013
3014 let capture_binding = capture_binding(&SessionState::default(), None);
3015 assert_eq!(capture_binding, None);
3016
3017 let resp = ok_stream_response();
3018 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3019 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3020 let req = sample_stream_event_request();
3021
3022 let mut warned = false;
3023 let got = send_stream_event(
3024 &client,
3025 &Attribution::Repo {
3026 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3027 project: None,
3028 },
3029 attribution_force(capture_binding.as_ref()),
3030 &req,
3031 &mut warned,
3032 )
3033 .await
3034 .expect("send_stream_event must succeed");
3035 assert_eq!(
3036 got.expect("a successful send returns a response").status,
3037 "accepted"
3038 );
3039
3040 let line = rx
3041 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3042 .expect("no request captured");
3043 assert!(
3044 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3045 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3046 );
3047 }
3048
3049 fn spawn_n_capturing_requests(
3060 responses: Vec<&'static str>,
3061 ) -> (String, mpsc::Receiver<String>) {
3062 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3063 listener.set_nonblocking(true).unwrap();
3064 let addr = listener.local_addr().unwrap();
3065 let (tx, rx) = mpsc::channel();
3066 thread::spawn(move || {
3067 for response in responses {
3068 let Some(stream) = accept_with_deadline(&listener) else {
3073 break;
3074 };
3075 capture_request_and_respond(stream, &tx, response);
3076 }
3077 });
3082 (format!("http://{addr}"), rx)
3083 }
3084
3085 #[tokio::test]
3092 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3093 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3094 let resp_400 = format!(
3095 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3096 body_400.len(),
3097 body_400
3098 );
3099 let resp_200 = ok_stream_response();
3100
3101 let (base, rx) = spawn_n_capturing_requests(vec![
3102 Box::leak(resp_400.into_boxed_str()),
3103 Box::leak(resp_200.into_boxed_str()),
3104 ]);
3105 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3106 let req = sample_stream_event_request();
3107 let pid = uuid::Uuid::from_u128(42);
3108
3109 let mut warned = false;
3110 let err = send_stream_event(
3111 &client,
3112 &Attribution::Repo {
3113 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3114 project: Some(pid),
3115 },
3116 attribution_force(None),
3117 &req,
3118 &mut warned,
3119 )
3120 .await
3121 .expect_err("a refused declared project must be an error, not a silent fallback");
3122 assert!(
3123 err.to_string().contains("400"),
3124 "propagated error must reflect the status, got: {err}"
3125 );
3126 assert!(
3127 warned,
3128 "the refusal must be printed (gated on `warned`) so it is visible"
3129 );
3130
3131 let first = rx
3132 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3133 .expect("no first request captured");
3134 assert!(
3135 first.contains(&format!("/projects/{pid}/stream")),
3136 "first request must hit the project-scoped endpoint, got: {first}"
3137 );
3138 assert!(
3139 first.contains("repo_id="),
3140 "first request must carry repo_id, got: {first}"
3141 );
3142
3143 assert!(
3144 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3145 "no second (repo-scoped fallback) request must be sent"
3146 );
3147 }
3148
3149 #[tokio::test]
3152 async fn send_stream_event_errors_on_403_without_fallback() {
3153 let body_403 = "forbidden";
3154 let resp_403 = format!(
3155 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3156 body_403.len(),
3157 body_403
3158 );
3159 let resp_200 = ok_stream_response();
3160
3161 let (base, rx) = spawn_n_capturing_requests(vec![
3162 Box::leak(resp_403.into_boxed_str()),
3163 Box::leak(resp_200.into_boxed_str()),
3164 ]);
3165 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3166 let req = sample_stream_event_request();
3167 let pid = uuid::Uuid::from_u128(43);
3168
3169 let mut warned = false;
3170 let err = send_stream_event(
3171 &client,
3172 &Attribution::Repo {
3173 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3174 project: Some(pid),
3175 },
3176 attribution_force(None),
3177 &req,
3178 &mut warned,
3179 )
3180 .await
3181 .expect_err("a refused declared project must be an error, not a silent fallback");
3182 assert!(
3183 err.to_string().contains("403"),
3184 "propagated error must reflect the status, got: {err}"
3185 );
3186 assert!(
3187 warned,
3188 "the refusal must be printed (gated on `warned`) so it is visible"
3189 );
3190
3191 let first = rx
3192 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3193 .expect("no first request captured");
3194 assert!(
3195 first.contains(&format!("/projects/{pid}/stream")),
3196 "first request must hit the project-scoped endpoint, got: {first}"
3197 );
3198 assert!(
3199 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3200 "no second (repo-scoped fallback) request must be sent"
3201 );
3202 }
3203
3204 #[tokio::test]
3209 async fn refused_error_is_printed_once_per_invocation() {
3210 let body_400 = "not a member";
3211 let resp_400 = || {
3212 format!(
3213 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3214 body_400.len(),
3215 body_400
3216 )
3217 };
3218 let (base, _rx) = spawn_n_capturing_requests(vec![
3219 Box::leak(resp_400().into_boxed_str()),
3220 Box::leak(resp_400().into_boxed_str()),
3221 ]);
3222 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3223 let req = sample_stream_event_request();
3224 let pid = uuid::Uuid::from_u128(44);
3225 let attribution = Attribution::Repo {
3226 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3227 project: Some(pid),
3228 };
3229
3230 let mut warned = false;
3231 assert!(
3232 send_stream_event(
3233 &client,
3234 &attribution,
3235 attribution_force(None),
3236 &req,
3237 &mut warned
3238 )
3239 .await
3240 .is_err(),
3241 "a refused declared project must be an error"
3242 );
3243 assert!(warned, "the flag must be set after the first refusal");
3244
3245 assert!(
3246 send_stream_event(
3247 &client,
3248 &attribution,
3249 attribution_force(None),
3250 &req,
3251 &mut warned
3252 )
3253 .await
3254 .is_err(),
3255 "a second refusal must also be an error"
3256 );
3257 assert!(warned, "the flag stays set across the shared invocation");
3258 }
3259
3260 #[tokio::test]
3272 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3273 let body_403 = "forbidden";
3274 let resp_403 = format!(
3275 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3276 body_403.len(),
3277 body_403
3278 );
3279 let resp_200 = ok_stream_response();
3280
3281 let (base, rx) = spawn_n_capturing_requests(vec![
3282 Box::leak(resp_403.into_boxed_str()),
3283 Box::leak(resp_200.into_boxed_str()),
3284 ]);
3285 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3286 let req = sample_stream_event_request();
3287 let pid = uuid::Uuid::from_u128(42);
3288
3289 let forced = crate::session_state::ProjectBinding {
3292 project_id: pid.to_string(),
3293 project_name: "forced".into(),
3294 updated_at: "".into(),
3295 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3296 };
3297
3298 let mut warned = false;
3299 let err = send_stream_event(
3300 &client,
3301 &Attribution::Repo {
3302 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3303 project: Some(pid),
3304 },
3305 attribution_force(Some(&forced)),
3306 &req,
3307 &mut warned,
3308 )
3309 .await
3310 .expect_err("a refused force must be an error, not a silent fallback");
3311 assert!(
3312 err.to_string().contains("403"),
3313 "propagated error must reflect the status, got: {err}"
3314 );
3315 assert!(warned, "the refusal must be printed exactly once");
3316
3317 let first = rx
3318 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3319 .expect("no first request captured");
3320 assert!(
3321 first.contains(&format!("/projects/{pid}/stream")),
3322 "first request must hit the project-scoped endpoint, got: {first}"
3323 );
3324 assert!(
3325 first
3326 .to_lowercase()
3327 .contains("x-tracevault-project-attribution: explicit"),
3328 "the refused send must have DECLARED explicit — this is the mode \
3329 `refused_error` is handed: {first}"
3330 );
3331
3332 assert!(
3333 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3334 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3335 );
3336 }
3337
3338 #[tokio::test]
3347 async fn send_stream_event_project_only_omits_repo_id() {
3348 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3349 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3350 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3351
3352 let resp = ok_stream_response();
3353 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3354 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3355 let req = sample_stream_event_request();
3356 let pid = uuid::Uuid::from_u128(11);
3357
3358 let mut warned = false;
3359 let got = send_stream_event(
3360 &client,
3361 &Attribution::ProjectOnly { project_id: pid },
3362 attribution_force(None),
3363 &req,
3364 &mut warned,
3365 )
3366 .await
3367 .expect("a repo-less project send must succeed");
3368 assert_eq!(
3369 got.expect("a successful send returns a response").status,
3370 "accepted"
3371 );
3372
3373 let line = rx
3374 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3375 .expect("no request captured");
3376 assert!(
3377 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3378 "expected a bare project path with no query string, got: {line}"
3379 );
3380 assert!(
3381 line.to_lowercase()
3382 .contains("x-tracevault-project-attribution: derived"),
3383 "with no forced binding, the header must declare `derived`, got: {line}"
3384 );
3385 assert!(
3386 !warned,
3387 "a repo-less send has no fallback and must not warn about one"
3388 );
3389 }
3390
3391 #[tokio::test]
3398 async fn send_stream_event_project_only_drops_on_scoping_4xx() {
3399 let body = "no such project";
3400 let resp_404 = format!(
3401 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3402 body.len(),
3403 body
3404 );
3405 let (base, rx) = spawn_n_capturing_requests(vec![
3412 Box::leak(resp_404.clone().into_boxed_str()),
3413 Box::leak(resp_404.into_boxed_str()),
3414 ]);
3415 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3416 let req = sample_stream_event_request();
3417 let pid = uuid::Uuid::from_u128(12);
3418
3419 let mut warned = false;
3420 let got = send_stream_event(
3421 &client,
3422 &Attribution::ProjectOnly { project_id: pid },
3423 attribution_force(None),
3424 &req,
3425 &mut warned,
3426 )
3427 .await
3428 .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
3429 assert!(
3430 got.is_none(),
3431 "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
3432 );
3433 assert!(
3434 warned,
3435 "dropping data silently is the failure mode to avoid"
3436 );
3437
3438 let first = rx
3439 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3440 .expect("no request captured");
3441 assert!(
3442 first.contains(&format!("/projects/{pid}/stream")),
3443 "must hit the project-scoped endpoint, got: {first}"
3444 );
3445 assert!(
3446 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3447 "a repo-less send must make exactly one request — no fallback exists"
3448 );
3449 }
3450
3451 #[tokio::test]
3455 async fn send_stream_event_project_only_buffers_on_403() {
3456 let body = "forbidden";
3457 let resp_403 = format!(
3458 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3459 body.len(),
3460 body
3461 );
3462 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
3463 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3464 let req = sample_stream_event_request();
3465
3466 let mut warned = false;
3467 let err = send_stream_event(
3468 &client,
3469 &Attribution::ProjectOnly {
3470 project_id: uuid::Uuid::from_u128(13),
3471 },
3472 attribution_force(None),
3473 &req,
3474 &mut warned,
3475 )
3476 .await
3477 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
3478 assert!(
3479 err.to_string().contains("403"),
3480 "propagated error must reflect the status, got: {err}"
3481 );
3482 }
3483
3484 #[tokio::test]
3489 async fn send_stream_event_does_not_fall_back_on_transient_503() {
3490 let body_503 = "internal error";
3491 let resp_503 = format!(
3492 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3493 body_503.len(),
3494 body_503
3495 );
3496 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
3497 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3498 let req = sample_stream_event_request();
3499 let pid = uuid::Uuid::from_u128(7);
3500
3501 let mut warned = false;
3502 let err = send_stream_event(
3503 &client,
3504 &Attribution::Repo {
3505 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3506 project: Some(pid),
3507 },
3508 attribution_force(None),
3509 &req,
3510 &mut warned,
3511 )
3512 .await
3513 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
3514 assert!(
3515 err.to_string().contains("503"),
3516 "propagated error must reflect the transient status, got: {err}"
3517 );
3518 assert!(
3519 deterministic_client_error_kind(err.as_ref()).is_none(),
3520 "a 503 must not be classified as a deterministic client error"
3521 );
3522
3523 let first = rx
3524 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3525 .expect("no request captured");
3526 assert!(
3527 first.contains(&format!("/projects/{pid}/stream")),
3528 "must hit the project-scoped endpoint, got: {first}"
3529 );
3530
3531 assert!(
3538 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3539 "no second (fallback) request should have been sent for a transient error"
3540 );
3541 }
3542
3543 #[test]
3547 fn a_403_is_classified_apart_from_the_scoping_statuses() {
3548 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3549 assert_eq!(
3550 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3551 Some(ClientErrorKind::Forbidden)
3552 );
3553 for scoping in [
3554 "Stream failed (400 Bad Request): {}",
3555 "Stream failed (404 Not Found): {}",
3556 "Stream failed (409 Conflict): {}",
3557 ] {
3558 assert_eq!(
3559 deterministic_client_error_kind(err(scoping).as_ref()),
3560 Some(ClientErrorKind::Scoping),
3561 "{scoping}"
3562 );
3563 }
3564 for transient in [
3567 "Stream failed (401 Unauthorized): {}",
3568 "Stream failed (503 Service Unavailable): {}",
3569 "error sending request for url (http://x/stream)",
3570 ] {
3571 assert_eq!(
3572 deterministic_client_error_kind(err(transient).as_ref()),
3573 None,
3574 "{transient}"
3575 );
3576 }
3577 }
3578
3579 #[test]
3584 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3585 let pid = uuid::Uuid::from_u128(7);
3586
3587 let forbidden = refused_error(
3588 pid,
3589 &ClientErrorKind::Forbidden,
3590 AttributionForce::default(),
3591 );
3592 assert!(forbidden.contains("403"), "{forbidden}");
3593 assert!(
3594 forbidden.contains("no `tracevault` grant in Control Plane"),
3595 "must offer the missing-role explanation: {forbidden}"
3596 );
3597 assert!(
3598 forbidden.contains("no `Operator` role on it"),
3599 "must still offer the project explanation: {forbidden}"
3600 );
3601 assert!(
3602 forbidden.starts_with("tracevault: error:"),
3603 "a refusal is an error, not a warning: {forbidden}"
3604 );
3605 assert!(forbidden.contains(&pid.to_string()));
3606
3607 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3610 assert!(scoping.contains("project switch"), "{scoping}");
3611 assert!(
3612 !scoping.contains("`tracevault` grant"),
3613 "the scoping case must not mention the `tracevault` grant: {scoping}"
3614 );
3615
3616 for s in [&forbidden, &scoping] {
3617 assert!(s.contains("--user"), "must name the --user fix: {s}");
3620 assert!(
3621 s.contains("user_project.toml"),
3622 "must name the machine-wide default's file: {s}"
3623 );
3624 assert!(
3625 !s.contains("repo deduction"),
3626 "must never describe re-attribution to another project: {s}"
3627 );
3628 assert!(
3629 !s.contains("Attributing via"),
3630 "must never claim the event was re-attributed: {s}"
3631 );
3632 }
3633 }
3634
3635 #[test]
3646 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3647 let pid = uuid::Uuid::from_u128(7);
3648
3649 let explicit = refused_error(
3650 pid,
3651 &ClientErrorKind::Forbidden,
3652 AttributionForce {
3653 env: false,
3654 binding: true,
3655 },
3656 );
3657 assert!(
3658 explicit.contains("FORCE"),
3659 "the refusal of the force itself must be named: {explicit}"
3660 );
3661 assert!(
3662 explicit.contains("Operator"),
3663 "must name the grant forcing requires: {explicit}"
3664 );
3665 assert!(
3666 explicit.contains("Control Plane"),
3667 "must name the identity forcing requires: {explicit}"
3668 );
3669 assert!(
3673 explicit.contains("`tracevault` grant")
3674 && explicit.contains("no `Operator` role on it"),
3675 "the membership causes must still be named: {explicit}"
3676 );
3677 assert!(
3680 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3681 "must never claim the event was re-attributed: {explicit}"
3682 );
3683
3684 let derived = refused_error(
3689 pid,
3690 &ClientErrorKind::Forbidden,
3691 AttributionForce::default(),
3692 );
3693 assert!(
3694 !derived.contains("FORCE"),
3695 "a `derived` send never forced anything: {derived}"
3696 );
3697 }
3698
3699 #[test]
3704 fn an_explicit_scoping_failure_does_not_blame_the_force() {
3705 let pid = uuid::Uuid::from_u128(7);
3706 let scoping = refused_error(
3707 pid,
3708 &ClientErrorKind::Scoping,
3709 AttributionForce {
3710 env: true,
3711 binding: true,
3712 },
3713 );
3714 assert!(!scoping.contains("FORCE"), "{scoping}");
3715 assert_eq!(
3716 scoping,
3717 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3718 "the scoping wording does not depend on the mode"
3719 );
3720 }
3721
3722 #[test]
3742 fn the_403_remediation_names_the_force_source_actually_in_effect() {
3743 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3744 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3745 let pid = uuid::Uuid::from_u128(7);
3746 let live = forced_binding(Some(
3747 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3748 ));
3749 let never_forced = forced_binding(None);
3750
3751 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3755 let env_only = refused_error(
3756 pid,
3757 &ClientErrorKind::Forbidden,
3758 attribution_force(Some(&never_forced)),
3759 );
3760 assert!(
3761 env_only.contains("FORCE"),
3762 "an env-sourced force is still a force: {env_only}"
3763 );
3764 assert!(
3765 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3766 "must name the variable that is doing the forcing: {env_only}"
3767 );
3768 assert!(
3769 !env_only.contains("--project-attribution"),
3770 "must NOT tell the operator to drop a flag that would change \
3771 nothing here — this is the bug: {env_only}"
3772 );
3773
3774 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3778 let binding_only = refused_error(
3779 pid,
3780 &ClientErrorKind::Forbidden,
3781 attribution_force(Some(&live)),
3782 );
3783 assert!(
3784 binding_only.contains("--project-attribution"),
3785 "a persisted force IS cleared by switching without the flag: {binding_only}"
3786 );
3787 assert!(
3788 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3789 "must not send the operator after an unset variable: {binding_only}"
3790 );
3791
3792 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3796 let both = refused_error(
3797 pid,
3798 &ClientErrorKind::Forbidden,
3799 attribution_force(Some(&live)),
3800 );
3801 assert!(
3802 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3803 && both.contains("--project-attribution"),
3804 "both sources are in effect and both must be named: {both}"
3805 );
3806 assert!(
3807 both.contains("BOTH"),
3808 "must say that removing only one is not enough: {both}"
3809 );
3810 }
3811
3812 #[test]
3817 fn no_force_means_no_remediation_clause() {
3818 let pid = uuid::Uuid::from_u128(7);
3819 let none = refused_error(
3820 pid,
3821 &ClientErrorKind::Forbidden,
3822 AttributionForce::default(),
3823 );
3824 assert!(
3825 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3826 && !none.contains("--project-attribution"),
3827 "a derived send has no force to remove: {none}"
3828 );
3829 }
3830
3831 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
3836 let path = dir.join("transcript.jsonl");
3837 let mut body = String::new();
3838 for i in 0..n {
3839 let line = serde_json::json!({
3840 "type": "user",
3841 "n": i,
3842 "message": {"content": "x".repeat(line_bytes)},
3843 });
3844 body.push_str(&line.to_string());
3845 body.push('\n');
3846 }
3847 fs::write(&path, body).unwrap();
3848 path
3849 }
3850
3851 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
3853 StreamEventRequest {
3854 tool_name: Some("Bash".into()),
3855 tool_use_id: Some("toolu_1".into()),
3856 tool_input: Some(serde_json::json!({"command": "ls"})),
3857 event_uuid: Some(uuid::Uuid::now_v7()),
3858 transcript_lines: Some(lines),
3859 transcript_offset: Some(offset),
3860 ..sample_stream_event_request()
3861 }
3862 }
3863
3864 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
3865 part.transcript_lines.clone().unwrap_or_default()
3866 }
3867
3868 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
3871 parts
3872 .iter()
3873 .flat_map(|p| {
3874 let offset = p.transcript_offset.unwrap();
3875 part_lines(p)
3876 .into_iter()
3877 .enumerate()
3878 .map(move |(i, l)| (offset + i as i64, l))
3879 })
3880 .collect()
3881 }
3882
3883 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
3885 (0..n)
3886 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
3887 .collect()
3888 }
3889
3890 #[test]
3891 fn split_leaves_a_request_under_the_cap_unchanged() {
3892 let req = event_with_lines(big_lines(3, 100), 0);
3893
3894 let parts = split_into_parts(req.clone());
3895
3896 assert_eq!(parts.len(), 1);
3897 assert_eq!(
3898 serde_json::to_value(&parts[0]).unwrap(),
3899 serde_json::to_value(&req).unwrap()
3900 );
3901 }
3902
3903 #[test]
3907 fn split_carries_every_line_of_a_batch_over_the_cap() {
3908 let dir = tempfile::tempdir().unwrap();
3909 let transcript = write_transcript(dir.path(), 300, 5_000);
3911 let (lines, start, _) =
3912 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
3913 let req = event_with_lines(lines.clone(), start);
3914 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
3915
3916 let parts = split_into_parts(req.clone());
3917
3918 assert!(parts.len() >= 3, "got {} parts", parts.len());
3919 for part in &parts {
3920 assert!(
3921 part.serialized_len() <= MAX_REQUEST_BYTES,
3922 "part of {} bytes exceeds the cap",
3923 part.serialized_len()
3924 );
3925 }
3926 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3927 assert_eq!(sent, lines, "every line, once, in order");
3928
3929 let (event, transcript_parts) = parts.split_last().unwrap();
3931 assert_eq!(event.event_type, StreamEventType::ToolUse);
3932 assert_eq!(event.event_uuid, req.event_uuid);
3933 assert_eq!(event.tool_input, req.tool_input);
3934 for part in transcript_parts {
3935 assert_eq!(part.event_type, StreamEventType::Transcript);
3936 assert!(part.event_uuid.is_none());
3937 assert!(part.tool_input.is_none());
3938 assert!(part.tool_name.is_none());
3939 }
3940 assert!(
3941 !part_lines(event).is_empty(),
3942 "the event keeps the lines that fit beside it"
3943 );
3944 }
3945
3946 #[test]
3950 fn split_keeps_each_lines_unsplit_chunk_index() {
3951 let lines = big_lines(300, 5_000);
3952 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
3953
3954 let expected: Vec<_> = lines
3955 .into_iter()
3956 .enumerate()
3957 .map(|(i, l)| (1_000 + i as i64, l))
3958 .collect();
3959 assert_eq!(chunk_indexes(&parts), expected);
3960 }
3961
3962 #[test]
3967 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
3968 let lines = big_lines(10, 200_000);
3969 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
3970 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
3971
3972 for (index, line) in &short {
3973 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
3974 assert_eq!(in_long.0, *index, "line {line} indexed differently");
3975 }
3976 }
3977
3978 #[test]
3981 fn split_sends_a_single_oversized_line_alone() {
3982 let lines = vec![
3983 serde_json::json!({"n": 0}),
3984 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
3985 serde_json::json!({"n": 2}),
3986 ];
3987
3988 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
3989
3990 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3991 assert_eq!(sent, lines);
3992 let big = parts
3993 .iter()
3994 .find(|p| part_lines(p).contains(&lines[1]))
3995 .unwrap();
3996 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
3997 assert_eq!(big.transcript_offset, Some(1));
3998 }
3999
4000 fn far_deadline() -> std::time::Instant {
4001 std::time::Instant::now() + Duration::from_secs(60)
4002 }
4003
4004 fn captured_body(captured: &str) -> StreamEventRequest {
4005 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
4006 serde_json::from_str(body).expect("request body is a StreamEventRequest")
4007 }
4008
4009 #[tokio::test]
4011 async fn deliver_parts_sends_every_part() {
4012 let dir = tempfile::tempdir().unwrap();
4013 let pending_path = dir.path().join("pending.jsonl");
4014 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4015 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4016 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4017
4018 let all_accepted = deliver_parts(
4019 &client,
4020 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4021 AttributionForce::default(),
4022 parts.clone(),
4023 &pending_path,
4024 false,
4025 far_deadline(),
4026 &mut false,
4027 )
4028 .await
4029 .unwrap();
4030
4031 assert!(all_accepted);
4032 for part in &parts {
4033 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4034 assert_eq!(got.transcript_offset, part.transcript_offset);
4035 assert_eq!(got.transcript_lines, part.transcript_lines);
4036 }
4037 assert!(drain_pending(&pending_path).unwrap().is_empty());
4038 }
4039
4040 #[tokio::test]
4044 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4045 let dir = tempfile::tempdir().unwrap();
4046 let pending_path = dir.path().join("pending.jsonl");
4047 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4048 assert!(parts.len() >= 3);
4049 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4050 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4051 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4052
4053 let all_accepted = deliver_parts(
4054 &client,
4055 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4056 AttributionForce::default(),
4057 parts.clone(),
4058 &pending_path,
4059 false,
4060 far_deadline(),
4061 &mut false,
4062 )
4063 .await
4064 .unwrap();
4065
4066 assert!(!all_accepted);
4067 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4068 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4069 assert!(
4070 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4071 "nothing is sent after the first failure"
4072 );
4073 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4074 .unwrap()
4075 .iter()
4076 .map(|j| serde_json::from_str(j).unwrap())
4077 .collect();
4078 assert_eq!(queued.len(), parts.len() - 1);
4079 for (q, part) in queued.iter().zip(&parts[1..]) {
4080 assert_eq!(q.transcript_offset, part.transcript_offset);
4081 assert_eq!(q.transcript_lines, part.transcript_lines);
4082 }
4083 }
4084
4085 #[tokio::test]
4088 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4089 let dir = tempfile::tempdir().unwrap();
4090 let pending_path = dir.path().join("pending.jsonl");
4091 let parts = split_into_parts(sample_stream_event_request());
4092 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4093
4094 let all_accepted = deliver_parts(
4095 &client,
4096 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4097 AttributionForce::default(),
4098 parts,
4099 &pending_path,
4100 true,
4101 far_deadline(),
4102 &mut false,
4103 )
4104 .await
4105 .unwrap();
4106
4107 assert!(!all_accepted);
4108 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4109 }
4110
4111 #[tokio::test]
4114 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
4115 let dir = tempfile::tempdir().unwrap();
4116 let pending_path = dir.path().join("pending.jsonl");
4117 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4118 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4119 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4120
4121 let all_accepted = deliver_parts(
4122 &client,
4123 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4124 AttributionForce::default(),
4125 parts.clone(),
4126 &pending_path,
4127 false,
4128 std::time::Instant::now(),
4129 &mut false,
4130 )
4131 .await
4132 .unwrap();
4133
4134 assert!(!all_accepted);
4135 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
4136 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
4137 }
4138
4139 #[tokio::test]
4144 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
4145 let dir = tempfile::tempdir().unwrap();
4146 let pending_path = dir.path().join("pending.jsonl");
4147 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
4148 let base = format!("http://{}", listener.local_addr().unwrap());
4149 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4151 let started = Instant::now();
4152
4153 let all_accepted = deliver_parts(
4154 &client,
4155 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4156 AttributionForce::default(),
4157 vec![event_with_lines(big_lines(1, 10), 0)],
4158 &pending_path,
4159 false,
4160 started + Duration::from_millis(100),
4161 &mut false,
4162 )
4163 .await
4164 .unwrap();
4165
4166 assert!(!all_accepted);
4167 assert!(started.elapsed() < Duration::from_secs(10));
4168 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4169 drop(listener);
4170 }
4171
4172 const PARENT_SESSION: &str = "parent-session";
4175 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
4176
4177 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
4181 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
4182 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4183 let subagents = dir.join(PARENT_SESSION).join("subagents");
4184 fs::create_dir_all(&subagents).unwrap();
4185 let session_dir = dir.join("tv-session");
4186 fs::create_dir_all(&session_dir).unwrap();
4187 (main, subagents, session_dir)
4188 }
4189
4190 fn subagent_line(agent: &str, n: usize) -> String {
4191 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
4192 }
4193
4194 fn append_raw(path: &Path, text: &str) {
4195 let mut f = fs::OpenOptions::new()
4196 .create(true)
4197 .append(true)
4198 .open(path)
4199 .unwrap();
4200 f.write_all(text.as_bytes()).unwrap();
4201 }
4202
4203 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
4204 let path = subagents.join(format!("agent-{agent}.jsonl"));
4205 for n in ns {
4206 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
4207 }
4208 }
4209
4210 async fn sweep(
4214 responses: Vec<String>,
4215 main: &Path,
4216 session_dir: &Path,
4217 pending_path: &Path,
4218 ) -> Vec<StreamEventRequest> {
4219 sweep_waiting(responses, main, session_dir, pending_path, None).await
4220 }
4221
4222 async fn sweep_waiting(
4225 responses: Vec<String>,
4226 main: &Path,
4227 session_dir: &Path,
4228 pending_path: &Path,
4229 wait_for_lock: Option<Instant>,
4230 ) -> Vec<StreamEventRequest> {
4231 let expected = responses.len();
4232 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4233 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4234 let event = StreamEventRequest {
4235 session_id: PARENT_SESSION.into(),
4236 ..sample_stream_event_request()
4237 };
4238 deliver_subagent_transcripts(
4239 &client,
4240 &repo_attr(SUBAGENT_REPO),
4241 AttributionForce::default(),
4242 &transcript_template(&event),
4243 main,
4244 session_dir,
4245 pending_path,
4246 false,
4247 Instant::now() + Duration::from_secs(60),
4248 wait_for_lock,
4249 &mut false,
4250 )
4251 .await
4252 .unwrap();
4253 (0..expected)
4254 .map(|_| {
4255 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4256 assert!(
4257 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4258 "{captured}"
4259 );
4260 let body = captured.splitn(3, " | ").nth(2).unwrap();
4261 serde_json::from_str(body).unwrap()
4262 })
4263 .collect()
4264 }
4265
4266 fn agent_of(line: &serde_json::Value) -> &str {
4267 line["agentId"].as_str().unwrap()
4268 }
4269
4270 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4274 for req in reqs {
4275 assert_eq!(req.event_type, StreamEventType::Transcript);
4276 assert_eq!(req.session_id, PARENT_SESSION);
4277 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4278 let lines = part_lines(req);
4279 let agent = agent_of(&lines[0]);
4280 assert!(
4281 lines.iter().all(|l| agent_of(l) == agent),
4282 "a request mixes subagent files: {lines:?}"
4283 );
4284 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4285 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4286 assert_eq!(req.transcript_offset, Some(first));
4287 }
4288 }
4289
4290 #[tokio::test]
4291 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4292 let dir = tempfile::tempdir().unwrap();
4293 let (main, subagents, session_dir) = claude_session(dir.path());
4294 let pending = session_dir.join("pending.jsonl");
4295 let ok = ok_stream_response;
4296 let mut all = Vec::new();
4297
4298 append_subagent_lines(&subagents, "a1", 0..2);
4300 append_subagent_lines(&subagents, "b2", 0..1);
4301 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4302 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4303 assert_eq!(reqs.len(), 2);
4304 all.extend(reqs);
4305
4306 append_subagent_lines(&subagents, "a1", 2..3);
4308 append_subagent_lines(&subagents, "b2", 1..2);
4309 let partial = subagent_line("b2", 2);
4310 let (head, tail) = partial.split_at(10);
4311 append_raw(&subagents.join("agent-b2.jsonl"), head);
4312 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4313 assert_eq!(reqs.len(), 2);
4314 all.extend(reqs);
4315
4316 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4318 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4319 assert_eq!(reqs.len(), 1);
4320 all.extend(reqs);
4321
4322 assert!(sweep(vec![], &main, &session_dir, &pending)
4324 .await
4325 .is_empty());
4326 assert!(!pending.exists(), "nothing may have failed and been queued");
4327
4328 assert_one_file_per_request(&subagents, &all);
4329 let mut sent: Vec<(String, u64)> = all
4330 .iter()
4331 .flat_map(part_lines)
4332 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4333 .collect();
4334 sent.sort();
4335 let expected: Vec<(String, u64)> = [
4336 ("a1", 0),
4337 ("a1", 1),
4338 ("a1", 2),
4339 ("b2", 0),
4340 ("b2", 1),
4341 ("b2", 2),
4342 ]
4343 .into_iter()
4344 .map(|(a, n)| (a.to_string(), n))
4345 .collect();
4346 assert_eq!(sent, expected, "each line exactly once");
4347 }
4348
4349 #[tokio::test]
4350 async fn a_session_without_subagents_sends_nothing_extra() {
4351 let dir = tempfile::tempdir().unwrap();
4352 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4353 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4354 let session_dir = dir.path().join("tv-session");
4355 fs::create_dir_all(&session_dir).unwrap();
4356 let pending = session_dir.join("pending.jsonl");
4357
4358 assert!(sweep(vec![], &main, &session_dir, &pending)
4359 .await
4360 .is_empty());
4361 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4362 }
4363
4364 #[tokio::test]
4369 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4370 let dir = tempfile::tempdir().unwrap();
4371 let (main, subagents, session_dir) = claude_session(dir.path());
4372 let pending = session_dir.join("pending.jsonl");
4373 append_subagent_lines(&subagents, "a1", 0..2);
4374 append_subagent_lines(&subagents, "b2", 0..1);
4375
4376 let error =
4377 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4378 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4379 assert_eq!(failed.len(), 1);
4380 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4381 .unwrap()
4382 .iter()
4383 .map(|j| serde_json::from_str(j).unwrap())
4384 .collect();
4385 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4386
4387 let resent = sweep(
4388 vec![ok_stream_response(), ok_stream_response()],
4389 &main,
4390 &session_dir,
4391 &pending,
4392 )
4393 .await;
4394 assert_one_file_per_request(&subagents, &resent);
4395 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4396 assert_eq!(
4397 resent.iter().map(key).collect::<Vec<_>>(),
4398 queued.iter().map(key).collect::<Vec<_>>()
4399 );
4400 assert!(sweep(vec![], &main, &session_dir, &pending)
4401 .await
4402 .is_empty());
4403 }
4404
4405 #[tokio::test]
4408 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
4409 let dir = tempfile::tempdir().unwrap();
4410 let (main, subagents, session_dir) = claude_session(dir.path());
4411 let pending = session_dir.join("pending.jsonl");
4412 append_subagent_lines(&subagents, "a1", 0..2);
4413 append_subagent_lines(&subagents, "b2", 0..1);
4414 let a1_offset =
4415 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4416 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4417
4418 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4419 assert_eq!(reqs.len(), 1);
4420 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
4421 assert!(!a1_offset.exists());
4422
4423 drop(held);
4424 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4425 assert_eq!(reqs.len(), 1);
4426 assert_eq!(part_lines(&reqs[0]).len(), 2);
4427 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
4428 }
4429
4430 #[tokio::test]
4433 async fn a_final_hook_waits_for_a_busy_subagent_file() {
4434 let dir = tempfile::tempdir().unwrap();
4435 let (main, subagents, session_dir) = claude_session(dir.path());
4436 let pending = session_dir.join("pending.jsonl");
4437 append_subagent_lines(&subagents, "a1", 0..2);
4438 let a1_offset =
4439 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4440 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4441 let release = thread::spawn(move || {
4442 thread::sleep(Duration::from_millis(300));
4443 drop(held);
4444 });
4445
4446 let reqs = sweep_waiting(
4447 vec![ok_stream_response()],
4448 &main,
4449 &session_dir,
4450 &pending,
4451 Some(Instant::now() + Duration::from_secs(10)),
4452 )
4453 .await;
4454 release.join().unwrap();
4455 assert_eq!(reqs.len(), 1);
4456 assert_eq!(part_lines(&reqs[0]).len(), 2);
4457 }
4458
4459 #[tokio::test]
4463 async fn a_large_subagent_batch_is_split_within_its_file() {
4464 let dir = tempfile::tempdir().unwrap();
4465 let (main, subagents, session_dir) = claude_session(dir.path());
4466 let pending = session_dir.join("pending.jsonl");
4467 let big = subagents.join("agent-a1.jsonl");
4468 for n in 0..300 {
4469 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
4470 append_raw(&big, &format!("{line}\n"));
4471 }
4472 append_subagent_lines(&subagents, "b2", 0..1);
4473
4474 let scratch = dir.path().join("scratch-offset");
4475 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
4476 let unsplit = StreamEventRequest {
4477 transcript_lines: Some(lines.clone()),
4478 transcript_offset: Some(start),
4479 ..transcript_template(&sample_stream_event_request())
4480 };
4481 let a1_parts = split_into_parts(unsplit).len();
4482 assert!(a1_parts > 1, "the batch must exceed the cap");
4483
4484 let reqs = sweep(
4485 vec![ok_stream_response(); a1_parts + 1],
4486 &main,
4487 &session_dir,
4488 &pending,
4489 )
4490 .await;
4491 assert!(!pending.exists());
4492 let (a1, b2) = reqs.split_at(a1_parts);
4493 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
4494 assert_eq!(
4495 chunk_indexes(a1),
4496 lines
4497 .into_iter()
4498 .enumerate()
4499 .map(|(i, l)| (start + i as i64, l))
4500 .collect::<Vec<_>>()
4501 );
4502 assert_eq!(b2.len(), 1);
4503 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
4504 assert_eq!(b2[0].transcript_offset, Some(0));
4505 }
4506}