use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
use std::path::Path;
use tracevault_protocol::hooks::{parse_hook_event, HookResponse};
use tracevault_protocol::streaming::{
extract_is_error_from_transcript, StreamEventRequest, StreamEventType, MAX_REQUEST_BYTES,
};
#[allow(clippy::type_complexity)]
pub fn apply_context(
ctx: crate::context::EffectiveContext,
) -> (
Option<String>,
Option<Vec<String>>,
Option<HashMap<String, String>>,
) {
let flow_id = ctx.flow_id;
let labels = if ctx.labels.is_empty() {
None
} else {
Some(ctx.labels)
};
let params = if ctx.params.is_empty() {
None
} else {
Some(ctx.params.into_iter().collect())
};
(flow_id, labels, params)
}
pub fn read_new_transcript_lines(
transcript_path: &Path,
offset_path: &Path,
) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
return Ok((vec![], 0, 0));
}
let offset: i64 = if offset_path.exists() {
let content = fs::read_to_string(offset_path)?;
content
.trim()
.parse::<i64>()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
} else {
0
};
let mut file = fs::File::open(transcript_path)?;
file.seek(SeekFrom::Start(offset as u64))?;
let reader = io::BufReader::new(file);
let mut lines = Vec::new();
let mut bytes_read = offset;
for line_result in reader.lines() {
let line = line_result?;
bytes_read += line.len() as i64 + 1;
if line.trim().is_empty() {
continue;
}
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
lines.push(value);
}
}
Ok((lines, offset, bytes_read))
}
pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
if transcript_path.is_empty() {
return Ok(());
}
let meta_path = session_dir.join("metadata.json");
let mut meta = fs::read_to_string(&meta_path)
.ok()
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.filter(serde_json::Value::is_object)
.unwrap_or_else(|| serde_json::json!({}));
if meta.get("transcript_path").and_then(|v| v.as_str()) == Some(transcript_path) {
return Ok(());
}
meta["transcript_path"] = serde_json::Value::String(transcript_path.to_string());
let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
fs::write(&tmp, meta.to_string())?;
fs::rename(&tmp, &meta_path).inspect_err(|_| {
let _ = fs::remove_file(&tmp);
})
}
pub fn record_inline_tool_calls(
session_dir: &Path,
records: &[serde_json::Value],
) -> Result<(), io::Error> {
let lines: String = records
.iter()
.flat_map(crate::transcript::tool_call_names)
.map(|name| {
let record = serde_json::json!({
"type": "message",
"message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
});
format!("{record}\n")
})
.collect();
if lines.is_empty() {
return Ok(());
}
let log_path = session_dir.join("tool_calls.jsonl");
OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)?
.write_all(lines.as_bytes())?;
record_transcript_path(session_dir, &log_path.to_string_lossy())
}
pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(pending_path)?;
writeln!(file, "{json}")?;
Ok(())
}
pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
if !pending_path.exists() {
return Ok(vec![]);
}
let content = fs::read_to_string(pending_path)?;
let lines: Vec<String> = content
.lines()
.filter(|l| !l.trim().is_empty())
.map(String::from)
.collect();
fs::remove_file(pending_path)?;
Ok(lines)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Attribution {
Repo {
repo_id: String,
project: Option<uuid::Uuid>,
},
ProjectOnly { project_id: uuid::Uuid },
}
impl Attribution {
pub(crate) fn pending_file_name(&self) -> String {
use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
match self {
Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
Self::ProjectOnly { project_id } => {
format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
}
}
}
}
pub(crate) fn attribution_for(
binding: Option<&crate::session_state::RepoBinding>,
project: Option<uuid::Uuid>,
) -> Option<Attribution> {
match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
Some(b) => Some(Attribution::Repo {
repo_id: b.repo_id.clone(),
project,
}),
None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
}
}
fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
session_dir.join(attribution.pending_file_name())
}
pub fn resolve_session_paths(
hook_cwd: &Path,
session_id: &str,
) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
let resolved = crate::paths::resolve_project_root(hook_cwd);
let session_dir = resolved
.root
.join(".tracevault")
.join("sessions")
.join(session_id);
(resolved, session_dir)
}
pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
uuid::Uuid::parse_str(repo_id).is_ok()
}
pub(crate) fn resolve_stream_binding(
session: &crate::session_state::SessionState,
worktree: &str,
bound: Option<crate::session_state::RepoBinding>,
user_default: Option<crate::session_state::RepoBinding>,
) -> Option<crate::session_state::RepoBinding> {
crate::resolution::effective_binding(crate::resolution::ResolveInputs {
repo_flag: None,
session,
worktree_path: Some(worktree),
bound,
user_default,
})
.map(|(b, _)| b)
}
pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
let raw = raw.trim();
let parsed = raw.parse::<uuid::Uuid>().ok()?;
Some(crate::session_state::ProjectBinding {
project_id: parsed.to_string(),
project_name: String::new(),
updated_at: String::new(),
forced_until: None,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct AttributionForce {
pub(crate) env: bool,
pub(crate) binding: bool,
}
impl AttributionForce {
pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
if self.env || self.binding {
crate::api_client::AttributionMode::Explicit
} else {
crate::api_client::AttributionMode::Derived
}
}
}
pub(crate) fn attribution_mode(
effective: Option<&crate::session_state::ProjectBinding>,
) -> crate::api_client::AttributionMode {
attribution_force(effective).mode()
}
pub(crate) fn attribution_force(
effective: Option<&crate::session_state::ProjectBinding>,
) -> AttributionForce {
AttributionForce {
env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
.map(|v| v.trim().eq_ignore_ascii_case("explicit"))
.unwrap_or(false),
binding: effective
.and_then(|b| b.forced_until.as_deref())
.is_some_and(|s| {
matches!(
crate::session_state::force_status(s),
crate::session_state::ForceStatus::Live(_)
)
}),
}
}
pub(crate) fn capture_binding(
session: &crate::session_state::SessionState,
worktree_path: Option<&str>,
) -> Option<crate::session_state::ProjectBinding> {
use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
let (binding, _) = capture_project_binding(&CaptureProjectInputs {
project_flag: None,
env_project: env_project_binding(),
session,
worktree_path,
user_default: crate::user_project_default::load(),
})?;
capture_project_id(&binding)?;
Some(binding)
}
pub(crate) fn capture_project(
session: &crate::session_state::SessionState,
worktree_path: Option<&str>,
) -> Option<uuid::Uuid> {
capture_binding(session, worktree_path)
.as_ref()
.and_then(crate::resolution::capture_project_id)
}
fn undeliverable_warning(pid: uuid::Uuid) -> String {
format!(
"tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
repo binding, so there is nothing to attribute these events to and they are being \
DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
that exists."
)
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ClientErrorKind {
Forbidden,
Scoping,
}
pub(crate) fn refused_error(
pid: uuid::Uuid,
kind: &ClientErrorKind,
force: AttributionForce,
) -> String {
let base = match kind {
ClientErrorKind::Forbidden => format!(
"tracevault: error: the server refused to attribute this event to active project \
{pid} (403). Either that project does not apply to this repo (not a member, or \
no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
binding is the machine-wide default in `user_project.toml`) — or this account has \
no `tracevault` grant in Control Plane at all, which an administrator must grant. \
The event was NOT re-attributed elsewhere; it has been queued and will be retried \
once the binding or the grant is fixed."
),
ClientErrorKind::Scoping => format!(
"tracevault: error: active project {pid} does not apply to this repo (not a member, \
missing permission, or the project no longer exists). The event was NOT \
re-attributed elsewhere; it has been queued and will be retried once the binding is \
fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
machine-wide default in `user_project.toml`) to update it."
),
};
if force.mode() == crate::api_client::AttributionMode::Explicit
&& matches!(kind, ClientErrorKind::Forbidden)
{
return format!(
"{base} This send declared `explicit` attribution, so the refusal may be of the \
FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
identity (a `tvk_` API key can never force). If membership attribution is what \
you want, {}",
force_remediation(force)
);
}
base
}
fn force_remediation(force: AttributionForce) -> String {
let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
process-wide and never expires, so no switch clears it)";
let binding_fix = "run `tracevault project switch <name>` WITHOUT \
`--project-attribution explicit` (add `--user` if the forced binding \
is the machine-wide default in `user_project.toml`)";
match (force.env, force.binding) {
(true, false) => format!("{env_fix}."),
(false, true) => format!("{binding_fix}."),
(true, true) => {
format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
}
(false, false) => format!("{env_fix}, or {binding_fix}."),
}
}
pub(crate) fn deterministic_client_error_kind(
e: &dyn std::error::Error,
) -> Option<ClientErrorKind> {
let s = e.to_string();
if s.contains("(403 ") {
return Some(ClientErrorKind::Forbidden);
}
if ["(400 ", "(404 ", "(409 "]
.iter()
.any(|marker| s.contains(marker))
{
return Some(ClientErrorKind::Scoping);
}
None
}
async fn send_stream_event(
client: &crate::api_client::ApiClient,
attribution: &Attribution,
force: AttributionForce,
req: &StreamEventRequest,
warned: &mut bool,
) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
{
let (repo_id, capture_pid) = match attribution {
Attribution::ProjectOnly { project_id } => {
let attempt = client
.stream_event_for_project(*project_id, None, force.mode(), req)
.await;
return match attempt {
Ok(r) => Ok(Some(r)),
Err(e) => match deterministic_client_error_kind(e.as_ref()) {
Some(ClientErrorKind::Scoping) => {
if !*warned {
eprintln!("{}", undeliverable_warning(*project_id));
*warned = true;
}
Ok(None)
}
_ => Err(e),
},
};
}
Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
};
match capture_pid {
None => client.stream_event(repo_id, req).await.map(Some),
Some(pid) => {
let attempt = client
.stream_event_for_project(pid, Some(repo_id), force.mode(), req)
.await;
let kind = match &attempt {
Ok(_) => None,
Err(e) => deterministic_client_error_kind(e.as_ref()),
};
match (attempt, kind) {
(Ok(r), _) => Ok(Some(r)),
(Err(e), Some(kind)) => {
if !*warned {
eprintln!("{}", refused_error(pid, &kind, force));
*warned = true;
}
Err(e)
}
(Err(e), None) => Err(e),
}
}
}
}
pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
(start_offset, start_offset + records_len)
}
pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
if req.serialized_len() <= MAX_REQUEST_BYTES {
return vec![req];
}
let lines = req.transcript_lines.take().unwrap_or_default();
let batch_offset = req.transcript_offset.unwrap_or(0);
req.truncate_large_fields();
let sizes: Vec<usize> = lines
.iter()
.map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
.collect();
let envelope = |r: &StreamEventRequest| {
let mut r = r.clone();
r.transcript_lines = Some(vec![]);
r.serialized_len()
};
let mut tail_start = lines.len();
let mut used = envelope(&req);
while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
tail_start -= 1;
used += sizes[tail_start];
}
let transcript_template = StreamEventRequest {
event_type: StreamEventType::Transcript,
tool_name: None,
tool_use_id: None,
tool_input: None,
tool_response: None,
tool_is_error: None,
event_index: None,
event_uuid: None,
transcript_lines: None,
final_stats: None,
..req.clone()
};
let transcript_envelope = envelope(&transcript_template);
let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
let mut start = 0;
while start < tail_start {
let mut end = start + 1;
let mut used = transcript_envelope + sizes[start];
while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
used += sizes[end];
end += 1;
}
groups.push(start..end);
start = end;
}
groups.push(tail_start..lines.len());
let last = groups.len() - 1;
let mut lines = lines.into_iter();
groups
.into_iter()
.enumerate()
.map(|(n, range)| {
let mut part = if n == last {
req.clone()
} else {
transcript_template.clone()
};
let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
part.transcript_offset = Some(batch_offset + range.start as i64);
part
})
.collect()
}
pub fn resolve_transcript_source(
inline_records: Option<Vec<serde_json::Value>>,
prior_offset: i64,
file_result: (Vec<serde_json::Value>, i64, i64),
) -> (Vec<serde_json::Value>, i64, i64) {
match inline_records {
Some(records) => {
let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
(records, send, next)
}
None => file_result,
}
}
pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
lines.iter().find_map(|line| {
let msg = line.get("message")?;
if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
Some(
msg.get("isError")
.and_then(|v| v.as_bool())
.unwrap_or(false),
)
} else {
None
}
})
}
pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
req.tool = Some(agent.tool_name().to_string());
req.protocol_version = agent.protocol_version() as u32;
}
const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
#[allow(clippy::too_many_arguments)]
async fn deliver_parts(
client: &crate::api_client::ApiClient,
attribution: &Attribution,
force: AttributionForce,
parts: Vec<StreamEventRequest>,
pending_path: &Path,
mut send_failed: bool,
deadline: std::time::Instant,
warned: &mut bool,
) -> Result<bool, Box<dyn std::error::Error>> {
let mut all_accepted = true;
for part in parts {
send_failed = send_failed || std::time::Instant::now() >= deadline;
if !send_failed {
match send_stream_event(client, attribution, force, &part, warned).await {
Ok(_) => continue,
Err(_) => send_failed = true,
}
}
all_accepted = false;
append_pending(pending_path, &serde_json::to_string(&part)?)?;
}
Ok(all_accepted)
}
pub async fn run_stream(
event_type: &str,
agent: crate::agent::Agent,
) -> Result<(), Box<dyn std::error::Error>> {
let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let mut hook_event = parse_hook_event(&input)?;
let hook_cwd = Path::new(&hook_event.cwd);
let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
if resolved.source == crate::paths::ProjectRootSource::Fallback {
eprintln!(
"tracevault: warning: could not resolve a git project root from {}; \
creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
that it runs inside the repository to keep sessions under the repo root.",
hook_cwd.display()
);
}
let project_root = resolved.root;
fs::create_dir_all(&session_dir)?;
let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
let _ = fs::write(session_dir.join("origin"), &worktree_top);
let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
if let Some(records) = &hook_event.transcript_records {
let _ = record_inline_tool_calls(&session_dir, records);
}
let event_uuid = uuid::Uuid::now_v7();
let transcript_path = Path::new(&hook_event.transcript_path);
let offset_path = session_dir.join(".stream_offset");
let (transcript_lines, start_offset, new_offset) =
read_new_transcript_lines(transcript_path, &offset_path)?;
let is_inline = hook_event.transcript_records.is_some();
let (transcript_lines, start_offset, new_offset) = if is_inline {
let prior_offset: i64 = if offset_path.exists() {
let content = fs::read_to_string(&offset_path)?;
content
.trim()
.parse::<i64>()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
.max(0)
} else {
0
};
resolve_transcript_source(
hook_event.transcript_records.take(),
prior_offset,
(transcript_lines, start_offset, new_offset),
)
} else {
(transcript_lines, start_offset, new_offset)
};
let stream_event_type = match event_type {
"notification" => StreamEventType::SessionStart,
"stop" => StreamEventType::SessionEnd,
_ => StreamEventType::ToolUse,
};
let tool_is_error = hook_event
.tool_use_id
.as_deref()
.and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
.or_else(|| inline_tool_is_error(&transcript_lines));
let config = crate::config::TracevaultConfig::try_load(&project_root);
let repo_uc = config
.as_ref()
.ok()
.and_then(|opt| opt.as_ref())
.and_then(|c| c.user_context.clone());
let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
let mut req = StreamEventRequest {
protocol_version: 1,
tool: Some("claude-code".to_string()),
event_type: stream_event_type,
session_id: hook_event.session_id.clone(),
timestamp: chrono::Utc::now(),
hook_event_name: Some(hook_event.hook_event_name.clone()),
tool_name: hook_event.tool_name.clone(),
tool_use_id: hook_event.tool_use_id.clone(),
tool_input: hook_event.tool_input.clone(),
tool_response: hook_event.tool_response.clone(),
tool_is_error,
event_index: None,
event_uuid: Some(event_uuid),
transcript_lines: if transcript_lines.is_empty() {
None
} else {
Some(transcript_lines)
},
transcript_offset: Some(start_offset),
model: None,
cwd: Some(hook_event.cwd.clone()),
final_stats: None,
flow_id: ctx_flow_id,
labels: ctx_labels,
params: ctx_params,
billing_mode: Some(crate::billing::detect_current(
agent,
hook_cwd,
&hook_event.transcript_path,
)),
};
stamp_agent(&mut req, agent);
let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
if let Err(e) = &config {
return Err(format!("malformed .tracevault/config.toml: {e}").into());
}
let session = crate::session_state::load(&hook_event.session_id);
let bound = config
.as_ref()
.ok()
.and_then(|opt| opt.as_ref())
.and_then(crate::resolution::binding_from_config);
let user_default = crate::user_default::load();
let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
let response = HookResponse::allow();
println!("{}", serde_json::to_string(&response)?);
Ok(())
};
let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
let capture_pid = capture_binding
.as_ref()
.and_then(crate::resolution::capture_project_id);
let force = attribution_force(capture_binding.as_ref());
let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
no_op_allow()?;
return Ok(());
};
let server_url = server_url.ok_or("server_url not configured")?;
let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
let pending_path = pending_path_for(&session_dir, &attribution);
let pending_events = drain_pending(&pending_path)?;
let mut send_failed = false;
let mut warned = false;
for (i, pending_json) in pending_events.iter().enumerate() {
if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
if std::time::Instant::now() >= deadline
|| send_stream_event(&client, &attribution, force, &pending_req, &mut warned)
.await
.is_err()
{
for evt in &pending_events[i..] {
append_pending(&pending_path, evt)?;
}
send_failed = true;
break;
}
}
}
let all_accepted = deliver_parts(
&client,
&attribution,
force,
split_into_parts(req),
&pending_path,
send_failed,
deadline,
&mut warned,
)
.await?;
if all_accepted || is_inline {
fs::write(&offset_path, new_offset.to_string())?;
}
let response = HookResponse::allow();
println!("{}", serde_json::to_string(&response)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::api_client::AttributionMode;
use crate::config::UserContext;
use crate::context::{Context, EffectiveContext};
use std::collections::BTreeMap;
#[test]
fn disabled_user_context_resolves_to_none() {
assert!(UserContext::Toggle(false).resolve().is_none());
}
#[test]
fn effective_with_no_user_layer_on_empty_repo_is_empty() {
let dir = tempfile::tempdir().unwrap();
let effective = Context::effective(dir.path(), None);
assert_eq!(effective, EffectiveContext::default());
}
#[test]
fn apply_context_stamps_all_fields() {
let dir = tempfile::tempdir().unwrap();
let mut params = BTreeMap::new();
params.insert("env".to_string(), "prod".to_string());
params.insert("region".to_string(), "eu-west-1".to_string());
let ctx = EffectiveContext {
flow_id: Some("flow-xyz".to_string()),
labels: vec!["backend".to_string(), "urgent".to_string()],
params,
};
let (flow_id, labels, params_out) = apply_context(ctx);
assert_eq!(flow_id, Some("flow-xyz".to_string()));
assert_eq!(
labels,
Some(vec!["backend".to_string(), "urgent".to_string()])
);
let p = params_out.expect("params should be Some");
assert_eq!(p.get("env").map(String::as_str), Some("prod"));
assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
let written = Context {
flow_id: Some("flow-xyz".to_string()),
labels: vec!["backend".to_string(), "urgent".to_string()],
params: {
let mut m = BTreeMap::new();
m.insert("env".to_string(), Some("prod".to_string()));
m.insert("region".to_string(), Some("eu-west-1".to_string()));
m
},
};
let ctx_path = dir.path().join(".tracevault").join("context.json");
written.save_to(&ctx_path).unwrap();
let loaded = Context::load_from(&ctx_path);
let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
assert_eq!(flow_id2, Some("flow-xyz".to_string()));
assert!(labels2.is_some());
assert!(params2.is_some());
}
#[test]
fn apply_context_missing_file_all_none() {
let dir = tempfile::tempdir().unwrap();
let missing_path = dir.path().join(".tracevault").join("context.json");
let ctx = Context::load_from(&missing_path); let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
assert!(flow_id.is_none(), "flow_id should be None");
assert!(labels.is_none(), "labels should be None");
assert!(params.is_none(), "params should be None");
}
#[test]
fn apply_context_empty_collections_are_none() {
let ctx = EffectiveContext {
flow_id: None,
labels: vec![],
params: BTreeMap::new(),
};
let (flow_id, labels, params) = apply_context(ctx);
assert!(flow_id.is_none());
assert!(
labels.is_none(),
"empty labels should be None, not Some([])"
);
assert!(
params.is_none(),
"empty params should be None, not Some({{}})"
);
}
#[test]
fn apply_context_flow_id_only() {
let ctx = EffectiveContext {
flow_id: Some("my-flow".to_string()),
labels: vec![],
params: BTreeMap::new(),
};
let (flow_id, labels, params) = apply_context(ctx);
assert_eq!(flow_id, Some("my-flow".to_string()));
assert!(labels.is_none());
assert!(params.is_none());
}
use crate::test_helpers::{add_worktree, init_git_repo};
#[test]
fn resolve_session_paths_primary_checkout() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
let project_root = resolved.root;
assert_eq!(
project_root.canonicalize().unwrap(),
repo.canonicalize().unwrap(),
"primary checkout: project_root must be repo root"
);
assert_eq!(
session_dir.canonicalize().unwrap_or(session_dir.clone()),
repo.join(".tracevault")
.join("sessions")
.join("sess-primary-123"),
"primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
);
assert!(
session_dir.starts_with(&repo),
"session_dir must be under the primary repo root"
);
}
#[test]
fn resolve_session_paths_sibling_worktree_uses_primary_root() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let wt = tmp.path().join("sibling-wt");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
add_worktree(&repo, &wt);
let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
let project_root = resolved.root;
assert_eq!(
project_root.canonicalize().unwrap(),
repo.canonicalize().unwrap(),
"sibling worktree: project_root must be primary repo root (not worktree dir)"
);
assert!(
session_dir.starts_with(&repo),
"sibling worktree: session_dir must be under the PRIMARY repo root"
);
assert!(
!session_dir.starts_with(&wt),
"sibling worktree: session_dir must NOT be under the sibling worktree dir"
);
assert!(
session_dir.ends_with(
std::path::Path::new(".tracevault")
.join("sessions")
.join("sess-sibling-456")
),
"session_dir must end with .tracevault/sessions/<session_id>"
);
}
#[test]
fn resolve_session_paths_non_git_fallback() {
let tmp = tempfile::tempdir().unwrap();
let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
let project_root = resolved.root;
assert_eq!(
project_root,
tmp.path(),
"non-git: project_root must fall back to hook_cwd"
);
assert_eq!(
session_dir,
tmp.path()
.join(".tracevault")
.join("sessions")
.join("sess-fallback-789"),
"non-git: session_dir must be relative to the fallback root"
);
}
#[test]
fn origin_marker_written_in_session_dir() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
let session_dir = repo
.join(".tracevault")
.join("sessions")
.join("test-sess-001");
std::fs::create_dir_all(&session_dir).unwrap();
let hook_cwd = &repo;
let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
assert_eq!(
origin_content.trim(),
expected.as_str(),
"origin marker must contain the canonicalized worktree toplevel"
);
}
fn metadata(session_dir: &Path) -> serde_json::Value {
serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
.unwrap()
}
#[test]
fn record_transcript_path_writes_metadata_for_check() {
let tmp = tempfile::tempdir().unwrap();
record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
}
#[test]
fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("metadata.json"),
r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
)
.unwrap();
record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
let m = metadata(tmp.path());
assert_eq!(m["transcript_path"], "/t/new.jsonl");
assert_eq!(m["model"], "m");
let leftovers = std::fs::read_dir(tmp.path())
.unwrap()
.filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
.count();
assert_eq!(leftovers, 0, "the temp file is renamed into place");
}
#[test]
fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
let tmp = tempfile::tempdir().unwrap();
record_transcript_path(tmp.path(), "").unwrap();
assert!(!tmp.path().join("metadata.json").exists());
std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
}
use crate::session_state::{RepoBinding, SessionState};
fn binding(id: &str) -> RepoBinding {
RepoBinding {
repo_id: id.into(),
git_url: None,
remote_id: None,
codebase_name: None,
updated_at: "t".into(),
}
}
#[test]
fn resolve_stream_binding_uses_session_active_when_unbound() {
let session = SessionState {
active: Some(binding("session-repo")),
subagents: HashMap::new(),
..Default::default()
};
let got = resolve_stream_binding(&session, "/wt/top", None, None);
assert_eq!(got.unwrap().repo_id, "session-repo");
}
#[test]
fn resolve_stream_binding_falls_back_to_bound_config() {
let session = SessionState::default();
let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
assert_eq!(got.unwrap().repo_id, "bound-repo");
}
#[test]
fn resolve_stream_binding_none_when_nothing_resolves() {
let session = SessionState::default();
let got = resolve_stream_binding(&session, "/wt/top", None, None);
assert!(got.is_none());
}
#[test]
fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
let session = SessionState {
active: Some(binding("session-repo")),
subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
..Default::default()
};
let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
assert_eq!(got.unwrap().repo_id, "subagent-repo");
}
#[test]
fn resolve_stream_binding_falls_back_to_user_default() {
let session = SessionState::default();
let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
assert_eq!(got.unwrap().repo_id, "userdef");
}
#[test]
fn resolve_stream_binding_prefers_bound_over_user_default() {
let session = SessionState::default();
let got = resolve_stream_binding(
&session,
"/wt/x",
Some(binding("bound")),
Some(binding("userdef")),
);
assert_eq!(got.unwrap().repo_id, "bound");
}
fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
crate::session_state::RepoBinding {
repo_id: repo_id.into(),
git_url: None,
remote_id: None,
codebase_name: None,
updated_at: String::new(),
}
}
#[test]
fn attribution_falls_back_to_project_when_no_repo_binds() {
let pid = uuid::Uuid::new_v4();
assert_eq!(
attribution_for(None, Some(pid)),
Some(Attribution::ProjectOnly { project_id: pid })
);
}
#[test]
fn attribution_is_none_when_neither_repo_nor_project_binds() {
assert_eq!(attribution_for(None, None), None);
}
#[test]
fn attribution_uses_repo_with_no_project_overlay() {
let repo = uuid::Uuid::new_v4().to_string();
let b = binding_with(&repo);
assert_eq!(
attribution_for(Some(&b), None),
Some(Attribution::Repo {
repo_id: repo,
project: None
})
);
}
#[test]
fn attribution_overlays_project_on_repo() {
let repo = uuid::Uuid::new_v4().to_string();
let pid = uuid::Uuid::new_v4();
let b = binding_with(&repo);
assert_eq!(
attribution_for(Some(&b), Some(pid)),
Some(Attribution::Repo {
repo_id: repo,
project: Some(pid)
})
);
}
#[test]
fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
let pid = uuid::Uuid::new_v4();
let b = binding_with("../../escape");
assert_eq!(
attribution_for(Some(&b), Some(pid)),
Some(Attribution::ProjectOnly { project_id: pid })
);
}
#[test]
fn attribution_drops_a_corrupt_repo_id_with_no_project() {
let b = binding_with("../../escape");
assert_eq!(attribution_for(Some(&b), None), None);
}
#[test]
fn pending_file_name_for_a_repo_is_unchanged() {
let repo = uuid::Uuid::new_v4().to_string();
assert_eq!(
Attribution::Repo {
repo_id: repo.clone(),
project: Some(uuid::Uuid::new_v4())
}
.pending_file_name(),
format!("pending-{repo}.jsonl")
);
}
#[test]
fn pending_file_name_for_a_project_is_distinct() {
let pid = uuid::Uuid::new_v4();
assert_eq!(
Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
format!("pending-project-{pid}.jsonl")
);
}
#[test]
fn binding_repo_id_is_valid_accepts_real_uuid() {
assert!(binding_repo_id_is_valid(
"550e8400-e29b-41d4-a716-446655440000"
));
}
#[test]
fn binding_repo_id_is_valid_rejects_path_traversal() {
assert!(!binding_repo_id_is_valid("../evil"));
}
#[test]
fn binding_repo_id_is_valid_rejects_empty() {
assert!(!binding_repo_id_is_valid(""));
}
#[test]
fn binding_repo_id_is_valid_rejects_non_uuid() {
assert!(!binding_repo_id_is_valid("not-a-uuid"));
}
#[test]
fn stamp_agent_sets_tool_and_version() {
use crate::agent::Agent;
let mut req = StreamEventRequest {
protocol_version: 1,
tool: Some("claude-code".to_string()),
event_type: StreamEventType::ToolUse,
session_id: "s".into(),
timestamp: chrono::Utc::now(),
hook_event_name: None,
tool_name: None,
tool_use_id: None,
tool_input: None,
tool_response: None,
tool_is_error: None,
event_index: None,
event_uuid: None,
transcript_lines: None,
transcript_offset: None,
model: None,
cwd: None,
final_stats: None,
flow_id: None,
labels: None,
params: None,
billing_mode: None,
};
stamp_agent(&mut req, Agent::Codex);
assert_eq!(req.tool.as_deref(), Some("codex"));
assert_eq!(req.protocol_version, 2);
stamp_agent(&mut req, Agent::ClaudeCode);
assert_eq!(req.tool.as_deref(), Some("claude-code"));
assert_eq!(req.protocol_version, 1);
}
fn repo_attr(repo_id: &str) -> Attribution {
Attribution::Repo {
repo_id: repo_id.into(),
project: None,
}
}
#[test]
fn pending_path_is_repo_scoped() {
let dir = std::path::Path::new("/tmp/sess");
assert_eq!(
pending_path_for(dir, &repo_attr("repo-a")),
std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
);
assert_ne!(
pending_path_for(dir, &repo_attr("repo-a")),
pending_path_for(dir, &repo_attr("repo-b")),
);
}
#[test]
fn pending_path_for_a_project_never_collides_with_a_repo() {
let dir = std::path::Path::new("/tmp/sess");
let pid = uuid::Uuid::from_u128(9);
assert_eq!(
pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
);
assert_ne!(
pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
pending_path_for(dir, &repo_attr(&pid.to_string())),
);
}
#[test]
fn read_new_transcript_lines_empty_path_is_noop() {
let dir = tempfile::tempdir().unwrap();
let offset_path = dir.path().join(".stream_offset");
let (lines, start_offset, end_offset) =
read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
assert!(
lines.is_empty(),
"empty path must yield no transcript lines"
);
assert_eq!(start_offset, 0);
assert_eq!(end_offset, 0);
}
#[test]
fn read_new_transcript_lines_second_read_starts_at_previous_end() {
let dir = tempfile::tempdir().unwrap();
let transcript_path = dir.path().join("transcript.jsonl");
let offset_path = dir.path().join(".stream_offset");
fs::write(
&transcript_path,
"{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
)
.unwrap();
let (lines, start_offset, end_offset) =
read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
assert_eq!(lines.len(), 2);
assert_eq!(start_offset, 0, "first read starts at byte 0");
assert!(end_offset > 0);
fs::write(&offset_path, end_offset.to_string()).unwrap();
let mut f = OpenOptions::new()
.append(true)
.open(&transcript_path)
.unwrap();
writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
drop(f);
let (lines2, start_offset2, end_offset2) =
read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
assert_eq!(lines2.len(), 1);
assert_eq!(
start_offset2, end_offset,
"second read's start_offset must equal the first read's persisted end_offset"
);
assert!(end_offset2 > start_offset2);
}
#[tokio::test]
async fn capture_project_precedence_local_only() {
use crate::session_state::{ProjectBinding, SessionState};
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.remove("TRACEVAULT_PROJECT");
let pb = |id: &str| ProjectBinding {
project_id: id.into(),
project_name: "n".into(),
updated_at: "".into(),
forced_until: None,
};
let u = uuid::Uuid::from_u128;
let s = SessionState {
active_project: Some(pb(&u(2).to_string())),
..Default::default()
};
assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
let mut s = s;
s.subagent_projects
.insert("/wt".into(), pb(&u(1).to_string()));
assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
assert_eq!(capture_project(&SessionState::default(), None), None);
let bad = SessionState {
active_project: Some(pb("not-a-uuid")),
..Default::default()
};
assert_eq!(capture_project(&bad, None), None);
let path = crate::user_project_default::default_project_path().unwrap();
assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
}
#[test]
fn capture_binding_preserves_forced_until_from_the_winning_tier() {
use crate::session_state::{ProjectBinding, SessionState};
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT");
let pid = uuid::Uuid::from_u128(2);
let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
let s = SessionState {
active_project: Some(ProjectBinding {
project_id: pid.to_string(),
project_name: "n".into(),
updated_at: "".into(),
forced_until: Some(future.clone()),
}),
..Default::default()
};
let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
assert_eq!(got.forced_until, Some(future));
}
#[test]
fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT", uuid);
let got = env_project_binding().expect("uuid form is honoured");
assert_eq!(got.project_id, uuid);
_guard.set("TRACEVAULT_PROJECT", "my-project");
assert!(
env_project_binding().is_none(),
"a name is ignored on the network-free capture path"
);
_guard.remove("TRACEVAULT_PROJECT");
assert!(env_project_binding().is_none());
}
fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
crate::session_state::ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "p".into(),
updated_at: chrono::Utc::now().to_rfc3339(),
forced_until: forced_until.map(str::to_string),
}
}
#[test]
fn env_force_is_explicit_and_needs_no_expiry() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
assert_eq!(attribution_mode(None), AttributionMode::Explicit);
}
#[test]
fn absent_or_unrecognised_env_is_derived() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
assert_eq!(attribution_mode(None), AttributionMode::Derived);
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
assert_eq!(attribution_mode(None), AttributionMode::Derived);
}
#[test]
fn live_binding_force_is_explicit_without_env() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
let binding = forced_binding(Some(&future));
assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
}
#[test]
fn lapsed_binding_force_is_derived_without_env() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
let binding = forced_binding(Some(&past));
assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
}
#[test]
fn unparseable_forced_until_is_derived() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let binding = forced_binding(Some("not-a-timestamp"));
assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
}
#[test]
fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
let binding = forced_binding(Some(&past));
assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
}
#[tokio::test]
async fn session_scoped_force_is_honoured_on_the_wire() {
use crate::session_state::{ProjectBinding, SessionState};
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
_guard.remove("TRACEVAULT_PROJECT");
let pid = uuid::Uuid::from_u128(321);
let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
let session = SessionState {
active_project: Some(ProjectBinding {
project_id: pid.to_string(),
project_name: "proj".into(),
updated_at: "".into(),
forced_until: Some(future),
}),
..Default::default()
};
let capture_binding = capture_binding(&session, None);
let resp = ok_stream_response();
let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let mut warned = false;
let got = send_stream_event(
&client,
&Attribution::ProjectOnly { project_id: pid },
attribution_force(capture_binding.as_ref()),
&req,
&mut warned,
)
.await
.expect("send_stream_event must succeed");
assert_eq!(
got.expect("a successful send returns a response").status,
"accepted"
);
let captured = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
captured
.to_lowercase()
.contains("x-tracevault-project-attribution: explicit"),
"a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
);
}
#[test]
fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
use crate::session_state::{ProjectBinding, SessionState};
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let project_a = uuid::Uuid::from_u128(1);
let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
crate::user_project_default::save(&ProjectBinding {
project_id: project_a.to_string(),
project_name: "a".into(),
updated_at: chrono::Utc::now().to_rfc3339(),
forced_until: Some(future),
})
.unwrap();
let project_b = uuid::Uuid::from_u128(2);
_guard.set("TRACEVAULT_PROJECT", project_b.to_string());
let capture_binding = capture_binding(&SessionState::default(), None);
assert_eq!(
capture_binding.as_ref().map(|b| b.project_id.as_str()),
Some(project_b.to_string()).as_deref(),
"TRACEVAULT_PROJECT must outrank the user-level default"
);
assert_eq!(
attribution_mode(capture_binding.as_ref()),
AttributionMode::Derived,
"a force on the user-default project must not leak onto a DIFFERENT, \
higher-precedence project that never asked to be forced"
);
}
use std::io::BufReader;
use std::net::TcpListener;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
let deadline = Instant::now() + ACCEPT_DEADLINE;
loop {
match listener.accept() {
Ok((stream, _)) => {
let _ = stream.set_nonblocking(false);
return Some(stream);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if Instant::now() >= deadline {
return None;
}
thread::sleep(Duration::from_millis(20));
}
Err(_) => return None,
}
}
}
const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
fn capture_request_and_respond(
stream: std::net::TcpStream,
tx: &mpsc::Sender<String>,
response: &str,
) {
let mut reader = BufReader::new(stream);
let mut captured = String::new();
let _ = reader.read_line(&mut captured);
loop {
let mut header = String::new();
if reader.read_line(&mut header).unwrap_or(0) == 0 {
break;
}
if header.trim().is_empty() {
break;
}
captured.push_str(&header);
}
let _ = tx.send(captured);
let mut stream = reader.into_inner();
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
if let Some(stream) = accept_with_deadline(&listener) {
capture_request_and_respond(stream, &tx, response);
}
});
(format!("http://{addr}"), rx)
}
fn ok_stream_response() -> String {
let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
session_db_id: uuid::Uuid::nil(),
event_db_id: Some(uuid::Uuid::nil()),
status: "accepted".to_string(),
})
.unwrap();
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
)
}
fn sample_stream_event_request() -> StreamEventRequest {
StreamEventRequest {
protocol_version: 2,
tool: Some("claude-code".to_string()),
event_type: StreamEventType::ToolUse,
session_id: "sess-1".into(),
timestamp: chrono::Utc::now(),
hook_event_name: Some("PostToolUse".into()),
tool_name: None,
tool_use_id: None,
tool_input: None,
tool_response: None,
tool_is_error: None,
event_index: None,
event_uuid: None,
transcript_lines: None,
transcript_offset: None,
model: None,
cwd: None,
final_stats: None,
flow_id: None,
labels: None,
params: None,
billing_mode: None,
}
}
#[tokio::test]
async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
use crate::session_state::{ProjectBinding, SessionState};
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_PROJECT");
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let pid = uuid::Uuid::from_u128(99);
let session = SessionState {
active_project: Some(ProjectBinding {
project_id: pid.to_string(),
project_name: "proj".into(),
updated_at: "".into(),
forced_until: None,
}),
..Default::default()
};
let capture_binding = capture_binding(&session, None);
let capture_pid = capture_binding
.as_ref()
.and_then(crate::resolution::capture_project_id);
assert_eq!(capture_pid, Some(pid));
let resp = ok_stream_response();
let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let mut warned = false;
let got = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: capture_pid,
},
attribution_force(capture_binding.as_ref()),
&req,
&mut warned,
)
.await
.expect("send_stream_event must succeed");
assert_eq!(
got.expect("a successful send returns a response").status,
"accepted"
);
let line = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
line.starts_with(&format!(
"POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
)),
"an active project binding must route to the project-scoped endpoint, got: {line}"
);
assert!(
line.to_lowercase()
.contains("x-tracevault-project-attribution: derived"),
"got: {line}"
);
}
#[tokio::test]
async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
use crate::session_state::SessionState;
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_PROJECT");
let capture_binding = capture_binding(&SessionState::default(), None);
assert_eq!(capture_binding, None);
let resp = ok_stream_response();
let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let mut warned = false;
let got = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: None,
},
attribution_force(capture_binding.as_ref()),
&req,
&mut warned,
)
.await
.expect("send_stream_event must succeed");
assert_eq!(
got.expect("a successful send returns a response").status,
"accepted"
);
let line = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
"no binding must fall back to the repo-scoped endpoint, got: {line}"
);
}
fn spawn_n_capturing_requests(
responses: Vec<&'static str>,
) -> (String, mpsc::Receiver<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for response in responses {
let Some(stream) = accept_with_deadline(&listener) else {
break;
};
capture_request_and_respond(stream, &tx, response);
}
});
(format!("http://{addr}"), rx)
}
#[tokio::test]
async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
let resp_400 = format!(
"HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body_400.len(),
body_400
);
let resp_200 = ok_stream_response();
let (base, rx) = spawn_n_capturing_requests(vec![
Box::leak(resp_400.into_boxed_str()),
Box::leak(resp_200.into_boxed_str()),
]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(42);
let mut warned = false;
let err = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: Some(pid),
},
attribution_force(None),
&req,
&mut warned,
)
.await
.expect_err("a refused declared project must be an error, not a silent fallback");
assert!(
err.to_string().contains("400"),
"propagated error must reflect the status, got: {err}"
);
assert!(
warned,
"the refusal must be printed (gated on `warned`) so it is visible"
);
let first = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no first request captured");
assert!(
first.contains(&format!("/projects/{pid}/stream")),
"first request must hit the project-scoped endpoint, got: {first}"
);
assert!(
first.contains("repo_id="),
"first request must carry repo_id, got: {first}"
);
assert!(
rx.recv_timeout(Duration::from_millis(500)).is_err(),
"no second (repo-scoped fallback) request must be sent"
);
}
#[tokio::test]
async fn send_stream_event_errors_on_403_without_fallback() {
let body_403 = "forbidden";
let resp_403 = format!(
"HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body_403.len(),
body_403
);
let resp_200 = ok_stream_response();
let (base, rx) = spawn_n_capturing_requests(vec![
Box::leak(resp_403.into_boxed_str()),
Box::leak(resp_200.into_boxed_str()),
]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(43);
let mut warned = false;
let err = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: Some(pid),
},
attribution_force(None),
&req,
&mut warned,
)
.await
.expect_err("a refused declared project must be an error, not a silent fallback");
assert!(
err.to_string().contains("403"),
"propagated error must reflect the status, got: {err}"
);
assert!(
warned,
"the refusal must be printed (gated on `warned`) so it is visible"
);
let first = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no first request captured");
assert!(
first.contains(&format!("/projects/{pid}/stream")),
"first request must hit the project-scoped endpoint, got: {first}"
);
assert!(
rx.recv_timeout(Duration::from_millis(500)).is_err(),
"no second (repo-scoped fallback) request must be sent"
);
}
#[tokio::test]
async fn refused_error_is_printed_once_per_invocation() {
let body_400 = "not a member";
let resp_400 = || {
format!(
"HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body_400.len(),
body_400
)
};
let (base, _rx) = spawn_n_capturing_requests(vec![
Box::leak(resp_400().into_boxed_str()),
Box::leak(resp_400().into_boxed_str()),
]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(44);
let attribution = Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: Some(pid),
};
let mut warned = false;
assert!(
send_stream_event(
&client,
&attribution,
attribution_force(None),
&req,
&mut warned
)
.await
.is_err(),
"a refused declared project must be an error"
);
assert!(warned, "the flag must be set after the first refusal");
assert!(
send_stream_event(
&client,
&attribution,
attribution_force(None),
&req,
&mut warned
)
.await
.is_err(),
"a second refusal must also be an error"
);
assert!(warned, "the flag stays set across the shared invocation");
}
#[tokio::test]
async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
let body_403 = "forbidden";
let resp_403 = format!(
"HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body_403.len(),
body_403
);
let resp_200 = ok_stream_response();
let (base, rx) = spawn_n_capturing_requests(vec![
Box::leak(resp_403.into_boxed_str()),
Box::leak(resp_200.into_boxed_str()),
]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(42);
let forced = crate::session_state::ProjectBinding {
project_id: pid.to_string(),
project_name: "forced".into(),
updated_at: "".into(),
forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
};
let mut warned = false;
let err = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: Some(pid),
},
attribution_force(Some(&forced)),
&req,
&mut warned,
)
.await
.expect_err("a refused force must be an error, not a silent fallback");
assert!(
err.to_string().contains("403"),
"propagated error must reflect the status, got: {err}"
);
assert!(warned, "the refusal must be printed exactly once");
let first = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no first request captured");
assert!(
first.contains(&format!("/projects/{pid}/stream")),
"first request must hit the project-scoped endpoint, got: {first}"
);
assert!(
first
.to_lowercase()
.contains("x-tracevault-project-attribution: explicit"),
"the refused send must have DECLARED explicit — this is the mode \
`refused_error` is handed: {first}"
);
assert!(
rx.recv_timeout(Duration::from_millis(500)).is_err(),
"a refused force must NOT be re-attributed via the repo-scoped endpoint"
);
}
#[tokio::test]
async fn send_stream_event_project_only_omits_repo_id() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let resp = ok_stream_response();
let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(11);
let mut warned = false;
let got = send_stream_event(
&client,
&Attribution::ProjectOnly { project_id: pid },
attribution_force(None),
&req,
&mut warned,
)
.await
.expect("a repo-less project send must succeed");
assert_eq!(
got.expect("a successful send returns a response").status,
"accepted"
);
let line = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
"expected a bare project path with no query string, got: {line}"
);
assert!(
line.to_lowercase()
.contains("x-tracevault-project-attribution: derived"),
"with no forced binding, the header must declare `derived`, got: {line}"
);
assert!(
!warned,
"a repo-less send has no fallback and must not warn about one"
);
}
#[tokio::test]
async fn send_stream_event_project_only_drops_on_scoping_4xx() {
let body = "no such project";
let resp_404 = format!(
"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let (base, rx) = spawn_n_capturing_requests(vec![
Box::leak(resp_404.clone().into_boxed_str()),
Box::leak(resp_404.into_boxed_str()),
]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(12);
let mut warned = false;
let got = send_stream_event(
&client,
&Attribution::ProjectOnly { project_id: pid },
attribution_force(None),
&req,
&mut warned,
)
.await
.expect("an undeliverable repo-less event is dropped, not surfaced as Err");
assert!(
got.is_none(),
"Ok(None) signals the deliberate drop; Some(_) would read as a real send"
);
assert!(
warned,
"dropping data silently is the failure mode to avoid"
);
let first = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
first.contains(&format!("/projects/{pid}/stream")),
"must hit the project-scoped endpoint, got: {first}"
);
assert!(
rx.recv_timeout(Duration::from_millis(500)).is_err(),
"a repo-less send must make exactly one request — no fallback exists"
);
}
#[tokio::test]
async fn send_stream_event_project_only_buffers_on_403() {
let body = "forbidden";
let resp_403 = format!(
"HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let mut warned = false;
let err = send_stream_event(
&client,
&Attribution::ProjectOnly {
project_id: uuid::Uuid::from_u128(13),
},
attribution_force(None),
&req,
&mut warned,
)
.await
.expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
assert!(
err.to_string().contains("403"),
"propagated error must reflect the status, got: {err}"
);
}
#[tokio::test]
async fn send_stream_event_does_not_fall_back_on_transient_503() {
let body_503 = "internal error";
let resp_503 = format!(
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body_503.len(),
body_503
);
let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let req = sample_stream_event_request();
let pid = uuid::Uuid::from_u128(7);
let mut warned = false;
let err = send_stream_event(
&client,
&Attribution::Repo {
repo_id: "11111111-1111-1111-1111-111111111111".into(),
project: Some(pid),
},
attribution_force(None),
&req,
&mut warned,
)
.await
.expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
assert!(
err.to_string().contains("503"),
"propagated error must reflect the transient status, got: {err}"
);
assert!(
deterministic_client_error_kind(err.as_ref()).is_none(),
"a 503 must not be classified as a deterministic client error"
);
let first = rx
.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
.expect("no request captured");
assert!(
first.contains(&format!("/projects/{pid}/stream")),
"must hit the project-scoped endpoint, got: {first}"
);
assert!(
rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
"no second (fallback) request should have been sent for a transient error"
);
}
#[test]
fn a_403_is_classified_apart_from_the_scoping_statuses() {
let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
assert_eq!(
deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
Some(ClientErrorKind::Forbidden)
);
for scoping in [
"Stream failed (400 Bad Request): {}",
"Stream failed (404 Not Found): {}",
"Stream failed (409 Conflict): {}",
] {
assert_eq!(
deterministic_client_error_kind(err(scoping).as_ref()),
Some(ClientErrorKind::Scoping),
"{scoping}"
);
}
for transient in [
"Stream failed (401 Unauthorized): {}",
"Stream failed (503 Service Unavailable): {}",
"error sending request for url (http://x/stream)",
] {
assert_eq!(
deterministic_client_error_kind(err(transient).as_ref()),
None,
"{transient}"
);
}
}
#[test]
fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
let pid = uuid::Uuid::from_u128(7);
let forbidden = refused_error(
pid,
&ClientErrorKind::Forbidden,
AttributionForce::default(),
);
assert!(forbidden.contains("403"), "{forbidden}");
assert!(
forbidden.contains("no `tracevault` grant in Control Plane"),
"must offer the missing-role explanation: {forbidden}"
);
assert!(
forbidden.contains("no `Operator` role on it"),
"must still offer the project explanation: {forbidden}"
);
assert!(
forbidden.starts_with("tracevault: error:"),
"a refusal is an error, not a warning: {forbidden}"
);
assert!(forbidden.contains(&pid.to_string()));
let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
assert!(scoping.contains("project switch"), "{scoping}");
assert!(
!scoping.contains("`tracevault` grant"),
"the scoping case must not mention the `tracevault` grant: {scoping}"
);
for s in [&forbidden, &scoping] {
assert!(s.contains("--user"), "must name the --user fix: {s}");
assert!(
s.contains("user_project.toml"),
"must name the machine-wide default's file: {s}"
);
assert!(
!s.contains("repo deduction"),
"must never describe re-attribution to another project: {s}"
);
assert!(
!s.contains("Attributing via"),
"must never claim the event was re-attributed: {s}"
);
}
}
#[test]
fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
let pid = uuid::Uuid::from_u128(7);
let explicit = refused_error(
pid,
&ClientErrorKind::Forbidden,
AttributionForce {
env: false,
binding: true,
},
);
assert!(
explicit.contains("FORCE"),
"the refusal of the force itself must be named: {explicit}"
);
assert!(
explicit.contains("Operator"),
"must name the grant forcing requires: {explicit}"
);
assert!(
explicit.contains("Control Plane"),
"must name the identity forcing requires: {explicit}"
);
assert!(
explicit.contains("`tracevault` grant")
&& explicit.contains("no `Operator` role on it"),
"the membership causes must still be named: {explicit}"
);
assert!(
!explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
"must never claim the event was re-attributed: {explicit}"
);
let derived = refused_error(
pid,
&ClientErrorKind::Forbidden,
AttributionForce::default(),
);
assert!(
!derived.contains("FORCE"),
"a `derived` send never forced anything: {derived}"
);
}
#[test]
fn an_explicit_scoping_failure_does_not_blame_the_force() {
let pid = uuid::Uuid::from_u128(7);
let scoping = refused_error(
pid,
&ClientErrorKind::Scoping,
AttributionForce {
env: true,
binding: true,
},
);
assert!(!scoping.contains("FORCE"), "{scoping}");
assert_eq!(
scoping,
refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
"the scoping wording does not depend on the mode"
);
}
#[test]
fn the_403_remediation_names_the_force_source_actually_in_effect() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
let pid = uuid::Uuid::from_u128(7);
let live = forced_binding(Some(
&(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
));
let never_forced = forced_binding(None);
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let env_only = refused_error(
pid,
&ClientErrorKind::Forbidden,
attribution_force(Some(&never_forced)),
);
assert!(
env_only.contains("FORCE"),
"an env-sourced force is still a force: {env_only}"
);
assert!(
env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
"must name the variable that is doing the forcing: {env_only}"
);
assert!(
!env_only.contains("--project-attribution"),
"must NOT tell the operator to drop a flag that would change \
nothing here — this is the bug: {env_only}"
);
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let binding_only = refused_error(
pid,
&ClientErrorKind::Forbidden,
attribution_force(Some(&live)),
);
assert!(
binding_only.contains("--project-attribution"),
"a persisted force IS cleared by switching without the flag: {binding_only}"
);
assert!(
!binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
"must not send the operator after an unset variable: {binding_only}"
);
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let both = refused_error(
pid,
&ClientErrorKind::Forbidden,
attribution_force(Some(&live)),
);
assert!(
both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
&& both.contains("--project-attribution"),
"both sources are in effect and both must be named: {both}"
);
assert!(
both.contains("BOTH"),
"must say that removing only one is not enough: {both}"
);
}
#[test]
fn no_force_means_no_remediation_clause() {
let pid = uuid::Uuid::from_u128(7);
let none = refused_error(
pid,
&ClientErrorKind::Forbidden,
AttributionForce::default(),
);
assert!(
!none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
&& !none.contains("--project-attribution"),
"a derived send has no force to remove: {none}"
);
}
fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
let path = dir.join("transcript.jsonl");
let mut body = String::new();
for i in 0..n {
let line = serde_json::json!({
"type": "user",
"n": i,
"message": {"content": "x".repeat(line_bytes)},
});
body.push_str(&line.to_string());
body.push('\n');
}
fs::write(&path, body).unwrap();
path
}
fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
StreamEventRequest {
tool_name: Some("Bash".into()),
tool_use_id: Some("toolu_1".into()),
tool_input: Some(serde_json::json!({"command": "ls"})),
event_uuid: Some(uuid::Uuid::now_v7()),
transcript_lines: Some(lines),
transcript_offset: Some(offset),
..sample_stream_event_request()
}
}
fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
part.transcript_lines.clone().unwrap_or_default()
}
fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
parts
.iter()
.flat_map(|p| {
let offset = p.transcript_offset.unwrap();
part_lines(p)
.into_iter()
.enumerate()
.map(move |(i, l)| (offset + i as i64, l))
})
.collect()
}
fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
(0..n)
.map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
.collect()
}
#[test]
fn split_leaves_a_request_under_the_cap_unchanged() {
let req = event_with_lines(big_lines(3, 100), 0);
let parts = split_into_parts(req.clone());
assert_eq!(parts.len(), 1);
assert_eq!(
serde_json::to_value(&parts[0]).unwrap(),
serde_json::to_value(&req).unwrap()
);
}
#[test]
fn split_carries_every_line_of_a_batch_over_the_cap() {
let dir = tempfile::tempdir().unwrap();
let transcript = write_transcript(dir.path(), 300, 5_000);
let (lines, start, _) =
read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
let req = event_with_lines(lines.clone(), start);
assert!(req.serialized_len() > MAX_REQUEST_BYTES);
let parts = split_into_parts(req.clone());
assert!(parts.len() >= 3, "got {} parts", parts.len());
for part in &parts {
assert!(
part.serialized_len() <= MAX_REQUEST_BYTES,
"part of {} bytes exceeds the cap",
part.serialized_len()
);
}
let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
assert_eq!(sent, lines, "every line, once, in order");
let (event, transcript_parts) = parts.split_last().unwrap();
assert_eq!(event.event_type, StreamEventType::ToolUse);
assert_eq!(event.event_uuid, req.event_uuid);
assert_eq!(event.tool_input, req.tool_input);
for part in transcript_parts {
assert_eq!(part.event_type, StreamEventType::Transcript);
assert!(part.event_uuid.is_none());
assert!(part.tool_input.is_none());
assert!(part.tool_name.is_none());
}
assert!(
!part_lines(event).is_empty(),
"the event keeps the lines that fit beside it"
);
}
#[test]
fn split_keeps_each_lines_unsplit_chunk_index() {
let lines = big_lines(300, 5_000);
let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
let expected: Vec<_> = lines
.into_iter()
.enumerate()
.map(|(i, l)| (1_000 + i as i64, l))
.collect();
assert_eq!(chunk_indexes(&parts), expected);
}
#[test]
fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
let lines = big_lines(10, 200_000);
let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
for (index, line) in &short {
let in_long = long.iter().find(|(_, l)| l == line).unwrap();
assert_eq!(in_long.0, *index, "line {line} indexed differently");
}
}
#[test]
fn split_sends_a_single_oversized_line_alone() {
let lines = vec![
serde_json::json!({"n": 0}),
serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
serde_json::json!({"n": 2}),
];
let parts = split_into_parts(event_with_lines(lines.clone(), 0));
let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
assert_eq!(sent, lines);
let big = parts
.iter()
.find(|p| part_lines(p).contains(&lines[1]))
.unwrap();
assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
assert_eq!(big.transcript_offset, Some(1));
}
fn far_deadline() -> std::time::Instant {
std::time::Instant::now() + Duration::from_secs(60)
}
fn captured_body(captured: &str) -> StreamEventRequest {
let body = captured.splitn(3, " | ").nth(2).expect("captured body");
serde_json::from_str(body).expect("request body is a StreamEventRequest")
}
#[tokio::test]
async fn deliver_parts_sends_every_part() {
let dir = tempfile::tempdir().unwrap();
let pending_path = dir.path().join("pending.jsonl");
let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let all_accepted = deliver_parts(
&client,
&repo_attr(&uuid::Uuid::new_v4().to_string()),
AttributionForce::default(),
parts.clone(),
&pending_path,
false,
far_deadline(),
&mut false,
)
.await
.unwrap();
assert!(all_accepted);
for part in &parts {
let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
assert_eq!(got.transcript_offset, part.transcript_offset);
assert_eq!(got.transcript_lines, part.transcript_lines);
}
assert!(drain_pending(&pending_path).unwrap().is_empty());
}
#[tokio::test]
async fn deliver_parts_queues_the_failed_part_and_the_rest() {
let dir = tempfile::tempdir().unwrap();
let pending_path = dir.path().join("pending.jsonl");
let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
assert!(parts.len() >= 3);
let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let all_accepted = deliver_parts(
&client,
&repo_attr(&uuid::Uuid::new_v4().to_string()),
AttributionForce::default(),
parts.clone(),
&pending_path,
false,
far_deadline(),
&mut false,
)
.await
.unwrap();
assert!(!all_accepted);
assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
assert!(
rx.recv_timeout(Duration::from_millis(300)).is_err(),
"nothing is sent after the first failure"
);
let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
.unwrap()
.iter()
.map(|j| serde_json::from_str(j).unwrap())
.collect();
assert_eq!(queued.len(), parts.len() - 1);
for (q, part) in queued.iter().zip(&parts[1..]) {
assert_eq!(q.transcript_offset, part.transcript_offset);
assert_eq!(q.transcript_lines, part.transcript_lines);
}
}
#[tokio::test]
async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
let dir = tempfile::tempdir().unwrap();
let pending_path = dir.path().join("pending.jsonl");
let parts = split_into_parts(sample_stream_event_request());
let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
let all_accepted = deliver_parts(
&client,
&repo_attr(&uuid::Uuid::new_v4().to_string()),
AttributionForce::default(),
parts,
&pending_path,
true,
far_deadline(),
&mut false,
)
.await
.unwrap();
assert!(!all_accepted);
assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
}
#[tokio::test]
async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
let dir = tempfile::tempdir().unwrap();
let pending_path = dir.path().join("pending.jsonl");
let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
let client = crate::api_client::ApiClient::new(&base, Some("tok"));
let all_accepted = deliver_parts(
&client,
&repo_attr(&uuid::Uuid::new_v4().to_string()),
AttributionForce::default(),
parts.clone(),
&pending_path,
false,
std::time::Instant::now(),
&mut false,
)
.await
.unwrap();
assert!(!all_accepted);
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
}
}