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
210fn adopt_queue(from: &Path, into: &Path) -> Result<(), io::Error> {
220 let adopted = match fs::read_to_string(from) {
221 Ok(s) => s,
222 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
223 Err(e) => return Err(e),
224 };
225 let existing = match fs::read_to_string(into) {
226 Ok(s) => s,
227 Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(),
228 Err(e) => return Err(e),
229 };
230 let mut merged = adopted;
231 if !merged.is_empty() && !merged.ends_with('\n') {
232 merged.push('\n');
233 }
234 merged.push_str(&existing);
235 let tmp = into.with_extension("jsonl.adopting");
236 fs::write(&tmp, merged)?;
237 fs::rename(&tmp, into)?;
238 fs::remove_file(from)
239}
240
241pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
242 if !pending_path.exists() {
243 return Ok(vec![]);
244 }
245 let content = fs::read_to_string(pending_path)?;
246 let lines: Vec<String> = content
247 .lines()
248 .filter(|l| !l.trim().is_empty())
249 .map(String::from)
250 .collect();
251 fs::remove_file(pending_path)?;
252 Ok(lines)
253}
254
255#[derive(Debug, Clone, PartialEq, Eq)]
265pub(crate) enum Attribution {
266 Repo {
269 repo_id: String,
270 project: Option<uuid::Uuid>,
271 },
272 ProjectOnly { project_id: uuid::Uuid },
275}
276
277impl Attribution {
278 pub(crate) fn pending_file_name(&self) -> String {
287 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
288 match self {
289 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
290 Self::ProjectOnly { project_id } => {
291 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
292 }
293 }
294 }
295}
296
297pub(crate) fn attribution_for(
317 binding: Option<&crate::session_state::RepoBinding>,
318 project: Option<uuid::Uuid>,
319) -> Option<Attribution> {
320 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
321 Some(b) => Some(Attribution::Repo {
322 repo_id: b.repo_id.clone(),
323 project,
324 }),
325 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
326 }
327}
328
329pub(crate) fn inference_project(
334 binding: Option<&crate::session_state::RepoBinding>,
335 project: Option<uuid::Uuid>,
336) -> Option<uuid::Uuid> {
337 match binding {
338 Some(_) => None,
339 None => project,
340 }
341}
342
343pub(crate) fn attribution_with_inference(
348 binding: Option<&crate::session_state::RepoBinding>,
349 project: Option<uuid::Uuid>,
350 inferred: Option<&crate::session_state::RepoBinding>,
351) -> Option<Attribution> {
352 match (inference_project(binding, project), inferred) {
353 (Some(pid), Some(repo)) if binding_repo_id_is_valid(&repo.repo_id) => {
354 Some(Attribution::Repo {
355 repo_id: repo.repo_id.clone(),
356 project: Some(pid),
357 })
358 }
359 _ => attribution_for(binding, project),
360 }
361}
362
363#[derive(Debug, Clone, PartialEq, Eq)]
367pub(crate) struct Recording {
368 pub attribution: Option<Attribution>,
369 pub inferred_from: Option<String>,
370}
371
372fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
374 session_dir.join(attribution.pending_file_name())
375}
376
377fn adopted_project_queue(
407 session_dir: &Path,
408 attribution: &Attribution,
409) -> Option<std::path::PathBuf> {
410 match attribution {
411 Attribution::Repo {
412 project: Some(project_id),
413 ..
414 } => Some(pending_path_for(
415 session_dir,
416 &Attribution::ProjectOnly {
417 project_id: *project_id,
418 },
419 )),
420 _ => None,
421 }
422}
423
424pub fn resolve_session_paths(
437 hook_cwd: &Path,
438 session_id: &str,
439) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
440 let resolved = crate::paths::resolve_project_root(hook_cwd);
441 let session_dir = resolved
442 .root
443 .join(".tracevault")
444 .join("sessions")
445 .join(session_id);
446 (resolved, session_dir)
447}
448
449pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
457 uuid::Uuid::parse_str(repo_id).is_ok()
458}
459
460pub(crate) fn resolve_stream_binding(
464 session: &crate::session_state::SessionState,
465 worktree: &str,
466 bound: Option<crate::session_state::RepoBinding>,
467 user_default: Option<crate::session_state::RepoBinding>,
468) -> Option<crate::session_state::RepoBinding> {
469 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
470 repo_flag: None,
471 session,
472 worktree_path: Some(worktree),
473 bound,
474 user_default,
475 })
476 .map(|(b, _)| b)
477}
478
479pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
487 let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
488 let raw = raw.trim();
489 let parsed = raw.parse::<uuid::Uuid>().ok()?;
490 Some(crate::session_state::ProjectBinding {
491 project_id: parsed.to_string(),
492 project_name: String::new(),
493 updated_at: String::new(),
494 forced_until: None,
495 })
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
520pub(crate) struct AttributionForce {
521 pub(crate) env: bool,
524 pub(crate) binding: bool,
528}
529
530impl AttributionForce {
531 pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
534 if self.env || self.binding {
535 crate::api_client::AttributionMode::Explicit
536 } else {
537 crate::api_client::AttributionMode::Derived
538 }
539 }
540}
541
542pub(crate) fn attribution_mode(
594 effective: Option<&crate::session_state::ProjectBinding>,
595) -> crate::api_client::AttributionMode {
596 attribution_force(effective).mode()
597}
598
599pub(crate) fn attribution_force(
606 effective: Option<&crate::session_state::ProjectBinding>,
607) -> AttributionForce {
608 AttributionForce {
609 env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
610 .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
611 .unwrap_or(false),
612 binding: effective
613 .and_then(|b| b.forced_until.as_deref())
614 .is_some_and(|s| {
615 matches!(
616 crate::session_state::force_status(s),
617 crate::session_state::ForceStatus::Live(_)
618 )
619 }),
620 }
621}
622
623pub(crate) fn capture_binding(
645 session: &crate::session_state::SessionState,
646 worktree_path: Option<&str>,
647 config_project: Option<crate::session_state::ProjectBinding>,
648) -> Option<crate::session_state::ProjectBinding> {
649 use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
650 let (binding, _) = capture_project_binding(&CaptureProjectInputs {
651 project_flag: None,
652 env_project: env_project_binding(),
653 session,
654 worktree_path,
655 config_project,
656 user_default: crate::user_project_default::load(),
657 })?;
658 capture_project_id(&binding)?;
663 Some(binding)
664}
665
666pub(crate) fn capture_project(
676 session: &crate::session_state::SessionState,
677 worktree_path: Option<&str>,
678 config_project: Option<crate::session_state::ProjectBinding>,
679) -> Option<uuid::Uuid> {
680 capture_binding(session, worktree_path, config_project)
681 .as_ref()
682 .and_then(crate::resolution::capture_project_id)
683}
684
685pub(crate) fn recording_attribution_for(
698 session: &crate::session_state::SessionState,
699 worktree: &str,
700 bound: Option<crate::session_state::RepoBinding>,
701 user_default_repo: Option<crate::session_state::RepoBinding>,
702 config_project: Option<crate::session_state::ProjectBinding>,
703) -> Recording {
704 let stream_binding = resolve_stream_binding(session, worktree, bound, user_default_repo);
705 let project = capture_project(session, Some(worktree), config_project);
706 let inferred = inference_project(stream_binding.as_ref(), project)
707 .and_then(|pid| crate::inferred_repo::cached_repo(session, worktree, pid));
708 let attribution =
709 attribution_with_inference(stream_binding.as_ref(), project, inferred.as_ref());
710 let inferred_from = match (&attribution, &inferred) {
711 (Some(Attribution::Repo { repo_id, .. }), Some(repo)) if *repo_id == repo.repo_id => {
712 Some(worktree.to_string())
713 }
714 _ => None,
715 };
716 Recording {
717 attribution,
718 inferred_from,
719 }
720}
721
722pub(crate) fn recording_line_for(recording: &Recording) -> String {
725 if let (
726 Some(Attribution::Repo {
727 repo_id,
728 project: Some(pid),
729 }),
730 Some(checkout),
731 ) = (&recording.attribution, &recording.inferred_from)
732 {
733 return format!(
734 "recording: repo {repo_id} in project {pid} — inferred from the checkout {checkout} \
735 (no repo is bound; events in other checkouts go to their own repo in the project, \
736 or to the project only)"
737 );
738 }
739 recording_line(recording.attribution.as_ref())
740}
741
742pub(crate) fn recording_line(attribution: Option<&Attribution>) -> String {
744 match attribution {
745 Some(Attribution::Repo {
746 repo_id,
747 project: None,
748 }) => format!("recording: repo {repo_id} (the server deduces the project from the repo)"),
749 Some(Attribution::Repo {
750 repo_id,
751 project: Some(pid),
752 }) => format!("recording: repo {repo_id} in project {pid}"),
753 Some(Attribution::ProjectOnly { project_id }) => format!(
754 "recording: project {project_id} only — no repo is bound, so events are sent \
755 without one (`tracevault repo switch <path>` adds the repo)"
756 ),
757 None => "recording: nothing — neither a repo nor a project is bound, so this \
758 session's events are not sent"
759 .to_string(),
760 }
761}
762
763pub(crate) fn refused_project_only_error(
776 pid: uuid::Uuid,
777 kind: &ClientErrorKind,
778 force: AttributionForce,
779) -> String {
780 let base = match kind {
781 ClientErrorKind::Forbidden => format!(
782 "tracevault: error: the server refused this repo-less session's event for project \
783 {pid} (403). Either this account has no access to that project (no `Operator` \
784 role on it) — run `tracevault project switch <name>` (add `--user` if the binding \
785 is the machine-wide default in `user_project.toml`) — or it has no `tracevault` \
786 grant in Control Plane at all, which an administrator must grant. The session has \
787 no repo binding, so the event was not sent anywhere else; it has been queued and \
788 will be retried with the next event."
789 ),
790 ClientErrorKind::Scoping => format!(
791 "tracevault: error: project {pid} does not resolve on the server (400/404/409: it \
792 does not exist, or this account cannot see it). The session has no repo binding, \
793 so the event was not sent anywhere else; it has been queued and will be retried \
794 with the next event. Run `tracevault project switch <name>` (add `--user` if the \
795 binding is the machine-wide default in `user_project.toml`) to bind a project that \
796 exists, or `tracevault repo switch <path>` to record this session to a repo."
797 ),
798 };
799 with_force_clause(base, kind, force)
800}
801
802#[derive(Debug, PartialEq, Eq)]
823pub(crate) enum ClientErrorKind {
824 Forbidden,
826 Scoping,
828}
829
830pub(crate) fn refused_error(
861 pid: uuid::Uuid,
862 kind: &ClientErrorKind,
863 force: AttributionForce,
864) -> String {
865 let base = match kind {
866 ClientErrorKind::Forbidden => format!(
872 "tracevault: error: the server refused to attribute this event to active project \
873 {pid} (403). Either that project does not apply to this repo (not a member, or \
874 no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
875 binding is the machine-wide default in `user_project.toml`) — or this account has \
876 no `tracevault` grant in Control Plane at all, which an administrator must grant. \
877 The event was NOT re-attributed elsewhere; it has been queued and will be retried \
878 once the binding or the grant is fixed."
879 ),
880 ClientErrorKind::Scoping => format!(
881 "tracevault: error: active project {pid} does not apply to this repo (not a member, \
882 missing permission, or the project no longer exists). The event was NOT \
883 re-attributed elsewhere; it has been queued and will be retried once the binding is \
884 fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
885 machine-wide default in `user_project.toml`) to update it."
886 ),
887 };
888 with_force_clause(base, kind, force)
889}
890
891fn with_force_clause(base: String, kind: &ClientErrorKind, force: AttributionForce) -> String {
895 if force.mode() == crate::api_client::AttributionMode::Explicit
896 && matches!(kind, ClientErrorKind::Forbidden)
897 {
898 return format!(
899 "{base} This send declared `explicit` attribution, so the refusal may be of the \
900 FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
901 identity (a `tvk_` API key can never force). If membership attribution is what \
902 you want, {}",
903 force_remediation(force)
904 );
905 }
906 base
907}
908
909fn force_remediation(force: AttributionForce) -> String {
926 let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
927 process-wide and never expires, so no switch clears it)";
928 let binding_fix = "run `tracevault project switch <name>` WITHOUT \
929 `--project-attribution explicit` (add `--user` if the forced binding \
930 is the machine-wide default in `user_project.toml`)";
931 match (force.env, force.binding) {
932 (true, false) => format!("{env_fix}."),
933 (false, true) => format!("{binding_fix}."),
934 (true, true) => {
936 format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
937 }
938 (false, false) => format!("{env_fix}, or {binding_fix}."),
939 }
940}
941
942pub(crate) fn deterministic_client_error_kind(
943 e: &dyn std::error::Error,
944) -> Option<ClientErrorKind> {
945 let s = e.to_string();
946 if s.contains("(403 ") {
953 return Some(ClientErrorKind::Forbidden);
954 }
955 if ["(400 ", "(404 ", "(409 "]
956 .iter()
957 .any(|marker| s.contains(marker))
958 {
959 return Some(ClientErrorKind::Scoping);
960 }
961 None
962}
963
964async fn send_stream_event(
1013 client: &crate::api_client::ApiClient,
1014 attribution: &Attribution,
1015 force: AttributionForce,
1016 req: &StreamEventRequest,
1017 warned: &mut bool,
1018) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn std::error::Error>> {
1019 let (repo_id, capture_pid) = match attribution {
1020 Attribution::ProjectOnly { project_id } => {
1029 let attempt = client
1030 .stream_event_for_project(*project_id, None, force.mode(), req)
1031 .await;
1032 if let Err(e) = &attempt {
1033 if let Some(kind) = deterministic_client_error_kind(e.as_ref()) {
1034 if !*warned {
1035 eprintln!("{}", refused_project_only_error(*project_id, &kind, force));
1036 *warned = true;
1037 }
1038 }
1039 }
1040 return attempt;
1041 }
1042 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
1043 };
1044 match capture_pid {
1045 None => client.stream_event(repo_id, req).await,
1046 Some(pid) => {
1047 let attempt = client
1048 .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
1049 .await;
1050 let kind = match &attempt {
1051 Ok(_) => None,
1052 Err(e) => deterministic_client_error_kind(e.as_ref()),
1053 };
1054 match (attempt, kind) {
1055 (Ok(r), _) => Ok(r),
1056 (Err(e), Some(kind)) => {
1057 if !*warned {
1058 eprintln!("{}", refused_error(pid, &kind, force));
1066 *warned = true;
1067 }
1068 Err(e)
1074 }
1075 (Err(e), None) => Err(e),
1077 }
1078 }
1079 }
1080}
1081
1082pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
1088 (start_offset, start_offset + records_len)
1089}
1090
1091pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
1107 if req.serialized_len() <= MAX_REQUEST_BYTES {
1108 return vec![req];
1109 }
1110 let lines = req.transcript_lines.take().unwrap_or_default();
1111 let batch_offset = req.transcript_offset.unwrap_or(0);
1112 req.truncate_large_fields();
1115
1116 let sizes: Vec<usize> = lines
1118 .iter()
1119 .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
1120 .collect();
1121 let envelope = |r: &StreamEventRequest| {
1122 let mut r = r.clone();
1123 r.transcript_lines = Some(vec![]);
1124 r.serialized_len()
1125 };
1126
1127 let mut tail_start = lines.len();
1129 let mut used = envelope(&req);
1130 while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
1131 tail_start -= 1;
1132 used += sizes[tail_start];
1133 }
1134
1135 let transcript_template = transcript_template(&req);
1136 let transcript_envelope = envelope(&transcript_template);
1137
1138 let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
1140 let mut start = 0;
1141 while start < tail_start {
1142 let mut end = start + 1;
1143 let mut used = transcript_envelope + sizes[start];
1144 while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
1145 used += sizes[end];
1146 end += 1;
1147 }
1148 groups.push(start..end);
1149 start = end;
1150 }
1151 groups.push(tail_start..lines.len());
1152
1153 let last = groups.len() - 1;
1154 let mut lines = lines.into_iter();
1155 groups
1156 .into_iter()
1157 .enumerate()
1158 .map(|(n, range)| {
1159 let mut part = if n == last {
1160 req.clone()
1161 } else {
1162 transcript_template.clone()
1163 };
1164 let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
1165 part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
1166 part.transcript_offset = Some(batch_offset + range.start as i64);
1167 part
1168 })
1169 .collect()
1170}
1171
1172pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
1177 StreamEventRequest {
1178 protocol_version: req.protocol_version,
1179 tool: req.tool.clone(),
1180 event_type: StreamEventType::Transcript,
1181 session_id: req.session_id.clone(),
1182 timestamp: req.timestamp,
1183 hook_event_name: req.hook_event_name.clone(),
1184 tool_name: None,
1185 tool_use_id: None,
1186 tool_input: None,
1187 tool_response: None,
1188 tool_is_error: None,
1189 event_index: None,
1190 event_uuid: None,
1191 transcript_lines: None,
1192 transcript_offset: req.transcript_offset,
1193 model: req.model.clone(),
1194 cwd: req.cwd.clone(),
1195 final_stats: None,
1196 flow_id: req.flow_id.clone(),
1197 labels: req.labels.clone(),
1198 params: req.params.clone(),
1199 billing_mode: req.billing_mode,
1200 }
1201}
1202
1203#[allow(clippy::too_many_arguments)]
1224async fn deliver_subagent_transcripts(
1225 client: &crate::api_client::ApiClient,
1226 attribution: &Attribution,
1227 force: AttributionForce,
1228 template: &StreamEventRequest,
1229 transcript_path: &Path,
1230 session_dir: &Path,
1231 pending_path: &Path,
1232 mut send_failed: bool,
1233 deadline: std::time::Instant,
1234 wait_for_lock: Option<std::time::Instant>,
1235 warned: &mut bool,
1236) -> Result<(), Box<dyn std::error::Error>> {
1237 for file in crate::subagents::transcripts(transcript_path) {
1238 let offset_path = crate::subagents::offset_path(session_dir, &file);
1239 let lock = loop {
1241 match crate::subagents::try_lock(&offset_path) {
1242 Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
1243 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1244 }
1245 other => break other,
1246 }
1247 };
1248 let _lock = match lock {
1249 Ok(Some(lock)) => lock,
1250 Ok(None) => {
1251 if wait_for_lock.is_some() {
1252 eprintln!(
1253 "tracevault: warning: skipping subagent transcript {}: \
1254 another hook is still sending it",
1255 file.display()
1256 );
1257 }
1258 continue;
1259 }
1260 Err(e) => {
1261 eprintln!(
1262 "tracevault: warning: skipping subagent transcript {}: cannot lock: {e}",
1263 file.display()
1264 );
1265 continue;
1266 }
1267 };
1268 let (lines, start, end) = match crate::subagents::read_new_lines(&file, &offset_path) {
1269 Ok(read) => read,
1270 Err(e) => {
1271 eprintln!(
1272 "tracevault: warning: skipping subagent transcript {}: {e}",
1273 file.display()
1274 );
1275 continue;
1276 }
1277 };
1278 if end == start {
1279 continue;
1280 }
1281 let mut accepted = true;
1283 if !lines.is_empty() {
1284 let mut req = template.clone();
1285 req.transcript_lines = Some(lines);
1286 req.transcript_offset = Some(start);
1287 accepted = deliver_parts(
1288 client,
1289 attribution,
1290 force,
1291 split_into_parts(req),
1292 pending_path,
1293 send_failed,
1294 deadline,
1295 warned,
1296 )
1297 .await?;
1298 send_failed |= !accepted;
1299 }
1300 if accepted {
1301 crate::subagents::write_offset(&offset_path, end)?;
1302 }
1303 }
1304 Ok(())
1305}
1306
1307pub fn resolve_transcript_source(
1313 inline_records: Option<Vec<serde_json::Value>>,
1314 prior_offset: i64,
1315 file_result: (Vec<serde_json::Value>, i64, i64),
1316) -> (Vec<serde_json::Value>, i64, i64) {
1317 match inline_records {
1318 Some(records) => {
1319 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1320 (records, send, next)
1321 }
1322 None => file_result,
1323 }
1324}
1325
1326pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1335 lines.iter().find_map(|line| {
1336 let msg = line.get("message")?;
1337 if line.get("type").and_then(|v| v.as_str()) == Some("amp_message") {
1338 return msg
1339 .get("content")?
1340 .as_array()?
1341 .iter()
1342 .find(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result"))
1343 .map(|b| b.get("status").and_then(|v| v.as_str()) == Some("error"));
1344 }
1345 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1346 Some(
1347 msg.get("isError")
1348 .and_then(|v| v.as_bool())
1349 .unwrap_or(false),
1350 )
1351 } else {
1352 None
1353 }
1354 })
1355}
1356
1357pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1361 req.tool = Some(agent.tool_name().to_string());
1362 req.protocol_version = agent.protocol_version() as u32;
1363}
1364
1365const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1371
1372pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1377
1378const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1385
1386#[allow(clippy::too_many_arguments)]
1394async fn deliver_parts(
1395 client: &crate::api_client::ApiClient,
1396 attribution: &Attribution,
1397 force: AttributionForce,
1398 parts: Vec<StreamEventRequest>,
1399 pending_path: &Path,
1400 mut send_failed: bool,
1401 deadline: std::time::Instant,
1402 warned: &mut bool,
1403) -> Result<bool, Box<dyn std::error::Error>> {
1404 let mut all_accepted = true;
1405 for part in parts {
1406 send_failed = send_failed || std::time::Instant::now() >= deadline;
1407 if !send_failed {
1408 let send = send_stream_event(client, attribution, force, &part, warned);
1409 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1410 Ok(Ok(_)) => continue,
1411 Ok(Err(_)) | Err(_) => send_failed = true,
1412 }
1413 }
1414 all_accepted = false;
1415 append_pending(pending_path, &serde_json::to_string(&part)?)?;
1416 }
1417 Ok(all_accepted)
1418}
1419
1420pub const TRACING_MODE_ENV: &str = "VISDOM_TRACING_MODE";
1425
1426pub const GATEWAY_SESSION_ENV: &str = "VISDOM_GATEWAY_SESSION";
1429
1430pub fn captured_by_gateway(marker: Option<&str>) -> bool {
1436 marker.is_some_and(|m| m.trim() == "1")
1437}
1438
1439pub async fn run_stream(
1440 event_type: &str,
1441 agent: crate::agent::Agent,
1442) -> Result<(), Box<dyn std::error::Error>> {
1443 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1445 let mut input = String::new();
1446 io::stdin().read_to_string(&mut input)?;
1447 if captured_by_gateway(std::env::var(GATEWAY_SESSION_ENV).ok().as_deref()) {
1449 println!("{}", serde_json::to_string(&HookResponse::allow())?);
1450 return Ok(());
1451 }
1452 let hook_event = parse_hook_event(&input)?;
1453
1454 let hook_cwd = Path::new(&hook_event.cwd);
1476 let (resolved, cwd_session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1477 let storage_root =
1478 crate::session_state::storage_root(&crate::session_state::load(&hook_event.session_id));
1479 let session_dir = match &storage_root {
1480 Some(root) => root
1481 .join(".tracevault")
1482 .join("sessions")
1483 .join(&hook_event.session_id),
1484 None => cwd_session_dir,
1485 };
1486 if storage_root.is_none() && resolved.source == crate::paths::ProjectRootSource::Fallback {
1487 eprintln!(
1492 "tracevault: warning: could not resolve a git project root from {}; \
1493 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1494 that it runs inside the repository to keep sessions under the repo root.",
1495 hook_cwd.display()
1496 );
1497 }
1498 let project_root = resolved.root;
1499
1500 fs::create_dir_all(&session_dir)?;
1502
1503 let storage = storage_root.as_ref().unwrap_or(&project_root);
1509 let _ = crate::config::TracevaultConfig::ensure_gitignore(&storage.join(".tracevault"));
1510
1511 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1516 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1517 if storage_root.is_some() {
1520 let _ = crate::session_state::record_worktree(&session_dir, &worktree_top);
1521 }
1522
1523 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1527 if let Some(records) = &hook_event.transcript_records {
1532 let _ = record_inline_tool_calls(&session_dir, records);
1533 }
1534
1535 let target = SessionTarget {
1536 project_root,
1537 session_dir,
1538 worktree_top,
1539 };
1540 stream_event(
1541 hook_event,
1542 event_type,
1543 agent,
1544 &target,
1545 deadline,
1546 Sender::Hook,
1547 )
1548 .await?;
1549
1550 let response = HookResponse::allow();
1552 println!("{}", serde_json::to_string(&response)?);
1553
1554 Ok(())
1555}
1556
1557pub fn stream_event_type(event_type: &str) -> StreamEventType {
1559 match event_type {
1560 "notification" => StreamEventType::SessionStart,
1561 "stop" => StreamEventType::SessionEnd,
1563 "session-end" => StreamEventType::Transcript,
1567 _ => StreamEventType::ToolUse,
1568 }
1569}
1570
1571pub(crate) struct SessionTarget {
1575 pub project_root: std::path::PathBuf,
1576 pub session_dir: std::path::PathBuf,
1578 pub worktree_top: String,
1580}
1581
1582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1584pub(crate) enum Sender {
1585 Hook,
1588 CatchUp,
1593}
1594
1595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1597pub(crate) enum Sent {
1598 Accepted,
1600 Queued,
1602 Skipped,
1605}
1606
1607pub(crate) async fn stream_event(
1611 mut hook_event: tracevault_protocol::hooks::HookEvent,
1612 event_type: &str,
1613 agent: crate::agent::Agent,
1614 target: &SessionTarget,
1615 deadline: std::time::Instant,
1616 sender: Sender,
1617) -> Result<Sent, Box<dyn std::error::Error>> {
1618 let SessionTarget {
1619 project_root,
1620 session_dir,
1621 worktree_top,
1622 } = target;
1623 let hook_cwd = Path::new(&hook_event.cwd);
1624
1625 let event_uuid = uuid::Uuid::now_v7();
1630
1631 let transcript_path = Path::new(&hook_event.transcript_path);
1633 let offset_path = session_dir.join(".stream_offset");
1634 let sends_main = event_type != "subagent-stop";
1641 let (transcript_lines, start_offset, new_offset) = if sends_main {
1642 read_new_transcript_lines(transcript_path, &offset_path)?
1643 } else {
1644 (vec![], 0, 0)
1645 };
1646
1647 let is_inline = hook_event.transcript_records.is_some();
1664 let (transcript_lines, start_offset, new_offset) = if is_inline {
1665 let prior_offset: i64 = if offset_path.exists() {
1672 let content = fs::read_to_string(&offset_path)?;
1673 content
1674 .trim()
1675 .parse::<i64>()
1676 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1677 .max(0)
1678 } else {
1679 0
1680 };
1681 resolve_transcript_source(
1685 hook_event.transcript_records.take(),
1686 prior_offset,
1687 (transcript_lines, start_offset, new_offset),
1688 )
1689 } else {
1690 (transcript_lines, start_offset, new_offset)
1691 };
1692 let stream_event_type = stream_event_type(event_type);
1694
1695 let tool_is_error = hook_event
1700 .tool_use_id
1701 .as_deref()
1702 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1703 .or_else(|| inline_tool_is_error(&transcript_lines));
1704
1705 let config = crate::config::TracevaultConfig::try_load(project_root);
1715 let repo_uc = config
1719 .as_ref()
1720 .ok()
1721 .and_then(|opt| opt.as_ref())
1722 .and_then(|c| c.user_context.clone());
1723 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1724
1725 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1731 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1732
1733 let mut req = StreamEventRequest {
1734 protocol_version: 1,
1735 tool: Some("claude-code".to_string()),
1736 event_type: stream_event_type,
1737 session_id: hook_event.session_id.clone(),
1738 timestamp: chrono::Utc::now(),
1739 hook_event_name: Some(hook_event.hook_event_name.clone()),
1740 tool_name: hook_event.tool_name.clone(),
1741 tool_use_id: hook_event.tool_use_id.clone(),
1742 tool_input: hook_event.tool_input.clone(),
1743 tool_response: hook_event.tool_response.clone(),
1744 tool_is_error,
1745 event_index: None,
1746 event_uuid: Some(event_uuid),
1747 transcript_lines: None,
1748 transcript_offset: Some(start_offset),
1749 model: None,
1750 cwd: Some(hook_event.cwd.clone()),
1751 final_stats: None,
1752 flow_id: ctx_flow_id,
1753 labels: ctx_labels,
1754 params: ctx_params,
1755 billing_mode: (sender == Sender::Hook)
1756 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1757 };
1758
1759 stamp_agent(&mut req, agent);
1760 let subagent_template = transcript_template(&req);
1762 if !transcript_lines.is_empty() {
1763 req.transcript_lines = Some(transcript_lines);
1764 }
1765
1766 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
1768
1769 if let Err(e) = &config {
1778 return Err(format!("malformed .tracevault/config.toml: {e}").into());
1779 }
1780
1781 let session = crate::session_state::load(&hook_event.session_id);
1786 let bound = config
1787 .as_ref()
1788 .ok()
1789 .and_then(|opt| opt.as_ref())
1790 .and_then(crate::resolution::binding_from_config);
1791 let user_default = crate::user_default::load();
1792 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
1793 let config_project = config
1807 .as_ref()
1808 .ok()
1809 .and_then(|opt| opt.as_ref())
1810 .and_then(crate::resolution::project_from_config);
1811 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()), config_project);
1812 let capture_pid = capture_binding
1813 .as_ref()
1814 .and_then(crate::resolution::capture_project_id);
1815 let client = server_url
1825 .as_deref()
1826 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1827 let mut inferred = None;
1828 if binding.is_none() {
1829 if let Some(client) = &client {
1830 match inference_project(None, capture_pid) {
1831 Some(pid) => {
1832 if let Some(checkout) = crate::inferred_repo::event_checkout(
1833 hook_cwd,
1834 hook_event.tool_input.as_ref(),
1835 worktree_top,
1836 ) {
1837 inferred = crate::inferred_repo::infer(
1838 &hook_event.session_id,
1839 &checkout,
1840 pid,
1841 client,
1842 deadline,
1843 )
1844 .await;
1845 if inferred.is_some() && checkout != *worktree_top {
1849 let _ = crate::session_state::record_worktree(session_dir, &checkout);
1850 }
1851 }
1852 }
1853 None => {
1854 let auto = crate::auto_bind::bind_session(
1855 &hook_event.session_id,
1856 hook_cwd,
1857 client,
1858 deadline,
1859 )
1860 .await;
1861 if let Some(notice) = auto.notice {
1862 eprintln!("{notice}");
1863 }
1864 binding = auto.binding;
1865 }
1866 }
1867 }
1868 }
1869 let force = attribution_force(capture_binding.as_ref());
1876
1877 let Some(attribution) =
1885 attribution_with_inference(binding.as_ref(), capture_pid, inferred.as_ref())
1886 else {
1887 return Ok(Sent::Skipped);
1888 };
1889 match sender {
1893 Sender::Hook => {
1894 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
1895 }
1896 Sender::CatchUp => {
1897 let meta = session_metadata(session_dir);
1898 if !catch_up_may_send(meta.get("attribution"), &attribution) {
1899 return Ok(Sent::Skipped);
1900 }
1901 }
1902 }
1903
1904 let client = client.ok_or("server_url not configured")?;
1906
1907 let pending_path = pending_path_for(session_dir, &attribution);
1919 let adopted = if inferred.is_some() && binding.is_none() {
1920 None
1921 } else {
1922 adopted_project_queue(session_dir, &attribution)
1923 };
1924 if let Some(adopted) = adopted {
1925 adopt_queue(&adopted, &pending_path)?;
1926 }
1927 let pending_events = drain_pending(&pending_path)?;
1928
1929 let mut send_failed = false;
1930 let mut warned = false;
1934
1935 for (i, pending_json) in pending_events.iter().enumerate() {
1939 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1940 if std::time::Instant::now() >= deadline
1944 || !matches!(
1945 tokio::time::timeout_at(
1946 (deadline + IN_FLIGHT_GRACE).into(),
1947 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1948 )
1949 .await,
1950 Ok(Ok(_))
1951 )
1952 {
1953 for evt in &pending_events[i..] {
1960 append_pending(&pending_path, evt)?;
1961 }
1962 send_failed = true;
1963 break;
1964 }
1965 }
1966 }
1967
1968 let sends_event = sends_main
1973 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
1974 let all_accepted = if sends_event {
1975 deliver_parts(
1976 &client,
1977 &attribution,
1978 force,
1979 split_into_parts(req),
1980 &pending_path,
1981 send_failed,
1982 deadline,
1983 &mut warned,
1984 )
1985 .await?
1986 } else {
1987 true
1988 };
1989 if sends_main && (all_accepted || is_inline) {
2002 crate::subagents::write_offset(&offset_path, new_offset)?;
2003 }
2004
2005 if sender == Sender::Hook && agent == crate::agent::Agent::ClaudeCode {
2010 deliver_subagent_transcripts(
2011 &client,
2012 &attribution,
2013 force,
2014 &subagent_template,
2015 transcript_path,
2016 session_dir,
2017 &pending_path,
2018 send_failed || !all_accepted,
2019 deadline,
2020 matches!(event_type, "stop" | "subagent-stop" | "session-end")
2021 .then(|| deadline + FINAL_LOCK_WAIT),
2022 &mut warned,
2023 )
2024 .await?;
2025 }
2026
2027 Ok(if !send_failed && all_accepted {
2028 Sent::Accepted
2029 } else {
2030 Sent::Queued
2031 })
2032}
2033
2034#[cfg(test)]
2035mod tests {
2036 use super::*;
2037 use crate::api_client::AttributionMode;
2038 use crate::config::UserContext;
2039 use crate::context::{Context, EffectiveContext};
2040 use std::collections::BTreeMap;
2041
2042 #[test]
2043 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
2044 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
2045 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
2046 project,
2047 };
2048 let a = uuid::Uuid::from_u128(0xa);
2049 let b = uuid::Uuid::from_u128(0xb);
2050 let only = |project_id| Attribution::ProjectOnly { project_id };
2051
2052 let recorded = attribution_record(&repo(Some(a)));
2053 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
2054 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
2055 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
2056 let recorded = attribution_record(&only(a));
2057 assert!(catch_up_may_send(Some(&recorded), &only(a)));
2058 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
2059 assert!(catch_up_may_send(None, &repo(Some(b))));
2062 assert!(!catch_up_may_send(None, &only(a)));
2063 }
2064
2065 #[test]
2066 fn record_metadata_keeps_the_other_keys() {
2067 let dir = tempfile::tempdir().unwrap();
2068 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
2069 record_metadata(
2070 dir.path(),
2071 "attribution",
2072 serde_json::json!({"repo_id": "r"}),
2073 )
2074 .unwrap();
2075 let meta = session_metadata(dir.path());
2076 assert_eq!(meta["transcript_path"], "/t.jsonl");
2077 assert_eq!(meta["attribution"]["repo_id"], "r");
2078 }
2079
2080 #[test]
2081 fn hook_events_map_to_server_events() {
2082 assert_eq!(
2083 stream_event_type("notification"),
2084 StreamEventType::SessionStart
2085 );
2086 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
2089 assert_eq!(
2090 stream_event_type("session-end"),
2091 StreamEventType::Transcript
2092 );
2093 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
2094 assert_eq!(
2095 stream_event_type(event),
2096 StreamEventType::ToolUse,
2097 "{event}"
2098 );
2099 }
2100 }
2101
2102 #[test]
2105 fn disabled_user_context_resolves_to_none() {
2106 assert!(UserContext::Toggle(false).resolve().is_none());
2110 }
2111
2112 #[test]
2113 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
2114 let dir = tempfile::tempdir().unwrap();
2118 let effective = Context::effective(dir.path(), None);
2119 assert_eq!(effective, EffectiveContext::default());
2120 }
2121
2122 #[test]
2125 fn apply_context_stamps_all_fields() {
2126 let dir = tempfile::tempdir().unwrap();
2127 let mut params = BTreeMap::new();
2128 params.insert("env".to_string(), "prod".to_string());
2129 params.insert("region".to_string(), "eu-west-1".to_string());
2130
2131 let ctx = EffectiveContext {
2132 flow_id: Some("flow-xyz".to_string()),
2133 labels: vec!["backend".to_string(), "urgent".to_string()],
2134 params,
2135 };
2136
2137 let (flow_id, labels, params_out) = apply_context(ctx);
2138
2139 assert_eq!(flow_id, Some("flow-xyz".to_string()));
2140 assert_eq!(
2141 labels,
2142 Some(vec!["backend".to_string(), "urgent".to_string()])
2143 );
2144 let p = params_out.expect("params should be Some");
2145 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
2146 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
2147
2148 let written = Context {
2151 flow_id: Some("flow-xyz".to_string()),
2152 labels: vec!["backend".to_string(), "urgent".to_string()],
2153 params: {
2154 let mut m = BTreeMap::new();
2155 m.insert("env".to_string(), Some("prod".to_string()));
2156 m.insert("region".to_string(), Some("eu-west-1".to_string()));
2157 m
2158 },
2159 };
2160 let ctx_path = dir.path().join(".tracevault").join("context.json");
2161 written.save_to(&ctx_path).unwrap();
2162 let loaded = Context::load_from(&ctx_path);
2163 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
2164 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
2165 assert!(labels2.is_some());
2166 assert!(params2.is_some());
2167 }
2168
2169 #[test]
2172 fn apply_context_missing_file_all_none() {
2173 let dir = tempfile::tempdir().unwrap();
2174 let missing_path = dir.path().join(".tracevault").join("context.json");
2175 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
2177 assert!(flow_id.is_none(), "flow_id should be None");
2178 assert!(labels.is_none(), "labels should be None");
2179 assert!(params.is_none(), "params should be None");
2180 }
2181
2182 #[test]
2185 fn apply_context_empty_collections_are_none() {
2186 let ctx = EffectiveContext {
2187 flow_id: None,
2188 labels: vec![],
2189 params: BTreeMap::new(),
2190 };
2191 let (flow_id, labels, params) = apply_context(ctx);
2192 assert!(flow_id.is_none());
2193 assert!(
2194 labels.is_none(),
2195 "empty labels should be None, not Some([])"
2196 );
2197 assert!(
2198 params.is_none(),
2199 "empty params should be None, not Some({{}})"
2200 );
2201 }
2202
2203 #[test]
2206 fn apply_context_flow_id_only() {
2207 let ctx = EffectiveContext {
2208 flow_id: Some("my-flow".to_string()),
2209 labels: vec![],
2210 params: BTreeMap::new(),
2211 };
2212 let (flow_id, labels, params) = apply_context(ctx);
2213 assert_eq!(flow_id, Some("my-flow".to_string()));
2214 assert!(labels.is_none());
2215 assert!(params.is_none());
2216 }
2217
2218 use crate::test_helpers::{add_worktree, init_git_repo};
2225
2226 #[test]
2229 fn resolve_session_paths_primary_checkout() {
2230 let tmp = tempfile::tempdir().unwrap();
2231 let repo = tmp.path().join("repo");
2232 std::fs::create_dir_all(&repo).unwrap();
2233 init_git_repo(&repo);
2234 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
2236
2237 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
2238 let project_root = resolved.root;
2239
2240 assert_eq!(
2241 project_root.canonicalize().unwrap(),
2242 repo.canonicalize().unwrap(),
2243 "primary checkout: project_root must be repo root"
2244 );
2245 assert_eq!(
2246 session_dir.canonicalize().unwrap_or(session_dir.clone()),
2247 repo.join(".tracevault")
2248 .join("sessions")
2249 .join("sess-primary-123"),
2250 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
2251 );
2252 assert!(
2254 session_dir.starts_with(&repo),
2255 "session_dir must be under the primary repo root"
2256 );
2257 }
2258
2259 #[test]
2263 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
2264 let tmp = tempfile::tempdir().unwrap();
2265 let repo = tmp.path().join("repo");
2266 let wt = tmp.path().join("sibling-wt");
2268
2269 std::fs::create_dir_all(&repo).unwrap();
2270 init_git_repo(&repo);
2271 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
2273 add_worktree(&repo, &wt);
2274
2275 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
2276 let project_root = resolved.root;
2277
2278 assert_eq!(
2280 project_root.canonicalize().unwrap(),
2281 repo.canonicalize().unwrap(),
2282 "sibling worktree: project_root must be primary repo root (not worktree dir)"
2283 );
2284 assert!(
2286 session_dir.starts_with(&repo),
2287 "sibling worktree: session_dir must be under the PRIMARY repo root"
2288 );
2289 assert!(
2290 !session_dir.starts_with(&wt),
2291 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
2292 );
2293 assert!(
2294 session_dir.ends_with(
2295 std::path::Path::new(".tracevault")
2296 .join("sessions")
2297 .join("sess-sibling-456")
2298 ),
2299 "session_dir must end with .tracevault/sessions/<session_id>"
2300 );
2301 }
2302
2303 #[test]
2306 fn resolve_session_paths_non_git_fallback() {
2307 let tmp = tempfile::tempdir().unwrap();
2308 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
2310 let project_root = resolved.root;
2311
2312 assert_eq!(
2313 project_root,
2314 tmp.path(),
2315 "non-git: project_root must fall back to hook_cwd"
2316 );
2317 assert_eq!(
2318 session_dir,
2319 tmp.path()
2320 .join(".tracevault")
2321 .join("sessions")
2322 .join("sess-fallback-789"),
2323 "non-git: session_dir must be relative to the fallback root"
2324 );
2325 }
2326
2327 #[test]
2332 fn origin_marker_written_in_session_dir() {
2333 let tmp = tempfile::tempdir().unwrap();
2334 let repo = tmp.path().join("repo");
2335 std::fs::create_dir_all(&repo).unwrap();
2336 init_git_repo(&repo);
2337
2338 let session_dir = repo
2339 .join(".tracevault")
2340 .join("sessions")
2341 .join("test-sess-001");
2342 std::fs::create_dir_all(&session_dir).unwrap();
2343
2344 let hook_cwd = &repo;
2345 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2346 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2347
2348 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2349 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2350 assert_eq!(
2351 origin_content.trim(),
2352 expected.as_str(),
2353 "origin marker must contain the canonicalized worktree toplevel"
2354 );
2355 }
2356
2357 fn metadata(session_dir: &Path) -> serde_json::Value {
2358 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2359 .unwrap()
2360 }
2361
2362 #[test]
2363 fn record_transcript_path_writes_metadata_for_check() {
2364 let tmp = tempfile::tempdir().unwrap();
2365 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2366 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2367 }
2368
2369 #[test]
2370 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2371 let tmp = tempfile::tempdir().unwrap();
2372 std::fs::write(
2373 tmp.path().join("metadata.json"),
2374 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2375 )
2376 .unwrap();
2377 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2378 let m = metadata(tmp.path());
2379 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2380 assert_eq!(m["model"], "m");
2381 let leftovers = std::fs::read_dir(tmp.path())
2382 .unwrap()
2383 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2384 .count();
2385 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2386 }
2387
2388 #[test]
2389 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2390 let tmp = tempfile::tempdir().unwrap();
2391 record_transcript_path(tmp.path(), "").unwrap();
2392 assert!(!tmp.path().join("metadata.json").exists());
2393
2394 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2395 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2396 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2397 }
2398
2399 use crate::session_state::{RepoBinding, SessionState};
2402
2403 fn binding(id: &str) -> RepoBinding {
2404 RepoBinding {
2405 repo_id: id.into(),
2406 git_url: None,
2407 remote_id: None,
2408 codebase_name: None,
2409 updated_at: "t".into(),
2410 }
2411 }
2412
2413 #[test]
2416 fn resolve_stream_binding_uses_session_active_when_unbound() {
2417 let session = SessionState {
2418 active: Some(binding("session-repo")),
2419 subagents: HashMap::new(),
2420 ..Default::default()
2421 };
2422 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2423 assert_eq!(got.unwrap().repo_id, "session-repo");
2424 }
2425
2426 #[test]
2429 fn resolve_stream_binding_falls_back_to_bound_config() {
2430 let session = SessionState::default();
2431 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2432 assert_eq!(got.unwrap().repo_id, "bound-repo");
2433 }
2434
2435 #[test]
2438 fn resolve_stream_binding_none_when_nothing_resolves() {
2439 let session = SessionState::default();
2440 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2441 assert!(got.is_none());
2442 }
2443
2444 #[test]
2447 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2448 let session = SessionState {
2449 active: Some(binding("session-repo")),
2450 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2451 ..Default::default()
2452 };
2453 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2454 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2455 }
2456
2457 #[test]
2461 fn resolve_stream_binding_falls_back_to_user_default() {
2462 let session = SessionState::default();
2463 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2464 assert_eq!(got.unwrap().repo_id, "userdef");
2465 }
2466
2467 #[test]
2470 fn resolve_stream_binding_prefers_bound_over_user_default() {
2471 let session = SessionState::default();
2472 let got = resolve_stream_binding(
2473 &session,
2474 "/wt/x",
2475 Some(binding("bound")),
2476 Some(binding("userdef")),
2477 );
2478 assert_eq!(got.unwrap().repo_id, "bound");
2479 }
2480
2481 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2484 crate::session_state::RepoBinding {
2485 repo_id: repo_id.into(),
2486 git_url: None,
2487 remote_id: None,
2488 codebase_name: None,
2489 updated_at: String::new(),
2490 }
2491 }
2492
2493 #[test]
2497 fn attribution_falls_back_to_project_when_no_repo_binds() {
2498 let pid = uuid::Uuid::new_v4();
2499 assert_eq!(
2500 attribution_for(None, Some(pid)),
2501 Some(Attribution::ProjectOnly { project_id: pid })
2502 );
2503 }
2504
2505 #[test]
2507 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2508 assert_eq!(attribution_for(None, None), None);
2509 }
2510
2511 #[test]
2514 fn attribution_uses_repo_with_no_project_overlay() {
2515 let repo = uuid::Uuid::new_v4().to_string();
2516 let b = binding_with(&repo);
2517 assert_eq!(
2518 attribution_for(Some(&b), None),
2519 Some(Attribution::Repo {
2520 repo_id: repo,
2521 project: None
2522 })
2523 );
2524 }
2525
2526 #[test]
2529 fn attribution_overlays_project_on_repo() {
2530 let repo = uuid::Uuid::new_v4().to_string();
2531 let pid = uuid::Uuid::new_v4();
2532 let b = binding_with(&repo);
2533 assert_eq!(
2534 attribution_for(Some(&b), Some(pid)),
2535 Some(Attribution::Repo {
2536 repo_id: repo,
2537 project: Some(pid)
2538 })
2539 );
2540 }
2541
2542 #[test]
2545 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2546 let pid = uuid::Uuid::new_v4();
2547 let b = binding_with("../../escape");
2548 assert_eq!(
2549 attribution_for(Some(&b), Some(pid)),
2550 Some(Attribution::ProjectOnly { project_id: pid })
2551 );
2552 }
2553
2554 #[test]
2557 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2558 let b = binding_with("../../escape");
2559 assert_eq!(attribution_for(Some(&b), None), None);
2560 }
2561
2562 #[test]
2567 fn pending_file_name_for_a_repo_is_unchanged() {
2568 let repo = uuid::Uuid::new_v4().to_string();
2569 assert_eq!(
2570 Attribution::Repo {
2571 repo_id: repo.clone(),
2572 project: Some(uuid::Uuid::new_v4())
2573 }
2574 .pending_file_name(),
2575 format!("pending-{repo}.jsonl")
2576 );
2577 }
2578
2579 #[test]
2582 fn pending_file_name_for_a_project_is_distinct() {
2583 let pid = uuid::Uuid::new_v4();
2584 assert_eq!(
2585 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2586 format!("pending-project-{pid}.jsonl")
2587 );
2588 }
2589
2590 #[test]
2593 fn binding_repo_id_is_valid_accepts_real_uuid() {
2594 assert!(binding_repo_id_is_valid(
2595 "550e8400-e29b-41d4-a716-446655440000"
2596 ));
2597 }
2598
2599 #[test]
2600 fn binding_repo_id_is_valid_rejects_path_traversal() {
2601 assert!(!binding_repo_id_is_valid("../evil"));
2602 }
2603
2604 #[test]
2605 fn binding_repo_id_is_valid_rejects_empty() {
2606 assert!(!binding_repo_id_is_valid(""));
2607 }
2608
2609 #[test]
2610 fn binding_repo_id_is_valid_rejects_non_uuid() {
2611 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2612 }
2613
2614 #[test]
2617 fn stamp_agent_sets_tool_and_version() {
2618 use crate::agent::Agent;
2619 let mut req = StreamEventRequest {
2620 protocol_version: 1,
2621 tool: Some("claude-code".to_string()),
2622 event_type: StreamEventType::ToolUse,
2623 session_id: "s".into(),
2624 timestamp: chrono::Utc::now(),
2625 hook_event_name: None,
2626 tool_name: None,
2627 tool_use_id: None,
2628 tool_input: None,
2629 tool_response: None,
2630 tool_is_error: None,
2631 event_index: None,
2632 event_uuid: None,
2633 transcript_lines: None,
2634 transcript_offset: None,
2635 model: None,
2636 cwd: None,
2637 final_stats: None,
2638 flow_id: None,
2639 labels: None,
2640 params: None,
2641 billing_mode: None,
2642 };
2643 stamp_agent(&mut req, Agent::Codex);
2644 assert_eq!(req.tool.as_deref(), Some("codex"));
2645 assert_eq!(req.protocol_version, 2);
2646
2647 stamp_agent(&mut req, Agent::ClaudeCode);
2648 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2649 assert_eq!(req.protocol_version, 1);
2650 }
2651
2652 fn repo_attr(repo_id: &str) -> Attribution {
2655 Attribution::Repo {
2656 repo_id: repo_id.into(),
2657 project: None,
2658 }
2659 }
2660
2661 #[test]
2662 fn pending_path_is_repo_scoped() {
2663 let dir = std::path::Path::new("/tmp/sess");
2664 assert_eq!(
2665 pending_path_for(dir, &repo_attr("repo-a")),
2666 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2667 );
2668 assert_ne!(
2669 pending_path_for(dir, &repo_attr("repo-a")),
2670 pending_path_for(dir, &repo_attr("repo-b")),
2671 );
2672 }
2673
2674 #[test]
2677 fn pending_path_for_a_project_never_collides_with_a_repo() {
2678 let dir = std::path::Path::new("/tmp/sess");
2679 let pid = uuid::Uuid::from_u128(9);
2680 assert_eq!(
2681 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2682 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2683 );
2684 assert_ne!(
2685 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2686 pending_path_for(dir, &repo_attr(&pid.to_string())),
2687 );
2688 }
2689
2690 #[test]
2693 fn read_new_transcript_lines_empty_path_is_noop() {
2694 let dir = tempfile::tempdir().unwrap();
2698 let offset_path = dir.path().join(".stream_offset");
2699 let (lines, start_offset, end_offset) =
2700 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2701 assert!(
2702 lines.is_empty(),
2703 "empty path must yield no transcript lines"
2704 );
2705 assert_eq!(start_offset, 0);
2706 assert_eq!(end_offset, 0);
2707 }
2708
2709 #[test]
2713 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2714 let dir = tempfile::tempdir().unwrap();
2715 let transcript_path = dir.path().join("transcript.jsonl");
2716 let offset_path = dir.path().join(".stream_offset");
2717
2718 fs::write(
2719 &transcript_path,
2720 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2721 )
2722 .unwrap();
2723
2724 let (lines, start_offset, end_offset) =
2725 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2726 assert_eq!(lines.len(), 2);
2727 assert_eq!(start_offset, 0, "first read starts at byte 0");
2728 assert!(end_offset > 0);
2729
2730 fs::write(&offset_path, end_offset.to_string()).unwrap();
2731
2732 let mut f = OpenOptions::new()
2733 .append(true)
2734 .open(&transcript_path)
2735 .unwrap();
2736 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2737 drop(f);
2738
2739 let (lines2, start_offset2, end_offset2) =
2740 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2741 assert_eq!(lines2.len(), 1);
2742 assert_eq!(
2743 start_offset2, end_offset,
2744 "second read's start_offset must equal the first read's persisted end_offset"
2745 );
2746 assert!(end_offset2 > start_offset2);
2747 }
2748
2749 #[tokio::test]
2767 async fn capture_project_precedence_local_only() {
2768 use crate::session_state::{ProjectBinding, SessionState};
2769 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2770 let tmp = tempfile::tempdir().unwrap();
2771 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2772 _guard.set("XDG_CONFIG_HOME", tmp.path());
2773 _guard.set("HOME", tmp.path());
2774 _guard.remove("TRACEVAULT_PROJECT");
2775
2776 let pb = |id: &str| ProjectBinding {
2777 project_id: id.into(),
2778 project_name: "n".into(),
2779 updated_at: "".into(),
2780 forced_until: None,
2781 };
2782 let u = uuid::Uuid::from_u128;
2783 let s = SessionState {
2785 active_project: Some(pb(&u(2).to_string())),
2786 ..Default::default()
2787 };
2788 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(2)));
2789 let mut s = s;
2791 s.subagent_projects
2792 .insert("/wt".into(), pb(&u(1).to_string()));
2793 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(1)));
2794 assert_eq!(capture_project(&s, Some("/other"), None), Some(u(2)));
2796 assert_eq!(capture_project(&SessionState::default(), None, None), None);
2798 let bad = SessionState {
2800 active_project: Some(pb("not-a-uuid")),
2801 ..Default::default()
2802 };
2803 assert_eq!(capture_project(&bad, None, None), None);
2804 let path = crate::user_project_default::default_project_path().unwrap();
2806 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2807 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2808 assert_eq!(
2809 capture_project(&SessionState::default(), None, None),
2810 Some(u(3))
2811 );
2812 }
2813
2814 #[test]
2825 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2826 use crate::session_state::{ProjectBinding, SessionState};
2827 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2828 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2829 _guard.remove("TRACEVAULT_PROJECT");
2830 let pid = uuid::Uuid::from_u128(2);
2831 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2832 let s = SessionState {
2833 active_project: Some(ProjectBinding {
2834 project_id: pid.to_string(),
2835 project_name: "n".into(),
2836 updated_at: "".into(),
2837 forced_until: Some(future.clone()),
2838 }),
2839 ..Default::default()
2840 };
2841 let got = capture_binding(&s, Some("/wt"), None).expect("session-active binding resolves");
2842 assert_eq!(got.forced_until, Some(future));
2843 }
2844
2845 #[test]
2850 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2851 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2855
2856 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2857 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2858
2859 _guard.set("TRACEVAULT_PROJECT", uuid);
2860 let got = env_project_binding().expect("uuid form is honoured");
2861 assert_eq!(got.project_id, uuid);
2862
2863 _guard.set("TRACEVAULT_PROJECT", "my-project");
2864 assert!(
2865 env_project_binding().is_none(),
2866 "a name is ignored on the network-free capture path"
2867 );
2868
2869 _guard.remove("TRACEVAULT_PROJECT");
2870 assert!(env_project_binding().is_none());
2871 }
2872
2873 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2881 crate::session_state::ProjectBinding {
2882 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2883 project_name: "p".into(),
2884 updated_at: chrono::Utc::now().to_rfc3339(),
2885 forced_until: forced_until.map(str::to_string),
2886 }
2887 }
2888
2889 #[test]
2890 fn env_force_is_explicit_and_needs_no_expiry() {
2891 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2892 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2893 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2894
2895 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2896 }
2897
2898 #[test]
2899 fn absent_or_unrecognised_env_is_derived() {
2900 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2901 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2902
2903 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2904 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2905
2906 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2911 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2912 }
2913
2914 #[test]
2920 fn live_binding_force_is_explicit_without_env() {
2921 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2922 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2923 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2924
2925 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2926 let binding = forced_binding(Some(&future));
2927
2928 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2929 }
2930
2931 #[test]
2938 fn lapsed_binding_force_is_derived_without_env() {
2939 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2940 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2941 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2942
2943 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2944 let binding = forced_binding(Some(&past));
2945
2946 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2947 }
2948
2949 #[test]
2954 fn unparseable_forced_until_is_derived() {
2955 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2956 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2957 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2958
2959 let binding = forced_binding(Some("not-a-timestamp"));
2960
2961 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2962 }
2963
2964 #[test]
2971 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2972 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2973 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2974 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2975
2976 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2977 let binding = forced_binding(Some(&past));
2978
2979 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2980 }
2981
2982 #[tokio::test]
2995 async fn session_scoped_force_is_honoured_on_the_wire() {
2996 use crate::session_state::{ProjectBinding, SessionState};
2997
2998 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2999 let tmp = tempfile::tempdir().unwrap();
3000 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3001 _guard.set("XDG_CONFIG_HOME", tmp.path());
3005 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3006 _guard.remove("TRACEVAULT_PROJECT");
3010
3011 let pid = uuid::Uuid::from_u128(321);
3012 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3013 let session = SessionState {
3014 active_project: Some(ProjectBinding {
3015 project_id: pid.to_string(),
3016 project_name: "proj".into(),
3017 updated_at: "".into(),
3018 forced_until: Some(future),
3019 }),
3020 ..Default::default()
3021 };
3022 let capture_binding = capture_binding(&session, None, None);
3023
3024 let resp = ok_stream_response();
3025 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3026 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3027 let req = sample_stream_event_request();
3028 let mut warned = false;
3029
3030 let got = send_stream_event(
3031 &client,
3032 &Attribution::ProjectOnly { project_id: pid },
3033 attribution_force(capture_binding.as_ref()),
3034 &req,
3035 &mut warned,
3036 )
3037 .await
3038 .expect("send_stream_event must succeed");
3039 assert_eq!(got.status, "accepted");
3040
3041 let captured = rx
3042 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3043 .expect("no request captured");
3044 assert!(
3045 captured
3046 .to_lowercase()
3047 .contains("x-tracevault-project-attribution: explicit"),
3048 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
3049 );
3050 }
3051
3052 #[test]
3061 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
3062 use crate::session_state::{ProjectBinding, SessionState};
3063
3064 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3065 let tmp = tempfile::tempdir().unwrap();
3066 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3067 _guard.set("XDG_CONFIG_HOME", tmp.path());
3068 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3069
3070 let project_a = uuid::Uuid::from_u128(1);
3071 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3072 crate::user_project_default::save(&ProjectBinding {
3073 project_id: project_a.to_string(),
3074 project_name: "a".into(),
3075 updated_at: chrono::Utc::now().to_rfc3339(),
3076 forced_until: Some(future),
3077 })
3078 .unwrap();
3079
3080 let project_b = uuid::Uuid::from_u128(2);
3081 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
3082
3083 let capture_binding = capture_binding(&SessionState::default(), None, None);
3084 assert_eq!(
3085 capture_binding.as_ref().map(|b| b.project_id.as_str()),
3086 Some(project_b.to_string()).as_deref(),
3087 "TRACEVAULT_PROJECT must outrank the user-level default"
3088 );
3089
3090 assert_eq!(
3091 attribution_mode(capture_binding.as_ref()),
3092 AttributionMode::Derived,
3093 "a force on the user-default project must not leak onto a DIFFERENT, \
3094 higher-precedence project that never asked to be forced"
3095 );
3096 }
3097
3098 use std::io::BufReader;
3101 use std::net::TcpListener;
3102 use std::sync::mpsc;
3103 use std::thread;
3104 use std::time::{Duration, Instant};
3105
3106 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
3111
3112 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
3117 let deadline = Instant::now() + ACCEPT_DEADLINE;
3118 loop {
3119 match listener.accept() {
3120 Ok((stream, _)) => {
3121 let _ = stream.set_nonblocking(false);
3126 return Some(stream);
3127 }
3128 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
3129 if Instant::now() >= deadline {
3130 return None;
3131 }
3132 thread::sleep(Duration::from_millis(20));
3133 }
3134 Err(_) => return None,
3135 }
3136 }
3137 }
3138
3139 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
3143
3144 fn capture_request_and_respond(
3164 stream: std::net::TcpStream,
3165 tx: &mpsc::Sender<String>,
3166 response: &str,
3167 ) {
3168 let mut reader = BufReader::new(stream);
3169 let mut captured = String::new();
3170 let _ = reader.read_line(&mut captured);
3171 loop {
3172 let mut header = String::new();
3173 if reader.read_line(&mut header).unwrap_or(0) == 0 {
3174 break;
3175 }
3176 if header.trim().is_empty() {
3177 break;
3178 }
3179 captured.push_str(&header);
3180 }
3181 let _ = tx.send(captured);
3182 let mut stream = reader.into_inner();
3183 let _ = stream.write_all(response.as_bytes());
3184 let _ = stream.flush();
3185 }
3186
3187 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
3192 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3193 listener.set_nonblocking(true).unwrap();
3194 let addr = listener.local_addr().unwrap();
3195 let (tx, rx) = mpsc::channel();
3196 thread::spawn(move || {
3197 if let Some(stream) = accept_with_deadline(&listener) {
3198 capture_request_and_respond(stream, &tx, response);
3199 }
3200 });
3201 (format!("http://{addr}"), rx)
3202 }
3203
3204 fn ok_stream_response() -> String {
3205 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
3206 session_db_id: uuid::Uuid::nil(),
3207 event_db_id: Some(uuid::Uuid::nil()),
3208 status: "accepted".to_string(),
3209 })
3210 .unwrap();
3211 format!(
3212 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3213 body.len(),
3214 body
3215 )
3216 }
3217
3218 fn sample_stream_event_request() -> StreamEventRequest {
3219 StreamEventRequest {
3220 protocol_version: 2,
3221 tool: Some("claude-code".to_string()),
3222 event_type: StreamEventType::ToolUse,
3223 session_id: "sess-1".into(),
3224 timestamp: chrono::Utc::now(),
3225 hook_event_name: Some("PostToolUse".into()),
3226 tool_name: None,
3227 tool_use_id: None,
3228 tool_input: None,
3229 tool_response: None,
3230 tool_is_error: None,
3231 event_index: None,
3232 event_uuid: None,
3233 transcript_lines: None,
3234 transcript_offset: None,
3235 model: None,
3236 cwd: None,
3237 final_stats: None,
3238 flow_id: None,
3239 labels: None,
3240 params: None,
3241 billing_mode: None,
3242 }
3243 }
3244
3245 #[tokio::test]
3250 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
3251 use crate::session_state::{ProjectBinding, SessionState};
3252
3253 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3257 let tmp = tempfile::tempdir().unwrap();
3258 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3259 _guard.set("XDG_CONFIG_HOME", tmp.path());
3260 _guard.remove("TRACEVAULT_PROJECT");
3265 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3266
3267 let pid = uuid::Uuid::from_u128(99);
3268 let session = SessionState {
3269 active_project: Some(ProjectBinding {
3270 project_id: pid.to_string(),
3271 project_name: "proj".into(),
3272 updated_at: "".into(),
3273 forced_until: None,
3274 }),
3275 ..Default::default()
3276 };
3277 let capture_binding = capture_binding(&session, None, None);
3278 let capture_pid = capture_binding
3279 .as_ref()
3280 .and_then(crate::resolution::capture_project_id);
3281 assert_eq!(capture_pid, Some(pid));
3282
3283 let resp = ok_stream_response();
3284 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3285 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3286 let req = sample_stream_event_request();
3287
3288 let mut warned = false;
3289 let got = send_stream_event(
3290 &client,
3291 &Attribution::Repo {
3292 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3293 project: capture_pid,
3294 },
3295 attribution_force(capture_binding.as_ref()),
3296 &req,
3297 &mut warned,
3298 )
3299 .await
3300 .expect("send_stream_event must succeed");
3301 assert_eq!(got.status, "accepted");
3302
3303 let line = rx
3304 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3305 .expect("no request captured");
3306 assert!(
3307 line.starts_with(&format!(
3308 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
3309 )),
3310 "an active project binding must route to the project-scoped endpoint, got: {line}"
3311 );
3312 assert!(
3318 line.to_lowercase()
3319 .contains("x-tracevault-project-attribution: derived"),
3320 "got: {line}"
3321 );
3322 }
3323
3324 #[tokio::test]
3329 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
3330 use crate::session_state::SessionState;
3331
3332 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3333 let tmp = tempfile::tempdir().unwrap();
3334 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3335 _guard.set("XDG_CONFIG_HOME", tmp.path());
3340 _guard.remove("TRACEVAULT_PROJECT");
3341
3342 let capture_binding = capture_binding(&SessionState::default(), None, None);
3343 assert_eq!(capture_binding, None);
3344
3345 let resp = ok_stream_response();
3346 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3347 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3348 let req = sample_stream_event_request();
3349
3350 let mut warned = false;
3351 let got = send_stream_event(
3352 &client,
3353 &Attribution::Repo {
3354 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3355 project: None,
3356 },
3357 attribution_force(capture_binding.as_ref()),
3358 &req,
3359 &mut warned,
3360 )
3361 .await
3362 .expect("send_stream_event must succeed");
3363 assert_eq!(got.status, "accepted");
3364
3365 let line = rx
3366 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3367 .expect("no request captured");
3368 assert!(
3369 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3370 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3371 );
3372 }
3373
3374 fn spawn_n_capturing_requests(
3385 responses: Vec<&'static str>,
3386 ) -> (String, mpsc::Receiver<String>) {
3387 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3388 listener.set_nonblocking(true).unwrap();
3389 let addr = listener.local_addr().unwrap();
3390 let (tx, rx) = mpsc::channel();
3391 thread::spawn(move || {
3392 for response in responses {
3393 let Some(stream) = accept_with_deadline(&listener) else {
3398 break;
3399 };
3400 capture_request_and_respond(stream, &tx, response);
3401 }
3402 });
3407 (format!("http://{addr}"), rx)
3408 }
3409
3410 #[tokio::test]
3417 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3418 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3419 let resp_400 = format!(
3420 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3421 body_400.len(),
3422 body_400
3423 );
3424 let resp_200 = ok_stream_response();
3425
3426 let (base, rx) = spawn_n_capturing_requests(vec![
3427 Box::leak(resp_400.into_boxed_str()),
3428 Box::leak(resp_200.into_boxed_str()),
3429 ]);
3430 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3431 let req = sample_stream_event_request();
3432 let pid = uuid::Uuid::from_u128(42);
3433
3434 let mut warned = false;
3435 let err = send_stream_event(
3436 &client,
3437 &Attribution::Repo {
3438 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3439 project: Some(pid),
3440 },
3441 attribution_force(None),
3442 &req,
3443 &mut warned,
3444 )
3445 .await
3446 .expect_err("a refused declared project must be an error, not a silent fallback");
3447 assert!(
3448 err.to_string().contains("400"),
3449 "propagated error must reflect the status, got: {err}"
3450 );
3451 assert!(
3452 warned,
3453 "the refusal must be printed (gated on `warned`) so it is visible"
3454 );
3455
3456 let first = rx
3457 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3458 .expect("no first request captured");
3459 assert!(
3460 first.contains(&format!("/projects/{pid}/stream")),
3461 "first request must hit the project-scoped endpoint, got: {first}"
3462 );
3463 assert!(
3464 first.contains("repo_id="),
3465 "first request must carry repo_id, got: {first}"
3466 );
3467
3468 assert!(
3469 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3470 "no second (repo-scoped fallback) request must be sent"
3471 );
3472 }
3473
3474 #[tokio::test]
3477 async fn send_stream_event_errors_on_403_without_fallback() {
3478 let body_403 = "forbidden";
3479 let resp_403 = format!(
3480 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3481 body_403.len(),
3482 body_403
3483 );
3484 let resp_200 = ok_stream_response();
3485
3486 let (base, rx) = spawn_n_capturing_requests(vec![
3487 Box::leak(resp_403.into_boxed_str()),
3488 Box::leak(resp_200.into_boxed_str()),
3489 ]);
3490 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3491 let req = sample_stream_event_request();
3492 let pid = uuid::Uuid::from_u128(43);
3493
3494 let mut warned = false;
3495 let err = send_stream_event(
3496 &client,
3497 &Attribution::Repo {
3498 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3499 project: Some(pid),
3500 },
3501 attribution_force(None),
3502 &req,
3503 &mut warned,
3504 )
3505 .await
3506 .expect_err("a refused declared project must be an error, not a silent fallback");
3507 assert!(
3508 err.to_string().contains("403"),
3509 "propagated error must reflect the status, got: {err}"
3510 );
3511 assert!(
3512 warned,
3513 "the refusal must be printed (gated on `warned`) so it is visible"
3514 );
3515
3516 let first = rx
3517 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3518 .expect("no first request captured");
3519 assert!(
3520 first.contains(&format!("/projects/{pid}/stream")),
3521 "first request must hit the project-scoped endpoint, got: {first}"
3522 );
3523 assert!(
3524 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3525 "no second (repo-scoped fallback) request must be sent"
3526 );
3527 }
3528
3529 #[tokio::test]
3534 async fn refused_error_is_printed_once_per_invocation() {
3535 let body_400 = "not a member";
3536 let resp_400 = || {
3537 format!(
3538 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3539 body_400.len(),
3540 body_400
3541 )
3542 };
3543 let (base, _rx) = spawn_n_capturing_requests(vec![
3544 Box::leak(resp_400().into_boxed_str()),
3545 Box::leak(resp_400().into_boxed_str()),
3546 ]);
3547 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3548 let req = sample_stream_event_request();
3549 let pid = uuid::Uuid::from_u128(44);
3550 let attribution = Attribution::Repo {
3551 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3552 project: Some(pid),
3553 };
3554
3555 let mut warned = false;
3556 assert!(
3557 send_stream_event(
3558 &client,
3559 &attribution,
3560 attribution_force(None),
3561 &req,
3562 &mut warned
3563 )
3564 .await
3565 .is_err(),
3566 "a refused declared project must be an error"
3567 );
3568 assert!(warned, "the flag must be set after the first refusal");
3569
3570 assert!(
3571 send_stream_event(
3572 &client,
3573 &attribution,
3574 attribution_force(None),
3575 &req,
3576 &mut warned
3577 )
3578 .await
3579 .is_err(),
3580 "a second refusal must also be an error"
3581 );
3582 assert!(warned, "the flag stays set across the shared invocation");
3583 }
3584
3585 #[tokio::test]
3597 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3598 let body_403 = "forbidden";
3599 let resp_403 = format!(
3600 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3601 body_403.len(),
3602 body_403
3603 );
3604 let resp_200 = ok_stream_response();
3605
3606 let (base, rx) = spawn_n_capturing_requests(vec![
3607 Box::leak(resp_403.into_boxed_str()),
3608 Box::leak(resp_200.into_boxed_str()),
3609 ]);
3610 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3611 let req = sample_stream_event_request();
3612 let pid = uuid::Uuid::from_u128(42);
3613
3614 let forced = crate::session_state::ProjectBinding {
3617 project_id: pid.to_string(),
3618 project_name: "forced".into(),
3619 updated_at: "".into(),
3620 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3621 };
3622
3623 let mut warned = false;
3624 let err = send_stream_event(
3625 &client,
3626 &Attribution::Repo {
3627 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3628 project: Some(pid),
3629 },
3630 attribution_force(Some(&forced)),
3631 &req,
3632 &mut warned,
3633 )
3634 .await
3635 .expect_err("a refused force must be an error, not a silent fallback");
3636 assert!(
3637 err.to_string().contains("403"),
3638 "propagated error must reflect the status, got: {err}"
3639 );
3640 assert!(warned, "the refusal must be printed exactly once");
3641
3642 let first = rx
3643 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3644 .expect("no first request captured");
3645 assert!(
3646 first.contains(&format!("/projects/{pid}/stream")),
3647 "first request must hit the project-scoped endpoint, got: {first}"
3648 );
3649 assert!(
3650 first
3651 .to_lowercase()
3652 .contains("x-tracevault-project-attribution: explicit"),
3653 "the refused send must have DECLARED explicit — this is the mode \
3654 `refused_error` is handed: {first}"
3655 );
3656
3657 assert!(
3658 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3659 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3660 );
3661 }
3662
3663 #[tokio::test]
3672 async fn send_stream_event_project_only_omits_repo_id() {
3673 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3674 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3675 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3676
3677 let resp = ok_stream_response();
3678 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3679 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3680 let req = sample_stream_event_request();
3681 let pid = uuid::Uuid::from_u128(11);
3682
3683 let mut warned = false;
3684 let got = send_stream_event(
3685 &client,
3686 &Attribution::ProjectOnly { project_id: pid },
3687 attribution_force(None),
3688 &req,
3689 &mut warned,
3690 )
3691 .await
3692 .expect("a repo-less project send must succeed");
3693 assert_eq!(got.status, "accepted");
3694
3695 let line = rx
3696 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3697 .expect("no request captured");
3698 assert!(
3699 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3700 "expected a bare project path with no query string, got: {line}"
3701 );
3702 assert!(
3703 line.to_lowercase()
3704 .contains("x-tracevault-project-attribution: derived"),
3705 "with no forced binding, the header must declare `derived`, got: {line}"
3706 );
3707 assert!(
3708 !warned,
3709 "a repo-less send has no fallback and must not warn about one"
3710 );
3711 }
3712
3713 #[tokio::test]
3720 async fn send_stream_event_project_only_buffers_on_scoping_4xx() {
3721 let body = "no such project";
3722 let resp_404 = format!(
3723 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3724 body.len(),
3725 body
3726 );
3727 let (base, rx) = spawn_n_capturing_requests(vec![
3734 Box::leak(resp_404.clone().into_boxed_str()),
3735 Box::leak(resp_404.into_boxed_str()),
3736 ]);
3737 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3738 let req = sample_stream_event_request();
3739 let pid = uuid::Uuid::from_u128(12);
3740
3741 let mut warned = false;
3742 let err = send_stream_event(
3743 &client,
3744 &Attribution::ProjectOnly { project_id: pid },
3745 attribution_force(None),
3746 &req,
3747 &mut warned,
3748 )
3749 .await
3750 .expect_err("a refused repo-less send must propagate so the caller buffers it");
3751 assert_eq!(
3752 deterministic_client_error_kind(err.as_ref()),
3753 Some(ClientErrorKind::Scoping),
3754 "the original 404 must propagate unchanged, got: {err}"
3755 );
3756 assert!(warned, "the refusal is printed (once per invocation)");
3757
3758 let first = rx
3759 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3760 .expect("no request captured");
3761 assert!(
3762 first.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3763 "must hit the bare project-scoped endpoint, got: {first}"
3764 );
3765 assert!(
3766 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3767 "a repo-less send must make exactly one request — no fallback exists"
3768 );
3769 }
3770
3771 #[test]
3775 fn refused_project_only_error_wording() {
3776 let pid = uuid::Uuid::from_u128(0x55);
3777 let scoping =
3778 refused_project_only_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3779 assert!(scoping.starts_with("tracevault: error:"), "{scoping}");
3780 assert!(scoping.contains(&pid.to_string()), "{scoping}");
3781 assert!(scoping.contains("queued"), "{scoping}");
3782 assert!(!scoping.contains("DROPPED"), "{scoping}");
3783 assert!(!scoping.contains("this repo"), "{scoping}");
3784 assert!(scoping.contains("tracevault repo switch"), "{scoping}");
3785
3786 let forbidden = refused_project_only_error(
3787 pid,
3788 &ClientErrorKind::Forbidden,
3789 AttributionForce::default(),
3790 );
3791 assert!(forbidden.contains("(403)"), "{forbidden}");
3792 assert!(forbidden.contains("queued"), "{forbidden}");
3793 assert!(!forbidden.contains("FORCE"), "derived send: {forbidden}");
3794
3795 let forced = AttributionForce {
3796 env: true,
3797 binding: false,
3798 };
3799 let explicit = refused_project_only_error(pid, &ClientErrorKind::Forbidden, forced);
3800 assert!(
3801 explicit.contains("FORCE itself"),
3802 "an explicit 403 must name the force, like the repo-scoped line: {explicit}"
3803 );
3804 assert!(
3805 !refused_project_only_error(pid, &ClientErrorKind::Scoping, forced)
3806 .contains("FORCE itself"),
3807 "a Scoping refusal never ran the force gate"
3808 );
3809 }
3810
3811 #[test]
3814 fn recording_line_names_each_attribution_shape() {
3815 let pid = uuid::Uuid::from_u128(0x99);
3816 let repo = "11111111-1111-1111-1111-111111111111".to_string();
3817 let only = recording_line(Some(&Attribution::ProjectOnly { project_id: pid }));
3818 assert!(only.starts_with("recording: project "), "{only}");
3819 assert!(
3820 only.contains(&pid.to_string()) && only.contains("no repo"),
3821 "{only}"
3822 );
3823 let both = recording_line(Some(&Attribution::Repo {
3824 repo_id: repo.clone(),
3825 project: Some(pid),
3826 }));
3827 assert!(
3828 both.contains(&repo) && both.contains(&pid.to_string()),
3829 "{both}"
3830 );
3831 let deduced = recording_line(Some(&Attribution::Repo {
3832 repo_id: repo.clone(),
3833 project: None,
3834 }));
3835 assert!(
3836 deduced.contains(&repo) && deduced.contains("deduces"),
3837 "{deduced}"
3838 );
3839 let none = recording_line(None);
3840 assert!(none.starts_with("recording: nothing"), "{none}");
3841 }
3842
3843 fn repo_binding(id: &str) -> crate::session_state::RepoBinding {
3844 crate::session_state::RepoBinding {
3845 repo_id: id.into(),
3846 git_url: None,
3847 remote_id: None,
3848 codebase_name: None,
3849 updated_at: "t".into(),
3850 }
3851 }
3852
3853 fn inferring_session(
3855 pid: uuid::Uuid,
3856 checkout: &str,
3857 repo: &str,
3858 ) -> crate::session_state::SessionState {
3859 let mut state = crate::session_state::SessionState {
3860 active_project: Some(crate::session_state::ProjectBinding {
3861 project_id: pid.to_string(),
3862 project_name: "p".into(),
3863 updated_at: "t".into(),
3864 forced_until: None,
3865 }),
3866 ..Default::default()
3867 };
3868 state.inferred_repos.insert(
3869 checkout.into(),
3870 crate::session_state::InferredRepo {
3871 project_id: pid.to_string(),
3872 retry_after: None,
3873 repo: Some(repo_binding(repo)),
3874 },
3875 );
3876 state
3877 }
3878
3879 #[test]
3882 fn attribution_with_inference_never_overrides_a_binding() {
3883 let pid = uuid::Uuid::from_u128(0x1258);
3884 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3885 let inferred = repo_binding("22222222-2222-2222-2222-222222222222");
3886 let repo = |id: &str| Attribution::Repo {
3887 repo_id: id.into(),
3888 project: Some(pid),
3889 };
3890
3891 assert_eq!(
3892 attribution_with_inference(None, Some(pid), Some(&inferred)),
3893 Some(repo(&inferred.repo_id))
3894 );
3895 assert_eq!(
3896 attribution_with_inference(Some(&bound), Some(pid), Some(&inferred)),
3897 Some(repo(&bound.repo_id))
3898 );
3899 let corrupt = repo_binding("not-a-uuid");
3902 assert_eq!(
3903 attribution_with_inference(Some(&corrupt), Some(pid), Some(&inferred)),
3904 Some(Attribution::ProjectOnly { project_id: pid })
3905 );
3906 assert_eq!(
3908 attribution_with_inference(None, None, Some(&inferred)),
3909 None
3910 );
3911 assert_eq!(
3912 attribution_with_inference(None, Some(pid), Some(&corrupt)),
3913 Some(Attribution::ProjectOnly { project_id: pid })
3914 );
3915 }
3916
3917 #[test]
3920 fn recording_attribution_labels_an_inferred_repo() {
3921 let pid = uuid::Uuid::from_u128(0x1258);
3922 let repo = "22222222-2222-2222-2222-222222222222";
3923 let state = inferring_session(pid, "/umbrella/child", repo);
3924
3925 let here = recording_attribution_for(&state, "/umbrella/child", None, None, None);
3926 assert_eq!(
3927 here.attribution,
3928 Some(Attribution::Repo {
3929 repo_id: repo.into(),
3930 project: Some(pid)
3931 })
3932 );
3933 assert_eq!(here.inferred_from.as_deref(), Some("/umbrella/child"));
3934 let line = recording_line_for(&here);
3935 assert!(
3936 line.contains(repo) && line.contains("inferred from the checkout /umbrella/child"),
3937 "{line}"
3938 );
3939
3940 let elsewhere = recording_attribution_for(&state, "/umbrella", None, None, None);
3941 assert_eq!(
3942 elsewhere.attribution,
3943 Some(Attribution::ProjectOnly { project_id: pid })
3944 );
3945 assert_eq!(elsewhere.inferred_from, None);
3946 assert_eq!(
3947 recording_line_for(&elsewhere),
3948 recording_line(elsewhere.attribution.as_ref())
3949 );
3950
3951 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3953 let explicit =
3954 recording_attribution_for(&state, "/umbrella/child", Some(bound.clone()), None, None);
3955 assert_eq!(
3956 explicit.attribution,
3957 Some(Attribution::Repo {
3958 repo_id: bound.repo_id,
3959 project: Some(pid)
3960 })
3961 );
3962 assert_eq!(explicit.inferred_from, None);
3963
3964 let mut from_config = state.clone();
3967 from_config.active_project = None;
3968 let workspace = crate::session_state::ProjectBinding {
3969 project_id: pid.to_string(),
3970 project_name: String::new(),
3971 updated_at: String::new(),
3972 forced_until: None,
3973 };
3974 let via_config =
3975 recording_attribution_for(&from_config, "/umbrella/child", None, None, Some(workspace));
3976 assert_eq!(via_config.inferred_from.as_deref(), Some("/umbrella/child"));
3977 }
3978
3979 #[test]
3980 fn adopt_queue_puts_the_older_queue_first_and_removes_it() {
3981 let dir = tempfile::tempdir().unwrap();
3982 let from = dir.path().join("pending-project-x.jsonl");
3983 let into = dir.path().join("pending-r.jsonl");
3984 std::fs::write(&from, "a1\na2").unwrap(); std::fs::write(&into, "r1\n").unwrap();
3986 adopt_queue(&from, &into).unwrap();
3987 assert!(!from.exists());
3988 assert_eq!(drain_pending(&into).unwrap(), vec!["a1", "a2", "r1"]);
3989 assert!(
3990 !dir.path().join("pending-r.jsonl.adopting").exists(),
3991 "no temp file left behind"
3992 );
3993 }
3994
3995 #[test]
3996 fn adopt_queue_without_a_source_is_a_no_op() {
3997 let dir = tempfile::tempdir().unwrap();
3998 let into = dir.path().join("pending-r.jsonl");
3999 std::fs::write(&into, "r1\n").unwrap();
4000 adopt_queue(&dir.path().join("absent.jsonl"), &into).unwrap();
4001 assert_eq!(drain_pending(&into).unwrap(), vec!["r1"]);
4002 }
4003
4004 #[test]
4007 fn adopt_queue_failure_leaves_the_source_intact() {
4008 let dir = tempfile::tempdir().unwrap();
4009 let from = dir.path().join("pending-project-x.jsonl");
4010 let into = dir.path().join("pending-r.jsonl");
4011 std::fs::write(&from, "a1\n").unwrap();
4012 std::fs::create_dir(&into).unwrap(); assert!(adopt_queue(&from, &into).is_err());
4014 assert_eq!(std::fs::read_to_string(&from).unwrap(), "a1\n");
4015 }
4016
4017 #[test]
4018 fn adopted_project_queue_only_for_the_same_project() {
4019 let dir = Path::new("/tmp/sess");
4020 let pid = uuid::Uuid::from_u128(0x77);
4021 let repo_id = "11111111-1111-1111-1111-111111111111".to_string();
4022 assert_eq!(
4023 adopted_project_queue(
4024 dir,
4025 &Attribution::Repo {
4026 repo_id: repo_id.clone(),
4027 project: Some(pid),
4028 }
4029 ),
4030 Some(dir.join(format!("pending-project-{pid}.jsonl")))
4031 );
4032 assert_eq!(
4033 adopted_project_queue(
4034 dir,
4035 &Attribution::Repo {
4036 repo_id,
4037 project: None,
4038 }
4039 ),
4040 None,
4041 "with no declared project the server deduces one; adopting would re-attribute"
4042 );
4043 assert_eq!(
4044 adopted_project_queue(dir, &Attribution::ProjectOnly { project_id: pid }),
4045 None,
4046 "a project-only target already drains its own queue"
4047 );
4048 }
4049
4050 #[tokio::test]
4054 async fn send_stream_event_project_only_buffers_on_403() {
4055 let body = "forbidden";
4056 let resp_403 = format!(
4057 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4058 body.len(),
4059 body
4060 );
4061 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
4062 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4063 let req = sample_stream_event_request();
4064
4065 let mut warned = false;
4066 let err = send_stream_event(
4067 &client,
4068 &Attribution::ProjectOnly {
4069 project_id: uuid::Uuid::from_u128(13),
4070 },
4071 attribution_force(None),
4072 &req,
4073 &mut warned,
4074 )
4075 .await
4076 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
4077 assert!(
4078 err.to_string().contains("403"),
4079 "propagated error must reflect the status, got: {err}"
4080 );
4081 }
4082
4083 #[tokio::test]
4088 async fn send_stream_event_does_not_fall_back_on_transient_503() {
4089 let body_503 = "internal error";
4090 let resp_503 = format!(
4091 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4092 body_503.len(),
4093 body_503
4094 );
4095 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
4096 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4097 let req = sample_stream_event_request();
4098 let pid = uuid::Uuid::from_u128(7);
4099
4100 let mut warned = false;
4101 let err = send_stream_event(
4102 &client,
4103 &Attribution::Repo {
4104 repo_id: "11111111-1111-1111-1111-111111111111".into(),
4105 project: Some(pid),
4106 },
4107 attribution_force(None),
4108 &req,
4109 &mut warned,
4110 )
4111 .await
4112 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
4113 assert!(
4114 err.to_string().contains("503"),
4115 "propagated error must reflect the transient status, got: {err}"
4116 );
4117 assert!(
4118 deterministic_client_error_kind(err.as_ref()).is_none(),
4119 "a 503 must not be classified as a deterministic client error"
4120 );
4121
4122 let first = rx
4123 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4124 .expect("no request captured");
4125 assert!(
4126 first.contains(&format!("/projects/{pid}/stream")),
4127 "must hit the project-scoped endpoint, got: {first}"
4128 );
4129
4130 assert!(
4137 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
4138 "no second (fallback) request should have been sent for a transient error"
4139 );
4140 }
4141
4142 #[test]
4146 fn a_403_is_classified_apart_from_the_scoping_statuses() {
4147 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
4148 assert_eq!(
4149 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
4150 Some(ClientErrorKind::Forbidden)
4151 );
4152 for scoping in [
4153 "Stream failed (400 Bad Request): {}",
4154 "Stream failed (404 Not Found): {}",
4155 "Stream failed (409 Conflict): {}",
4156 ] {
4157 assert_eq!(
4158 deterministic_client_error_kind(err(scoping).as_ref()),
4159 Some(ClientErrorKind::Scoping),
4160 "{scoping}"
4161 );
4162 }
4163 for transient in [
4166 "Stream failed (401 Unauthorized): {}",
4167 "Stream failed (503 Service Unavailable): {}",
4168 "error sending request for url (http://x/stream)",
4169 ] {
4170 assert_eq!(
4171 deterministic_client_error_kind(err(transient).as_ref()),
4172 None,
4173 "{transient}"
4174 );
4175 }
4176 }
4177
4178 #[test]
4183 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
4184 let pid = uuid::Uuid::from_u128(7);
4185
4186 let forbidden = refused_error(
4187 pid,
4188 &ClientErrorKind::Forbidden,
4189 AttributionForce::default(),
4190 );
4191 assert!(forbidden.contains("403"), "{forbidden}");
4192 assert!(
4193 forbidden.contains("no `tracevault` grant in Control Plane"),
4194 "must offer the missing-role explanation: {forbidden}"
4195 );
4196 assert!(
4197 forbidden.contains("no `Operator` role on it"),
4198 "must still offer the project explanation: {forbidden}"
4199 );
4200 assert!(
4201 forbidden.starts_with("tracevault: error:"),
4202 "a refusal is an error, not a warning: {forbidden}"
4203 );
4204 assert!(forbidden.contains(&pid.to_string()));
4205
4206 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
4209 assert!(scoping.contains("project switch"), "{scoping}");
4210 assert!(
4211 !scoping.contains("`tracevault` grant"),
4212 "the scoping case must not mention the `tracevault` grant: {scoping}"
4213 );
4214
4215 for s in [&forbidden, &scoping] {
4216 assert!(s.contains("--user"), "must name the --user fix: {s}");
4219 assert!(
4220 s.contains("user_project.toml"),
4221 "must name the machine-wide default's file: {s}"
4222 );
4223 assert!(
4224 !s.contains("repo deduction"),
4225 "must never describe re-attribution to another project: {s}"
4226 );
4227 assert!(
4228 !s.contains("Attributing via"),
4229 "must never claim the event was re-attributed: {s}"
4230 );
4231 }
4232 }
4233
4234 #[test]
4245 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
4246 let pid = uuid::Uuid::from_u128(7);
4247
4248 let explicit = refused_error(
4249 pid,
4250 &ClientErrorKind::Forbidden,
4251 AttributionForce {
4252 env: false,
4253 binding: true,
4254 },
4255 );
4256 assert!(
4257 explicit.contains("FORCE"),
4258 "the refusal of the force itself must be named: {explicit}"
4259 );
4260 assert!(
4261 explicit.contains("Operator"),
4262 "must name the grant forcing requires: {explicit}"
4263 );
4264 assert!(
4265 explicit.contains("Control Plane"),
4266 "must name the identity forcing requires: {explicit}"
4267 );
4268 assert!(
4272 explicit.contains("`tracevault` grant")
4273 && explicit.contains("no `Operator` role on it"),
4274 "the membership causes must still be named: {explicit}"
4275 );
4276 assert!(
4279 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
4280 "must never claim the event was re-attributed: {explicit}"
4281 );
4282
4283 let derived = refused_error(
4288 pid,
4289 &ClientErrorKind::Forbidden,
4290 AttributionForce::default(),
4291 );
4292 assert!(
4293 !derived.contains("FORCE"),
4294 "a `derived` send never forced anything: {derived}"
4295 );
4296 }
4297
4298 #[test]
4303 fn an_explicit_scoping_failure_does_not_blame_the_force() {
4304 let pid = uuid::Uuid::from_u128(7);
4305 let scoping = refused_error(
4306 pid,
4307 &ClientErrorKind::Scoping,
4308 AttributionForce {
4309 env: true,
4310 binding: true,
4311 },
4312 );
4313 assert!(!scoping.contains("FORCE"), "{scoping}");
4314 assert_eq!(
4315 scoping,
4316 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
4317 "the scoping wording does not depend on the mode"
4318 );
4319 }
4320
4321 #[test]
4341 fn the_403_remediation_names_the_force_source_actually_in_effect() {
4342 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
4343 let mut _guard = crate::test_helpers::EnvVarGuard::new();
4344 let pid = uuid::Uuid::from_u128(7);
4345 let live = forced_binding(Some(
4346 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
4347 ));
4348 let never_forced = forced_binding(None);
4349
4350 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4354 let env_only = refused_error(
4355 pid,
4356 &ClientErrorKind::Forbidden,
4357 attribution_force(Some(&never_forced)),
4358 );
4359 assert!(
4360 env_only.contains("FORCE"),
4361 "an env-sourced force is still a force: {env_only}"
4362 );
4363 assert!(
4364 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
4365 "must name the variable that is doing the forcing: {env_only}"
4366 );
4367 assert!(
4368 !env_only.contains("--project-attribution"),
4369 "must NOT tell the operator to drop a flag that would change \
4370 nothing here — this is the bug: {env_only}"
4371 );
4372
4373 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
4377 let binding_only = refused_error(
4378 pid,
4379 &ClientErrorKind::Forbidden,
4380 attribution_force(Some(&live)),
4381 );
4382 assert!(
4383 binding_only.contains("--project-attribution"),
4384 "a persisted force IS cleared by switching without the flag: {binding_only}"
4385 );
4386 assert!(
4387 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
4388 "must not send the operator after an unset variable: {binding_only}"
4389 );
4390
4391 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4395 let both = refused_error(
4396 pid,
4397 &ClientErrorKind::Forbidden,
4398 attribution_force(Some(&live)),
4399 );
4400 assert!(
4401 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4402 && both.contains("--project-attribution"),
4403 "both sources are in effect and both must be named: {both}"
4404 );
4405 assert!(
4406 both.contains("BOTH"),
4407 "must say that removing only one is not enough: {both}"
4408 );
4409 }
4410
4411 #[test]
4416 fn no_force_means_no_remediation_clause() {
4417 let pid = uuid::Uuid::from_u128(7);
4418 let none = refused_error(
4419 pid,
4420 &ClientErrorKind::Forbidden,
4421 AttributionForce::default(),
4422 );
4423 assert!(
4424 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4425 && !none.contains("--project-attribution"),
4426 "a derived send has no force to remove: {none}"
4427 );
4428 }
4429
4430 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
4435 let path = dir.join("transcript.jsonl");
4436 let mut body = String::new();
4437 for i in 0..n {
4438 let line = serde_json::json!({
4439 "type": "user",
4440 "n": i,
4441 "message": {"content": "x".repeat(line_bytes)},
4442 });
4443 body.push_str(&line.to_string());
4444 body.push('\n');
4445 }
4446 fs::write(&path, body).unwrap();
4447 path
4448 }
4449
4450 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
4452 StreamEventRequest {
4453 tool_name: Some("Bash".into()),
4454 tool_use_id: Some("toolu_1".into()),
4455 tool_input: Some(serde_json::json!({"command": "ls"})),
4456 event_uuid: Some(uuid::Uuid::now_v7()),
4457 transcript_lines: Some(lines),
4458 transcript_offset: Some(offset),
4459 ..sample_stream_event_request()
4460 }
4461 }
4462
4463 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
4464 part.transcript_lines.clone().unwrap_or_default()
4465 }
4466
4467 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
4470 parts
4471 .iter()
4472 .flat_map(|p| {
4473 let offset = p.transcript_offset.unwrap();
4474 part_lines(p)
4475 .into_iter()
4476 .enumerate()
4477 .map(move |(i, l)| (offset + i as i64, l))
4478 })
4479 .collect()
4480 }
4481
4482 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
4484 (0..n)
4485 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
4486 .collect()
4487 }
4488
4489 #[test]
4490 fn split_leaves_a_request_under_the_cap_unchanged() {
4491 let req = event_with_lines(big_lines(3, 100), 0);
4492
4493 let parts = split_into_parts(req.clone());
4494
4495 assert_eq!(parts.len(), 1);
4496 assert_eq!(
4497 serde_json::to_value(&parts[0]).unwrap(),
4498 serde_json::to_value(&req).unwrap()
4499 );
4500 }
4501
4502 #[test]
4506 fn split_carries_every_line_of_a_batch_over_the_cap() {
4507 let dir = tempfile::tempdir().unwrap();
4508 let transcript = write_transcript(dir.path(), 300, 5_000);
4510 let (lines, start, _) =
4511 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
4512 let req = event_with_lines(lines.clone(), start);
4513 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
4514
4515 let parts = split_into_parts(req.clone());
4516
4517 assert!(parts.len() >= 3, "got {} parts", parts.len());
4518 for part in &parts {
4519 assert!(
4520 part.serialized_len() <= MAX_REQUEST_BYTES,
4521 "part of {} bytes exceeds the cap",
4522 part.serialized_len()
4523 );
4524 }
4525 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4526 assert_eq!(sent, lines, "every line, once, in order");
4527
4528 let (event, transcript_parts) = parts.split_last().unwrap();
4530 assert_eq!(event.event_type, StreamEventType::ToolUse);
4531 assert_eq!(event.event_uuid, req.event_uuid);
4532 assert_eq!(event.tool_input, req.tool_input);
4533 for part in transcript_parts {
4534 assert_eq!(part.event_type, StreamEventType::Transcript);
4535 assert!(part.event_uuid.is_none());
4536 assert!(part.tool_input.is_none());
4537 assert!(part.tool_name.is_none());
4538 }
4539 assert!(
4540 !part_lines(event).is_empty(),
4541 "the event keeps the lines that fit beside it"
4542 );
4543 }
4544
4545 #[test]
4549 fn split_keeps_each_lines_unsplit_chunk_index() {
4550 let lines = big_lines(300, 5_000);
4551 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
4552
4553 let expected: Vec<_> = lines
4554 .into_iter()
4555 .enumerate()
4556 .map(|(i, l)| (1_000 + i as i64, l))
4557 .collect();
4558 assert_eq!(chunk_indexes(&parts), expected);
4559 }
4560
4561 #[test]
4566 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
4567 let lines = big_lines(10, 200_000);
4568 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
4569 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
4570
4571 for (index, line) in &short {
4572 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
4573 assert_eq!(in_long.0, *index, "line {line} indexed differently");
4574 }
4575 }
4576
4577 #[test]
4580 fn split_sends_a_single_oversized_line_alone() {
4581 let lines = vec![
4582 serde_json::json!({"n": 0}),
4583 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
4584 serde_json::json!({"n": 2}),
4585 ];
4586
4587 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
4588
4589 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4590 assert_eq!(sent, lines);
4591 let big = parts
4592 .iter()
4593 .find(|p| part_lines(p).contains(&lines[1]))
4594 .unwrap();
4595 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
4596 assert_eq!(big.transcript_offset, Some(1));
4597 }
4598
4599 fn far_deadline() -> std::time::Instant {
4600 std::time::Instant::now() + Duration::from_secs(60)
4601 }
4602
4603 fn captured_body(captured: &str) -> StreamEventRequest {
4604 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
4605 serde_json::from_str(body).expect("request body is a StreamEventRequest")
4606 }
4607
4608 #[tokio::test]
4610 async fn deliver_parts_sends_every_part() {
4611 let dir = tempfile::tempdir().unwrap();
4612 let pending_path = dir.path().join("pending.jsonl");
4613 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4614 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4615 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4616
4617 let all_accepted = deliver_parts(
4618 &client,
4619 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4620 AttributionForce::default(),
4621 parts.clone(),
4622 &pending_path,
4623 false,
4624 far_deadline(),
4625 &mut false,
4626 )
4627 .await
4628 .unwrap();
4629
4630 assert!(all_accepted);
4631 for part in &parts {
4632 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4633 assert_eq!(got.transcript_offset, part.transcript_offset);
4634 assert_eq!(got.transcript_lines, part.transcript_lines);
4635 }
4636 assert!(drain_pending(&pending_path).unwrap().is_empty());
4637 }
4638
4639 #[tokio::test]
4643 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4644 let dir = tempfile::tempdir().unwrap();
4645 let pending_path = dir.path().join("pending.jsonl");
4646 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4647 assert!(parts.len() >= 3);
4648 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4649 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4650 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4651
4652 let all_accepted = deliver_parts(
4653 &client,
4654 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4655 AttributionForce::default(),
4656 parts.clone(),
4657 &pending_path,
4658 false,
4659 far_deadline(),
4660 &mut false,
4661 )
4662 .await
4663 .unwrap();
4664
4665 assert!(!all_accepted);
4666 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4667 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4668 assert!(
4669 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4670 "nothing is sent after the first failure"
4671 );
4672 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4673 .unwrap()
4674 .iter()
4675 .map(|j| serde_json::from_str(j).unwrap())
4676 .collect();
4677 assert_eq!(queued.len(), parts.len() - 1);
4678 for (q, part) in queued.iter().zip(&parts[1..]) {
4679 assert_eq!(q.transcript_offset, part.transcript_offset);
4680 assert_eq!(q.transcript_lines, part.transcript_lines);
4681 }
4682 }
4683
4684 #[tokio::test]
4687 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4688 let dir = tempfile::tempdir().unwrap();
4689 let pending_path = dir.path().join("pending.jsonl");
4690 let parts = split_into_parts(sample_stream_event_request());
4691 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4692
4693 let all_accepted = deliver_parts(
4694 &client,
4695 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4696 AttributionForce::default(),
4697 parts,
4698 &pending_path,
4699 true,
4700 far_deadline(),
4701 &mut false,
4702 )
4703 .await
4704 .unwrap();
4705
4706 assert!(!all_accepted);
4707 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4708 }
4709
4710 #[tokio::test]
4713 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
4714 let dir = tempfile::tempdir().unwrap();
4715 let pending_path = dir.path().join("pending.jsonl");
4716 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4717 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4718 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4719
4720 let all_accepted = deliver_parts(
4721 &client,
4722 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4723 AttributionForce::default(),
4724 parts.clone(),
4725 &pending_path,
4726 false,
4727 std::time::Instant::now(),
4728 &mut false,
4729 )
4730 .await
4731 .unwrap();
4732
4733 assert!(!all_accepted);
4734 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
4735 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
4736 }
4737
4738 #[tokio::test]
4743 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
4744 let dir = tempfile::tempdir().unwrap();
4745 let pending_path = dir.path().join("pending.jsonl");
4746 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
4747 let base = format!("http://{}", listener.local_addr().unwrap());
4748 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4750 let started = Instant::now();
4751
4752 let all_accepted = deliver_parts(
4753 &client,
4754 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4755 AttributionForce::default(),
4756 vec![event_with_lines(big_lines(1, 10), 0)],
4757 &pending_path,
4758 false,
4759 started + Duration::from_millis(100),
4760 &mut false,
4761 )
4762 .await
4763 .unwrap();
4764
4765 assert!(!all_accepted);
4766 assert!(started.elapsed() < Duration::from_secs(10));
4767 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4768 drop(listener);
4769 }
4770
4771 const PARENT_SESSION: &str = "parent-session";
4774 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
4775
4776 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
4780 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
4781 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4782 let subagents = dir.join(PARENT_SESSION).join("subagents");
4783 fs::create_dir_all(&subagents).unwrap();
4784 let session_dir = dir.join("tv-session");
4785 fs::create_dir_all(&session_dir).unwrap();
4786 (main, subagents, session_dir)
4787 }
4788
4789 fn subagent_line(agent: &str, n: usize) -> String {
4790 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
4791 }
4792
4793 fn append_raw(path: &Path, text: &str) {
4794 let mut f = fs::OpenOptions::new()
4795 .create(true)
4796 .append(true)
4797 .open(path)
4798 .unwrap();
4799 f.write_all(text.as_bytes()).unwrap();
4800 }
4801
4802 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
4803 let path = subagents.join(format!("agent-{agent}.jsonl"));
4804 for n in ns {
4805 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
4806 }
4807 }
4808
4809 async fn sweep(
4813 responses: Vec<String>,
4814 main: &Path,
4815 session_dir: &Path,
4816 pending_path: &Path,
4817 ) -> Vec<StreamEventRequest> {
4818 sweep_waiting(responses, main, session_dir, pending_path, None).await
4819 }
4820
4821 async fn sweep_waiting(
4824 responses: Vec<String>,
4825 main: &Path,
4826 session_dir: &Path,
4827 pending_path: &Path,
4828 wait_for_lock: Option<Instant>,
4829 ) -> Vec<StreamEventRequest> {
4830 let expected = responses.len();
4831 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4832 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4833 let event = StreamEventRequest {
4834 session_id: PARENT_SESSION.into(),
4835 ..sample_stream_event_request()
4836 };
4837 deliver_subagent_transcripts(
4838 &client,
4839 &repo_attr(SUBAGENT_REPO),
4840 AttributionForce::default(),
4841 &transcript_template(&event),
4842 main,
4843 session_dir,
4844 pending_path,
4845 false,
4846 Instant::now() + Duration::from_secs(60),
4847 wait_for_lock,
4848 &mut false,
4849 )
4850 .await
4851 .unwrap();
4852 (0..expected)
4853 .map(|_| {
4854 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4855 assert!(
4856 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4857 "{captured}"
4858 );
4859 let body = captured.splitn(3, " | ").nth(2).unwrap();
4860 serde_json::from_str(body).unwrap()
4861 })
4862 .collect()
4863 }
4864
4865 fn agent_of(line: &serde_json::Value) -> &str {
4866 line["agentId"].as_str().unwrap()
4867 }
4868
4869 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4873 for req in reqs {
4874 assert_eq!(req.event_type, StreamEventType::Transcript);
4875 assert_eq!(req.session_id, PARENT_SESSION);
4876 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4877 let lines = part_lines(req);
4878 let agent = agent_of(&lines[0]);
4879 assert!(
4880 lines.iter().all(|l| agent_of(l) == agent),
4881 "a request mixes subagent files: {lines:?}"
4882 );
4883 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4884 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4885 assert_eq!(req.transcript_offset, Some(first));
4886 }
4887 }
4888
4889 #[tokio::test]
4890 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4891 let dir = tempfile::tempdir().unwrap();
4892 let (main, subagents, session_dir) = claude_session(dir.path());
4893 let pending = session_dir.join("pending.jsonl");
4894 let ok = ok_stream_response;
4895 let mut all = Vec::new();
4896
4897 append_subagent_lines(&subagents, "a1", 0..2);
4899 append_subagent_lines(&subagents, "b2", 0..1);
4900 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4901 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4902 assert_eq!(reqs.len(), 2);
4903 all.extend(reqs);
4904
4905 append_subagent_lines(&subagents, "a1", 2..3);
4907 append_subagent_lines(&subagents, "b2", 1..2);
4908 let partial = subagent_line("b2", 2);
4909 let (head, tail) = partial.split_at(10);
4910 append_raw(&subagents.join("agent-b2.jsonl"), head);
4911 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4912 assert_eq!(reqs.len(), 2);
4913 all.extend(reqs);
4914
4915 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4917 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4918 assert_eq!(reqs.len(), 1);
4919 all.extend(reqs);
4920
4921 assert!(sweep(vec![], &main, &session_dir, &pending)
4923 .await
4924 .is_empty());
4925 assert!(!pending.exists(), "nothing may have failed and been queued");
4926
4927 assert_one_file_per_request(&subagents, &all);
4928 let mut sent: Vec<(String, u64)> = all
4929 .iter()
4930 .flat_map(part_lines)
4931 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4932 .collect();
4933 sent.sort();
4934 let expected: Vec<(String, u64)> = [
4935 ("a1", 0),
4936 ("a1", 1),
4937 ("a1", 2),
4938 ("b2", 0),
4939 ("b2", 1),
4940 ("b2", 2),
4941 ]
4942 .into_iter()
4943 .map(|(a, n)| (a.to_string(), n))
4944 .collect();
4945 assert_eq!(sent, expected, "each line exactly once");
4946 }
4947
4948 #[tokio::test]
4949 async fn a_session_without_subagents_sends_nothing_extra() {
4950 let dir = tempfile::tempdir().unwrap();
4951 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4952 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4953 let session_dir = dir.path().join("tv-session");
4954 fs::create_dir_all(&session_dir).unwrap();
4955 let pending = session_dir.join("pending.jsonl");
4956
4957 assert!(sweep(vec![], &main, &session_dir, &pending)
4958 .await
4959 .is_empty());
4960 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4961 }
4962
4963 #[tokio::test]
4968 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4969 let dir = tempfile::tempdir().unwrap();
4970 let (main, subagents, session_dir) = claude_session(dir.path());
4971 let pending = session_dir.join("pending.jsonl");
4972 append_subagent_lines(&subagents, "a1", 0..2);
4973 append_subagent_lines(&subagents, "b2", 0..1);
4974
4975 let error =
4976 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4977 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4978 assert_eq!(failed.len(), 1);
4979 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4980 .unwrap()
4981 .iter()
4982 .map(|j| serde_json::from_str(j).unwrap())
4983 .collect();
4984 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4985
4986 let resent = sweep(
4987 vec![ok_stream_response(), ok_stream_response()],
4988 &main,
4989 &session_dir,
4990 &pending,
4991 )
4992 .await;
4993 assert_one_file_per_request(&subagents, &resent);
4994 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4995 assert_eq!(
4996 resent.iter().map(key).collect::<Vec<_>>(),
4997 queued.iter().map(key).collect::<Vec<_>>()
4998 );
4999 assert!(sweep(vec![], &main, &session_dir, &pending)
5000 .await
5001 .is_empty());
5002 }
5003
5004 #[tokio::test]
5007 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
5008 let dir = tempfile::tempdir().unwrap();
5009 let (main, subagents, session_dir) = claude_session(dir.path());
5010 let pending = session_dir.join("pending.jsonl");
5011 append_subagent_lines(&subagents, "a1", 0..2);
5012 append_subagent_lines(&subagents, "b2", 0..1);
5013 let a1_offset =
5014 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5015 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5016
5017 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5018 assert_eq!(reqs.len(), 1);
5019 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
5020 assert!(!a1_offset.exists());
5021
5022 drop(held);
5023 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5024 assert_eq!(reqs.len(), 1);
5025 assert_eq!(part_lines(&reqs[0]).len(), 2);
5026 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
5027 }
5028
5029 #[tokio::test]
5032 async fn a_final_hook_waits_for_a_busy_subagent_file() {
5033 let dir = tempfile::tempdir().unwrap();
5034 let (main, subagents, session_dir) = claude_session(dir.path());
5035 let pending = session_dir.join("pending.jsonl");
5036 append_subagent_lines(&subagents, "a1", 0..2);
5037 let a1_offset =
5038 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5039 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5040 let release = thread::spawn(move || {
5041 thread::sleep(Duration::from_millis(300));
5042 drop(held);
5043 });
5044
5045 let reqs = sweep_waiting(
5046 vec![ok_stream_response()],
5047 &main,
5048 &session_dir,
5049 &pending,
5050 Some(Instant::now() + Duration::from_secs(10)),
5051 )
5052 .await;
5053 release.join().unwrap();
5054 assert_eq!(reqs.len(), 1);
5055 assert_eq!(part_lines(&reqs[0]).len(), 2);
5056 }
5057
5058 #[tokio::test]
5062 async fn a_large_subagent_batch_is_split_within_its_file() {
5063 let dir = tempfile::tempdir().unwrap();
5064 let (main, subagents, session_dir) = claude_session(dir.path());
5065 let pending = session_dir.join("pending.jsonl");
5066 let big = subagents.join("agent-a1.jsonl");
5067 for n in 0..300 {
5068 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
5069 append_raw(&big, &format!("{line}\n"));
5070 }
5071 append_subagent_lines(&subagents, "b2", 0..1);
5072
5073 let scratch = dir.path().join("scratch-offset");
5074 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
5075 let unsplit = StreamEventRequest {
5076 transcript_lines: Some(lines.clone()),
5077 transcript_offset: Some(start),
5078 ..transcript_template(&sample_stream_event_request())
5079 };
5080 let a1_parts = split_into_parts(unsplit).len();
5081 assert!(a1_parts > 1, "the batch must exceed the cap");
5082
5083 let reqs = sweep(
5084 vec![ok_stream_response(); a1_parts + 1],
5085 &main,
5086 &session_dir,
5087 &pending,
5088 )
5089 .await;
5090 assert!(!pending.exists());
5091 let (a1, b2) = reqs.split_at(a1_parts);
5092 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
5093 assert_eq!(
5094 chunk_indexes(a1),
5095 lines
5096 .into_iter()
5097 .enumerate()
5098 .map(|(i, l)| (start + i as i64, l))
5099 .collect::<Vec<_>>()
5100 );
5101 assert_eq!(b2.len(), 1);
5102 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
5103 assert_eq!(b2[0].transcript_offset, Some(0));
5104 }
5105}