1use crate::program::{CLI, TOP};
2use std::collections::HashMap;
3use std::fs::{self, OpenOptions};
4use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
5use std::path::Path;
6
7use tracevault_protocol::hooks::{parse_hook_event, HookResponse};
8use tracevault_protocol::streaming::{
9 extract_is_error_from_transcript, StreamEventRequest, StreamEventType, MAX_REQUEST_BYTES,
10};
11
12#[allow(clippy::type_complexity)]
22pub fn apply_context(
23 ctx: crate::context::EffectiveContext,
24) -> (
25 Option<String>,
26 Option<Vec<String>>,
27 Option<HashMap<String, String>>,
28) {
29 let flow_id = ctx.flow_id;
30 let labels = if ctx.labels.is_empty() {
31 None
32 } else {
33 Some(ctx.labels)
34 };
35 let params = if ctx.params.is_empty() {
36 None
37 } else {
38 Some(ctx.params.into_iter().collect())
39 };
40 (flow_id, labels, params)
41}
42
43pub fn read_new_transcript_lines(
52 transcript_path: &Path,
53 offset_path: &Path,
54) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
55 if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
61 return Ok((vec![], 0, 0));
62 }
63
64 let offset: i64 = if offset_path.exists() {
65 let content = fs::read_to_string(offset_path)?;
66 content
67 .trim()
68 .parse::<i64>()
69 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
70 } else {
71 0
72 };
73
74 let mut file = fs::File::open(transcript_path)?;
75 file.seek(SeekFrom::Start(offset as u64))?;
76
77 let reader = io::BufReader::new(file);
78 let mut lines = Vec::new();
79 let mut bytes_read = offset;
80
81 for line_result in reader.lines() {
82 let line = line_result?;
83 bytes_read += line.len() as i64 + 1;
85 if line.trim().is_empty() {
86 continue;
87 }
88 if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
89 lines.push(value);
90 }
91 }
92
93 Ok((lines, offset, bytes_read))
94}
95
96pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
104 if transcript_path.is_empty() {
105 return Ok(());
106 }
107 record_metadata(
108 session_dir,
109 "transcript_path",
110 serde_json::Value::String(transcript_path.to_string()),
111 )
112}
113
114pub(crate) fn session_metadata(session_dir: &Path) -> serde_json::Value {
116 fs::read_to_string(session_dir.join("metadata.json"))
117 .ok()
118 .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
119 .filter(serde_json::Value::is_object)
120 .unwrap_or_else(|| serde_json::json!({}))
121}
122
123fn record_metadata(
127 session_dir: &Path,
128 key: &str,
129 value: serde_json::Value,
130) -> Result<(), io::Error> {
131 let mut meta = session_metadata(session_dir);
132 if meta.get(key) == Some(&value) {
133 return Ok(());
134 }
135 meta[key] = value;
136 let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
137 fs::write(&tmp, meta.to_string())?;
138 fs::rename(&tmp, session_dir.join("metadata.json")).inspect_err(|_| {
139 let _ = fs::remove_file(&tmp);
140 })
141}
142
143fn attribution_record(attribution: &Attribution) -> serde_json::Value {
145 match attribution {
146 Attribution::Repo { repo_id, project } => {
147 serde_json::json!({"repo_id": repo_id, "project_id": project})
148 }
149 Attribution::ProjectOnly { project_id } => {
150 serde_json::json!({"repo_id": null, "project_id": project_id})
151 }
152 }
153}
154
155pub(crate) fn catch_up_may_send(recorded: Option<&serde_json::Value>, now: &Attribution) -> bool {
163 match recorded {
164 Some(recorded) => *recorded == attribution_record(now),
165 None => matches!(now, Attribution::Repo { .. }),
166 }
167}
168
169pub fn record_inline_tool_calls(
176 session_dir: &Path,
177 records: &[serde_json::Value],
178) -> Result<(), io::Error> {
179 let lines: String = records
180 .iter()
181 .flat_map(crate::transcript::tool_call_names)
182 .map(|name| {
183 let record = serde_json::json!({
184 "type": "message",
185 "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
186 });
187 format!("{record}\n")
188 })
189 .collect();
190 if lines.is_empty() {
191 return Ok(());
192 }
193 let log_path = session_dir.join("tool_calls.jsonl");
194 OpenOptions::new()
195 .create(true)
196 .append(true)
197 .open(&log_path)?
198 .write_all(lines.as_bytes())?;
199 record_transcript_path(session_dir, &log_path.to_string_lossy())
200}
201
202pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
203 let mut file = OpenOptions::new()
204 .create(true)
205 .append(true)
206 .open(pending_path)?;
207 writeln!(file, "{json}")?;
208 Ok(())
209}
210
211fn adopt_queue(from: &Path, into: &Path) -> Result<(), io::Error> {
221 let adopted = match fs::read_to_string(from) {
222 Ok(s) => s,
223 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
224 Err(e) => return Err(e),
225 };
226 let existing = match fs::read_to_string(into) {
227 Ok(s) => s,
228 Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(),
229 Err(e) => return Err(e),
230 };
231 let mut merged = adopted;
232 if !merged.is_empty() && !merged.ends_with('\n') {
233 merged.push('\n');
234 }
235 merged.push_str(&existing);
236 let tmp = into.with_extension("jsonl.adopting");
237 fs::write(&tmp, merged)?;
238 fs::rename(&tmp, into)?;
239 fs::remove_file(from)
240}
241
242pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
243 if !pending_path.exists() {
244 return Ok(vec![]);
245 }
246 let content = fs::read_to_string(pending_path)?;
247 let lines: Vec<String> = content
248 .lines()
249 .filter(|l| !l.trim().is_empty())
250 .map(String::from)
251 .collect();
252 fs::remove_file(pending_path)?;
253 Ok(lines)
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
266pub(crate) enum Attribution {
267 Repo {
270 repo_id: String,
271 project: Option<uuid::Uuid>,
272 },
273 ProjectOnly { project_id: uuid::Uuid },
276}
277
278impl Attribution {
279 pub(crate) fn pending_file_name(&self) -> String {
288 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
289 match self {
290 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
291 Self::ProjectOnly { project_id } => {
292 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
293 }
294 }
295 }
296}
297
298pub(crate) fn attribution_for(
318 binding: Option<&crate::session_state::RepoBinding>,
319 project: Option<uuid::Uuid>,
320) -> Option<Attribution> {
321 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
322 Some(b) => Some(Attribution::Repo {
323 repo_id: b.repo_id.clone(),
324 project,
325 }),
326 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
327 }
328}
329
330pub(crate) fn inference_project(
335 binding: Option<&crate::session_state::RepoBinding>,
336 project: Option<uuid::Uuid>,
337) -> Option<uuid::Uuid> {
338 match binding {
339 Some(_) => None,
340 None => project,
341 }
342}
343
344pub(crate) fn attribution_with_inference(
349 binding: Option<&crate::session_state::RepoBinding>,
350 project: Option<uuid::Uuid>,
351 inferred: Option<&crate::session_state::RepoBinding>,
352) -> Option<Attribution> {
353 match (inference_project(binding, project), inferred) {
354 (Some(pid), Some(repo)) if binding_repo_id_is_valid(&repo.repo_id) => {
355 Some(Attribution::Repo {
356 repo_id: repo.repo_id.clone(),
357 project: Some(pid),
358 })
359 }
360 _ => attribution_for(binding, project),
361 }
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
368pub(crate) struct Recording {
369 pub attribution: Option<Attribution>,
370 pub inferred_from: Option<String>,
371}
372
373fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
375 session_dir.join(attribution.pending_file_name())
376}
377
378fn adopted_project_queue(
408 session_dir: &Path,
409 attribution: &Attribution,
410) -> Option<std::path::PathBuf> {
411 match attribution {
412 Attribution::Repo {
413 project: Some(project_id),
414 ..
415 } => Some(pending_path_for(
416 session_dir,
417 &Attribution::ProjectOnly {
418 project_id: *project_id,
419 },
420 )),
421 _ => None,
422 }
423}
424
425pub fn resolve_session_paths(
438 hook_cwd: &Path,
439 session_id: &str,
440) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
441 let resolved = crate::paths::resolve_project_root(hook_cwd);
442 let session_dir = crate::layout::session_dir(&resolved.root, session_id);
443 (resolved, session_dir)
444}
445
446pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
454 uuid::Uuid::parse_str(repo_id).is_ok()
455}
456
457pub(crate) fn resolve_stream_binding(
461 session: &crate::session_state::SessionState,
462 worktree: &str,
463 bound: Option<crate::session_state::RepoBinding>,
464 user_default: Option<crate::session_state::RepoBinding>,
465) -> Option<crate::session_state::RepoBinding> {
466 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
467 repo_flag: None,
468 session,
469 worktree_path: Some(worktree),
470 bound,
471 user_default,
472 })
473 .map(|(b, _)| b)
474}
475
476pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
484 let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
485 let raw = raw.trim();
486 let parsed = raw.parse::<uuid::Uuid>().ok()?;
487 Some(crate::session_state::ProjectBinding {
488 project_id: parsed.to_string(),
489 project_name: String::new(),
490 updated_at: String::new(),
491 forced_until: None,
492 })
493}
494
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
517pub(crate) struct AttributionForce {
518 pub(crate) env: bool,
521 pub(crate) binding: bool,
525}
526
527impl AttributionForce {
528 pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
531 if self.env || self.binding {
532 crate::api_client::AttributionMode::Explicit
533 } else {
534 crate::api_client::AttributionMode::Derived
535 }
536 }
537}
538
539pub(crate) fn attribution_mode(
591 effective: Option<&crate::session_state::ProjectBinding>,
592) -> crate::api_client::AttributionMode {
593 attribution_force(effective).mode()
594}
595
596pub(crate) fn attribution_force(
603 effective: Option<&crate::session_state::ProjectBinding>,
604) -> AttributionForce {
605 AttributionForce {
606 env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
607 .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
608 .unwrap_or(false),
609 binding: effective
610 .and_then(|b| b.forced_until.as_deref())
611 .is_some_and(|s| {
612 matches!(
613 crate::session_state::force_status(s),
614 crate::session_state::ForceStatus::Live(_)
615 )
616 }),
617 }
618}
619
620pub(crate) fn capture_binding(
642 session: &crate::session_state::SessionState,
643 worktree_path: Option<&str>,
644 config_project: Option<crate::session_state::ProjectBinding>,
645) -> Option<crate::session_state::ProjectBinding> {
646 use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
647 let (binding, _) = capture_project_binding(&CaptureProjectInputs {
648 project_flag: None,
649 env_project: env_project_binding(),
650 session,
651 worktree_path,
652 config_project,
653 user_default: crate::user_project_default::load(),
654 })?;
655 capture_project_id(&binding)?;
660 Some(binding)
661}
662
663pub(crate) fn capture_project(
673 session: &crate::session_state::SessionState,
674 worktree_path: Option<&str>,
675 config_project: Option<crate::session_state::ProjectBinding>,
676) -> Option<uuid::Uuid> {
677 capture_binding(session, worktree_path, config_project)
678 .as_ref()
679 .and_then(crate::resolution::capture_project_id)
680}
681
682pub(crate) fn recording_attribution_for(
695 session: &crate::session_state::SessionState,
696 worktree: &str,
697 bound: Option<crate::session_state::RepoBinding>,
698 user_default_repo: Option<crate::session_state::RepoBinding>,
699 config_project: Option<crate::session_state::ProjectBinding>,
700) -> Recording {
701 let stream_binding = resolve_stream_binding(session, worktree, bound, user_default_repo);
702 let project = capture_project(session, Some(worktree), config_project);
703 let inferred = inference_project(stream_binding.as_ref(), project)
704 .and_then(|pid| crate::inferred_repo::cached_repo(session, worktree, pid));
705 let attribution =
706 attribution_with_inference(stream_binding.as_ref(), project, inferred.as_ref());
707 let inferred_from = match (&attribution, &inferred) {
708 (Some(Attribution::Repo { repo_id, .. }), Some(repo)) if *repo_id == repo.repo_id => {
709 Some(worktree.to_string())
710 }
711 _ => None,
712 };
713 Recording {
714 attribution,
715 inferred_from,
716 }
717}
718
719pub(crate) fn recording_line_for(recording: &Recording) -> String {
722 if let (
723 Some(Attribution::Repo {
724 repo_id,
725 project: Some(pid),
726 }),
727 Some(checkout),
728 ) = (&recording.attribution, &recording.inferred_from)
729 {
730 return format!(
731 "recording: repo {repo_id} in project {pid} — inferred from the checkout {checkout} \
732 (no repo is bound; events in other checkouts go to their own repo in the project, \
733 or to the project only)"
734 );
735 }
736 recording_line(recording.attribution.as_ref())
737}
738
739pub(crate) fn recording_line(attribution: Option<&Attribution>) -> String {
741 match attribution {
742 Some(Attribution::Repo {
743 repo_id,
744 project: None,
745 }) => format!("recording: repo {repo_id} (the server deduces the project from the repo)"),
746 Some(Attribution::Repo {
747 repo_id,
748 project: Some(pid),
749 }) => format!("recording: repo {repo_id} in project {pid}"),
750 Some(Attribution::ProjectOnly { project_id }) => format!(
751 "recording: project {project_id} only — no repo is bound, so events are sent \
752 without one (`{CLI} repo switch <path>` adds the repo)"
753 ),
754 None => "recording: nothing — neither a repo nor a project is bound, so this \
755 session's events are not sent"
756 .to_string(),
757 }
758}
759
760pub(crate) fn refused_project_only_error(
773 pid: uuid::Uuid,
774 kind: &ClientErrorKind,
775 force: AttributionForce,
776) -> String {
777 let base = match kind {
778 ClientErrorKind::Forbidden => format!(
779 "{TOP}: error: the server refused this repo-less session's event for project \
780 {pid} (403). Either this account has no access to that project (no `Operator` \
781 role on it) — run `{CLI} project switch <name>` (add `--user` if the binding \
782 is the machine-wide default in `user_project.toml`) — or it has no `tracevault` \
783 grant in Control Plane at all, which an administrator must grant. The session has \
784 no repo binding, so the event was not sent anywhere else; it has been queued and \
785 will be retried with the next event."
786 ),
787 ClientErrorKind::Scoping => format!(
788 "{TOP}: error: project {pid} does not resolve on the server (400/404/409: it \
789 does not exist, or this account cannot see it). The session has no repo binding, \
790 so the event was not sent anywhere else; it has been queued and will be retried \
791 with the next event. Run `{CLI} project switch <name>` (add `--user` if the \
792 binding is the machine-wide default in `user_project.toml`) to bind a project that \
793 exists, or `{CLI} repo switch <path>` to record this session to a repo."
794 ),
795 };
796 with_force_clause(base, kind, force)
797}
798
799#[derive(Debug, PartialEq, Eq)]
820pub(crate) enum ClientErrorKind {
821 Forbidden,
823 Scoping,
825}
826
827pub(crate) fn refused_error(
858 pid: uuid::Uuid,
859 kind: &ClientErrorKind,
860 force: AttributionForce,
861) -> String {
862 let base = match kind {
863 ClientErrorKind::Forbidden => format!(
869 "{TOP}: error: the server refused to attribute this event to active project \
870 {pid} (403). Either that project does not apply to this repo (not a member, or \
871 no `Operator` role on it) — run `{CLI} project switch <name>` (add `--user` if the \
872 binding is the machine-wide default in `user_project.toml`) — or this account has \
873 no `tracevault` grant in Control Plane at all, which an administrator must grant. \
874 The event was NOT re-attributed elsewhere; it has been queued and will be retried \
875 once the binding or the grant is fixed."
876 ),
877 ClientErrorKind::Scoping => format!(
878 "{TOP}: error: active project {pid} does not apply to this repo (not a member, \
879 missing permission, or the project no longer exists). The event was NOT \
880 re-attributed elsewhere; it has been queued and will be retried once the binding is \
881 fixed. Run `{CLI} project switch <name>` (add `--user` if the binding is the \
882 machine-wide default in `user_project.toml`) to update it."
883 ),
884 };
885 with_force_clause(base, kind, force)
886}
887
888fn with_force_clause(base: String, kind: &ClientErrorKind, force: AttributionForce) -> String {
892 if force.mode() == crate::api_client::AttributionMode::Explicit
893 && matches!(kind, ClientErrorKind::Forbidden)
894 {
895 return format!(
896 "{base} This send declared `explicit` attribution, so the refusal may be of the \
897 FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
898 identity (a `tvk_` API key can never force). If membership attribution is what \
899 you want, {}",
900 force_remediation(force)
901 );
902 }
903 base
904}
905
906fn force_remediation(force: AttributionForce) -> String {
923 let env_fix = crate::program::say(
924 "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
925 process-wide and never expires, so no switch clears it)",
926 );
927 let binding_fix = crate::program::say(
928 "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 );
932 match (force.env, force.binding) {
933 (true, false) => format!("{env_fix}."),
934 (false, true) => format!("{binding_fix}."),
935 (true, true) => {
937 format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
938 }
939 (false, false) => format!("{env_fix}, or {binding_fix}."),
940 }
941}
942
943pub(crate) fn deterministic_client_error_kind(
944 e: &dyn std::error::Error,
945) -> Option<ClientErrorKind> {
946 let s = e.to_string();
947 if s.contains("(403 ") {
954 return Some(ClientErrorKind::Forbidden);
955 }
956 if ["(400 ", "(404 ", "(409 "]
957 .iter()
958 .any(|marker| s.contains(marker))
959 {
960 return Some(ClientErrorKind::Scoping);
961 }
962 None
963}
964
965async fn send_stream_event(
1014 client: &crate::api_client::ApiClient,
1015 attribution: &Attribution,
1016 force: AttributionForce,
1017 req: &StreamEventRequest,
1018 warned: &mut bool,
1019) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn std::error::Error>> {
1020 let (repo_id, capture_pid) = match attribution {
1021 Attribution::ProjectOnly { project_id } => {
1030 let attempt = client
1031 .stream_event_for_project(*project_id, None, force.mode(), req)
1032 .await;
1033 if let Err(e) = &attempt {
1034 if let Some(kind) = deterministic_client_error_kind(e.as_ref()) {
1035 if !*warned {
1036 eprintln!("{}", refused_project_only_error(*project_id, &kind, force));
1037 *warned = true;
1038 }
1039 }
1040 }
1041 return attempt;
1042 }
1043 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
1044 };
1045 match capture_pid {
1046 None => client.stream_event(repo_id, req).await,
1047 Some(pid) => {
1048 let attempt = client
1049 .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
1050 .await;
1051 let kind = match &attempt {
1052 Ok(_) => None,
1053 Err(e) => deterministic_client_error_kind(e.as_ref()),
1054 };
1055 match (attempt, kind) {
1056 (Ok(r), _) => Ok(r),
1057 (Err(e), Some(kind)) => {
1058 if !*warned {
1059 eprintln!("{}", refused_error(pid, &kind, force));
1067 *warned = true;
1068 }
1069 Err(e)
1075 }
1076 (Err(e), None) => Err(e),
1078 }
1079 }
1080 }
1081}
1082
1083pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
1089 (start_offset, start_offset + records_len)
1090}
1091
1092pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
1108 if req.serialized_len() <= MAX_REQUEST_BYTES {
1109 return vec![req];
1110 }
1111 let lines = req.transcript_lines.take().unwrap_or_default();
1112 let batch_offset = req.transcript_offset.unwrap_or(0);
1113 req.truncate_large_fields();
1116
1117 let sizes: Vec<usize> = lines
1119 .iter()
1120 .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
1121 .collect();
1122 let envelope = |r: &StreamEventRequest| {
1123 let mut r = r.clone();
1124 r.transcript_lines = Some(vec![]);
1125 r.serialized_len()
1126 };
1127
1128 let mut tail_start = lines.len();
1130 let mut used = envelope(&req);
1131 while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
1132 tail_start -= 1;
1133 used += sizes[tail_start];
1134 }
1135
1136 let transcript_template = transcript_template(&req);
1137 let transcript_envelope = envelope(&transcript_template);
1138
1139 let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
1141 let mut start = 0;
1142 while start < tail_start {
1143 let mut end = start + 1;
1144 let mut used = transcript_envelope + sizes[start];
1145 while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
1146 used += sizes[end];
1147 end += 1;
1148 }
1149 groups.push(start..end);
1150 start = end;
1151 }
1152 groups.push(tail_start..lines.len());
1153
1154 let last = groups.len() - 1;
1155 let mut lines = lines.into_iter();
1156 groups
1157 .into_iter()
1158 .enumerate()
1159 .map(|(n, range)| {
1160 let mut part = if n == last {
1161 req.clone()
1162 } else {
1163 transcript_template.clone()
1164 };
1165 let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
1166 part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
1167 part.transcript_offset = Some(batch_offset + range.start as i64);
1168 part
1169 })
1170 .collect()
1171}
1172
1173pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
1178 StreamEventRequest {
1179 protocol_version: req.protocol_version,
1180 tool: req.tool.clone(),
1181 event_type: StreamEventType::Transcript,
1182 session_id: req.session_id.clone(),
1183 timestamp: req.timestamp,
1184 hook_event_name: req.hook_event_name.clone(),
1185 tool_name: None,
1186 tool_use_id: None,
1187 tool_input: None,
1188 tool_response: None,
1189 tool_is_error: None,
1190 event_index: None,
1191 event_uuid: None,
1192 transcript_lines: None,
1193 transcript_offset: req.transcript_offset,
1194 model: req.model.clone(),
1195 cwd: req.cwd.clone(),
1196 final_stats: None,
1197 flow_id: req.flow_id.clone(),
1198 labels: req.labels.clone(),
1199 params: req.params.clone(),
1200 billing_mode: req.billing_mode,
1201 }
1202}
1203
1204#[allow(clippy::too_many_arguments)]
1225async fn deliver_subagent_transcripts(
1226 client: &crate::api_client::ApiClient,
1227 attribution: &Attribution,
1228 force: AttributionForce,
1229 template: &StreamEventRequest,
1230 transcript_path: &Path,
1231 session_dir: &Path,
1232 pending_path: &Path,
1233 mut send_failed: bool,
1234 deadline: std::time::Instant,
1235 wait_for_lock: Option<std::time::Instant>,
1236 warned: &mut bool,
1237) -> Result<(), Box<dyn std::error::Error>> {
1238 for file in crate::subagents::transcripts(transcript_path) {
1239 let offset_path = crate::subagents::offset_path(session_dir, &file);
1240 let lock = loop {
1242 match crate::subagents::try_lock(&offset_path) {
1243 Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
1244 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1245 }
1246 other => break other,
1247 }
1248 };
1249 let _lock = match lock {
1250 Ok(Some(lock)) => lock,
1251 Ok(None) => {
1252 if wait_for_lock.is_some() {
1253 eprintln!(
1254 "{TOP}: warning: skipping subagent transcript {}: \
1255 another hook is still sending it",
1256 file.display()
1257 );
1258 }
1259 continue;
1260 }
1261 Err(e) => {
1262 eprintln!(
1263 "{TOP}: warning: skipping subagent transcript {}: cannot lock: {e}",
1264 file.display()
1265 );
1266 continue;
1267 }
1268 };
1269 let (lines, start, end) = match crate::subagents::read_new_lines(&file, &offset_path) {
1270 Ok(read) => read,
1271 Err(e) => {
1272 eprintln!(
1273 "{TOP}: warning: skipping subagent transcript {}: {e}",
1274 file.display()
1275 );
1276 continue;
1277 }
1278 };
1279 if end == start {
1280 continue;
1281 }
1282 let mut accepted = true;
1284 if !lines.is_empty() {
1285 let mut req = template.clone();
1286 req.transcript_lines = Some(lines);
1287 req.transcript_offset = Some(start);
1288 accepted = deliver_parts(
1289 client,
1290 attribution,
1291 force,
1292 split_into_parts(req),
1293 pending_path,
1294 send_failed,
1295 deadline,
1296 warned,
1297 )
1298 .await?;
1299 send_failed |= !accepted;
1300 }
1301 if accepted {
1302 crate::subagents::write_offset(&offset_path, end)?;
1303 }
1304 }
1305 Ok(())
1306}
1307
1308pub fn resolve_transcript_source(
1314 inline_records: Option<Vec<serde_json::Value>>,
1315 prior_offset: i64,
1316 file_result: (Vec<serde_json::Value>, i64, i64),
1317) -> (Vec<serde_json::Value>, i64, i64) {
1318 match inline_records {
1319 Some(records) => {
1320 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1321 (records, send, next)
1322 }
1323 None => file_result,
1324 }
1325}
1326
1327pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1336 lines.iter().find_map(|line| {
1337 let msg = line.get("message")?;
1338 if line.get("type").and_then(|v| v.as_str()) == Some("amp_message") {
1339 return msg
1340 .get("content")?
1341 .as_array()?
1342 .iter()
1343 .find(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result"))
1344 .map(|b| b.get("status").and_then(|v| v.as_str()) == Some("error"));
1345 }
1346 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1347 Some(
1348 msg.get("isError")
1349 .and_then(|v| v.as_bool())
1350 .unwrap_or(false),
1351 )
1352 } else {
1353 None
1354 }
1355 })
1356}
1357
1358pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1362 req.tool = Some(agent.tool_name().to_string());
1363 req.protocol_version = agent.protocol_version() as u32;
1364}
1365
1366const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1372
1373pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1378
1379const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1386
1387#[allow(clippy::too_many_arguments)]
1395async fn deliver_parts(
1396 client: &crate::api_client::ApiClient,
1397 attribution: &Attribution,
1398 force: AttributionForce,
1399 parts: Vec<StreamEventRequest>,
1400 pending_path: &Path,
1401 mut send_failed: bool,
1402 deadline: std::time::Instant,
1403 warned: &mut bool,
1404) -> Result<bool, Box<dyn std::error::Error>> {
1405 let mut all_accepted = true;
1406 for part in parts {
1407 send_failed = send_failed || std::time::Instant::now() >= deadline;
1408 if !send_failed {
1409 let send = send_stream_event(client, attribution, force, &part, warned);
1410 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1411 Ok(Ok(_)) => continue,
1412 Ok(Err(_)) | Err(_) => send_failed = true,
1413 }
1414 }
1415 all_accepted = false;
1416 append_pending(pending_path, &serde_json::to_string(&part)?)?;
1417 }
1418 Ok(all_accepted)
1419}
1420
1421pub const TRACING_MODE_ENV: &str = "VISDOM_TRACING_MODE";
1426
1427pub const GATEWAY_SESSION_ENV: &str = "VISDOM_GATEWAY_SESSION";
1431
1432pub fn captured_by_gateway(marker: Option<&str>, agent: crate::agent::Agent) -> bool {
1447 marker
1448 .map(str::trim)
1449 .is_some_and(|m| m == "1" || m.eq_ignore_ascii_case(agent.tool_name()))
1450}
1451
1452pub async fn run_stream(
1453 event_type: &str,
1454 agent: crate::agent::Agent,
1455) -> Result<(), Box<dyn std::error::Error>> {
1456 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1458 let mut input = String::new();
1459 io::stdin().read_to_string(&mut input)?;
1460 if captured_by_gateway(std::env::var(GATEWAY_SESSION_ENV).ok().as_deref(), agent) {
1462 println!("{}", serde_json::to_string(&HookResponse::allow())?);
1463 return Ok(());
1464 }
1465 let hook_event = parse_hook_event(&input)?;
1466
1467 let hook_cwd = Path::new(&hook_event.cwd);
1489 let (resolved, cwd_session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1490 let storage_root =
1491 crate::session_state::storage_root(&crate::session_state::load(&hook_event.session_id));
1492 let session_dir = match &storage_root {
1493 Some(root) => crate::layout::session_dir(root, &hook_event.session_id),
1494 None => cwd_session_dir,
1495 };
1496 if storage_root.is_none() && resolved.source == crate::paths::ProjectRootSource::Fallback {
1497 eprintln!(
1502 "{TOP}: warning: could not resolve a git project root from {}; \
1503 creating .visdom/ there. Ensure `git` is on PATH for the hook and \
1504 that it runs inside the repository to keep sessions under the repo root.",
1505 hook_cwd.display()
1506 );
1507 }
1508 let project_root = resolved.root;
1509
1510 fs::create_dir_all(&session_dir)?;
1512
1513 if let Some(dir) = session_dir.parent().and_then(Path::parent) {
1521 let _ = crate::config::TracevaultConfig::ensure_gitignore(dir);
1522 }
1523
1524 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1529 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1530 if storage_root.is_some() {
1533 let _ = crate::session_state::record_worktree(&session_dir, &worktree_top);
1534 }
1535
1536 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1540 if let Some(records) = &hook_event.transcript_records {
1545 let _ = record_inline_tool_calls(&session_dir, records);
1546 }
1547
1548 let target = SessionTarget {
1549 project_root,
1550 session_dir,
1551 worktree_top,
1552 };
1553 stream_event(
1554 hook_event,
1555 event_type,
1556 agent,
1557 &target,
1558 deadline,
1559 Sender::Hook,
1560 )
1561 .await?;
1562
1563 let response = HookResponse::allow();
1565 println!("{}", serde_json::to_string(&response)?);
1566
1567 Ok(())
1568}
1569
1570pub fn stream_event_type(event_type: &str) -> StreamEventType {
1572 match event_type {
1573 "notification" => StreamEventType::SessionStart,
1574 "stop" => StreamEventType::SessionEnd,
1576 "session-end" => StreamEventType::Transcript,
1580 _ => StreamEventType::ToolUse,
1581 }
1582}
1583
1584pub(crate) struct SessionTarget {
1588 pub project_root: std::path::PathBuf,
1589 pub session_dir: std::path::PathBuf,
1591 pub worktree_top: String,
1593}
1594
1595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1597pub(crate) enum Sender {
1598 Hook,
1601 CatchUp,
1606}
1607
1608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1610pub(crate) enum Sent {
1611 Accepted,
1613 Queued,
1615 Skipped,
1618}
1619
1620pub(crate) async fn stream_event(
1624 mut hook_event: tracevault_protocol::hooks::HookEvent,
1625 event_type: &str,
1626 agent: crate::agent::Agent,
1627 target: &SessionTarget,
1628 deadline: std::time::Instant,
1629 sender: Sender,
1630) -> Result<Sent, Box<dyn std::error::Error>> {
1631 let SessionTarget {
1632 project_root,
1633 session_dir,
1634 worktree_top,
1635 } = target;
1636 let hook_cwd = Path::new(&hook_event.cwd);
1637
1638 let event_uuid = uuid::Uuid::now_v7();
1643
1644 let transcript_path = Path::new(&hook_event.transcript_path);
1646 let offset_path = session_dir.join(".stream_offset");
1647 let sends_main = event_type != "subagent-stop";
1654 let (transcript_lines, start_offset, new_offset) = if sends_main {
1655 read_new_transcript_lines(transcript_path, &offset_path)?
1656 } else {
1657 (vec![], 0, 0)
1658 };
1659
1660 let is_inline = hook_event.transcript_records.is_some();
1677 let (transcript_lines, start_offset, new_offset) = if is_inline {
1678 let prior_offset: i64 = if offset_path.exists() {
1685 let content = fs::read_to_string(&offset_path)?;
1686 content
1687 .trim()
1688 .parse::<i64>()
1689 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1690 .max(0)
1691 } else {
1692 0
1693 };
1694 resolve_transcript_source(
1698 hook_event.transcript_records.take(),
1699 prior_offset,
1700 (transcript_lines, start_offset, new_offset),
1701 )
1702 } else {
1703 (transcript_lines, start_offset, new_offset)
1704 };
1705 let stream_event_type = stream_event_type(event_type);
1707
1708 let tool_is_error = hook_event
1713 .tool_use_id
1714 .as_deref()
1715 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1716 .or_else(|| inline_tool_is_error(&transcript_lines));
1717
1718 let config = crate::config::TracevaultConfig::try_load(project_root);
1728 let repo_uc = config
1732 .as_ref()
1733 .ok()
1734 .and_then(|opt| opt.as_ref())
1735 .and_then(|c| c.user_context.clone());
1736 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1737
1738 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1744 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1745
1746 let mut req = StreamEventRequest {
1747 protocol_version: 1,
1748 tool: Some("claude-code".to_string()),
1749 event_type: stream_event_type,
1750 session_id: hook_event.session_id.clone(),
1751 timestamp: chrono::Utc::now(),
1752 hook_event_name: Some(hook_event.hook_event_name.clone()),
1753 tool_name: hook_event.tool_name.clone(),
1754 tool_use_id: hook_event.tool_use_id.clone(),
1755 tool_input: hook_event.tool_input.clone(),
1756 tool_response: hook_event.tool_response.clone(),
1757 tool_is_error,
1758 event_index: None,
1759 event_uuid: Some(event_uuid),
1760 transcript_lines: None,
1761 transcript_offset: Some(start_offset),
1762 model: None,
1763 cwd: Some(hook_event.cwd.clone()),
1764 final_stats: None,
1765 flow_id: ctx_flow_id,
1766 labels: ctx_labels,
1767 params: ctx_params,
1768 billing_mode: (sender == Sender::Hook)
1769 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1770 };
1771
1772 stamp_agent(&mut req, agent);
1773 let subagent_template = transcript_template(&req);
1775 if !transcript_lines.is_empty() {
1776 req.transcript_lines = Some(transcript_lines);
1777 }
1778
1779 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
1781
1782 if let Err(e) = &config {
1791 return Err(format!("malformed .visdom/tracing.toml: {e}").into());
1792 }
1793
1794 let session = crate::session_state::load(&hook_event.session_id);
1799 let bound = config
1800 .as_ref()
1801 .ok()
1802 .and_then(|opt| opt.as_ref())
1803 .and_then(crate::resolution::binding_from_config);
1804 let user_default = crate::user_default::load();
1805 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
1806 let config_project = config
1820 .as_ref()
1821 .ok()
1822 .and_then(|opt| opt.as_ref())
1823 .and_then(crate::resolution::project_from_config);
1824 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()), config_project);
1825 let capture_pid = capture_binding
1826 .as_ref()
1827 .and_then(crate::resolution::capture_project_id);
1828 let client = server_url
1838 .as_deref()
1839 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1840 let mut inferred = None;
1841 if binding.is_none() {
1842 if let Some(client) = &client {
1843 match inference_project(None, capture_pid) {
1844 Some(pid) => {
1845 if let Some(checkout) = crate::inferred_repo::event_checkout(
1846 hook_cwd,
1847 hook_event.tool_input.as_ref(),
1848 worktree_top,
1849 ) {
1850 inferred = crate::inferred_repo::infer(
1851 &hook_event.session_id,
1852 &checkout,
1853 pid,
1854 client,
1855 deadline,
1856 )
1857 .await;
1858 if inferred.is_some() && checkout != *worktree_top {
1862 let _ = crate::session_state::record_worktree(session_dir, &checkout);
1863 }
1864 }
1865 }
1866 None => {
1867 let auto = crate::auto_bind::bind_session(
1868 &hook_event.session_id,
1869 hook_cwd,
1870 client,
1871 deadline,
1872 )
1873 .await;
1874 if let Some(notice) = auto.notice {
1875 eprintln!("{notice}");
1876 }
1877 binding = auto.binding;
1878 }
1879 }
1880 }
1881 }
1882 let force = attribution_force(capture_binding.as_ref());
1889
1890 let Some(attribution) =
1898 attribution_with_inference(binding.as_ref(), capture_pid, inferred.as_ref())
1899 else {
1900 return Ok(Sent::Skipped);
1901 };
1902 match sender {
1906 Sender::Hook => {
1907 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
1908 }
1909 Sender::CatchUp => {
1910 let meta = session_metadata(session_dir);
1911 if !catch_up_may_send(meta.get("attribution"), &attribution) {
1912 return Ok(Sent::Skipped);
1913 }
1914 }
1915 }
1916
1917 let client = client.ok_or("server_url not configured")?;
1919
1920 let pending_path = pending_path_for(session_dir, &attribution);
1932 let adopted = if inferred.is_some() && binding.is_none() {
1933 None
1934 } else {
1935 adopted_project_queue(session_dir, &attribution)
1936 };
1937 if let Some(adopted) = adopted {
1938 adopt_queue(&adopted, &pending_path)?;
1939 }
1940 let pending_events = drain_pending(&pending_path)?;
1941
1942 let mut send_failed = false;
1943 let mut warned = false;
1947
1948 for (i, pending_json) in pending_events.iter().enumerate() {
1952 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1953 if std::time::Instant::now() >= deadline
1957 || !matches!(
1958 tokio::time::timeout_at(
1959 (deadline + IN_FLIGHT_GRACE).into(),
1960 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1961 )
1962 .await,
1963 Ok(Ok(_))
1964 )
1965 {
1966 for evt in &pending_events[i..] {
1973 append_pending(&pending_path, evt)?;
1974 }
1975 send_failed = true;
1976 break;
1977 }
1978 }
1979 }
1980
1981 let sends_event = sends_main
1986 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
1987 let all_accepted = if sends_event {
1988 deliver_parts(
1989 &client,
1990 &attribution,
1991 force,
1992 split_into_parts(req),
1993 &pending_path,
1994 send_failed,
1995 deadline,
1996 &mut warned,
1997 )
1998 .await?
1999 } else {
2000 true
2001 };
2002 if sends_main && (all_accepted || is_inline) {
2015 crate::subagents::write_offset(&offset_path, new_offset)?;
2016 }
2017
2018 if sender == Sender::Hook && agent == crate::agent::Agent::ClaudeCode {
2023 deliver_subagent_transcripts(
2024 &client,
2025 &attribution,
2026 force,
2027 &subagent_template,
2028 transcript_path,
2029 session_dir,
2030 &pending_path,
2031 send_failed || !all_accepted,
2032 deadline,
2033 matches!(event_type, "stop" | "subagent-stop" | "session-end")
2034 .then(|| deadline + FINAL_LOCK_WAIT),
2035 &mut warned,
2036 )
2037 .await?;
2038 }
2039
2040 Ok(if !send_failed && all_accepted {
2041 Sent::Accepted
2042 } else {
2043 Sent::Queued
2044 })
2045}
2046
2047#[cfg(test)]
2048mod tests {
2049 use super::*;
2050 use crate::api_client::AttributionMode;
2051 use crate::config::UserContext;
2052 use crate::context::{Context, EffectiveContext};
2053 use std::collections::BTreeMap;
2054
2055 #[test]
2056 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
2057 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
2058 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
2059 project,
2060 };
2061 let a = uuid::Uuid::from_u128(0xa);
2062 let b = uuid::Uuid::from_u128(0xb);
2063 let only = |project_id| Attribution::ProjectOnly { project_id };
2064
2065 let recorded = attribution_record(&repo(Some(a)));
2066 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
2067 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
2068 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
2069 let recorded = attribution_record(&only(a));
2070 assert!(catch_up_may_send(Some(&recorded), &only(a)));
2071 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
2072 assert!(catch_up_may_send(None, &repo(Some(b))));
2075 assert!(!catch_up_may_send(None, &only(a)));
2076 }
2077
2078 #[test]
2079 fn record_metadata_keeps_the_other_keys() {
2080 let dir = tempfile::tempdir().unwrap();
2081 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
2082 record_metadata(
2083 dir.path(),
2084 "attribution",
2085 serde_json::json!({"repo_id": "r"}),
2086 )
2087 .unwrap();
2088 let meta = session_metadata(dir.path());
2089 assert_eq!(meta["transcript_path"], "/t.jsonl");
2090 assert_eq!(meta["attribution"]["repo_id"], "r");
2091 }
2092
2093 #[test]
2094 fn hook_events_map_to_server_events() {
2095 assert_eq!(
2096 stream_event_type("notification"),
2097 StreamEventType::SessionStart
2098 );
2099 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
2102 assert_eq!(
2103 stream_event_type("session-end"),
2104 StreamEventType::Transcript
2105 );
2106 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
2107 assert_eq!(
2108 stream_event_type(event),
2109 StreamEventType::ToolUse,
2110 "{event}"
2111 );
2112 }
2113 }
2114
2115 #[test]
2118 fn disabled_user_context_resolves_to_none() {
2119 assert!(UserContext::Toggle(false).resolve().is_none());
2123 }
2124
2125 #[test]
2126 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
2127 let dir = tempfile::tempdir().unwrap();
2131 let effective = Context::effective(dir.path(), None);
2132 assert_eq!(effective, EffectiveContext::default());
2133 }
2134
2135 #[test]
2138 fn apply_context_stamps_all_fields() {
2139 let dir = tempfile::tempdir().unwrap();
2140 let mut params = BTreeMap::new();
2141 params.insert("env".to_string(), "prod".to_string());
2142 params.insert("region".to_string(), "eu-west-1".to_string());
2143
2144 let ctx = EffectiveContext {
2145 flow_id: Some("flow-xyz".to_string()),
2146 labels: vec!["backend".to_string(), "urgent".to_string()],
2147 params,
2148 };
2149
2150 let (flow_id, labels, params_out) = apply_context(ctx);
2151
2152 assert_eq!(flow_id, Some("flow-xyz".to_string()));
2153 assert_eq!(
2154 labels,
2155 Some(vec!["backend".to_string(), "urgent".to_string()])
2156 );
2157 let p = params_out.expect("params should be Some");
2158 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
2159 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
2160
2161 let written = Context {
2164 flow_id: Some("flow-xyz".to_string()),
2165 labels: vec!["backend".to_string(), "urgent".to_string()],
2166 params: {
2167 let mut m = BTreeMap::new();
2168 m.insert("env".to_string(), Some("prod".to_string()));
2169 m.insert("region".to_string(), Some("eu-west-1".to_string()));
2170 m
2171 },
2172 };
2173 let ctx_path = dir.path().join(".visdom").join("context.json");
2174 written.save_to(&ctx_path).unwrap();
2175 let loaded = Context::load_from(&ctx_path);
2176 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
2177 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
2178 assert!(labels2.is_some());
2179 assert!(params2.is_some());
2180 }
2181
2182 #[test]
2185 fn apply_context_missing_file_all_none() {
2186 let dir = tempfile::tempdir().unwrap();
2187 let missing_path = dir.path().join(".visdom").join("context.json");
2188 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
2190 assert!(flow_id.is_none(), "flow_id should be None");
2191 assert!(labels.is_none(), "labels should be None");
2192 assert!(params.is_none(), "params should be None");
2193 }
2194
2195 #[test]
2198 fn apply_context_empty_collections_are_none() {
2199 let ctx = EffectiveContext {
2200 flow_id: None,
2201 labels: vec![],
2202 params: BTreeMap::new(),
2203 };
2204 let (flow_id, labels, params) = apply_context(ctx);
2205 assert!(flow_id.is_none());
2206 assert!(
2207 labels.is_none(),
2208 "empty labels should be None, not Some([])"
2209 );
2210 assert!(
2211 params.is_none(),
2212 "empty params should be None, not Some({{}})"
2213 );
2214 }
2215
2216 #[test]
2219 fn apply_context_flow_id_only() {
2220 let ctx = EffectiveContext {
2221 flow_id: Some("my-flow".to_string()),
2222 labels: vec![],
2223 params: BTreeMap::new(),
2224 };
2225 let (flow_id, labels, params) = apply_context(ctx);
2226 assert_eq!(flow_id, Some("my-flow".to_string()));
2227 assert!(labels.is_none());
2228 assert!(params.is_none());
2229 }
2230
2231 use crate::test_helpers::{add_worktree, init_git_repo};
2238
2239 #[test]
2242 fn resolve_session_paths_primary_checkout() {
2243 let tmp = tempfile::tempdir().unwrap();
2244 let repo = tmp.path().join("repo");
2245 std::fs::create_dir_all(&repo).unwrap();
2246 init_git_repo(&repo);
2247 std::fs::create_dir_all(repo.join(".visdom")).unwrap();
2249
2250 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
2251 let project_root = resolved.root;
2252
2253 assert_eq!(
2254 project_root.canonicalize().unwrap(),
2255 repo.canonicalize().unwrap(),
2256 "primary checkout: project_root must be repo root"
2257 );
2258 assert_eq!(
2259 session_dir.canonicalize().unwrap_or(session_dir.clone()),
2260 repo.join(".visdom")
2261 .join("sessions")
2262 .join("sess-primary-123"),
2263 "primary checkout: session_dir must be <repo>/.visdom/sessions/<id>/"
2264 );
2265 assert!(
2267 session_dir.starts_with(&repo),
2268 "session_dir must be under the primary repo root"
2269 );
2270 }
2271
2272 #[test]
2276 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
2277 let tmp = tempfile::tempdir().unwrap();
2278 let repo = tmp.path().join("repo");
2279 let wt = tmp.path().join("sibling-wt");
2281
2282 std::fs::create_dir_all(&repo).unwrap();
2283 init_git_repo(&repo);
2284 std::fs::create_dir_all(repo.join(".visdom")).unwrap();
2286 add_worktree(&repo, &wt);
2287
2288 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
2289 let project_root = resolved.root;
2290
2291 assert_eq!(
2293 project_root.canonicalize().unwrap(),
2294 repo.canonicalize().unwrap(),
2295 "sibling worktree: project_root must be primary repo root (not worktree dir)"
2296 );
2297 assert!(
2299 session_dir.starts_with(&repo),
2300 "sibling worktree: session_dir must be under the PRIMARY repo root"
2301 );
2302 assert!(
2303 !session_dir.starts_with(&wt),
2304 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
2305 );
2306 assert!(
2307 session_dir.ends_with(
2308 std::path::Path::new(".visdom")
2309 .join("sessions")
2310 .join("sess-sibling-456")
2311 ),
2312 "session_dir must end with .visdom/sessions/<session_id>"
2313 );
2314 }
2315
2316 #[test]
2319 fn resolve_session_paths_non_git_fallback() {
2320 let tmp = tempfile::tempdir().unwrap();
2321 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
2323 let project_root = resolved.root;
2324
2325 assert_eq!(
2326 project_root,
2327 tmp.path(),
2328 "non-git: project_root must fall back to hook_cwd"
2329 );
2330 assert_eq!(
2331 session_dir,
2332 tmp.path()
2333 .join(".visdom")
2334 .join("sessions")
2335 .join("sess-fallback-789"),
2336 "non-git: session_dir must be relative to the fallback root"
2337 );
2338 }
2339
2340 #[test]
2345 fn origin_marker_written_in_session_dir() {
2346 let tmp = tempfile::tempdir().unwrap();
2347 let repo = tmp.path().join("repo");
2348 std::fs::create_dir_all(&repo).unwrap();
2349 init_git_repo(&repo);
2350
2351 let session_dir = repo.join(".visdom").join("sessions").join("test-sess-001");
2352 std::fs::create_dir_all(&session_dir).unwrap();
2353
2354 let hook_cwd = &repo;
2355 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2356 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2357
2358 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2359 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2360 assert_eq!(
2361 origin_content.trim(),
2362 expected.as_str(),
2363 "origin marker must contain the canonicalized worktree toplevel"
2364 );
2365 }
2366
2367 fn metadata(session_dir: &Path) -> serde_json::Value {
2368 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2369 .unwrap()
2370 }
2371
2372 #[test]
2373 fn record_transcript_path_writes_metadata_for_check() {
2374 let tmp = tempfile::tempdir().unwrap();
2375 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2376 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2377 }
2378
2379 #[test]
2380 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2381 let tmp = tempfile::tempdir().unwrap();
2382 std::fs::write(
2383 tmp.path().join("metadata.json"),
2384 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2385 )
2386 .unwrap();
2387 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2388 let m = metadata(tmp.path());
2389 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2390 assert_eq!(m["model"], "m");
2391 let leftovers = std::fs::read_dir(tmp.path())
2392 .unwrap()
2393 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2394 .count();
2395 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2396 }
2397
2398 #[test]
2399 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2400 let tmp = tempfile::tempdir().unwrap();
2401 record_transcript_path(tmp.path(), "").unwrap();
2402 assert!(!tmp.path().join("metadata.json").exists());
2403
2404 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2405 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2406 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2407 }
2408
2409 use crate::session_state::{RepoBinding, SessionState};
2412
2413 fn binding(id: &str) -> RepoBinding {
2414 RepoBinding {
2415 repo_id: id.into(),
2416 git_url: None,
2417 remote_id: None,
2418 codebase_name: None,
2419 updated_at: "t".into(),
2420 }
2421 }
2422
2423 #[test]
2426 fn resolve_stream_binding_uses_session_active_when_unbound() {
2427 let session = SessionState {
2428 active: Some(binding("session-repo")),
2429 subagents: HashMap::new(),
2430 ..Default::default()
2431 };
2432 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2433 assert_eq!(got.unwrap().repo_id, "session-repo");
2434 }
2435
2436 #[test]
2439 fn resolve_stream_binding_falls_back_to_bound_config() {
2440 let session = SessionState::default();
2441 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2442 assert_eq!(got.unwrap().repo_id, "bound-repo");
2443 }
2444
2445 #[test]
2448 fn resolve_stream_binding_none_when_nothing_resolves() {
2449 let session = SessionState::default();
2450 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2451 assert!(got.is_none());
2452 }
2453
2454 #[test]
2457 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2458 let session = SessionState {
2459 active: Some(binding("session-repo")),
2460 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2461 ..Default::default()
2462 };
2463 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2464 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2465 }
2466
2467 #[test]
2471 fn resolve_stream_binding_falls_back_to_user_default() {
2472 let session = SessionState::default();
2473 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2474 assert_eq!(got.unwrap().repo_id, "userdef");
2475 }
2476
2477 #[test]
2480 fn resolve_stream_binding_prefers_bound_over_user_default() {
2481 let session = SessionState::default();
2482 let got = resolve_stream_binding(
2483 &session,
2484 "/wt/x",
2485 Some(binding("bound")),
2486 Some(binding("userdef")),
2487 );
2488 assert_eq!(got.unwrap().repo_id, "bound");
2489 }
2490
2491 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2494 crate::session_state::RepoBinding {
2495 repo_id: repo_id.into(),
2496 git_url: None,
2497 remote_id: None,
2498 codebase_name: None,
2499 updated_at: String::new(),
2500 }
2501 }
2502
2503 #[test]
2507 fn attribution_falls_back_to_project_when_no_repo_binds() {
2508 let pid = uuid::Uuid::new_v4();
2509 assert_eq!(
2510 attribution_for(None, Some(pid)),
2511 Some(Attribution::ProjectOnly { project_id: pid })
2512 );
2513 }
2514
2515 #[test]
2517 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2518 assert_eq!(attribution_for(None, None), None);
2519 }
2520
2521 #[test]
2524 fn attribution_uses_repo_with_no_project_overlay() {
2525 let repo = uuid::Uuid::new_v4().to_string();
2526 let b = binding_with(&repo);
2527 assert_eq!(
2528 attribution_for(Some(&b), None),
2529 Some(Attribution::Repo {
2530 repo_id: repo,
2531 project: None
2532 })
2533 );
2534 }
2535
2536 #[test]
2539 fn attribution_overlays_project_on_repo() {
2540 let repo = uuid::Uuid::new_v4().to_string();
2541 let pid = uuid::Uuid::new_v4();
2542 let b = binding_with(&repo);
2543 assert_eq!(
2544 attribution_for(Some(&b), Some(pid)),
2545 Some(Attribution::Repo {
2546 repo_id: repo,
2547 project: Some(pid)
2548 })
2549 );
2550 }
2551
2552 #[test]
2555 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2556 let pid = uuid::Uuid::new_v4();
2557 let b = binding_with("../../escape");
2558 assert_eq!(
2559 attribution_for(Some(&b), Some(pid)),
2560 Some(Attribution::ProjectOnly { project_id: pid })
2561 );
2562 }
2563
2564 #[test]
2567 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2568 let b = binding_with("../../escape");
2569 assert_eq!(attribution_for(Some(&b), None), None);
2570 }
2571
2572 #[test]
2577 fn pending_file_name_for_a_repo_is_unchanged() {
2578 let repo = uuid::Uuid::new_v4().to_string();
2579 assert_eq!(
2580 Attribution::Repo {
2581 repo_id: repo.clone(),
2582 project: Some(uuid::Uuid::new_v4())
2583 }
2584 .pending_file_name(),
2585 format!("pending-{repo}.jsonl")
2586 );
2587 }
2588
2589 #[test]
2592 fn pending_file_name_for_a_project_is_distinct() {
2593 let pid = uuid::Uuid::new_v4();
2594 assert_eq!(
2595 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2596 format!("pending-project-{pid}.jsonl")
2597 );
2598 }
2599
2600 #[test]
2603 fn binding_repo_id_is_valid_accepts_real_uuid() {
2604 assert!(binding_repo_id_is_valid(
2605 "550e8400-e29b-41d4-a716-446655440000"
2606 ));
2607 }
2608
2609 #[test]
2610 fn binding_repo_id_is_valid_rejects_path_traversal() {
2611 assert!(!binding_repo_id_is_valid("../evil"));
2612 }
2613
2614 #[test]
2615 fn binding_repo_id_is_valid_rejects_empty() {
2616 assert!(!binding_repo_id_is_valid(""));
2617 }
2618
2619 #[test]
2620 fn binding_repo_id_is_valid_rejects_non_uuid() {
2621 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2622 }
2623
2624 #[test]
2627 fn stamp_agent_sets_tool_and_version() {
2628 use crate::agent::Agent;
2629 let mut req = StreamEventRequest {
2630 protocol_version: 1,
2631 tool: Some("claude-code".to_string()),
2632 event_type: StreamEventType::ToolUse,
2633 session_id: "s".into(),
2634 timestamp: chrono::Utc::now(),
2635 hook_event_name: None,
2636 tool_name: None,
2637 tool_use_id: None,
2638 tool_input: None,
2639 tool_response: None,
2640 tool_is_error: None,
2641 event_index: None,
2642 event_uuid: None,
2643 transcript_lines: None,
2644 transcript_offset: None,
2645 model: None,
2646 cwd: None,
2647 final_stats: None,
2648 flow_id: None,
2649 labels: None,
2650 params: None,
2651 billing_mode: None,
2652 };
2653 stamp_agent(&mut req, Agent::Codex);
2654 assert_eq!(req.tool.as_deref(), Some("codex"));
2655 assert_eq!(req.protocol_version, 2);
2656
2657 stamp_agent(&mut req, Agent::ClaudeCode);
2658 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2659 assert_eq!(req.protocol_version, 1);
2660 }
2661
2662 fn repo_attr(repo_id: &str) -> Attribution {
2665 Attribution::Repo {
2666 repo_id: repo_id.into(),
2667 project: None,
2668 }
2669 }
2670
2671 #[test]
2672 fn pending_path_is_repo_scoped() {
2673 let dir = std::path::Path::new("/tmp/sess");
2674 assert_eq!(
2675 pending_path_for(dir, &repo_attr("repo-a")),
2676 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2677 );
2678 assert_ne!(
2679 pending_path_for(dir, &repo_attr("repo-a")),
2680 pending_path_for(dir, &repo_attr("repo-b")),
2681 );
2682 }
2683
2684 #[test]
2687 fn pending_path_for_a_project_never_collides_with_a_repo() {
2688 let dir = std::path::Path::new("/tmp/sess");
2689 let pid = uuid::Uuid::from_u128(9);
2690 assert_eq!(
2691 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2692 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2693 );
2694 assert_ne!(
2695 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2696 pending_path_for(dir, &repo_attr(&pid.to_string())),
2697 );
2698 }
2699
2700 #[test]
2703 fn read_new_transcript_lines_empty_path_is_noop() {
2704 let dir = tempfile::tempdir().unwrap();
2708 let offset_path = dir.path().join(".stream_offset");
2709 let (lines, start_offset, end_offset) =
2710 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2711 assert!(
2712 lines.is_empty(),
2713 "empty path must yield no transcript lines"
2714 );
2715 assert_eq!(start_offset, 0);
2716 assert_eq!(end_offset, 0);
2717 }
2718
2719 #[test]
2723 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2724 let dir = tempfile::tempdir().unwrap();
2725 let transcript_path = dir.path().join("transcript.jsonl");
2726 let offset_path = dir.path().join(".stream_offset");
2727
2728 fs::write(
2729 &transcript_path,
2730 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2731 )
2732 .unwrap();
2733
2734 let (lines, start_offset, end_offset) =
2735 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2736 assert_eq!(lines.len(), 2);
2737 assert_eq!(start_offset, 0, "first read starts at byte 0");
2738 assert!(end_offset > 0);
2739
2740 fs::write(&offset_path, end_offset.to_string()).unwrap();
2741
2742 let mut f = OpenOptions::new()
2743 .append(true)
2744 .open(&transcript_path)
2745 .unwrap();
2746 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2747 drop(f);
2748
2749 let (lines2, start_offset2, end_offset2) =
2750 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2751 assert_eq!(lines2.len(), 1);
2752 assert_eq!(
2753 start_offset2, end_offset,
2754 "second read's start_offset must equal the first read's persisted end_offset"
2755 );
2756 assert!(end_offset2 > start_offset2);
2757 }
2758
2759 #[tokio::test]
2777 async fn capture_project_precedence_local_only() {
2778 use crate::session_state::{ProjectBinding, SessionState};
2779 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2780 let tmp = tempfile::tempdir().unwrap();
2781 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2782 _guard.set("XDG_CONFIG_HOME", tmp.path());
2783 _guard.set("HOME", tmp.path());
2784 _guard.remove("TRACEVAULT_PROJECT");
2785
2786 let pb = |id: &str| ProjectBinding {
2787 project_id: id.into(),
2788 project_name: "n".into(),
2789 updated_at: "".into(),
2790 forced_until: None,
2791 };
2792 let u = uuid::Uuid::from_u128;
2793 let s = SessionState {
2795 active_project: Some(pb(&u(2).to_string())),
2796 ..Default::default()
2797 };
2798 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(2)));
2799 let mut s = s;
2801 s.subagent_projects
2802 .insert("/wt".into(), pb(&u(1).to_string()));
2803 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(1)));
2804 assert_eq!(capture_project(&s, Some("/other"), None), Some(u(2)));
2806 assert_eq!(capture_project(&SessionState::default(), None, None), None);
2808 let bad = SessionState {
2810 active_project: Some(pb("not-a-uuid")),
2811 ..Default::default()
2812 };
2813 assert_eq!(capture_project(&bad, None, None), None);
2814 let path = crate::user_project_default::default_project_path().unwrap();
2816 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2817 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2818 assert_eq!(
2819 capture_project(&SessionState::default(), None, None),
2820 Some(u(3))
2821 );
2822 }
2823
2824 #[test]
2835 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2836 use crate::session_state::{ProjectBinding, SessionState};
2837 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2838 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2839 _guard.remove("TRACEVAULT_PROJECT");
2840 let pid = uuid::Uuid::from_u128(2);
2841 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2842 let s = SessionState {
2843 active_project: Some(ProjectBinding {
2844 project_id: pid.to_string(),
2845 project_name: "n".into(),
2846 updated_at: "".into(),
2847 forced_until: Some(future.clone()),
2848 }),
2849 ..Default::default()
2850 };
2851 let got = capture_binding(&s, Some("/wt"), None).expect("session-active binding resolves");
2852 assert_eq!(got.forced_until, Some(future));
2853 }
2854
2855 #[test]
2860 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2861 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2865
2866 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2867 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2868
2869 _guard.set("TRACEVAULT_PROJECT", uuid);
2870 let got = env_project_binding().expect("uuid form is honoured");
2871 assert_eq!(got.project_id, uuid);
2872
2873 _guard.set("TRACEVAULT_PROJECT", "my-project");
2874 assert!(
2875 env_project_binding().is_none(),
2876 "a name is ignored on the network-free capture path"
2877 );
2878
2879 _guard.remove("TRACEVAULT_PROJECT");
2880 assert!(env_project_binding().is_none());
2881 }
2882
2883 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2891 crate::session_state::ProjectBinding {
2892 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2893 project_name: "p".into(),
2894 updated_at: chrono::Utc::now().to_rfc3339(),
2895 forced_until: forced_until.map(str::to_string),
2896 }
2897 }
2898
2899 #[test]
2900 fn env_force_is_explicit_and_needs_no_expiry() {
2901 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2902 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2903 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2904
2905 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2906 }
2907
2908 #[test]
2909 fn absent_or_unrecognised_env_is_derived() {
2910 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2911 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2912
2913 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2914 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2915
2916 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2921 assert_eq!(attribution_mode(None), AttributionMode::Derived);
2922 }
2923
2924 #[test]
2930 fn live_binding_force_is_explicit_without_env() {
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 future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2936 let binding = forced_binding(Some(&future));
2937
2938 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2939 }
2940
2941 #[test]
2948 fn lapsed_binding_force_is_derived_without_env() {
2949 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2950 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2951 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2952
2953 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2954 let binding = forced_binding(Some(&past));
2955
2956 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2957 }
2958
2959 #[test]
2964 fn unparseable_forced_until_is_derived() {
2965 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2966 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2967 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2968
2969 let binding = forced_binding(Some("not-a-timestamp"));
2970
2971 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2972 }
2973
2974 #[test]
2981 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2982 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2983 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2984 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2985
2986 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2987 let binding = forced_binding(Some(&past));
2988
2989 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2990 }
2991
2992 #[tokio::test]
3005 async fn session_scoped_force_is_honoured_on_the_wire() {
3006 use crate::session_state::{ProjectBinding, SessionState};
3007
3008 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3009 let tmp = tempfile::tempdir().unwrap();
3010 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3011 _guard.set("XDG_CONFIG_HOME", tmp.path());
3015 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3016 _guard.remove("TRACEVAULT_PROJECT");
3020
3021 let pid = uuid::Uuid::from_u128(321);
3022 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3023 let session = SessionState {
3024 active_project: Some(ProjectBinding {
3025 project_id: pid.to_string(),
3026 project_name: "proj".into(),
3027 updated_at: "".into(),
3028 forced_until: Some(future),
3029 }),
3030 ..Default::default()
3031 };
3032 let capture_binding = capture_binding(&session, None, None);
3033
3034 let resp = ok_stream_response();
3035 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3036 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3037 let req = sample_stream_event_request();
3038 let mut warned = false;
3039
3040 let got = send_stream_event(
3041 &client,
3042 &Attribution::ProjectOnly { project_id: pid },
3043 attribution_force(capture_binding.as_ref()),
3044 &req,
3045 &mut warned,
3046 )
3047 .await
3048 .expect("send_stream_event must succeed");
3049 assert_eq!(got.status, "accepted");
3050
3051 let captured = rx
3052 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3053 .expect("no request captured");
3054 assert!(
3055 captured
3056 .to_lowercase()
3057 .contains("x-tracevault-project-attribution: explicit"),
3058 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
3059 );
3060 }
3061
3062 #[test]
3071 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
3072 use crate::session_state::{ProjectBinding, SessionState};
3073
3074 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3075 let tmp = tempfile::tempdir().unwrap();
3076 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3077 _guard.set("XDG_CONFIG_HOME", tmp.path());
3078 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3079
3080 let project_a = uuid::Uuid::from_u128(1);
3081 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3082 crate::user_project_default::save(&ProjectBinding {
3083 project_id: project_a.to_string(),
3084 project_name: "a".into(),
3085 updated_at: chrono::Utc::now().to_rfc3339(),
3086 forced_until: Some(future),
3087 })
3088 .unwrap();
3089
3090 let project_b = uuid::Uuid::from_u128(2);
3091 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
3092
3093 let capture_binding = capture_binding(&SessionState::default(), None, None);
3094 assert_eq!(
3095 capture_binding.as_ref().map(|b| b.project_id.as_str()),
3096 Some(project_b.to_string()).as_deref(),
3097 "TRACEVAULT_PROJECT must outrank the user-level default"
3098 );
3099
3100 assert_eq!(
3101 attribution_mode(capture_binding.as_ref()),
3102 AttributionMode::Derived,
3103 "a force on the user-default project must not leak onto a DIFFERENT, \
3104 higher-precedence project that never asked to be forced"
3105 );
3106 }
3107
3108 use std::io::BufReader;
3111 use std::net::TcpListener;
3112 use std::sync::mpsc;
3113 use std::thread;
3114 use std::time::{Duration, Instant};
3115
3116 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
3121
3122 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
3127 let deadline = Instant::now() + ACCEPT_DEADLINE;
3128 loop {
3129 match listener.accept() {
3130 Ok((stream, _)) => {
3131 let _ = stream.set_nonblocking(false);
3136 return Some(stream);
3137 }
3138 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
3139 if Instant::now() >= deadline {
3140 return None;
3141 }
3142 thread::sleep(Duration::from_millis(20));
3143 }
3144 Err(_) => return None,
3145 }
3146 }
3147 }
3148
3149 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
3153
3154 fn capture_request_and_respond(
3174 stream: std::net::TcpStream,
3175 tx: &mpsc::Sender<String>,
3176 response: &str,
3177 ) {
3178 let mut reader = BufReader::new(stream);
3179 let mut captured = String::new();
3180 let _ = reader.read_line(&mut captured);
3181 loop {
3182 let mut header = String::new();
3183 if reader.read_line(&mut header).unwrap_or(0) == 0 {
3184 break;
3185 }
3186 if header.trim().is_empty() {
3187 break;
3188 }
3189 captured.push_str(&header);
3190 }
3191 let _ = tx.send(captured);
3192 let mut stream = reader.into_inner();
3193 let _ = stream.write_all(response.as_bytes());
3194 let _ = stream.flush();
3195 }
3196
3197 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
3202 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3203 listener.set_nonblocking(true).unwrap();
3204 let addr = listener.local_addr().unwrap();
3205 let (tx, rx) = mpsc::channel();
3206 thread::spawn(move || {
3207 if let Some(stream) = accept_with_deadline(&listener) {
3208 capture_request_and_respond(stream, &tx, response);
3209 }
3210 });
3211 (format!("http://{addr}"), rx)
3212 }
3213
3214 fn ok_stream_response() -> String {
3215 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
3216 session_db_id: uuid::Uuid::nil(),
3217 event_db_id: Some(uuid::Uuid::nil()),
3218 status: "accepted".to_string(),
3219 })
3220 .unwrap();
3221 format!(
3222 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3223 body.len(),
3224 body
3225 )
3226 }
3227
3228 fn sample_stream_event_request() -> StreamEventRequest {
3229 StreamEventRequest {
3230 protocol_version: 2,
3231 tool: Some("claude-code".to_string()),
3232 event_type: StreamEventType::ToolUse,
3233 session_id: "sess-1".into(),
3234 timestamp: chrono::Utc::now(),
3235 hook_event_name: Some("PostToolUse".into()),
3236 tool_name: None,
3237 tool_use_id: None,
3238 tool_input: None,
3239 tool_response: None,
3240 tool_is_error: None,
3241 event_index: None,
3242 event_uuid: None,
3243 transcript_lines: None,
3244 transcript_offset: None,
3245 model: None,
3246 cwd: None,
3247 final_stats: None,
3248 flow_id: None,
3249 labels: None,
3250 params: None,
3251 billing_mode: None,
3252 }
3253 }
3254
3255 #[tokio::test]
3260 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
3261 use crate::session_state::{ProjectBinding, SessionState};
3262
3263 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3267 let tmp = tempfile::tempdir().unwrap();
3268 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3269 _guard.set("XDG_CONFIG_HOME", tmp.path());
3270 _guard.remove("TRACEVAULT_PROJECT");
3275 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3276
3277 let pid = uuid::Uuid::from_u128(99);
3278 let session = SessionState {
3279 active_project: Some(ProjectBinding {
3280 project_id: pid.to_string(),
3281 project_name: "proj".into(),
3282 updated_at: "".into(),
3283 forced_until: None,
3284 }),
3285 ..Default::default()
3286 };
3287 let capture_binding = capture_binding(&session, None, None);
3288 let capture_pid = capture_binding
3289 .as_ref()
3290 .and_then(crate::resolution::capture_project_id);
3291 assert_eq!(capture_pid, Some(pid));
3292
3293 let resp = ok_stream_response();
3294 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3295 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3296 let req = sample_stream_event_request();
3297
3298 let mut warned = false;
3299 let got = send_stream_event(
3300 &client,
3301 &Attribution::Repo {
3302 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3303 project: capture_pid,
3304 },
3305 attribution_force(capture_binding.as_ref()),
3306 &req,
3307 &mut warned,
3308 )
3309 .await
3310 .expect("send_stream_event must succeed");
3311 assert_eq!(got.status, "accepted");
3312
3313 let line = rx
3314 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3315 .expect("no request captured");
3316 assert!(
3317 line.starts_with(&format!(
3318 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
3319 )),
3320 "an active project binding must route to the project-scoped endpoint, got: {line}"
3321 );
3322 assert!(
3328 line.to_lowercase()
3329 .contains("x-tracevault-project-attribution: derived"),
3330 "got: {line}"
3331 );
3332 }
3333
3334 #[tokio::test]
3339 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
3340 use crate::session_state::SessionState;
3341
3342 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3343 let tmp = tempfile::tempdir().unwrap();
3344 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3345 _guard.set("XDG_CONFIG_HOME", tmp.path());
3350 _guard.remove("TRACEVAULT_PROJECT");
3351
3352 let capture_binding = capture_binding(&SessionState::default(), None, None);
3353 assert_eq!(capture_binding, None);
3354
3355 let resp = ok_stream_response();
3356 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3357 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3358 let req = sample_stream_event_request();
3359
3360 let mut warned = false;
3361 let got = send_stream_event(
3362 &client,
3363 &Attribution::Repo {
3364 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3365 project: None,
3366 },
3367 attribution_force(capture_binding.as_ref()),
3368 &req,
3369 &mut warned,
3370 )
3371 .await
3372 .expect("send_stream_event must succeed");
3373 assert_eq!(got.status, "accepted");
3374
3375 let line = rx
3376 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3377 .expect("no request captured");
3378 assert!(
3379 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3380 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3381 );
3382 }
3383
3384 fn spawn_n_capturing_requests(
3395 responses: Vec<&'static str>,
3396 ) -> (String, mpsc::Receiver<String>) {
3397 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3398 listener.set_nonblocking(true).unwrap();
3399 let addr = listener.local_addr().unwrap();
3400 let (tx, rx) = mpsc::channel();
3401 thread::spawn(move || {
3402 for response in responses {
3403 let Some(stream) = accept_with_deadline(&listener) else {
3408 break;
3409 };
3410 capture_request_and_respond(stream, &tx, response);
3411 }
3412 });
3417 (format!("http://{addr}"), rx)
3418 }
3419
3420 #[tokio::test]
3427 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3428 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3429 let resp_400 = format!(
3430 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3431 body_400.len(),
3432 body_400
3433 );
3434 let resp_200 = ok_stream_response();
3435
3436 let (base, rx) = spawn_n_capturing_requests(vec![
3437 Box::leak(resp_400.into_boxed_str()),
3438 Box::leak(resp_200.into_boxed_str()),
3439 ]);
3440 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3441 let req = sample_stream_event_request();
3442 let pid = uuid::Uuid::from_u128(42);
3443
3444 let mut warned = false;
3445 let err = send_stream_event(
3446 &client,
3447 &Attribution::Repo {
3448 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3449 project: Some(pid),
3450 },
3451 attribution_force(None),
3452 &req,
3453 &mut warned,
3454 )
3455 .await
3456 .expect_err("a refused declared project must be an error, not a silent fallback");
3457 assert!(
3458 err.to_string().contains("400"),
3459 "propagated error must reflect the status, got: {err}"
3460 );
3461 assert!(
3462 warned,
3463 "the refusal must be printed (gated on `warned`) so it is visible"
3464 );
3465
3466 let first = rx
3467 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3468 .expect("no first request captured");
3469 assert!(
3470 first.contains(&format!("/projects/{pid}/stream")),
3471 "first request must hit the project-scoped endpoint, got: {first}"
3472 );
3473 assert!(
3474 first.contains("repo_id="),
3475 "first request must carry repo_id, got: {first}"
3476 );
3477
3478 assert!(
3479 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3480 "no second (repo-scoped fallback) request must be sent"
3481 );
3482 }
3483
3484 #[tokio::test]
3487 async fn send_stream_event_errors_on_403_without_fallback() {
3488 let body_403 = "forbidden";
3489 let resp_403 = format!(
3490 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3491 body_403.len(),
3492 body_403
3493 );
3494 let resp_200 = ok_stream_response();
3495
3496 let (base, rx) = spawn_n_capturing_requests(vec![
3497 Box::leak(resp_403.into_boxed_str()),
3498 Box::leak(resp_200.into_boxed_str()),
3499 ]);
3500 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3501 let req = sample_stream_event_request();
3502 let pid = uuid::Uuid::from_u128(43);
3503
3504 let mut warned = false;
3505 let err = send_stream_event(
3506 &client,
3507 &Attribution::Repo {
3508 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3509 project: Some(pid),
3510 },
3511 attribution_force(None),
3512 &req,
3513 &mut warned,
3514 )
3515 .await
3516 .expect_err("a refused declared project must be an error, not a silent fallback");
3517 assert!(
3518 err.to_string().contains("403"),
3519 "propagated error must reflect the status, got: {err}"
3520 );
3521 assert!(
3522 warned,
3523 "the refusal must be printed (gated on `warned`) so it is visible"
3524 );
3525
3526 let first = rx
3527 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3528 .expect("no first request captured");
3529 assert!(
3530 first.contains(&format!("/projects/{pid}/stream")),
3531 "first request must hit the project-scoped endpoint, got: {first}"
3532 );
3533 assert!(
3534 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3535 "no second (repo-scoped fallback) request must be sent"
3536 );
3537 }
3538
3539 #[tokio::test]
3544 async fn refused_error_is_printed_once_per_invocation() {
3545 let body_400 = "not a member";
3546 let resp_400 = || {
3547 format!(
3548 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3549 body_400.len(),
3550 body_400
3551 )
3552 };
3553 let (base, _rx) = spawn_n_capturing_requests(vec![
3554 Box::leak(resp_400().into_boxed_str()),
3555 Box::leak(resp_400().into_boxed_str()),
3556 ]);
3557 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3558 let req = sample_stream_event_request();
3559 let pid = uuid::Uuid::from_u128(44);
3560 let attribution = Attribution::Repo {
3561 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3562 project: Some(pid),
3563 };
3564
3565 let mut warned = false;
3566 assert!(
3567 send_stream_event(
3568 &client,
3569 &attribution,
3570 attribution_force(None),
3571 &req,
3572 &mut warned
3573 )
3574 .await
3575 .is_err(),
3576 "a refused declared project must be an error"
3577 );
3578 assert!(warned, "the flag must be set after the first refusal");
3579
3580 assert!(
3581 send_stream_event(
3582 &client,
3583 &attribution,
3584 attribution_force(None),
3585 &req,
3586 &mut warned
3587 )
3588 .await
3589 .is_err(),
3590 "a second refusal must also be an error"
3591 );
3592 assert!(warned, "the flag stays set across the shared invocation");
3593 }
3594
3595 #[tokio::test]
3607 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3608 let body_403 = "forbidden";
3609 let resp_403 = format!(
3610 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3611 body_403.len(),
3612 body_403
3613 );
3614 let resp_200 = ok_stream_response();
3615
3616 let (base, rx) = spawn_n_capturing_requests(vec![
3617 Box::leak(resp_403.into_boxed_str()),
3618 Box::leak(resp_200.into_boxed_str()),
3619 ]);
3620 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3621 let req = sample_stream_event_request();
3622 let pid = uuid::Uuid::from_u128(42);
3623
3624 let forced = crate::session_state::ProjectBinding {
3627 project_id: pid.to_string(),
3628 project_name: "forced".into(),
3629 updated_at: "".into(),
3630 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3631 };
3632
3633 let mut warned = false;
3634 let err = send_stream_event(
3635 &client,
3636 &Attribution::Repo {
3637 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3638 project: Some(pid),
3639 },
3640 attribution_force(Some(&forced)),
3641 &req,
3642 &mut warned,
3643 )
3644 .await
3645 .expect_err("a refused force must be an error, not a silent fallback");
3646 assert!(
3647 err.to_string().contains("403"),
3648 "propagated error must reflect the status, got: {err}"
3649 );
3650 assert!(warned, "the refusal must be printed exactly once");
3651
3652 let first = rx
3653 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3654 .expect("no first request captured");
3655 assert!(
3656 first.contains(&format!("/projects/{pid}/stream")),
3657 "first request must hit the project-scoped endpoint, got: {first}"
3658 );
3659 assert!(
3660 first
3661 .to_lowercase()
3662 .contains("x-tracevault-project-attribution: explicit"),
3663 "the refused send must have DECLARED explicit — this is the mode \
3664 `refused_error` is handed: {first}"
3665 );
3666
3667 assert!(
3668 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3669 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3670 );
3671 }
3672
3673 #[tokio::test]
3682 async fn send_stream_event_project_only_omits_repo_id() {
3683 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3684 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3685 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3686
3687 let resp = ok_stream_response();
3688 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3689 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3690 let req = sample_stream_event_request();
3691 let pid = uuid::Uuid::from_u128(11);
3692
3693 let mut warned = false;
3694 let got = send_stream_event(
3695 &client,
3696 &Attribution::ProjectOnly { project_id: pid },
3697 attribution_force(None),
3698 &req,
3699 &mut warned,
3700 )
3701 .await
3702 .expect("a repo-less project send must succeed");
3703 assert_eq!(got.status, "accepted");
3704
3705 let line = rx
3706 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3707 .expect("no request captured");
3708 assert!(
3709 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3710 "expected a bare project path with no query string, got: {line}"
3711 );
3712 assert!(
3713 line.to_lowercase()
3714 .contains("x-tracevault-project-attribution: derived"),
3715 "with no forced binding, the header must declare `derived`, got: {line}"
3716 );
3717 assert!(
3718 !warned,
3719 "a repo-less send has no fallback and must not warn about one"
3720 );
3721 }
3722
3723 #[tokio::test]
3730 async fn send_stream_event_project_only_buffers_on_scoping_4xx() {
3731 let body = "no such project";
3732 let resp_404 = format!(
3733 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3734 body.len(),
3735 body
3736 );
3737 let (base, rx) = spawn_n_capturing_requests(vec![
3744 Box::leak(resp_404.clone().into_boxed_str()),
3745 Box::leak(resp_404.into_boxed_str()),
3746 ]);
3747 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3748 let req = sample_stream_event_request();
3749 let pid = uuid::Uuid::from_u128(12);
3750
3751 let mut warned = false;
3752 let err = send_stream_event(
3753 &client,
3754 &Attribution::ProjectOnly { project_id: pid },
3755 attribution_force(None),
3756 &req,
3757 &mut warned,
3758 )
3759 .await
3760 .expect_err("a refused repo-less send must propagate so the caller buffers it");
3761 assert_eq!(
3762 deterministic_client_error_kind(err.as_ref()),
3763 Some(ClientErrorKind::Scoping),
3764 "the original 404 must propagate unchanged, got: {err}"
3765 );
3766 assert!(warned, "the refusal is printed (once per invocation)");
3767
3768 let first = rx
3769 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3770 .expect("no request captured");
3771 assert!(
3772 first.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3773 "must hit the bare project-scoped endpoint, got: {first}"
3774 );
3775 assert!(
3776 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3777 "a repo-less send must make exactly one request — no fallback exists"
3778 );
3779 }
3780
3781 #[test]
3785 fn refused_project_only_error_wording() {
3786 let pid = uuid::Uuid::from_u128(0x55);
3787 let scoping =
3788 refused_project_only_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3789 assert!(scoping.starts_with("tracevault: error:"), "{scoping}");
3790 assert!(scoping.contains(&pid.to_string()), "{scoping}");
3791 assert!(scoping.contains("queued"), "{scoping}");
3792 assert!(!scoping.contains("DROPPED"), "{scoping}");
3793 assert!(!scoping.contains("this repo"), "{scoping}");
3794 assert!(scoping.contains("tracevault repo switch"), "{scoping}");
3795
3796 let forbidden = refused_project_only_error(
3797 pid,
3798 &ClientErrorKind::Forbidden,
3799 AttributionForce::default(),
3800 );
3801 assert!(forbidden.contains("(403)"), "{forbidden}");
3802 assert!(forbidden.contains("queued"), "{forbidden}");
3803 assert!(!forbidden.contains("FORCE"), "derived send: {forbidden}");
3804
3805 let forced = AttributionForce {
3806 env: true,
3807 binding: false,
3808 };
3809 let explicit = refused_project_only_error(pid, &ClientErrorKind::Forbidden, forced);
3810 assert!(
3811 explicit.contains("FORCE itself"),
3812 "an explicit 403 must name the force, like the repo-scoped line: {explicit}"
3813 );
3814 assert!(
3815 !refused_project_only_error(pid, &ClientErrorKind::Scoping, forced)
3816 .contains("FORCE itself"),
3817 "a Scoping refusal never ran the force gate"
3818 );
3819 }
3820
3821 #[test]
3824 fn recording_line_names_each_attribution_shape() {
3825 let pid = uuid::Uuid::from_u128(0x99);
3826 let repo = "11111111-1111-1111-1111-111111111111".to_string();
3827 let only = recording_line(Some(&Attribution::ProjectOnly { project_id: pid }));
3828 assert!(only.starts_with("recording: project "), "{only}");
3829 assert!(
3830 only.contains(&pid.to_string()) && only.contains("no repo"),
3831 "{only}"
3832 );
3833 let both = recording_line(Some(&Attribution::Repo {
3834 repo_id: repo.clone(),
3835 project: Some(pid),
3836 }));
3837 assert!(
3838 both.contains(&repo) && both.contains(&pid.to_string()),
3839 "{both}"
3840 );
3841 let deduced = recording_line(Some(&Attribution::Repo {
3842 repo_id: repo.clone(),
3843 project: None,
3844 }));
3845 assert!(
3846 deduced.contains(&repo) && deduced.contains("deduces"),
3847 "{deduced}"
3848 );
3849 let none = recording_line(None);
3850 assert!(none.starts_with("recording: nothing"), "{none}");
3851 }
3852
3853 fn repo_binding(id: &str) -> crate::session_state::RepoBinding {
3854 crate::session_state::RepoBinding {
3855 repo_id: id.into(),
3856 git_url: None,
3857 remote_id: None,
3858 codebase_name: None,
3859 updated_at: "t".into(),
3860 }
3861 }
3862
3863 fn inferring_session(
3865 pid: uuid::Uuid,
3866 checkout: &str,
3867 repo: &str,
3868 ) -> crate::session_state::SessionState {
3869 let mut state = crate::session_state::SessionState {
3870 active_project: Some(crate::session_state::ProjectBinding {
3871 project_id: pid.to_string(),
3872 project_name: "p".into(),
3873 updated_at: "t".into(),
3874 forced_until: None,
3875 }),
3876 ..Default::default()
3877 };
3878 state.inferred_repos.insert(
3879 checkout.into(),
3880 crate::session_state::InferredRepo {
3881 project_id: pid.to_string(),
3882 retry_after: None,
3883 repo: Some(repo_binding(repo)),
3884 },
3885 );
3886 state
3887 }
3888
3889 #[test]
3892 fn attribution_with_inference_never_overrides_a_binding() {
3893 let pid = uuid::Uuid::from_u128(0x1258);
3894 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3895 let inferred = repo_binding("22222222-2222-2222-2222-222222222222");
3896 let repo = |id: &str| Attribution::Repo {
3897 repo_id: id.into(),
3898 project: Some(pid),
3899 };
3900
3901 assert_eq!(
3902 attribution_with_inference(None, Some(pid), Some(&inferred)),
3903 Some(repo(&inferred.repo_id))
3904 );
3905 assert_eq!(
3906 attribution_with_inference(Some(&bound), Some(pid), Some(&inferred)),
3907 Some(repo(&bound.repo_id))
3908 );
3909 let corrupt = repo_binding("not-a-uuid");
3912 assert_eq!(
3913 attribution_with_inference(Some(&corrupt), Some(pid), Some(&inferred)),
3914 Some(Attribution::ProjectOnly { project_id: pid })
3915 );
3916 assert_eq!(
3918 attribution_with_inference(None, None, Some(&inferred)),
3919 None
3920 );
3921 assert_eq!(
3922 attribution_with_inference(None, Some(pid), Some(&corrupt)),
3923 Some(Attribution::ProjectOnly { project_id: pid })
3924 );
3925 }
3926
3927 #[test]
3930 fn recording_attribution_labels_an_inferred_repo() {
3931 let pid = uuid::Uuid::from_u128(0x1258);
3932 let repo = "22222222-2222-2222-2222-222222222222";
3933 let state = inferring_session(pid, "/umbrella/child", repo);
3934
3935 let here = recording_attribution_for(&state, "/umbrella/child", None, None, None);
3936 assert_eq!(
3937 here.attribution,
3938 Some(Attribution::Repo {
3939 repo_id: repo.into(),
3940 project: Some(pid)
3941 })
3942 );
3943 assert_eq!(here.inferred_from.as_deref(), Some("/umbrella/child"));
3944 let line = recording_line_for(&here);
3945 assert!(
3946 line.contains(repo) && line.contains("inferred from the checkout /umbrella/child"),
3947 "{line}"
3948 );
3949
3950 let elsewhere = recording_attribution_for(&state, "/umbrella", None, None, None);
3951 assert_eq!(
3952 elsewhere.attribution,
3953 Some(Attribution::ProjectOnly { project_id: pid })
3954 );
3955 assert_eq!(elsewhere.inferred_from, None);
3956 assert_eq!(
3957 recording_line_for(&elsewhere),
3958 recording_line(elsewhere.attribution.as_ref())
3959 );
3960
3961 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
3963 let explicit =
3964 recording_attribution_for(&state, "/umbrella/child", Some(bound.clone()), None, None);
3965 assert_eq!(
3966 explicit.attribution,
3967 Some(Attribution::Repo {
3968 repo_id: bound.repo_id,
3969 project: Some(pid)
3970 })
3971 );
3972 assert_eq!(explicit.inferred_from, None);
3973
3974 let mut from_config = state.clone();
3977 from_config.active_project = None;
3978 let workspace = crate::session_state::ProjectBinding {
3979 project_id: pid.to_string(),
3980 project_name: String::new(),
3981 updated_at: String::new(),
3982 forced_until: None,
3983 };
3984 let via_config =
3985 recording_attribution_for(&from_config, "/umbrella/child", None, None, Some(workspace));
3986 assert_eq!(via_config.inferred_from.as_deref(), Some("/umbrella/child"));
3987 }
3988
3989 #[test]
3990 fn adopt_queue_puts_the_older_queue_first_and_removes_it() {
3991 let dir = tempfile::tempdir().unwrap();
3992 let from = dir.path().join("pending-project-x.jsonl");
3993 let into = dir.path().join("pending-r.jsonl");
3994 std::fs::write(&from, "a1\na2").unwrap(); std::fs::write(&into, "r1\n").unwrap();
3996 adopt_queue(&from, &into).unwrap();
3997 assert!(!from.exists());
3998 assert_eq!(drain_pending(&into).unwrap(), vec!["a1", "a2", "r1"]);
3999 assert!(
4000 !dir.path().join("pending-r.jsonl.adopting").exists(),
4001 "no temp file left behind"
4002 );
4003 }
4004
4005 #[test]
4006 fn adopt_queue_without_a_source_is_a_no_op() {
4007 let dir = tempfile::tempdir().unwrap();
4008 let into = dir.path().join("pending-r.jsonl");
4009 std::fs::write(&into, "r1\n").unwrap();
4010 adopt_queue(&dir.path().join("absent.jsonl"), &into).unwrap();
4011 assert_eq!(drain_pending(&into).unwrap(), vec!["r1"]);
4012 }
4013
4014 #[test]
4017 fn adopt_queue_failure_leaves_the_source_intact() {
4018 let dir = tempfile::tempdir().unwrap();
4019 let from = dir.path().join("pending-project-x.jsonl");
4020 let into = dir.path().join("pending-r.jsonl");
4021 std::fs::write(&from, "a1\n").unwrap();
4022 std::fs::create_dir(&into).unwrap(); assert!(adopt_queue(&from, &into).is_err());
4024 assert_eq!(std::fs::read_to_string(&from).unwrap(), "a1\n");
4025 }
4026
4027 #[test]
4028 fn adopted_project_queue_only_for_the_same_project() {
4029 let dir = Path::new("/tmp/sess");
4030 let pid = uuid::Uuid::from_u128(0x77);
4031 let repo_id = "11111111-1111-1111-1111-111111111111".to_string();
4032 assert_eq!(
4033 adopted_project_queue(
4034 dir,
4035 &Attribution::Repo {
4036 repo_id: repo_id.clone(),
4037 project: Some(pid),
4038 }
4039 ),
4040 Some(dir.join(format!("pending-project-{pid}.jsonl")))
4041 );
4042 assert_eq!(
4043 adopted_project_queue(
4044 dir,
4045 &Attribution::Repo {
4046 repo_id,
4047 project: None,
4048 }
4049 ),
4050 None,
4051 "with no declared project the server deduces one; adopting would re-attribute"
4052 );
4053 assert_eq!(
4054 adopted_project_queue(dir, &Attribution::ProjectOnly { project_id: pid }),
4055 None,
4056 "a project-only target already drains its own queue"
4057 );
4058 }
4059
4060 #[tokio::test]
4064 async fn send_stream_event_project_only_buffers_on_403() {
4065 let body = "forbidden";
4066 let resp_403 = format!(
4067 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4068 body.len(),
4069 body
4070 );
4071 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
4072 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4073 let req = sample_stream_event_request();
4074
4075 let mut warned = false;
4076 let err = send_stream_event(
4077 &client,
4078 &Attribution::ProjectOnly {
4079 project_id: uuid::Uuid::from_u128(13),
4080 },
4081 attribution_force(None),
4082 &req,
4083 &mut warned,
4084 )
4085 .await
4086 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
4087 assert!(
4088 err.to_string().contains("403"),
4089 "propagated error must reflect the status, got: {err}"
4090 );
4091 }
4092
4093 #[tokio::test]
4098 async fn send_stream_event_does_not_fall_back_on_transient_503() {
4099 let body_503 = "internal error";
4100 let resp_503 = format!(
4101 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4102 body_503.len(),
4103 body_503
4104 );
4105 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
4106 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4107 let req = sample_stream_event_request();
4108 let pid = uuid::Uuid::from_u128(7);
4109
4110 let mut warned = false;
4111 let err = send_stream_event(
4112 &client,
4113 &Attribution::Repo {
4114 repo_id: "11111111-1111-1111-1111-111111111111".into(),
4115 project: Some(pid),
4116 },
4117 attribution_force(None),
4118 &req,
4119 &mut warned,
4120 )
4121 .await
4122 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
4123 assert!(
4124 err.to_string().contains("503"),
4125 "propagated error must reflect the transient status, got: {err}"
4126 );
4127 assert!(
4128 deterministic_client_error_kind(err.as_ref()).is_none(),
4129 "a 503 must not be classified as a deterministic client error"
4130 );
4131
4132 let first = rx
4133 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4134 .expect("no request captured");
4135 assert!(
4136 first.contains(&format!("/projects/{pid}/stream")),
4137 "must hit the project-scoped endpoint, got: {first}"
4138 );
4139
4140 assert!(
4147 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
4148 "no second (fallback) request should have been sent for a transient error"
4149 );
4150 }
4151
4152 #[test]
4156 fn a_403_is_classified_apart_from_the_scoping_statuses() {
4157 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
4158 assert_eq!(
4159 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
4160 Some(ClientErrorKind::Forbidden)
4161 );
4162 for scoping in [
4163 "Stream failed (400 Bad Request): {}",
4164 "Stream failed (404 Not Found): {}",
4165 "Stream failed (409 Conflict): {}",
4166 ] {
4167 assert_eq!(
4168 deterministic_client_error_kind(err(scoping).as_ref()),
4169 Some(ClientErrorKind::Scoping),
4170 "{scoping}"
4171 );
4172 }
4173 for transient in [
4176 "Stream failed (401 Unauthorized): {}",
4177 "Stream failed (503 Service Unavailable): {}",
4178 "error sending request for url (http://x/stream)",
4179 ] {
4180 assert_eq!(
4181 deterministic_client_error_kind(err(transient).as_ref()),
4182 None,
4183 "{transient}"
4184 );
4185 }
4186 }
4187
4188 #[test]
4193 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
4194 let pid = uuid::Uuid::from_u128(7);
4195
4196 let forbidden = refused_error(
4197 pid,
4198 &ClientErrorKind::Forbidden,
4199 AttributionForce::default(),
4200 );
4201 assert!(forbidden.contains("403"), "{forbidden}");
4202 assert!(
4203 forbidden.contains("no `tracevault` grant in Control Plane"),
4204 "must offer the missing-role explanation: {forbidden}"
4205 );
4206 assert!(
4207 forbidden.contains("no `Operator` role on it"),
4208 "must still offer the project explanation: {forbidden}"
4209 );
4210 assert!(
4211 forbidden.starts_with("tracevault: error:"),
4212 "a refusal is an error, not a warning: {forbidden}"
4213 );
4214 assert!(forbidden.contains(&pid.to_string()));
4215
4216 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
4219 assert!(scoping.contains("project switch"), "{scoping}");
4220 assert!(
4221 !scoping.contains("`tracevault` grant"),
4222 "the scoping case must not mention the `tracevault` grant: {scoping}"
4223 );
4224
4225 for s in [&forbidden, &scoping] {
4226 assert!(s.contains("--user"), "must name the --user fix: {s}");
4229 assert!(
4230 s.contains("user_project.toml"),
4231 "must name the machine-wide default's file: {s}"
4232 );
4233 assert!(
4234 !s.contains("repo deduction"),
4235 "must never describe re-attribution to another project: {s}"
4236 );
4237 assert!(
4238 !s.contains("Attributing via"),
4239 "must never claim the event was re-attributed: {s}"
4240 );
4241 }
4242 }
4243
4244 #[test]
4255 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
4256 let pid = uuid::Uuid::from_u128(7);
4257
4258 let explicit = refused_error(
4259 pid,
4260 &ClientErrorKind::Forbidden,
4261 AttributionForce {
4262 env: false,
4263 binding: true,
4264 },
4265 );
4266 assert!(
4267 explicit.contains("FORCE"),
4268 "the refusal of the force itself must be named: {explicit}"
4269 );
4270 assert!(
4271 explicit.contains("Operator"),
4272 "must name the grant forcing requires: {explicit}"
4273 );
4274 assert!(
4275 explicit.contains("Control Plane"),
4276 "must name the identity forcing requires: {explicit}"
4277 );
4278 assert!(
4282 explicit.contains("`tracevault` grant")
4283 && explicit.contains("no `Operator` role on it"),
4284 "the membership causes must still be named: {explicit}"
4285 );
4286 assert!(
4289 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
4290 "must never claim the event was re-attributed: {explicit}"
4291 );
4292
4293 let derived = refused_error(
4298 pid,
4299 &ClientErrorKind::Forbidden,
4300 AttributionForce::default(),
4301 );
4302 assert!(
4303 !derived.contains("FORCE"),
4304 "a `derived` send never forced anything: {derived}"
4305 );
4306 }
4307
4308 #[test]
4313 fn an_explicit_scoping_failure_does_not_blame_the_force() {
4314 let pid = uuid::Uuid::from_u128(7);
4315 let scoping = refused_error(
4316 pid,
4317 &ClientErrorKind::Scoping,
4318 AttributionForce {
4319 env: true,
4320 binding: true,
4321 },
4322 );
4323 assert!(!scoping.contains("FORCE"), "{scoping}");
4324 assert_eq!(
4325 scoping,
4326 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
4327 "the scoping wording does not depend on the mode"
4328 );
4329 }
4330
4331 #[test]
4351 fn the_403_remediation_names_the_force_source_actually_in_effect() {
4352 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
4353 let mut _guard = crate::test_helpers::EnvVarGuard::new();
4354 let pid = uuid::Uuid::from_u128(7);
4355 let live = forced_binding(Some(
4356 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
4357 ));
4358 let never_forced = forced_binding(None);
4359
4360 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4364 let env_only = refused_error(
4365 pid,
4366 &ClientErrorKind::Forbidden,
4367 attribution_force(Some(&never_forced)),
4368 );
4369 assert!(
4370 env_only.contains("FORCE"),
4371 "an env-sourced force is still a force: {env_only}"
4372 );
4373 assert!(
4374 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
4375 "must name the variable that is doing the forcing: {env_only}"
4376 );
4377 assert!(
4378 !env_only.contains("--project-attribution"),
4379 "must NOT tell the operator to drop a flag that would change \
4380 nothing here — this is the bug: {env_only}"
4381 );
4382
4383 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
4387 let binding_only = refused_error(
4388 pid,
4389 &ClientErrorKind::Forbidden,
4390 attribution_force(Some(&live)),
4391 );
4392 assert!(
4393 binding_only.contains("--project-attribution"),
4394 "a persisted force IS cleared by switching without the flag: {binding_only}"
4395 );
4396 assert!(
4397 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
4398 "must not send the operator after an unset variable: {binding_only}"
4399 );
4400
4401 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4405 let both = refused_error(
4406 pid,
4407 &ClientErrorKind::Forbidden,
4408 attribution_force(Some(&live)),
4409 );
4410 assert!(
4411 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4412 && both.contains("--project-attribution"),
4413 "both sources are in effect and both must be named: {both}"
4414 );
4415 assert!(
4416 both.contains("BOTH"),
4417 "must say that removing only one is not enough: {both}"
4418 );
4419 }
4420
4421 #[test]
4426 fn no_force_means_no_remediation_clause() {
4427 let pid = uuid::Uuid::from_u128(7);
4428 let none = refused_error(
4429 pid,
4430 &ClientErrorKind::Forbidden,
4431 AttributionForce::default(),
4432 );
4433 assert!(
4434 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4435 && !none.contains("--project-attribution"),
4436 "a derived send has no force to remove: {none}"
4437 );
4438 }
4439
4440 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
4445 let path = dir.join("transcript.jsonl");
4446 let mut body = String::new();
4447 for i in 0..n {
4448 let line = serde_json::json!({
4449 "type": "user",
4450 "n": i,
4451 "message": {"content": "x".repeat(line_bytes)},
4452 });
4453 body.push_str(&line.to_string());
4454 body.push('\n');
4455 }
4456 fs::write(&path, body).unwrap();
4457 path
4458 }
4459
4460 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
4462 StreamEventRequest {
4463 tool_name: Some("Bash".into()),
4464 tool_use_id: Some("toolu_1".into()),
4465 tool_input: Some(serde_json::json!({"command": "ls"})),
4466 event_uuid: Some(uuid::Uuid::now_v7()),
4467 transcript_lines: Some(lines),
4468 transcript_offset: Some(offset),
4469 ..sample_stream_event_request()
4470 }
4471 }
4472
4473 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
4474 part.transcript_lines.clone().unwrap_or_default()
4475 }
4476
4477 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
4480 parts
4481 .iter()
4482 .flat_map(|p| {
4483 let offset = p.transcript_offset.unwrap();
4484 part_lines(p)
4485 .into_iter()
4486 .enumerate()
4487 .map(move |(i, l)| (offset + i as i64, l))
4488 })
4489 .collect()
4490 }
4491
4492 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
4494 (0..n)
4495 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
4496 .collect()
4497 }
4498
4499 #[test]
4500 fn split_leaves_a_request_under_the_cap_unchanged() {
4501 let req = event_with_lines(big_lines(3, 100), 0);
4502
4503 let parts = split_into_parts(req.clone());
4504
4505 assert_eq!(parts.len(), 1);
4506 assert_eq!(
4507 serde_json::to_value(&parts[0]).unwrap(),
4508 serde_json::to_value(&req).unwrap()
4509 );
4510 }
4511
4512 #[test]
4516 fn split_carries_every_line_of_a_batch_over_the_cap() {
4517 let dir = tempfile::tempdir().unwrap();
4518 let transcript = write_transcript(dir.path(), 300, 5_000);
4520 let (lines, start, _) =
4521 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
4522 let req = event_with_lines(lines.clone(), start);
4523 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
4524
4525 let parts = split_into_parts(req.clone());
4526
4527 assert!(parts.len() >= 3, "got {} parts", parts.len());
4528 for part in &parts {
4529 assert!(
4530 part.serialized_len() <= MAX_REQUEST_BYTES,
4531 "part of {} bytes exceeds the cap",
4532 part.serialized_len()
4533 );
4534 }
4535 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4536 assert_eq!(sent, lines, "every line, once, in order");
4537
4538 let (event, transcript_parts) = parts.split_last().unwrap();
4540 assert_eq!(event.event_type, StreamEventType::ToolUse);
4541 assert_eq!(event.event_uuid, req.event_uuid);
4542 assert_eq!(event.tool_input, req.tool_input);
4543 for part in transcript_parts {
4544 assert_eq!(part.event_type, StreamEventType::Transcript);
4545 assert!(part.event_uuid.is_none());
4546 assert!(part.tool_input.is_none());
4547 assert!(part.tool_name.is_none());
4548 }
4549 assert!(
4550 !part_lines(event).is_empty(),
4551 "the event keeps the lines that fit beside it"
4552 );
4553 }
4554
4555 #[test]
4559 fn split_keeps_each_lines_unsplit_chunk_index() {
4560 let lines = big_lines(300, 5_000);
4561 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
4562
4563 let expected: Vec<_> = lines
4564 .into_iter()
4565 .enumerate()
4566 .map(|(i, l)| (1_000 + i as i64, l))
4567 .collect();
4568 assert_eq!(chunk_indexes(&parts), expected);
4569 }
4570
4571 #[test]
4576 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
4577 let lines = big_lines(10, 200_000);
4578 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
4579 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
4580
4581 for (index, line) in &short {
4582 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
4583 assert_eq!(in_long.0, *index, "line {line} indexed differently");
4584 }
4585 }
4586
4587 #[test]
4590 fn split_sends_a_single_oversized_line_alone() {
4591 let lines = vec![
4592 serde_json::json!({"n": 0}),
4593 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
4594 serde_json::json!({"n": 2}),
4595 ];
4596
4597 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
4598
4599 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4600 assert_eq!(sent, lines);
4601 let big = parts
4602 .iter()
4603 .find(|p| part_lines(p).contains(&lines[1]))
4604 .unwrap();
4605 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
4606 assert_eq!(big.transcript_offset, Some(1));
4607 }
4608
4609 fn far_deadline() -> std::time::Instant {
4610 std::time::Instant::now() + Duration::from_secs(60)
4611 }
4612
4613 fn captured_body(captured: &str) -> StreamEventRequest {
4614 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
4615 serde_json::from_str(body).expect("request body is a StreamEventRequest")
4616 }
4617
4618 #[tokio::test]
4620 async fn deliver_parts_sends_every_part() {
4621 let dir = tempfile::tempdir().unwrap();
4622 let pending_path = dir.path().join("pending.jsonl");
4623 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4624 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4625 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4626
4627 let all_accepted = deliver_parts(
4628 &client,
4629 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4630 AttributionForce::default(),
4631 parts.clone(),
4632 &pending_path,
4633 false,
4634 far_deadline(),
4635 &mut false,
4636 )
4637 .await
4638 .unwrap();
4639
4640 assert!(all_accepted);
4641 for part in &parts {
4642 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4643 assert_eq!(got.transcript_offset, part.transcript_offset);
4644 assert_eq!(got.transcript_lines, part.transcript_lines);
4645 }
4646 assert!(drain_pending(&pending_path).unwrap().is_empty());
4647 }
4648
4649 #[tokio::test]
4653 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4654 let dir = tempfile::tempdir().unwrap();
4655 let pending_path = dir.path().join("pending.jsonl");
4656 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4657 assert!(parts.len() >= 3);
4658 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4659 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4660 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4661
4662 let all_accepted = deliver_parts(
4663 &client,
4664 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4665 AttributionForce::default(),
4666 parts.clone(),
4667 &pending_path,
4668 false,
4669 far_deadline(),
4670 &mut false,
4671 )
4672 .await
4673 .unwrap();
4674
4675 assert!(!all_accepted);
4676 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4677 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4678 assert!(
4679 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4680 "nothing is sent after the first failure"
4681 );
4682 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4683 .unwrap()
4684 .iter()
4685 .map(|j| serde_json::from_str(j).unwrap())
4686 .collect();
4687 assert_eq!(queued.len(), parts.len() - 1);
4688 for (q, part) in queued.iter().zip(&parts[1..]) {
4689 assert_eq!(q.transcript_offset, part.transcript_offset);
4690 assert_eq!(q.transcript_lines, part.transcript_lines);
4691 }
4692 }
4693
4694 #[tokio::test]
4697 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4698 let dir = tempfile::tempdir().unwrap();
4699 let pending_path = dir.path().join("pending.jsonl");
4700 let parts = split_into_parts(sample_stream_event_request());
4701 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4702
4703 let all_accepted = deliver_parts(
4704 &client,
4705 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4706 AttributionForce::default(),
4707 parts,
4708 &pending_path,
4709 true,
4710 far_deadline(),
4711 &mut false,
4712 )
4713 .await
4714 .unwrap();
4715
4716 assert!(!all_accepted);
4717 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4718 }
4719
4720 #[tokio::test]
4723 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
4724 let dir = tempfile::tempdir().unwrap();
4725 let pending_path = dir.path().join("pending.jsonl");
4726 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4727 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4728 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4729
4730 let all_accepted = deliver_parts(
4731 &client,
4732 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4733 AttributionForce::default(),
4734 parts.clone(),
4735 &pending_path,
4736 false,
4737 std::time::Instant::now(),
4738 &mut false,
4739 )
4740 .await
4741 .unwrap();
4742
4743 assert!(!all_accepted);
4744 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
4745 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
4746 }
4747
4748 #[tokio::test]
4753 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
4754 let dir = tempfile::tempdir().unwrap();
4755 let pending_path = dir.path().join("pending.jsonl");
4756 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
4757 let base = format!("http://{}", listener.local_addr().unwrap());
4758 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4760 let started = Instant::now();
4761
4762 let all_accepted = deliver_parts(
4763 &client,
4764 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4765 AttributionForce::default(),
4766 vec![event_with_lines(big_lines(1, 10), 0)],
4767 &pending_path,
4768 false,
4769 started + Duration::from_millis(100),
4770 &mut false,
4771 )
4772 .await
4773 .unwrap();
4774
4775 assert!(!all_accepted);
4776 assert!(started.elapsed() < Duration::from_secs(10));
4777 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
4778 drop(listener);
4779 }
4780
4781 const PARENT_SESSION: &str = "parent-session";
4784 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
4785
4786 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
4790 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
4791 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4792 let subagents = dir.join(PARENT_SESSION).join("subagents");
4793 fs::create_dir_all(&subagents).unwrap();
4794 let session_dir = dir.join("tv-session");
4795 fs::create_dir_all(&session_dir).unwrap();
4796 (main, subagents, session_dir)
4797 }
4798
4799 fn subagent_line(agent: &str, n: usize) -> String {
4800 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
4801 }
4802
4803 fn append_raw(path: &Path, text: &str) {
4804 let mut f = fs::OpenOptions::new()
4805 .create(true)
4806 .append(true)
4807 .open(path)
4808 .unwrap();
4809 f.write_all(text.as_bytes()).unwrap();
4810 }
4811
4812 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
4813 let path = subagents.join(format!("agent-{agent}.jsonl"));
4814 for n in ns {
4815 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
4816 }
4817 }
4818
4819 async fn sweep(
4823 responses: Vec<String>,
4824 main: &Path,
4825 session_dir: &Path,
4826 pending_path: &Path,
4827 ) -> Vec<StreamEventRequest> {
4828 sweep_waiting(responses, main, session_dir, pending_path, None).await
4829 }
4830
4831 async fn sweep_waiting(
4834 responses: Vec<String>,
4835 main: &Path,
4836 session_dir: &Path,
4837 pending_path: &Path,
4838 wait_for_lock: Option<Instant>,
4839 ) -> Vec<StreamEventRequest> {
4840 let expected = responses.len();
4841 let (base, rx) = crate::test_helpers::spawn_seq(responses);
4842 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4843 let event = StreamEventRequest {
4844 session_id: PARENT_SESSION.into(),
4845 ..sample_stream_event_request()
4846 };
4847 deliver_subagent_transcripts(
4848 &client,
4849 &repo_attr(SUBAGENT_REPO),
4850 AttributionForce::default(),
4851 &transcript_template(&event),
4852 main,
4853 session_dir,
4854 pending_path,
4855 false,
4856 Instant::now() + Duration::from_secs(60),
4857 wait_for_lock,
4858 &mut false,
4859 )
4860 .await
4861 .unwrap();
4862 (0..expected)
4863 .map(|_| {
4864 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4865 assert!(
4866 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4867 "{captured}"
4868 );
4869 let body = captured.splitn(3, " | ").nth(2).unwrap();
4870 serde_json::from_str(body).unwrap()
4871 })
4872 .collect()
4873 }
4874
4875 fn agent_of(line: &serde_json::Value) -> &str {
4876 line["agentId"].as_str().unwrap()
4877 }
4878
4879 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4883 for req in reqs {
4884 assert_eq!(req.event_type, StreamEventType::Transcript);
4885 assert_eq!(req.session_id, PARENT_SESSION);
4886 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4887 let lines = part_lines(req);
4888 let agent = agent_of(&lines[0]);
4889 assert!(
4890 lines.iter().all(|l| agent_of(l) == agent),
4891 "a request mixes subagent files: {lines:?}"
4892 );
4893 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4894 let first = file.find(&lines[0].to_string()).unwrap() as i64;
4895 assert_eq!(req.transcript_offset, Some(first));
4896 }
4897 }
4898
4899 #[tokio::test]
4900 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4901 let dir = tempfile::tempdir().unwrap();
4902 let (main, subagents, session_dir) = claude_session(dir.path());
4903 let pending = session_dir.join("pending.jsonl");
4904 let ok = ok_stream_response;
4905 let mut all = Vec::new();
4906
4907 append_subagent_lines(&subagents, "a1", 0..2);
4909 append_subagent_lines(&subagents, "b2", 0..1);
4910 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4911 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4912 assert_eq!(reqs.len(), 2);
4913 all.extend(reqs);
4914
4915 append_subagent_lines(&subagents, "a1", 2..3);
4917 append_subagent_lines(&subagents, "b2", 1..2);
4918 let partial = subagent_line("b2", 2);
4919 let (head, tail) = partial.split_at(10);
4920 append_raw(&subagents.join("agent-b2.jsonl"), head);
4921 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4922 assert_eq!(reqs.len(), 2);
4923 all.extend(reqs);
4924
4925 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4927 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4928 assert_eq!(reqs.len(), 1);
4929 all.extend(reqs);
4930
4931 assert!(sweep(vec![], &main, &session_dir, &pending)
4933 .await
4934 .is_empty());
4935 assert!(!pending.exists(), "nothing may have failed and been queued");
4936
4937 assert_one_file_per_request(&subagents, &all);
4938 let mut sent: Vec<(String, u64)> = all
4939 .iter()
4940 .flat_map(part_lines)
4941 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4942 .collect();
4943 sent.sort();
4944 let expected: Vec<(String, u64)> = [
4945 ("a1", 0),
4946 ("a1", 1),
4947 ("a1", 2),
4948 ("b2", 0),
4949 ("b2", 1),
4950 ("b2", 2),
4951 ]
4952 .into_iter()
4953 .map(|(a, n)| (a.to_string(), n))
4954 .collect();
4955 assert_eq!(sent, expected, "each line exactly once");
4956 }
4957
4958 #[tokio::test]
4959 async fn a_session_without_subagents_sends_nothing_extra() {
4960 let dir = tempfile::tempdir().unwrap();
4961 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4962 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4963 let session_dir = dir.path().join("tv-session");
4964 fs::create_dir_all(&session_dir).unwrap();
4965 let pending = session_dir.join("pending.jsonl");
4966
4967 assert!(sweep(vec![], &main, &session_dir, &pending)
4968 .await
4969 .is_empty());
4970 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4971 }
4972
4973 #[tokio::test]
4978 async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4979 let dir = tempfile::tempdir().unwrap();
4980 let (main, subagents, session_dir) = claude_session(dir.path());
4981 let pending = session_dir.join("pending.jsonl");
4982 append_subagent_lines(&subagents, "a1", 0..2);
4983 append_subagent_lines(&subagents, "b2", 0..1);
4984
4985 let error =
4986 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4987 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4988 assert_eq!(failed.len(), 1);
4989 let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4990 .unwrap()
4991 .iter()
4992 .map(|j| serde_json::from_str(j).unwrap())
4993 .collect();
4994 assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4995
4996 let resent = sweep(
4997 vec![ok_stream_response(), ok_stream_response()],
4998 &main,
4999 &session_dir,
5000 &pending,
5001 )
5002 .await;
5003 assert_one_file_per_request(&subagents, &resent);
5004 let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
5005 assert_eq!(
5006 resent.iter().map(key).collect::<Vec<_>>(),
5007 queued.iter().map(key).collect::<Vec<_>>()
5008 );
5009 assert!(sweep(vec![], &main, &session_dir, &pending)
5010 .await
5011 .is_empty());
5012 }
5013
5014 #[tokio::test]
5017 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
5018 let dir = tempfile::tempdir().unwrap();
5019 let (main, subagents, session_dir) = claude_session(dir.path());
5020 let pending = session_dir.join("pending.jsonl");
5021 append_subagent_lines(&subagents, "a1", 0..2);
5022 append_subagent_lines(&subagents, "b2", 0..1);
5023 let a1_offset =
5024 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5025 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5026
5027 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5028 assert_eq!(reqs.len(), 1);
5029 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
5030 assert!(!a1_offset.exists());
5031
5032 drop(held);
5033 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5034 assert_eq!(reqs.len(), 1);
5035 assert_eq!(part_lines(&reqs[0]).len(), 2);
5036 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
5037 }
5038
5039 #[tokio::test]
5042 async fn a_final_hook_waits_for_a_busy_subagent_file() {
5043 let dir = tempfile::tempdir().unwrap();
5044 let (main, subagents, session_dir) = claude_session(dir.path());
5045 let pending = session_dir.join("pending.jsonl");
5046 append_subagent_lines(&subagents, "a1", 0..2);
5047 let a1_offset =
5048 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5049 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5050 let release = thread::spawn(move || {
5051 thread::sleep(Duration::from_millis(300));
5052 drop(held);
5053 });
5054
5055 let reqs = sweep_waiting(
5056 vec![ok_stream_response()],
5057 &main,
5058 &session_dir,
5059 &pending,
5060 Some(Instant::now() + Duration::from_secs(10)),
5061 )
5062 .await;
5063 release.join().unwrap();
5064 assert_eq!(reqs.len(), 1);
5065 assert_eq!(part_lines(&reqs[0]).len(), 2);
5066 }
5067
5068 #[tokio::test]
5072 async fn a_large_subagent_batch_is_split_within_its_file() {
5073 let dir = tempfile::tempdir().unwrap();
5074 let (main, subagents, session_dir) = claude_session(dir.path());
5075 let pending = session_dir.join("pending.jsonl");
5076 let big = subagents.join("agent-a1.jsonl");
5077 for n in 0..300 {
5078 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
5079 append_raw(&big, &format!("{line}\n"));
5080 }
5081 append_subagent_lines(&subagents, "b2", 0..1);
5082
5083 let scratch = dir.path().join("scratch-offset");
5084 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
5085 let unsplit = StreamEventRequest {
5086 transcript_lines: Some(lines.clone()),
5087 transcript_offset: Some(start),
5088 ..transcript_template(&sample_stream_event_request())
5089 };
5090 let a1_parts = split_into_parts(unsplit).len();
5091 assert!(a1_parts > 1, "the batch must exceed the cap");
5092
5093 let reqs = sweep(
5094 vec![ok_stream_response(); a1_parts + 1],
5095 &main,
5096 &session_dir,
5097 &pending,
5098 )
5099 .await;
5100 assert!(!pending.exists());
5101 let (a1, b2) = reqs.split_at(a1_parts);
5102 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
5103 assert_eq!(
5104 chunk_indexes(a1),
5105 lines
5106 .into_iter()
5107 .enumerate()
5108 .map(|(i, l)| (start + i as i64, l))
5109 .collect::<Vec<_>>()
5110 );
5111 assert_eq!(b2.len(), 1);
5112 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
5113 assert_eq!(b2[0].transcript_offset, Some(0));
5114 }
5115}