Skip to main content

tracevault_cli/commands/
stream.rs

1use std::collections::HashMap;
2use std::fs::{self, OpenOptions};
3use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
4use std::path::Path;
5
6use tracevault_protocol::hooks::{parse_hook_event, HookResponse};
7use tracevault_protocol::streaming::{
8    extract_is_error_from_transcript, StreamEventRequest, StreamEventType, MAX_REQUEST_BYTES,
9};
10
11/// Convert a resolved [`crate::context::EffectiveContext`] into the three
12/// optional fields that are stamped onto a [`StreamEventRequest`].
13///
14/// - `flow_id`  — taken directly from `ctx.flow_id`
15/// - `labels`   — `None` when the vec is empty, `Some(vec)` otherwise
16/// - `params`   — `None` when the map is empty, `Some(HashMap)` otherwise
17///   (BTreeMap → HashMap conversion)
18///
19/// This is a pure function so it can be unit-tested without I/O.
20#[allow(clippy::type_complexity)]
21pub fn apply_context(
22    ctx: crate::context::EffectiveContext,
23) -> (
24    Option<String>,
25    Option<Vec<String>>,
26    Option<HashMap<String, String>>,
27) {
28    let flow_id = ctx.flow_id;
29    let labels = if ctx.labels.is_empty() {
30        None
31    } else {
32        Some(ctx.labels)
33    };
34    let params = if ctx.params.is_empty() {
35        None
36    } else {
37        Some(ctx.params.into_iter().collect())
38    };
39    (flow_id, labels, params)
40}
41
42/// Returns `(lines, start_offset, end_offset)`: `start_offset` is the seek
43/// position read from `offset_path` (0 if absent), and `end_offset` is the
44/// byte offset after the last line read (the old `bytes_read`).
45///
46/// Callers should send `start_offset` as `StreamEventRequest::transcript_offset`
47/// (so the server's `chunk_index = transcript_offset + line_index` is stable
48/// per physical line across overlapping/retried reads) and persist
49/// `end_offset` to `.stream_offset` as the next read's seek position.
50pub fn read_new_transcript_lines(
51    transcript_path: &Path,
52    offset_path: &Path,
53) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
54    // An empty path means "no transcript yet" — Codex documents `transcript_path`
55    // as nullable (e.g. on SessionStart before a rollout exists), and the hook
56    // payload deserializes null/absent to "". Guard explicitly so we never hand
57    // `Path::new("")` to `exists()`/`File::open` (whose behavior on an empty path
58    // is platform-dependent); treat it as a clean no-op.
59    if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
60        return Ok((vec![], 0, 0));
61    }
62
63    let offset: i64 = if offset_path.exists() {
64        let content = fs::read_to_string(offset_path)?;
65        content
66            .trim()
67            .parse::<i64>()
68            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
69    } else {
70        0
71    };
72
73    let mut file = fs::File::open(transcript_path)?;
74    file.seek(SeekFrom::Start(offset as u64))?;
75
76    let reader = io::BufReader::new(file);
77    let mut lines = Vec::new();
78    let mut bytes_read = offset;
79
80    for line_result in reader.lines() {
81        let line = line_result?;
82        // +1 for the newline character
83        bytes_read += line.len() as i64 + 1;
84        if line.trim().is_empty() {
85            continue;
86        }
87        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
88            lines.push(value);
89        }
90    }
91
92    Ok((lines, offset, bytes_read))
93}
94
95/// Store `transcript_path` in the session's `metadata.json`, which is where
96/// `tracevault check` looks for the transcript it counts tool calls from.
97/// Without it every session reports no tool calls, and a "must call X" policy
98/// can never pass. Other keys in the file are kept. An empty path (Codex
99/// before its first record) writes nothing, and an unchanged path skips the
100/// write. The file is replaced atomically: parallel tool hooks of one session
101/// run concurrently, and `check` must never read a half-written file.
102pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
103    if transcript_path.is_empty() {
104        return Ok(());
105    }
106    let meta_path = session_dir.join("metadata.json");
107    let mut meta = fs::read_to_string(&meta_path)
108        .ok()
109        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
110        .filter(serde_json::Value::is_object)
111        .unwrap_or_else(|| serde_json::json!({}));
112    if meta.get("transcript_path").and_then(|v| v.as_str()) == Some(transcript_path) {
113        return Ok(());
114    }
115    meta["transcript_path"] = serde_json::Value::String(transcript_path.to_string());
116    let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
117    fs::write(&tmp, meta.to_string())?;
118    fs::rename(&tmp, &meta_path).inspect_err(|_| {
119        let _ = fs::remove_file(&tmp);
120    })
121}
122
123/// Fileless agents (OpenCode) have no transcript for `tracevault check` to
124/// count tool calls from: their records ride inline on each hook event. Append
125/// one slim `toolCall` record per tool called in `records` to the session's
126/// `tool_calls.jsonl` and record that file as the session's transcript. Only
127/// the tool name is kept — arguments and outputs (file contents, bash stdout)
128/// would grow the file for nothing. Records with no tool call write nothing.
129pub fn record_inline_tool_calls(
130    session_dir: &Path,
131    records: &[serde_json::Value],
132) -> Result<(), io::Error> {
133    let lines: String = records
134        .iter()
135        .flat_map(crate::transcript::tool_call_names)
136        .map(|name| {
137            let record = serde_json::json!({
138                "type": "message",
139                "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
140            });
141            format!("{record}\n")
142        })
143        .collect();
144    if lines.is_empty() {
145        return Ok(());
146    }
147    let log_path = session_dir.join("tool_calls.jsonl");
148    OpenOptions::new()
149        .create(true)
150        .append(true)
151        .open(&log_path)?
152        .write_all(lines.as_bytes())?;
153    record_transcript_path(session_dir, &log_path.to_string_lossy())
154}
155
156pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
157    let mut file = OpenOptions::new()
158        .create(true)
159        .append(true)
160        .open(pending_path)?;
161    writeln!(file, "{json}")?;
162    Ok(())
163}
164
165pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
166    if !pending_path.exists() {
167        return Ok(vec![]);
168    }
169    let content = fs::read_to_string(pending_path)?;
170    let lines: Vec<String> = content
171        .lines()
172        .filter(|l| !l.trim().is_empty())
173        .map(String::from)
174        .collect();
175    fs::remove_file(pending_path)?;
176    Ok(lines)
177}
178
179/// How a stream event is attributed on the wire, resolved from the local repo
180/// and project bindings before anything is sent.
181///
182/// The rule this type encodes: an event ships when EITHER a repo or a project
183/// resolves. Before this existed the hook required a repo binding and dropped
184/// the event otherwise, which silently discarded every event of a repo-less
185/// session even when its project was bound — despite the server supporting
186/// exactly that shape (`ProjectStreamQuery::repo_id` is `Option<Uuid>`:
187/// "repo-less (0-repo) projects are supported").
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub(crate) enum Attribution {
190    /// A usable repo binding resolved. `project` is the capture-time project
191    /// overlay; when `None` the server deduces the project from the repo.
192    Repo {
193        repo_id: String,
194        project: Option<uuid::Uuid>,
195    },
196    /// No usable repo binding, but a project did — repo-less project-scoped
197    /// ingest.
198    ProjectOnly { project_id: uuid::Uuid },
199}
200
201impl Attribution {
202    /// Offline-queue filename for this attribution. Keyed by whatever
203    /// identifies the target so a mid-session rebind (workspace mode) can
204    /// never flush one target's queued events to another.
205    ///
206    /// The `project-` infix is load-bearing for back-compat: an older CLI's
207    /// `repo_id_from_pending_filename` extracts `project-<uuid>` from this
208    /// name, fails its UUID check, and skips the file — so a downgrade leaves
209    /// these queues alone instead of trying to POST them at a repo endpoint.
210    pub(crate) fn pending_file_name(&self) -> String {
211        use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
212        match self {
213            Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
214            Self::ProjectOnly { project_id } => {
215                format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
216            }
217        }
218    }
219}
220
221/// Pure attribution resolver: fold the repo binding and the capture-time
222/// project into the target this event will be sent to. `None` means neither
223/// resolved and the hook must no-op.
224///
225/// A binding whose `repo_id` is not a UUID degrades to `ProjectOnly` rather
226/// than dropping the event — a corrupted session-state file should cost the
227/// repo attribution, not the whole trace, when a project is available.
228///
229/// `project` here is whatever `capture_project` resolved, and its lowest tier
230/// is the MACHINE-GLOBAL `project switch --user` default — not just
231/// session-scoped bindings. That tier is therefore now a sufficient condition
232/// for an event to ship, where previously it could only redirect an event that
233/// was already shipping because a repo bound. This is deliberate: it is the
234/// only binding a container can establish before the agent session exists and
235/// before the repo is cloned, which is the case this whole path serves.
236/// `resolve_stream_binding` has the same machine-global tier for repos, so the
237/// two sides stay symmetric. Consequence worth knowing: a session started in an
238/// unrelated directory, with no repo and no `.tracevault/`, will attribute to
239/// that default project.
240pub(crate) fn attribution_for(
241    binding: Option<&crate::session_state::RepoBinding>,
242    project: Option<uuid::Uuid>,
243) -> Option<Attribution> {
244    match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
245        Some(b) => Some(Attribution::Repo {
246            repo_id: b.repo_id.clone(),
247            project,
248        }),
249        None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
250    }
251}
252
253/// Offline-queue path for an attribution target.
254fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
255    session_dir.join(attribution.pending_file_name())
256}
257
258/// Resolve the project root and session directory for a stream hook invocation.
259///
260/// This is the pure, testable core of `run_stream`'s path resolution. It uses
261/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
262/// --git-common-dir` first, so it correctly resolves to the **primary**
263/// `.tracevault/` directory from any worktree — including sibling linked
264/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
265///
266/// Returns `(resolved, session_dir)` — the resolved
267/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
268/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
269/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
270pub fn resolve_session_paths(
271    hook_cwd: &Path,
272    session_id: &str,
273) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
274    let resolved = crate::paths::resolve_project_root(hook_cwd);
275    let session_dir = resolved
276        .root
277        .join(".tracevault")
278        .join("sessions")
279        .join(session_id);
280    (resolved, session_dir)
281}
282
283/// A resolved binding is usable for hook attribution only if its repo_id is a
284/// real UUID — guards against a corrupted/edited session-state file injecting
285/// path separators into the pending-<repo_id>.jsonl filename.
286///
287/// `pub(crate)`: also called by `commands::status`, so a binding with a
288/// malformed `repo_id` is never displayed as bound (`Check::ok`) when this
289/// same check means the hook will not actually honor it.
290pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
291    uuid::Uuid::parse_str(repo_id).is_ok()
292}
293
294/// The effective repo binding for a stream event, given the loaded session
295/// state, the event's worktree, and the bound-config fallback. Pure — the
296/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
297pub(crate) fn resolve_stream_binding(
298    session: &crate::session_state::SessionState,
299    worktree: &str,
300    bound: Option<crate::session_state::RepoBinding>,
301    user_default: Option<crate::session_state::RepoBinding>,
302) -> Option<crate::session_state::RepoBinding> {
303    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
304        repo_flag: None,
305        session,
306        worktree_path: Some(worktree),
307        bound,
308        user_default,
309    })
310    .map(|(b, _)| b)
311}
312
313/// `TRACEVAULT_PROJECT` as a binding, UUID form only.
314///
315/// A project NAME would require a `list_projects` round trip, and the capture
316/// path fires per event in a short-lived process — the same reason
317/// `capture_project` already ignores the repo config's `default_project`. The
318/// name form is honoured by the interactive commands, which already have a
319/// client in hand.
320pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
321    let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
322    let raw = raw.trim();
323    let parsed = raw.parse::<uuid::Uuid>().ok()?;
324    Some(crate::session_state::ProjectBinding {
325        project_id: parsed.to_string(),
326        project_name: String::new(),
327        updated_at: String::new(),
328        forced_until: None,
329    })
330}
331
332/// WHICH of the two force sources put a send into `explicit` attribution —
333/// the reason behind [`attribution_mode`]'s verdict, not a second opinion on
334/// it.
335///
336/// The two sources are not interchangeable and, crucially, are not undone
337/// the same way: the env var is process-wide and cleared by unsetting it,
338/// while a persisted force lives on the binding and is cleared by switching
339/// again without the flag. Any message that tells an operator how to STOP
340/// forcing therefore has to know which one is actually in effect — telling
341/// someone whose force came from `TRACEVAULT_PROJECT_ATTRIBUTION` to drop a
342/// CLI flag is advice that silently changes nothing (Copilot on PR #54).
343///
344/// This carries the reason alongside the verdict instead of letting the
345/// message-building code re-derive it, because re-deriving it would mean a
346/// second copy of the env-var read and the `forced_until` parse — exactly
347/// the two-codepaths-for-one-fact shape whose removal is the whole point of
348/// [`attribution_mode`] taking the winning binding as a parameter.
349///
350/// `Default` is "neither source is forcing", i.e. plain derived attribution
351/// — the ordinary case, and what a test that cares about routing rather
352/// than attribution wants to pass.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
354pub(crate) struct AttributionForce {
355    /// `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` is set in this process's
356    /// environment. Never expires; only unsetting it stops the forcing.
357    pub(crate) env: bool,
358    /// The winning binding carries a LIVE `forced_until`. Lapses on its own
359    /// (~12h); `project switch` without `--project-attribution explicit`
360    /// clears it immediately.
361    pub(crate) binding: bool,
362}
363
364impl AttributionForce {
365    /// The verdict these sources add up to. Either source alone forces;
366    /// neither does not.
367    pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
368        if self.env || self.binding {
369            crate::api_client::AttributionMode::Explicit
370        } else {
371            crate::api_client::AttributionMode::Derived
372        }
373    }
374}
375
376/// Which attribution mode THIS PARTICULAR winning binding declares.
377///
378/// `explicit` comes either from `TRACEVAULT_PROJECT_ATTRIBUTION` (per-process,
379/// re-asserted at every launch, no expiry — genuinely global, by design) OR
380/// from a LIVE `forced_until` carried by `effective` — the exact
381/// [`crate::session_state::ProjectBinding`] that [`capture_project`] resolved
382/// as the one this event is being attributed to.
383///
384/// `forced_until` is stored PER-BINDING (see that field's own doc comment:
385/// "the FORCE lapses (the binding itself survives)"), so this must read the
386/// force off THAT binding and no other. An earlier version of this function
387/// instead did a process-global disk read
388/// (`user_project_default::load_with_force()`), which had it backwards two
389/// ways at once: a session-scoped force (`project switch` without `--user`,
390/// which is the ordinary case whenever a session id is set) is written into
391/// session state and was never read there at all, so it silently never took
392/// effect while still telling the user membership was not being checked; and
393/// a live force sitting on the user-level default leaked onto ANY
394/// higher-precedence project that happened to resolve instead (subagent
395/// override, `TRACEVAULT_PROJECT`, session active), stamping `explicit` for a
396/// project nobody forced. Taking `effective` as a parameter — the actual
397/// winning binding — makes both mistakes impossible: a force can only apply
398/// when it is attached to the binding actually being used.
399///
400/// Whether that force is live is [`crate::session_state::force_status`]'s
401/// answer, not this function's: `commands::project`'s status line reads the
402/// same field and must never disagree with the header this fills, so there is
403/// exactly one parse and one `Utc::now()` comparison. A lapsed persisted
404/// force reads as `derived` — not sending an `explicit` header IS the
405/// fallback, so ingest never starts failing because a force was forgotten —
406/// and so does an unparseable one, for the same fail-safe reason.
407///
408/// An unrecognised (or absent) `TRACEVAULT_PROJECT_ATTRIBUTION` also reads as
409/// `derived`, deliberately asymmetric with the server, which 400s an unknown
410/// value: that strictness is for callers that bypass the CLI entirely, and
411/// failing a hook over a typo'd env var helps nobody — silently falling back
412/// to the always-checked default is the safe direction to fail in.
413///
414/// This always returns one of the two variants and the caller always sends
415/// it as the header — including the
416/// [`crate::api_client::AttributionMode::Derived`] case. The
417/// server treats an absent header and an explicit `derived` value
418/// identically, but nothing here omits the header; "always emits one of two
419/// values" is simpler to reason about than "sometimes sends a header,
420/// sometimes doesn't."
421///
422/// A verdict only. Callers that must also explain THE REASON — the refusal
423/// remediation, which has to name the force source it is telling the
424/// operator to remove — take [`attribution_force`] instead and call
425/// [`AttributionForce::mode`] on it; both spellings run the one evaluation
426/// below.
427pub(crate) fn attribution_mode(
428    effective: Option<&crate::session_state::ProjectBinding>,
429) -> crate::api_client::AttributionMode {
430    attribution_force(effective).mode()
431}
432
433/// The single evaluation behind [`attribution_mode`]: reads both force
434/// sources ONCE and reports each separately, so the verdict and any
435/// explanation of it are the same fact viewed twice rather than two facts
436/// that can drift. See [`AttributionForce`] for why the distinction is
437/// load-bearing, and [`attribution_mode`]'s doc comment for why each source
438/// is read the way it is.
439pub(crate) fn attribution_force(
440    effective: Option<&crate::session_state::ProjectBinding>,
441) -> AttributionForce {
442    AttributionForce {
443        env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
444            .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
445            .unwrap_or(false),
446        binding: effective
447            .and_then(|b| b.forced_until.as_deref())
448            .is_some_and(|s| {
449                matches!(
450                    crate::session_state::force_status(s),
451                    crate::session_state::ForceStatus::Live(_)
452                )
453            }),
454    }
455}
456
457/// The capture-time project BINDING for a stream event: a thin wrapper over
458/// the shared chain [`crate::resolution::capture_project_binding`] (subagent
459/// worktree override -> `TRACEVAULT_PROJECT` -> session `active_project` ->
460/// user-level default; no `--project` flag on the hook path), with a binding
461/// whose stored id is not a UUID dropped exactly as
462/// [`crate::resolution::capture_project_id`] drops it. Local only — no
463/// network (the hook fires per event in a short-lived process), which is why
464/// repo config `default_project` (a name) is not a tier and why
465/// `TRACEVAULT_PROJECT` is honoured in its UUID form only.
466/// `commands::project::status` calls the same shared chain, so it reports
467/// exactly what this returns.
468///
469/// Returns the full [`crate::session_state::ProjectBinding`], not just its
470/// id: `forced_until` travels with whichever binding actually wins this
471/// precedence chain, so a caller can ask THAT binding — via
472/// [`attribution_mode`] — whether it is currently forced, rather than
473/// consulting some other, unrelated binding (see `attribution_mode`'s doc
474/// comment for why that distinction matters). Callers that only need the id
475/// use [`capture_project`].
476pub(crate) fn capture_binding(
477    session: &crate::session_state::SessionState,
478    worktree_path: Option<&str>,
479) -> Option<crate::session_state::ProjectBinding> {
480    use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
481    let (binding, _) = capture_project_binding(&CaptureProjectInputs {
482        project_flag: None,
483        env_project: env_project_binding(),
484        session,
485        worktree_path,
486        user_default: crate::user_project_default::load(),
487    })?;
488    // Defensive: a corrupted/hand-edited binding whose id isn't a real UUID
489    // must not be usable for attribution at all (mirrors
490    // `binding_repo_id_is_valid` for the repo side) — checked here, once, so
491    // every caller gets the same guarantee rather than re-deriving it.
492    capture_project_id(&binding)?;
493    Some(binding)
494}
495
496/// The capture-time project ID for a stream event: [`capture_binding`]
497/// projected down to its id. `None` -> fall back to the repo-scoped stream
498/// (server deduces).
499///
500/// `pub(crate)`: also called by `commands::status`, which reuses this
501/// function (plus `resolve_stream_binding`/`attribution_for`) as the
502/// authoritative "will this session record anything" gate, so the status
503/// verdict can never drift from what this hook actually does. `commands::flush`
504/// and `commands::project::status` call it for the same reason.
505pub(crate) fn capture_project(
506    session: &crate::session_state::SessionState,
507    worktree_path: Option<&str>,
508) -> Option<uuid::Uuid> {
509    capture_binding(session, worktree_path)
510        .as_ref()
511        .and_then(crate::resolution::capture_project_id)
512}
513
514/// The one-line warning printed when a repo-less event is dropped as
515/// permanently undeliverable. Pure, so the wording is asserted directly.
516fn undeliverable_warning(pid: uuid::Uuid) -> String {
517    format!(
518        "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
519         repo binding, so there is nothing to attribute these events to and they are being \
520         DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
521         that exists."
522    )
523}
524
525/// True when a stream-send error's rendered message carries a `(4xx ...)`
526/// status marker — i.e. the server deterministically rejected the request in
527/// a way that will never succeed on blind retry (bad binding, missing
528/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
529/// transport/network/timeout failures (which have no `(NNN ` marker at all,
530/// or a 5xx one) — those remain transient and must keep propagating so the
531/// existing buffer/retry logic in `run_stream` still applies to them.
532///
533/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
534/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
535///
536/// COUPLING: the `"(NNN "` markers below must byte-for-byte match what
537/// `ApiClient::authed_send_json`'s `err_prefix` closures render (e.g.
538/// `stream_event`'s `"Stream failed ({status})"`, where `{status}` Displays
539/// as `"404 Not Found"`, yielding `"Stream failed (404 Not Found): ..."` —
540/// hence the `"(404 "` marker below matching on the open-paren + code + the
541/// space before the reason phrase). If that error-formatting ever changes,
542/// update this list (and its tests) to match.
543/// Which deterministic client error this is, so the refusal error can name a
544/// cause that is actually possible instead of assuming one.
545#[derive(Debug, PartialEq, Eq)]
546pub(crate) enum ClientErrorKind {
547    /// 403, which now has TWO plausible causes — see [`send_stream_event`].
548    Forbidden,
549    /// 400/404/409: a binding/scoping problem, and only that.
550    Scoping,
551}
552
553/// The one-line error printed when the server refuses a project-scoped send.
554/// Pure, so the wording is asserted directly rather than by capturing stderr.
555///
556/// `force` is the force situation this send actually declared — the exact
557/// [`AttributionForce`] whose [`AttributionForce::mode`] filled the
558/// `x-tracevault-project-attribution` header, so the message and the wire
559/// can never disagree. It matters because the force gate also refuses with a
560/// 403: "not Operator on the project", or "`explicit` from a `tvk_` key".
561/// Without naming it, an operator who asked for `explicit` got an error about
562/// membership and realm roles and was never told the force itself was what
563/// got refused. Failing closed on trust is right; failing closed silently is
564/// the defect.
565///
566/// The force clause takes the whole `AttributionForce`, not just the mode,
567/// because its remediation has to name the source ACTUALLY in effect. The
568/// two are undone differently and only one of them by a CLI flag: an earlier
569/// wording told everyone to switch again without `--project-attribution
570/// explicit`, which for an env-sourced force clears a persisted
571/// `forced_until` that may not even exist while [`attribution_force`] goes
572/// on reading `TRACEVAULT_PROJECT_ATTRIBUTION` and every subsequent send
573/// keeps declaring `explicit` — advice that silently does nothing, handed
574/// out on the one code path a confused operator reaches (Copilot on PR #54).
575/// [`force_remediation`] derives the fix from the same struct the header
576/// came from, so it cannot name a source that is not set, or miss one that
577/// is.
578///
579/// The extra clause is attached to `Forbidden` ONLY. A `Scoping` 4xx
580/// (400/404/409) means the project id itself does not resolve — the force
581/// gate never ran — so blaming the force there would be a new wrong
582/// explanation of exactly the kind this fixes.
583pub(crate) fn refused_error(
584    pid: uuid::Uuid,
585    kind: &ClientErrorKind,
586    force: AttributionForce,
587) -> String {
588    let base = match kind {
589        // Since Keycloak, a 403 has a SECOND and now more common cause: the
590        // account has no `tracevault` grant in Control Plane, in which case nothing this
591        // hook does will work and `project switch` is confidently wrong advice —
592        // on the code path users hit most. The server's 403 envelope is not
593        // distinguishable from here (see `ClientErrorKind`), so name both.
594        ClientErrorKind::Forbidden => format!(
595            "tracevault: error: the server refused to attribute this event to active project \
596             {pid} (403). Either that project does not apply to this repo (not a member, or \
597             no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
598             binding is the machine-wide default in `user_project.toml`) — or this account has \
599             no `tracevault` grant in Control Plane at all, which an administrator must grant. \
600             The event was NOT re-attributed elsewhere; it has been queued and will be retried \
601             once the binding or the grant is fixed."
602        ),
603        ClientErrorKind::Scoping => format!(
604            "tracevault: error: active project {pid} does not apply to this repo (not a member, \
605             missing permission, or the project no longer exists). The event was NOT \
606             re-attributed elsewhere; it has been queued and will be retried once the binding is \
607             fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
608             machine-wide default in `user_project.toml`) to update it."
609        ),
610    };
611    if force.mode() == crate::api_client::AttributionMode::Explicit
612        && matches!(kind, ClientErrorKind::Forbidden)
613    {
614        return format!(
615            "{base} This send declared `explicit` attribution, so the refusal may be of the \
616             FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
617             identity (a `tvk_` API key can never force). If membership attribution is what \
618             you want, {}",
619            force_remediation(force)
620        );
621    }
622    base
623}
624
625/// How to STOP forcing, given which source(s) are doing it.
626///
627/// A sentence fragment completing "If membership attribution is what you
628/// want, ...", so the caller keeps the framing and this keeps the facts.
629///
630/// Only ever reached with at least one source set (see [`refused_error`]'s
631/// guard, which is `force.mode() == Explicit` — i.e. `env || binding`), so
632/// the all-false arm is unreachable in practice. It still has to say
633/// something rather than panic: this runs while printing an error on the
634/// capture path, and a hook that panics mid-diagnostic is strictly worse
635/// than one that prints a slightly vague line. The fallback names both ways,
636/// which is wrong about emphasis but never wrong about the fix.
637///
638/// When BOTH are set the message says so explicitly: removing one alone
639/// leaves the other still forcing, which would look exactly like the fix not
640/// working.
641fn force_remediation(force: AttributionForce) -> String {
642    let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
643                   process-wide and never expires, so no switch clears it)";
644    let binding_fix = "run `tracevault project switch <name>` WITHOUT \
645                       `--project-attribution explicit` (add `--user` if the forced binding \
646                       is the machine-wide default in `user_project.toml`)";
647    match (force.env, force.binding) {
648        (true, false) => format!("{env_fix}."),
649        (false, true) => format!("{binding_fix}."),
650        // Both: neither fix is sufficient alone.
651        (true, true) => {
652            format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
653        }
654        (false, false) => format!("{env_fix}, or {binding_fix}."),
655    }
656}
657
658pub(crate) fn deterministic_client_error_kind(
659    e: &dyn std::error::Error,
660) -> Option<ClientErrorKind> {
661    let s = e.to_string();
662    // 401 is deliberately excluded: it's an authentication failure (bad/expired
663    // token), not a project-scoping problem, and the buffer/retry path already
664    // handles it correctly without a misleading project-scoping message. 403
665    // stays in: it can mean the token is valid but lacks `Operator` on the bound
666    // project (or the account has no `tracevault` grant at all), and the refusal
667    // line can name both possible causes.
668    if s.contains("(403 ") {
669        return Some(ClientErrorKind::Forbidden);
670    }
671    if ["(400 ", "(404 ", "(409 "]
672        .iter()
673        .any(|marker| s.contains(marker))
674    {
675        return Some(ClientErrorKind::Scoping);
676    }
677    None
678}
679
680/// Send a single stream event, routing to the project-scoped endpoint when a
681/// local project binding resolved (`capture_pid = Some(_)`), else the
682/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
683/// the pending-flush loop and the live send share one branch.
684///
685/// Routing is decided by the [`Attribution`] resolved before the send:
686/// `Repo` with no project goes to the repo-scoped endpoint (the server
687/// deduces the project); `Repo` with a project goes to the project-scoped
688/// endpoint carrying `repo_id`; `ProjectOnly` goes to the project-scoped
689/// endpoint with no `repo_id` at all. Having no fallback endpoint, it decides
690/// instead between buffering and dropping: a `Scoping` 4xx (the project does
691/// not resolve) can never succeed on retry — the offline queue is keyed by
692/// that same project id — so it warns and returns `Ok(None)`, while a 403 or
693/// any transient error propagates to be buffered. See the arm itself for why
694/// the two differ.
695///
696/// `Ok(None)` therefore means "deliberately dropped, do not queue": callers
697/// must treat it like a success for offset/queue purposes, not like an error.
698///
699/// When the attribution carries BOTH a repo and a project, the project was
700/// explicitly declared (by binding or by `project switch`), so the server's
701/// refusal of it is an error, never re-derived elsewhere: a deterministic
702/// client error (the bound project doesn't apply to this repo: not a member,
703/// or the caller lacks `Operator` on it) prints the refusal line to stderr
704/// and returns `Err(e)` with the original error, unchanged, so the caller's
705/// existing buffer/retry logic queues it in the REPO's pending file
706/// (`pending-<repo_id>.jsonl`, see [`Attribution::pending_file_name`]); the
707/// next drain (the hook's or `tracevault flush`'s) re-applies whatever capture
708/// project is in force at that time (mirrors the server-side rule from VIS-305: a declared project the server
709/// refuses is not silently re-attributed). A transient error (5xx,
710/// network/transport, timeout) also propagates as `Err`, and is handled
711/// identically by that same buffer/retry path.
712///
713/// `warned` is shared across every call made for a single hook
714/// invocation (both the pending-flush loop and the live send). The
715/// pending-flush loop only `break`s on `Err`, so without this flag a stale,
716/// refused binding would print the refusal line once per buffered event
717/// before the loop breaks. Gating on `*warned` caps stderr at one line per
718/// invocation. The repo-less drop warning shares the flag for the same
719/// reason: draining a queue of undeliverable events would otherwise print one
720/// line per buffered event.
721///
722/// `force` is the invocation's attribution force — [`attribution_force`]
723/// applied to the capture binding. Its [`AttributionForce::mode`] goes on
724/// every project-scoped send as the `x-tracevault-project-attribution`
725/// header, and the same value is handed to [`refused_error`], which needs
726/// the SOURCES and not only the verdict to tell the operator how to stop
727/// forcing. Taken as a parameter rather than derived here because the
728/// binding is invariant across a whole hook invocation while this function
729/// runs once per buffered event, and the evaluation costs an env read plus
730/// an RFC3339 parse. `commands::flush` resolves it once per queue for the
731/// same reason.
732async fn send_stream_event(
733    client: &crate::api_client::ApiClient,
734    attribution: &Attribution,
735    force: AttributionForce,
736    req: &StreamEventRequest,
737    warned: &mut bool,
738) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
739{
740    let (repo_id, capture_pid) = match attribution {
741        // Repo-less: there is no repo-scoped endpoint to fall back TO, so the
742        // only choice is buffer-for-retry vs. drop, and that turns on whether
743        // a retry could EVER succeed.
744        //
745        // `Scoping` (400/404/409) means the project itself does not resolve.
746        // The offline queue is keyed by that same project id
747        // (`pending-project-<uuid>.jsonl`), so re-binding to a project that
748        // does exist writes to a DIFFERENT file and these events are never
749        // retried under the corrected binding — they would accumulate forever,
750        // one per tool call, each hook fire re-reading and re-appending the
751        // whole queue. Warn and drop instead: undeliverable is undeliverable,
752        // and a growing queue only hides it.
753        //
754        // `Forbidden` (403) is deliberately NOT dropped. It can mean the
755        // account has no `tracevault` grant at all, which an administrator can
756        // grant — after which the buffered events do deliver. Same for any
757        // transient error. Both propagate so the caller queues them.
758        Attribution::ProjectOnly { project_id } => {
759            let attempt = client
760                .stream_event_for_project(*project_id, None, force.mode(), req)
761                .await;
762            return match attempt {
763                Ok(r) => Ok(Some(r)),
764                Err(e) => match deterministic_client_error_kind(e.as_ref()) {
765                    Some(ClientErrorKind::Scoping) => {
766                        if !*warned {
767                            eprintln!("{}", undeliverable_warning(*project_id));
768                            *warned = true;
769                        }
770                        Ok(None)
771                    }
772                    _ => Err(e),
773                },
774            };
775        }
776        Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
777    };
778    match capture_pid {
779        None => client.stream_event(repo_id, req).await.map(Some),
780        Some(pid) => {
781            let attempt = client
782                .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
783                .await;
784            let kind = match &attempt {
785                Ok(_) => None,
786                Err(e) => deterministic_client_error_kind(e.as_ref()),
787            };
788            match (attempt, kind) {
789                (Ok(r), _) => Ok(Some(r)),
790                (Err(e), Some(kind)) => {
791                    if !*warned {
792                        // Since Keycloak, a 403 has a SECOND and now more common
793                        // cause: the account has no `tracevault` grant at all,
794                        // in which case nothing this hook does will work and
795                        // `project switch` is confidently wrong advice — on the
796                        // code path users hit most. The server's 403 envelope
797                        // isn't distinguishable from here (see
798                        // `ClientErrorKind`), so the wording names both.
799                        eprintln!("{}", refused_error(pid, &kind, force));
800                        *warned = true;
801                    }
802                    // The caller declared this project; the server refused it.
803                    // Do NOT re-attribute to another project by falling back to
804                    // the repo-scoped endpoint — propagate so the caller queues
805                    // this event for retry under the same (or a corrected)
806                    // binding.
807                    Err(e)
808                }
809                // transient — propagate for buffer/retry
810                (Err(e), None) => Err(e),
811            }
812        }
813    }
814}
815
816/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
817/// byte-offset semantics of `read_new_transcript_lines`: returns
818/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
819/// `transcript_offset` (base for the server's per-line `chunk_index`) and
820/// `next_offset` is persisted to `.stream_offset`.
821pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
822    (start_offset, start_offset + records_len)
823}
824
825/// Split a hook event whose transcript batch does not fit in one request
826/// ([`MAX_REQUEST_BYTES`]) into several requests, so no line is dropped. A
827/// request that fits is returned unchanged as the only part.
828///
829/// Otherwise the event itself (its type, tool payload and `event_uuid`) goes
830/// in the LAST part, with as many trailing lines as fit beside it; the lines
831/// before those go, in order, in `Transcript` parts, which the server handles
832/// as lines only. A single line larger than the cap is sent alone; it cannot
833/// be split.
834///
835/// Every line keeps the chunk_index it would have had unsplit: a part's
836/// `transcript_offset` is the batch's plus the index of the part's first line
837/// in the batch. Where the batch is cut therefore never matters — not between
838/// two hooks of one session that read from the same offset concurrently and
839/// split different lengths, and not between a delivery and its retry.
840pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
841    if req.serialized_len() <= MAX_REQUEST_BYTES {
842        return vec![req];
843    }
844    let lines = req.transcript_lines.take().unwrap_or_default();
845    let batch_offset = req.transcript_offset.unwrap_or(0);
846    // The event part without lines: shed its tool payload if even that does
847    // not fit, as before.
848    req.truncate_large_fields();
849
850    // Each line costs its JSON plus a separating comma in the array.
851    let sizes: Vec<usize> = lines
852        .iter()
853        .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
854        .collect();
855    let envelope = |r: &StreamEventRequest| {
856        let mut r = r.clone();
857        r.transcript_lines = Some(vec![]);
858        r.serialized_len()
859    };
860
861    // Trailing lines that fit beside the event.
862    let mut tail_start = lines.len();
863    let mut used = envelope(&req);
864    while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
865        tail_start -= 1;
866        used += sizes[tail_start];
867    }
868
869    let transcript_template = StreamEventRequest {
870        event_type: StreamEventType::Transcript,
871        tool_name: None,
872        tool_use_id: None,
873        tool_input: None,
874        tool_response: None,
875        tool_is_error: None,
876        event_index: None,
877        event_uuid: None,
878        transcript_lines: None,
879        final_stats: None,
880        ..req.clone()
881    };
882    let transcript_envelope = envelope(&transcript_template);
883
884    // Group the leading lines into `Transcript` parts, then the tail.
885    let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
886    let mut start = 0;
887    while start < tail_start {
888        let mut end = start + 1;
889        let mut used = transcript_envelope + sizes[start];
890        while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
891            used += sizes[end];
892            end += 1;
893        }
894        groups.push(start..end);
895        start = end;
896    }
897    groups.push(tail_start..lines.len());
898
899    let last = groups.len() - 1;
900    let mut lines = lines.into_iter();
901    groups
902        .into_iter()
903        .enumerate()
904        .map(|(n, range)| {
905            let mut part = if n == last {
906                req.clone()
907            } else {
908                transcript_template.clone()
909            };
910            let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
911            part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
912            part.transcript_offset = Some(batch_offset + range.start as i64);
913            part
914        })
915        .collect()
916}
917
918/// Choose the transcript source for a stream event. Inline records (from a
919/// plugin-based agent like OpenCode) win over the file-read result whenever the
920/// hook event carries them — INCLUDING an empty vec, so an event with no new
921/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
922/// instead of resetting it to the file-path's 0.
923pub fn resolve_transcript_source(
924    inline_records: Option<Vec<serde_json::Value>>,
925    prior_offset: i64,
926    file_result: (Vec<serde_json::Value>, i64, i64),
927) -> (Vec<serde_json::Value>, i64, i64) {
928    match inline_records {
929        Some(records) => {
930            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
931            (records, send, next)
932        }
933        None => file_result,
934    }
935}
936
937/// Derive the event-level tool-error flag from inline transcript records.
938/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
939/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
940/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
941/// record found, or `None` when there is none (non-tool events).
942pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
943    lines.iter().find_map(|line| {
944        let msg = line.get("message")?;
945        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
946            Some(
947                msg.get("isError")
948                    .and_then(|v| v.as_bool())
949                    .unwrap_or(false),
950            )
951        } else {
952            None
953        }
954    })
955}
956
957/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
958/// Factored out so the mapping is testable without the network/FS-bound
959/// `run_stream`.
960pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
961    req.tool = Some(agent.tool_name().to_string());
962    req.protocol_version = agent.protocol_version() as u32;
963}
964
965/// How long a hook may keep starting requests. `init` installs the hooks
966/// with a 10 s timeout and the agent kills a hook that overruns it, so a
967/// split batch (or a long pending queue) still unsent after this is queued
968/// instead: a killed hook would lose whatever it held only in memory. Half
969/// the timeout leaves room for the request already in flight.
970const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
971
972/// Send a hook event's parts in order. From the first failure on (or from the
973/// start when `send_failed`, i.e. older queued events are still waiting), or
974/// once `deadline` has passed, a part is appended to the pending queue
975/// instead, behind whatever is already there. Returns whether every part was
976/// accepted.
977#[allow(clippy::too_many_arguments)]
978async fn deliver_parts(
979    client: &crate::api_client::ApiClient,
980    attribution: &Attribution,
981    force: AttributionForce,
982    parts: Vec<StreamEventRequest>,
983    pending_path: &Path,
984    mut send_failed: bool,
985    deadline: std::time::Instant,
986    warned: &mut bool,
987) -> Result<bool, Box<dyn std::error::Error>> {
988    let mut all_accepted = true;
989    for part in parts {
990        send_failed = send_failed || std::time::Instant::now() >= deadline;
991        if !send_failed {
992            match send_stream_event(client, attribution, force, &part, warned).await {
993                Ok(_) => continue,
994                Err(_) => send_failed = true,
995            }
996        }
997        all_accepted = false;
998        append_pending(pending_path, &serde_json::to_string(&part)?)?;
999    }
1000    Ok(all_accepted)
1001}
1002
1003pub async fn run_stream(
1004    event_type: &str,
1005    agent: crate::agent::Agent,
1006) -> Result<(), Box<dyn std::error::Error>> {
1007    // 1. Read HookEvent from stdin
1008    let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1009    let mut input = String::new();
1010    io::stdin().read_to_string(&mut input)?;
1011    let mut hook_event = parse_hook_event(&input)?;
1012
1013    // Resolve project_root and session_dir via the shared git-aware resolver.
1014    //
1015    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
1016    // the primary worktree root, so it works correctly from a primary checkout,
1017    // a nested worktree, AND a sibling linked worktree (where the primary
1018    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
1019    // would fall back to hook_cwd itself, fail to load config, and silently
1020    // drop the event).
1021    //
1022    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
1023    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
1024    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
1025    // just below runs BEFORE the config/credentials check and can itself
1026    // `?`-exit early — that remains graceful because `main.rs` catches all
1027    // `Err` from `run_stream` and exits 0 without blocking the tool.
1028    let hook_cwd = Path::new(&hook_event.cwd);
1029    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1030    if resolved.source == crate::paths::ProjectRootSource::Fallback {
1031        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
1032        // we are about to create a fresh `.tracevault/` at the hook's working
1033        // directory — which is how stray per-subdirectory `.tracevault/` dirs
1034        // appear. Surface it (best-effort; stderr never blocks the hook).
1035        eprintln!(
1036            "tracevault: warning: could not resolve a git project root from {}; \
1037             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1038             that it runs inside the repository to keep sessions under the repo root.",
1039            hook_cwd.display()
1040        );
1041    }
1042    let project_root = resolved.root;
1043
1044    // 2. Create session dir
1045    fs::create_dir_all(&session_dir)?;
1046
1047    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
1048    // inside whatever `.tracevault/` we just created — including a per-subproject
1049    // one. `tracevault init` writes this for the root dir, but runtime-created
1050    // dirs would otherwise have no .gitignore and leak sessions into commits.
1051    // Best-effort: never fail the hook on this.
1052    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
1053
1054    // Write origin marker so verify-start can disambiguate sessions by worktree.
1055    // Best-effort: never fail the hook on marker errors. Uses the shared
1056    // canonicalizing helper so the value matches what verify-start compares
1057    // against on the read side.
1058    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1059    let _ = fs::write(session_dir.join("origin"), &worktree_top);
1060
1061    // Record where the transcript lives: `tracevault check` counts the
1062    // session's tool calls from it, and finds it only through metadata.json.
1063    // Best-effort, like the origin marker.
1064    let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1065    // Inline records (OpenCode) reach no transcript file `check` could read,
1066    // so keep their tool calls locally for it. Done here, before the
1067    // `.stream_offset` read below can fail the hook, so a corrupt offset file
1068    // never costs `check` a tool call.
1069    if let Some(records) = &hook_event.transcript_records {
1070        let _ = record_inline_tool_calls(&session_dir, records);
1071    }
1072
1073    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
1074    //    it both orders events and is a stable idempotency key — no shared
1075    //    `.event_counter` file (which raced between concurrent parallel-tool
1076    //    hooks and could collide/drop events).
1077    let event_uuid = uuid::Uuid::now_v7();
1078
1079    // 4. Read new transcript lines
1080    let transcript_path = Path::new(&hook_event.transcript_path);
1081    let offset_path = session_dir.join(".stream_offset");
1082    // transcript_offset carries the batch START byte offset so the server
1083    // derives a stable per-line chunk_index across overlapping/retried reads;
1084    // .stream_offset persists the END (next read position).
1085    let (transcript_lines, start_offset, new_offset) =
1086        read_new_transcript_lines(transcript_path, &offset_path)?;
1087
1088    // Fileless inline path (OpenCode): a plugin-based agent with no single
1089    // tailable transcript supplies records directly on the hook event. When
1090    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
1091    // sends `transcript_records: []`) — they take priority over the file-read
1092    // result. `.stream_offset` is reused as a per-session RECORD counter so
1093    // the server's chunk_index stays stable/monotonic across retries, exactly
1094    // as with the byte-offset path. Treating an empty vec as "no new
1095    // records" rather than "fall back to the file" matters: OpenCode's
1096    // `transcript_path` is always "", so the file-read result is always
1097    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
1098    // offset back to 0 and collide with earlier turns' chunk_index on the
1099    // server.
1100    // Only inline (plugin-based) events override the file-read result, and only
1101    // they need `.stream_offset` re-read as a record counter. File-based agents
1102    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
1103    // the byte-offset values from `read_new_transcript_lines` above.
1104    let is_inline = hook_event.transcript_records.is_some();
1105    let (transcript_lines, start_offset, new_offset) = if is_inline {
1106        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
1107        // `.stream_offset` must NOT silently reset to 0 — that would restart the
1108        // record counter and collide with earlier turns' chunk_index on the
1109        // server (the offset-clobber failure mode). Propagate the error instead;
1110        // `main` treats a hook error as non-fatal (exits 0 without blocking the
1111        // tool call). Negatives are clamped to 0 defensively.
1112        let prior_offset: i64 = if offset_path.exists() {
1113            let content = fs::read_to_string(&offset_path)?;
1114            content
1115                .trim()
1116                .parse::<i64>()
1117                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1118                .max(0)
1119        } else {
1120            0
1121        };
1122        // `take()` moves the records out (nothing below reads
1123        // `transcript_records` again) — avoids deep-cloning a potentially
1124        // large payload (full bash stdout / file contents) on the hook path.
1125        resolve_transcript_source(
1126            hook_event.transcript_records.take(),
1127            prior_offset,
1128            (transcript_lines, start_offset, new_offset),
1129        )
1130    } else {
1131        (transcript_lines, start_offset, new_offset)
1132    };
1133    // 5. Build StreamEventRequest
1134    let stream_event_type = match event_type {
1135        "notification" => StreamEventType::SessionStart,
1136        "stop" => StreamEventType::SessionEnd,
1137        _ => StreamEventType::ToolUse,
1138    };
1139
1140    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
1141    // events have no tool_use_id, so fall back to a forwarded `toolResult`
1142    // record's `isError` — otherwise a failed OpenCode tool would render as
1143    // successful (the event-level flag file-based agents populate would be None).
1144    let tool_is_error = hook_event
1145        .tool_use_id
1146        .as_deref()
1147        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1148        .or_else(|| inline_tool_is_error(&transcript_lines));
1149
1150    // Load config once, up front, so it can back both the user-level context
1151    // layer resolution below and the repo_id lookup further down — avoids a
1152    // redundant second read of the same file. `try_load` keeps the
1153    // missing/malformed distinction so the required-config error further down
1154    // can report which one it is.
1155    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
1156    // user context" — `resolve_user_context` below falls back to the user-level
1157    // config in that case. A malformed repo config is surfaced as an error
1158    // later (the required-config check), not silently dropped here.
1159    let config = crate::config::TracevaultConfig::try_load(&project_root);
1160    // Repo config's user_context wins when the repo configured it; otherwise
1161    // fall back to the user-level ~/.config/tracevault/config.toml. This is
1162    // what lets a detached session (no checkout) still carry user context.
1163    let repo_uc = config
1164        .as_ref()
1165        .ok()
1166        .and_then(|opt| opt.as_ref())
1167        .and_then(|c| c.user_context.clone());
1168    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1169
1170    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
1171    // global and per-worktree) and extract fields before building the
1172    // request.  Using `effective` means parallel sessions in different linked
1173    // worktrees each stamp their own per-worktree context without
1174    // interfering with each other.
1175    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1176    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1177
1178    let mut req = StreamEventRequest {
1179        protocol_version: 1,
1180        tool: Some("claude-code".to_string()),
1181        event_type: stream_event_type,
1182        session_id: hook_event.session_id.clone(),
1183        timestamp: chrono::Utc::now(),
1184        hook_event_name: Some(hook_event.hook_event_name.clone()),
1185        tool_name: hook_event.tool_name.clone(),
1186        tool_use_id: hook_event.tool_use_id.clone(),
1187        tool_input: hook_event.tool_input.clone(),
1188        tool_response: hook_event.tool_response.clone(),
1189        tool_is_error,
1190        event_index: None,
1191        event_uuid: Some(event_uuid),
1192        transcript_lines: if transcript_lines.is_empty() {
1193            None
1194        } else {
1195            Some(transcript_lines)
1196        },
1197        transcript_offset: Some(start_offset),
1198        model: None,
1199        cwd: Some(hook_event.cwd.clone()),
1200        final_stats: None,
1201        flow_id: ctx_flow_id,
1202        labels: ctx_labels,
1203        params: ctx_params,
1204        billing_mode: Some(crate::billing::detect_current(
1205            agent,
1206            hook_cwd,
1207            &hook_event.transcript_path,
1208        )),
1209    };
1210
1211    stamp_agent(&mut req, agent);
1212
1213    // 6. Resolve credentials
1214    let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
1215
1216    // 7. Config (loaded above, alongside the user-level context layer
1217    // resolution) no longer directly gates repo_id — a missing config is not
1218    // fatal on its own, since the repo may instead resolve via the
1219    // workspace-mode precedence chain (session binding / subagent worktree
1220    // override) below. A malformed config is still surfaced here — that's
1221    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
1222    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
1223    // below).
1224    if let Err(e) = &config {
1225        return Err(format!("malformed .tracevault/config.toml: {e}").into());
1226    }
1227
1228    // Resolve the effective repo binding (workspace/detached mode). Bound
1229    // mode (a pinned config.toml) still works — it's the lowest-precedence
1230    // tier, wired below via `binding_from_config`, fed from the `config`
1231    // already loaded above (no second read of config.toml on this hot path).
1232    let session = crate::session_state::load(&hook_event.session_id);
1233    let bound = config
1234        .as_ref()
1235        .ok()
1236        .and_then(|opt| opt.as_ref())
1237        .and_then(crate::resolution::binding_from_config);
1238    let user_default = crate::user_default::load();
1239    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
1240    // Graceful no-op, exactly like the hook's normal success path. Do NOT
1241    // error: a failing hook would block the tool.
1242    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
1243        let response = HookResponse::allow();
1244        println!("{}", serde_json::to_string(&response)?);
1245        Ok(())
1246    };
1247    // Explicit local project binding (if any) overrides server-side repo
1248    // deduction. Computed BEFORE the attribution gate below, reusing the
1249    // already-loaded session + worktree used just above for the repo-binding
1250    // resolution: a repo-less session is attributable by project alone, so the
1251    // project must be known before deciding whether this event can be sent.
1252    // The full binding (not just its id) is resolved: `attribution_mode`
1253    // reads its `forced_until`, and this is the binding that actually decided
1254    // the target project, so it's the only one whose force is allowed to
1255    // apply (see `attribution_mode`'s doc comment).
1256    let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1257    let capture_pid = capture_binding
1258        .as_ref()
1259        .and_then(crate::resolution::capture_project_id);
1260    // Resolved once per invocation, not per event — the binding is invariant
1261    // across the pending-flush loop and the live send below, while the
1262    // evaluation costs an env read and an RFC3339 parse. `commands::flush`
1263    // resolves it once per queue for the same reason. The whole
1264    // `AttributionForce` travels, not just its mode: a refusal has to name
1265    // the force source it is telling the operator to remove.
1266    let force = attribution_force(capture_binding.as_ref());
1267
1268    // Ship if EITHER a repo or a project resolved; no-op only when neither
1269    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
1270    // session-state file whose repo_id could carry path separators into the
1271    // pending filename — such a binding degrades to project-only inside
1272    // `attribution_for` rather than dropping the event.)
1273    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1274        no_op_allow()?;
1275        return Ok(());
1276    };
1277
1278    // 8. Create ApiClient
1279    let server_url = server_url.ok_or("server_url not configured")?;
1280    let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
1281
1282    // 9. Try drain pending queue and send
1283    let pending_path = pending_path_for(&session_dir, &attribution);
1284    let pending_events = drain_pending(&pending_path)?;
1285
1286    let mut send_failed = false;
1287    // Spans the whole invocation (pending-flush loop + live send below) so a
1288    // refused project binding prints its error at most once per invocation,
1289    // not once per buffered event.
1290    let mut warned = false;
1291
1292    // Send pending events first. Past the delivery budget, put the rest back
1293    // unsent (the queue file is already gone), so a hook killed at its timeout
1294    // loses none of them.
1295    for (i, pending_json) in pending_events.iter().enumerate() {
1296        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1297            if std::time::Instant::now() >= deadline
1298                || send_stream_event(&client, &attribution, force, &pending_req, &mut warned)
1299                    .await
1300                    .is_err()
1301            {
1302                // Re-queue only the failed event and the ones after it that
1303                // were never attempted, in order. Events before `i` already
1304                // got a server response and must NOT be re-queued here — a
1305                // prior iteration already appended them if IT failed, and if
1306                // it succeeded, re-adding them would deliver them twice on
1307                // the next drain.
1308                for evt in &pending_events[i..] {
1309                    append_pending(&pending_path, evt)?;
1310                }
1311                send_failed = true;
1312                break;
1313            }
1314        }
1315    }
1316
1317    // Send the current event — several requests when its transcript batch
1318    // exceeds the request cap (see `split_into_parts`), never dropping lines.
1319    let all_accepted = deliver_parts(
1320        &client,
1321        &attribution,
1322        force,
1323        split_into_parts(req),
1324        &pending_path,
1325        send_failed,
1326        deadline,
1327        &mut warned,
1328    )
1329    .await?;
1330    // 10. Advance .stream_offset once every part is accepted. The inline
1331    // (OpenCode) path CONSUMES its records from the hook event — they are not
1332    // re-readable like a transcript file — so its record counter must advance
1333    // whenever the event is accepted for delivery, INCLUDING when parts were
1334    // queued after a failure. Otherwise the next inline event reuses these
1335    // chunk_indexes and the server drops the overlap via ON CONFLICT. The queued
1336    // parts already carry their `transcript_offset`, so the records keep their
1337    // indices on drain. (File-based agents must NOT advance on failure: their
1338    // next read re-covers these lines from the same start offset, so every line
1339    // gets the same chunk_index again and the server dedupes it — whatever the
1340    // queue meanwhile delivered or lost.)
1341    if all_accepted || is_inline {
1342        fs::write(&offset_path, new_offset.to_string())?;
1343    }
1344
1345    // 12. Always print HookResponse::allow() to stdout
1346    let response = HookResponse::allow();
1347    println!("{}", serde_json::to_string(&response)?);
1348
1349    Ok(())
1350}
1351
1352#[cfg(test)]
1353mod tests {
1354    use super::*;
1355    use crate::api_client::AttributionMode;
1356    use crate::config::UserContext;
1357    use crate::context::{Context, EffectiveContext};
1358    use std::collections::BTreeMap;
1359
1360    // ── user layer resolution: disabled config → no user layer ────────────────
1361
1362    #[test]
1363    fn disabled_user_context_resolves_to_none() {
1364        // Default/disabled `user_context` (the `Toggle(false)` variant) must
1365        // resolve to `None`, matching the pre-existing hook behavior of
1366        // stamping without a user layer when it isn't configured.
1367        assert!(UserContext::Toggle(false).resolve().is_none());
1368    }
1369
1370    #[test]
1371    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1372        // With no user layer and no global/worktree context files present,
1373        // `Context::effective` must yield a default (empty) `EffectiveContext`
1374        // — i.e. passing `None` for `user_layer` is behavior-preserving.
1375        let dir = tempfile::tempdir().unwrap();
1376        let effective = Context::effective(dir.path(), None);
1377        assert_eq!(effective, EffectiveContext::default());
1378    }
1379
1380    // ── apply_context: all three fields populated ─────────────────────────────
1381
1382    #[test]
1383    fn apply_context_stamps_all_fields() {
1384        let dir = tempfile::tempdir().unwrap();
1385        let mut params = BTreeMap::new();
1386        params.insert("env".to_string(), "prod".to_string());
1387        params.insert("region".to_string(), "eu-west-1".to_string());
1388
1389        let ctx = EffectiveContext {
1390            flow_id: Some("flow-xyz".to_string()),
1391            labels: vec!["backend".to_string(), "urgent".to_string()],
1392            params,
1393        };
1394
1395        let (flow_id, labels, params_out) = apply_context(ctx);
1396
1397        assert_eq!(flow_id, Some("flow-xyz".to_string()));
1398        assert_eq!(
1399            labels,
1400            Some(vec!["backend".to_string(), "urgent".to_string()])
1401        );
1402        let p = params_out.expect("params should be Some");
1403        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1404        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1405
1406        // Verify the stored context round-trips through save_to → load_from →
1407        // merge_layers → apply_context (stored params are now `Option<String>`).
1408        let written = Context {
1409            flow_id: Some("flow-xyz".to_string()),
1410            labels: vec!["backend".to_string(), "urgent".to_string()],
1411            params: {
1412                let mut m = BTreeMap::new();
1413                m.insert("env".to_string(), Some("prod".to_string()));
1414                m.insert("region".to_string(), Some("eu-west-1".to_string()));
1415                m
1416            },
1417        };
1418        let ctx_path = dir.path().join(".tracevault").join("context.json");
1419        written.save_to(&ctx_path).unwrap();
1420        let loaded = Context::load_from(&ctx_path);
1421        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1422        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1423        assert!(labels2.is_some());
1424        assert!(params2.is_some());
1425    }
1426
1427    // ── apply_context: missing context file → all None ────────────────────────
1428
1429    #[test]
1430    fn apply_context_missing_file_all_none() {
1431        let dir = tempfile::tempdir().unwrap();
1432        let missing_path = dir.path().join(".tracevault").join("context.json");
1433        let ctx = Context::load_from(&missing_path); // no context.json → default
1434        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1435        assert!(flow_id.is_none(), "flow_id should be None");
1436        assert!(labels.is_none(), "labels should be None");
1437        assert!(params.is_none(), "params should be None");
1438    }
1439
1440    // ── apply_context: empty labels vec / empty params map → None ─────────────
1441
1442    #[test]
1443    fn apply_context_empty_collections_are_none() {
1444        let ctx = EffectiveContext {
1445            flow_id: None,
1446            labels: vec![],
1447            params: BTreeMap::new(),
1448        };
1449        let (flow_id, labels, params) = apply_context(ctx);
1450        assert!(flow_id.is_none());
1451        assert!(
1452            labels.is_none(),
1453            "empty labels should be None, not Some([])"
1454        );
1455        assert!(
1456            params.is_none(),
1457            "empty params should be None, not Some({{}})"
1458        );
1459    }
1460
1461    // ── apply_context: flow_id only, collections empty ────────────────────────
1462
1463    #[test]
1464    fn apply_context_flow_id_only() {
1465        let ctx = EffectiveContext {
1466            flow_id: Some("my-flow".to_string()),
1467            labels: vec![],
1468            params: BTreeMap::new(),
1469        };
1470        let (flow_id, labels, params) = apply_context(ctx);
1471        assert_eq!(flow_id, Some("my-flow".to_string()));
1472        assert!(labels.is_none());
1473        assert!(params.is_none());
1474    }
1475
1476    // ── resolve_session_paths tests ───────────────────────────────────────────
1477    //
1478    // These tests verify that `resolve_session_paths` routes through the
1479    // git-aware resolver so that sibling linked worktrees capture events under
1480    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
1481
1482    use crate::test_helpers::{add_worktree, init_git_repo};
1483
1484    /// Primary checkout: project_root resolves to the repo root; session_dir is
1485    /// under `<repo>/.tracevault/sessions/<id>/`.
1486    #[test]
1487    fn resolve_session_paths_primary_checkout() {
1488        let tmp = tempfile::tempdir().unwrap();
1489        let repo = tmp.path().join("repo");
1490        std::fs::create_dir_all(&repo).unwrap();
1491        init_git_repo(&repo);
1492        // Create a .tracevault/ in the primary root to match a real init.
1493        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1494
1495        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1496        let project_root = resolved.root;
1497
1498        assert_eq!(
1499            project_root.canonicalize().unwrap(),
1500            repo.canonicalize().unwrap(),
1501            "primary checkout: project_root must be repo root"
1502        );
1503        assert_eq!(
1504            session_dir.canonicalize().unwrap_or(session_dir.clone()),
1505            repo.join(".tracevault")
1506                .join("sessions")
1507                .join("sess-primary-123"),
1508            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1509        );
1510        // session_dir must be INSIDE the primary repo, not elsewhere.
1511        assert!(
1512            session_dir.starts_with(&repo),
1513            "session_dir must be under the primary repo root"
1514        );
1515    }
1516
1517    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1518    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1519    /// git-aware resolver must return the PRIMARY root.
1520    #[test]
1521    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1522        let tmp = tempfile::tempdir().unwrap();
1523        let repo = tmp.path().join("repo");
1524        // Sibling worktree lives outside the primary repo directory.
1525        let wt = tmp.path().join("sibling-wt");
1526
1527        std::fs::create_dir_all(&repo).unwrap();
1528        init_git_repo(&repo);
1529        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1530        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1531        add_worktree(&repo, &wt);
1532
1533        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1534        let project_root = resolved.root;
1535
1536        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1537        assert_eq!(
1538            project_root.canonicalize().unwrap(),
1539            repo.canonicalize().unwrap(),
1540            "sibling worktree: project_root must be primary repo root (not worktree dir)"
1541        );
1542        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1543        assert!(
1544            session_dir.starts_with(&repo),
1545            "sibling worktree: session_dir must be under the PRIMARY repo root"
1546        );
1547        assert!(
1548            !session_dir.starts_with(&wt),
1549            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1550        );
1551        assert!(
1552            session_dir.ends_with(
1553                std::path::Path::new(".tracevault")
1554                    .join("sessions")
1555                    .join("sess-sibling-456")
1556            ),
1557            "session_dir must end with .tracevault/sessions/<session_id>"
1558        );
1559    }
1560
1561    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1562    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1563    #[test]
1564    fn resolve_session_paths_non_git_fallback() {
1565        let tmp = tempfile::tempdir().unwrap();
1566        // No git repo, no .tracevault/ anywhere.
1567        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1568        let project_root = resolved.root;
1569
1570        assert_eq!(
1571            project_root,
1572            tmp.path(),
1573            "non-git: project_root must fall back to hook_cwd"
1574        );
1575        assert_eq!(
1576            session_dir,
1577            tmp.path()
1578                .join(".tracevault")
1579                .join("sessions")
1580                .join("sess-fallback-789"),
1581            "non-git: session_dir must be relative to the fallback root"
1582        );
1583    }
1584
1585    /// The origin marker written by run_stream contains the worktree toplevel.
1586    /// This test exercises the same `paths::worktree_toplevel` helper the hook
1587    /// uses (can't call run_stream end-to-end without a real server) so the
1588    /// marker content is computed and canonicalized exactly as in production.
1589    #[test]
1590    fn origin_marker_written_in_session_dir() {
1591        let tmp = tempfile::tempdir().unwrap();
1592        let repo = tmp.path().join("repo");
1593        std::fs::create_dir_all(&repo).unwrap();
1594        init_git_repo(&repo);
1595
1596        let session_dir = repo
1597            .join(".tracevault")
1598            .join("sessions")
1599            .join("test-sess-001");
1600        std::fs::create_dir_all(&session_dir).unwrap();
1601
1602        let hook_cwd = &repo;
1603        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1604        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1605
1606        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1607        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1608        assert_eq!(
1609            origin_content.trim(),
1610            expected.as_str(),
1611            "origin marker must contain the canonicalized worktree toplevel"
1612        );
1613    }
1614
1615    fn metadata(session_dir: &Path) -> serde_json::Value {
1616        serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
1617            .unwrap()
1618    }
1619
1620    #[test]
1621    fn record_transcript_path_writes_metadata_for_check() {
1622        let tmp = tempfile::tempdir().unwrap();
1623        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1624        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1625    }
1626
1627    #[test]
1628    fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
1629        let tmp = tempfile::tempdir().unwrap();
1630        std::fs::write(
1631            tmp.path().join("metadata.json"),
1632            r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
1633        )
1634        .unwrap();
1635        record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
1636        let m = metadata(tmp.path());
1637        assert_eq!(m["transcript_path"], "/t/new.jsonl");
1638        assert_eq!(m["model"], "m");
1639        let leftovers = std::fs::read_dir(tmp.path())
1640            .unwrap()
1641            .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
1642            .count();
1643        assert_eq!(leftovers, 0, "the temp file is renamed into place");
1644    }
1645
1646    #[test]
1647    fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
1648        let tmp = tempfile::tempdir().unwrap();
1649        record_transcript_path(tmp.path(), "").unwrap();
1650        assert!(!tmp.path().join("metadata.json").exists());
1651
1652        std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
1653        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1654        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1655    }
1656
1657    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1658
1659    use crate::session_state::{RepoBinding, SessionState};
1660
1661    fn binding(id: &str) -> RepoBinding {
1662        RepoBinding {
1663            repo_id: id.into(),
1664            git_url: None,
1665            remote_id: None,
1666            codebase_name: None,
1667            updated_at: "t".into(),
1668        }
1669    }
1670
1671    /// Workspace mode: no pinned config, but the session is bound (e.g. via
1672    /// `tracevault repo switch`) — the stream event attributes to that repo.
1673    #[test]
1674    fn resolve_stream_binding_uses_session_active_when_unbound() {
1675        let session = SessionState {
1676            active: Some(binding("session-repo")),
1677            subagents: HashMap::new(),
1678            ..Default::default()
1679        };
1680        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1681        assert_eq!(got.unwrap().repo_id, "session-repo");
1682    }
1683
1684    /// Bound-mode regression: an empty session (no `repo switch` ever run)
1685    /// with a bound config.toml still resolves via the config.
1686    #[test]
1687    fn resolve_stream_binding_falls_back_to_bound_config() {
1688        let session = SessionState::default();
1689        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1690        assert_eq!(got.unwrap().repo_id, "bound-repo");
1691    }
1692
1693    /// No session binding and no bound config: nothing resolves, which is
1694    /// exactly what should trigger `run_stream`'s graceful no-op.
1695    #[test]
1696    fn resolve_stream_binding_none_when_nothing_resolves() {
1697        let session = SessionState::default();
1698        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1699        assert!(got.is_none());
1700    }
1701
1702    /// Subagent override precedence: a per-worktree override for the current
1703    /// worktree wins over the session's `active` binding.
1704    #[test]
1705    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1706        let session = SessionState {
1707            active: Some(binding("session-repo")),
1708            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1709            ..Default::default()
1710        };
1711        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1712        assert_eq!(got.unwrap().repo_id, "subagent-repo");
1713    }
1714
1715    /// Workspace mode: no bound config, but a user-level default is set (e.g.
1716    /// via `tracevault repo switch --user`) — the stream event attributes to
1717    /// that repo when nothing more specific resolves.
1718    #[test]
1719    fn resolve_stream_binding_falls_back_to_user_default() {
1720        let session = SessionState::default();
1721        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1722        assert_eq!(got.unwrap().repo_id, "userdef");
1723    }
1724
1725    /// The user-level default is the LOWEST-precedence tier: a bound config
1726    /// still wins over it.
1727    #[test]
1728    fn resolve_stream_binding_prefers_bound_over_user_default() {
1729        let session = SessionState::default();
1730        let got = resolve_stream_binding(
1731            &session,
1732            "/wt/x",
1733            Some(binding("bound")),
1734            Some(binding("userdef")),
1735        );
1736        assert_eq!(got.unwrap().repo_id, "bound");
1737    }
1738
1739    // ── attribution_for: repo-or-project gate ────────────────────────────────
1740
1741    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1742        crate::session_state::RepoBinding {
1743            repo_id: repo_id.into(),
1744            git_url: None,
1745            remote_id: None,
1746            codebase_name: None,
1747            updated_at: String::new(),
1748        }
1749    }
1750
1751    /// The regression this whole change exists for: a session with a project
1752    /// binding and NO repo binding must still ship, repo-less, instead of
1753    /// being dropped by the hook.
1754    #[test]
1755    fn attribution_falls_back_to_project_when_no_repo_binds() {
1756        let pid = uuid::Uuid::new_v4();
1757        assert_eq!(
1758            attribution_for(None, Some(pid)),
1759            Some(Attribution::ProjectOnly { project_id: pid })
1760        );
1761    }
1762
1763    /// Neither binding resolves — the only case that may still no-op.
1764    #[test]
1765    fn attribution_is_none_when_neither_repo_nor_project_binds() {
1766        assert_eq!(attribution_for(None, None), None);
1767    }
1768
1769    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1770    /// server left to deduce the project.
1771    #[test]
1772    fn attribution_uses_repo_with_no_project_overlay() {
1773        let repo = uuid::Uuid::new_v4().to_string();
1774        let b = binding_with(&repo);
1775        assert_eq!(
1776            attribution_for(Some(&b), None),
1777            Some(Attribution::Repo {
1778                repo_id: repo,
1779                project: None
1780            })
1781        );
1782    }
1783
1784    /// Both bound: the project overlays the repo (project-scoped ingest
1785    /// carrying repo_id), unchanged from before.
1786    #[test]
1787    fn attribution_overlays_project_on_repo() {
1788        let repo = uuid::Uuid::new_v4().to_string();
1789        let pid = uuid::Uuid::new_v4();
1790        let b = binding_with(&repo);
1791        assert_eq!(
1792            attribution_for(Some(&b), Some(pid)),
1793            Some(Attribution::Repo {
1794                repo_id: repo,
1795                project: Some(pid)
1796            })
1797        );
1798    }
1799
1800    /// A corrupted repo_id costs the repo attribution, not the trace: it
1801    /// degrades to project-only rather than dropping the event.
1802    #[test]
1803    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
1804        let pid = uuid::Uuid::new_v4();
1805        let b = binding_with("../../escape");
1806        assert_eq!(
1807            attribution_for(Some(&b), Some(pid)),
1808            Some(Attribution::ProjectOnly { project_id: pid })
1809        );
1810    }
1811
1812    /// ...but with no project to fall back to, a corrupt repo_id still drops,
1813    /// so it can never reach the pending filename.
1814    #[test]
1815    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
1816        let b = binding_with("../../escape");
1817        assert_eq!(attribution_for(Some(&b), None), None);
1818    }
1819
1820    // ── pending queue filenames ──────────────────────────────────────────────
1821
1822    /// The repo filename is unchanged, so queues buffered by earlier releases
1823    /// are still found and drained after this upgrade.
1824    #[test]
1825    fn pending_file_name_for_a_repo_is_unchanged() {
1826        let repo = uuid::Uuid::new_v4().to_string();
1827        assert_eq!(
1828            Attribution::Repo {
1829                repo_id: repo.clone(),
1830                project: Some(uuid::Uuid::new_v4())
1831            }
1832            .pending_file_name(),
1833            format!("pending-{repo}.jsonl")
1834        );
1835    }
1836
1837    /// Repo-less queues carry the `project-` infix, which an older CLI reads
1838    /// as a non-UUID repo id and skips (see the doc comment).
1839    #[test]
1840    fn pending_file_name_for_a_project_is_distinct() {
1841        let pid = uuid::Uuid::new_v4();
1842        assert_eq!(
1843            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
1844            format!("pending-project-{pid}.jsonl")
1845        );
1846    }
1847
1848    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1849
1850    #[test]
1851    fn binding_repo_id_is_valid_accepts_real_uuid() {
1852        assert!(binding_repo_id_is_valid(
1853            "550e8400-e29b-41d4-a716-446655440000"
1854        ));
1855    }
1856
1857    #[test]
1858    fn binding_repo_id_is_valid_rejects_path_traversal() {
1859        assert!(!binding_repo_id_is_valid("../evil"));
1860    }
1861
1862    #[test]
1863    fn binding_repo_id_is_valid_rejects_empty() {
1864        assert!(!binding_repo_id_is_valid(""));
1865    }
1866
1867    #[test]
1868    fn binding_repo_id_is_valid_rejects_non_uuid() {
1869        assert!(!binding_repo_id_is_valid("not-a-uuid"));
1870    }
1871
1872    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1873
1874    #[test]
1875    fn stamp_agent_sets_tool_and_version() {
1876        use crate::agent::Agent;
1877        let mut req = StreamEventRequest {
1878            protocol_version: 1,
1879            tool: Some("claude-code".to_string()),
1880            event_type: StreamEventType::ToolUse,
1881            session_id: "s".into(),
1882            timestamp: chrono::Utc::now(),
1883            hook_event_name: None,
1884            tool_name: None,
1885            tool_use_id: None,
1886            tool_input: None,
1887            tool_response: None,
1888            tool_is_error: None,
1889            event_index: None,
1890            event_uuid: None,
1891            transcript_lines: None,
1892            transcript_offset: None,
1893            model: None,
1894            cwd: None,
1895            final_stats: None,
1896            flow_id: None,
1897            labels: None,
1898            params: None,
1899            billing_mode: None,
1900        };
1901        stamp_agent(&mut req, Agent::Codex);
1902        assert_eq!(req.tool.as_deref(), Some("codex"));
1903        assert_eq!(req.protocol_version, 2);
1904
1905        stamp_agent(&mut req, Agent::ClaudeCode);
1906        assert_eq!(req.tool.as_deref(), Some("claude-code"));
1907        assert_eq!(req.protocol_version, 1);
1908    }
1909
1910    // ── pending_path_for: per-target offline queue ───────────────────────────
1911
1912    fn repo_attr(repo_id: &str) -> Attribution {
1913        Attribution::Repo {
1914            repo_id: repo_id.into(),
1915            project: None,
1916        }
1917    }
1918
1919    #[test]
1920    fn pending_path_is_repo_scoped() {
1921        let dir = std::path::Path::new("/tmp/sess");
1922        assert_eq!(
1923            pending_path_for(dir, &repo_attr("repo-a")),
1924            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1925        );
1926        assert_ne!(
1927            pending_path_for(dir, &repo_attr("repo-a")),
1928            pending_path_for(dir, &repo_attr("repo-b")),
1929        );
1930    }
1931
1932    /// A repo-less session must not share a queue file with any repo, so its
1933    /// buffered events can never be flushed to a repo endpoint.
1934    #[test]
1935    fn pending_path_for_a_project_never_collides_with_a_repo() {
1936        let dir = std::path::Path::new("/tmp/sess");
1937        let pid = uuid::Uuid::from_u128(9);
1938        assert_eq!(
1939            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1940            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
1941        );
1942        assert_ne!(
1943            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1944            pending_path_for(dir, &repo_attr(&pid.to_string())),
1945        );
1946    }
1947
1948    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1949
1950    #[test]
1951    fn read_new_transcript_lines_empty_path_is_noop() {
1952        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1953        // An empty path must yield no lines and offset 0, never an error from
1954        // handing `Path::new("")` to exists()/File::open.
1955        let dir = tempfile::tempdir().unwrap();
1956        let offset_path = dir.path().join(".stream_offset");
1957        let (lines, start_offset, end_offset) =
1958            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1959        assert!(
1960            lines.is_empty(),
1961            "empty path must yield no transcript lines"
1962        );
1963        assert_eq!(start_offset, 0);
1964        assert_eq!(end_offset, 0);
1965    }
1966
1967    // ── read_new_transcript_lines: start_offset is stable across a persisted
1968    //    end_offset, and equals the previous read's end_offset ─────────────────
1969
1970    #[test]
1971    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1972        let dir = tempfile::tempdir().unwrap();
1973        let transcript_path = dir.path().join("transcript.jsonl");
1974        let offset_path = dir.path().join(".stream_offset");
1975
1976        fs::write(
1977            &transcript_path,
1978            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1979        )
1980        .unwrap();
1981
1982        let (lines, start_offset, end_offset) =
1983            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1984        assert_eq!(lines.len(), 2);
1985        assert_eq!(start_offset, 0, "first read starts at byte 0");
1986        assert!(end_offset > 0);
1987
1988        fs::write(&offset_path, end_offset.to_string()).unwrap();
1989
1990        let mut f = OpenOptions::new()
1991            .append(true)
1992            .open(&transcript_path)
1993            .unwrap();
1994        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1995        drop(f);
1996
1997        let (lines2, start_offset2, end_offset2) =
1998            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1999        assert_eq!(lines2.len(), 1);
2000        assert_eq!(
2001            start_offset2, end_offset,
2002            "second read's start_offset must equal the first read's persisted end_offset"
2003        );
2004        assert!(end_offset2 > start_offset2);
2005    }
2006
2007    // ── capture_project: local-only project resolver ──────────────────────────
2008
2009    /// Holds the env lock and points the config dir (`XDG_CONFIG_HOME` on
2010    /// Linux, `HOME` for macOS's `dirs::config_dir()`) at a tempdir: the last
2011    /// tier reads `user_project.toml` from there, so without isolation this
2012    /// test fails on any machine with a real user default and races tests
2013    /// that write one.
2014    ///
2015    /// `TRACEVAULT_PROJECT` is pinned UNSET for the same reason:
2016    /// `capture_project` reads it (rung 3, above `session.active_project`),
2017    /// and other tests in this same binary SET it. The crate lock only
2018    /// serializes mutators against each other, so a non-locking reader still
2019    /// races them — and `std::env::set_var` concurrent with `std::env::var`
2020    /// is exactly the UB the `unsafe` blocks in `EnvVarGuard` are annotated
2021    /// against. Holding the lock AND declaring the value is what makes the
2022    /// precedence assertions below describe the tiers they name rather than
2023    /// whatever the ambient shell happens to export.
2024    #[tokio::test]
2025    async fn capture_project_precedence_local_only() {
2026        use crate::session_state::{ProjectBinding, SessionState};
2027        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2028        let tmp = tempfile::tempdir().unwrap();
2029        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2030        _guard.set("XDG_CONFIG_HOME", tmp.path());
2031        _guard.set("HOME", tmp.path());
2032        _guard.remove("TRACEVAULT_PROJECT");
2033
2034        let pb = |id: &str| ProjectBinding {
2035            project_id: id.into(),
2036            project_name: "n".into(),
2037            updated_at: "".into(),
2038            forced_until: None,
2039        };
2040        let u = uuid::Uuid::from_u128;
2041        // session active only
2042        let s = SessionState {
2043            active_project: Some(pb(&u(2).to_string())),
2044            ..Default::default()
2045        };
2046        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
2047        // subagent worktree beats session
2048        let mut s = s;
2049        s.subagent_projects
2050            .insert("/wt".into(), pb(&u(1).to_string()));
2051        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
2052        // no worktree match -> session active
2053        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
2054        // empty session, no user_project.toml in the isolated config dir -> None
2055        assert_eq!(capture_project(&SessionState::default(), None), None);
2056        // malformed stored id -> None (defensive)
2057        let bad = SessionState {
2058            active_project: Some(pb("not-a-uuid")),
2059            ..Default::default()
2060        };
2061        assert_eq!(capture_project(&bad, None), None);
2062        // a valid user_project.toml in the isolated config dir is the last tier
2063        let path = crate::user_project_default::default_project_path().unwrap();
2064        assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2065        crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2066        assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
2067    }
2068
2069    /// The full binding — not just its id — survives `capture_binding`: this
2070    /// is what lets `attribution_mode` see a session-scoped `forced_until`
2071    /// (Important finding 1 in the VIS-305 Part C review: the old
2072    /// process-global disk read never saw a force written into SESSION
2073    /// state, which is where a plain `project switch --project-attribution
2074    /// explicit` — no `--user` — writes it).
2075    /// ENV ISOLATION: see `capture_project_precedence_local_only` — this
2076    /// test also goes through the capture chain, which reads
2077    /// `TRACEVAULT_PROJECT` at a rung ABOVE the session-active binding it is
2078    /// asserting on.
2079    #[test]
2080    fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2081        use crate::session_state::{ProjectBinding, SessionState};
2082        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2083        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2084        _guard.remove("TRACEVAULT_PROJECT");
2085        let pid = uuid::Uuid::from_u128(2);
2086        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2087        let s = SessionState {
2088            active_project: Some(ProjectBinding {
2089                project_id: pid.to_string(),
2090                project_name: "n".into(),
2091                updated_at: "".into(),
2092                forced_until: Some(future.clone()),
2093            }),
2094            ..Default::default()
2095        };
2096        let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
2097        assert_eq!(got.forced_until, Some(future));
2098    }
2099
2100    /// `_env_lock` serializes this against other tests in the crate that
2101    /// mutate `TRACEVAULT_PROJECT` (see `test_helpers::lock_env_mutation_sync`),
2102    /// including any that call `commands::project::status`, which reads the
2103    /// same var.
2104    #[test]
2105    fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2106        // A name would need a `list_projects` round trip, and this path runs
2107        // per-event in a short-lived hook process. Same rule already excludes
2108        // `config_default` here.
2109        let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2110
2111        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2112        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2113
2114        _guard.set("TRACEVAULT_PROJECT", uuid);
2115        let got = env_project_binding().expect("uuid form is honoured");
2116        assert_eq!(got.project_id, uuid);
2117
2118        _guard.set("TRACEVAULT_PROJECT", "my-project");
2119        assert!(
2120            env_project_binding().is_none(),
2121            "a name is ignored on the network-free capture path"
2122        );
2123
2124        _guard.remove("TRACEVAULT_PROJECT");
2125        assert!(env_project_binding().is_none());
2126    }
2127
2128    // ── attribution_mode ───────────────────────────────────────────────────
2129    //
2130    // `attribution_mode` no longer touches disk at all: it takes the WINNING
2131    // binding (as resolved by `capture_project`) as a parameter, so these
2132    // tests only need to isolate `TRACEVAULT_PROJECT_ATTRIBUTION` via the
2133    // crate's env-mutation lock/guard, not `XDG_CONFIG_HOME`.
2134
2135    fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2136        crate::session_state::ProjectBinding {
2137            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2138            project_name: "p".into(),
2139            updated_at: chrono::Utc::now().to_rfc3339(),
2140            forced_until: forced_until.map(str::to_string),
2141        }
2142    }
2143
2144    #[test]
2145    fn env_force_is_explicit_and_needs_no_expiry() {
2146        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2147        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2148        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2149
2150        assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2151    }
2152
2153    #[test]
2154    fn absent_or_unrecognised_env_is_derived() {
2155        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2156        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2157
2158        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2159        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2160
2161        // The CLI does not forward a value it does not recognise: the server
2162        // would 400 it, and failing a hook over a typo'd env var helps
2163        // nobody. The server's strictness is for callers that bypass the
2164        // CLI.
2165        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2166        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2167    }
2168
2169    /// The binding-persisted half of `attribution_mode`: a LIVE `forced_until`
2170    /// on the WINNING binding (no env var involved) must also read as
2171    /// `explicit` — this is what `project switch --project-attribution
2172    /// explicit` ultimately drives, whether that binding lives in session
2173    /// state or the user-level default.
2174    #[test]
2175    fn live_binding_force_is_explicit_without_env() {
2176        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2177        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2178        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2179
2180        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2181        let binding = forced_binding(Some(&future));
2182
2183        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2184    }
2185
2186    /// This is the test that would fail if a lapsed persisted force still
2187    /// made it onto the wire: with no env override, a `forced_until` in the
2188    /// past on the winning binding must make `attribution_mode` — the exact
2189    /// function that supplies the header — report `derived`, not `explicit`.
2190    /// Not sending an `explicit` header IS the fallback to derived
2191    /// attribution.
2192    #[test]
2193    fn lapsed_binding_force_is_derived_without_env() {
2194        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2195        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2196        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2197
2198        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2199        let binding = forced_binding(Some(&past));
2200
2201        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2202    }
2203
2204    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
2205    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
2206    /// read as `derived`, never panic or, worse, read as `explicit`. Pins the
2207    /// fail-safe direction against a future refactor to `.expect(...)`.
2208    #[test]
2209    fn unparseable_forced_until_is_derived() {
2210        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2211        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2212        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2213
2214        let binding = forced_binding(Some("not-a-timestamp"));
2215
2216        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2217    }
2218
2219    /// Env-provided force must be exempt from expiry in fact, not just by
2220    /// coincidence of the OR: pairing it with a binding force that has
2221    /// ALREADY LAPSED still yields `explicit`. If `attribution_mode` were
2222    /// refactored to gate the env branch on any timestamp, this is the test
2223    /// that would catch it — `lapsed_binding_force_is_derived_without_env`
2224    /// alone couldn't, since it never sets the env var.
2225    #[test]
2226    fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2227        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2228        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2229        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2230
2231        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2232        let binding = forced_binding(Some(&past));
2233
2234        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2235    }
2236
2237    /// VIS-305 Part C review, Important finding 1: a SESSION-scoped force
2238    /// (`project switch --project-attribution explicit` WITHOUT `--user`,
2239    /// which is the default whenever a session id is set — i.e. the ordinary
2240    /// case inside every instrumented agent session) must actually reach the
2241    /// wire as `explicit`. The old process-global `attribution_mode` only
2242    /// ever consulted the user-level default store and never saw a force
2243    /// written into session state at all, so this would have silently sent
2244    /// `derived` while `project switch`'s own success message claimed
2245    /// membership was not being checked. Exercised end-to-end through
2246    /// `send_stream_event` and a real captured request header, not just the
2247    /// pure `attribution_mode` function, so a regression anywhere in the
2248    /// plumbing between `capture_project` and the wire is caught.
2249    #[tokio::test]
2250    async fn session_scoped_force_is_honoured_on_the_wire() {
2251        use crate::session_state::{ProjectBinding, SessionState};
2252
2253        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2254        let tmp = tempfile::tempdir().unwrap();
2255        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2256        // No user-level default at all: the force under test lives ONLY in
2257        // session state, so a pass here can't be explained by an ambient or
2258        // accidentally-written user_project.toml.
2259        _guard.set("XDG_CONFIG_HOME", tmp.path());
2260        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2261        // `capture_project` reads `TRACEVAULT_PROJECT` ABOVE the
2262        // session-active tier this test pins the force on; unset it so an
2263        // ambient export can't redirect the capture at another project.
2264        _guard.remove("TRACEVAULT_PROJECT");
2265
2266        let pid = uuid::Uuid::from_u128(321);
2267        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2268        let session = SessionState {
2269            active_project: Some(ProjectBinding {
2270                project_id: pid.to_string(),
2271                project_name: "proj".into(),
2272                updated_at: "".into(),
2273                forced_until: Some(future),
2274            }),
2275            ..Default::default()
2276        };
2277        let capture_binding = capture_binding(&session, None);
2278
2279        let resp = ok_stream_response();
2280        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2281        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2282        let req = sample_stream_event_request();
2283        let mut warned = false;
2284
2285        let got = send_stream_event(
2286            &client,
2287            &Attribution::ProjectOnly { project_id: pid },
2288            attribution_force(capture_binding.as_ref()),
2289            &req,
2290            &mut warned,
2291        )
2292        .await
2293        .expect("send_stream_event must succeed");
2294        assert_eq!(
2295            got.expect("a successful send returns a response").status,
2296            "accepted"
2297        );
2298
2299        let captured = rx
2300            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2301            .expect("no request captured");
2302        assert!(
2303            captured
2304                .to_lowercase()
2305                .contains("x-tracevault-project-attribution: explicit"),
2306            "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2307        );
2308    }
2309
2310    /// VIS-305 Part C review, Important finding 2: a LIVE force sitting on
2311    /// the machine-global user-level default must NOT leak onto a different,
2312    /// higher-precedence project that resolves instead. The old
2313    /// process-global `attribution_mode` couldn't tell the two apart — it
2314    /// declared `explicit` for ANY project as long as SOME force existed
2315    /// anywhere on disk. Here the user-default's force belongs to project A,
2316    /// but `TRACEVAULT_PROJECT` (a higher-precedence local tier) points this
2317    /// capture at project B, which was never forced.
2318    #[test]
2319    fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2320        use crate::session_state::{ProjectBinding, SessionState};
2321
2322        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2323        let tmp = tempfile::tempdir().unwrap();
2324        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2325        _guard.set("XDG_CONFIG_HOME", tmp.path());
2326        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2327
2328        let project_a = uuid::Uuid::from_u128(1);
2329        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2330        crate::user_project_default::save(&ProjectBinding {
2331            project_id: project_a.to_string(),
2332            project_name: "a".into(),
2333            updated_at: chrono::Utc::now().to_rfc3339(),
2334            forced_until: Some(future),
2335        })
2336        .unwrap();
2337
2338        let project_b = uuid::Uuid::from_u128(2);
2339        _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2340
2341        let capture_binding = capture_binding(&SessionState::default(), None);
2342        assert_eq!(
2343            capture_binding.as_ref().map(|b| b.project_id.as_str()),
2344            Some(project_b.to_string()).as_deref(),
2345            "TRACEVAULT_PROJECT must outrank the user-level default"
2346        );
2347
2348        assert_eq!(
2349            attribution_mode(capture_binding.as_ref()),
2350            AttributionMode::Derived,
2351            "a force on the user-default project must not leak onto a DIFFERENT, \
2352             higher-precedence project that never asked to be forced"
2353        );
2354    }
2355
2356    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
2357
2358    use std::io::BufReader;
2359    use std::net::TcpListener;
2360    use std::sync::mpsc;
2361    use std::thread;
2362    use std::time::{Duration, Instant};
2363
2364    /// How long an accept loop waits for a connection that never arrives
2365    /// (e.g. a regression that stops the client from making an expected
2366    /// request) before giving up, so the server thread exits cleanly
2367    /// instead of blocking in `accept()` forever.
2368    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2369
2370    /// Poll a non-blocking `listener` for a connection until one arrives or
2371    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
2372    /// `WouldBlock` accept error) so callers can stop cleanly rather than
2373    /// block forever.
2374    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2375        let deadline = Instant::now() + ACCEPT_DEADLINE;
2376        loop {
2377            match listener.accept() {
2378                Ok((stream, _)) => {
2379                    // The accepted stream's blocking mode isn't guaranteed to
2380                    // be inherited from the (non-blocking) listener across
2381                    // platforms — make it explicitly blocking so the
2382                    // subsequent read/write calls behave as before.
2383                    let _ = stream.set_nonblocking(false);
2384                    return Some(stream);
2385                }
2386                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2387                    if Instant::now() >= deadline {
2388                        return None;
2389                    }
2390                    thread::sleep(Duration::from_millis(20));
2391                }
2392                Err(_) => return None,
2393            }
2394        }
2395    }
2396
2397    /// How long a test waits for the captured request before failing (rather
2398    /// than hanging forever if the client never connects). Mirrors the
2399    /// harness in `tests/stream_event_project_test.rs`.
2400    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2401
2402    /// Read one request's line and headers off `stream`, hand the pair to
2403    /// `tx` as a single string, then write `response` back.
2404    ///
2405    /// Shared by [`spawn_once_capturing_request`] and
2406    /// [`spawn_n_capturing_requests`], which grew this same capture
2407    /// independently and disagreed only on `trim()` vs `trim_end()` for the
2408    /// blank-line terminator (equivalent, since a bare CRLF trims empty
2409    /// either way).
2410    ///
2411    /// Deliberately NOT `test_helpers::read_request`: that one is private to
2412    /// its module and blocks in `accept()`, where these two use
2413    /// `set_nonblocking` plus a deadline.
2414    ///
2415    /// Headers are captured, not just the request line, so a test can assert
2416    /// on `x-tracevault-project-attribution` — without them a regression that
2417    /// hardcoded `"derived"` at a `stream_event_for_project` call site would
2418    /// pass the whole suite, since nothing in-crate ever looked at the header
2419    /// actually sent. They are appended AFTER the request line, leaving
2420    /// `starts_with`/`contains` assertions on the line itself unaffected.
2421    fn capture_request_and_respond(
2422        stream: std::net::TcpStream,
2423        tx: &mpsc::Sender<String>,
2424        response: &str,
2425    ) {
2426        let mut reader = BufReader::new(stream);
2427        let mut captured = String::new();
2428        let _ = reader.read_line(&mut captured);
2429        loop {
2430            let mut header = String::new();
2431            if reader.read_line(&mut header).unwrap_or(0) == 0 {
2432                break;
2433            }
2434            if header.trim().is_empty() {
2435                break;
2436            }
2437            captured.push_str(&header);
2438        }
2439        let _ = tx.send(captured);
2440        let mut stream = reader.into_inner();
2441        let _ = stream.write_all(response.as_bytes());
2442        let _ = stream.flush();
2443    }
2444
2445    /// Spawn a one-shot server that returns `response` (a full HTTP response)
2446    /// to the first request, capturing it via
2447    /// [`capture_request_and_respond`]. Mirrors the harness in
2448    /// `tests/stream_event_project_test.rs` / `tests/resolve_remote_test.rs`.
2449    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2450        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2451        listener.set_nonblocking(true).unwrap();
2452        let addr = listener.local_addr().unwrap();
2453        let (tx, rx) = mpsc::channel();
2454        thread::spawn(move || {
2455            if let Some(stream) = accept_with_deadline(&listener) {
2456                capture_request_and_respond(stream, &tx, response);
2457            }
2458        });
2459        (format!("http://{addr}"), rx)
2460    }
2461
2462    fn ok_stream_response() -> String {
2463        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2464            session_db_id: uuid::Uuid::nil(),
2465            event_db_id: Some(uuid::Uuid::nil()),
2466            status: "accepted".to_string(),
2467        })
2468        .unwrap();
2469        format!(
2470            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2471            body.len(),
2472            body
2473        )
2474    }
2475
2476    fn sample_stream_event_request() -> StreamEventRequest {
2477        StreamEventRequest {
2478            protocol_version: 2,
2479            tool: Some("claude-code".to_string()),
2480            event_type: StreamEventType::ToolUse,
2481            session_id: "sess-1".into(),
2482            timestamp: chrono::Utc::now(),
2483            hook_event_name: Some("PostToolUse".into()),
2484            tool_name: None,
2485            tool_use_id: None,
2486            tool_input: None,
2487            tool_response: None,
2488            tool_is_error: None,
2489            event_index: None,
2490            event_uuid: None,
2491            transcript_lines: None,
2492            transcript_offset: None,
2493            model: None,
2494            cwd: None,
2495            final_stats: None,
2496            flow_id: None,
2497            labels: None,
2498            params: None,
2499            billing_mode: None,
2500        }
2501    }
2502
2503    /// With a `SessionState` whose `active_project` is set, `capture_project`
2504    /// resolves a `capture_pid`, and `send_stream_event` must route to the
2505    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
2506    /// than the repo-scoped one.
2507    #[tokio::test]
2508    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2509        use crate::session_state::{ProjectBinding, SessionState};
2510
2511        // Isolate from any ambient user-level project default so this test's
2512        // `capture_project` call depends only on the SessionState below —
2513        // mirrors the isolation pattern in `commands::project`'s tests.
2514        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2515        let tmp = tempfile::tempdir().unwrap();
2516        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2517        _guard.set("XDG_CONFIG_HOME", tmp.path());
2518        // `capture_project` reads `TRACEVAULT_PROJECT` above the
2519        // session-active tier asserted below — pin it unset. Ditto
2520        // `TRACEVAULT_PROJECT_ATTRIBUTION`, which the `derived` header
2521        // assertion at the end of this test depends on.
2522        _guard.remove("TRACEVAULT_PROJECT");
2523        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2524
2525        let pid = uuid::Uuid::from_u128(99);
2526        let session = SessionState {
2527            active_project: Some(ProjectBinding {
2528                project_id: pid.to_string(),
2529                project_name: "proj".into(),
2530                updated_at: "".into(),
2531                forced_until: None,
2532            }),
2533            ..Default::default()
2534        };
2535        let capture_binding = capture_binding(&session, None);
2536        let capture_pid = capture_binding
2537            .as_ref()
2538            .and_then(crate::resolution::capture_project_id);
2539        assert_eq!(capture_pid, Some(pid));
2540
2541        let resp = ok_stream_response();
2542        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2543        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2544        let req = sample_stream_event_request();
2545
2546        let mut warned = false;
2547        let got = send_stream_event(
2548            &client,
2549            &Attribution::Repo {
2550                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2551                project: capture_pid,
2552            },
2553            attribution_force(capture_binding.as_ref()),
2554            &req,
2555            &mut warned,
2556        )
2557        .await
2558        .expect("send_stream_event must succeed");
2559        assert_eq!(
2560            got.expect("a successful send returns a response").status,
2561            "accepted"
2562        );
2563
2564        let line = rx
2565            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2566            .expect("no request captured");
2567        assert!(
2568            line.starts_with(&format!(
2569                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2570            )),
2571            "an active project binding must route to the project-scoped endpoint, got: {line}"
2572        );
2573        // Covers the `Attribution::Repo { project: Some(_) }` call site of
2574        // `stream_event_for_project` (the `ProjectOnly` call site is covered
2575        // by `session_scoped_force_is_honoured_on_the_wire` and
2576        // `send_stream_event_project_only_omits_repo_id`) — an unforced
2577        // binding must still send the header, declaring `derived`.
2578        assert!(
2579            line.to_lowercase()
2580                .contains("x-tracevault-project-attribution: derived"),
2581            "got: {line}"
2582        );
2583    }
2584
2585    /// With an empty binding (default `SessionState`, no worktree override)
2586    /// and no user-level default present in the test env, `capture_project`
2587    /// resolves `None` and `send_stream_event` must fall back to the
2588    /// repo-scoped endpoint.
2589    #[tokio::test]
2590    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2591        use crate::session_state::SessionState;
2592
2593        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2594        let tmp = tempfile::tempdir().unwrap();
2595        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2596        // No user_project.toml under this isolated config dir, so there is no
2597        // ambient user-level default to leak in — and no `TRACEVAULT_PROJECT`
2598        // either, which `capture_project` would otherwise honour and turn
2599        // this "nothing resolves" case into a project-scoped send.
2600        _guard.set("XDG_CONFIG_HOME", tmp.path());
2601        _guard.remove("TRACEVAULT_PROJECT");
2602
2603        let capture_binding = capture_binding(&SessionState::default(), None);
2604        assert_eq!(capture_binding, None);
2605
2606        let resp = ok_stream_response();
2607        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2608        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2609        let req = sample_stream_event_request();
2610
2611        let mut warned = false;
2612        let got = send_stream_event(
2613            &client,
2614            &Attribution::Repo {
2615                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2616                project: None,
2617            },
2618            attribution_force(capture_binding.as_ref()),
2619            &req,
2620            &mut warned,
2621        )
2622        .await
2623        .expect("send_stream_event must succeed");
2624        assert_eq!(
2625            got.expect("a successful send returns a response").status,
2626            "accepted"
2627        );
2628
2629        let line = rx
2630            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2631            .expect("no request captured");
2632        assert!(
2633            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
2634            "no binding must fall back to the repo-scoped endpoint, got: {line}"
2635        );
2636    }
2637
2638    // ── I1/I2: refused project-scoped send is an error + transient no-fallback ───
2639
2640    /// Spawn a server that replies to up to `responses.len()` sequential
2641    /// connections with the given full HTTP responses, in order, capturing
2642    /// each request (line + headers, via [`capture_request_and_respond`])
2643    /// over the channel. The listening socket itself is dropped (closing it)
2644    /// once all responses have been served, so any further connection attempt
2645    /// fails fast (connection refused) rather than hanging for the client's
2646    /// request timeout — this lets a test assert "no further request was
2647    /// sent" cheaply.
2648    fn spawn_n_capturing_requests(
2649        responses: Vec<&'static str>,
2650    ) -> (String, mpsc::Receiver<String>) {
2651        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2652        listener.set_nonblocking(true).unwrap();
2653        let addr = listener.local_addr().unwrap();
2654        let (tx, rx) = mpsc::channel();
2655        thread::spawn(move || {
2656            for response in responses {
2657                // If a regression stops the client from making this request
2658                // (e.g. the expected Nth call never happens), don't block
2659                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
2660                // and let the thread end so the test process can't hang.
2661                let Some(stream) = accept_with_deadline(&listener) else {
2662                    break;
2663                };
2664                capture_request_and_respond(stream, &tx, response);
2665            }
2666            // `listener` (and `tx`) drop here, closing the socket and the
2667            // channel — a stray extra request gets ECONNREFUSED immediately
2668            // instead of hanging, and a stray extra `rx.recv` returns
2669            // Disconnected immediately instead of blocking.
2670        });
2671        (format!("http://{addr}"), rx)
2672    }
2673
2674    /// I1: a deterministic 400 ("is not a member of project ...") from the
2675    /// project-scoped endpoint must be an error, not a silent second send to
2676    /// the repo-scoped endpoint. TWO responses (400 then 200) are staged so
2677    /// the "no second request" check is non-vacuous — see the comment in
2678    /// `send_stream_event_project_only_drops_on_scoping_4xx` for why a single
2679    /// staged response would make that assertion pass vacuously.
2680    #[tokio::test]
2681    async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
2682        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
2683        let resp_400 = format!(
2684            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2685            body_400.len(),
2686            body_400
2687        );
2688        let resp_200 = ok_stream_response();
2689
2690        let (base, rx) = spawn_n_capturing_requests(vec![
2691            Box::leak(resp_400.into_boxed_str()),
2692            Box::leak(resp_200.into_boxed_str()),
2693        ]);
2694        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2695        let req = sample_stream_event_request();
2696        let pid = uuid::Uuid::from_u128(42);
2697
2698        let mut warned = false;
2699        let err = send_stream_event(
2700            &client,
2701            &Attribution::Repo {
2702                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2703                project: Some(pid),
2704            },
2705            attribution_force(None),
2706            &req,
2707            &mut warned,
2708        )
2709        .await
2710        .expect_err("a refused declared project must be an error, not a silent fallback");
2711        assert!(
2712            err.to_string().contains("400"),
2713            "propagated error must reflect the status, got: {err}"
2714        );
2715        assert!(
2716            warned,
2717            "the refusal must be printed (gated on `warned`) so it is visible"
2718        );
2719
2720        let first = rx
2721            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2722            .expect("no first request captured");
2723        assert!(
2724            first.contains(&format!("/projects/{pid}/stream")),
2725            "first request must hit the project-scoped endpoint, got: {first}"
2726        );
2727        assert!(
2728            first.contains("repo_id="),
2729            "first request must carry repo_id, got: {first}"
2730        );
2731
2732        assert!(
2733            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2734            "no second (repo-scoped fallback) request must be sent"
2735        );
2736    }
2737
2738    /// A 403 from the project-scoped endpoint must likewise be an error, not a
2739    /// silent second send to the repo-scoped endpoint.
2740    #[tokio::test]
2741    async fn send_stream_event_errors_on_403_without_fallback() {
2742        let body_403 = "forbidden";
2743        let resp_403 = format!(
2744            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2745            body_403.len(),
2746            body_403
2747        );
2748        let resp_200 = ok_stream_response();
2749
2750        let (base, rx) = spawn_n_capturing_requests(vec![
2751            Box::leak(resp_403.into_boxed_str()),
2752            Box::leak(resp_200.into_boxed_str()),
2753        ]);
2754        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2755        let req = sample_stream_event_request();
2756        let pid = uuid::Uuid::from_u128(43);
2757
2758        let mut warned = false;
2759        let err = send_stream_event(
2760            &client,
2761            &Attribution::Repo {
2762                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2763                project: Some(pid),
2764            },
2765            attribution_force(None),
2766            &req,
2767            &mut warned,
2768        )
2769        .await
2770        .expect_err("a refused declared project must be an error, not a silent fallback");
2771        assert!(
2772            err.to_string().contains("403"),
2773            "propagated error must reflect the status, got: {err}"
2774        );
2775        assert!(
2776            warned,
2777            "the refusal must be printed (gated on `warned`) so it is visible"
2778        );
2779
2780        let first = rx
2781            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2782            .expect("no first request captured");
2783        assert!(
2784            first.contains(&format!("/projects/{pid}/stream")),
2785            "first request must hit the project-scoped endpoint, got: {first}"
2786        );
2787        assert!(
2788            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2789            "no second (repo-scoped fallback) request must be sent"
2790        );
2791    }
2792
2793    /// The refusal error must be printed at most once per hook invocation
2794    /// (i.e. per shared `warned` flag), even across multiple calls sharing
2795    /// it — mirroring how the pending-flush loop and the live send share one
2796    /// `warned` for a single invocation.
2797    #[tokio::test]
2798    async fn refused_error_is_printed_once_per_invocation() {
2799        let body_400 = "not a member";
2800        let resp_400 = || {
2801            format!(
2802                "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2803                body_400.len(),
2804                body_400
2805            )
2806        };
2807        let (base, _rx) = spawn_n_capturing_requests(vec![
2808            Box::leak(resp_400().into_boxed_str()),
2809            Box::leak(resp_400().into_boxed_str()),
2810        ]);
2811        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2812        let req = sample_stream_event_request();
2813        let pid = uuid::Uuid::from_u128(44);
2814        let attribution = Attribution::Repo {
2815            repo_id: "11111111-1111-1111-1111-111111111111".into(),
2816            project: Some(pid),
2817        };
2818
2819        let mut warned = false;
2820        assert!(
2821            send_stream_event(
2822                &client,
2823                &attribution,
2824                attribution_force(None),
2825                &req,
2826                &mut warned
2827            )
2828            .await
2829            .is_err(),
2830            "a refused declared project must be an error"
2831        );
2832        assert!(warned, "the flag must be set after the first refusal");
2833
2834        assert!(
2835            send_stream_event(
2836                &client,
2837                &attribution,
2838                attribution_force(None),
2839                &req,
2840                &mut warned
2841            )
2842            .await
2843            .is_err(),
2844            "a second refusal must also be an error"
2845        );
2846        assert!(warned, "the flag stays set across the shared invocation");
2847    }
2848
2849    /// Finding 5's scenario end to end, on the repo-bound path, as VIS-316
2850    /// leaves it: a live persisted force makes this send declare `explicit`,
2851    /// the force gate refuses it with a 403 — and the event is now an ERROR
2852    /// queued for retry, never re-sent to the repo-scoped endpoint where the
2853    /// server would DEDUCE a project that is precisely not the one the
2854    /// operator forced.
2855    ///
2856    /// Pins the fact the refusal clause depends on: the mode that went on
2857    /// the wire really is `explicit`, and it is the same value
2858    /// `refused_error` is handed — the message and the wire cannot disagree.
2859    /// A spare 200 is staged so "no second request" is non-vacuous.
2860    #[tokio::test]
2861    async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
2862        let body_403 = "forbidden";
2863        let resp_403 = format!(
2864            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2865            body_403.len(),
2866            body_403
2867        );
2868        let resp_200 = ok_stream_response();
2869
2870        let (base, rx) = spawn_n_capturing_requests(vec![
2871            Box::leak(resp_403.into_boxed_str()),
2872            Box::leak(resp_200.into_boxed_str()),
2873        ]);
2874        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2875        let req = sample_stream_event_request();
2876        let pid = uuid::Uuid::from_u128(42);
2877
2878        // A live persisted force on the winning binding — no env var needed,
2879        // so this test takes no env lock.
2880        let forced = crate::session_state::ProjectBinding {
2881            project_id: pid.to_string(),
2882            project_name: "forced".into(),
2883            updated_at: "".into(),
2884            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
2885        };
2886
2887        let mut warned = false;
2888        let err = send_stream_event(
2889            &client,
2890            &Attribution::Repo {
2891                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2892                project: Some(pid),
2893            },
2894            attribution_force(Some(&forced)),
2895            &req,
2896            &mut warned,
2897        )
2898        .await
2899        .expect_err("a refused force must be an error, not a silent fallback");
2900        assert!(
2901            err.to_string().contains("403"),
2902            "propagated error must reflect the status, got: {err}"
2903        );
2904        assert!(warned, "the refusal must be printed exactly once");
2905
2906        let first = rx
2907            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2908            .expect("no first request captured");
2909        assert!(
2910            first.contains(&format!("/projects/{pid}/stream")),
2911            "first request must hit the project-scoped endpoint, got: {first}"
2912        );
2913        assert!(
2914            first
2915                .to_lowercase()
2916                .contains("x-tracevault-project-attribution: explicit"),
2917            "the refused send must have DECLARED explicit — this is the mode \
2918             `refused_error` is handed: {first}"
2919        );
2920
2921        assert!(
2922            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2923            "a refused force must NOT be re-attributed via the repo-scoped endpoint"
2924        );
2925    }
2926
2927    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
2928    /// project endpoint with NO `repo_id` query pair. This is the wire shape
2929    /// the server documents as "repo-less (0-repo) projects are supported".
2930    ///
2931    /// Takes the env lock and pins `TRACEVAULT_PROJECT_ATTRIBUTION` unset:
2932    /// this test also asserts the `derived` attribution header, and
2933    /// `attribution_mode` reads that variable even when the binding passed
2934    /// in is `None`.
2935    #[tokio::test]
2936    async fn send_stream_event_project_only_omits_repo_id() {
2937        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2938        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2939        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2940
2941        let resp = ok_stream_response();
2942        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2943        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2944        let req = sample_stream_event_request();
2945        let pid = uuid::Uuid::from_u128(11);
2946
2947        let mut warned = false;
2948        let got = send_stream_event(
2949            &client,
2950            &Attribution::ProjectOnly { project_id: pid },
2951            attribution_force(None),
2952            &req,
2953            &mut warned,
2954        )
2955        .await
2956        .expect("a repo-less project send must succeed");
2957        assert_eq!(
2958            got.expect("a successful send returns a response").status,
2959            "accepted"
2960        );
2961
2962        let line = rx
2963            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2964            .expect("no request captured");
2965        assert!(
2966            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
2967            "expected a bare project path with no query string, got: {line}"
2968        );
2969        assert!(
2970            line.to_lowercase()
2971                .contains("x-tracevault-project-attribution: derived"),
2972            "with no forced binding, the header must declare `derived`, got: {line}"
2973        );
2974        assert!(
2975            !warned,
2976            "a repo-less send has no fallback and must not warn about one"
2977        );
2978    }
2979
2980    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
2981    /// the queue is keyed by the very project id the server says does not
2982    /// resolve, so a corrected binding writes to a different file and these
2983    /// events would never be retried — they would just accumulate, one per
2984    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
2985    /// trigger a second, impossible request.
2986    #[tokio::test]
2987    async fn send_stream_event_project_only_drops_on_scoping_4xx() {
2988        let body = "no such project";
2989        let resp_404 = format!(
2990            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2991            body.len(),
2992            body
2993        );
2994        // TWO responses are staged although only one request is expected. With
2995        // a single response the helper drops its sender the moment the list is
2996        // exhausted, so the "no second request" assertion below would pass on
2997        // `Disconnected` whether or not a second request happened — a vacuous
2998        // check. Staging a spare keeps the server accepting, so a stray
2999        // request really is captured and really fails the test.
3000        let (base, rx) = spawn_n_capturing_requests(vec![
3001            Box::leak(resp_404.clone().into_boxed_str()),
3002            Box::leak(resp_404.into_boxed_str()),
3003        ]);
3004        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3005        let req = sample_stream_event_request();
3006        let pid = uuid::Uuid::from_u128(12);
3007
3008        let mut warned = false;
3009        let got = send_stream_event(
3010            &client,
3011            &Attribution::ProjectOnly { project_id: pid },
3012            attribution_force(None),
3013            &req,
3014            &mut warned,
3015        )
3016        .await
3017        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
3018        assert!(
3019            got.is_none(),
3020            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
3021        );
3022        assert!(
3023            warned,
3024            "dropping data silently is the failure mode to avoid"
3025        );
3026
3027        let first = rx
3028            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3029            .expect("no request captured");
3030        assert!(
3031            first.contains(&format!("/projects/{pid}/stream")),
3032            "must hit the project-scoped endpoint, got: {first}"
3033        );
3034        assert!(
3035            rx.recv_timeout(Duration::from_millis(500)).is_err(),
3036            "a repo-less send must make exactly one request — no fallback exists"
3037        );
3038    }
3039
3040    /// A 403 is NOT dropped. It can mean the account has no `tracevault` grant,
3041    /// which an administrator can grant — after which the buffered events do
3042    /// deliver. It must propagate so the caller queues them.
3043    #[tokio::test]
3044    async fn send_stream_event_project_only_buffers_on_403() {
3045        let body = "forbidden";
3046        let resp_403 = format!(
3047            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3048            body.len(),
3049            body
3050        );
3051        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
3052        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3053        let req = sample_stream_event_request();
3054
3055        let mut warned = false;
3056        let err = send_stream_event(
3057            &client,
3058            &Attribution::ProjectOnly {
3059                project_id: uuid::Uuid::from_u128(13),
3060            },
3061            attribution_force(None),
3062            &req,
3063            &mut warned,
3064        )
3065        .await
3066        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
3067        assert!(
3068            err.to_string().contains("403"),
3069            "propagated error must reflect the status, got: {err}"
3070        );
3071    }
3072
3073    /// I2: a transient 503 from the project-scoped endpoint must propagate as
3074    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
3075    /// existing buffer/retry logic in `run_stream` still handles it. Only one
3076    /// request (to the project endpoint) may be observed.
3077    #[tokio::test]
3078    async fn send_stream_event_does_not_fall_back_on_transient_503() {
3079        let body_503 = "internal error";
3080        let resp_503 = format!(
3081            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3082            body_503.len(),
3083            body_503
3084        );
3085        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
3086        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3087        let req = sample_stream_event_request();
3088        let pid = uuid::Uuid::from_u128(7);
3089
3090        let mut warned = false;
3091        let err = send_stream_event(
3092            &client,
3093            &Attribution::Repo {
3094                repo_id: "11111111-1111-1111-1111-111111111111".into(),
3095                project: Some(pid),
3096            },
3097            attribution_force(None),
3098            &req,
3099            &mut warned,
3100        )
3101        .await
3102        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
3103        assert!(
3104            err.to_string().contains("503"),
3105            "propagated error must reflect the transient status, got: {err}"
3106        );
3107        assert!(
3108            deterministic_client_error_kind(err.as_ref()).is_none(),
3109            "a 503 must not be classified as a deterministic client error"
3110        );
3111
3112        let first = rx
3113            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3114            .expect("no request captured");
3115        assert!(
3116            first.contains(&format!("/projects/{pid}/stream")),
3117            "must hit the project-scoped endpoint, got: {first}"
3118        );
3119
3120        // The mock server only serves ONE response and then drops its
3121        // listener/sender — a stray fallback request would either fail the
3122        // `expect_err` above (if it somehow succeeded) or, if it also failed,
3123        // would still mean a second request was attempted. Confirming the
3124        // channel is immediately disconnected (rather than blocking) proves
3125        // no second request was ever sent.
3126        assert!(
3127            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3128            "no second (fallback) request should have been sent for a transient error"
3129        );
3130    }
3131
3132    /// A 403 must be classified apart from the binding/scoping statuses: since
3133    /// Keycloak it has a second, now more common cause (no `tracevault` grant
3134    /// at all) whose advice is completely different.
3135    #[test]
3136    fn a_403_is_classified_apart_from_the_scoping_statuses() {
3137        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3138        assert_eq!(
3139            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3140            Some(ClientErrorKind::Forbidden)
3141        );
3142        for scoping in [
3143            "Stream failed (400 Bad Request): {}",
3144            "Stream failed (404 Not Found): {}",
3145            "Stream failed (409 Conflict): {}",
3146        ] {
3147            assert_eq!(
3148                deterministic_client_error_kind(err(scoping).as_ref()),
3149                Some(ClientErrorKind::Scoping),
3150                "{scoping}"
3151            );
3152        }
3153        // Unchanged: 401 and transient failures are not deterministic client
3154        // errors and must keep propagating to buffer/retry.
3155        for transient in [
3156            "Stream failed (401 Unauthorized): {}",
3157            "Stream failed (503 Service Unavailable): {}",
3158            "error sending request for url (http://x/stream)",
3159        ] {
3160            assert_eq!(
3161                deterministic_client_error_kind(err(transient).as_ref()),
3162                None,
3163                "{transient}"
3164            );
3165        }
3166    }
3167
3168    /// The 403 error must not tell a user whose account has no `tracevault` grant
3169    /// to switch projects, which cannot possibly help. It names both causes,
3170    /// and — since the CLI no longer re-attributes to another project — must
3171    /// never claim it did.
3172    #[test]
3173    fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3174        let pid = uuid::Uuid::from_u128(7);
3175
3176        let forbidden = refused_error(
3177            pid,
3178            &ClientErrorKind::Forbidden,
3179            AttributionForce::default(),
3180        );
3181        assert!(forbidden.contains("403"), "{forbidden}");
3182        assert!(
3183            forbidden.contains("no `tracevault` grant in Control Plane"),
3184            "must offer the missing-role explanation: {forbidden}"
3185        );
3186        assert!(
3187            forbidden.contains("no `Operator` role on it"),
3188            "must still offer the project explanation: {forbidden}"
3189        );
3190        assert!(
3191            forbidden.starts_with("tracevault: error:"),
3192            "a refusal is an error, not a warning: {forbidden}"
3193        );
3194        assert!(forbidden.contains(&pid.to_string()));
3195
3196        // A 400/404/409 genuinely IS a binding problem, so that wording stays
3197        // unhedged — hedging everything would dilute the useful case.
3198        let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3199        assert!(scoping.contains("project switch"), "{scoping}");
3200        assert!(
3201            !scoping.contains("`tracevault` grant"),
3202            "the scoping case must not mention the `tracevault` grant: {scoping}"
3203        );
3204
3205        for s in [&forbidden, &scoping] {
3206            // A machine-wide default is rebound with `--user`; without the
3207            // hint, `project switch` in a session only shadows it.
3208            assert!(s.contains("--user"), "must name the --user fix: {s}");
3209            assert!(
3210                s.contains("user_project.toml"),
3211                "must name the machine-wide default's file: {s}"
3212            );
3213            assert!(
3214                !s.contains("repo deduction"),
3215                "must never describe re-attribution to another project: {s}"
3216            );
3217            assert!(
3218                !s.contains("Attributing via"),
3219                "must never claim the event was re-attributed: {s}"
3220            );
3221        }
3222    }
3223
3224    /// VIS-305 whole-branch review, Important finding 5: a REFUSED FORCE
3225    /// said nothing about the force. The 403 the force gate returns for "not
3226    /// Operator on the project" or "`explicit` from a `tvk_` key" is
3227    /// indistinguishable from here (see `ClientErrorKind`) from a membership
3228    /// 403, so an operator who asked for `explicit` got a message about
3229    /// membership and realm roles and was never told the force itself was
3230    /// what got refused. Failing closed on trust is right; failing closed
3231    /// silently is the defect. (VIS-316 made the refusal an error rather
3232    /// than a fallback; the missing explanation is orthogonal to that and
3233    /// still has to be given.)
3234    #[test]
3235    fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3236        let pid = uuid::Uuid::from_u128(7);
3237
3238        let explicit = refused_error(
3239            pid,
3240            &ClientErrorKind::Forbidden,
3241            AttributionForce {
3242                env: false,
3243                binding: true,
3244            },
3245        );
3246        assert!(
3247            explicit.contains("FORCE"),
3248            "the refusal of the force itself must be named: {explicit}"
3249        );
3250        assert!(
3251            explicit.contains("Operator"),
3252            "must name the grant forcing requires: {explicit}"
3253        );
3254        assert!(
3255            explicit.contains("Control Plane"),
3256            "must name the identity forcing requires: {explicit}"
3257        );
3258        // `main`'s Forbidden wording is ADDED TO, not replaced: the
3259        // membership causes it already names must survive alongside the
3260        // force clause.
3261        assert!(
3262            explicit.contains("`tracevault` grant")
3263                && explicit.contains("no `Operator` role on it"),
3264            "the membership causes must still be named: {explicit}"
3265        );
3266        // The event is queued, not re-attributed — the force clause must not
3267        // reintroduce the claim VIS-316 removed.
3268        assert!(
3269            !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3270            "must never claim the event was re-attributed: {explicit}"
3271        );
3272
3273        // Same 403, `derived` mode: no force was asked for, so none was
3274        // refused and the clause must not appear. This is the discriminating
3275        // half — without it the test would pass on a message that blamed the
3276        // force unconditionally, which is just a different wrong story.
3277        let derived = refused_error(
3278            pid,
3279            &ClientErrorKind::Forbidden,
3280            AttributionForce::default(),
3281        );
3282        assert!(
3283            !derived.contains("FORCE"),
3284            "a `derived` send never forced anything: {derived}"
3285        );
3286    }
3287
3288    /// The force clause belongs to the 403 the force gate returns, and to
3289    /// nothing else: a 400/404/409 means the project id does not resolve, so
3290    /// the gate never ran. Blaming the force there would be a new wrong
3291    /// explanation of the same family as the one finding 5 reports.
3292    #[test]
3293    fn an_explicit_scoping_failure_does_not_blame_the_force() {
3294        let pid = uuid::Uuid::from_u128(7);
3295        let scoping = refused_error(
3296            pid,
3297            &ClientErrorKind::Scoping,
3298            AttributionForce {
3299                env: true,
3300                binding: true,
3301            },
3302        );
3303        assert!(!scoping.contains("FORCE"), "{scoping}");
3304        assert_eq!(
3305            scoping,
3306            refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3307            "the scoping wording does not depend on the mode"
3308        );
3309    }
3310
3311    /// Copilot on PR #54: the remediation told EVERY forced sender to switch
3312    /// again without `--project-attribution explicit`. That clears a
3313    /// persisted `forced_until` and nothing else — so when the force came
3314    /// from `TRACEVAULT_PROJECT_ATTRIBUTION`, [`attribution_force`] goes on
3315    /// reading the environment, every later send still declares `explicit`,
3316    /// and the advice silently does nothing. On the one code path a confused
3317    /// operator reaches.
3318    ///
3319    /// Each case is driven through `attribution_force` and a REAL exported
3320    /// variable rather than a hand-built struct, so what this pins is the
3321    /// whole path: the value that decides the header is the value the
3322    /// wording is derived from, and the two cannot describe different
3323    /// worlds.
3324    ///
3325    /// Discriminating in both directions — each case asserts the fix that
3326    /// applies AND the absence of the one that doesn't — because a message
3327    /// that simply listed both remediations every time would pass a
3328    /// one-sided test while being the same "advice that may not apply"
3329    /// defect in a longer form.
3330    #[test]
3331    fn the_403_remediation_names_the_force_source_actually_in_effect() {
3332        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3333        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3334        let pid = uuid::Uuid::from_u128(7);
3335        let live = forced_binding(Some(
3336            &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3337        ));
3338        let never_forced = forced_binding(None);
3339
3340        // ENV ONLY. The binding carries no force at all, so "switch again
3341        // without the flag" would change precisely nothing: the next send
3342        // reads the same variable and declares `explicit` again.
3343        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3344        let env_only = refused_error(
3345            pid,
3346            &ClientErrorKind::Forbidden,
3347            attribution_force(Some(&never_forced)),
3348        );
3349        assert!(
3350            env_only.contains("FORCE"),
3351            "an env-sourced force is still a force: {env_only}"
3352        );
3353        assert!(
3354            env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3355            "must name the variable that is doing the forcing: {env_only}"
3356        );
3357        assert!(
3358            !env_only.contains("--project-attribution"),
3359            "must NOT tell the operator to drop a flag that would change \
3360             nothing here — this is the bug: {env_only}"
3361        );
3362
3363        // BINDING ONLY. Now the flag advice is the right one, and naming the
3364        // env var would send the operator hunting for an export that isn't
3365        // set.
3366        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3367        let binding_only = refused_error(
3368            pid,
3369            &ClientErrorKind::Forbidden,
3370            attribution_force(Some(&live)),
3371        );
3372        assert!(
3373            binding_only.contains("--project-attribution"),
3374            "a persisted force IS cleared by switching without the flag: {binding_only}"
3375        );
3376        assert!(
3377            !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3378            "must not send the operator after an unset variable: {binding_only}"
3379        );
3380
3381        // BOTH. Removing either one alone leaves the other forcing, which
3382        // would look exactly like the fix not working — so the message has
3383        // to say both must go.
3384        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3385        let both = refused_error(
3386            pid,
3387            &ClientErrorKind::Forbidden,
3388            attribution_force(Some(&live)),
3389        );
3390        assert!(
3391            both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3392                && both.contains("--project-attribution"),
3393            "both sources are in effect and both must be named: {both}"
3394        );
3395        assert!(
3396            both.contains("BOTH"),
3397            "must say that removing only one is not enough: {both}"
3398        );
3399    }
3400
3401    /// The remediation is built from the same `AttributionForce` the header
3402    /// is, so it can never describe a force the send did not declare: with
3403    /// no source set there is no force clause at all, whatever the wording
3404    /// of the fixes would have been.
3405    #[test]
3406    fn no_force_means_no_remediation_clause() {
3407        let pid = uuid::Uuid::from_u128(7);
3408        let none = refused_error(
3409            pid,
3410            &ClientErrorKind::Forbidden,
3411            AttributionForce::default(),
3412        );
3413        assert!(
3414            !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3415                && !none.contains("--project-attribution"),
3416            "a derived send has no force to remove: {none}"
3417        );
3418    }
3419
3420    // ── VIS-1018: a batch over the request cap is split, never dropped ────────
3421
3422    /// A transcript of `n` lines, each about `line_bytes` long, written to
3423    /// `dir/transcript.jsonl`.
3424    fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
3425        let path = dir.join("transcript.jsonl");
3426        let mut body = String::new();
3427        for i in 0..n {
3428            let line = serde_json::json!({
3429                "type": "user",
3430                "n": i,
3431                "message": {"content": "x".repeat(line_bytes)},
3432            });
3433            body.push_str(&line.to_string());
3434            body.push('\n');
3435        }
3436        fs::write(&path, body).unwrap();
3437        path
3438    }
3439
3440    /// The tool event a hook would build around a transcript batch.
3441    fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
3442        StreamEventRequest {
3443            tool_name: Some("Bash".into()),
3444            tool_use_id: Some("toolu_1".into()),
3445            tool_input: Some(serde_json::json!({"command": "ls"})),
3446            event_uuid: Some(uuid::Uuid::now_v7()),
3447            transcript_lines: Some(lines),
3448            transcript_offset: Some(offset),
3449            ..sample_stream_event_request()
3450        }
3451    }
3452
3453    fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
3454        part.transcript_lines.clone().unwrap_or_default()
3455    }
3456
3457    /// `(chunk_index, line)` for every line of `parts`, as the server derives
3458    /// it: `transcript_offset + index within the request`.
3459    fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
3460        parts
3461            .iter()
3462            .flat_map(|p| {
3463                let offset = p.transcript_offset.unwrap();
3464                part_lines(p)
3465                    .into_iter()
3466                    .enumerate()
3467                    .map(move |(i, l)| (offset + i as i64, l))
3468            })
3469            .collect()
3470    }
3471
3472    /// `n` lines of about `bytes` each.
3473    fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
3474        (0..n)
3475            .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
3476            .collect()
3477    }
3478
3479    #[test]
3480    fn split_leaves_a_request_under_the_cap_unchanged() {
3481        let req = event_with_lines(big_lines(3, 100), 0);
3482
3483        let parts = split_into_parts(req.clone());
3484
3485        assert_eq!(parts.len(), 1);
3486        assert_eq!(
3487            serde_json::to_value(&parts[0]).unwrap(),
3488            serde_json::to_value(&req).unwrap()
3489        );
3490    }
3491
3492    /// The prod loss: a batch over 512 KiB used to go out with
3493    /// `transcript_lines = None` while `.stream_offset` moved past it. Every
3494    /// line must now arrive, in order, in requests that each fit the cap.
3495    #[test]
3496    fn split_carries_every_line_of_a_batch_over_the_cap() {
3497        let dir = tempfile::tempdir().unwrap();
3498        // ~1.5 MiB: three to four requests' worth.
3499        let transcript = write_transcript(dir.path(), 300, 5_000);
3500        let (lines, start, _) =
3501            read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
3502        let req = event_with_lines(lines.clone(), start);
3503        assert!(req.serialized_len() > MAX_REQUEST_BYTES);
3504
3505        let parts = split_into_parts(req.clone());
3506
3507        assert!(parts.len() >= 3, "got {} parts", parts.len());
3508        for part in &parts {
3509            assert!(
3510                part.serialized_len() <= MAX_REQUEST_BYTES,
3511                "part of {} bytes exceeds the cap",
3512                part.serialized_len()
3513            );
3514        }
3515        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3516        assert_eq!(sent, lines, "every line, once, in order");
3517
3518        // The event goes once, last; the parts before it are lines only.
3519        let (event, transcript_parts) = parts.split_last().unwrap();
3520        assert_eq!(event.event_type, StreamEventType::ToolUse);
3521        assert_eq!(event.event_uuid, req.event_uuid);
3522        assert_eq!(event.tool_input, req.tool_input);
3523        for part in transcript_parts {
3524            assert_eq!(part.event_type, StreamEventType::Transcript);
3525            assert!(part.event_uuid.is_none());
3526            assert!(part.tool_input.is_none());
3527            assert!(part.tool_name.is_none());
3528        }
3529        assert!(
3530            !part_lines(event).is_empty(),
3531            "the event keeps the lines that fit beside it"
3532        );
3533    }
3534
3535    /// Every line gets the chunk_index it has unsplit (`batch offset + its
3536    /// index in the batch`), so the server stores the same rows as for one
3537    /// request.
3538    #[test]
3539    fn split_keeps_each_lines_unsplit_chunk_index() {
3540        let lines = big_lines(300, 5_000);
3541        let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
3542
3543        let expected: Vec<_> = lines
3544            .into_iter()
3545            .enumerate()
3546            .map(|(i, l)| (1_000 + i as i64, l))
3547            .collect();
3548        assert_eq!(chunk_indexes(&parts), expected);
3549    }
3550
3551    /// Two hooks of one session read from the same offset concurrently and
3552    /// see different lengths, so they cut the batch at different places: a
3553    /// line shared by both must still get one chunk_index, or ON CONFLICT
3554    /// keeps both copies.
3555    #[test]
3556    fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
3557        let lines = big_lines(10, 200_000);
3558        let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
3559        let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
3560
3561        for (index, line) in &short {
3562            let in_long = long.iter().find(|(_, l)| l == line).unwrap();
3563            assert_eq!(in_long.0, *index, "line {line} indexed differently");
3564        }
3565    }
3566
3567    /// A single line over the cap cannot be split: it goes alone rather than
3568    /// being dropped, and the lines around it still travel.
3569    #[test]
3570    fn split_sends_a_single_oversized_line_alone() {
3571        let lines = vec![
3572            serde_json::json!({"n": 0}),
3573            serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
3574            serde_json::json!({"n": 2}),
3575        ];
3576
3577        let parts = split_into_parts(event_with_lines(lines.clone(), 0));
3578
3579        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3580        assert_eq!(sent, lines);
3581        let big = parts
3582            .iter()
3583            .find(|p| part_lines(p).contains(&lines[1]))
3584            .unwrap();
3585        assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
3586        assert_eq!(big.transcript_offset, Some(1));
3587    }
3588
3589    fn far_deadline() -> std::time::Instant {
3590        std::time::Instant::now() + Duration::from_secs(60)
3591    }
3592
3593    fn captured_body(captured: &str) -> StreamEventRequest {
3594        let body = captured.splitn(3, " | ").nth(2).expect("captured body");
3595        serde_json::from_str(body).expect("request body is a StreamEventRequest")
3596    }
3597
3598    /// Every part reaches the server, in order, with its own offset.
3599    #[tokio::test]
3600    async fn deliver_parts_sends_every_part() {
3601        let dir = tempfile::tempdir().unwrap();
3602        let pending_path = dir.path().join("pending.jsonl");
3603        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3604        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3605        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3606
3607        let all_accepted = deliver_parts(
3608            &client,
3609            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3610            AttributionForce::default(),
3611            parts.clone(),
3612            &pending_path,
3613            false,
3614            far_deadline(),
3615            &mut false,
3616        )
3617        .await
3618        .unwrap();
3619
3620        assert!(all_accepted);
3621        for part in &parts {
3622            let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
3623            assert_eq!(got.transcript_offset, part.transcript_offset);
3624            assert_eq!(got.transcript_lines, part.transcript_lines);
3625        }
3626        assert!(drain_pending(&pending_path).unwrap().is_empty());
3627    }
3628
3629    /// A part that fails is queued with the parts after it, in order and
3630    /// unsent, and the delivery reports that not everything was accepted (so
3631    /// a file-based hook keeps `.stream_offset` where it was).
3632    #[tokio::test]
3633    async fn deliver_parts_queues_the_failed_part_and_the_rest() {
3634        let dir = tempfile::tempdir().unwrap();
3635        let pending_path = dir.path().join("pending.jsonl");
3636        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3637        assert!(parts.len() >= 3);
3638        let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
3639        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
3640        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3641
3642        let all_accepted = deliver_parts(
3643            &client,
3644            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3645            AttributionForce::default(),
3646            parts.clone(),
3647            &pending_path,
3648            false,
3649            far_deadline(),
3650            &mut false,
3651        )
3652        .await
3653        .unwrap();
3654
3655        assert!(!all_accepted);
3656        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3657        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3658        assert!(
3659            rx.recv_timeout(Duration::from_millis(300)).is_err(),
3660            "nothing is sent after the first failure"
3661        );
3662        let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
3663            .unwrap()
3664            .iter()
3665            .map(|j| serde_json::from_str(j).unwrap())
3666            .collect();
3667        assert_eq!(queued.len(), parts.len() - 1);
3668        for (q, part) in queued.iter().zip(&parts[1..]) {
3669            assert_eq!(q.transcript_offset, part.transcript_offset);
3670            assert_eq!(q.transcript_lines, part.transcript_lines);
3671        }
3672    }
3673
3674    /// Older events still queued (`send_failed`): the new parts queue behind
3675    /// them without a send.
3676    #[tokio::test]
3677    async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
3678        let dir = tempfile::tempdir().unwrap();
3679        let pending_path = dir.path().join("pending.jsonl");
3680        let parts = split_into_parts(sample_stream_event_request());
3681        let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
3682
3683        let all_accepted = deliver_parts(
3684            &client,
3685            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3686            AttributionForce::default(),
3687            parts,
3688            &pending_path,
3689            true,
3690            far_deadline(),
3691            &mut false,
3692        )
3693        .await
3694        .unwrap();
3695
3696        assert!(!all_accepted);
3697        assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
3698    }
3699
3700    /// Past the delivery budget nothing more is sent: the parts are queued
3701    /// before the agent can kill the hook at its timeout and lose them.
3702    #[tokio::test]
3703    async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
3704        let dir = tempfile::tempdir().unwrap();
3705        let pending_path = dir.path().join("pending.jsonl");
3706        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3707        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3708        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3709
3710        let all_accepted = deliver_parts(
3711            &client,
3712            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3713            AttributionForce::default(),
3714            parts.clone(),
3715            &pending_path,
3716            false,
3717            std::time::Instant::now(),
3718            &mut false,
3719        )
3720        .await
3721        .unwrap();
3722
3723        assert!(!all_accepted);
3724        assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
3725        assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
3726    }
3727}