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 let batch = read_transcript_batch(transcript_path, offset_path, i64::MAX)?;
56 Ok((batch.lines, batch.start, batch.end))
57}
58
59pub const MAX_BATCH_BYTES: i64 = 4 * 1024 * 1024;
64
65#[derive(Debug, Default)]
68pub struct TranscriptBatch {
69 pub lines: Vec<serde_json::Value>,
70 pub ends: Vec<i64>,
71 pub start: i64,
72 pub end: i64,
73}
74
75impl TranscriptBatch {
76 pub fn next_offset(&self, delivered: &Delivered) -> Option<i64> {
83 if delivered.lines >= self.ends.len() {
84 return Some(self.end);
85 }
86 delivered
87 .lines
88 .checked_sub(1)
89 .and_then(|last| self.ends.get(last))
90 .copied()
91 }
92}
93
94pub fn read_transcript_batch(
97 transcript_path: &Path,
98 offset_path: &Path,
99 max_bytes: i64,
100) -> Result<TranscriptBatch, io::Error> {
101 if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
107 return Ok(TranscriptBatch::default());
108 }
109
110 let offset: i64 = if offset_path.exists() {
111 let content = fs::read_to_string(offset_path)?;
112 content
113 .trim()
114 .parse::<i64>()
115 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
116 } else {
117 0
118 };
119
120 let mut file = fs::File::open(transcript_path)?;
121 file.seek(SeekFrom::Start(offset as u64))?;
122
123 let reader = io::BufReader::new(file);
124 let mut lines = Vec::new();
125 let mut ends = Vec::new();
126 let mut bytes_read = offset;
127
128 for line_result in reader.lines() {
129 let line = line_result?;
130 bytes_read += line.len() as i64 + 1;
132 if line.trim().is_empty() {
133 continue;
134 }
135 if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
136 lines.push(value);
137 ends.push(bytes_read);
138 }
139 if bytes_read - offset >= max_bytes {
140 break;
141 }
142 }
143
144 Ok(TranscriptBatch {
145 lines,
146 ends,
147 start: offset,
148 end: bytes_read,
149 })
150}
151
152fn advance_offset(offset_path: &Path, to: i64) -> io::Result<()> {
157 let _lock = crate::pending_queue::lock(&offset_path.with_extension("advance.lock"))?;
160 let current = fs::read_to_string(offset_path)
161 .ok()
162 .and_then(|c| c.trim().parse::<i64>().ok());
163 if current.is_some_and(|c| c >= to) {
164 return Ok(());
165 }
166 crate::subagents::write_offset(offset_path, to)
167}
168
169pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
177 if transcript_path.is_empty() {
178 return Ok(());
179 }
180 record_metadata(
181 session_dir,
182 "transcript_path",
183 serde_json::Value::String(transcript_path.to_string()),
184 )
185}
186
187pub(crate) fn session_metadata(session_dir: &Path) -> serde_json::Value {
189 fs::read_to_string(session_dir.join("metadata.json"))
190 .ok()
191 .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
192 .filter(serde_json::Value::is_object)
193 .unwrap_or_else(|| serde_json::json!({}))
194}
195
196fn record_metadata(
200 session_dir: &Path,
201 key: &str,
202 value: serde_json::Value,
203) -> Result<(), io::Error> {
204 let mut meta = session_metadata(session_dir);
205 if meta.get(key) == Some(&value) {
206 return Ok(());
207 }
208 meta[key] = value;
209 let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
210 fs::write(&tmp, meta.to_string())?;
211 fs::rename(&tmp, session_dir.join("metadata.json")).inspect_err(|_| {
212 let _ = fs::remove_file(&tmp);
213 })
214}
215
216fn attribution_record(attribution: &Attribution) -> serde_json::Value {
218 match attribution {
219 Attribution::Repo { repo_id, project } => {
220 serde_json::json!({"repo_id": repo_id, "project_id": project})
221 }
222 Attribution::ProjectOnly { project_id } => {
223 serde_json::json!({"repo_id": null, "project_id": project_id})
224 }
225 }
226}
227
228pub(crate) fn catch_up_may_send(recorded: Option<&serde_json::Value>, now: &Attribution) -> bool {
236 match recorded {
237 Some(recorded) => *recorded == attribution_record(now),
238 None => matches!(now, Attribution::Repo { .. }),
239 }
240}
241
242pub fn record_inline_tool_calls(
249 session_dir: &Path,
250 records: &[serde_json::Value],
251) -> Result<(), io::Error> {
252 let lines: String = records
253 .iter()
254 .flat_map(crate::transcript::tool_call_names)
255 .map(|name| {
256 let record = serde_json::json!({
257 "type": "message",
258 "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
259 });
260 format!("{record}\n")
261 })
262 .collect();
263 if lines.is_empty() {
264 return Ok(());
265 }
266 let log_path = session_dir.join("tool_calls.jsonl");
267 OpenOptions::new()
268 .create(true)
269 .append(true)
270 .open(&log_path)?
271 .write_all(lines.as_bytes())?;
272 record_transcript_path(session_dir, &log_path.to_string_lossy())
273}
274
275pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
276 let mut file = OpenOptions::new()
277 .create(true)
278 .append(true)
279 .open(pending_path)?;
280 writeln!(file, "{json}")?;
281 Ok(())
282}
283
284pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
285 if !pending_path.exists() {
286 return Ok(vec![]);
287 }
288 let content = fs::read_to_string(pending_path)?;
289 let lines: Vec<String> = content
290 .lines()
291 .filter(|l| !l.trim().is_empty())
292 .map(String::from)
293 .collect();
294 fs::remove_file(pending_path)?;
295 Ok(lines)
296}
297
298#[derive(Debug, Clone, PartialEq, Eq)]
308pub(crate) enum Attribution {
309 Repo {
312 repo_id: String,
313 project: Option<uuid::Uuid>,
314 },
315 ProjectOnly { project_id: uuid::Uuid },
318}
319
320impl Attribution {
321 pub(crate) fn pending_file_name(&self) -> String {
330 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
331 match self {
332 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
333 Self::ProjectOnly { project_id } => {
334 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
335 }
336 }
337 }
338}
339
340pub(crate) fn attribution_for(
360 binding: Option<&crate::session_state::RepoBinding>,
361 project: Option<uuid::Uuid>,
362) -> Option<Attribution> {
363 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
364 Some(b) => Some(Attribution::Repo {
365 repo_id: b.repo_id.clone(),
366 project,
367 }),
368 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
369 }
370}
371
372pub(crate) fn inference_project(
377 binding: Option<&crate::session_state::RepoBinding>,
378 project: Option<uuid::Uuid>,
379) -> Option<uuid::Uuid> {
380 match binding {
381 Some(_) => None,
382 None => project,
383 }
384}
385
386pub(crate) fn attribution_with_inference(
391 binding: Option<&crate::session_state::RepoBinding>,
392 project: Option<uuid::Uuid>,
393 inferred: Option<&crate::session_state::RepoBinding>,
394) -> Option<Attribution> {
395 match (inference_project(binding, project), inferred) {
396 (Some(pid), Some(repo)) if binding_repo_id_is_valid(&repo.repo_id) => {
397 Some(Attribution::Repo {
398 repo_id: repo.repo_id.clone(),
399 project: Some(pid),
400 })
401 }
402 _ => attribution_for(binding, project),
403 }
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
410pub(crate) struct Recording {
411 pub attribution: Option<Attribution>,
412 pub inferred_from: Option<String>,
413}
414
415fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
417 session_dir.join(attribution.pending_file_name())
418}
419
420fn adopted_project_queue(
450 session_dir: &Path,
451 attribution: &Attribution,
452) -> Option<std::path::PathBuf> {
453 match attribution {
454 Attribution::Repo {
455 project: Some(project_id),
456 ..
457 } => Some(pending_path_for(
458 session_dir,
459 &Attribution::ProjectOnly {
460 project_id: *project_id,
461 },
462 )),
463 _ => None,
464 }
465}
466
467pub fn resolve_session_paths(
480 hook_cwd: &Path,
481 session_id: &str,
482) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
483 let resolved = crate::paths::resolve_project_root(hook_cwd);
484 let session_dir = crate::layout::session_dir(&resolved.root, session_id);
485 (resolved, session_dir)
486}
487
488pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
496 uuid::Uuid::parse_str(repo_id).is_ok()
497}
498
499pub(crate) fn resolve_stream_binding(
503 session: &crate::session_state::SessionState,
504 worktree: &str,
505 bound: Option<crate::session_state::RepoBinding>,
506 user_default: Option<crate::session_state::RepoBinding>,
507) -> Option<crate::session_state::RepoBinding> {
508 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
509 repo_flag: None,
510 session,
511 worktree_path: Some(worktree),
512 bound,
513 user_default,
514 })
515 .map(|(b, _)| b)
516}
517
518pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
526 let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
527 let raw = raw.trim();
528 let parsed = raw.parse::<uuid::Uuid>().ok()?;
529 Some(crate::session_state::ProjectBinding {
530 project_id: parsed.to_string(),
531 project_name: String::new(),
532 updated_at: String::new(),
533 forced_until: None,
534 })
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
559pub(crate) struct AttributionForce {
560 pub(crate) env: bool,
563 pub(crate) binding: bool,
567}
568
569impl AttributionForce {
570 pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
573 if self.env || self.binding {
574 crate::api_client::AttributionMode::Explicit
575 } else {
576 crate::api_client::AttributionMode::Derived
577 }
578 }
579}
580
581pub(crate) fn attribution_mode(
633 effective: Option<&crate::session_state::ProjectBinding>,
634) -> crate::api_client::AttributionMode {
635 attribution_force(effective).mode()
636}
637
638pub(crate) fn attribution_force(
645 effective: Option<&crate::session_state::ProjectBinding>,
646) -> AttributionForce {
647 AttributionForce {
648 env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
649 .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
650 .unwrap_or(false),
651 binding: effective
652 .and_then(|b| b.forced_until.as_deref())
653 .is_some_and(|s| {
654 matches!(
655 crate::session_state::force_status(s),
656 crate::session_state::ForceStatus::Live(_)
657 )
658 }),
659 }
660}
661
662pub(crate) fn capture_binding(
684 session: &crate::session_state::SessionState,
685 worktree_path: Option<&str>,
686 config_project: Option<crate::session_state::ProjectBinding>,
687) -> Option<crate::session_state::ProjectBinding> {
688 use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
689 let (binding, _) = capture_project_binding(&CaptureProjectInputs {
690 project_flag: None,
691 env_project: env_project_binding(),
692 session,
693 worktree_path,
694 config_project,
695 user_default: crate::user_project_default::load(),
696 })?;
697 capture_project_id(&binding)?;
702 Some(binding)
703}
704
705pub(crate) fn capture_project(
715 session: &crate::session_state::SessionState,
716 worktree_path: Option<&str>,
717 config_project: Option<crate::session_state::ProjectBinding>,
718) -> Option<uuid::Uuid> {
719 capture_binding(session, worktree_path, config_project)
720 .as_ref()
721 .and_then(crate::resolution::capture_project_id)
722}
723
724pub(crate) fn recording_attribution_for(
737 session: &crate::session_state::SessionState,
738 worktree: &str,
739 bound: Option<crate::session_state::RepoBinding>,
740 user_default_repo: Option<crate::session_state::RepoBinding>,
741 config_project: Option<crate::session_state::ProjectBinding>,
742) -> Recording {
743 let stream_binding = resolve_stream_binding(session, worktree, bound, user_default_repo);
744 let project = capture_project(session, Some(worktree), config_project);
745 let inferred = inference_project(stream_binding.as_ref(), project)
746 .and_then(|pid| crate::inferred_repo::cached_repo(session, worktree, pid));
747 let attribution =
748 attribution_with_inference(stream_binding.as_ref(), project, inferred.as_ref());
749 let inferred_from = match (&attribution, &inferred) {
750 (Some(Attribution::Repo { repo_id, .. }), Some(repo)) if *repo_id == repo.repo_id => {
751 Some(worktree.to_string())
752 }
753 _ => None,
754 };
755 Recording {
756 attribution,
757 inferred_from,
758 }
759}
760
761pub(crate) fn recording_line_for(recording: &Recording) -> String {
764 if let (
765 Some(Attribution::Repo {
766 repo_id,
767 project: Some(pid),
768 }),
769 Some(checkout),
770 ) = (&recording.attribution, &recording.inferred_from)
771 {
772 return format!(
773 "recording: repo {repo_id} in project {pid} — inferred from the checkout {checkout} \
774 (no repo is bound; events in other checkouts go to their own repo in the project, \
775 or to the project only)"
776 );
777 }
778 recording_line(recording.attribution.as_ref())
779}
780
781pub(crate) fn recording_line(attribution: Option<&Attribution>) -> String {
783 match attribution {
784 Some(Attribution::Repo {
785 repo_id,
786 project: None,
787 }) => format!("recording: repo {repo_id} (the server deduces the project from the repo)"),
788 Some(Attribution::Repo {
789 repo_id,
790 project: Some(pid),
791 }) => format!("recording: repo {repo_id} in project {pid}"),
792 Some(Attribution::ProjectOnly { project_id }) => format!(
793 "recording: project {project_id} only — no repo is bound, so events are sent \
794 without one (`{CLI} repo switch <path>` adds the repo)"
795 ),
796 None => "recording: nothing — neither a repo nor a project is bound, so this \
797 session's events are not sent"
798 .to_string(),
799 }
800}
801
802pub(crate) fn refused_project_only_error(
815 pid: uuid::Uuid,
816 kind: &ClientErrorKind,
817 force: AttributionForce,
818) -> String {
819 let base = match kind {
820 ClientErrorKind::Forbidden => format!(
821 "{TOP}: error: the server refused this repo-less session's event for project \
822 {pid} (403). Either this account has no access to that project (no `Operator` \
823 role on it) — run `{CLI} project switch <name>` (add `--user` if the binding \
824 is the machine-wide default in `user_project.toml`) — or it has no `tracevault` \
825 grant in Control Plane at all, which an administrator must grant. The session has \
826 no repo binding, so the event was not sent anywhere else; it has been queued and \
827 will be retried with the next event."
828 ),
829 ClientErrorKind::Scoping => format!(
830 "{TOP}: error: project {pid} does not resolve on the server (400/404/409: it \
831 does not exist, or this account cannot see it). The session has no repo binding, \
832 so the event was not sent anywhere else; it has been queued and will be retried \
833 with the next event. Run `{CLI} project switch <name>` (add `--user` if the \
834 binding is the machine-wide default in `user_project.toml`) to bind a project that \
835 exists, or `{CLI} repo switch <path>` to record this session to a repo."
836 ),
837 };
838 with_force_clause(base, kind, force)
839}
840
841#[derive(Debug, PartialEq, Eq)]
862pub(crate) enum ClientErrorKind {
863 Forbidden,
865 Scoping,
867}
868
869pub(crate) fn refused_error(
900 pid: uuid::Uuid,
901 kind: &ClientErrorKind,
902 force: AttributionForce,
903) -> String {
904 let base = match kind {
905 ClientErrorKind::Forbidden => format!(
911 "{TOP}: error: the server refused to attribute this event to active project \
912 {pid} (403). Either that project does not apply to this repo (not a member, or \
913 no `Operator` role on it) — run `{CLI} project switch <name>` (add `--user` if the \
914 binding is the machine-wide default in `user_project.toml`) — or this account has \
915 no `tracevault` grant in Control Plane at all, which an administrator must grant. \
916 The event was NOT re-attributed elsewhere; it has been queued and will be retried \
917 once the binding or the grant is fixed."
918 ),
919 ClientErrorKind::Scoping => format!(
920 "{TOP}: error: active project {pid} does not apply to this repo (not a member, \
921 missing permission, or the project no longer exists). The event was NOT \
922 re-attributed elsewhere; it has been queued and will be retried once the binding is \
923 fixed. Run `{CLI} project switch <name>` (add `--user` if the binding is the \
924 machine-wide default in `user_project.toml`) to update it."
925 ),
926 };
927 with_force_clause(base, kind, force)
928}
929
930fn with_force_clause(base: String, kind: &ClientErrorKind, force: AttributionForce) -> String {
934 if force.mode() == crate::api_client::AttributionMode::Explicit
935 && matches!(kind, ClientErrorKind::Forbidden)
936 {
937 return format!(
938 "{base} This send declared `explicit` attribution, so the refusal may be of the \
939 FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
940 identity (a `tvk_` API key can never force). If membership attribution is what \
941 you want, {}",
942 force_remediation(force)
943 );
944 }
945 base
946}
947
948fn force_remediation(force: AttributionForce) -> String {
965 let env_fix = crate::program::say(
966 "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
967 process-wide and never expires, so no switch clears it)",
968 );
969 let binding_fix = crate::program::say(
970 "run `tracevault project switch <name>` WITHOUT \
971 `--project-attribution explicit` (add `--user` if the forced binding \
972 is the machine-wide default in `user_project.toml`)",
973 );
974 match (force.env, force.binding) {
975 (true, false) => format!("{env_fix}."),
976 (false, true) => format!("{binding_fix}."),
977 (true, true) => {
979 format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
980 }
981 (false, false) => format!("{env_fix}, or {binding_fix}."),
982 }
983}
984
985pub(crate) fn deterministic_client_error_kind(
986 e: &dyn std::error::Error,
987) -> Option<ClientErrorKind> {
988 let s = e.to_string();
989 if s.contains("(403 ") {
996 return Some(ClientErrorKind::Forbidden);
997 }
998 if ["(400 ", "(404 ", "(409 "]
999 .iter()
1000 .any(|marker| s.contains(marker))
1001 {
1002 return Some(ClientErrorKind::Scoping);
1003 }
1004 None
1005}
1006
1007async fn send_stream_event(
1056 client: &crate::api_client::ApiClient,
1057 attribution: &Attribution,
1058 force: AttributionForce,
1059 req: &StreamEventRequest,
1060 warned: &mut bool,
1061) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn std::error::Error>> {
1062 let (repo_id, capture_pid) = match attribution {
1063 Attribution::ProjectOnly { project_id } => {
1072 let attempt = client
1073 .stream_event_for_project(*project_id, None, force.mode(), req)
1074 .await;
1075 if let Err(e) = &attempt {
1076 if let Some(kind) = deterministic_client_error_kind(e.as_ref()) {
1077 if !*warned {
1078 eprintln!("{}", refused_project_only_error(*project_id, &kind, force));
1079 *warned = true;
1080 }
1081 }
1082 }
1083 return attempt;
1084 }
1085 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
1086 };
1087 match capture_pid {
1088 None => client.stream_event(repo_id, req).await,
1089 Some(pid) => {
1090 let attempt = client
1091 .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
1092 .await;
1093 let kind = match &attempt {
1094 Ok(_) => None,
1095 Err(e) => deterministic_client_error_kind(e.as_ref()),
1096 };
1097 match (attempt, kind) {
1098 (Ok(r), _) => Ok(r),
1099 (Err(e), Some(kind)) => {
1100 if !*warned {
1101 eprintln!("{}", refused_error(pid, &kind, force));
1109 *warned = true;
1110 }
1111 Err(e)
1117 }
1118 (Err(e), None) => Err(e),
1120 }
1121 }
1122 }
1123}
1124
1125pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
1131 (start_offset, start_offset + records_len)
1132}
1133
1134pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
1150 if req.serialized_len() <= MAX_REQUEST_BYTES {
1151 return vec![req];
1152 }
1153 let lines = req.transcript_lines.take().unwrap_or_default();
1154 let batch_offset = req.transcript_offset.unwrap_or(0);
1155 req.truncate_large_fields();
1158
1159 let sizes: Vec<usize> = lines
1161 .iter()
1162 .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
1163 .collect();
1164 let envelope = |r: &StreamEventRequest| {
1165 let mut r = r.clone();
1166 r.transcript_lines = Some(vec![]);
1167 r.serialized_len()
1168 };
1169
1170 let mut tail_start = lines.len();
1172 let mut used = envelope(&req);
1173 while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
1174 tail_start -= 1;
1175 used += sizes[tail_start];
1176 }
1177
1178 let transcript_template = transcript_template(&req);
1179 let transcript_envelope = envelope(&transcript_template);
1180
1181 let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
1183 let mut start = 0;
1184 while start < tail_start {
1185 let mut end = start + 1;
1186 let mut used = transcript_envelope + sizes[start];
1187 while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
1188 used += sizes[end];
1189 end += 1;
1190 }
1191 groups.push(start..end);
1192 start = end;
1193 }
1194 groups.push(tail_start..lines.len());
1195
1196 let last = groups.len() - 1;
1197 let mut lines = lines.into_iter();
1198 groups
1199 .into_iter()
1200 .enumerate()
1201 .map(|(n, range)| {
1202 let mut part = if n == last {
1203 req.clone()
1204 } else {
1205 transcript_template.clone()
1206 };
1207 let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
1208 part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
1209 part.transcript_offset = Some(batch_offset + range.start as i64);
1210 part
1211 })
1212 .collect()
1213}
1214
1215pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
1220 StreamEventRequest {
1221 protocol_version: req.protocol_version,
1222 tool: req.tool.clone(),
1223 event_type: StreamEventType::Transcript,
1224 session_id: req.session_id.clone(),
1225 timestamp: req.timestamp,
1226 hook_event_name: req.hook_event_name.clone(),
1227 tool_name: None,
1228 tool_use_id: None,
1229 tool_input: None,
1230 tool_response: None,
1231 tool_is_error: None,
1232 event_index: None,
1233 event_uuid: None,
1234 transcript_lines: None,
1235 transcript_offset: req.transcript_offset,
1236 model: req.model.clone(),
1237 cwd: req.cwd.clone(),
1238 final_stats: None,
1239 flow_id: req.flow_id.clone(),
1240 labels: req.labels.clone(),
1241 params: req.params.clone(),
1242 billing_mode: req.billing_mode,
1243 }
1244}
1245
1246#[allow(clippy::too_many_arguments)]
1267async fn deliver_subagent_transcripts(
1268 client: &crate::api_client::ApiClient,
1269 attribution: &Attribution,
1270 force: AttributionForce,
1271 template: &StreamEventRequest,
1272 transcript_path: &Path,
1273 session_dir: &Path,
1274 pending_path: &Path,
1275 mut send_failed: bool,
1276 deadline: std::time::Instant,
1277 wait_for_lock: Option<std::time::Instant>,
1278 warned: &mut bool,
1279) -> Result<bool, Box<dyn std::error::Error>> {
1280 let mut complete = true;
1282 for file in crate::subagents::transcripts(transcript_path) {
1283 let offset_path = crate::subagents::offset_path(session_dir, &file);
1284 let lock = loop {
1286 match crate::subagents::try_lock(&offset_path) {
1287 Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
1288 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1289 }
1290 other => break other,
1291 }
1292 };
1293 let _lock = match lock {
1294 Ok(Some(lock)) => lock,
1295 Ok(None) => {
1296 complete = false;
1297 if wait_for_lock.is_some() {
1298 eprintln!(
1299 "{TOP}: warning: skipping subagent transcript {}: \
1300 another hook is still sending it",
1301 file.display()
1302 );
1303 }
1304 continue;
1305 }
1306 Err(e) => {
1307 eprintln!(
1308 "{TOP}: warning: skipping subagent transcript {}: cannot lock: {e}",
1309 file.display()
1310 );
1311 complete = false;
1312 continue;
1313 }
1314 };
1315 loop {
1320 let mut batch = match crate::subagents::read_batch(&file, &offset_path, MAX_BATCH_BYTES)
1321 {
1322 Ok(read) => read,
1323 Err(e) => {
1324 eprintln!(
1325 "{TOP}: warning: skipping subagent transcript {}: {e}",
1326 file.display()
1327 );
1328 complete = false;
1329 break;
1330 }
1331 };
1332 if batch.end == batch.start {
1333 break;
1334 }
1335 let mut delivered = Delivered {
1337 all: true,
1338 lines: 0,
1339 };
1340 if !batch.lines.is_empty() {
1341 let mut req = template.clone();
1342 req.transcript_lines = Some(std::mem::take(&mut batch.lines));
1343 req.transcript_offset = Some(batch.start);
1344 delivered = deliver_parts(
1345 client,
1346 attribution,
1347 force,
1348 split_into_parts(req),
1349 pending_path,
1350 send_failed,
1351 deadline,
1352 Unsent::Queued,
1353 warned,
1354 )
1355 .await?;
1356 send_failed |= !delivered.all;
1357 }
1358 let next = batch.next_offset(&delivered);
1361 if let Some(next) = next {
1362 crate::subagents::write_offset(&offset_path, next)?;
1363 }
1364 let stopped_short = next != Some(batch.end);
1365 if wait_for_lock.is_none() || stopped_short {
1366 let unread = fs::metadata(&file).is_ok_and(|m| m.len() as i64 > batch.end);
1367 complete &= delivered.all && !stopped_short && !unread;
1368 break;
1369 }
1370 complete &= delivered.all;
1371 }
1372 }
1373 Ok(complete)
1374}
1375
1376pub fn resolve_transcript_source(
1382 inline_records: Option<Vec<serde_json::Value>>,
1383 prior_offset: i64,
1384 file_result: (Vec<serde_json::Value>, i64, i64),
1385) -> (Vec<serde_json::Value>, i64, i64) {
1386 match inline_records {
1387 Some(records) => {
1388 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1389 (records, send, next)
1390 }
1391 None => file_result,
1392 }
1393}
1394
1395pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1404 lines.iter().find_map(|line| {
1405 let msg = line.get("message")?;
1406 if line.get("type").and_then(|v| v.as_str()) == Some("amp_message") {
1407 return msg
1408 .get("content")?
1409 .as_array()?
1410 .iter()
1411 .find(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result"))
1412 .map(|b| b.get("status").and_then(|v| v.as_str()) == Some("error"));
1413 }
1414 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1415 Some(
1416 msg.get("isError")
1417 .and_then(|v| v.as_bool())
1418 .unwrap_or(false),
1419 )
1420 } else {
1421 None
1422 }
1423 })
1424}
1425
1426pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1430 req.tool = Some(agent.tool_name().to_string());
1431 req.protocol_version = agent.protocol_version() as u32;
1432}
1433
1434const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1440
1441pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1446
1447const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1454
1455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1457pub enum Unsent {
1458 Queued,
1464 StayInFile,
1469 Inline,
1472}
1473
1474#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1479pub struct Delivered {
1480 pub all: bool,
1481 pub lines: usize,
1482}
1483
1484#[allow(clippy::too_many_arguments)]
1496async fn deliver_parts(
1497 client: &crate::api_client::ApiClient,
1498 attribution: &Attribution,
1499 force: AttributionForce,
1500 parts: Vec<StreamEventRequest>,
1501 pending_path: &Path,
1502 mut send_failed: bool,
1503 deadline: std::time::Instant,
1504 unsent: Unsent,
1505 warned: &mut bool,
1506) -> Result<Delivered, Box<dyn std::error::Error>> {
1507 let mut delivered = Delivered {
1508 all: true,
1509 lines: 0,
1510 };
1511 let mut queue_full = unsent == Unsent::StayInFile;
1512 for part in parts {
1513 send_failed = send_failed || std::time::Instant::now() >= deadline;
1514 if !send_failed {
1515 let send = send_stream_event(client, attribution, force, &part, warned);
1516 let failure =
1517 match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1518 Ok(Ok(_)) => {
1519 delivered.lines += lines_of(&part);
1520 continue;
1521 }
1522 Ok(Err(e)) => e.to_string(),
1523 Err(_) => "no answer in time".to_string(),
1524 };
1525 warn_unsent(warned, &failure);
1526 send_failed = true;
1527 }
1528 delivered.all = false;
1529 let json = serde_json::to_string(&part)?;
1530 if unsent == Unsent::Inline {
1531 crate::pending_queue::append(pending_path, &json)?;
1532 continue;
1533 }
1534 if !queue_full && crate::pending_queue::try_append(pending_path, &json)? {
1535 delivered.lines += lines_of(&part);
1536 continue;
1537 }
1538 queue_full = true;
1541 if let Some(event) = crate::pending_queue::without_lines(part) {
1542 crate::pending_queue::append(pending_path, &serde_json::to_string(&event)?)?;
1543 }
1544 }
1545 Ok(delivered)
1546}
1547
1548fn lines_of(part: &StreamEventRequest) -> usize {
1549 part.transcript_lines.as_ref().map_or(0, Vec::len)
1550}
1551
1552fn too_large(failure: &str) -> bool {
1555 failure.contains("(413 ")
1556}
1557
1558fn tool_is_error_past(transcript: &Path, from: i64, tool_use_id: &str) -> Option<bool> {
1564 let mut file = fs::File::open(transcript).ok()?;
1565 let len = file.metadata().ok()?.len() as i64;
1566 if len <= from || tool_use_id.is_empty() {
1567 return None;
1568 }
1569 file.seek(SeekFrom::Start(from.max(len - MAX_BATCH_BYTES) as u64))
1570 .ok()?;
1571 let mut tail = Vec::new();
1572 file.take(MAX_BATCH_BYTES as u64)
1573 .read_to_end(&mut tail)
1574 .ok()?;
1575 let needle = tool_use_id.as_bytes();
1576 let lines: Vec<serde_json::Value> = tail
1577 .split(|b| *b == b'\n')
1578 .filter(|line| line.windows(needle.len()).any(|w| w == needle))
1579 .filter_map(|line| serde_json::from_slice(line).ok())
1580 .collect();
1581 extract_is_error_from_transcript(tool_use_id, &lines)
1582}
1583
1584fn warn_unsent(warned: &mut bool, failure: &str) {
1588 if !*warned {
1589 eprintln!("{TOP}: warning: could not send to the server ({failure}); it will be retried");
1590 *warned = true;
1591 }
1592}
1593
1594pub const TRACING_MODE_ENV: &str = "VISDOM_TRACING_MODE";
1599
1600pub const GATEWAY_SESSION_ENV: &str = "VISDOM_GATEWAY_SESSION";
1604
1605pub fn captured_by_gateway(marker: Option<&str>, agent: crate::agent::Agent) -> bool {
1620 marker
1621 .map(str::trim)
1622 .is_some_and(|m| m == "1" || m.eq_ignore_ascii_case(agent.tool_name()))
1623}
1624
1625pub async fn run_stream(
1626 event_type: &str,
1627 agent: crate::agent::Agent,
1628) -> Result<(), Box<dyn std::error::Error>> {
1629 let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1631 let mut input = String::new();
1632 io::stdin().read_to_string(&mut input)?;
1633 if captured_by_gateway(std::env::var(GATEWAY_SESSION_ENV).ok().as_deref(), agent) {
1635 println!("{}", serde_json::to_string(&HookResponse::allow())?);
1636 return Ok(());
1637 }
1638 let hook_event = parse_hook_event(&input)?;
1639
1640 let hook_cwd = Path::new(&hook_event.cwd);
1662 let (resolved, cwd_session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1663 let storage_root =
1664 crate::session_state::storage_root(&crate::session_state::load(&hook_event.session_id));
1665 let session_dir = match &storage_root {
1666 Some(root) => crate::layout::session_dir(root, &hook_event.session_id),
1667 None => cwd_session_dir,
1668 };
1669 if storage_root.is_none() && resolved.source == crate::paths::ProjectRootSource::Fallback {
1670 eprintln!(
1675 "{TOP}: warning: could not resolve a git project root from {}; \
1676 creating .visdom/ there. Ensure `git` is on PATH for the hook and \
1677 that it runs inside the repository to keep sessions under the repo root.",
1678 hook_cwd.display()
1679 );
1680 }
1681 let project_root = resolved.root;
1682
1683 fs::create_dir_all(&session_dir)?;
1685
1686 if let Some(dir) = session_dir.parent().and_then(Path::parent) {
1694 let _ = crate::config::TracevaultConfig::ensure_gitignore(dir);
1695 }
1696
1697 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1702 let _ = fs::write(session_dir.join("origin"), &worktree_top);
1703 if storage_root.is_some() {
1706 let _ = crate::session_state::record_worktree(&session_dir, &worktree_top);
1707 }
1708
1709 let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1713 if let Some(records) = &hook_event.transcript_records {
1718 let _ = record_inline_tool_calls(&session_dir, records);
1719 }
1720
1721 let target = SessionTarget {
1722 project_root,
1723 session_dir,
1724 worktree_top,
1725 };
1726 stream_event(
1727 hook_event,
1728 event_type,
1729 agent,
1730 &target,
1731 deadline,
1732 Sender::Hook,
1733 )
1734 .await?;
1735
1736 let response = HookResponse::allow();
1738 println!("{}", serde_json::to_string(&response)?);
1739
1740 Ok(())
1741}
1742
1743pub fn stream_event_type(event_type: &str) -> StreamEventType {
1745 match event_type {
1746 "notification" => StreamEventType::SessionStart,
1747 "stop" => StreamEventType::SessionEnd,
1749 "session-end" => StreamEventType::Transcript,
1753 _ => StreamEventType::ToolUse,
1754 }
1755}
1756
1757pub(crate) struct SessionTarget {
1761 pub project_root: std::path::PathBuf,
1762 pub session_dir: std::path::PathBuf,
1764 pub worktree_top: String,
1766}
1767
1768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1770pub(crate) enum Sender {
1771 Hook,
1774 CatchUp,
1779 Flush,
1784}
1785
1786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1788pub(crate) enum Sent {
1789 Accepted,
1792 Queued,
1795 Skipped,
1798}
1799
1800pub(crate) async fn stream_event(
1804 mut hook_event: tracevault_protocol::hooks::HookEvent,
1805 event_type: &str,
1806 agent: crate::agent::Agent,
1807 target: &SessionTarget,
1808 deadline: std::time::Instant,
1809 sender: Sender,
1810) -> Result<Sent, Box<dyn std::error::Error>> {
1811 let SessionTarget {
1812 project_root,
1813 session_dir,
1814 worktree_top,
1815 } = target;
1816 let hook_cwd = Path::new(&hook_event.cwd);
1817
1818 let event_uuid = uuid::Uuid::now_v7();
1823
1824 let transcript_path = Path::new(&hook_event.transcript_path);
1826 let offset_path = session_dir.join(".stream_offset");
1827 let sends_main = event_type != "subagent-stop";
1834 let reads_file = sends_main && hook_event.transcript_records.is_none();
1842 let main_lock = if reads_file {
1843 let wait_until =
1844 matches!(event_type, "stop" | "session-end").then(|| deadline + FINAL_LOCK_WAIT);
1845 loop {
1846 match crate::subagents::try_lock(&offset_path) {
1847 Ok(None) if wait_until.is_some_and(|t| std::time::Instant::now() < t) => {
1848 tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1849 }
1850 Ok(lock) => break lock,
1851 Err(e) => {
1852 eprintln!("{TOP}: warning: cannot lock the transcript offset: {e}");
1853 break None;
1854 }
1855 }
1856 }
1857 } else {
1858 None
1859 };
1860 let sends_lines = !reads_file || main_lock.is_some();
1861 let mut batch = if sends_main {
1862 read_transcript_batch(transcript_path, &offset_path, MAX_BATCH_BYTES)?
1863 } else {
1864 TranscriptBatch::default()
1865 };
1866 let (transcript_lines, start_offset, new_offset) =
1867 (std::mem::take(&mut batch.lines), batch.start, batch.end);
1868
1869 let is_inline = hook_event.transcript_records.is_some();
1886 let (transcript_lines, start_offset, new_offset) = if is_inline {
1887 let prior_offset: i64 = if offset_path.exists() {
1894 let content = fs::read_to_string(&offset_path)?;
1895 content
1896 .trim()
1897 .parse::<i64>()
1898 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1899 .max(0)
1900 } else {
1901 0
1902 };
1903 resolve_transcript_source(
1907 hook_event.transcript_records.take(),
1908 prior_offset,
1909 (transcript_lines, start_offset, new_offset),
1910 )
1911 } else {
1912 (transcript_lines, start_offset, new_offset)
1913 };
1914 let stream_event_type = stream_event_type(event_type);
1916
1917 let tool_is_error = hook_event
1922 .tool_use_id
1923 .as_deref()
1924 .and_then(|uid| {
1925 extract_is_error_from_transcript(uid, &transcript_lines)
1926 .or_else(|| {
1928 reads_file
1929 .then(|| tool_is_error_past(transcript_path, new_offset, uid))
1930 .flatten()
1931 })
1932 })
1933 .or_else(|| inline_tool_is_error(&transcript_lines));
1934
1935 let config = crate::config::TracevaultConfig::try_load(project_root);
1945 let repo_uc = config
1949 .as_ref()
1950 .ok()
1951 .and_then(|opt| opt.as_ref())
1952 .and_then(|c| c.user_context.clone());
1953 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1954
1955 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1961 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1962
1963 let mut req = StreamEventRequest {
1964 protocol_version: 1,
1965 tool: Some("claude-code".to_string()),
1966 event_type: stream_event_type,
1967 session_id: hook_event.session_id.clone(),
1968 timestamp: chrono::Utc::now(),
1969 hook_event_name: Some(hook_event.hook_event_name.clone()),
1970 tool_name: hook_event.tool_name.clone(),
1971 tool_use_id: hook_event.tool_use_id.clone(),
1972 tool_input: hook_event.tool_input.clone(),
1973 tool_response: hook_event.tool_response.clone(),
1974 tool_is_error,
1975 event_index: None,
1976 event_uuid: Some(event_uuid),
1977 transcript_lines: None,
1978 transcript_offset: Some(start_offset),
1979 model: None,
1980 cwd: Some(hook_event.cwd.clone()),
1981 final_stats: None,
1982 flow_id: ctx_flow_id,
1983 labels: ctx_labels,
1984 params: ctx_params,
1985 billing_mode: (sender == Sender::Hook)
1986 .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
1987 };
1988
1989 stamp_agent(&mut req, agent);
1990 let subagent_template = transcript_template(&req);
1992 if sends_lines && !transcript_lines.is_empty() {
1995 req.transcript_lines = Some(transcript_lines);
1996 }
1997
1998 let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;
2000
2001 if let Err(e) = &config {
2010 return Err(format!("malformed .visdom/tracing.toml: {e}").into());
2011 }
2012
2013 let session = crate::session_state::load(&hook_event.session_id);
2018 let bound = config
2019 .as_ref()
2020 .ok()
2021 .and_then(|opt| opt.as_ref())
2022 .and_then(crate::resolution::binding_from_config);
2023 let user_default = crate::user_default::load();
2024 let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
2025 let config_project = config
2039 .as_ref()
2040 .ok()
2041 .and_then(|opt| opt.as_ref())
2042 .and_then(crate::resolution::project_from_config);
2043 let capture_binding = capture_binding(&session, Some(worktree_top.as_str()), config_project);
2044 let capture_pid = capture_binding
2045 .as_ref()
2046 .and_then(crate::resolution::capture_project_id);
2047 let client = server_url
2057 .as_deref()
2058 .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
2059 let mut inferred = None;
2060 if binding.is_none() {
2061 if let Some(client) = &client {
2062 match inference_project(None, capture_pid) {
2063 Some(pid) => {
2064 if let Some(checkout) = crate::inferred_repo::event_checkout(
2065 hook_cwd,
2066 hook_event.tool_input.as_ref(),
2067 worktree_top,
2068 ) {
2069 inferred = crate::inferred_repo::infer(
2070 &hook_event.session_id,
2071 &checkout,
2072 pid,
2073 client,
2074 deadline,
2075 )
2076 .await;
2077 if inferred.is_some() && checkout != *worktree_top {
2081 let _ = crate::session_state::record_worktree(session_dir, &checkout);
2082 }
2083 }
2084 }
2085 None => {
2086 let auto = crate::auto_bind::bind_session(
2087 &hook_event.session_id,
2088 hook_cwd,
2089 client,
2090 deadline,
2091 )
2092 .await;
2093 if let Some(notice) = auto.notice {
2094 eprintln!("{notice}");
2095 }
2096 binding = auto.binding;
2097 }
2098 }
2099 }
2100 }
2101 let force = attribution_force(capture_binding.as_ref());
2108
2109 let Some(attribution) =
2117 attribution_with_inference(binding.as_ref(), capture_pid, inferred.as_ref())
2118 else {
2119 return Ok(Sent::Skipped);
2120 };
2121 match sender {
2125 Sender::Hook => {
2126 let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
2127 let _ = record_metadata(session_dir, "agent", agent.tool_name().into());
2130 }
2131 Sender::CatchUp | Sender::Flush => {
2132 let meta = session_metadata(session_dir);
2133 let recorded = meta.get("attribution");
2134 if (sender == Sender::Flush && recorded.is_none())
2138 || !catch_up_may_send(recorded, &attribution)
2139 {
2140 return Ok(Sent::Skipped);
2141 }
2142 }
2143 }
2144
2145 let client = client.ok_or("server_url not configured")?;
2147
2148 let pending_path = pending_path_for(session_dir, &attribution);
2160 let adopted = if inferred.is_some() && binding.is_none() {
2161 None
2162 } else {
2163 adopted_project_queue(session_dir, &attribution)
2164 };
2165 crate::pending_queue::upgrade(session_dir)?;
2166 let claimed = match adopted {
2172 Some(adopted) => crate::pending_queue::claim(&adopted)?.retarget(&pending_path)?,
2173 None => crate::pending_queue::Claimed::default(),
2174 }
2175 .then(crate::pending_queue::claim(&pending_path)?);
2176
2177 let mut send_failed = false;
2178 let mut warned = false;
2182
2183 let mut rest = None;
2192 let mut reader = claimed.reader();
2193 while let Some(record) = reader.next_record()? {
2194 let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(&record) else {
2195 continue;
2196 };
2197 if std::time::Instant::now() >= deadline {
2198 send_failed = true;
2199 rest = Some(reader.before_last());
2200 break;
2201 }
2202 let failure = match tokio::time::timeout_at(
2205 (deadline + IN_FLIGHT_GRACE).into(),
2206 send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
2207 )
2208 .await
2209 {
2210 Ok(Ok(_)) => continue,
2211 Ok(Err(e)) => e.to_string(),
2212 Err(_) => "no answer in time".to_string(),
2213 };
2214 warn_unsent(&mut warned, &failure);
2215 if too_large(&failure) {
2216 crate::pending_queue::requeue(&pending_path, &record)?;
2220 continue;
2221 }
2222 send_failed = true;
2223 rest = Some(reader.before_last());
2224 break;
2225 }
2226 drop(reader);
2227 claimed.finish(rest, &pending_path)?;
2228
2229 let sends_event = sends_main
2234 && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
2235 let unsent = if is_inline {
2238 Unsent::Inline
2239 } else if event_type == "session-end" {
2240 Unsent::StayInFile
2241 } else {
2242 Unsent::Queued
2243 };
2244 let delivered = if sends_event {
2245 deliver_parts(
2246 &client,
2247 &attribution,
2248 force,
2249 split_into_parts(req),
2250 &pending_path,
2251 send_failed,
2252 deadline,
2253 unsent,
2254 &mut warned,
2255 )
2256 .await?
2257 } else {
2258 Delivered {
2259 all: true,
2260 lines: 0,
2261 }
2262 };
2263 let all_accepted = delivered.all;
2264 let mut all_accepted = all_accepted;
2277 if sends_main && sends_lines {
2278 let next = if is_inline {
2279 Some(new_offset)
2280 } else {
2281 batch.next_offset(&delivered)
2282 };
2283 if let Some(next) = next {
2284 advance_offset(&offset_path, next)?;
2285 }
2286 let mut read_on = (event_type == "stop" || sender == Sender::Flush)
2292 && !is_inline
2293 && next == Some(new_offset);
2294 while read_on {
2295 let mut more = read_transcript_batch(transcript_path, &offset_path, MAX_BATCH_BYTES)?;
2296 if more.end == more.start {
2297 break;
2298 }
2299 let mut delivered = Delivered {
2300 all: true,
2301 lines: 0,
2302 };
2303 if !more.lines.is_empty() {
2304 let mut req = subagent_template.clone();
2305 req.transcript_lines = Some(std::mem::take(&mut more.lines));
2306 req.transcript_offset = Some(more.start);
2307 delivered = deliver_parts(
2308 &client,
2309 &attribution,
2310 force,
2311 split_into_parts(req),
2312 &pending_path,
2313 send_failed || !all_accepted,
2314 deadline,
2315 unsent,
2316 &mut warned,
2317 )
2318 .await?;
2319 all_accepted &= delivered.all;
2320 }
2321 let next = more.next_offset(&delivered);
2322 if let Some(next) = next {
2323 advance_offset(&offset_path, next)?;
2324 }
2325 read_on = next == Some(more.end);
2326 }
2327 }
2328 drop(main_lock);
2329
2330 let mut complete = !send_failed && all_accepted && sends_lines;
2335 if sender != Sender::CatchUp && agent == crate::agent::Agent::ClaudeCode {
2336 complete &= deliver_subagent_transcripts(
2337 &client,
2338 &attribution,
2339 force,
2340 &subagent_template,
2341 transcript_path,
2342 session_dir,
2343 &pending_path,
2344 send_failed || !all_accepted,
2345 deadline,
2346 matches!(event_type, "stop" | "subagent-stop" | "session-end")
2347 .then(|| deadline + FINAL_LOCK_WAIT),
2348 &mut warned,
2349 )
2350 .await?;
2351 }
2352
2353 Ok(if complete {
2354 Sent::Accepted
2355 } else {
2356 Sent::Queued
2357 })
2358}
2359
2360#[cfg(test)]
2361mod tests {
2362 use super::*;
2363 use crate::api_client::AttributionMode;
2364 use crate::config::UserContext;
2365 use crate::context::{Context, EffectiveContext};
2366 use std::collections::BTreeMap;
2367
2368 #[test]
2369 fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
2370 let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
2371 repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
2372 project,
2373 };
2374 let a = uuid::Uuid::from_u128(0xa);
2375 let b = uuid::Uuid::from_u128(0xb);
2376 let only = |project_id| Attribution::ProjectOnly { project_id };
2377
2378 let recorded = attribution_record(&repo(Some(a)));
2379 assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
2380 assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
2381 assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
2382 let recorded = attribution_record(&only(a));
2383 assert!(catch_up_may_send(Some(&recorded), &only(a)));
2384 assert!(!catch_up_may_send(Some(&recorded), &only(b)));
2385 assert!(catch_up_may_send(None, &repo(Some(b))));
2388 assert!(!catch_up_may_send(None, &only(a)));
2389 }
2390
2391 #[test]
2392 fn record_metadata_keeps_the_other_keys() {
2393 let dir = tempfile::tempdir().unwrap();
2394 record_transcript_path(dir.path(), "/t.jsonl").unwrap();
2395 record_metadata(
2396 dir.path(),
2397 "attribution",
2398 serde_json::json!({"repo_id": "r"}),
2399 )
2400 .unwrap();
2401 let meta = session_metadata(dir.path());
2402 assert_eq!(meta["transcript_path"], "/t.jsonl");
2403 assert_eq!(meta["attribution"]["repo_id"], "r");
2404 }
2405
2406 #[test]
2407 fn hook_events_map_to_server_events() {
2408 assert_eq!(
2409 stream_event_type("notification"),
2410 StreamEventType::SessionStart
2411 );
2412 assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
2415 assert_eq!(
2416 stream_event_type("session-end"),
2417 StreamEventType::Transcript
2418 );
2419 for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
2420 assert_eq!(
2421 stream_event_type(event),
2422 StreamEventType::ToolUse,
2423 "{event}"
2424 );
2425 }
2426 }
2427
2428 #[test]
2431 fn disabled_user_context_resolves_to_none() {
2432 assert!(UserContext::Toggle(false).resolve().is_none());
2436 }
2437
2438 #[test]
2439 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
2440 let dir = tempfile::tempdir().unwrap();
2444 let effective = Context::effective(dir.path(), None);
2445 assert_eq!(effective, EffectiveContext::default());
2446 }
2447
2448 #[test]
2451 fn apply_context_stamps_all_fields() {
2452 let dir = tempfile::tempdir().unwrap();
2453 let mut params = BTreeMap::new();
2454 params.insert("env".to_string(), "prod".to_string());
2455 params.insert("region".to_string(), "eu-west-1".to_string());
2456
2457 let ctx = EffectiveContext {
2458 flow_id: Some("flow-xyz".to_string()),
2459 labels: vec!["backend".to_string(), "urgent".to_string()],
2460 params,
2461 };
2462
2463 let (flow_id, labels, params_out) = apply_context(ctx);
2464
2465 assert_eq!(flow_id, Some("flow-xyz".to_string()));
2466 assert_eq!(
2467 labels,
2468 Some(vec!["backend".to_string(), "urgent".to_string()])
2469 );
2470 let p = params_out.expect("params should be Some");
2471 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
2472 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
2473
2474 let written = Context {
2477 flow_id: Some("flow-xyz".to_string()),
2478 labels: vec!["backend".to_string(), "urgent".to_string()],
2479 params: {
2480 let mut m = BTreeMap::new();
2481 m.insert("env".to_string(), Some("prod".to_string()));
2482 m.insert("region".to_string(), Some("eu-west-1".to_string()));
2483 m
2484 },
2485 };
2486 let ctx_path = dir.path().join(".visdom").join("context.json");
2487 written.save_to(&ctx_path).unwrap();
2488 let loaded = Context::load_from(&ctx_path);
2489 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
2490 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
2491 assert!(labels2.is_some());
2492 assert!(params2.is_some());
2493 }
2494
2495 #[test]
2498 fn apply_context_missing_file_all_none() {
2499 let dir = tempfile::tempdir().unwrap();
2500 let missing_path = dir.path().join(".visdom").join("context.json");
2501 let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
2503 assert!(flow_id.is_none(), "flow_id should be None");
2504 assert!(labels.is_none(), "labels should be None");
2505 assert!(params.is_none(), "params should be None");
2506 }
2507
2508 #[test]
2511 fn apply_context_empty_collections_are_none() {
2512 let ctx = EffectiveContext {
2513 flow_id: None,
2514 labels: vec![],
2515 params: BTreeMap::new(),
2516 };
2517 let (flow_id, labels, params) = apply_context(ctx);
2518 assert!(flow_id.is_none());
2519 assert!(
2520 labels.is_none(),
2521 "empty labels should be None, not Some([])"
2522 );
2523 assert!(
2524 params.is_none(),
2525 "empty params should be None, not Some({{}})"
2526 );
2527 }
2528
2529 #[test]
2532 fn apply_context_flow_id_only() {
2533 let ctx = EffectiveContext {
2534 flow_id: Some("my-flow".to_string()),
2535 labels: vec![],
2536 params: BTreeMap::new(),
2537 };
2538 let (flow_id, labels, params) = apply_context(ctx);
2539 assert_eq!(flow_id, Some("my-flow".to_string()));
2540 assert!(labels.is_none());
2541 assert!(params.is_none());
2542 }
2543
2544 use crate::test_helpers::{add_worktree, init_git_repo};
2551
2552 #[test]
2555 fn resolve_session_paths_primary_checkout() {
2556 let tmp = tempfile::tempdir().unwrap();
2557 let repo = tmp.path().join("repo");
2558 std::fs::create_dir_all(&repo).unwrap();
2559 init_git_repo(&repo);
2560 std::fs::create_dir_all(repo.join(".visdom")).unwrap();
2562
2563 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
2564 let project_root = resolved.root;
2565
2566 assert_eq!(
2567 project_root.canonicalize().unwrap(),
2568 repo.canonicalize().unwrap(),
2569 "primary checkout: project_root must be repo root"
2570 );
2571 assert_eq!(
2572 session_dir.canonicalize().unwrap_or(session_dir.clone()),
2573 repo.join(".visdom")
2574 .join("sessions")
2575 .join("sess-primary-123"),
2576 "primary checkout: session_dir must be <repo>/.visdom/sessions/<id>/"
2577 );
2578 assert!(
2580 session_dir.starts_with(&repo),
2581 "session_dir must be under the primary repo root"
2582 );
2583 }
2584
2585 #[test]
2589 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
2590 let tmp = tempfile::tempdir().unwrap();
2591 let repo = tmp.path().join("repo");
2592 let wt = tmp.path().join("sibling-wt");
2594
2595 std::fs::create_dir_all(&repo).unwrap();
2596 init_git_repo(&repo);
2597 std::fs::create_dir_all(repo.join(".visdom")).unwrap();
2599 add_worktree(&repo, &wt);
2600
2601 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
2602 let project_root = resolved.root;
2603
2604 assert_eq!(
2606 project_root.canonicalize().unwrap(),
2607 repo.canonicalize().unwrap(),
2608 "sibling worktree: project_root must be primary repo root (not worktree dir)"
2609 );
2610 assert!(
2612 session_dir.starts_with(&repo),
2613 "sibling worktree: session_dir must be under the PRIMARY repo root"
2614 );
2615 assert!(
2616 !session_dir.starts_with(&wt),
2617 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
2618 );
2619 assert!(
2620 session_dir.ends_with(
2621 std::path::Path::new(".visdom")
2622 .join("sessions")
2623 .join("sess-sibling-456")
2624 ),
2625 "session_dir must end with .visdom/sessions/<session_id>"
2626 );
2627 }
2628
2629 #[test]
2632 fn resolve_session_paths_non_git_fallback() {
2633 let tmp = tempfile::tempdir().unwrap();
2634 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
2636 let project_root = resolved.root;
2637
2638 assert_eq!(
2639 project_root,
2640 tmp.path(),
2641 "non-git: project_root must fall back to hook_cwd"
2642 );
2643 assert_eq!(
2644 session_dir,
2645 tmp.path()
2646 .join(".visdom")
2647 .join("sessions")
2648 .join("sess-fallback-789"),
2649 "non-git: session_dir must be relative to the fallback root"
2650 );
2651 }
2652
2653 #[test]
2658 fn origin_marker_written_in_session_dir() {
2659 let tmp = tempfile::tempdir().unwrap();
2660 let repo = tmp.path().join("repo");
2661 std::fs::create_dir_all(&repo).unwrap();
2662 init_git_repo(&repo);
2663
2664 let session_dir = repo.join(".visdom").join("sessions").join("test-sess-001");
2665 std::fs::create_dir_all(&session_dir).unwrap();
2666
2667 let hook_cwd = &repo;
2668 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
2669 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
2670
2671 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
2672 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
2673 assert_eq!(
2674 origin_content.trim(),
2675 expected.as_str(),
2676 "origin marker must contain the canonicalized worktree toplevel"
2677 );
2678 }
2679
2680 fn metadata(session_dir: &Path) -> serde_json::Value {
2681 serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
2682 .unwrap()
2683 }
2684
2685 #[test]
2686 fn record_transcript_path_writes_metadata_for_check() {
2687 let tmp = tempfile::tempdir().unwrap();
2688 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2689 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2690 }
2691
2692 #[test]
2693 fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
2694 let tmp = tempfile::tempdir().unwrap();
2695 std::fs::write(
2696 tmp.path().join("metadata.json"),
2697 r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
2698 )
2699 .unwrap();
2700 record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
2701 let m = metadata(tmp.path());
2702 assert_eq!(m["transcript_path"], "/t/new.jsonl");
2703 assert_eq!(m["model"], "m");
2704 let leftovers = std::fs::read_dir(tmp.path())
2705 .unwrap()
2706 .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
2707 .count();
2708 assert_eq!(leftovers, 0, "the temp file is renamed into place");
2709 }
2710
2711 #[test]
2712 fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
2713 let tmp = tempfile::tempdir().unwrap();
2714 record_transcript_path(tmp.path(), "").unwrap();
2715 assert!(!tmp.path().join("metadata.json").exists());
2716
2717 std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
2718 record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
2719 assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
2720 }
2721
2722 use crate::session_state::{RepoBinding, SessionState};
2725
2726 fn binding(id: &str) -> RepoBinding {
2727 RepoBinding {
2728 repo_id: id.into(),
2729 git_url: None,
2730 remote_id: None,
2731 codebase_name: None,
2732 updated_at: "t".into(),
2733 }
2734 }
2735
2736 #[test]
2739 fn resolve_stream_binding_uses_session_active_when_unbound() {
2740 let session = SessionState {
2741 active: Some(binding("session-repo")),
2742 subagents: HashMap::new(),
2743 ..Default::default()
2744 };
2745 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2746 assert_eq!(got.unwrap().repo_id, "session-repo");
2747 }
2748
2749 #[test]
2752 fn resolve_stream_binding_falls_back_to_bound_config() {
2753 let session = SessionState::default();
2754 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
2755 assert_eq!(got.unwrap().repo_id, "bound-repo");
2756 }
2757
2758 #[test]
2761 fn resolve_stream_binding_none_when_nothing_resolves() {
2762 let session = SessionState::default();
2763 let got = resolve_stream_binding(&session, "/wt/top", None, None);
2764 assert!(got.is_none());
2765 }
2766
2767 #[test]
2770 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
2771 let session = SessionState {
2772 active: Some(binding("session-repo")),
2773 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
2774 ..Default::default()
2775 };
2776 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
2777 assert_eq!(got.unwrap().repo_id, "subagent-repo");
2778 }
2779
2780 #[test]
2784 fn resolve_stream_binding_falls_back_to_user_default() {
2785 let session = SessionState::default();
2786 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
2787 assert_eq!(got.unwrap().repo_id, "userdef");
2788 }
2789
2790 #[test]
2793 fn resolve_stream_binding_prefers_bound_over_user_default() {
2794 let session = SessionState::default();
2795 let got = resolve_stream_binding(
2796 &session,
2797 "/wt/x",
2798 Some(binding("bound")),
2799 Some(binding("userdef")),
2800 );
2801 assert_eq!(got.unwrap().repo_id, "bound");
2802 }
2803
2804 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
2807 crate::session_state::RepoBinding {
2808 repo_id: repo_id.into(),
2809 git_url: None,
2810 remote_id: None,
2811 codebase_name: None,
2812 updated_at: String::new(),
2813 }
2814 }
2815
2816 #[test]
2820 fn attribution_falls_back_to_project_when_no_repo_binds() {
2821 let pid = uuid::Uuid::new_v4();
2822 assert_eq!(
2823 attribution_for(None, Some(pid)),
2824 Some(Attribution::ProjectOnly { project_id: pid })
2825 );
2826 }
2827
2828 #[test]
2830 fn attribution_is_none_when_neither_repo_nor_project_binds() {
2831 assert_eq!(attribution_for(None, None), None);
2832 }
2833
2834 #[test]
2837 fn attribution_uses_repo_with_no_project_overlay() {
2838 let repo = uuid::Uuid::new_v4().to_string();
2839 let b = binding_with(&repo);
2840 assert_eq!(
2841 attribution_for(Some(&b), None),
2842 Some(Attribution::Repo {
2843 repo_id: repo,
2844 project: None
2845 })
2846 );
2847 }
2848
2849 #[test]
2852 fn attribution_overlays_project_on_repo() {
2853 let repo = uuid::Uuid::new_v4().to_string();
2854 let pid = uuid::Uuid::new_v4();
2855 let b = binding_with(&repo);
2856 assert_eq!(
2857 attribution_for(Some(&b), Some(pid)),
2858 Some(Attribution::Repo {
2859 repo_id: repo,
2860 project: Some(pid)
2861 })
2862 );
2863 }
2864
2865 #[test]
2868 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2869 let pid = uuid::Uuid::new_v4();
2870 let b = binding_with("../../escape");
2871 assert_eq!(
2872 attribution_for(Some(&b), Some(pid)),
2873 Some(Attribution::ProjectOnly { project_id: pid })
2874 );
2875 }
2876
2877 #[test]
2880 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2881 let b = binding_with("../../escape");
2882 assert_eq!(attribution_for(Some(&b), None), None);
2883 }
2884
2885 #[test]
2890 fn pending_file_name_for_a_repo_is_unchanged() {
2891 let repo = uuid::Uuid::new_v4().to_string();
2892 assert_eq!(
2893 Attribution::Repo {
2894 repo_id: repo.clone(),
2895 project: Some(uuid::Uuid::new_v4())
2896 }
2897 .pending_file_name(),
2898 format!("pending-{repo}.jsonl")
2899 );
2900 }
2901
2902 #[test]
2905 fn pending_file_name_for_a_project_is_distinct() {
2906 let pid = uuid::Uuid::new_v4();
2907 assert_eq!(
2908 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2909 format!("pending-project-{pid}.jsonl")
2910 );
2911 }
2912
2913 #[test]
2916 fn binding_repo_id_is_valid_accepts_real_uuid() {
2917 assert!(binding_repo_id_is_valid(
2918 "550e8400-e29b-41d4-a716-446655440000"
2919 ));
2920 }
2921
2922 #[test]
2923 fn binding_repo_id_is_valid_rejects_path_traversal() {
2924 assert!(!binding_repo_id_is_valid("../evil"));
2925 }
2926
2927 #[test]
2928 fn binding_repo_id_is_valid_rejects_empty() {
2929 assert!(!binding_repo_id_is_valid(""));
2930 }
2931
2932 #[test]
2933 fn binding_repo_id_is_valid_rejects_non_uuid() {
2934 assert!(!binding_repo_id_is_valid("not-a-uuid"));
2935 }
2936
2937 #[test]
2940 fn stamp_agent_sets_tool_and_version() {
2941 use crate::agent::Agent;
2942 let mut req = StreamEventRequest {
2943 protocol_version: 1,
2944 tool: Some("claude-code".to_string()),
2945 event_type: StreamEventType::ToolUse,
2946 session_id: "s".into(),
2947 timestamp: chrono::Utc::now(),
2948 hook_event_name: None,
2949 tool_name: None,
2950 tool_use_id: None,
2951 tool_input: None,
2952 tool_response: None,
2953 tool_is_error: None,
2954 event_index: None,
2955 event_uuid: None,
2956 transcript_lines: None,
2957 transcript_offset: None,
2958 model: None,
2959 cwd: None,
2960 final_stats: None,
2961 flow_id: None,
2962 labels: None,
2963 params: None,
2964 billing_mode: None,
2965 };
2966 stamp_agent(&mut req, Agent::Codex);
2967 assert_eq!(req.tool.as_deref(), Some("codex"));
2968 assert_eq!(req.protocol_version, 2);
2969
2970 stamp_agent(&mut req, Agent::ClaudeCode);
2971 assert_eq!(req.tool.as_deref(), Some("claude-code"));
2972 assert_eq!(req.protocol_version, 1);
2973 }
2974
2975 fn repo_attr(repo_id: &str) -> Attribution {
2978 Attribution::Repo {
2979 repo_id: repo_id.into(),
2980 project: None,
2981 }
2982 }
2983
2984 #[test]
2985 fn pending_path_is_repo_scoped() {
2986 let dir = std::path::Path::new("/tmp/sess");
2987 assert_eq!(
2988 pending_path_for(dir, &repo_attr("repo-a")),
2989 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2990 );
2991 assert_ne!(
2992 pending_path_for(dir, &repo_attr("repo-a")),
2993 pending_path_for(dir, &repo_attr("repo-b")),
2994 );
2995 }
2996
2997 #[test]
3000 fn pending_path_for_a_project_never_collides_with_a_repo() {
3001 let dir = std::path::Path::new("/tmp/sess");
3002 let pid = uuid::Uuid::from_u128(9);
3003 assert_eq!(
3004 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
3005 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
3006 );
3007 assert_ne!(
3008 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
3009 pending_path_for(dir, &repo_attr(&pid.to_string())),
3010 );
3011 }
3012
3013 #[test]
3016 fn read_new_transcript_lines_empty_path_is_noop() {
3017 let dir = tempfile::tempdir().unwrap();
3021 let offset_path = dir.path().join(".stream_offset");
3022 let (lines, start_offset, end_offset) =
3023 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
3024 assert!(
3025 lines.is_empty(),
3026 "empty path must yield no transcript lines"
3027 );
3028 assert_eq!(start_offset, 0);
3029 assert_eq!(end_offset, 0);
3030 }
3031
3032 #[test]
3036 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
3037 let dir = tempfile::tempdir().unwrap();
3038 let transcript_path = dir.path().join("transcript.jsonl");
3039 let offset_path = dir.path().join(".stream_offset");
3040
3041 fs::write(
3042 &transcript_path,
3043 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
3044 )
3045 .unwrap();
3046
3047 let (lines, start_offset, end_offset) =
3048 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
3049 assert_eq!(lines.len(), 2);
3050 assert_eq!(start_offset, 0, "first read starts at byte 0");
3051 assert!(end_offset > 0);
3052
3053 fs::write(&offset_path, end_offset.to_string()).unwrap();
3054
3055 let mut f = OpenOptions::new()
3056 .append(true)
3057 .open(&transcript_path)
3058 .unwrap();
3059 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
3060 drop(f);
3061
3062 let (lines2, start_offset2, end_offset2) =
3063 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
3064 assert_eq!(lines2.len(), 1);
3065 assert_eq!(
3066 start_offset2, end_offset,
3067 "second read's start_offset must equal the first read's persisted end_offset"
3068 );
3069 assert!(end_offset2 > start_offset2);
3070 }
3071
3072 #[tokio::test]
3090 async fn capture_project_precedence_local_only() {
3091 use crate::session_state::{ProjectBinding, SessionState};
3092 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3093 let tmp = tempfile::tempdir().unwrap();
3094 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3095 _guard.set("XDG_CONFIG_HOME", tmp.path());
3096 _guard.set("HOME", tmp.path());
3097 _guard.remove("TRACEVAULT_PROJECT");
3098
3099 let pb = |id: &str| ProjectBinding {
3100 project_id: id.into(),
3101 project_name: "n".into(),
3102 updated_at: "".into(),
3103 forced_until: None,
3104 };
3105 let u = uuid::Uuid::from_u128;
3106 let s = SessionState {
3108 active_project: Some(pb(&u(2).to_string())),
3109 ..Default::default()
3110 };
3111 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(2)));
3112 let mut s = s;
3114 s.subagent_projects
3115 .insert("/wt".into(), pb(&u(1).to_string()));
3116 assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(1)));
3117 assert_eq!(capture_project(&s, Some("/other"), None), Some(u(2)));
3119 assert_eq!(capture_project(&SessionState::default(), None, None), None);
3121 let bad = SessionState {
3123 active_project: Some(pb("not-a-uuid")),
3124 ..Default::default()
3125 };
3126 assert_eq!(capture_project(&bad, None, None), None);
3127 let path = crate::user_project_default::default_project_path().unwrap();
3129 assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
3130 crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
3131 assert_eq!(
3132 capture_project(&SessionState::default(), None, None),
3133 Some(u(3))
3134 );
3135 }
3136
3137 #[test]
3148 fn capture_binding_preserves_forced_until_from_the_winning_tier() {
3149 use crate::session_state::{ProjectBinding, SessionState};
3150 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3151 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3152 _guard.remove("TRACEVAULT_PROJECT");
3153 let pid = uuid::Uuid::from_u128(2);
3154 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3155 let s = SessionState {
3156 active_project: Some(ProjectBinding {
3157 project_id: pid.to_string(),
3158 project_name: "n".into(),
3159 updated_at: "".into(),
3160 forced_until: Some(future.clone()),
3161 }),
3162 ..Default::default()
3163 };
3164 let got = capture_binding(&s, Some("/wt"), None).expect("session-active binding resolves");
3165 assert_eq!(got.forced_until, Some(future));
3166 }
3167
3168 #[test]
3173 fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
3174 let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
3178
3179 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3180 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3181
3182 _guard.set("TRACEVAULT_PROJECT", uuid);
3183 let got = env_project_binding().expect("uuid form is honoured");
3184 assert_eq!(got.project_id, uuid);
3185
3186 _guard.set("TRACEVAULT_PROJECT", "my-project");
3187 assert!(
3188 env_project_binding().is_none(),
3189 "a name is ignored on the network-free capture path"
3190 );
3191
3192 _guard.remove("TRACEVAULT_PROJECT");
3193 assert!(env_project_binding().is_none());
3194 }
3195
3196 fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
3204 crate::session_state::ProjectBinding {
3205 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
3206 project_name: "p".into(),
3207 updated_at: chrono::Utc::now().to_rfc3339(),
3208 forced_until: forced_until.map(str::to_string),
3209 }
3210 }
3211
3212 #[test]
3213 fn env_force_is_explicit_and_needs_no_expiry() {
3214 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3215 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3216 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3217
3218 assert_eq!(attribution_mode(None), AttributionMode::Explicit);
3219 }
3220
3221 #[test]
3222 fn absent_or_unrecognised_env_is_derived() {
3223 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3224 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3225
3226 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3227 assert_eq!(attribution_mode(None), AttributionMode::Derived);
3228
3229 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
3234 assert_eq!(attribution_mode(None), AttributionMode::Derived);
3235 }
3236
3237 #[test]
3243 fn live_binding_force_is_explicit_without_env() {
3244 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3245 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3246 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3247
3248 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3249 let binding = forced_binding(Some(&future));
3250
3251 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
3252 }
3253
3254 #[test]
3261 fn lapsed_binding_force_is_derived_without_env() {
3262 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3263 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3264 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3265
3266 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
3267 let binding = forced_binding(Some(&past));
3268
3269 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
3270 }
3271
3272 #[test]
3277 fn unparseable_forced_until_is_derived() {
3278 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3279 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3280 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3281
3282 let binding = forced_binding(Some("not-a-timestamp"));
3283
3284 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
3285 }
3286
3287 #[test]
3294 fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
3295 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3296 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3297 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3298
3299 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
3300 let binding = forced_binding(Some(&past));
3301
3302 assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
3303 }
3304
3305 #[tokio::test]
3318 async fn session_scoped_force_is_honoured_on_the_wire() {
3319 use crate::session_state::{ProjectBinding, SessionState};
3320
3321 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3322 let tmp = tempfile::tempdir().unwrap();
3323 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3324 _guard.set("XDG_CONFIG_HOME", tmp.path());
3328 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3329 _guard.remove("TRACEVAULT_PROJECT");
3333
3334 let pid = uuid::Uuid::from_u128(321);
3335 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3336 let session = SessionState {
3337 active_project: Some(ProjectBinding {
3338 project_id: pid.to_string(),
3339 project_name: "proj".into(),
3340 updated_at: "".into(),
3341 forced_until: Some(future),
3342 }),
3343 ..Default::default()
3344 };
3345 let capture_binding = capture_binding(&session, None, None);
3346
3347 let resp = ok_stream_response();
3348 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3349 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3350 let req = sample_stream_event_request();
3351 let mut warned = false;
3352
3353 let got = send_stream_event(
3354 &client,
3355 &Attribution::ProjectOnly { project_id: pid },
3356 attribution_force(capture_binding.as_ref()),
3357 &req,
3358 &mut warned,
3359 )
3360 .await
3361 .expect("send_stream_event must succeed");
3362 assert_eq!(got.status, "accepted");
3363
3364 let captured = rx
3365 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3366 .expect("no request captured");
3367 assert!(
3368 captured
3369 .to_lowercase()
3370 .contains("x-tracevault-project-attribution: explicit"),
3371 "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
3372 );
3373 }
3374
3375 #[test]
3384 fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
3385 use crate::session_state::{ProjectBinding, SessionState};
3386
3387 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3388 let tmp = tempfile::tempdir().unwrap();
3389 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3390 _guard.set("XDG_CONFIG_HOME", tmp.path());
3391 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3392
3393 let project_a = uuid::Uuid::from_u128(1);
3394 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
3395 crate::user_project_default::save(&ProjectBinding {
3396 project_id: project_a.to_string(),
3397 project_name: "a".into(),
3398 updated_at: chrono::Utc::now().to_rfc3339(),
3399 forced_until: Some(future),
3400 })
3401 .unwrap();
3402
3403 let project_b = uuid::Uuid::from_u128(2);
3404 _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
3405
3406 let capture_binding = capture_binding(&SessionState::default(), None, None);
3407 assert_eq!(
3408 capture_binding.as_ref().map(|b| b.project_id.as_str()),
3409 Some(project_b.to_string()).as_deref(),
3410 "TRACEVAULT_PROJECT must outrank the user-level default"
3411 );
3412
3413 assert_eq!(
3414 attribution_mode(capture_binding.as_ref()),
3415 AttributionMode::Derived,
3416 "a force on the user-default project must not leak onto a DIFFERENT, \
3417 higher-precedence project that never asked to be forced"
3418 );
3419 }
3420
3421 use std::io::BufReader;
3424 use std::net::TcpListener;
3425 use std::sync::mpsc;
3426 use std::thread;
3427 use std::time::{Duration, Instant};
3428
3429 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
3434
3435 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
3440 let deadline = Instant::now() + ACCEPT_DEADLINE;
3441 loop {
3442 match listener.accept() {
3443 Ok((stream, _)) => {
3444 let _ = stream.set_nonblocking(false);
3449 return Some(stream);
3450 }
3451 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
3452 if Instant::now() >= deadline {
3453 return None;
3454 }
3455 thread::sleep(Duration::from_millis(20));
3456 }
3457 Err(_) => return None,
3458 }
3459 }
3460 }
3461
3462 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
3466
3467 fn capture_request_and_respond(
3487 stream: std::net::TcpStream,
3488 tx: &mpsc::Sender<String>,
3489 response: &str,
3490 ) {
3491 let mut reader = BufReader::new(stream);
3492 let mut captured = String::new();
3493 let _ = reader.read_line(&mut captured);
3494 loop {
3495 let mut header = String::new();
3496 if reader.read_line(&mut header).unwrap_or(0) == 0 {
3497 break;
3498 }
3499 if header.trim().is_empty() {
3500 break;
3501 }
3502 captured.push_str(&header);
3503 }
3504 let _ = tx.send(captured);
3505 let mut stream = reader.into_inner();
3506 let _ = stream.write_all(response.as_bytes());
3507 let _ = stream.flush();
3508 }
3509
3510 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
3515 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3516 listener.set_nonblocking(true).unwrap();
3517 let addr = listener.local_addr().unwrap();
3518 let (tx, rx) = mpsc::channel();
3519 thread::spawn(move || {
3520 if let Some(stream) = accept_with_deadline(&listener) {
3521 capture_request_and_respond(stream, &tx, response);
3522 }
3523 });
3524 (format!("http://{addr}"), rx)
3525 }
3526
3527 fn ok_stream_response() -> String {
3528 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
3529 session_db_id: uuid::Uuid::nil(),
3530 event_db_id: Some(uuid::Uuid::nil()),
3531 status: "accepted".to_string(),
3532 })
3533 .unwrap();
3534 format!(
3535 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3536 body.len(),
3537 body
3538 )
3539 }
3540
3541 fn sample_stream_event_request() -> StreamEventRequest {
3542 StreamEventRequest {
3543 protocol_version: 2,
3544 tool: Some("claude-code".to_string()),
3545 event_type: StreamEventType::ToolUse,
3546 session_id: "sess-1".into(),
3547 timestamp: chrono::Utc::now(),
3548 hook_event_name: Some("PostToolUse".into()),
3549 tool_name: None,
3550 tool_use_id: None,
3551 tool_input: None,
3552 tool_response: None,
3553 tool_is_error: None,
3554 event_index: None,
3555 event_uuid: None,
3556 transcript_lines: None,
3557 transcript_offset: None,
3558 model: None,
3559 cwd: None,
3560 final_stats: None,
3561 flow_id: None,
3562 labels: None,
3563 params: None,
3564 billing_mode: None,
3565 }
3566 }
3567
3568 #[tokio::test]
3573 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
3574 use crate::session_state::{ProjectBinding, SessionState};
3575
3576 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3580 let tmp = tempfile::tempdir().unwrap();
3581 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3582 _guard.set("XDG_CONFIG_HOME", tmp.path());
3583 _guard.remove("TRACEVAULT_PROJECT");
3588 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3589
3590 let pid = uuid::Uuid::from_u128(99);
3591 let session = SessionState {
3592 active_project: Some(ProjectBinding {
3593 project_id: pid.to_string(),
3594 project_name: "proj".into(),
3595 updated_at: "".into(),
3596 forced_until: None,
3597 }),
3598 ..Default::default()
3599 };
3600 let capture_binding = capture_binding(&session, None, None);
3601 let capture_pid = capture_binding
3602 .as_ref()
3603 .and_then(crate::resolution::capture_project_id);
3604 assert_eq!(capture_pid, Some(pid));
3605
3606 let resp = ok_stream_response();
3607 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3608 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3609 let req = sample_stream_event_request();
3610
3611 let mut warned = false;
3612 let got = send_stream_event(
3613 &client,
3614 &Attribution::Repo {
3615 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3616 project: capture_pid,
3617 },
3618 attribution_force(capture_binding.as_ref()),
3619 &req,
3620 &mut warned,
3621 )
3622 .await
3623 .expect("send_stream_event must succeed");
3624 assert_eq!(got.status, "accepted");
3625
3626 let line = rx
3627 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3628 .expect("no request captured");
3629 assert!(
3630 line.starts_with(&format!(
3631 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
3632 )),
3633 "an active project binding must route to the project-scoped endpoint, got: {line}"
3634 );
3635 assert!(
3641 line.to_lowercase()
3642 .contains("x-tracevault-project-attribution: derived"),
3643 "got: {line}"
3644 );
3645 }
3646
3647 #[tokio::test]
3652 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
3653 use crate::session_state::SessionState;
3654
3655 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3656 let tmp = tempfile::tempdir().unwrap();
3657 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3658 _guard.set("XDG_CONFIG_HOME", tmp.path());
3663 _guard.remove("TRACEVAULT_PROJECT");
3664
3665 let capture_binding = capture_binding(&SessionState::default(), None, None);
3666 assert_eq!(capture_binding, None);
3667
3668 let resp = ok_stream_response();
3669 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3670 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3671 let req = sample_stream_event_request();
3672
3673 let mut warned = false;
3674 let got = send_stream_event(
3675 &client,
3676 &Attribution::Repo {
3677 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3678 project: None,
3679 },
3680 attribution_force(capture_binding.as_ref()),
3681 &req,
3682 &mut warned,
3683 )
3684 .await
3685 .expect("send_stream_event must succeed");
3686 assert_eq!(got.status, "accepted");
3687
3688 let line = rx
3689 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3690 .expect("no request captured");
3691 assert!(
3692 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
3693 "no binding must fall back to the repo-scoped endpoint, got: {line}"
3694 );
3695 }
3696
3697 fn spawn_n_capturing_requests(
3708 responses: Vec<&'static str>,
3709 ) -> (String, mpsc::Receiver<String>) {
3710 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3711 listener.set_nonblocking(true).unwrap();
3712 let addr = listener.local_addr().unwrap();
3713 let (tx, rx) = mpsc::channel();
3714 thread::spawn(move || {
3715 for response in responses {
3716 let Some(stream) = accept_with_deadline(&listener) else {
3721 break;
3722 };
3723 capture_request_and_respond(stream, &tx, response);
3724 }
3725 });
3730 (format!("http://{addr}"), rx)
3731 }
3732
3733 #[tokio::test]
3740 async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
3741 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
3742 let resp_400 = format!(
3743 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3744 body_400.len(),
3745 body_400
3746 );
3747 let resp_200 = ok_stream_response();
3748
3749 let (base, rx) = spawn_n_capturing_requests(vec![
3750 Box::leak(resp_400.into_boxed_str()),
3751 Box::leak(resp_200.into_boxed_str()),
3752 ]);
3753 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3754 let req = sample_stream_event_request();
3755 let pid = uuid::Uuid::from_u128(42);
3756
3757 let mut warned = false;
3758 let err = send_stream_event(
3759 &client,
3760 &Attribution::Repo {
3761 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3762 project: Some(pid),
3763 },
3764 attribution_force(None),
3765 &req,
3766 &mut warned,
3767 )
3768 .await
3769 .expect_err("a refused declared project must be an error, not a silent fallback");
3770 assert!(
3771 err.to_string().contains("400"),
3772 "propagated error must reflect the status, got: {err}"
3773 );
3774 assert!(
3775 warned,
3776 "the refusal must be printed (gated on `warned`) so it is visible"
3777 );
3778
3779 let first = rx
3780 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3781 .expect("no first request captured");
3782 assert!(
3783 first.contains(&format!("/projects/{pid}/stream")),
3784 "first request must hit the project-scoped endpoint, got: {first}"
3785 );
3786 assert!(
3787 first.contains("repo_id="),
3788 "first request must carry repo_id, got: {first}"
3789 );
3790
3791 assert!(
3792 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3793 "no second (repo-scoped fallback) request must be sent"
3794 );
3795 }
3796
3797 #[tokio::test]
3800 async fn send_stream_event_errors_on_403_without_fallback() {
3801 let body_403 = "forbidden";
3802 let resp_403 = format!(
3803 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3804 body_403.len(),
3805 body_403
3806 );
3807 let resp_200 = ok_stream_response();
3808
3809 let (base, rx) = spawn_n_capturing_requests(vec![
3810 Box::leak(resp_403.into_boxed_str()),
3811 Box::leak(resp_200.into_boxed_str()),
3812 ]);
3813 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3814 let req = sample_stream_event_request();
3815 let pid = uuid::Uuid::from_u128(43);
3816
3817 let mut warned = false;
3818 let err = send_stream_event(
3819 &client,
3820 &Attribution::Repo {
3821 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3822 project: Some(pid),
3823 },
3824 attribution_force(None),
3825 &req,
3826 &mut warned,
3827 )
3828 .await
3829 .expect_err("a refused declared project must be an error, not a silent fallback");
3830 assert!(
3831 err.to_string().contains("403"),
3832 "propagated error must reflect the status, got: {err}"
3833 );
3834 assert!(
3835 warned,
3836 "the refusal must be printed (gated on `warned`) so it is visible"
3837 );
3838
3839 let first = rx
3840 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3841 .expect("no first request captured");
3842 assert!(
3843 first.contains(&format!("/projects/{pid}/stream")),
3844 "first request must hit the project-scoped endpoint, got: {first}"
3845 );
3846 assert!(
3847 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3848 "no second (repo-scoped fallback) request must be sent"
3849 );
3850 }
3851
3852 #[tokio::test]
3857 async fn refused_error_is_printed_once_per_invocation() {
3858 let body_400 = "not a member";
3859 let resp_400 = || {
3860 format!(
3861 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3862 body_400.len(),
3863 body_400
3864 )
3865 };
3866 let (base, _rx) = spawn_n_capturing_requests(vec![
3867 Box::leak(resp_400().into_boxed_str()),
3868 Box::leak(resp_400().into_boxed_str()),
3869 ]);
3870 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3871 let req = sample_stream_event_request();
3872 let pid = uuid::Uuid::from_u128(44);
3873 let attribution = Attribution::Repo {
3874 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3875 project: Some(pid),
3876 };
3877
3878 let mut warned = false;
3879 assert!(
3880 send_stream_event(
3881 &client,
3882 &attribution,
3883 attribution_force(None),
3884 &req,
3885 &mut warned
3886 )
3887 .await
3888 .is_err(),
3889 "a refused declared project must be an error"
3890 );
3891 assert!(warned, "the flag must be set after the first refusal");
3892
3893 assert!(
3894 send_stream_event(
3895 &client,
3896 &attribution,
3897 attribution_force(None),
3898 &req,
3899 &mut warned
3900 )
3901 .await
3902 .is_err(),
3903 "a second refusal must also be an error"
3904 );
3905 assert!(warned, "the flag stays set across the shared invocation");
3906 }
3907
3908 #[tokio::test]
3920 async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3921 let body_403 = "forbidden";
3922 let resp_403 = format!(
3923 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3924 body_403.len(),
3925 body_403
3926 );
3927 let resp_200 = ok_stream_response();
3928
3929 let (base, rx) = spawn_n_capturing_requests(vec![
3930 Box::leak(resp_403.into_boxed_str()),
3931 Box::leak(resp_200.into_boxed_str()),
3932 ]);
3933 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3934 let req = sample_stream_event_request();
3935 let pid = uuid::Uuid::from_u128(42);
3936
3937 let forced = crate::session_state::ProjectBinding {
3940 project_id: pid.to_string(),
3941 project_name: "forced".into(),
3942 updated_at: "".into(),
3943 forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3944 };
3945
3946 let mut warned = false;
3947 let err = send_stream_event(
3948 &client,
3949 &Attribution::Repo {
3950 repo_id: "11111111-1111-1111-1111-111111111111".into(),
3951 project: Some(pid),
3952 },
3953 attribution_force(Some(&forced)),
3954 &req,
3955 &mut warned,
3956 )
3957 .await
3958 .expect_err("a refused force must be an error, not a silent fallback");
3959 assert!(
3960 err.to_string().contains("403"),
3961 "propagated error must reflect the status, got: {err}"
3962 );
3963 assert!(warned, "the refusal must be printed exactly once");
3964
3965 let first = rx
3966 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3967 .expect("no first request captured");
3968 assert!(
3969 first.contains(&format!("/projects/{pid}/stream")),
3970 "first request must hit the project-scoped endpoint, got: {first}"
3971 );
3972 assert!(
3973 first
3974 .to_lowercase()
3975 .contains("x-tracevault-project-attribution: explicit"),
3976 "the refused send must have DECLARED explicit — this is the mode \
3977 `refused_error` is handed: {first}"
3978 );
3979
3980 assert!(
3981 rx.recv_timeout(Duration::from_millis(500)).is_err(),
3982 "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3983 );
3984 }
3985
3986 #[tokio::test]
3995 async fn send_stream_event_project_only_omits_repo_id() {
3996 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3997 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3998 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3999
4000 let resp = ok_stream_response();
4001 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
4002 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4003 let req = sample_stream_event_request();
4004 let pid = uuid::Uuid::from_u128(11);
4005
4006 let mut warned = false;
4007 let got = send_stream_event(
4008 &client,
4009 &Attribution::ProjectOnly { project_id: pid },
4010 attribution_force(None),
4011 &req,
4012 &mut warned,
4013 )
4014 .await
4015 .expect("a repo-less project send must succeed");
4016 assert_eq!(got.status, "accepted");
4017
4018 let line = rx
4019 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4020 .expect("no request captured");
4021 assert!(
4022 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
4023 "expected a bare project path with no query string, got: {line}"
4024 );
4025 assert!(
4026 line.to_lowercase()
4027 .contains("x-tracevault-project-attribution: derived"),
4028 "with no forced binding, the header must declare `derived`, got: {line}"
4029 );
4030 assert!(
4031 !warned,
4032 "a repo-less send has no fallback and must not warn about one"
4033 );
4034 }
4035
4036 #[tokio::test]
4043 async fn send_stream_event_project_only_buffers_on_scoping_4xx() {
4044 let body = "no such project";
4045 let resp_404 = format!(
4046 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4047 body.len(),
4048 body
4049 );
4050 let (base, rx) = spawn_n_capturing_requests(vec![
4057 Box::leak(resp_404.clone().into_boxed_str()),
4058 Box::leak(resp_404.into_boxed_str()),
4059 ]);
4060 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4061 let req = sample_stream_event_request();
4062 let pid = uuid::Uuid::from_u128(12);
4063
4064 let mut warned = false;
4065 let err = send_stream_event(
4066 &client,
4067 &Attribution::ProjectOnly { project_id: pid },
4068 attribution_force(None),
4069 &req,
4070 &mut warned,
4071 )
4072 .await
4073 .expect_err("a refused repo-less send must propagate so the caller buffers it");
4074 assert_eq!(
4075 deterministic_client_error_kind(err.as_ref()),
4076 Some(ClientErrorKind::Scoping),
4077 "the original 404 must propagate unchanged, got: {err}"
4078 );
4079 assert!(warned, "the refusal is printed (once per invocation)");
4080
4081 let first = rx
4082 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4083 .expect("no request captured");
4084 assert!(
4085 first.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
4086 "must hit the bare project-scoped endpoint, got: {first}"
4087 );
4088 assert!(
4089 rx.recv_timeout(Duration::from_millis(500)).is_err(),
4090 "a repo-less send must make exactly one request — no fallback exists"
4091 );
4092 }
4093
4094 #[test]
4098 fn refused_project_only_error_wording() {
4099 let pid = uuid::Uuid::from_u128(0x55);
4100 let scoping =
4101 refused_project_only_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
4102 assert!(scoping.starts_with("tracevault: error:"), "{scoping}");
4103 assert!(scoping.contains(&pid.to_string()), "{scoping}");
4104 assert!(scoping.contains("queued"), "{scoping}");
4105 assert!(!scoping.contains("DROPPED"), "{scoping}");
4106 assert!(!scoping.contains("this repo"), "{scoping}");
4107 assert!(scoping.contains("tracevault repo switch"), "{scoping}");
4108
4109 let forbidden = refused_project_only_error(
4110 pid,
4111 &ClientErrorKind::Forbidden,
4112 AttributionForce::default(),
4113 );
4114 assert!(forbidden.contains("(403)"), "{forbidden}");
4115 assert!(forbidden.contains("queued"), "{forbidden}");
4116 assert!(!forbidden.contains("FORCE"), "derived send: {forbidden}");
4117
4118 let forced = AttributionForce {
4119 env: true,
4120 binding: false,
4121 };
4122 let explicit = refused_project_only_error(pid, &ClientErrorKind::Forbidden, forced);
4123 assert!(
4124 explicit.contains("FORCE itself"),
4125 "an explicit 403 must name the force, like the repo-scoped line: {explicit}"
4126 );
4127 assert!(
4128 !refused_project_only_error(pid, &ClientErrorKind::Scoping, forced)
4129 .contains("FORCE itself"),
4130 "a Scoping refusal never ran the force gate"
4131 );
4132 }
4133
4134 #[test]
4137 fn recording_line_names_each_attribution_shape() {
4138 let pid = uuid::Uuid::from_u128(0x99);
4139 let repo = "11111111-1111-1111-1111-111111111111".to_string();
4140 let only = recording_line(Some(&Attribution::ProjectOnly { project_id: pid }));
4141 assert!(only.starts_with("recording: project "), "{only}");
4142 assert!(
4143 only.contains(&pid.to_string()) && only.contains("no repo"),
4144 "{only}"
4145 );
4146 let both = recording_line(Some(&Attribution::Repo {
4147 repo_id: repo.clone(),
4148 project: Some(pid),
4149 }));
4150 assert!(
4151 both.contains(&repo) && both.contains(&pid.to_string()),
4152 "{both}"
4153 );
4154 let deduced = recording_line(Some(&Attribution::Repo {
4155 repo_id: repo.clone(),
4156 project: None,
4157 }));
4158 assert!(
4159 deduced.contains(&repo) && deduced.contains("deduces"),
4160 "{deduced}"
4161 );
4162 let none = recording_line(None);
4163 assert!(none.starts_with("recording: nothing"), "{none}");
4164 }
4165
4166 fn repo_binding(id: &str) -> crate::session_state::RepoBinding {
4167 crate::session_state::RepoBinding {
4168 repo_id: id.into(),
4169 git_url: None,
4170 remote_id: None,
4171 codebase_name: None,
4172 updated_at: "t".into(),
4173 }
4174 }
4175
4176 fn inferring_session(
4178 pid: uuid::Uuid,
4179 checkout: &str,
4180 repo: &str,
4181 ) -> crate::session_state::SessionState {
4182 let mut state = crate::session_state::SessionState {
4183 active_project: Some(crate::session_state::ProjectBinding {
4184 project_id: pid.to_string(),
4185 project_name: "p".into(),
4186 updated_at: "t".into(),
4187 forced_until: None,
4188 }),
4189 ..Default::default()
4190 };
4191 state.inferred_repos.insert(
4192 checkout.into(),
4193 crate::session_state::InferredRepo {
4194 project_id: pid.to_string(),
4195 retry_after: None,
4196 repo: Some(repo_binding(repo)),
4197 },
4198 );
4199 state
4200 }
4201
4202 #[test]
4205 fn attribution_with_inference_never_overrides_a_binding() {
4206 let pid = uuid::Uuid::from_u128(0x1258);
4207 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
4208 let inferred = repo_binding("22222222-2222-2222-2222-222222222222");
4209 let repo = |id: &str| Attribution::Repo {
4210 repo_id: id.into(),
4211 project: Some(pid),
4212 };
4213
4214 assert_eq!(
4215 attribution_with_inference(None, Some(pid), Some(&inferred)),
4216 Some(repo(&inferred.repo_id))
4217 );
4218 assert_eq!(
4219 attribution_with_inference(Some(&bound), Some(pid), Some(&inferred)),
4220 Some(repo(&bound.repo_id))
4221 );
4222 let corrupt = repo_binding("not-a-uuid");
4225 assert_eq!(
4226 attribution_with_inference(Some(&corrupt), Some(pid), Some(&inferred)),
4227 Some(Attribution::ProjectOnly { project_id: pid })
4228 );
4229 assert_eq!(
4231 attribution_with_inference(None, None, Some(&inferred)),
4232 None
4233 );
4234 assert_eq!(
4235 attribution_with_inference(None, Some(pid), Some(&corrupt)),
4236 Some(Attribution::ProjectOnly { project_id: pid })
4237 );
4238 }
4239
4240 #[test]
4243 fn recording_attribution_labels_an_inferred_repo() {
4244 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
4246 let mut env = crate::test_helpers::EnvVarGuard::new();
4247 env.remove("TRACEVAULT_PROJECT");
4248 env.remove("VISDOM_PROJECT");
4249 let pid = uuid::Uuid::from_u128(0x1258);
4250 let repo = "22222222-2222-2222-2222-222222222222";
4251 let state = inferring_session(pid, "/umbrella/child", repo);
4252
4253 let here = recording_attribution_for(&state, "/umbrella/child", None, None, None);
4254 assert_eq!(
4255 here.attribution,
4256 Some(Attribution::Repo {
4257 repo_id: repo.into(),
4258 project: Some(pid)
4259 })
4260 );
4261 assert_eq!(here.inferred_from.as_deref(), Some("/umbrella/child"));
4262 let line = recording_line_for(&here);
4263 assert!(
4264 line.contains(repo) && line.contains("inferred from the checkout /umbrella/child"),
4265 "{line}"
4266 );
4267
4268 let elsewhere = recording_attribution_for(&state, "/umbrella", None, None, None);
4269 assert_eq!(
4270 elsewhere.attribution,
4271 Some(Attribution::ProjectOnly { project_id: pid })
4272 );
4273 assert_eq!(elsewhere.inferred_from, None);
4274 assert_eq!(
4275 recording_line_for(&elsewhere),
4276 recording_line(elsewhere.attribution.as_ref())
4277 );
4278
4279 let bound = repo_binding("11111111-1111-1111-1111-111111111111");
4281 let explicit =
4282 recording_attribution_for(&state, "/umbrella/child", Some(bound.clone()), None, None);
4283 assert_eq!(
4284 explicit.attribution,
4285 Some(Attribution::Repo {
4286 repo_id: bound.repo_id,
4287 project: Some(pid)
4288 })
4289 );
4290 assert_eq!(explicit.inferred_from, None);
4291
4292 let mut from_config = state.clone();
4295 from_config.active_project = None;
4296 let workspace = crate::session_state::ProjectBinding {
4297 project_id: pid.to_string(),
4298 project_name: String::new(),
4299 updated_at: String::new(),
4300 forced_until: None,
4301 };
4302 let via_config =
4303 recording_attribution_for(&from_config, "/umbrella/child", None, None, Some(workspace));
4304 assert_eq!(via_config.inferred_from.as_deref(), Some("/umbrella/child"));
4305 }
4306
4307 #[test]
4308 fn adopted_project_queue_only_for_the_same_project() {
4309 let dir = Path::new("/tmp/sess");
4310 let pid = uuid::Uuid::from_u128(0x77);
4311 let repo_id = "11111111-1111-1111-1111-111111111111".to_string();
4312 assert_eq!(
4313 adopted_project_queue(
4314 dir,
4315 &Attribution::Repo {
4316 repo_id: repo_id.clone(),
4317 project: Some(pid),
4318 }
4319 ),
4320 Some(dir.join(format!("pending-project-{pid}.jsonl")))
4321 );
4322 assert_eq!(
4323 adopted_project_queue(
4324 dir,
4325 &Attribution::Repo {
4326 repo_id,
4327 project: None,
4328 }
4329 ),
4330 None,
4331 "with no declared project the server deduces one; adopting would re-attribute"
4332 );
4333 assert_eq!(
4334 adopted_project_queue(dir, &Attribution::ProjectOnly { project_id: pid }),
4335 None,
4336 "a project-only target already drains its own queue"
4337 );
4338 }
4339
4340 #[tokio::test]
4344 async fn send_stream_event_project_only_buffers_on_403() {
4345 let body = "forbidden";
4346 let resp_403 = format!(
4347 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4348 body.len(),
4349 body
4350 );
4351 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
4352 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4353 let req = sample_stream_event_request();
4354
4355 let mut warned = false;
4356 let err = send_stream_event(
4357 &client,
4358 &Attribution::ProjectOnly {
4359 project_id: uuid::Uuid::from_u128(13),
4360 },
4361 attribution_force(None),
4362 &req,
4363 &mut warned,
4364 )
4365 .await
4366 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
4367 assert!(
4368 err.to_string().contains("403"),
4369 "propagated error must reflect the status, got: {err}"
4370 );
4371 }
4372
4373 #[tokio::test]
4378 async fn send_stream_event_does_not_fall_back_on_transient_503() {
4379 let body_503 = "internal error";
4380 let resp_503 = format!(
4381 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
4382 body_503.len(),
4383 body_503
4384 );
4385 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
4386 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4387 let req = sample_stream_event_request();
4388 let pid = uuid::Uuid::from_u128(7);
4389
4390 let mut warned = false;
4391 let err = send_stream_event(
4392 &client,
4393 &Attribution::Repo {
4394 repo_id: "11111111-1111-1111-1111-111111111111".into(),
4395 project: Some(pid),
4396 },
4397 attribution_force(None),
4398 &req,
4399 &mut warned,
4400 )
4401 .await
4402 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
4403 assert!(
4404 err.to_string().contains("503"),
4405 "propagated error must reflect the transient status, got: {err}"
4406 );
4407 assert!(
4408 deterministic_client_error_kind(err.as_ref()).is_none(),
4409 "a 503 must not be classified as a deterministic client error"
4410 );
4411
4412 let first = rx
4413 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
4414 .expect("no request captured");
4415 assert!(
4416 first.contains(&format!("/projects/{pid}/stream")),
4417 "must hit the project-scoped endpoint, got: {first}"
4418 );
4419
4420 assert!(
4427 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
4428 "no second (fallback) request should have been sent for a transient error"
4429 );
4430 }
4431
4432 #[test]
4436 fn a_403_is_classified_apart_from_the_scoping_statuses() {
4437 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
4438 assert_eq!(
4439 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
4440 Some(ClientErrorKind::Forbidden)
4441 );
4442 for scoping in [
4443 "Stream failed (400 Bad Request): {}",
4444 "Stream failed (404 Not Found): {}",
4445 "Stream failed (409 Conflict): {}",
4446 ] {
4447 assert_eq!(
4448 deterministic_client_error_kind(err(scoping).as_ref()),
4449 Some(ClientErrorKind::Scoping),
4450 "{scoping}"
4451 );
4452 }
4453 for transient in [
4456 "Stream failed (401 Unauthorized): {}",
4457 "Stream failed (503 Service Unavailable): {}",
4458 "error sending request for url (http://x/stream)",
4459 ] {
4460 assert_eq!(
4461 deterministic_client_error_kind(err(transient).as_ref()),
4462 None,
4463 "{transient}"
4464 );
4465 }
4466 }
4467
4468 #[test]
4473 fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
4474 let pid = uuid::Uuid::from_u128(7);
4475
4476 let forbidden = refused_error(
4477 pid,
4478 &ClientErrorKind::Forbidden,
4479 AttributionForce::default(),
4480 );
4481 assert!(forbidden.contains("403"), "{forbidden}");
4482 assert!(
4483 forbidden.contains("no `tracevault` grant in Control Plane"),
4484 "must offer the missing-role explanation: {forbidden}"
4485 );
4486 assert!(
4487 forbidden.contains("no `Operator` role on it"),
4488 "must still offer the project explanation: {forbidden}"
4489 );
4490 assert!(
4491 forbidden.starts_with("tracevault: error:"),
4492 "a refusal is an error, not a warning: {forbidden}"
4493 );
4494 assert!(forbidden.contains(&pid.to_string()));
4495
4496 let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
4499 assert!(scoping.contains("project switch"), "{scoping}");
4500 assert!(
4501 !scoping.contains("`tracevault` grant"),
4502 "the scoping case must not mention the `tracevault` grant: {scoping}"
4503 );
4504
4505 for s in [&forbidden, &scoping] {
4506 assert!(s.contains("--user"), "must name the --user fix: {s}");
4509 assert!(
4510 s.contains("user_project.toml"),
4511 "must name the machine-wide default's file: {s}"
4512 );
4513 assert!(
4514 !s.contains("repo deduction"),
4515 "must never describe re-attribution to another project: {s}"
4516 );
4517 assert!(
4518 !s.contains("Attributing via"),
4519 "must never claim the event was re-attributed: {s}"
4520 );
4521 }
4522 }
4523
4524 #[test]
4535 fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
4536 let pid = uuid::Uuid::from_u128(7);
4537
4538 let explicit = refused_error(
4539 pid,
4540 &ClientErrorKind::Forbidden,
4541 AttributionForce {
4542 env: false,
4543 binding: true,
4544 },
4545 );
4546 assert!(
4547 explicit.contains("FORCE"),
4548 "the refusal of the force itself must be named: {explicit}"
4549 );
4550 assert!(
4551 explicit.contains("Operator"),
4552 "must name the grant forcing requires: {explicit}"
4553 );
4554 assert!(
4555 explicit.contains("Control Plane"),
4556 "must name the identity forcing requires: {explicit}"
4557 );
4558 assert!(
4562 explicit.contains("`tracevault` grant")
4563 && explicit.contains("no `Operator` role on it"),
4564 "the membership causes must still be named: {explicit}"
4565 );
4566 assert!(
4569 !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
4570 "must never claim the event was re-attributed: {explicit}"
4571 );
4572
4573 let derived = refused_error(
4578 pid,
4579 &ClientErrorKind::Forbidden,
4580 AttributionForce::default(),
4581 );
4582 assert!(
4583 !derived.contains("FORCE"),
4584 "a `derived` send never forced anything: {derived}"
4585 );
4586 }
4587
4588 #[test]
4593 fn an_explicit_scoping_failure_does_not_blame_the_force() {
4594 let pid = uuid::Uuid::from_u128(7);
4595 let scoping = refused_error(
4596 pid,
4597 &ClientErrorKind::Scoping,
4598 AttributionForce {
4599 env: true,
4600 binding: true,
4601 },
4602 );
4603 assert!(!scoping.contains("FORCE"), "{scoping}");
4604 assert_eq!(
4605 scoping,
4606 refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
4607 "the scoping wording does not depend on the mode"
4608 );
4609 }
4610
4611 #[test]
4631 fn the_403_remediation_names_the_force_source_actually_in_effect() {
4632 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
4633 let mut _guard = crate::test_helpers::EnvVarGuard::new();
4634 let pid = uuid::Uuid::from_u128(7);
4635 let live = forced_binding(Some(
4636 &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
4637 ));
4638 let never_forced = forced_binding(None);
4639
4640 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4644 let env_only = refused_error(
4645 pid,
4646 &ClientErrorKind::Forbidden,
4647 attribution_force(Some(&never_forced)),
4648 );
4649 assert!(
4650 env_only.contains("FORCE"),
4651 "an env-sourced force is still a force: {env_only}"
4652 );
4653 assert!(
4654 env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
4655 "must name the variable that is doing the forcing: {env_only}"
4656 );
4657 assert!(
4658 !env_only.contains("--project-attribution"),
4659 "must NOT tell the operator to drop a flag that would change \
4660 nothing here — this is the bug: {env_only}"
4661 );
4662
4663 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
4667 let binding_only = refused_error(
4668 pid,
4669 &ClientErrorKind::Forbidden,
4670 attribution_force(Some(&live)),
4671 );
4672 assert!(
4673 binding_only.contains("--project-attribution"),
4674 "a persisted force IS cleared by switching without the flag: {binding_only}"
4675 );
4676 assert!(
4677 !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
4678 "must not send the operator after an unset variable: {binding_only}"
4679 );
4680
4681 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
4685 let both = refused_error(
4686 pid,
4687 &ClientErrorKind::Forbidden,
4688 attribution_force(Some(&live)),
4689 );
4690 assert!(
4691 both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4692 && both.contains("--project-attribution"),
4693 "both sources are in effect and both must be named: {both}"
4694 );
4695 assert!(
4696 both.contains("BOTH"),
4697 "must say that removing only one is not enough: {both}"
4698 );
4699 }
4700
4701 #[test]
4706 fn no_force_means_no_remediation_clause() {
4707 let pid = uuid::Uuid::from_u128(7);
4708 let none = refused_error(
4709 pid,
4710 &ClientErrorKind::Forbidden,
4711 AttributionForce::default(),
4712 );
4713 assert!(
4714 !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
4715 && !none.contains("--project-attribution"),
4716 "a derived send has no force to remove: {none}"
4717 );
4718 }
4719
4720 fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
4725 let path = dir.join("transcript.jsonl");
4726 let mut body = String::new();
4727 for i in 0..n {
4728 let line = serde_json::json!({
4729 "type": "user",
4730 "n": i,
4731 "message": {"content": "x".repeat(line_bytes)},
4732 });
4733 body.push_str(&line.to_string());
4734 body.push('\n');
4735 }
4736 fs::write(&path, body).unwrap();
4737 path
4738 }
4739
4740 fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
4742 StreamEventRequest {
4743 tool_name: Some("Bash".into()),
4744 tool_use_id: Some("toolu_1".into()),
4745 tool_input: Some(serde_json::json!({"command": "ls"})),
4746 event_uuid: Some(uuid::Uuid::now_v7()),
4747 transcript_lines: Some(lines),
4748 transcript_offset: Some(offset),
4749 ..sample_stream_event_request()
4750 }
4751 }
4752
4753 fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
4754 part.transcript_lines.clone().unwrap_or_default()
4755 }
4756
4757 fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
4760 parts
4761 .iter()
4762 .flat_map(|p| {
4763 let offset = p.transcript_offset.unwrap();
4764 part_lines(p)
4765 .into_iter()
4766 .enumerate()
4767 .map(move |(i, l)| (offset + i as i64, l))
4768 })
4769 .collect()
4770 }
4771
4772 fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
4774 (0..n)
4775 .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
4776 .collect()
4777 }
4778
4779 #[test]
4780 fn split_leaves_a_request_under_the_cap_unchanged() {
4781 let req = event_with_lines(big_lines(3, 100), 0);
4782
4783 let parts = split_into_parts(req.clone());
4784
4785 assert_eq!(parts.len(), 1);
4786 assert_eq!(
4787 serde_json::to_value(&parts[0]).unwrap(),
4788 serde_json::to_value(&req).unwrap()
4789 );
4790 }
4791
4792 #[test]
4796 fn split_carries_every_line_of_a_batch_over_the_cap() {
4797 let dir = tempfile::tempdir().unwrap();
4798 let transcript = write_transcript(dir.path(), 300, 5_000);
4800 let (lines, start, _) =
4801 read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
4802 let req = event_with_lines(lines.clone(), start);
4803 assert!(req.serialized_len() > MAX_REQUEST_BYTES);
4804
4805 let parts = split_into_parts(req.clone());
4806
4807 assert!(parts.len() >= 3, "got {} parts", parts.len());
4808 for part in &parts {
4809 assert!(
4810 part.serialized_len() <= MAX_REQUEST_BYTES,
4811 "part of {} bytes exceeds the cap",
4812 part.serialized_len()
4813 );
4814 }
4815 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4816 assert_eq!(sent, lines, "every line, once, in order");
4817
4818 let (event, transcript_parts) = parts.split_last().unwrap();
4820 assert_eq!(event.event_type, StreamEventType::ToolUse);
4821 assert_eq!(event.event_uuid, req.event_uuid);
4822 assert_eq!(event.tool_input, req.tool_input);
4823 for part in transcript_parts {
4824 assert_eq!(part.event_type, StreamEventType::Transcript);
4825 assert!(part.event_uuid.is_none());
4826 assert!(part.tool_input.is_none());
4827 assert!(part.tool_name.is_none());
4828 }
4829 assert!(
4830 !part_lines(event).is_empty(),
4831 "the event keeps the lines that fit beside it"
4832 );
4833 }
4834
4835 #[test]
4839 fn split_keeps_each_lines_unsplit_chunk_index() {
4840 let lines = big_lines(300, 5_000);
4841 let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
4842
4843 let expected: Vec<_> = lines
4844 .into_iter()
4845 .enumerate()
4846 .map(|(i, l)| (1_000 + i as i64, l))
4847 .collect();
4848 assert_eq!(chunk_indexes(&parts), expected);
4849 }
4850
4851 #[test]
4856 fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
4857 let lines = big_lines(10, 200_000);
4858 let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
4859 let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
4860
4861 for (index, line) in &short {
4862 let in_long = long.iter().find(|(_, l)| l == line).unwrap();
4863 assert_eq!(in_long.0, *index, "line {line} indexed differently");
4864 }
4865 }
4866
4867 #[test]
4870 fn split_sends_a_single_oversized_line_alone() {
4871 let lines = vec![
4872 serde_json::json!({"n": 0}),
4873 serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
4874 serde_json::json!({"n": 2}),
4875 ];
4876
4877 let parts = split_into_parts(event_with_lines(lines.clone(), 0));
4878
4879 let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
4880 assert_eq!(sent, lines);
4881 let big = parts
4882 .iter()
4883 .find(|p| part_lines(p).contains(&lines[1]))
4884 .unwrap();
4885 assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
4886 assert_eq!(big.transcript_offset, Some(1));
4887 }
4888
4889 fn far_deadline() -> std::time::Instant {
4890 std::time::Instant::now() + Duration::from_secs(60)
4891 }
4892
4893 fn captured_body(captured: &str) -> StreamEventRequest {
4894 let body = captured.splitn(3, " | ").nth(2).expect("captured body");
4895 serde_json::from_str(body).expect("request body is a StreamEventRequest")
4896 }
4897
4898 #[tokio::test]
4900 async fn deliver_parts_sends_every_part() {
4901 let dir = tempfile::tempdir().unwrap();
4902 let pending_path = dir.path().join("pending.jsonl");
4903 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4904 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
4905 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4906
4907 let all_accepted = deliver_parts(
4908 &client,
4909 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4910 AttributionForce::default(),
4911 parts.clone(),
4912 &pending_path,
4913 false,
4914 far_deadline(),
4915 Unsent::Inline,
4916 &mut false,
4917 )
4918 .await
4919 .unwrap()
4920 .all;
4921
4922 assert!(all_accepted);
4923 for part in &parts {
4924 let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
4925 assert_eq!(got.transcript_offset, part.transcript_offset);
4926 assert_eq!(got.transcript_lines, part.transcript_lines);
4927 }
4928 assert!(drain_pending(&pending_path).unwrap().is_empty());
4929 }
4930
4931 #[tokio::test]
4935 async fn deliver_parts_queues_the_failed_part_and_the_rest() {
4936 let dir = tempfile::tempdir().unwrap();
4937 let pending_path = dir.path().join("pending.jsonl");
4938 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
4939 assert!(parts.len() >= 3);
4940 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
4941 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
4942 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4943
4944 let all_accepted = deliver_parts(
4945 &client,
4946 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4947 AttributionForce::default(),
4948 parts.clone(),
4949 &pending_path,
4950 false,
4951 far_deadline(),
4952 Unsent::Inline,
4953 &mut false,
4954 )
4955 .await
4956 .unwrap()
4957 .all;
4958
4959 assert!(!all_accepted);
4960 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4961 assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
4962 assert!(
4963 rx.recv_timeout(Duration::from_millis(300)).is_err(),
4964 "nothing is sent after the first failure"
4965 );
4966 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
4967 .unwrap()
4968 .iter()
4969 .map(|j| serde_json::from_str(j).unwrap())
4970 .collect();
4971 assert_eq!(queued.len(), parts.len() - 1);
4972 for (q, part) in queued.iter().zip(&parts[1..]) {
4973 assert_eq!(q.transcript_offset, part.transcript_offset);
4974 assert_eq!(q.transcript_lines, part.transcript_lines);
4975 }
4976 }
4977
4978 #[tokio::test]
4981 async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
4982 let dir = tempfile::tempdir().unwrap();
4983 let pending_path = dir.path().join("pending.jsonl");
4984 let parts = split_into_parts(sample_stream_event_request());
4985 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
4986
4987 let all_accepted = deliver_parts(
4988 &client,
4989 &repo_attr(&uuid::Uuid::new_v4().to_string()),
4990 AttributionForce::default(),
4991 parts,
4992 &pending_path,
4993 true,
4994 far_deadline(),
4995 Unsent::Inline,
4996 &mut false,
4997 )
4998 .await
4999 .unwrap()
5000 .all;
5001
5002 assert!(!all_accepted);
5003 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
5004 }
5005
5006 #[tokio::test]
5009 async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
5010 let dir = tempfile::tempdir().unwrap();
5011 let pending_path = dir.path().join("pending.jsonl");
5012 let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
5013 let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
5014 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
5015
5016 let all_accepted = deliver_parts(
5017 &client,
5018 &repo_attr(&uuid::Uuid::new_v4().to_string()),
5019 AttributionForce::default(),
5020 parts.clone(),
5021 &pending_path,
5022 false,
5023 std::time::Instant::now(),
5024 Unsent::Inline,
5025 &mut false,
5026 )
5027 .await
5028 .unwrap()
5029 .all;
5030
5031 assert!(!all_accepted);
5032 assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
5033 assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
5034 }
5035
5036 #[tokio::test]
5041 async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
5042 let dir = tempfile::tempdir().unwrap();
5043 let pending_path = dir.path().join("pending.jsonl");
5044 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
5045 let base = format!("http://{}", listener.local_addr().unwrap());
5046 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
5048 let started = Instant::now();
5049
5050 let all_accepted = deliver_parts(
5051 &client,
5052 &repo_attr(&uuid::Uuid::new_v4().to_string()),
5053 AttributionForce::default(),
5054 vec![event_with_lines(big_lines(1, 10), 0)],
5055 &pending_path,
5056 false,
5057 started + Duration::from_millis(100),
5058 Unsent::Inline,
5059 &mut false,
5060 )
5061 .await
5062 .unwrap()
5063 .all;
5064
5065 assert!(!all_accepted);
5066 assert!(started.elapsed() < Duration::from_secs(10));
5067 assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
5068 drop(listener);
5069 }
5070
5071 const PARENT_SESSION: &str = "parent-session";
5074 const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
5075
5076 fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
5080 let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
5081 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
5082 let subagents = dir.join(PARENT_SESSION).join("subagents");
5083 fs::create_dir_all(&subagents).unwrap();
5084 let session_dir = dir.join("tv-session");
5085 fs::create_dir_all(&session_dir).unwrap();
5086 (main, subagents, session_dir)
5087 }
5088
5089 fn subagent_line(agent: &str, n: usize) -> String {
5090 serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
5091 }
5092
5093 fn append_raw(path: &Path, text: &str) {
5094 let mut f = fs::OpenOptions::new()
5095 .create(true)
5096 .append(true)
5097 .open(path)
5098 .unwrap();
5099 f.write_all(text.as_bytes()).unwrap();
5100 }
5101
5102 fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
5103 let path = subagents.join(format!("agent-{agent}.jsonl"));
5104 for n in ns {
5105 append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
5106 }
5107 }
5108
5109 async fn sweep(
5113 responses: Vec<String>,
5114 main: &Path,
5115 session_dir: &Path,
5116 pending_path: &Path,
5117 ) -> Vec<StreamEventRequest> {
5118 sweep_waiting(responses, main, session_dir, pending_path, None).await
5119 }
5120
5121 async fn sweep_waiting(
5124 responses: Vec<String>,
5125 main: &Path,
5126 session_dir: &Path,
5127 pending_path: &Path,
5128 wait_for_lock: Option<Instant>,
5129 ) -> Vec<StreamEventRequest> {
5130 let expected = responses.len();
5131 let (base, rx) = crate::test_helpers::spawn_seq(responses);
5132 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
5133 let event = StreamEventRequest {
5134 session_id: PARENT_SESSION.into(),
5135 ..sample_stream_event_request()
5136 };
5137 deliver_subagent_transcripts(
5138 &client,
5139 &repo_attr(SUBAGENT_REPO),
5140 AttributionForce::default(),
5141 &transcript_template(&event),
5142 main,
5143 session_dir,
5144 pending_path,
5145 false,
5146 Instant::now() + Duration::from_secs(60),
5147 wait_for_lock,
5148 &mut false,
5149 )
5150 .await
5151 .unwrap();
5152 (0..expected)
5153 .map(|_| {
5154 let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
5155 assert!(
5156 captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
5157 "{captured}"
5158 );
5159 let body = captured.splitn(3, " | ").nth(2).unwrap();
5160 serde_json::from_str(body).unwrap()
5161 })
5162 .collect()
5163 }
5164
5165 fn agent_of(line: &serde_json::Value) -> &str {
5166 line["agentId"].as_str().unwrap()
5167 }
5168
5169 fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
5173 for req in reqs {
5174 assert_eq!(req.event_type, StreamEventType::Transcript);
5175 assert_eq!(req.session_id, PARENT_SESSION);
5176 assert!(req.event_uuid.is_none() && req.tool_name.is_none());
5177 let lines = part_lines(req);
5178 let agent = agent_of(&lines[0]);
5179 assert!(
5180 lines.iter().all(|l| agent_of(l) == agent),
5181 "a request mixes subagent files: {lines:?}"
5182 );
5183 let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
5184 let first = file.find(&lines[0].to_string()).unwrap() as i64;
5185 assert_eq!(req.transcript_offset, Some(first));
5186 }
5187 }
5188
5189 #[tokio::test]
5190 async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
5191 let dir = tempfile::tempdir().unwrap();
5192 let (main, subagents, session_dir) = claude_session(dir.path());
5193 let pending = session_dir.join("pending.jsonl");
5194 let ok = ok_stream_response;
5195 let mut all = Vec::new();
5196
5197 append_subagent_lines(&subagents, "a1", 0..2);
5199 append_subagent_lines(&subagents, "b2", 0..1);
5200 fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
5201 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
5202 assert_eq!(reqs.len(), 2);
5203 all.extend(reqs);
5204
5205 append_subagent_lines(&subagents, "a1", 2..3);
5207 append_subagent_lines(&subagents, "b2", 1..2);
5208 let partial = subagent_line("b2", 2);
5209 let (head, tail) = partial.split_at(10);
5210 append_raw(&subagents.join("agent-b2.jsonl"), head);
5211 let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
5212 assert_eq!(reqs.len(), 2);
5213 all.extend(reqs);
5214
5215 append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
5217 let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
5218 assert_eq!(reqs.len(), 1);
5219 all.extend(reqs);
5220
5221 assert!(sweep(vec![], &main, &session_dir, &pending)
5223 .await
5224 .is_empty());
5225 assert!(!pending.exists(), "nothing may have failed and been queued");
5226
5227 assert_one_file_per_request(&subagents, &all);
5228 let mut sent: Vec<(String, u64)> = all
5229 .iter()
5230 .flat_map(part_lines)
5231 .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
5232 .collect();
5233 sent.sort();
5234 let expected: Vec<(String, u64)> = [
5235 ("a1", 0),
5236 ("a1", 1),
5237 ("a1", 2),
5238 ("b2", 0),
5239 ("b2", 1),
5240 ("b2", 2),
5241 ]
5242 .into_iter()
5243 .map(|(a, n)| (a.to_string(), n))
5244 .collect();
5245 assert_eq!(sent, expected, "each line exactly once");
5246 }
5247
5248 #[tokio::test]
5249 async fn a_session_without_subagents_sends_nothing_extra() {
5250 let dir = tempfile::tempdir().unwrap();
5251 let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
5252 fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
5253 let session_dir = dir.path().join("tv-session");
5254 fs::create_dir_all(&session_dir).unwrap();
5255 let pending = session_dir.join("pending.jsonl");
5256
5257 assert!(sweep(vec![], &main, &session_dir, &pending)
5258 .await
5259 .is_empty());
5260 assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
5261 }
5262
5263 #[tokio::test]
5268 async fn a_failed_subagent_send_is_queued_once_and_not_read_again() {
5269 let dir = tempfile::tempdir().unwrap();
5270 let (main, subagents, session_dir) = claude_session(dir.path());
5271 let pending = session_dir.join("pending.jsonl");
5272 append_subagent_lines(&subagents, "a1", 0..2);
5273 append_subagent_lines(&subagents, "b2", 0..1);
5274
5275 let error =
5276 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
5277 let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
5278 assert_eq!(failed.len(), 1);
5279 let queued = |path: &Path| -> Vec<StreamEventRequest> {
5280 fs::read_to_string(path)
5281 .unwrap()
5282 .lines()
5283 .map(|j| serde_json::from_str(j).unwrap())
5284 .collect()
5285 };
5286 let first = queued(&pending);
5287 assert_eq!(first.len(), 2, "the failed batch and the one behind it");
5288 assert_one_file_per_request(&subagents, &first);
5289 assert_eq!(first[0].transcript_offset, failed[0].transcript_offset);
5290 assert_eq!(part_lines(&first[0]), part_lines(&failed[0]));
5291 assert!(first.iter().all(|r| r.transcript_offset == Some(0)));
5292
5293 for _ in 0..2 {
5295 assert!(sweep(vec![], &main, &session_dir, &pending)
5296 .await
5297 .is_empty());
5298 }
5299 assert_eq!(queued(&pending).len(), 2, "nothing was queued twice");
5300 }
5301
5302 #[tokio::test]
5306 async fn a_final_hook_reads_a_subagent_backlog_to_its_end() {
5307 let dir = tempfile::tempdir().unwrap();
5308 let (main, subagents, session_dir) = claude_session(dir.path());
5309 let pending = session_dir.join("pending.jsonl");
5310 let file = subagents.join("agent-a1.jsonl");
5311 for n in 0..90 {
5312 let line = serde_json::json!({"agentId": "a1", "n": n, "pad": "x".repeat(100_000)});
5313 append_raw(&file, &format!("{line}\n"));
5314 }
5315 let len = fs::metadata(&file).unwrap().len() as i64;
5316 let offset = || -> i64 {
5317 fs::read_to_string(crate::subagents::offset_path(&session_dir, &file))
5318 .unwrap()
5319 .trim()
5320 .parse()
5321 .unwrap()
5322 };
5323 let queued_ns = || -> Vec<u64> {
5324 fs::read_to_string(&pending)
5325 .unwrap()
5326 .lines()
5327 .map(|j| serde_json::from_str::<StreamEventRequest>(j).unwrap())
5328 .flat_map(|r| part_lines(&r))
5329 .map(|l| l["n"].as_u64().unwrap())
5330 .collect()
5331 };
5332
5333 assert!(sweep(vec![], &main, &session_dir, &pending)
5334 .await
5335 .is_empty());
5336 let after_one = offset();
5337 assert!(
5338 after_one >= MAX_BATCH_BYTES && after_one < len,
5339 "{after_one}"
5340 );
5341
5342 let sent = sweep_waiting(vec![], &main, &session_dir, &pending, Some(Instant::now())).await;
5343 assert!(sent.is_empty());
5344 assert_eq!(offset(), len);
5345 assert_eq!(queued_ns(), (0..90).collect::<Vec<_>>(), "each line once");
5346 }
5347
5348 #[tokio::test]
5351 async fn deliver_parts_queues_file_lines_and_counts_them() {
5352 let dir = tempfile::tempdir().unwrap();
5353 let pending_path = dir.path().join("pending.jsonl");
5354 let event = event_with_lines(big_lines(300, 5_000), 0);
5355 let parts = split_into_parts(event.clone());
5356 assert!(parts.len() >= 3);
5357 let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
5358 let (base, _rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
5359 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
5360
5361 let delivered = deliver_parts(
5362 &client,
5363 &repo_attr(&uuid::Uuid::new_v4().to_string()),
5364 AttributionForce::default(),
5365 parts.clone(),
5366 &pending_path,
5367 false,
5368 far_deadline(),
5369 Unsent::Queued,
5370 &mut false,
5371 )
5372 .await
5373 .unwrap();
5374
5375 assert_eq!(
5376 delivered,
5377 Delivered {
5378 all: false,
5379 lines: 300
5380 }
5381 );
5382 let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
5383 .unwrap()
5384 .iter()
5385 .map(|j| serde_json::from_str(j).unwrap())
5386 .collect();
5387 assert_eq!(queued.len(), parts.len() - 1);
5388 for (q, part) in queued.iter().zip(&parts[1..]) {
5389 assert_eq!(q.transcript_offset, part.transcript_offset);
5390 assert_eq!(q.transcript_lines, part.transcript_lines);
5391 }
5392 }
5393
5394 #[tokio::test]
5398 async fn deliver_parts_leaves_lines_in_the_file_once_the_queue_is_full() {
5399 let dir = tempfile::tempdir().unwrap();
5400 let pending_path = dir.path().join("pending.jsonl");
5401 let event = event_with_lines(big_lines(300, 5_000), 0);
5402 let parts = split_into_parts(event.clone());
5403 assert!(parts.len() >= 3);
5404 let first = serde_json::to_string(&parts[0]).unwrap().len() as u64;
5406 fs::write(&pending_path, "\n").unwrap();
5407 fs::OpenOptions::new()
5408 .write(true)
5409 .open(&pending_path)
5410 .unwrap()
5411 .set_len(crate::pending_queue::MAX_QUEUE_BYTES - first - 10_000)
5412 .unwrap();
5413 let before = fs::metadata(&pending_path).unwrap().len();
5414 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
5415
5416 let delivered = deliver_parts(
5417 &client,
5418 &repo_attr(&uuid::Uuid::new_v4().to_string()),
5419 AttributionForce::default(),
5420 parts.clone(),
5421 &pending_path,
5422 true,
5423 far_deadline(),
5424 Unsent::Queued,
5425 &mut false,
5426 )
5427 .await
5428 .unwrap();
5429
5430 assert_eq!(
5431 delivered,
5432 Delivered {
5433 all: false,
5434 lines: part_lines(&parts[0]).len()
5435 }
5436 );
5437 let mut added = Vec::new();
5438 let mut file = fs::File::open(&pending_path).unwrap();
5439 file.seek(SeekFrom::Start(before)).unwrap();
5440 file.read_to_end(&mut added).unwrap();
5441 let queued: Vec<StreamEventRequest> = String::from_utf8(added)
5442 .unwrap()
5443 .lines()
5444 .map(|j| serde_json::from_str(j).unwrap())
5445 .collect();
5446 assert_eq!(
5447 queued.len(),
5448 2,
5449 "the first part, and the event without lines"
5450 );
5451 assert_eq!(queued[0].transcript_lines, parts[0].transcript_lines);
5452 assert_eq!(queued[1].event_uuid, event.event_uuid);
5453 assert_eq!(queued[1].tool_input, event.tool_input);
5454 assert_eq!(queued[1].transcript_lines, None);
5455 }
5456
5457 #[tokio::test]
5460 async fn deliver_parts_can_leave_unsent_lines_in_the_file() {
5461 let dir = tempfile::tempdir().unwrap();
5462 let pending_path = dir.path().join("pending.jsonl");
5463 let lines_only = StreamEventRequest {
5464 event_type: StreamEventType::Transcript,
5465 ..event_with_lines(big_lines(3, 100), 0)
5466 };
5467 let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
5468
5469 let delivered = deliver_parts(
5470 &client,
5471 &repo_attr(&uuid::Uuid::new_v4().to_string()),
5472 AttributionForce::default(),
5473 split_into_parts(lines_only),
5474 &pending_path,
5475 false,
5476 far_deadline(),
5477 Unsent::StayInFile,
5478 &mut false,
5479 )
5480 .await
5481 .unwrap();
5482
5483 assert_eq!(
5484 delivered,
5485 Delivered {
5486 all: false,
5487 lines: 0
5488 }
5489 );
5490 assert!(!pending_path.exists());
5491 }
5492
5493 #[test]
5496 fn a_batch_is_capped_and_knows_where_its_lines_end() {
5497 let dir = tempfile::tempdir().unwrap();
5498 let transcript = dir.path().join("t.jsonl");
5499 let offset_path = dir.path().join(".stream_offset");
5500 let line = |n: usize| format!("{}\n", serde_json::json!({"n": n, "pad": "x".repeat(90)}));
5501 let len = line(0).len() as i64;
5502 let body: String = (0..10).map(line).collect::<Vec<_>>().join("\n");
5503 fs::write(&transcript, &body).unwrap();
5505
5506 let batch = read_transcript_batch(&transcript, &offset_path, 2 * len).unwrap();
5507 assert_eq!(batch.start, 0);
5508 assert_eq!(batch.lines.len(), 2, "two lines and the blank after each");
5509 assert_eq!(batch.ends, vec![len, 2 * len + 1]);
5510 assert_eq!(batch.end, 2 * len + 1);
5511
5512 let none = Delivered {
5515 all: false,
5516 lines: 0,
5517 };
5518 let one = Delivered {
5519 all: false,
5520 lines: 1,
5521 };
5522 let all = Delivered {
5523 all: false,
5524 lines: 2,
5525 };
5526 assert_eq!(batch.next_offset(&none), None);
5527 assert_eq!(batch.next_offset(&one), Some(len));
5528 assert_eq!(batch.next_offset(&all), Some(batch.end));
5529
5530 fs::write(&offset_path, len.to_string()).unwrap();
5532 let rest = read_transcript_batch(&transcript, &offset_path, i64::MAX).unwrap();
5533 assert_eq!(rest.lines.len(), 9);
5534 assert_eq!(rest.lines[0]["n"], 1);
5535 assert_eq!(rest.end, body.len() as i64);
5536 }
5537
5538 #[test]
5541 fn a_tool_error_past_the_batch_is_still_found() {
5542 let dir = tempfile::tempdir().unwrap();
5543 let transcript = dir.path().join("t.jsonl");
5544 let result = |id: &str, is_error: bool| {
5545 serde_json::json!({"type": "user", "message": {"content": [
5546 {"type": "tool_result", "tool_use_id": id, "is_error": is_error}
5547 ]}})
5548 .to_string()
5549 };
5550 let backlog = serde_json::json!({"type": "assistant", "pad": "x".repeat(1000)}).to_string();
5551 let body = format!(
5552 "{backlog}\n{backlog}\n{}\n{}\n",
5553 result("toolu_ok", false),
5554 result("toolu_bad", true)
5555 );
5556 fs::write(&transcript, &body).unwrap();
5557 let after_backlog = 2 * (backlog.len() as i64 + 1);
5558
5559 assert_eq!(
5560 tool_is_error_past(&transcript, after_backlog, "toolu_bad"),
5561 Some(true)
5562 );
5563 assert_eq!(
5564 tool_is_error_past(&transcript, after_backlog, "toolu_ok"),
5565 Some(false)
5566 );
5567 assert_eq!(
5568 tool_is_error_past(&transcript, after_backlog, "toolu_none"),
5569 None
5570 );
5571 assert_eq!(
5573 tool_is_error_past(&transcript, body.len() as i64, "toolu_bad"),
5574 None
5575 );
5576 assert_eq!(
5577 tool_is_error_past(&dir.path().join("absent"), 0, "toolu_bad"),
5578 None
5579 );
5580 }
5581
5582 #[test]
5583 fn a_413_is_told_from_other_failures() {
5584 assert!(too_large("Stream failed (413 Payload Too Large): "));
5585 assert!(!too_large("Stream failed (503 Service Unavailable): {}"));
5586 assert!(!too_large("Stream failed (404 Not Found): no repo 4130"));
5587 }
5588
5589 #[test]
5590 fn the_read_offset_only_moves_forward() {
5591 let dir = tempfile::tempdir().unwrap();
5592 let offset_path = dir.path().join(".stream_offset");
5593 let read = || fs::read_to_string(&offset_path).unwrap();
5594
5595 advance_offset(&offset_path, 100).unwrap();
5596 assert_eq!(read(), "100");
5597 advance_offset(&offset_path, 40).unwrap();
5598 assert_eq!(
5599 read(),
5600 "100",
5601 "a hook that got less through does not undo it"
5602 );
5603 advance_offset(&offset_path, 250).unwrap();
5604 assert_eq!(read(), "250");
5605 fs::write(&offset_path, "garbage").unwrap();
5607 advance_offset(&offset_path, 7).unwrap();
5608 assert_eq!(read(), "7");
5609 }
5610
5611 #[tokio::test]
5614 async fn a_subagent_file_another_hook_is_sending_is_skipped() {
5615 let dir = tempfile::tempdir().unwrap();
5616 let (main, subagents, session_dir) = claude_session(dir.path());
5617 let pending = session_dir.join("pending.jsonl");
5618 append_subagent_lines(&subagents, "a1", 0..2);
5619 append_subagent_lines(&subagents, "b2", 0..1);
5620 let a1_offset =
5621 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5622 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5623
5624 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5625 assert_eq!(reqs.len(), 1);
5626 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
5627 assert!(!a1_offset.exists());
5628
5629 drop(held);
5630 let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
5631 assert_eq!(reqs.len(), 1);
5632 assert_eq!(part_lines(&reqs[0]).len(), 2);
5633 assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
5634 }
5635
5636 #[tokio::test]
5639 async fn a_final_hook_waits_for_a_busy_subagent_file() {
5640 let dir = tempfile::tempdir().unwrap();
5641 let (main, subagents, session_dir) = claude_session(dir.path());
5642 let pending = session_dir.join("pending.jsonl");
5643 append_subagent_lines(&subagents, "a1", 0..2);
5644 let a1_offset =
5645 crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
5646 let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
5647 let release = thread::spawn(move || {
5648 thread::sleep(Duration::from_millis(300));
5649 drop(held);
5650 });
5651
5652 let reqs = sweep_waiting(
5653 vec![ok_stream_response()],
5654 &main,
5655 &session_dir,
5656 &pending,
5657 Some(Instant::now() + Duration::from_secs(10)),
5658 )
5659 .await;
5660 release.join().unwrap();
5661 assert_eq!(reqs.len(), 1);
5662 assert_eq!(part_lines(&reqs[0]).len(), 2);
5663 }
5664
5665 #[tokio::test]
5669 async fn a_large_subagent_batch_is_split_within_its_file() {
5670 let dir = tempfile::tempdir().unwrap();
5671 let (main, subagents, session_dir) = claude_session(dir.path());
5672 let pending = session_dir.join("pending.jsonl");
5673 let big = subagents.join("agent-a1.jsonl");
5674 for n in 0..300 {
5675 let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
5676 append_raw(&big, &format!("{line}\n"));
5677 }
5678 append_subagent_lines(&subagents, "b2", 0..1);
5679
5680 let scratch = dir.path().join("scratch-offset");
5681 let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
5682 let unsplit = StreamEventRequest {
5683 transcript_lines: Some(lines.clone()),
5684 transcript_offset: Some(start),
5685 ..transcript_template(&sample_stream_event_request())
5686 };
5687 let a1_parts = split_into_parts(unsplit).len();
5688 assert!(a1_parts > 1, "the batch must exceed the cap");
5689
5690 let reqs = sweep(
5691 vec![ok_stream_response(); a1_parts + 1],
5692 &main,
5693 &session_dir,
5694 &pending,
5695 )
5696 .await;
5697 assert!(!pending.exists());
5698 let (a1, b2) = reqs.split_at(a1_parts);
5699 assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
5700 assert_eq!(
5701 chunk_indexes(a1),
5702 lines
5703 .into_iter()
5704 .enumerate()
5705 .map(|(i, l)| (start + i as i64, l))
5706 .collect::<Vec<_>>()
5707 );
5708 assert_eq!(b2.len(), 1);
5709 assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
5710 assert_eq!(b2[0].transcript_offset, Some(0));
5711 }
5712}