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 async fn run_stream(
1421 event_type: &str,
1422 agent: crate::agent::Agent,
1423) -> Result<(), Box<dyn std::error::Error>> {
1424 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1426 let mut input = String::new();
1427 io::stdin().read_to_string(&mut input)?;
1428 let hook_event = parse_hook_event(&input)?;
1429
1430 let hook_cwd = Path::new(&hook_event.cwd);
1452 let (resolved, cwd_session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1453 let storage_root =
1454 crate::session_state::storage_root(&crate::session_state::load(&hook_event.session_id));
1455 let session_dir = match &storage_root {
1456 Some(root) => root
1457 .join(".tracevault")
1458 .join("sessions")
1459 .join(&hook_event.session_id),
1460 None => cwd_session_dir,
1461 };
1462 if storage_root.is_none() && resolved.source == crate::paths::ProjectRootSource::Fallback {
1463 eprintln!(
1468 "tracevault: warning: could not resolve a git project root from {}; \
1469 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1470 that it runs inside the repository to keep sessions under the repo root.",
1471 hook_cwd.display()
1472 );
1473 }
1474 let project_root = resolved.root;
1475
1476 fs::create_dir_all(&session_dir)?;
1478
1479 let storage = storage_root.as_ref().unwrap_or(&project_root);
1485 let _ = crate::config::TracevaultConfig::ensure_gitignore(&storage.join(".tracevault"));
1486
1487 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1492 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1493 if storage_root.is_some() {
1496 let _ = crate::session_state::record_worktree(&session_dir, &worktree_top);
1497 }
1498
1499 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1503 if let Some(records) = &hook_event.transcript_records {
1508 let _ = record_inline_tool_calls(&session_dir, records);
1509 }
1510
1511 let target = SessionTarget {
1512 project_root,
1513 session_dir,
1514 worktree_top,
1515 };
1516 stream_event(
1517 hook_event,
1518 event_type,
1519 agent,
1520 &target,
1521 deadline,
1522 Sender::Hook,
1523 )
1524 .await?;
1525
1526 let response = HookResponse::allow();
1528 println!("{}", serde_json::to_string(&response)?);
1529
1530 Ok(())
1531}
1532
1533pub fn stream_event_type(event_type: &str) -> StreamEventType {
1535 match event_type {
1536 "notification" => StreamEventType::SessionStart,
1537 "stop" => StreamEventType::SessionEnd,
1539 "session-end" => StreamEventType::Transcript,
1543 _ => StreamEventType::ToolUse,
1544 }
1545}
1546
1547pub(crate) struct SessionTarget {
1551 pub project_root: std::path::PathBuf,
1552 pub session_dir: std::path::PathBuf,
1554 pub worktree_top: String,
1556}
1557
1558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1560pub(crate) enum Sender {
1561 Hook,
1564 CatchUp,
1569}
1570
1571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1573pub(crate) enum Sent {
1574 Accepted,
1576 Queued,
1578 Skipped,
1581}
1582
1583pub(crate) async fn stream_event(
1587 mut hook_event: tracevault_protocol::hooks::HookEvent,
1588 event_type: &str,
1589 agent: crate::agent::Agent,
1590 target: &SessionTarget,
1591 deadline: std::time::Instant,
1592 sender: Sender,
1593) -> Result<Sent, Box<dyn std::error::Error>> {
1594 let SessionTarget {
1595 project_root,
1596 session_dir,
1597 worktree_top,
1598 } = target;
1599 let hook_cwd = Path::new(&hook_event.cwd);
1600
1601 let event_uuid = uuid::Uuid::now_v7();
1606
1607 let transcript_path = Path::new(&hook_event.transcript_path);
1609 let offset_path = session_dir.join(".stream_offset");
1610 let sends_main = event_type != "subagent-stop";
1617 let (transcript_lines, start_offset, new_offset) = if sends_main {
1618 read_new_transcript_lines(transcript_path, &offset_path)?
1619 } else {
1620 (vec![], 0, 0)
1621 };
1622
1623 let is_inline = hook_event.transcript_records.is_some();
1640 let (transcript_lines, start_offset, new_offset) = if is_inline {
1641 let prior_offset: i64 = if offset_path.exists() {
1648 let content = fs::read_to_string(&offset_path)?;
1649 content
1650 .trim()
1651 .parse::<i64>()
1652 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1653 .max(0)
1654 } else {
1655 0
1656 };
1657 resolve_transcript_source(
1661 hook_event.transcript_records.take(),
1662 prior_offset,
1663 (transcript_lines, start_offset, new_offset),
1664 )
1665 } else {
1666 (transcript_lines, start_offset, new_offset)
1667 };
1668 let stream_event_type = stream_event_type(event_type);
1670
1671 let tool_is_error = hook_event
1676 .tool_use_id
1677 .as_deref()
1678 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1679 .or_else(|| inline_tool_is_error(&transcript_lines));
1680
1681 let config = crate::config::TracevaultConfig::try_load(project_root);
1691 let repo_uc = config
1695 .as_ref()
1696 .ok()
1697 .and_then(|opt| opt.as_ref())
1698 .and_then(|c| c.user_context.clone());
1699 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1700
1701 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1707 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1708
1709 let mut req = StreamEventRequest {
1710 protocol_version: 1,
1711 tool: Some("claude-code".to_string()),
1712 event_type: stream_event_type,
1713 session_id: hook_event.session_id.clone(),
1714 timestamp: chrono::Utc::now(),
1715 hook_event_name: Some(hook_event.hook_event_name.clone()),
1716 tool_name: hook_event.tool_name.clone(),
1717 tool_use_id: hook_event.tool_use_id.clone(),
1718 tool_input: hook_event.tool_input.clone(),
1719 tool_response: hook_event.tool_response.clone(),
1720 tool_is_error,
1721 event_index: None,
1722 event_uuid: Some(event_uuid),
1723 transcript_lines: None,
1724 transcript_offset: Some(start_offset),
1725 model: None,
1726 cwd: Some(hook_event.cwd.clone()),
1727 final_stats: None,
1728 flow_id: ctx_flow_id,
1729 labels: ctx_labels,
1730 params: ctx_params,
1731 billing_mode: (sender == Sender::Hook)
1732 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1733 };
1734
1735 stamp_agent(&mut req, agent);
1736 let subagent_template = transcript_template(&req);
1738 if !transcript_lines.is_empty() {
1739 req.transcript_lines = Some(transcript_lines);
1740 }
1741
1742 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
1744
1745 if let Err(e) = &config {
1754 return Err(format!("malformed .tracevault/config.toml: {e}").into());
1755 }
1756
1757 let session = crate::session_state::load(&hook_event.session_id);
1762 let bound = config
1763 .as_ref()
1764 .ok()
1765 .and_then(|opt| opt.as_ref())
1766 .and_then(crate::resolution::binding_from_config);
1767 let user_default = crate::user_default::load();
1768 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
1769 let config_project = config
1783 .as_ref()
1784 .ok()
1785 .and_then(|opt| opt.as_ref())
1786 .and_then(crate::resolution::project_from_config);
1787 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()), config_project);
1788 let capture_pid = capture_binding
1789 .as_ref()
1790 .and_then(crate::resolution::capture_project_id);
1791 let client = server_url
1801 .as_deref()
1802 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1803 let mut inferred = None;
1804 if binding.is_none() {
1805 if let Some(client) = &client {
1806 match inference_project(None, capture_pid) {
1807 Some(pid) => {
1808 if let Some(checkout) = crate::inferred_repo::event_checkout(
1809 hook_cwd,
1810 hook_event.tool_input.as_ref(),
1811 worktree_top,
1812 ) {
1813 inferred = crate::inferred_repo::infer(
1814 &hook_event.session_id,
1815 &checkout,
1816 pid,
1817 client,
1818 deadline,
1819 )
1820 .await;
1821 if inferred.is_some() && checkout != *worktree_top {
1825 let _ = crate::session_state::record_worktree(session_dir, &checkout);
1826 }
1827 }
1828 }
1829 None => {
1830 let auto = crate::auto_bind::bind_session(
1831 &hook_event.session_id,
1832 hook_cwd,
1833 client,
1834 deadline,
1835 )
1836 .await;
1837 if let Some(notice) = auto.notice {
1838 eprintln!("{notice}");
1839 }
1840 binding = auto.binding;
1841 }
1842 }
1843 }
1844 }
1845 let force = attribution_force(capture_binding.as_ref());
1852
1853 let Some(attribution) =
1861 attribution_with_inference(binding.as_ref(), capture_pid, inferred.as_ref())
1862 else {
1863 return Ok(Sent::Skipped);
1864 };
1865 match sender {
1869 Sender::Hook => {
1870 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
1871 }
1872 Sender::CatchUp => {
1873 let meta = session_metadata(session_dir);
1874 if !catch_up_may_send(meta.get("attribution"), &attribution) {
1875 return Ok(Sent::Skipped);
1876 }
1877 }
1878 }
1879
1880 let client = client.ok_or("server_url not configured")?;
1882
1883 let pending_path = pending_path_for(session_dir, &attribution);
1895 let adopted = if inferred.is_some() && binding.is_none() {
1896 None
1897 } else {
1898 adopted_project_queue(session_dir, &attribution)
1899 };
1900 if let Some(adopted) = adopted {
1901 adopt_queue(&adopted, &pending_path)?;
1902 }
1903 let pending_events = drain_pending(&pending_path)?;
1904
1905 let mut send_failed = false;
1906 let mut warned = false;
1910
1911 for (i, pending_json) in pending_events.iter().enumerate() {
1915 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1916 if std::time::Instant::now() >= deadline
1920 || !matches!(
1921 tokio::time::timeout_at(
1922 (deadline + IN_FLIGHT_GRACE).into(),
1923 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1924 )
1925 .await,
1926 Ok(Ok(_))
1927 )
1928 {
1929 for evt in &pending_events[i..] {
1936 append_pending(&pending_path, evt)?;
1937 }
1938 send_failed = true;
1939 break;
1940 }
1941 }
1942 }
1943
1944 let sends_event = sends_main
1949 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
1950 let all_accepted = if sends_event {
1951 deliver_parts(
1952 &client,
1953 &attribution,
1954 force,
1955 split_into_parts(req),
1956 &pending_path,
1957 send_failed,
1958 deadline,
1959 &mut warned,
1960 )
1961 .await?
1962 } else {
1963 true
1964 };
1965 if sends_main && (all_accepted || is_inline) {
1978 crate::subagents::write_offset(&offset_path, new_offset)?;
1979 }
1980
1981 if sender == Sender::Hook && agent == crate::agent::Agent::ClaudeCode {
1986 deliver_subagent_transcripts(
1987 &client,
1988 &attribution,
1989 force,
1990 &subagent_template,
1991 transcript_path,
1992 session_dir,
1993 &pending_path,
1994 send_failed || !all_accepted,
1995 deadline,
1996 matches!(event_type, "stop" | "subagent-stop" | "session-end")
1997 .then(|| deadline + FINAL_LOCK_WAIT),
1998 &mut warned,
1999 )
2000 .await?;
2001 }
2002
2003 Ok(if !send_failed && all_accepted {
2004 Sent::Accepted
2005 } else {
2006 Sent::Queued
2007 })
2008}
2009
2010#[cfg(test)]
2011mod tests {
2012 use super::*;
2013 use crate::api_client::AttributionMode;
2014 use crate::config::UserContext;
2015 use crate::context::{Context, EffectiveContext};
2016 use std::collections::BTreeMap;
2017
2018 #[test]
2019 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
2020 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
2021 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
2022 project,
2023 };
2024 let a = uuid::Uuid::from_u128(0xa);
2025 let b = uuid::Uuid::from_u128(0xb);
2026 let only = |project_id| Attribution::ProjectOnly { project_id };
2027
2028 let recorded = attribution_record(&repo(Some(a)));
2029 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
2030 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
2031 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
2032 let recorded = attribution_record(&only(a));
2033 assert!(catch_up_may_send(Some(&recorded), &only(a)));
2034 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
2035 assert!(catch_up_may_send(None, &repo(Some(b))));
2038 assert!(!catch_up_may_send(None, &only(a)));
2039 }
2040
2041 #[test]
2042 fn record_metadata_keeps_the_other_keys() {
2043 let dir = tempfile::tempdir().unwrap();
2044 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
2045 record_metadata(
2046 dir.path(),
2047 "attribution",
2048 serde_json::json!({"repo_id": "r"}),
2049 )
2050 .unwrap();
2051 let meta = session_metadata(dir.path());
2052 assert_eq!(meta["transcript_path"], "/t.jsonl");
2053 assert_eq!(meta["attribution"]["repo_id"], "r");
2054 }
2055
2056 #[test]
2057 fn hook_events_map_to_server_events() {
2058 assert_eq!(
2059 stream_event_type("notification"),
2060 StreamEventType::SessionStart
2061 );
2062 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
2065 assert_eq!(
2066 stream_event_type("session-end"),
2067 StreamEventType::Transcript
2068 );
2069 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
2070 assert_eq!(
2071 stream_event_type(event),
2072 StreamEventType::ToolUse,
2073 "{event}"
2074 );
2075 }
2076 }
2077
2078 #[test]
2081 fn disabled_user_context_resolves_to_none() {
2082 assert!(UserContext::Toggle(false).resolve().is_none());
2086 }
2087
2088 #[test]
2089 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
2090 let dir = tempfile::tempdir().unwrap();
2094 let effective = Context::effective(dir.path(), None);
2095 assert_eq!(effective, EffectiveContext::default());
2096 }
2097
2098 #[test]
2101 fn apply_context_stamps_all_fields() {
2102 let dir = tempfile::tempdir().unwrap();
2103 let mut params = BTreeMap::new();
2104 params.insert("env".to_string(), "prod".to_string());
2105 params.insert("region".to_string(), "eu-west-1".to_string());
2106
2107 let ctx = EffectiveContext {
2108 flow_id: Some("flow-xyz".to_string()),
2109 labels: vec!["backend".to_string(), "urgent".to_string()],
2110 params,
2111 };
2112
2113 let (flow_id, labels, params_out) = apply_context(ctx);
2114
2115 assert_eq!(flow_id, Some("flow-xyz".to_string()));
2116 assert_eq!(
2117 labels,
2118 Some(vec!["backend".to_string(), "urgent".to_string()])
2119 );
2120 let p = params_out.expect("params should be Some");
2121 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
2122 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
2123
2124 let written = Context {
2127 flow_id: Some("flow-xyz".to_string()),
2128 labels: vec!["backend".to_string(), "urgent".to_string()],
2129 params: {
2130 let mut m = BTreeMap::new();
2131 m.insert("env".to_string(), Some("prod".to_string()));
2132 m.insert("region".to_string(), Some("eu-west-1".to_string()));
2133 m
2134 },
2135 };
2136 let ctx_path = dir.path().join(".tracevault").join("context.json");
2137 written.save_to(&ctx_path).unwrap();
2138 let loaded = Context::load_from(&ctx_path);
2139 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
2140 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
2141 assert!(labels2.is_some());
2142 assert!(params2.is_some());
2143 }
2144
2145 #[test]
2148 fn apply_context_missing_file_all_none() {
2149 let dir = tempfile::tempdir().unwrap();
2150 let missing_path = dir.path().join(".tracevault").join("context.json");
2151 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
2153 assert!(flow_id.is_none(), "flow_id should be None");
2154 assert!(labels.is_none(), "labels should be None");
2155 assert!(params.is_none(), "params should be None");
2156 }
2157
2158 #[test]
2161 fn apply_context_empty_collections_are_none() {
2162 let ctx = EffectiveContext {
2163 flow_id: None,
2164 labels: vec![],
2165 params: BTreeMap::new(),
2166 };
2167 let (flow_id, labels, params) = apply_context(ctx);
2168 assert!(flow_id.is_none());
2169 assert!(
2170 labels.is_none(),
2171 "empty labels should be None, not Some([])"
2172 );
2173 assert!(
2174 params.is_none(),
2175 "empty params should be None, not Some({{}})"
2176 );
2177 }
2178
2179 #[test]
2182 fn apply_context_flow_id_only() {
2183 let ctx = EffectiveContext {
2184 flow_id: Some("my-flow".to_string()),
2185 labels: vec![],
2186 params: BTreeMap::new(),
2187 };
2188 let (flow_id, labels, params) = apply_context(ctx);
2189 assert_eq!(flow_id, Some("my-flow".to_string()));
2190 assert!(labels.is_none());
2191 assert!(params.is_none());
2192 }
2193
2194 use crate::test_helpers::{add_worktree, init_git_repo};
2201
2202 #[test]
2205 fn resolve_session_paths_primary_checkout() {
2206 let tmp = tempfile::tempdir().unwrap();
2207 let repo = tmp.path().join("repo");
2208 std::fs::create_dir_all(&repo).unwrap();
2209 init_git_repo(&repo);
2210 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
2212
2213 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
2214 let project_root = resolved.root;
2215
2216 assert_eq!(
2217 project_root.canonicalize().unwrap(),
2218 repo.canonicalize().unwrap(),
2219 "primary checkout: project_root must be repo root"
2220 );
2221 assert_eq!(
2222 session_dir.canonicalize().unwrap_or(session_dir.clone()),
2223 repo.join(".tracevault")
2224 .join("sessions")
2225 .join("sess-primary-123"),
2226 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
2227 );
2228 assert!(
2230 session_dir.starts_with(&repo),
2231 "session_dir must be under the primary repo root"
2232 );
2233 }
2234
2235 #[test]
2239 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
2240 let tmp = tempfile::tempdir().unwrap();
2241 let repo = tmp.path().join("repo");
2242 let wt = tmp.path().join("sibling-wt");
2244
2245 std::fs::create_dir_all(&repo).unwrap();
2246 init_git_repo(&repo);
2247 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
2249 add_worktree(&repo, &wt);
2250
2251 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
2252 let project_root = resolved.root;
2253
2254 assert_eq!(
2256 project_root.canonicalize().unwrap(),
2257 repo.canonicalize().unwrap(),
2258 "sibling worktree: project_root must be primary repo root (not worktree dir)"
2259 );
2260 assert!(
2262 session_dir.starts_with(&repo),
2263 "sibling worktree: session_dir must be under the PRIMARY repo root"
2264 );
2265 assert!(
2266 !session_dir.starts_with(&wt),
2267 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
2268 );
2269 assert!(
2270 session_dir.ends_with(
2271 std::path::Path::new(".tracevault")
2272 .join("sessions")
2273 .join("sess-sibling-456")
2274 ),
2275 "session_dir must end with .tracevault/sessions/<session_id>"
2276 );
2277 }
2278
2279 #[test]
2282 fn resolve_session_paths_non_git_fallback() {
2283 let tmp = tempfile::tempdir().unwrap();
2284 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
2286 let project_root = resolved.root;
2287
2288 assert_eq!(
2289 project_root,
2290 tmp.path(),
2291 "non-git: project_root must fall back to hook_cwd"
2292 );
2293 assert_eq!(
2294 session_dir,
2295 tmp.path()
2296 .join(".tracevault")
2297 .join("sessions")
2298 .join("sess-fallback-789"),
2299 "non-git: session_dir must be relative to the fallback root"
2300 );
2301 }
2302
2303 #[test]
2308 fn origin_marker_written_in_session_dir() {
2309 let tmp = tempfile::tempdir().unwrap();
2310 let repo = tmp.path().join("repo");
2311 std::fs::create_dir_all(&repo).unwrap();
2312 init_git_repo(&repo);
2313
2314 let session_dir = repo
2315 .join(".tracevault")
2316 .join("sessions")
2317 .join("test-sess-001");
2318 std::fs::create_dir_all(&session_dir).unwrap();
2319
2320 let hook_cwd = &repo;
2321 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2322 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2323
2324 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2325 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2326 assert_eq!(
2327 origin_content.trim(),
2328 expected.as_str(),
2329 "origin marker must contain the canonicalized worktree toplevel"
2330 );
2331 }
2332
2333 fn metadata(session_dir: &Path) -> serde_json::Value {
2334 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2335 .unwrap()
2336 }
2337
2338 #[test]
2339 fn record_transcript_path_writes_metadata_for_check() {
2340 let tmp = tempfile::tempdir().unwrap();
2341 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2342 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2343 }
2344
2345 #[test]
2346 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2347 let tmp = tempfile::tempdir().unwrap();
2348 std::fs::write(
2349 tmp.path().join("metadata.json"),
2350 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2351 )
2352 .unwrap();
2353 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2354 let m = metadata(tmp.path());
2355 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2356 assert_eq!(m["model"], "m");
2357 let leftovers = std::fs::read_dir(tmp.path())
2358 .unwrap()
2359 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2360 .count();
2361 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2362 }
2363
2364 #[test]
2365 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2366 let tmp = tempfile::tempdir().unwrap();
2367 record_transcript_path(tmp.path(), "").unwrap();
2368 assert!(!tmp.path().join("metadata.json").exists());
2369
2370 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2371 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2372 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2373 }
2374
2375 use crate::session_state::{RepoBinding, SessionState};
2378
2379 fn binding(id: &str) -> RepoBinding {
2380 RepoBinding {
2381 repo_id: id.into(),
2382 git_url: None,
2383 remote_id: None,
2384 codebase_name: None,
2385 updated_at: "t".into(),
2386 }
2387 }
2388
2389 #[test]
2392 fn resolve_stream_binding_uses_session_active_when_unbound() {
2393 let session = SessionState {
2394 active: Some(binding("session-repo")),
2395 subagents: HashMap::new(),
2396 ..Default::default()
2397 };
2398 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2399 assert_eq!(got.unwrap().repo_id, "session-repo");
2400 }
2401
2402 #[test]
2405 fn resolve_stream_binding_falls_back_to_bound_config() {
2406 let session = SessionState::default();
2407 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2408 assert_eq!(got.unwrap().repo_id, "bound-repo");
2409 }
2410
2411 #[test]
2414 fn resolve_stream_binding_none_when_nothing_resolves() {
2415 let session = SessionState::default();
2416 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2417 assert!(got.is_none());
2418 }
2419
2420 #[test]
2423 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2424 let session = SessionState {
2425 active: Some(binding("session-repo")),
2426 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2427 ..Default::default()
2428 };
2429 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2430 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2431 }
2432
2433 #[test]
2437 fn resolve_stream_binding_falls_back_to_user_default() {
2438 let session = SessionState::default();
2439 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2440 assert_eq!(got.unwrap().repo_id, "userdef");
2441 }
2442
2443 #[test]
2446 fn resolve_stream_binding_prefers_bound_over_user_default() {
2447 let session = SessionState::default();
2448 let got = resolve_stream_binding(
2449 &session,
2450 "/wt/x",
2451 Some(binding("bound")),
2452 Some(binding("userdef")),
2453 );
2454 assert_eq!(got.unwrap().repo_id, "bound");
2455 }
2456
2457 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2460 crate::session_state::RepoBinding {
2461 repo_id: repo_id.into(),
2462 git_url: None,
2463 remote_id: None,
2464 codebase_name: None,
2465 updated_at: String::new(),
2466 }
2467 }
2468
2469 #[test]
2473 fn attribution_falls_back_to_project_when_no_repo_binds() {
2474 let pid = uuid::Uuid::new_v4();
2475 assert_eq!(
2476 attribution_for(None, Some(pid)),
2477 Some(Attribution::ProjectOnly { project_id: pid })
2478 );
2479 }
2480
2481 #[test]
2483 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2484 assert_eq!(attribution_for(None, None), None);
2485 }
2486
2487 #[test]
2490 fn attribution_uses_repo_with_no_project_overlay() {
2491 let repo = uuid::Uuid::new_v4().to_string();
2492 let b = binding_with(&repo);
2493 assert_eq!(
2494 attribution_for(Some(&b), None),
2495 Some(Attribution::Repo {
2496 repo_id: repo,
2497 project: None
2498 })
2499 );
2500 }
2501
2502 #[test]
2505 fn attribution_overlays_project_on_repo() {
2506 let repo = uuid::Uuid::new_v4().to_string();
2507 let pid = uuid::Uuid::new_v4();
2508 let b = binding_with(&repo);
2509 assert_eq!(
2510 attribution_for(Some(&b), Some(pid)),
2511 Some(Attribution::Repo {
2512 repo_id: repo,
2513 project: Some(pid)
2514 })
2515 );
2516 }
2517
2518 #[test]
2521 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2522 let pid = uuid::Uuid::new_v4();
2523 let b = binding_with("../../escape");
2524 assert_eq!(
2525 attribution_for(Some(&b), Some(pid)),
2526 Some(Attribution::ProjectOnly { project_id: pid })
2527 );
2528 }
2529
2530 #[test]
2533 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2534 let b = binding_with("../../escape");
2535 assert_eq!(attribution_for(Some(&b), None), None);
2536 }
2537
2538 #[test]
2543 fn pending_file_name_for_a_repo_is_unchanged() {
2544 let repo = uuid::Uuid::new_v4().to_string();
2545 assert_eq!(
2546 Attribution::Repo {
2547 repo_id: repo.clone(),
2548 project: Some(uuid::Uuid::new_v4())
2549 }
2550 .pending_file_name(),
2551 format!("pending-{repo}.jsonl")
2552 );
2553 }
2554
2555 #[test]
2558 fn pending_file_name_for_a_project_is_distinct() {
2559 let pid = uuid::Uuid::new_v4();
2560 assert_eq!(
2561 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2562 format!("pending-project-{pid}.jsonl")
2563 );
2564 }
2565
2566 #[test]
2569 fn binding_repo_id_is_valid_accepts_real_uuid() {
2570 assert!(binding_repo_id_is_valid(
2571 "550e8400-e29b-41d4-a716-446655440000"
2572 ));
2573 }
2574
2575 #[test]
2576 fn binding_repo_id_is_valid_rejects_path_traversal() {
2577 assert!(!binding_repo_id_is_valid("../evil"));
2578 }
2579
2580 #[test]
2581 fn binding_repo_id_is_valid_rejects_empty() {
2582 assert!(!binding_repo_id_is_valid(""));
2583 }
2584
2585 #[test]
2586 fn binding_repo_id_is_valid_rejects_non_uuid() {
2587 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2588 }
2589
2590 #[test]
2593 fn stamp_agent_sets_tool_and_version() {
2594 use crate::agent::Agent;
2595 let mut req = StreamEventRequest {
2596 protocol_version: 1,
2597 tool: Some("claude-code".to_string()),
2598 event_type: StreamEventType::ToolUse,
2599 session_id: "s".into(),
2600 timestamp: chrono::Utc::now(),
2601 hook_event_name: None,
2602 tool_name: None,
2603 tool_use_id: None,
2604 tool_input: None,
2605 tool_response: None,
2606 tool_is_error: None,
2607 event_index: None,
2608 event_uuid: None,
2609 transcript_lines: None,
2610 transcript_offset: None,
2611 model: None,
2612 cwd: None,
2613 final_stats: None,
2614 flow_id: None,
2615 labels: None,
2616 params: None,
2617 billing_mode: None,
2618 };
2619 stamp_agent(&mut req, Agent::Codex);
2620 assert_eq!(req.tool.as_deref(), Some("codex"));
2621 assert_eq!(req.protocol_version, 2);
2622
2623 stamp_agent(&mut req, Agent::ClaudeCode);
2624 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2625 assert_eq!(req.protocol_version, 1);
2626 }
2627
2628 fn repo_attr(repo_id: &str) -> Attribution {
2631 Attribution::Repo {
2632 repo_id: repo_id.into(),
2633 project: None,
2634 }
2635 }
2636
2637 #[test]
2638 fn pending_path_is_repo_scoped() {
2639 let dir = std::path::Path::new("/tmp/sess");
2640 assert_eq!(
2641 pending_path_for(dir, &repo_attr("repo-a")),
2642 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2643 );
2644 assert_ne!(
2645 pending_path_for(dir, &repo_attr("repo-a")),
2646 pending_path_for(dir, &repo_attr("repo-b")),
2647 );
2648 }
2649
2650 #[test]
2653 fn pending_path_for_a_project_never_collides_with_a_repo() {
2654 let dir = std::path::Path::new("/tmp/sess");
2655 let pid = uuid::Uuid::from_u128(9);
2656 assert_eq!(
2657 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2658 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2659 );
2660 assert_ne!(
2661 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2662 pending_path_for(dir, &repo_attr(&pid.to_string())),
2663 );
2664 }
2665
2666 #[test]
2669 fn read_new_transcript_lines_empty_path_is_noop() {
2670 let dir = tempfile::tempdir().unwrap();
2674 let offset_path = dir.path().join(".stream_offset");
2675 let (lines, start_offset, end_offset) =
2676 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2677 assert!(
2678 lines.is_empty(),
2679 "empty path must yield no transcript lines"
2680 );
2681 assert_eq!(start_offset, 0);
2682 assert_eq!(end_offset, 0);
2683 }
2684
2685 #[test]
2689 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2690 let dir = tempfile::tempdir().unwrap();
2691 let transcript_path = dir.path().join("transcript.jsonl");
2692 let offset_path = dir.path().join(".stream_offset");
2693
2694 fs::write(
2695 &transcript_path,
2696 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2697 )
2698 .unwrap();
2699
2700 let (lines, start_offset, end_offset) =
2701 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2702 assert_eq!(lines.len(), 2);
2703 assert_eq!(start_offset, 0, "first read starts at byte 0");
2704 assert!(end_offset > 0);
2705
2706 fs::write(&offset_path, end_offset.to_string()).unwrap();
2707
2708 let mut f = OpenOptions::new()
2709 .append(true)
2710 .open(&transcript_path)
2711 .unwrap();
2712 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2713 drop(f);
2714
2715 let (lines2, start_offset2, end_offset2) =
2716 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2717 assert_eq!(lines2.len(), 1);
2718 assert_eq!(
2719 start_offset2, end_offset,
2720 "second read's start_offset must equal the first read's persisted end_offset"
2721 );
2722 assert!(end_offset2 > start_offset2);
2723 }
2724
2725 #[tokio::test]
2743 async fn capture_project_precedence_local_only() {
2744 use crate::session_state::{ProjectBinding, SessionState};
2745 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2746 let tmp = tempfile::tempdir().unwrap();
2747 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2748 _guard.set("XDG_CONFIG_HOME", tmp.path());
2749 _guard.set("HOME", tmp.path());
2750 _guard.remove("TRACEVAULT_PROJECT");
2751
2752 let pb = |id: &str| ProjectBinding {
2753 project_id: id.into(),
2754 project_name: "n".into(),
2755 updated_at: "".into(),
2756 forced_until: None,
2757 };
2758 let u = uuid::Uuid::from_u128;
2759 let s = SessionState {
2761 active_project: Some(pb(&u(2).to_string())),
2762 ..Default::default()
2763 };
2764 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(2)));
2765 let mut s = s;
2767 s.subagent_projects
2768 .insert("/wt".into(), pb(&u(1).to_string()));
2769 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(1)));
2770 assert_eq!(capture_project(&s, Some("/other"), None), Some(u(2)));
2772 assert_eq!(capture_project(&SessionState::default(), None, None), None);
2774 let bad = SessionState {
2776 active_project: Some(pb("not-a-uuid")),
2777 ..Default::default()
2778 };
2779 assert_eq!(capture_project(&bad, None, None), None);
2780 let path = crate::user_project_default::default_project_path().unwrap();
2782 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2783 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2784 assert_eq!(
2785 capture_project(&SessionState::default(), None, None),
2786 Some(u(3))
2787 );
2788 }
2789
2790 #[test]
2801 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2802 use crate::session_state::{ProjectBinding, SessionState};
2803 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2804 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2805 _guard.remove("TRACEVAULT_PROJECT");
2806 let pid = uuid::Uuid::from_u128(2);
2807 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2808 let s = SessionState {
2809 active_project: Some(ProjectBinding {
2810 project_id: pid.to_string(),
2811 project_name: "n".into(),
2812 updated_at: "".into(),
2813 forced_until: Some(future.clone()),
2814 }),
2815 ..Default::default()
2816 };
2817 let got = capture_binding(&s, Some("/wt"), None).expect("session-active binding resolves");
2818 assert_eq!(got.forced_until, Some(future));
2819 }
2820
2821 #[test]
2826 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2827 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2831
2832 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2833 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2834
2835 _guard.set("TRACEVAULT_PROJECT", uuid);
2836 let got = env_project_binding().expect("uuid form is honoured");
2837 assert_eq!(got.project_id, uuid);
2838
2839 _guard.set("TRACEVAULT_PROJECT", "my-project");
2840 assert!(
2841 env_project_binding().is_none(),
2842 "a name is ignored on the network-free capture path"
2843 );
2844
2845 _guard.remove("TRACEVAULT_PROJECT");
2846 assert!(env_project_binding().is_none());
2847 }
2848
2849 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2857 crate::session_state::ProjectBinding {
2858 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2859 project_name: "p".into(),
2860 updated_at: chrono::Utc::now().to_rfc3339(),
2861 forced_until: forced_until.map(str::to_string),
2862 }
2863 }
2864
2865 #[test]
2866 fn env_force_is_explicit_and_needs_no_expiry() {
2867 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2868 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2869 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2870
2871 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2872 }
2873
2874 #[test]
2875 fn absent_or_unrecognised_env_is_derived() {
2876 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2877 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2878
2879 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2880 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2881
2882 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2887 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2888 }
2889
2890 #[test]
2896 fn live_binding_force_is_explicit_without_env() {
2897 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2898 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2899 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2900
2901 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2902 let binding = forced_binding(Some(&future));
2903
2904 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2905 }
2906
2907 #[test]
2914 fn lapsed_binding_force_is_derived_without_env() {
2915 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2916 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2917 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2918
2919 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2920 let binding = forced_binding(Some(&past));
2921
2922 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2923 }
2924
2925 #[test]
2930 fn unparseable_forced_until_is_derived() {
2931 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2932 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2933 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2934
2935 let binding = forced_binding(Some("not-a-timestamp"));
2936
2937 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2938 }
2939
2940 #[test]
2947 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2948 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2949 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2950 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2951
2952 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2953 let binding = forced_binding(Some(&past));
2954
2955 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2956 }
2957
2958 #[tokio::test]
2971 async fn session_scoped_force_is_honoured_on_the_wire() {
2972 use crate::session_state::{ProjectBinding, SessionState};
2973
2974 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2975 let tmp = tempfile::tempdir().unwrap();
2976 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2977 _guard.set("XDG_CONFIG_HOME", tmp.path());
2981 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2982 _guard.remove("TRACEVAULT_PROJECT");
2986
2987 let pid = uuid::Uuid::from_u128(321);
2988 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2989 let session = SessionState {
2990 active_project: Some(ProjectBinding {
2991 project_id: pid.to_string(),
2992 project_name: "proj".into(),
2993 updated_at: "".into(),
2994 forced_until: Some(future),
2995 }),
2996 ..Default::default()
2997 };
2998 let capture_binding = capture_binding(&session, None, None);
2999
3000 let resp = ok_stream_response();
3001 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3002 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3003 let req = sample_stream_event_request();
3004 let mut warned = false;
3005
3006 let got = send_stream_event(
3007 &client,
3008 &Attribution::ProjectOnly { project_id: pid },
3009 attribution_force(capture_binding.as_ref()),
3010 &req,
3011 &mut warned,
3012 )
3013 .await
3014 .expect("send_stream_event must succeed");
3015 assert_eq!(got.status, "accepted");
3016
3017 let captured = rx
3018 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3019 .expect("no request captured");
3020 assert!(
3021 captured
3022 .to_lowercase()
3023 .contains("x-tracevault-project-attribution: explicit"),
3024 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
3025 );
3026 }
3027
3028 #[test]
3037 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
3038 use crate::session_state::{ProjectBinding, SessionState};
3039
3040 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3041 let tmp = tempfile::tempdir().unwrap();
3042 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3043 _guard.set("XDG_CONFIG_HOME", tmp.path());
3044 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3045
3046 let project_a = uuid::Uuid::from_u128(1);
3047 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3048 crate::user_project_default::save(&ProjectBinding {
3049 project_id: project_a.to_string(),
3050 project_name: "a".into(),
3051 updated_at: chrono::Utc::now().to_rfc3339(),
3052 forced_until: Some(future),
3053 })
3054 .unwrap();
3055
3056 let project_b = uuid::Uuid::from_u128(2);
3057 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
3058
3059 let capture_binding = capture_binding(&SessionState::default(), None, None);
3060 assert_eq!(
3061 capture_binding.as_ref().map(|b| b.project_id.as_str()),
3062 Some(project_b.to_string()).as_deref(),
3063 "TRACEVAULT_PROJECT must outrank the user-level default"
3064 );
3065
3066 assert_eq!(
3067 attribution_mode(capture_binding.as_ref()),
3068 AttributionMode::Derived,
3069 "a force on the user-default project must not leak onto a DIFFERENT, \
3070 higher-precedence project that never asked to be forced"
3071 );
3072 }
3073
3074 use std::io::BufReader;
3077 use std::net::TcpListener;
3078 use std::sync::mpsc;
3079 use std::thread;
3080 use std::time::{Duration, Instant};
3081
3082 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
3087
3088 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
3093 let deadline = Instant::now() + ACCEPT_DEADLINE;
3094 loop {
3095 match listener.accept() {
3096 Ok((stream, _)) => {
3097 let _ = stream.set_nonblocking(false);
3102 return Some(stream);
3103 }
3104 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
3105 if Instant::now() >= deadline {
3106 return None;
3107 }
3108 thread::sleep(Duration::from_millis(20));
3109 }
3110 Err(_) => return None,
3111 }
3112 }
3113 }
3114
3115 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
3119
3120 fn capture_request_and_respond(
3140 stream: std::net::TcpStream,
3141 tx: &mpsc::Sender<String>,
3142 response: &str,
3143 ) {
3144 let mut reader = BufReader::new(stream);
3145 let mut captured = String::new();
3146 let _ = reader.read_line(&mut captured);
3147 loop {
3148 let mut header = String::new();
3149 if reader.read_line(&mut header).unwrap_or(0) == 0 {
3150 break;
3151 }
3152 if header.trim().is_empty() {
3153 break;
3154 }
3155 captured.push_str(&header);
3156 }
3157 let _ = tx.send(captured);
3158 let mut stream = reader.into_inner();
3159 let _ = stream.write_all(response.as_bytes());
3160 let _ = stream.flush();
3161 }
3162
3163 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
3168 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3169 listener.set_nonblocking(true).unwrap();
3170 let addr = listener.local_addr().unwrap();
3171 let (tx, rx) = mpsc::channel();
3172 thread::spawn(move || {
3173 if let Some(stream) = accept_with_deadline(&listener) {
3174 capture_request_and_respond(stream, &tx, response);
3175 }
3176 });
3177 (format!("http://{addr}"), rx)
3178 }
3179
3180 fn ok_stream_response() -> String {
3181 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
3182 session_db_id: uuid::Uuid::nil(),
3183 event_db_id: Some(uuid::Uuid::nil()),
3184 status: "accepted".to_string(),
3185 })
3186 .unwrap();
3187 format!(
3188 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3189 body.len(),
3190 body
3191 )
3192 }
3193
3194 fn sample_stream_event_request() -> StreamEventRequest {
3195 StreamEventRequest {
3196 protocol_version: 2,
3197 tool: Some("claude-code".to_string()),
3198 event_type: StreamEventType::ToolUse,
3199 session_id: "sess-1".into(),
3200 timestamp: chrono::Utc::now(),
3201 hook_event_name: Some("PostToolUse".into()),
3202 tool_name: None,
3203 tool_use_id: None,
3204 tool_input: None,
3205 tool_response: None,
3206 tool_is_error: None,
3207 event_index: None,
3208 event_uuid: None,
3209 transcript_lines: None,
3210 transcript_offset: None,
3211 model: None,
3212 cwd: None,
3213 final_stats: None,
3214 flow_id: None,
3215 labels: None,
3216 params: None,
3217 billing_mode: None,
3218 }
3219 }
3220
3221 #[tokio::test]
3226 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
3227 use crate::session_state::{ProjectBinding, SessionState};
3228
3229 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3233 let tmp = tempfile::tempdir().unwrap();
3234 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3235 _guard.set("XDG_CONFIG_HOME", tmp.path());
3236 _guard.remove("TRACEVAULT_PROJECT");
3241 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3242
3243 let pid = uuid::Uuid::from_u128(99);
3244 let session = SessionState {
3245 active_project: Some(ProjectBinding {
3246 project_id: pid.to_string(),
3247 project_name: "proj".into(),
3248 updated_at: "".into(),
3249 forced_until: None,
3250 }),
3251 ..Default::default()
3252 };
3253 let capture_binding = capture_binding(&session, None, None);
3254 let capture_pid = capture_binding
3255 .as_ref()
3256 .and_then(crate::resolution::capture_project_id);
3257 assert_eq!(capture_pid, Some(pid));
3258
3259 let resp = ok_stream_response();
3260 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3261 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3262 let req = sample_stream_event_request();
3263
3264 let mut warned = false;
3265 let got = send_stream_event(
3266 &client,
3267 &Attribution::Repo {
3268 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3269 project: capture_pid,
3270 },
3271 attribution_force(capture_binding.as_ref()),
3272 &req,
3273 &mut warned,
3274 )
3275 .await
3276 .expect("send_stream_event must succeed");
3277 assert_eq!(got.status, "accepted");
3278
3279 let line = rx
3280 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3281 .expect("no request captured");
3282 assert!(
3283 line.starts_with(&format!(
3284 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
3285 )),
3286 "an active project binding must route to the project-scoped endpoint, got: {line}"
3287 );
3288 assert!(
3294 line.to_lowercase()
3295 .contains("x-tracevault-project-attribution: derived"),
3296 "got: {line}"
3297 );
3298 }
3299
3300 #[tokio::test]
3305 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
3306 use crate::session_state::SessionState;
3307
3308 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3309 let tmp = tempfile::tempdir().unwrap();
3310 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3311 _guard.set("XDG_CONFIG_HOME", tmp.path());
3316 _guard.remove("TRACEVAULT_PROJECT");
3317
3318 let capture_binding = capture_binding(&SessionState::default(), None, None);
3319 assert_eq!(capture_binding, None);
3320
3321 let resp = ok_stream_response();
3322 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3323 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3324 let req = sample_stream_event_request();
3325
3326 let mut warned = false;
3327 let got = send_stream_event(
3328 &client,
3329 &Attribution::Repo {
3330 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3331 project: None,
3332 },
3333 attribution_force(capture_binding.as_ref()),
3334 &req,
3335 &mut warned,
3336 )
3337 .await
3338 .expect("send_stream_event must succeed");
3339 assert_eq!(got.status, "accepted");
3340
3341 let line = rx
3342 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3343 .expect("no request captured");
3344 assert!(
3345 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3346 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3347 );
3348 }
3349
3350 fn spawn_n_capturing_requests(
3361 responses: Vec<&'static str>,
3362 ) -> (String, mpsc::Receiver<String>) {
3363 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3364 listener.set_nonblocking(true).unwrap();
3365 let addr = listener.local_addr().unwrap();
3366 let (tx, rx) = mpsc::channel();
3367 thread::spawn(move || {
3368 for response in responses {
3369 let Some(stream) = accept_with_deadline(&listener) else {
3374 break;
3375 };
3376 capture_request_and_respond(stream, &tx, response);
3377 }
3378 });
3383 (format!("http://{addr}"), rx)
3384 }
3385
3386 #[tokio::test]
3393 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3394 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3395 let resp_400 = format!(
3396 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3397 body_400.len(),
3398 body_400
3399 );
3400 let resp_200 = ok_stream_response();
3401
3402 let (base, rx) = spawn_n_capturing_requests(vec![
3403 Box::leak(resp_400.into_boxed_str()),
3404 Box::leak(resp_200.into_boxed_str()),
3405 ]);
3406 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3407 let req = sample_stream_event_request();
3408 let pid = uuid::Uuid::from_u128(42);
3409
3410 let mut warned = false;
3411 let err = send_stream_event(
3412 &client,
3413 &Attribution::Repo {
3414 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3415 project: Some(pid),
3416 },
3417 attribution_force(None),
3418 &req,
3419 &mut warned,
3420 )
3421 .await
3422 .expect_err("a refused declared project must be an error, not a silent fallback");
3423 assert!(
3424 err.to_string().contains("400"),
3425 "propagated error must reflect the status, got: {err}"
3426 );
3427 assert!(
3428 warned,
3429 "the refusal must be printed (gated on `warned`) so it is visible"
3430 );
3431
3432 let first = rx
3433 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3434 .expect("no first request captured");
3435 assert!(
3436 first.contains(&format!("/projects/{pid}/stream")),
3437 "first request must hit the project-scoped endpoint, got: {first}"
3438 );
3439 assert!(
3440 first.contains("repo_id="),
3441 "first request must carry repo_id, got: {first}"
3442 );
3443
3444 assert!(
3445 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3446 "no second (repo-scoped fallback) request must be sent"
3447 );
3448 }
3449
3450 #[tokio::test]
3453 async fn send_stream_event_errors_on_403_without_fallback() {
3454 let body_403 = "forbidden";
3455 let resp_403 = format!(
3456 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3457 body_403.len(),
3458 body_403
3459 );
3460 let resp_200 = ok_stream_response();
3461
3462 let (base, rx) = spawn_n_capturing_requests(vec![
3463 Box::leak(resp_403.into_boxed_str()),
3464 Box::leak(resp_200.into_boxed_str()),
3465 ]);
3466 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3467 let req = sample_stream_event_request();
3468 let pid = uuid::Uuid::from_u128(43);
3469
3470 let mut warned = false;
3471 let err = send_stream_event(
3472 &client,
3473 &Attribution::Repo {
3474 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3475 project: Some(pid),
3476 },
3477 attribution_force(None),
3478 &req,
3479 &mut warned,
3480 )
3481 .await
3482 .expect_err("a refused declared project must be an error, not a silent fallback");
3483 assert!(
3484 err.to_string().contains("403"),
3485 "propagated error must reflect the status, got: {err}"
3486 );
3487 assert!(
3488 warned,
3489 "the refusal must be printed (gated on `warned`) so it is visible"
3490 );
3491
3492 let first = rx
3493 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3494 .expect("no first request captured");
3495 assert!(
3496 first.contains(&format!("/projects/{pid}/stream")),
3497 "first request must hit the project-scoped endpoint, got: {first}"
3498 );
3499 assert!(
3500 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3501 "no second (repo-scoped fallback) request must be sent"
3502 );
3503 }
3504
3505 #[tokio::test]
3510 async fn refused_error_is_printed_once_per_invocation() {
3511 let body_400 = "not a member";
3512 let resp_400 = || {
3513 format!(
3514 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3515 body_400.len(),
3516 body_400
3517 )
3518 };
3519 let (base, _rx) = spawn_n_capturing_requests(vec![
3520 Box::leak(resp_400().into_boxed_str()),
3521 Box::leak(resp_400().into_boxed_str()),
3522 ]);
3523 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3524 let req = sample_stream_event_request();
3525 let pid = uuid::Uuid::from_u128(44);
3526 let attribution = Attribution::Repo {
3527 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3528 project: Some(pid),
3529 };
3530
3531 let mut warned = false;
3532 assert!(
3533 send_stream_event(
3534 &client,
3535 &attribution,
3536 attribution_force(None),
3537 &req,
3538 &mut warned
3539 )
3540 .await
3541 .is_err(),
3542 "a refused declared project must be an error"
3543 );
3544 assert!(warned, "the flag must be set after the first refusal");
3545
3546 assert!(
3547 send_stream_event(
3548 &client,
3549 &attribution,
3550 attribution_force(None),
3551 &req,
3552 &mut warned
3553 )
3554 .await
3555 .is_err(),
3556 "a second refusal must also be an error"
3557 );
3558 assert!(warned, "the flag stays set across the shared invocation");
3559 }
3560
3561 #[tokio::test]
3573 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3574 let body_403 = "forbidden";
3575 let resp_403 = format!(
3576 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3577 body_403.len(),
3578 body_403
3579 );
3580 let resp_200 = ok_stream_response();
3581
3582 let (base, rx) = spawn_n_capturing_requests(vec![
3583 Box::leak(resp_403.into_boxed_str()),
3584 Box::leak(resp_200.into_boxed_str()),
3585 ]);
3586 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3587 let req = sample_stream_event_request();
3588 let pid = uuid::Uuid::from_u128(42);
3589
3590 let forced = crate::session_state::ProjectBinding {
3593 project_id: pid.to_string(),
3594 project_name: "forced".into(),
3595 updated_at: "".into(),
3596 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3597 };
3598
3599 let mut warned = false;
3600 let err = send_stream_event(
3601 &client,
3602 &Attribution::Repo {
3603 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3604 project: Some(pid),
3605 },
3606 attribution_force(Some(&forced)),
3607 &req,
3608 &mut warned,
3609 )
3610 .await
3611 .expect_err("a refused force must be an error, not a silent fallback");
3612 assert!(
3613 err.to_string().contains("403"),
3614 "propagated error must reflect the status, got: {err}"
3615 );
3616 assert!(warned, "the refusal must be printed exactly once");
3617
3618 let first = rx
3619 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3620 .expect("no first request captured");
3621 assert!(
3622 first.contains(&format!("/projects/{pid}/stream")),
3623 "first request must hit the project-scoped endpoint, got: {first}"
3624 );
3625 assert!(
3626 first
3627 .to_lowercase()
3628 .contains("x-tracevault-project-attribution: explicit"),
3629 "the refused send must have DECLARED explicit — this is the mode \
3630 `refused_error` is handed: {first}"
3631 );
3632
3633 assert!(
3634 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3635 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3636 );
3637 }
3638
3639 #[tokio::test]
3648 async fn send_stream_event_project_only_omits_repo_id() {
3649 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3650 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3651 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3652
3653 let resp = ok_stream_response();
3654 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3655 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3656 let req = sample_stream_event_request();
3657 let pid = uuid::Uuid::from_u128(11);
3658
3659 let mut warned = false;
3660 let got = send_stream_event(
3661 &client,
3662 &Attribution::ProjectOnly { project_id: pid },
3663 attribution_force(None),
3664 &req,
3665 &mut warned,
3666 )
3667 .await
3668 .expect("a repo-less project send must succeed");
3669 assert_eq!(got.status, "accepted");
3670
3671 let line = rx
3672 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3673 .expect("no request captured");
3674 assert!(
3675 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3676 "expected a bare project path with no query string, got: {line}"
3677 );
3678 assert!(
3679 line.to_lowercase()
3680 .contains("x-tracevault-project-attribution: derived"),
3681 "with no forced binding, the header must declare `derived`, got: {line}"
3682 );
3683 assert!(
3684 !warned,
3685 "a repo-less send has no fallback and must not warn about one"
3686 );
3687 }
3688
3689 #[tokio::test]
3696 async fn send_stream_event_project_only_buffers_on_scoping_4xx() {
3697 let body = "no such project";
3698 let resp_404 = format!(
3699 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3700 body.len(),
3701 body
3702 );
3703 let (base, rx) = spawn_n_capturing_requests(vec![
3710 Box::leak(resp_404.clone().into_boxed_str()),
3711 Box::leak(resp_404.into_boxed_str()),
3712 ]);
3713 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3714 let req = sample_stream_event_request();
3715 let pid = uuid::Uuid::from_u128(12);
3716
3717 let mut warned = false;
3718 let err = send_stream_event(
3719 &client,
3720 &Attribution::ProjectOnly { project_id: pid },
3721 attribution_force(None),
3722 &req,
3723 &mut warned,
3724 )
3725 .await
3726 .expect_err("a refused repo-less send must propagate so the caller buffers it");
3727 assert_eq!(
3728 deterministic_client_error_kind(err.as_ref()),
3729 Some(ClientErrorKind::Scoping),
3730 "the original 404 must propagate unchanged, got: {err}"
3731 );
3732 assert!(warned, "the refusal is printed (once per invocation)");
3733
3734 let first = rx
3735 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3736 .expect("no request captured");
3737 assert!(
3738 first.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3739 "must hit the bare project-scoped endpoint, got: {first}"
3740 );
3741 assert!(
3742 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3743 "a repo-less send must make exactly one request — no fallback exists"
3744 );
3745 }
3746
3747 #[test]
3751 fn refused_project_only_error_wording() {
3752 let pid = uuid::Uuid::from_u128(0x55);
3753 let scoping =
3754 refused_project_only_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3755 assert!(scoping.starts_with("tracevault: error:"), "{scoping}");
3756 assert!(scoping.contains(&pid.to_string()), "{scoping}");
3757 assert!(scoping.contains("queued"), "{scoping}");
3758 assert!(!scoping.contains("DROPPED"), "{scoping}");
3759 assert!(!scoping.contains("this repo"), "{scoping}");
3760 assert!(scoping.contains("tracevault repo switch"), "{scoping}");
3761
3762 let forbidden = refused_project_only_error(
3763 pid,
3764 &ClientErrorKind::Forbidden,
3765 AttributionForce::default(),
3766 );
3767 assert!(forbidden.contains("(403)"), "{forbidden}");
3768 assert!(forbidden.contains("queued"), "{forbidden}");
3769 assert!(!forbidden.contains("FORCE"), "derived send: {forbidden}");
3770
3771 let forced = AttributionForce {
3772 env: true,
3773 binding: false,
3774 };
3775 let explicit = refused_project_only_error(pid, &ClientErrorKind::Forbidden, forced);
3776 assert!(
3777 explicit.contains("FORCE itself"),
3778 "an explicit 403 must name the force, like the repo-scoped line: {explicit}"
3779 );
3780 assert!(
3781 !refused_project_only_error(pid, &ClientErrorKind::Scoping, forced)
3782 .contains("FORCE itself"),
3783 "a Scoping refusal never ran the force gate"
3784 );
3785 }
3786
3787 #[test]
3790 fn recording_line_names_each_attribution_shape() {
3791 let pid = uuid::Uuid::from_u128(0x99);
3792 let repo = "11111111-1111-1111-1111-111111111111".to_string();
3793 let only = recording_line(Some(&Attribution::ProjectOnly { project_id: pid }));
3794 assert!(only.starts_with("recording: project "), "{only}");
3795 assert!(
3796 only.contains(&pid.to_string()) && only.contains("no repo"),
3797 "{only}"
3798 );
3799 let both = recording_line(Some(&Attribution::Repo {
3800 repo_id: repo.clone(),
3801 project: Some(pid),
3802 }));
3803 assert!(
3804 both.contains(&repo) && both.contains(&pid.to_string()),
3805 "{both}"
3806 );
3807 let deduced = recording_line(Some(&Attribution::Repo {
3808 repo_id: repo.clone(),
3809 project: None,
3810 }));
3811 assert!(
3812 deduced.contains(&repo) && deduced.contains("deduces"),
3813 "{deduced}"
3814 );
3815 let none = recording_line(None);
3816 assert!(none.starts_with("recording: nothing"), "{none}");
3817 }
3818
3819 fn repo_binding(id: &str) -> crate::session_state::RepoBinding {
3820 crate::session_state::RepoBinding {
3821 repo_id: id.into(),
3822 git_url: None,
3823 remote_id: None,
3824 codebase_name: None,
3825 updated_at: "t".into(),
3826 }
3827 }
3828
3829 fn inferring_session(
3831 pid: uuid::Uuid,
3832 checkout: &str,
3833 repo: &str,
3834 ) -> crate::session_state::SessionState {
3835 let mut state = crate::session_state::SessionState {
3836 active_project: Some(crate::session_state::ProjectBinding {
3837 project_id: pid.to_string(),
3838 project_name: "p".into(),
3839 updated_at: "t".into(),
3840 forced_until: None,
3841 }),
3842 ..Default::default()
3843 };
3844 state.inferred_repos.insert(
3845 checkout.into(),
3846 crate::session_state::InferredRepo {
3847 project_id: pid.to_string(),
3848 retry_after: None,
3849 repo: Some(repo_binding(repo)),
3850 },
3851 );
3852 state
3853 }
3854
3855 #[test]
3858 fn attribution_with_inference_never_overrides_a_binding() {
3859 let pid = uuid::Uuid::from_u128(0x1258);
3860 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3861 let inferred = repo_binding("22222222-2222-2222-2222-222222222222");
3862 let repo = |id: &str| Attribution::Repo {
3863 repo_id: id.into(),
3864 project: Some(pid),
3865 };
3866
3867 assert_eq!(
3868 attribution_with_inference(None, Some(pid), Some(&inferred)),
3869 Some(repo(&inferred.repo_id))
3870 );
3871 assert_eq!(
3872 attribution_with_inference(Some(&bound), Some(pid), Some(&inferred)),
3873 Some(repo(&bound.repo_id))
3874 );
3875 let corrupt = repo_binding("not-a-uuid");
3878 assert_eq!(
3879 attribution_with_inference(Some(&corrupt), Some(pid), Some(&inferred)),
3880 Some(Attribution::ProjectOnly { project_id: pid })
3881 );
3882 assert_eq!(
3884 attribution_with_inference(None, None, Some(&inferred)),
3885 None
3886 );
3887 assert_eq!(
3888 attribution_with_inference(None, Some(pid), Some(&corrupt)),
3889 Some(Attribution::ProjectOnly { project_id: pid })
3890 );
3891 }
3892
3893 #[test]
3896 fn recording_attribution_labels_an_inferred_repo() {
3897 let pid = uuid::Uuid::from_u128(0x1258);
3898 let repo = "22222222-2222-2222-2222-222222222222";
3899 let state = inferring_session(pid, "/umbrella/child", repo);
3900
3901 let here = recording_attribution_for(&state, "/umbrella/child", None, None, None);
3902 assert_eq!(
3903 here.attribution,
3904 Some(Attribution::Repo {
3905 repo_id: repo.into(),
3906 project: Some(pid)
3907 })
3908 );
3909 assert_eq!(here.inferred_from.as_deref(), Some("/umbrella/child"));
3910 let line = recording_line_for(&here);
3911 assert!(
3912 line.contains(repo) && line.contains("inferred from the checkout /umbrella/child"),
3913 "{line}"
3914 );
3915
3916 let elsewhere = recording_attribution_for(&state, "/umbrella", None, None, None);
3917 assert_eq!(
3918 elsewhere.attribution,
3919 Some(Attribution::ProjectOnly { project_id: pid })
3920 );
3921 assert_eq!(elsewhere.inferred_from, None);
3922 assert_eq!(
3923 recording_line_for(&elsewhere),
3924 recording_line(elsewhere.attribution.as_ref())
3925 );
3926
3927 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3929 let explicit =
3930 recording_attribution_for(&state, "/umbrella/child", Some(bound.clone()), None, None);
3931 assert_eq!(
3932 explicit.attribution,
3933 Some(Attribution::Repo {
3934 repo_id: bound.repo_id,
3935 project: Some(pid)
3936 })
3937 );
3938 assert_eq!(explicit.inferred_from, None);
3939
3940 let mut from_config = state.clone();
3943 from_config.active_project = None;
3944 let workspace = crate::session_state::ProjectBinding {
3945 project_id: pid.to_string(),
3946 project_name: String::new(),
3947 updated_at: String::new(),
3948 forced_until: None,
3949 };
3950 let via_config =
3951 recording_attribution_for(&from_config, "/umbrella/child", None, None, Some(workspace));
3952 assert_eq!(via_config.inferred_from.as_deref(), Some("/umbrella/child"));
3953 }
3954
3955 #[test]
3956 fn adopt_queue_puts_the_older_queue_first_and_removes_it() {
3957 let dir = tempfile::tempdir().unwrap();
3958 let from = dir.path().join("pending-project-x.jsonl");
3959 let into = dir.path().join("pending-r.jsonl");
3960 std::fs::write(&from, "a1\na2").unwrap(); std::fs::write(&into, "r1\n").unwrap();
3962 adopt_queue(&from, &into).unwrap();
3963 assert!(!from.exists());
3964 assert_eq!(drain_pending(&into).unwrap(), vec!["a1", "a2", "r1"]);
3965 assert!(
3966 !dir.path().join("pending-r.jsonl.adopting").exists(),
3967 "no temp file left behind"
3968 );
3969 }
3970
3971 #[test]
3972 fn adopt_queue_without_a_source_is_a_no_op() {
3973 let dir = tempfile::tempdir().unwrap();
3974 let into = dir.path().join("pending-r.jsonl");
3975 std::fs::write(&into, "r1\n").unwrap();
3976 adopt_queue(&dir.path().join("absent.jsonl"), &into).unwrap();
3977 assert_eq!(drain_pending(&into).unwrap(), vec!["r1"]);
3978 }
3979
3980 #[test]
3983 fn adopt_queue_failure_leaves_the_source_intact() {
3984 let dir = tempfile::tempdir().unwrap();
3985 let from = dir.path().join("pending-project-x.jsonl");
3986 let into = dir.path().join("pending-r.jsonl");
3987 std::fs::write(&from, "a1\n").unwrap();
3988 std::fs::create_dir(&into).unwrap(); assert!(adopt_queue(&from, &into).is_err());
3990 assert_eq!(std::fs::read_to_string(&from).unwrap(), "a1\n");
3991 }
3992
3993 #[test]
3994 fn adopted_project_queue_only_for_the_same_project() {
3995 let dir = Path::new("/tmp/sess");
3996 let pid = uuid::Uuid::from_u128(0x77);
3997 let repo_id = "11111111-1111-1111-1111-111111111111".to_string();
3998 assert_eq!(
3999 adopted_project_queue(
4000 dir,
4001 &Attribution::Repo {
4002 repo_id: repo_id.clone(),
4003 project: Some(pid),
4004 }
4005 ),
4006 Some(dir.join(format!("pending-project-{pid}.jsonl")))
4007 );
4008 assert_eq!(
4009 adopted_project_queue(
4010 dir,
4011 &Attribution::Repo {
4012 repo_id,
4013 project: None,
4014 }
4015 ),
4016 None,
4017 "with no declared project the server deduces one; adopting would re-attribute"
4018 );
4019 assert_eq!(
4020 adopted_project_queue(dir, &Attribution::ProjectOnly { project_id: pid }),
4021 None,
4022 "a project-only target already drains its own queue"
4023 );
4024 }
4025
4026 #[tokio::test]
4030 async fn send_stream_event_project_only_buffers_on_403() {
4031 let body = "forbidden";
4032 let resp_403 = format!(
4033 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4034 body.len(),
4035 body
4036 );
4037 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
4038 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4039 let req = sample_stream_event_request();
4040
4041 let mut warned = false;
4042 let err = send_stream_event(
4043 &client,
4044 &Attribution::ProjectOnly {
4045 project_id: uuid::Uuid::from_u128(13),
4046 },
4047 attribution_force(None),
4048 &req,
4049 &mut warned,
4050 )
4051 .await
4052 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
4053 assert!(
4054 err.to_string().contains("403"),
4055 "propagated error must reflect the status, got: {err}"
4056 );
4057 }
4058
4059 #[tokio::test]
4064 async fn send_stream_event_does_not_fall_back_on_transient_503() {
4065 let body_503 = "internal error";
4066 let resp_503 = format!(
4067 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4068 body_503.len(),
4069 body_503
4070 );
4071 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
4072 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4073 let req = sample_stream_event_request();
4074 let pid = uuid::Uuid::from_u128(7);
4075
4076 let mut warned = false;
4077 let err = send_stream_event(
4078 &client,
4079 &Attribution::Repo {
4080 repo_id: "11111111-1111-1111-1111-111111111111".into(),
4081 project: Some(pid),
4082 },
4083 attribution_force(None),
4084 &req,
4085 &mut warned,
4086 )
4087 .await
4088 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
4089 assert!(
4090 err.to_string().contains("503"),
4091 "propagated error must reflect the transient status, got: {err}"
4092 );
4093 assert!(
4094 deterministic_client_error_kind(err.as_ref()).is_none(),
4095 "a 503 must not be classified as a deterministic client error"
4096 );
4097
4098 let first = rx
4099 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4100 .expect("no request captured");
4101 assert!(
4102 first.contains(&format!("/projects/{pid}/stream")),
4103 "must hit the project-scoped endpoint, got: {first}"
4104 );
4105
4106 assert!(
4113 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
4114 "no second (fallback) request should have been sent for a transient error"
4115 );
4116 }
4117
4118 #[test]
4122 fn a_403_is_classified_apart_from_the_scoping_statuses() {
4123 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
4124 assert_eq!(
4125 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
4126 Some(ClientErrorKind::Forbidden)
4127 );
4128 for scoping in [
4129 "Stream failed (400 Bad Request): {}",
4130 "Stream failed (404 Not Found): {}",
4131 "Stream failed (409 Conflict): {}",
4132 ] {
4133 assert_eq!(
4134 deterministic_client_error_kind(err(scoping).as_ref()),
4135 Some(ClientErrorKind::Scoping),
4136 "{scoping}"
4137 );
4138 }
4139 for transient in [
4142 "Stream failed (401 Unauthorized): {}",
4143 "Stream failed (503 Service Unavailable): {}",
4144 "error sending request for url (http://x/stream)",
4145 ] {
4146 assert_eq!(
4147 deterministic_client_error_kind(err(transient).as_ref()),
4148 None,
4149 "{transient}"
4150 );
4151 }
4152 }
4153
4154 #[test]
4159 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
4160 let pid = uuid::Uuid::from_u128(7);
4161
4162 let forbidden = refused_error(
4163 pid,
4164 &ClientErrorKind::Forbidden,
4165 AttributionForce::default(),
4166 );
4167 assert!(forbidden.contains("403"), "{forbidden}");
4168 assert!(
4169 forbidden.contains("no `tracevault` grant in Control Plane"),
4170 "must offer the missing-role explanation: {forbidden}"
4171 );
4172 assert!(
4173 forbidden.contains("no `Operator` role on it"),
4174 "must still offer the project explanation: {forbidden}"
4175 );
4176 assert!(
4177 forbidden.starts_with("tracevault: error:"),
4178 "a refusal is an error, not a warning: {forbidden}"
4179 );
4180 assert!(forbidden.contains(&pid.to_string()));
4181
4182 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
4185 assert!(scoping.contains("project switch"), "{scoping}");
4186 assert!(
4187 !scoping.contains("`tracevault` grant"),
4188 "the scoping case must not mention the `tracevault` grant: {scoping}"
4189 );
4190
4191 for s in [&forbidden, &scoping] {
4192 assert!(s.contains("--user"), "must name the --user fix: {s}");
4195 assert!(
4196 s.contains("user_project.toml"),
4197 "must name the machine-wide default's file: {s}"
4198 );
4199 assert!(
4200 !s.contains("repo deduction"),
4201 "must never describe re-attribution to another project: {s}"
4202 );
4203 assert!(
4204 !s.contains("Attributing via"),
4205 "must never claim the event was re-attributed: {s}"
4206 );
4207 }
4208 }
4209
4210 #[test]
4221 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
4222 let pid = uuid::Uuid::from_u128(7);
4223
4224 let explicit = refused_error(
4225 pid,
4226 &ClientErrorKind::Forbidden,
4227 AttributionForce {
4228 env: false,
4229 binding: true,
4230 },
4231 );
4232 assert!(
4233 explicit.contains("FORCE"),
4234 "the refusal of the force itself must be named: {explicit}"
4235 );
4236 assert!(
4237 explicit.contains("Operator"),
4238 "must name the grant forcing requires: {explicit}"
4239 );
4240 assert!(
4241 explicit.contains("Control Plane"),
4242 "must name the identity forcing requires: {explicit}"
4243 );
4244 assert!(
4248 explicit.contains("`tracevault` grant")
4249 && explicit.contains("no `Operator` role on it"),
4250 "the membership causes must still be named: {explicit}"
4251 );
4252 assert!(
4255 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
4256 "must never claim the event was re-attributed: {explicit}"
4257 );
4258
4259 let derived = refused_error(
4264 pid,
4265 &ClientErrorKind::Forbidden,
4266 AttributionForce::default(),
4267 );
4268 assert!(
4269 !derived.contains("FORCE"),
4270 "a `derived` send never forced anything: {derived}"
4271 );
4272 }
4273
4274 #[test]
4279 fn an_explicit_scoping_failure_does_not_blame_the_force() {
4280 let pid = uuid::Uuid::from_u128(7);
4281 let scoping = refused_error(
4282 pid,
4283 &ClientErrorKind::Scoping,
4284 AttributionForce {
4285 env: true,
4286 binding: true,
4287 },
4288 );
4289 assert!(!scoping.contains("FORCE"), "{scoping}");
4290 assert_eq!(
4291 scoping,
4292 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
4293 "the scoping wording does not depend on the mode"
4294 );
4295 }
4296
4297 #[test]
4317 fn the_403_remediation_names_the_force_source_actually_in_effect() {
4318 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
4319 let mut _guard = crate::test_helpers::EnvVarGuard::new();
4320 let pid = uuid::Uuid::from_u128(7);
4321 let live = forced_binding(Some(
4322 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
4323 ));
4324 let never_forced = forced_binding(None);
4325
4326 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4330 let env_only = refused_error(
4331 pid,
4332 &ClientErrorKind::Forbidden,
4333 attribution_force(Some(&never_forced)),
4334 );
4335 assert!(
4336 env_only.contains("FORCE"),
4337 "an env-sourced force is still a force: {env_only}"
4338 );
4339 assert!(
4340 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
4341 "must name the variable that is doing the forcing: {env_only}"
4342 );
4343 assert!(
4344 !env_only.contains("--project-attribution"),
4345 "must NOT tell the operator to drop a flag that would change \
4346 nothing here — this is the bug: {env_only}"
4347 );
4348
4349 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
4353 let binding_only = refused_error(
4354 pid,
4355 &ClientErrorKind::Forbidden,
4356 attribution_force(Some(&live)),
4357 );
4358 assert!(
4359 binding_only.contains("--project-attribution"),
4360 "a persisted force IS cleared by switching without the flag: {binding_only}"
4361 );
4362 assert!(
4363 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
4364 "must not send the operator after an unset variable: {binding_only}"
4365 );
4366
4367 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4371 let both = refused_error(
4372 pid,
4373 &ClientErrorKind::Forbidden,
4374 attribution_force(Some(&live)),
4375 );
4376 assert!(
4377 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4378 && both.contains("--project-attribution"),
4379 "both sources are in effect and both must be named: {both}"
4380 );
4381 assert!(
4382 both.contains("BOTH"),
4383 "must say that removing only one is not enough: {both}"
4384 );
4385 }
4386
4387 #[test]
4392 fn no_force_means_no_remediation_clause() {
4393 let pid = uuid::Uuid::from_u128(7);
4394 let none = refused_error(
4395 pid,
4396 &ClientErrorKind::Forbidden,
4397 AttributionForce::default(),
4398 );
4399 assert!(
4400 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4401 && !none.contains("--project-attribution"),
4402 "a derived send has no force to remove: {none}"
4403 );
4404 }
4405
4406 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
4411 let path = dir.join("transcript.jsonl");
4412 let mut body = String::new();
4413 for i in 0..n {
4414 let line = serde_json::json!({
4415 "type": "user",
4416 "n": i,
4417 "message": {"content": "x".repeat(line_bytes)},
4418 });
4419 body.push_str(&line.to_string());
4420 body.push('\n');
4421 }
4422 fs::write(&path, body).unwrap();
4423 path
4424 }
4425
4426 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
4428 StreamEventRequest {
4429 tool_name: Some("Bash".into()),
4430 tool_use_id: Some("toolu_1".into()),
4431 tool_input: Some(serde_json::json!({"command": "ls"})),
4432 event_uuid: Some(uuid::Uuid::now_v7()),
4433 transcript_lines: Some(lines),
4434 transcript_offset: Some(offset),
4435 ..sample_stream_event_request()
4436 }
4437 }
4438
4439 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
4440 part.transcript_lines.clone().unwrap_or_default()
4441 }
4442
4443 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
4446 parts
4447 .iter()
4448 .flat_map(|p| {
4449 let offset = p.transcript_offset.unwrap();
4450 part_lines(p)
4451 .into_iter()
4452 .enumerate()
4453 .map(move |(i, l)| (offset + i as i64, l))
4454 })
4455 .collect()
4456 }
4457
4458 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
4460 (0..n)
4461 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
4462 .collect()
4463 }
4464
4465 #[test]
4466 fn split_leaves_a_request_under_the_cap_unchanged() {
4467 let req = event_with_lines(big_lines(3, 100), 0);
4468
4469 let parts = split_into_parts(req.clone());
4470
4471 assert_eq!(parts.len(), 1);
4472 assert_eq!(
4473 serde_json::to_value(&parts[0]).unwrap(),
4474 serde_json::to_value(&req).unwrap()
4475 );
4476 }
4477
4478 #[test]
4482 fn split_carries_every_line_of_a_batch_over_the_cap() {
4483 let dir = tempfile::tempdir().unwrap();
4484 let transcript = write_transcript(dir.path(), 300, 5_000);
4486 let (lines, start, _) =
4487 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
4488 let req = event_with_lines(lines.clone(), start);
4489 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
4490
4491 let parts = split_into_parts(req.clone());
4492
4493 assert!(parts.len() >= 3, "got {} parts", parts.len());
4494 for part in &parts {
4495 assert!(
4496 part.serialized_len() <= MAX_REQUEST_BYTES,
4497 "part of {} bytes exceeds the cap",
4498 part.serialized_len()
4499 );
4500 }
4501 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4502 assert_eq!(sent, lines, "every line, once, in order");
4503
4504 let (event, transcript_parts) = parts.split_last().unwrap();
4506 assert_eq!(event.event_type, StreamEventType::ToolUse);
4507 assert_eq!(event.event_uuid, req.event_uuid);
4508 assert_eq!(event.tool_input, req.tool_input);
4509 for part in transcript_parts {
4510 assert_eq!(part.event_type, StreamEventType::Transcript);
4511 assert!(part.event_uuid.is_none());
4512 assert!(part.tool_input.is_none());
4513 assert!(part.tool_name.is_none());
4514 }
4515 assert!(
4516 !part_lines(event).is_empty(),
4517 "the event keeps the lines that fit beside it"
4518 );
4519 }
4520
4521 #[test]
4525 fn split_keeps_each_lines_unsplit_chunk_index() {
4526 let lines = big_lines(300, 5_000);
4527 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
4528
4529 let expected: Vec<_> = lines
4530 .into_iter()
4531 .enumerate()
4532 .map(|(i, l)| (1_000 + i as i64, l))
4533 .collect();
4534 assert_eq!(chunk_indexes(&parts), expected);
4535 }
4536
4537 #[test]
4542 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
4543 let lines = big_lines(10, 200_000);
4544 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
4545 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
4546
4547 for (index, line) in &short {
4548 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
4549 assert_eq!(in_long.0, *index, "line {line} indexed differently");
4550 }
4551 }
4552
4553 #[test]
4556 fn split_sends_a_single_oversized_line_alone() {
4557 let lines = vec![
4558 serde_json::json!({"n": 0}),
4559 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
4560 serde_json::json!({"n": 2}),
4561 ];
4562
4563 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
4564
4565 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4566 assert_eq!(sent, lines);
4567 let big = parts
4568 .iter()
4569 .find(|p| part_lines(p).contains(&lines[1]))
4570 .unwrap();
4571 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
4572 assert_eq!(big.transcript_offset, Some(1));
4573 }
4574
4575 fn far_deadline() -> std::time::Instant {
4576 std::time::Instant::now() + Duration::from_secs(60)
4577 }
4578
4579 fn captured_body(captured: &str) -> StreamEventRequest {
4580 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
4581 serde_json::from_str(body).expect("request body is a StreamEventRequest")
4582 }
4583
4584 #[tokio::test]
4586 async fn deliver_parts_sends_every_part() {
4587 let dir = tempfile::tempdir().unwrap();
4588 let pending_path = dir.path().join("pending.jsonl");
4589 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4590 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4591 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4592
4593 let all_accepted = deliver_parts(
4594 &client,
4595 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4596 AttributionForce::default(),
4597 parts.clone(),
4598 &pending_path,
4599 false,
4600 far_deadline(),
4601 &mut false,
4602 )
4603 .await
4604 .unwrap();
4605
4606 assert!(all_accepted);
4607 for part in &parts {
4608 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4609 assert_eq!(got.transcript_offset, part.transcript_offset);
4610 assert_eq!(got.transcript_lines, part.transcript_lines);
4611 }
4612 assert!(drain_pending(&pending_path).unwrap().is_empty());
4613 }
4614
4615 #[tokio::test]
4619 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4620 let dir = tempfile::tempdir().unwrap();
4621 let pending_path = dir.path().join("pending.jsonl");
4622 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4623 assert!(parts.len() >= 3);
4624 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4625 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4626 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4627
4628 let all_accepted = deliver_parts(
4629 &client,
4630 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4631 AttributionForce::default(),
4632 parts.clone(),
4633 &pending_path,
4634 false,
4635 far_deadline(),
4636 &mut false,
4637 )
4638 .await
4639 .unwrap();
4640
4641 assert!(!all_accepted);
4642 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4643 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4644 assert!(
4645 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4646 "nothing is sent after the first failure"
4647 );
4648 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4649 .unwrap()
4650 .iter()
4651 .map(|j| serde_json::from_str(j).unwrap())
4652 .collect();
4653 assert_eq!(queued.len(), parts.len() - 1);
4654 for (q, part) in queued.iter().zip(&parts[1..]) {
4655 assert_eq!(q.transcript_offset, part.transcript_offset);
4656 assert_eq!(q.transcript_lines, part.transcript_lines);
4657 }
4658 }
4659
4660 #[tokio::test]
4663 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4664 let dir = tempfile::tempdir().unwrap();
4665 let pending_path = dir.path().join("pending.jsonl");
4666 let parts = split_into_parts(sample_stream_event_request());
4667 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4668
4669 let all_accepted = deliver_parts(
4670 &client,
4671 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4672 AttributionForce::default(),
4673 parts,
4674 &pending_path,
4675 true,
4676 far_deadline(),
4677 &mut false,
4678 )
4679 .await
4680 .unwrap();
4681
4682 assert!(!all_accepted);
4683 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4684 }
4685
4686 #[tokio::test]
4689 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
4690 let dir = tempfile::tempdir().unwrap();
4691 let pending_path = dir.path().join("pending.jsonl");
4692 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4693 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4694 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4695
4696 let all_accepted = deliver_parts(
4697 &client,
4698 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4699 AttributionForce::default(),
4700 parts.clone(),
4701 &pending_path,
4702 false,
4703 std::time::Instant::now(),
4704 &mut false,
4705 )
4706 .await
4707 .unwrap();
4708
4709 assert!(!all_accepted);
4710 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
4711 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
4712 }
4713
4714 #[tokio::test]
4719 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
4720 let dir = tempfile::tempdir().unwrap();
4721 let pending_path = dir.path().join("pending.jsonl");
4722 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
4723 let base = format!("http://{}", listener.local_addr().unwrap());
4724 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4726 let started = Instant::now();
4727
4728 let all_accepted = deliver_parts(
4729 &client,
4730 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4731 AttributionForce::default(),
4732 vec![event_with_lines(big_lines(1, 10), 0)],
4733 &pending_path,
4734 false,
4735 started + Duration::from_millis(100),
4736 &mut false,
4737 )
4738 .await
4739 .unwrap();
4740
4741 assert!(!all_accepted);
4742 assert!(started.elapsed() < Duration::from_secs(10));
4743 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4744 drop(listener);
4745 }
4746
4747 const PARENT_SESSION: &str = "parent-session";
4750 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
4751
4752 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
4756 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
4757 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4758 let subagents = dir.join(PARENT_SESSION).join("subagents");
4759 fs::create_dir_all(&subagents).unwrap();
4760 let session_dir = dir.join("tv-session");
4761 fs::create_dir_all(&session_dir).unwrap();
4762 (main, subagents, session_dir)
4763 }
4764
4765 fn subagent_line(agent: &str, n: usize) -> String {
4766 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
4767 }
4768
4769 fn append_raw(path: &Path, text: &str) {
4770 let mut f = fs::OpenOptions::new()
4771 .create(true)
4772 .append(true)
4773 .open(path)
4774 .unwrap();
4775 f.write_all(text.as_bytes()).unwrap();
4776 }
4777
4778 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
4779 let path = subagents.join(format!("agent-{agent}.jsonl"));
4780 for n in ns {
4781 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
4782 }
4783 }
4784
4785 async fn sweep(
4789 responses: Vec<String>,
4790 main: &Path,
4791 session_dir: &Path,
4792 pending_path: &Path,
4793 ) -> Vec<StreamEventRequest> {
4794 sweep_waiting(responses, main, session_dir, pending_path, None).await
4795 }
4796
4797 async fn sweep_waiting(
4800 responses: Vec<String>,
4801 main: &Path,
4802 session_dir: &Path,
4803 pending_path: &Path,
4804 wait_for_lock: Option<Instant>,
4805 ) -> Vec<StreamEventRequest> {
4806 let expected = responses.len();
4807 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4808 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4809 let event = StreamEventRequest {
4810 session_id: PARENT_SESSION.into(),
4811 ..sample_stream_event_request()
4812 };
4813 deliver_subagent_transcripts(
4814 &client,
4815 &repo_attr(SUBAGENT_REPO),
4816 AttributionForce::default(),
4817 &transcript_template(&event),
4818 main,
4819 session_dir,
4820 pending_path,
4821 false,
4822 Instant::now() + Duration::from_secs(60),
4823 wait_for_lock,
4824 &mut false,
4825 )
4826 .await
4827 .unwrap();
4828 (0..expected)
4829 .map(|_| {
4830 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4831 assert!(
4832 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4833 "{captured}"
4834 );
4835 let body = captured.splitn(3, " | ").nth(2).unwrap();
4836 serde_json::from_str(body).unwrap()
4837 })
4838 .collect()
4839 }
4840
4841 fn agent_of(line: &serde_json::Value) -> &str {
4842 line["agentId"].as_str().unwrap()
4843 }
4844
4845 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4849 for req in reqs {
4850 assert_eq!(req.event_type, StreamEventType::Transcript);
4851 assert_eq!(req.session_id, PARENT_SESSION);
4852 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4853 let lines = part_lines(req);
4854 let agent = agent_of(&lines[0]);
4855 assert!(
4856 lines.iter().all(|l| agent_of(l) == agent),
4857 "a request mixes subagent files: {lines:?}"
4858 );
4859 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4860 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4861 assert_eq!(req.transcript_offset, Some(first));
4862 }
4863 }
4864
4865 #[tokio::test]
4866 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4867 let dir = tempfile::tempdir().unwrap();
4868 let (main, subagents, session_dir) = claude_session(dir.path());
4869 let pending = session_dir.join("pending.jsonl");
4870 let ok = ok_stream_response;
4871 let mut all = Vec::new();
4872
4873 append_subagent_lines(&subagents, "a1", 0..2);
4875 append_subagent_lines(&subagents, "b2", 0..1);
4876 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4877 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4878 assert_eq!(reqs.len(), 2);
4879 all.extend(reqs);
4880
4881 append_subagent_lines(&subagents, "a1", 2..3);
4883 append_subagent_lines(&subagents, "b2", 1..2);
4884 let partial = subagent_line("b2", 2);
4885 let (head, tail) = partial.split_at(10);
4886 append_raw(&subagents.join("agent-b2.jsonl"), head);
4887 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4888 assert_eq!(reqs.len(), 2);
4889 all.extend(reqs);
4890
4891 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4893 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4894 assert_eq!(reqs.len(), 1);
4895 all.extend(reqs);
4896
4897 assert!(sweep(vec![], &main, &session_dir, &pending)
4899 .await
4900 .is_empty());
4901 assert!(!pending.exists(), "nothing may have failed and been queued");
4902
4903 assert_one_file_per_request(&subagents, &all);
4904 let mut sent: Vec<(String, u64)> = all
4905 .iter()
4906 .flat_map(part_lines)
4907 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4908 .collect();
4909 sent.sort();
4910 let expected: Vec<(String, u64)> = [
4911 ("a1", 0),
4912 ("a1", 1),
4913 ("a1", 2),
4914 ("b2", 0),
4915 ("b2", 1),
4916 ("b2", 2),
4917 ]
4918 .into_iter()
4919 .map(|(a, n)| (a.to_string(), n))
4920 .collect();
4921 assert_eq!(sent, expected, "each line exactly once");
4922 }
4923
4924 #[tokio::test]
4925 async fn a_session_without_subagents_sends_nothing_extra() {
4926 let dir = tempfile::tempdir().unwrap();
4927 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4928 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4929 let session_dir = dir.path().join("tv-session");
4930 fs::create_dir_all(&session_dir).unwrap();
4931 let pending = session_dir.join("pending.jsonl");
4932
4933 assert!(sweep(vec![], &main, &session_dir, &pending)
4934 .await
4935 .is_empty());
4936 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4937 }
4938
4939 #[tokio::test]
4944 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4945 let dir = tempfile::tempdir().unwrap();
4946 let (main, subagents, session_dir) = claude_session(dir.path());
4947 let pending = session_dir.join("pending.jsonl");
4948 append_subagent_lines(&subagents, "a1", 0..2);
4949 append_subagent_lines(&subagents, "b2", 0..1);
4950
4951 let error =
4952 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4953 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4954 assert_eq!(failed.len(), 1);
4955 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4956 .unwrap()
4957 .iter()
4958 .map(|j| serde_json::from_str(j).unwrap())
4959 .collect();
4960 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4961
4962 let resent = sweep(
4963 vec![ok_stream_response(), ok_stream_response()],
4964 &main,
4965 &session_dir,
4966 &pending,
4967 )
4968 .await;
4969 assert_one_file_per_request(&subagents, &resent);
4970 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4971 assert_eq!(
4972 resent.iter().map(key).collect::<Vec<_>>(),
4973 queued.iter().map(key).collect::<Vec<_>>()
4974 );
4975 assert!(sweep(vec![], &main, &session_dir, &pending)
4976 .await
4977 .is_empty());
4978 }
4979
4980 #[tokio::test]
4983 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
4984 let dir = tempfile::tempdir().unwrap();
4985 let (main, subagents, session_dir) = claude_session(dir.path());
4986 let pending = session_dir.join("pending.jsonl");
4987 append_subagent_lines(&subagents, "a1", 0..2);
4988 append_subagent_lines(&subagents, "b2", 0..1);
4989 let a1_offset =
4990 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4991 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4992
4993 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4994 assert_eq!(reqs.len(), 1);
4995 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
4996 assert!(!a1_offset.exists());
4997
4998 drop(held);
4999 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5000 assert_eq!(reqs.len(), 1);
5001 assert_eq!(part_lines(&reqs[0]).len(), 2);
5002 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
5003 }
5004
5005 #[tokio::test]
5008 async fn a_final_hook_waits_for_a_busy_subagent_file() {
5009 let dir = tempfile::tempdir().unwrap();
5010 let (main, subagents, session_dir) = claude_session(dir.path());
5011 let pending = session_dir.join("pending.jsonl");
5012 append_subagent_lines(&subagents, "a1", 0..2);
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 let release = thread::spawn(move || {
5017 thread::sleep(Duration::from_millis(300));
5018 drop(held);
5019 });
5020
5021 let reqs = sweep_waiting(
5022 vec![ok_stream_response()],
5023 &main,
5024 &session_dir,
5025 &pending,
5026 Some(Instant::now() + Duration::from_secs(10)),
5027 )
5028 .await;
5029 release.join().unwrap();
5030 assert_eq!(reqs.len(), 1);
5031 assert_eq!(part_lines(&reqs[0]).len(), 2);
5032 }
5033
5034 #[tokio::test]
5038 async fn a_large_subagent_batch_is_split_within_its_file() {
5039 let dir = tempfile::tempdir().unwrap();
5040 let (main, subagents, session_dir) = claude_session(dir.path());
5041 let pending = session_dir.join("pending.jsonl");
5042 let big = subagents.join("agent-a1.jsonl");
5043 for n in 0..300 {
5044 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
5045 append_raw(&big, &format!("{line}\n"));
5046 }
5047 append_subagent_lines(&subagents, "b2", 0..1);
5048
5049 let scratch = dir.path().join("scratch-offset");
5050 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
5051 let unsplit = StreamEventRequest {
5052 transcript_lines: Some(lines.clone()),
5053 transcript_offset: Some(start),
5054 ..transcript_template(&sample_stream_event_request())
5055 };
5056 let a1_parts = split_into_parts(unsplit).len();
5057 assert!(a1_parts > 1, "the batch must exceed the cap");
5058
5059 let reqs = sweep(
5060 vec![ok_stream_response(); a1_parts + 1],
5061 &main,
5062 &session_dir,
5063 &pending,
5064 )
5065 .await;
5066 assert!(!pending.exists());
5067 let (a1, b2) = reqs.split_at(a1_parts);
5068 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
5069 assert_eq!(
5070 chunk_indexes(a1),
5071 lines
5072 .into_iter()
5073 .enumerate()
5074 .map(|(i, l)| (start + i as i64, l))
5075 .collect::<Vec<_>>()
5076 );
5077 assert_eq!(b2.len(), 1);
5078 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
5079 assert_eq!(b2[0].transcript_offset, Some(0));
5080 }
5081}