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 = transcript_template(&req);
870    let transcript_envelope = envelope(&transcript_template);
871
872    // Group the leading lines into `Transcript` parts, then the tail.
873    let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
874    let mut start = 0;
875    while start < tail_start {
876        let mut end = start + 1;
877        let mut used = transcript_envelope + sizes[start];
878        while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
879            used += sizes[end];
880            end += 1;
881        }
882        groups.push(start..end);
883        start = end;
884    }
885    groups.push(tail_start..lines.len());
886
887    let last = groups.len() - 1;
888    let mut lines = lines.into_iter();
889    groups
890        .into_iter()
891        .enumerate()
892        .map(|(n, range)| {
893            let mut part = if n == last {
894                req.clone()
895            } else {
896                transcript_template.clone()
897            };
898            let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
899            part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
900            part.transcript_offset = Some(batch_offset + range.start as i64);
901            part
902        })
903        .collect()
904}
905
906/// A lines-only `Transcript` request with `req`'s session, agent and context
907/// fields but none of its event (type, tool payload, `event_uuid`), which the
908/// server handles as transcript lines only. `req`'s lines are not copied.
909/// Every field is listed, so a new one has to be decided on here.
910pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
911    StreamEventRequest {
912        protocol_version: req.protocol_version,
913        tool: req.tool.clone(),
914        event_type: StreamEventType::Transcript,
915        session_id: req.session_id.clone(),
916        timestamp: req.timestamp,
917        hook_event_name: req.hook_event_name.clone(),
918        tool_name: None,
919        tool_use_id: None,
920        tool_input: None,
921        tool_response: None,
922        tool_is_error: None,
923        event_index: None,
924        event_uuid: None,
925        transcript_lines: None,
926        transcript_offset: req.transcript_offset,
927        model: req.model.clone(),
928        cwd: req.cwd.clone(),
929        final_stats: None,
930        flow_id: req.flow_id.clone(),
931        labels: req.labels.clone(),
932        params: req.params.clone(),
933        billing_mode: req.billing_mode,
934    }
935}
936
937/// Send what the session's subagents (Claude Code: see [`crate::subagents`])
938/// appended to their transcripts since the last hook. Each file goes in its
939/// own `Transcript` request(s) under the parent session, never mixed with
940/// another file's lines or the main transcript's, with `transcript_offset`
941/// counted within that file and split like any batch, so every line keeps one
942/// chunk_index per file.
943///
944/// Delivery is the event's: same budget, same queue, and once a send fails
945/// the remaining files are queued behind it. A file's offset advances only
946/// when all its parts were accepted, as with the main transcript, so a queued
947/// or failed batch is read again (same offsets, same chunk_indexes) next time.
948/// A file whose offset cannot be read is skipped with a warning; it must not
949/// cost the other files their delivery.
950///
951/// A file another hook of the session is sending right now (it holds the
952/// file's lock) is skipped, unless `wait_for_lock` is set: then the lock is
953/// awaited until that instant, and only a holder still busy by then makes the
954/// file skipped, with a warning. Final hooks wait: the holder may have read
955/// before the subagent wrote its last lines, and no hook may come after a
956/// final one to send them.
957#[allow(clippy::too_many_arguments)]
958async fn deliver_subagent_transcripts(
959    client: &crate::api_client::ApiClient,
960    attribution: &Attribution,
961    force: AttributionForce,
962    template: &StreamEventRequest,
963    transcript_path: &Path,
964    session_dir: &Path,
965    pending_path: &Path,
966    mut send_failed: bool,
967    deadline: std::time::Instant,
968    wait_for_lock: Option<std::time::Instant>,
969    warned: &mut bool,
970) -> Result<(), Box<dyn std::error::Error>> {
971    for file in crate::subagents::transcripts(transcript_path) {
972        let offset_path = crate::subagents::offset_path(session_dir, &file);
973        // Held until the offset is written (see `subagents::try_lock`).
974        let lock = loop {
975            match crate::subagents::try_lock(&offset_path) {
976                Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
977                    tokio::time::sleep(std::time::Duration::from_millis(25)).await;
978                }
979                other => break other,
980            }
981        };
982        let _lock = match lock {
983            Ok(Some(lock)) => lock,
984            Ok(None) => {
985                if wait_for_lock.is_some() {
986                    eprintln!(
987                        "tracevault: warning: skipping subagent transcript {}: \
988                         another hook is still sending it",
989                        file.display()
990                    );
991                }
992                continue;
993            }
994            Err(e) => {
995                eprintln!(
996                    "tracevault: warning: skipping subagent transcript {}: cannot lock: {e}",
997                    file.display()
998                );
999                continue;
1000            }
1001        };
1002        let (lines, start, end) = match crate::subagents::read_new_lines(&file, &offset_path) {
1003            Ok(read) => read,
1004            Err(e) => {
1005                eprintln!(
1006                    "tracevault: warning: skipping subagent transcript {}: {e}",
1007                    file.display()
1008                );
1009                continue;
1010            }
1011        };
1012        if end == start {
1013            continue;
1014        }
1015        // Only blank or malformed lines: nothing to send, but move past them.
1016        let mut accepted = true;
1017        if !lines.is_empty() {
1018            let mut req = template.clone();
1019            req.transcript_lines = Some(lines);
1020            req.transcript_offset = Some(start);
1021            accepted = deliver_parts(
1022                client,
1023                attribution,
1024                force,
1025                split_into_parts(req),
1026                pending_path,
1027                send_failed,
1028                deadline,
1029                warned,
1030            )
1031            .await?;
1032            send_failed |= !accepted;
1033        }
1034        if accepted {
1035            crate::subagents::write_offset(&offset_path, end)?;
1036        }
1037    }
1038    Ok(())
1039}
1040
1041/// Choose the transcript source for a stream event. Inline records (from a
1042/// plugin-based agent like OpenCode) win over the file-read result whenever the
1043/// hook event carries them — INCLUDING an empty vec, so an event with no new
1044/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
1045/// instead of resetting it to the file-path's 0.
1046pub fn resolve_transcript_source(
1047    inline_records: Option<Vec<serde_json::Value>>,
1048    prior_offset: i64,
1049    file_result: (Vec<serde_json::Value>, i64, i64),
1050) -> (Vec<serde_json::Value>, i64, i64) {
1051    match inline_records {
1052        Some(records) => {
1053            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
1054            (records, send, next)
1055        }
1056        None => file_result,
1057    }
1058}
1059
1060/// Derive the event-level tool-error flag from inline transcript records.
1061/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
1062/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
1063/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
1064/// record found, or `None` when there is none (non-tool events).
1065pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
1066    lines.iter().find_map(|line| {
1067        let msg = line.get("message")?;
1068        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
1069            Some(
1070                msg.get("isError")
1071                    .and_then(|v| v.as_bool())
1072                    .unwrap_or(false),
1073            )
1074        } else {
1075            None
1076        }
1077    })
1078}
1079
1080/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
1081/// Factored out so the mapping is testable without the network/FS-bound
1082/// `run_stream`.
1083pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
1084    req.tool = Some(agent.tool_name().to_string());
1085    req.protocol_version = agent.protocol_version() as u32;
1086}
1087
1088/// How long a hook may keep starting requests. `init` installs the hooks
1089/// with a 10 s timeout and the agent kills a hook that overruns it, so a
1090/// split batch (or a long pending queue) still unsent after this is queued
1091/// instead: a killed hook would lose whatever it held only in memory. Half
1092/// the timeout leaves room for the request already in flight.
1093const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
1094
1095/// How long past the delivery budget a request already in flight may run
1096/// before it is given up and its part queued (the client's own timeout is
1097/// 60 s, past the hook's). This bounds how long a hook holds a subagent
1098/// file's lock: at most its budget plus this.
1099const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1100
1101/// How long past its own delivery budget a final hook (`Stop`,
1102/// `SubagentStop`) waits for a subagent file another hook is sending. A
1103/// holder started no later than the final hook and releases the lock by its
1104/// budget plus [`IN_FLIGHT_GRACE`], so this outlasts every holder; what is
1105/// read after the budget is queued, not sent, which takes well under the two
1106/// seconds left before the 10 s hook timeout.
1107const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
1108
1109/// Send a hook event's parts in order. From the first failure on (or from the
1110/// start when `send_failed`, i.e. older queued events are still waiting), or
1111/// once `deadline` has passed, a part is appended to the pending queue
1112/// instead, behind whatever is already there. A request still in flight
1113/// [`IN_FLIGHT_GRACE`] past `deadline` counts as failed: the server may have
1114/// stored it, and the queued copy then dedupes on its chunk_indexes and
1115/// `event_uuid`. Returns whether every part was accepted.
1116#[allow(clippy::too_many_arguments)]
1117async fn deliver_parts(
1118    client: &crate::api_client::ApiClient,
1119    attribution: &Attribution,
1120    force: AttributionForce,
1121    parts: Vec<StreamEventRequest>,
1122    pending_path: &Path,
1123    mut send_failed: bool,
1124    deadline: std::time::Instant,
1125    warned: &mut bool,
1126) -> Result<bool, Box<dyn std::error::Error>> {
1127    let mut all_accepted = true;
1128    for part in parts {
1129        send_failed = send_failed || std::time::Instant::now() >= deadline;
1130        if !send_failed {
1131            let send = send_stream_event(client, attribution, force, &part, warned);
1132            match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
1133                Ok(Ok(_)) => continue,
1134                Ok(Err(_)) | Err(_) => send_failed = true,
1135            }
1136        }
1137        all_accepted = false;
1138        append_pending(pending_path, &serde_json::to_string(&part)?)?;
1139    }
1140    Ok(all_accepted)
1141}
1142
1143pub async fn run_stream(
1144    event_type: &str,
1145    agent: crate::agent::Agent,
1146) -> Result<(), Box<dyn std::error::Error>> {
1147    // 1. Read HookEvent from stdin
1148    let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
1149    let mut input = String::new();
1150    io::stdin().read_to_string(&mut input)?;
1151    let mut hook_event = parse_hook_event(&input)?;
1152
1153    // Resolve project_root and session_dir via the shared git-aware resolver.
1154    //
1155    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
1156    // the primary worktree root, so it works correctly from a primary checkout,
1157    // a nested worktree, AND a sibling linked worktree (where the primary
1158    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
1159    // would fall back to hook_cwd itself, fail to load config, and silently
1160    // drop the event).
1161    //
1162    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
1163    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
1164    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
1165    // just below runs BEFORE the config/credentials check and can itself
1166    // `?`-exit early — that remains graceful because `main.rs` catches all
1167    // `Err` from `run_stream` and exits 0 without blocking the tool.
1168    let hook_cwd = Path::new(&hook_event.cwd);
1169    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
1170    if resolved.source == crate::paths::ProjectRootSource::Fallback {
1171        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
1172        // we are about to create a fresh `.tracevault/` at the hook's working
1173        // directory — which is how stray per-subdirectory `.tracevault/` dirs
1174        // appear. Surface it (best-effort; stderr never blocks the hook).
1175        eprintln!(
1176            "tracevault: warning: could not resolve a git project root from {}; \
1177             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
1178             that it runs inside the repository to keep sessions under the repo root.",
1179            hook_cwd.display()
1180        );
1181    }
1182    let project_root = resolved.root;
1183
1184    // 2. Create session dir
1185    fs::create_dir_all(&session_dir)?;
1186
1187    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
1188    // inside whatever `.tracevault/` we just created — including a per-subproject
1189    // one. `tracevault init` writes this for the root dir, but runtime-created
1190    // dirs would otherwise have no .gitignore and leak sessions into commits.
1191    // Best-effort: never fail the hook on this.
1192    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
1193
1194    // Write origin marker so verify-start can disambiguate sessions by worktree.
1195    // Best-effort: never fail the hook on marker errors. Uses the shared
1196    // canonicalizing helper so the value matches what verify-start compares
1197    // against on the read side.
1198    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1199    let _ = fs::write(session_dir.join("origin"), &worktree_top);
1200
1201    // Record where the transcript lives: `tracevault check` counts the
1202    // session's tool calls from it, and finds it only through metadata.json.
1203    // Best-effort, like the origin marker.
1204    let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
1205    // Inline records (OpenCode) reach no transcript file `check` could read,
1206    // so keep their tool calls locally for it. Done here, before the
1207    // `.stream_offset` read below can fail the hook, so a corrupt offset file
1208    // never costs `check` a tool call.
1209    if let Some(records) = &hook_event.transcript_records {
1210        let _ = record_inline_tool_calls(&session_dir, records);
1211    }
1212
1213    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
1214    //    it both orders events and is a stable idempotency key — no shared
1215    //    `.event_counter` file (which raced between concurrent parallel-tool
1216    //    hooks and could collide/drop events).
1217    let event_uuid = uuid::Uuid::now_v7();
1218
1219    // 4. Read new transcript lines
1220    let transcript_path = Path::new(&hook_event.transcript_path);
1221    let offset_path = session_dir.join(".stream_offset");
1222    // transcript_offset carries the batch START byte offset so the server
1223    // derives a stable per-line chunk_index across overlapping/retried reads;
1224    // .stream_offset persists the END (next read position).
1225    // Claude Code's `SubagentStop` hook only sweeps the subagent transcripts
1226    // (see `deliver_subagent_transcripts` below): it is not an event of the
1227    // main conversation, so it neither reads nor advances `.stream_offset`.
1228    let sends_main = event_type != "subagent-stop";
1229    let (transcript_lines, start_offset, new_offset) = if sends_main {
1230        read_new_transcript_lines(transcript_path, &offset_path)?
1231    } else {
1232        (vec![], 0, 0)
1233    };
1234
1235    // Fileless inline path (OpenCode): a plugin-based agent with no single
1236    // tailable transcript supplies records directly on the hook event. When
1237    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
1238    // sends `transcript_records: []`) — they take priority over the file-read
1239    // result. `.stream_offset` is reused as a per-session RECORD counter so
1240    // the server's chunk_index stays stable/monotonic across retries, exactly
1241    // as with the byte-offset path. Treating an empty vec as "no new
1242    // records" rather than "fall back to the file" matters: OpenCode's
1243    // `transcript_path` is always "", so the file-read result is always
1244    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
1245    // offset back to 0 and collide with earlier turns' chunk_index on the
1246    // server.
1247    // Only inline (plugin-based) events override the file-read result, and only
1248    // they need `.stream_offset` re-read as a record counter. File-based agents
1249    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
1250    // the byte-offset values from `read_new_transcript_lines` above.
1251    let is_inline = hook_event.transcript_records.is_some();
1252    let (transcript_lines, start_offset, new_offset) = if is_inline {
1253        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
1254        // `.stream_offset` must NOT silently reset to 0 — that would restart the
1255        // record counter and collide with earlier turns' chunk_index on the
1256        // server (the offset-clobber failure mode). Propagate the error instead;
1257        // `main` treats a hook error as non-fatal (exits 0 without blocking the
1258        // tool call). Negatives are clamped to 0 defensively.
1259        let prior_offset: i64 = if offset_path.exists() {
1260            let content = fs::read_to_string(&offset_path)?;
1261            content
1262                .trim()
1263                .parse::<i64>()
1264                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
1265                .max(0)
1266        } else {
1267            0
1268        };
1269        // `take()` moves the records out (nothing below reads
1270        // `transcript_records` again) — avoids deep-cloning a potentially
1271        // large payload (full bash stdout / file contents) on the hook path.
1272        resolve_transcript_source(
1273            hook_event.transcript_records.take(),
1274            prior_offset,
1275            (transcript_lines, start_offset, new_offset),
1276        )
1277    } else {
1278        (transcript_lines, start_offset, new_offset)
1279    };
1280    // 5. Build StreamEventRequest
1281    let stream_event_type = match event_type {
1282        "notification" => StreamEventType::SessionStart,
1283        "stop" => StreamEventType::SessionEnd,
1284        _ => StreamEventType::ToolUse,
1285    };
1286
1287    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
1288    // events have no tool_use_id, so fall back to a forwarded `toolResult`
1289    // record's `isError` — otherwise a failed OpenCode tool would render as
1290    // successful (the event-level flag file-based agents populate would be None).
1291    let tool_is_error = hook_event
1292        .tool_use_id
1293        .as_deref()
1294        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1295        .or_else(|| inline_tool_is_error(&transcript_lines));
1296
1297    // Load config once, up front, so it can back both the user-level context
1298    // layer resolution below and the repo_id lookup further down — avoids a
1299    // redundant second read of the same file. `try_load` keeps the
1300    // missing/malformed distinction so the required-config error further down
1301    // can report which one it is.
1302    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
1303    // user context" — `resolve_user_context` below falls back to the user-level
1304    // config in that case. A malformed repo config is surfaced as an error
1305    // later (the required-config check), not silently dropped here.
1306    let config = crate::config::TracevaultConfig::try_load(&project_root);
1307    // Repo config's user_context wins when the repo configured it; otherwise
1308    // fall back to the user-level ~/.config/tracevault/config.toml. This is
1309    // what lets a detached session (no checkout) still carry user context.
1310    let repo_uc = config
1311        .as_ref()
1312        .ok()
1313        .and_then(|opt| opt.as_ref())
1314        .and_then(|c| c.user_context.clone());
1315    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1316
1317    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
1318    // global and per-worktree) and extract fields before building the
1319    // request.  Using `effective` means parallel sessions in different linked
1320    // worktrees each stamp their own per-worktree context without
1321    // interfering with each other.
1322    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1323    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1324
1325    let mut req = StreamEventRequest {
1326        protocol_version: 1,
1327        tool: Some("claude-code".to_string()),
1328        event_type: stream_event_type,
1329        session_id: hook_event.session_id.clone(),
1330        timestamp: chrono::Utc::now(),
1331        hook_event_name: Some(hook_event.hook_event_name.clone()),
1332        tool_name: hook_event.tool_name.clone(),
1333        tool_use_id: hook_event.tool_use_id.clone(),
1334        tool_input: hook_event.tool_input.clone(),
1335        tool_response: hook_event.tool_response.clone(),
1336        tool_is_error,
1337        event_index: None,
1338        event_uuid: Some(event_uuid),
1339        transcript_lines: None,
1340        transcript_offset: Some(start_offset),
1341        model: None,
1342        cwd: Some(hook_event.cwd.clone()),
1343        final_stats: None,
1344        flow_id: ctx_flow_id,
1345        labels: ctx_labels,
1346        params: ctx_params,
1347        billing_mode: Some(crate::billing::detect_current(
1348            agent,
1349            hook_cwd,
1350            &hook_event.transcript_path,
1351        )),
1352    };
1353
1354    stamp_agent(&mut req, agent);
1355    // Taken before the lines go in, so they are not copied.
1356    let subagent_template = transcript_template(&req);
1357    if !transcript_lines.is_empty() {
1358        req.transcript_lines = Some(transcript_lines);
1359    }
1360
1361    // 6. Resolve credentials
1362    let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
1363
1364    // 7. Config (loaded above, alongside the user-level context layer
1365    // resolution) no longer directly gates repo_id — a missing config is not
1366    // fatal on its own, since the repo may instead resolve via the
1367    // workspace-mode precedence chain (session binding / subagent worktree
1368    // override) below. A malformed config is still surfaced here — that's
1369    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
1370    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
1371    // below).
1372    if let Err(e) = &config {
1373        return Err(format!("malformed .tracevault/config.toml: {e}").into());
1374    }
1375
1376    // Resolve the effective repo binding (workspace/detached mode). Bound
1377    // mode (a pinned config.toml) still works — it's the lowest-precedence
1378    // tier, wired below via `binding_from_config`, fed from the `config`
1379    // already loaded above (no second read of config.toml on this hot path).
1380    let session = crate::session_state::load(&hook_event.session_id);
1381    let bound = config
1382        .as_ref()
1383        .ok()
1384        .and_then(|opt| opt.as_ref())
1385        .and_then(crate::resolution::binding_from_config);
1386    let user_default = crate::user_default::load();
1387    let mut binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
1388    // The client is built here, not at step 8, because an unbound session may
1389    // need it first: bind it from its checkout's remote, as the SessionStart
1390    // hook does — this covers agents without that hook and a SessionStart
1391    // whose lookup failed (VIS-1048). One lookup per remote per session.
1392    let client = server_url
1393        .as_deref()
1394        .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
1395    if binding.is_none() {
1396        if let Some(client) = &client {
1397            let auto =
1398                crate::auto_bind::bind_session(&hook_event.session_id, hook_cwd, client, deadline)
1399                    .await;
1400            if let Some(notice) = auto.notice {
1401                eprintln!("{notice}");
1402            }
1403            binding = auto.binding;
1404        }
1405    }
1406    // Graceful no-op, exactly like the hook's normal success path. Do NOT
1407    // error: a failing hook would block the tool.
1408    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
1409        let response = HookResponse::allow();
1410        println!("{}", serde_json::to_string(&response)?);
1411        Ok(())
1412    };
1413    // Explicit local project binding (if any) overrides server-side repo
1414    // deduction. Computed BEFORE the attribution gate below, reusing the
1415    // already-loaded session + worktree used just above for the repo-binding
1416    // resolution: a repo-less session is attributable by project alone, so the
1417    // project must be known before deciding whether this event can be sent.
1418    // The full binding (not just its id) is resolved: `attribution_mode`
1419    // reads its `forced_until`, and this is the binding that actually decided
1420    // the target project, so it's the only one whose force is allowed to
1421    // apply (see `attribution_mode`'s doc comment).
1422    let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1423    let capture_pid = capture_binding
1424        .as_ref()
1425        .and_then(crate::resolution::capture_project_id);
1426    // Resolved once per invocation, not per event — the binding is invariant
1427    // across the pending-flush loop and the live send below, while the
1428    // evaluation costs an env read and an RFC3339 parse. `commands::flush`
1429    // resolves it once per queue for the same reason. The whole
1430    // `AttributionForce` travels, not just its mode: a refusal has to name
1431    // the force source it is telling the operator to remove.
1432    let force = attribution_force(capture_binding.as_ref());
1433
1434    // Ship if EITHER a repo or a project resolved; no-op only when neither
1435    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
1436    // session-state file whose repo_id could carry path separators into the
1437    // pending filename — such a binding degrades to project-only inside
1438    // `attribution_for` rather than dropping the event.)
1439    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1440        no_op_allow()?;
1441        return Ok(());
1442    };
1443
1444    // 8. The ApiClient (built above)
1445    let client = client.ok_or("server_url not configured")?;
1446
1447    // 9. Try drain pending queue and send
1448    let pending_path = pending_path_for(&session_dir, &attribution);
1449    let pending_events = drain_pending(&pending_path)?;
1450
1451    let mut send_failed = false;
1452    // Spans the whole invocation (pending-flush loop + live send below) so a
1453    // refused project binding prints its error at most once per invocation,
1454    // not once per buffered event.
1455    let mut warned = false;
1456
1457    // Send pending events first. Past the delivery budget, put the rest back
1458    // unsent (the queue file is already gone), so a hook killed at its timeout
1459    // loses none of them.
1460    for (i, pending_json) in pending_events.iter().enumerate() {
1461        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1462            // Capped like `deliver_parts`: the queue file is already gone, so
1463            // a hook killed at its timeout mid-request would lose every event
1464            // not yet re-queued, and never reach the subagent sweep.
1465            if std::time::Instant::now() >= deadline
1466                || !matches!(
1467                    tokio::time::timeout_at(
1468                        (deadline + IN_FLIGHT_GRACE).into(),
1469                        send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
1470                    )
1471                    .await,
1472                    Ok(Ok(_))
1473                )
1474            {
1475                // Re-queue only the failed event and the ones after it that
1476                // were never attempted, in order. Events before `i` already
1477                // got a server response and must NOT be re-queued here — a
1478                // prior iteration already appended them if IT failed, and if
1479                // it succeeded, re-adding them would deliver them twice on
1480                // the next drain.
1481                for evt in &pending_events[i..] {
1482                    append_pending(&pending_path, evt)?;
1483                }
1484                send_failed = true;
1485                break;
1486            }
1487        }
1488    }
1489
1490    // Send the current event — several requests when its transcript batch
1491    // exceeds the request cap (see `split_into_parts`), never dropping lines.
1492    let all_accepted = if sends_main {
1493        deliver_parts(
1494            &client,
1495            &attribution,
1496            force,
1497            split_into_parts(req),
1498            &pending_path,
1499            send_failed,
1500            deadline,
1501            &mut warned,
1502        )
1503        .await?
1504    } else {
1505        true
1506    };
1507    // 10. Advance .stream_offset once every part is accepted. The inline
1508    // (OpenCode) path CONSUMES its records from the hook event — they are not
1509    // re-readable like a transcript file — so its record counter must advance
1510    // whenever the event is accepted for delivery, INCLUDING when parts were
1511    // queued after a failure. Otherwise the next inline event reuses these
1512    // chunk_indexes and the server drops the overlap via ON CONFLICT. The queued
1513    // parts already carry their `transcript_offset`, so the records keep their
1514    // indices on drain. (File-based agents must NOT advance on failure: their
1515    // next read re-covers these lines from the same start offset, so every line
1516    // gets the same chunk_index again and the server dedupes it — whatever the
1517    // queue meanwhile delivered or lost.)
1518    if sends_main && (all_accepted || is_inline) {
1519        fs::write(&offset_path, new_offset.to_string())?;
1520    }
1521
1522    // 11. Subagent transcripts (Claude Code keeps each subagent's conversation
1523    // out of the main file). Swept on every hook, not only on `SubagentStop`,
1524    // so a long-running or background subagent is sent while it runs, and
1525    // `Stop` reads every file to its end.
1526    if agent == crate::agent::Agent::ClaudeCode {
1527        deliver_subagent_transcripts(
1528            &client,
1529            &attribution,
1530            force,
1531            &subagent_template,
1532            transcript_path,
1533            &session_dir,
1534            &pending_path,
1535            send_failed || !all_accepted,
1536            deadline,
1537            matches!(event_type, "stop" | "subagent-stop").then(|| deadline + FINAL_LOCK_WAIT),
1538            &mut warned,
1539        )
1540        .await?;
1541    }
1542
1543    // 12. Always print HookResponse::allow() to stdout
1544    let response = HookResponse::allow();
1545    println!("{}", serde_json::to_string(&response)?);
1546
1547    Ok(())
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use super::*;
1553    use crate::api_client::AttributionMode;
1554    use crate::config::UserContext;
1555    use crate::context::{Context, EffectiveContext};
1556    use std::collections::BTreeMap;
1557
1558    // ── user layer resolution: disabled config → no user layer ────────────────
1559
1560    #[test]
1561    fn disabled_user_context_resolves_to_none() {
1562        // Default/disabled `user_context` (the `Toggle(false)` variant) must
1563        // resolve to `None`, matching the pre-existing hook behavior of
1564        // stamping without a user layer when it isn't configured.
1565        assert!(UserContext::Toggle(false).resolve().is_none());
1566    }
1567
1568    #[test]
1569    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1570        // With no user layer and no global/worktree context files present,
1571        // `Context::effective` must yield a default (empty) `EffectiveContext`
1572        // — i.e. passing `None` for `user_layer` is behavior-preserving.
1573        let dir = tempfile::tempdir().unwrap();
1574        let effective = Context::effective(dir.path(), None);
1575        assert_eq!(effective, EffectiveContext::default());
1576    }
1577
1578    // ── apply_context: all three fields populated ─────────────────────────────
1579
1580    #[test]
1581    fn apply_context_stamps_all_fields() {
1582        let dir = tempfile::tempdir().unwrap();
1583        let mut params = BTreeMap::new();
1584        params.insert("env".to_string(), "prod".to_string());
1585        params.insert("region".to_string(), "eu-west-1".to_string());
1586
1587        let ctx = EffectiveContext {
1588            flow_id: Some("flow-xyz".to_string()),
1589            labels: vec!["backend".to_string(), "urgent".to_string()],
1590            params,
1591        };
1592
1593        let (flow_id, labels, params_out) = apply_context(ctx);
1594
1595        assert_eq!(flow_id, Some("flow-xyz".to_string()));
1596        assert_eq!(
1597            labels,
1598            Some(vec!["backend".to_string(), "urgent".to_string()])
1599        );
1600        let p = params_out.expect("params should be Some");
1601        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1602        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1603
1604        // Verify the stored context round-trips through save_to → load_from →
1605        // merge_layers → apply_context (stored params are now `Option<String>`).
1606        let written = Context {
1607            flow_id: Some("flow-xyz".to_string()),
1608            labels: vec!["backend".to_string(), "urgent".to_string()],
1609            params: {
1610                let mut m = BTreeMap::new();
1611                m.insert("env".to_string(), Some("prod".to_string()));
1612                m.insert("region".to_string(), Some("eu-west-1".to_string()));
1613                m
1614            },
1615        };
1616        let ctx_path = dir.path().join(".tracevault").join("context.json");
1617        written.save_to(&ctx_path).unwrap();
1618        let loaded = Context::load_from(&ctx_path);
1619        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1620        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1621        assert!(labels2.is_some());
1622        assert!(params2.is_some());
1623    }
1624
1625    // ── apply_context: missing context file → all None ────────────────────────
1626
1627    #[test]
1628    fn apply_context_missing_file_all_none() {
1629        let dir = tempfile::tempdir().unwrap();
1630        let missing_path = dir.path().join(".tracevault").join("context.json");
1631        let ctx = Context::load_from(&missing_path); // no context.json → default
1632        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1633        assert!(flow_id.is_none(), "flow_id should be None");
1634        assert!(labels.is_none(), "labels should be None");
1635        assert!(params.is_none(), "params should be None");
1636    }
1637
1638    // ── apply_context: empty labels vec / empty params map → None ─────────────
1639
1640    #[test]
1641    fn apply_context_empty_collections_are_none() {
1642        let ctx = EffectiveContext {
1643            flow_id: None,
1644            labels: vec![],
1645            params: BTreeMap::new(),
1646        };
1647        let (flow_id, labels, params) = apply_context(ctx);
1648        assert!(flow_id.is_none());
1649        assert!(
1650            labels.is_none(),
1651            "empty labels should be None, not Some([])"
1652        );
1653        assert!(
1654            params.is_none(),
1655            "empty params should be None, not Some({{}})"
1656        );
1657    }
1658
1659    // ── apply_context: flow_id only, collections empty ────────────────────────
1660
1661    #[test]
1662    fn apply_context_flow_id_only() {
1663        let ctx = EffectiveContext {
1664            flow_id: Some("my-flow".to_string()),
1665            labels: vec![],
1666            params: BTreeMap::new(),
1667        };
1668        let (flow_id, labels, params) = apply_context(ctx);
1669        assert_eq!(flow_id, Some("my-flow".to_string()));
1670        assert!(labels.is_none());
1671        assert!(params.is_none());
1672    }
1673
1674    // ── resolve_session_paths tests ───────────────────────────────────────────
1675    //
1676    // These tests verify that `resolve_session_paths` routes through the
1677    // git-aware resolver so that sibling linked worktrees capture events under
1678    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
1679
1680    use crate::test_helpers::{add_worktree, init_git_repo};
1681
1682    /// Primary checkout: project_root resolves to the repo root; session_dir is
1683    /// under `<repo>/.tracevault/sessions/<id>/`.
1684    #[test]
1685    fn resolve_session_paths_primary_checkout() {
1686        let tmp = tempfile::tempdir().unwrap();
1687        let repo = tmp.path().join("repo");
1688        std::fs::create_dir_all(&repo).unwrap();
1689        init_git_repo(&repo);
1690        // Create a .tracevault/ in the primary root to match a real init.
1691        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1692
1693        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1694        let project_root = resolved.root;
1695
1696        assert_eq!(
1697            project_root.canonicalize().unwrap(),
1698            repo.canonicalize().unwrap(),
1699            "primary checkout: project_root must be repo root"
1700        );
1701        assert_eq!(
1702            session_dir.canonicalize().unwrap_or(session_dir.clone()),
1703            repo.join(".tracevault")
1704                .join("sessions")
1705                .join("sess-primary-123"),
1706            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1707        );
1708        // session_dir must be INSIDE the primary repo, not elsewhere.
1709        assert!(
1710            session_dir.starts_with(&repo),
1711            "session_dir must be under the primary repo root"
1712        );
1713    }
1714
1715    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1716    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1717    /// git-aware resolver must return the PRIMARY root.
1718    #[test]
1719    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1720        let tmp = tempfile::tempdir().unwrap();
1721        let repo = tmp.path().join("repo");
1722        // Sibling worktree lives outside the primary repo directory.
1723        let wt = tmp.path().join("sibling-wt");
1724
1725        std::fs::create_dir_all(&repo).unwrap();
1726        init_git_repo(&repo);
1727        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1728        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1729        add_worktree(&repo, &wt);
1730
1731        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1732        let project_root = resolved.root;
1733
1734        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1735        assert_eq!(
1736            project_root.canonicalize().unwrap(),
1737            repo.canonicalize().unwrap(),
1738            "sibling worktree: project_root must be primary repo root (not worktree dir)"
1739        );
1740        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1741        assert!(
1742            session_dir.starts_with(&repo),
1743            "sibling worktree: session_dir must be under the PRIMARY repo root"
1744        );
1745        assert!(
1746            !session_dir.starts_with(&wt),
1747            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1748        );
1749        assert!(
1750            session_dir.ends_with(
1751                std::path::Path::new(".tracevault")
1752                    .join("sessions")
1753                    .join("sess-sibling-456")
1754            ),
1755            "session_dir must end with .tracevault/sessions/<session_id>"
1756        );
1757    }
1758
1759    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1760    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1761    #[test]
1762    fn resolve_session_paths_non_git_fallback() {
1763        let tmp = tempfile::tempdir().unwrap();
1764        // No git repo, no .tracevault/ anywhere.
1765        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1766        let project_root = resolved.root;
1767
1768        assert_eq!(
1769            project_root,
1770            tmp.path(),
1771            "non-git: project_root must fall back to hook_cwd"
1772        );
1773        assert_eq!(
1774            session_dir,
1775            tmp.path()
1776                .join(".tracevault")
1777                .join("sessions")
1778                .join("sess-fallback-789"),
1779            "non-git: session_dir must be relative to the fallback root"
1780        );
1781    }
1782
1783    /// The origin marker written by run_stream contains the worktree toplevel.
1784    /// This test exercises the same `paths::worktree_toplevel` helper the hook
1785    /// uses (can't call run_stream end-to-end without a real server) so the
1786    /// marker content is computed and canonicalized exactly as in production.
1787    #[test]
1788    fn origin_marker_written_in_session_dir() {
1789        let tmp = tempfile::tempdir().unwrap();
1790        let repo = tmp.path().join("repo");
1791        std::fs::create_dir_all(&repo).unwrap();
1792        init_git_repo(&repo);
1793
1794        let session_dir = repo
1795            .join(".tracevault")
1796            .join("sessions")
1797            .join("test-sess-001");
1798        std::fs::create_dir_all(&session_dir).unwrap();
1799
1800        let hook_cwd = &repo;
1801        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1802        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1803
1804        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1805        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1806        assert_eq!(
1807            origin_content.trim(),
1808            expected.as_str(),
1809            "origin marker must contain the canonicalized worktree toplevel"
1810        );
1811    }
1812
1813    fn metadata(session_dir: &Path) -> serde_json::Value {
1814        serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
1815            .unwrap()
1816    }
1817
1818    #[test]
1819    fn record_transcript_path_writes_metadata_for_check() {
1820        let tmp = tempfile::tempdir().unwrap();
1821        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1822        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1823    }
1824
1825    #[test]
1826    fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
1827        let tmp = tempfile::tempdir().unwrap();
1828        std::fs::write(
1829            tmp.path().join("metadata.json"),
1830            r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
1831        )
1832        .unwrap();
1833        record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
1834        let m = metadata(tmp.path());
1835        assert_eq!(m["transcript_path"], "/t/new.jsonl");
1836        assert_eq!(m["model"], "m");
1837        let leftovers = std::fs::read_dir(tmp.path())
1838            .unwrap()
1839            .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
1840            .count();
1841        assert_eq!(leftovers, 0, "the temp file is renamed into place");
1842    }
1843
1844    #[test]
1845    fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
1846        let tmp = tempfile::tempdir().unwrap();
1847        record_transcript_path(tmp.path(), "").unwrap();
1848        assert!(!tmp.path().join("metadata.json").exists());
1849
1850        std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
1851        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1852        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1853    }
1854
1855    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1856
1857    use crate::session_state::{RepoBinding, SessionState};
1858
1859    fn binding(id: &str) -> RepoBinding {
1860        RepoBinding {
1861            repo_id: id.into(),
1862            git_url: None,
1863            remote_id: None,
1864            codebase_name: None,
1865            updated_at: "t".into(),
1866        }
1867    }
1868
1869    /// Workspace mode: no pinned config, but the session is bound (e.g. via
1870    /// `tracevault repo switch`) — the stream event attributes to that repo.
1871    #[test]
1872    fn resolve_stream_binding_uses_session_active_when_unbound() {
1873        let session = SessionState {
1874            active: Some(binding("session-repo")),
1875            subagents: HashMap::new(),
1876            ..Default::default()
1877        };
1878        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1879        assert_eq!(got.unwrap().repo_id, "session-repo");
1880    }
1881
1882    /// Bound-mode regression: an empty session (no `repo switch` ever run)
1883    /// with a bound config.toml still resolves via the config.
1884    #[test]
1885    fn resolve_stream_binding_falls_back_to_bound_config() {
1886        let session = SessionState::default();
1887        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1888        assert_eq!(got.unwrap().repo_id, "bound-repo");
1889    }
1890
1891    /// No session binding and no bound config: nothing resolves, which is
1892    /// exactly what should trigger `run_stream`'s graceful no-op.
1893    #[test]
1894    fn resolve_stream_binding_none_when_nothing_resolves() {
1895        let session = SessionState::default();
1896        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1897        assert!(got.is_none());
1898    }
1899
1900    /// Subagent override precedence: a per-worktree override for the current
1901    /// worktree wins over the session's `active` binding.
1902    #[test]
1903    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1904        let session = SessionState {
1905            active: Some(binding("session-repo")),
1906            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1907            ..Default::default()
1908        };
1909        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1910        assert_eq!(got.unwrap().repo_id, "subagent-repo");
1911    }
1912
1913    /// Workspace mode: no bound config, but a user-level default is set (e.g.
1914    /// via `tracevault repo switch --user`) — the stream event attributes to
1915    /// that repo when nothing more specific resolves.
1916    #[test]
1917    fn resolve_stream_binding_falls_back_to_user_default() {
1918        let session = SessionState::default();
1919        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1920        assert_eq!(got.unwrap().repo_id, "userdef");
1921    }
1922
1923    /// The user-level default is the LOWEST-precedence tier: a bound config
1924    /// still wins over it.
1925    #[test]
1926    fn resolve_stream_binding_prefers_bound_over_user_default() {
1927        let session = SessionState::default();
1928        let got = resolve_stream_binding(
1929            &session,
1930            "/wt/x",
1931            Some(binding("bound")),
1932            Some(binding("userdef")),
1933        );
1934        assert_eq!(got.unwrap().repo_id, "bound");
1935    }
1936
1937    // ── attribution_for: repo-or-project gate ────────────────────────────────
1938
1939    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1940        crate::session_state::RepoBinding {
1941            repo_id: repo_id.into(),
1942            git_url: None,
1943            remote_id: None,
1944            codebase_name: None,
1945            updated_at: String::new(),
1946        }
1947    }
1948
1949    /// The regression this whole change exists for: a session with a project
1950    /// binding and NO repo binding must still ship, repo-less, instead of
1951    /// being dropped by the hook.
1952    #[test]
1953    fn attribution_falls_back_to_project_when_no_repo_binds() {
1954        let pid = uuid::Uuid::new_v4();
1955        assert_eq!(
1956            attribution_for(None, Some(pid)),
1957            Some(Attribution::ProjectOnly { project_id: pid })
1958        );
1959    }
1960
1961    /// Neither binding resolves — the only case that may still no-op.
1962    #[test]
1963    fn attribution_is_none_when_neither_repo_nor_project_binds() {
1964        assert_eq!(attribution_for(None, None), None);
1965    }
1966
1967    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1968    /// server left to deduce the project.
1969    #[test]
1970    fn attribution_uses_repo_with_no_project_overlay() {
1971        let repo = uuid::Uuid::new_v4().to_string();
1972        let b = binding_with(&repo);
1973        assert_eq!(
1974            attribution_for(Some(&b), None),
1975            Some(Attribution::Repo {
1976                repo_id: repo,
1977                project: None
1978            })
1979        );
1980    }
1981
1982    /// Both bound: the project overlays the repo (project-scoped ingest
1983    /// carrying repo_id), unchanged from before.
1984    #[test]
1985    fn attribution_overlays_project_on_repo() {
1986        let repo = uuid::Uuid::new_v4().to_string();
1987        let pid = uuid::Uuid::new_v4();
1988        let b = binding_with(&repo);
1989        assert_eq!(
1990            attribution_for(Some(&b), Some(pid)),
1991            Some(Attribution::Repo {
1992                repo_id: repo,
1993                project: Some(pid)
1994            })
1995        );
1996    }
1997
1998    /// A corrupted repo_id costs the repo attribution, not the trace: it
1999    /// degrades to project-only rather than dropping the event.
2000    #[test]
2001    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
2002        let pid = uuid::Uuid::new_v4();
2003        let b = binding_with("../../escape");
2004        assert_eq!(
2005            attribution_for(Some(&b), Some(pid)),
2006            Some(Attribution::ProjectOnly { project_id: pid })
2007        );
2008    }
2009
2010    /// ...but with no project to fall back to, a corrupt repo_id still drops,
2011    /// so it can never reach the pending filename.
2012    #[test]
2013    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
2014        let b = binding_with("../../escape");
2015        assert_eq!(attribution_for(Some(&b), None), None);
2016    }
2017
2018    // ── pending queue filenames ──────────────────────────────────────────────
2019
2020    /// The repo filename is unchanged, so queues buffered by earlier releases
2021    /// are still found and drained after this upgrade.
2022    #[test]
2023    fn pending_file_name_for_a_repo_is_unchanged() {
2024        let repo = uuid::Uuid::new_v4().to_string();
2025        assert_eq!(
2026            Attribution::Repo {
2027                repo_id: repo.clone(),
2028                project: Some(uuid::Uuid::new_v4())
2029            }
2030            .pending_file_name(),
2031            format!("pending-{repo}.jsonl")
2032        );
2033    }
2034
2035    /// Repo-less queues carry the `project-` infix, which an older CLI reads
2036    /// as a non-UUID repo id and skips (see the doc comment).
2037    #[test]
2038    fn pending_file_name_for_a_project_is_distinct() {
2039        let pid = uuid::Uuid::new_v4();
2040        assert_eq!(
2041            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
2042            format!("pending-project-{pid}.jsonl")
2043        );
2044    }
2045
2046    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
2047
2048    #[test]
2049    fn binding_repo_id_is_valid_accepts_real_uuid() {
2050        assert!(binding_repo_id_is_valid(
2051            "550e8400-e29b-41d4-a716-446655440000"
2052        ));
2053    }
2054
2055    #[test]
2056    fn binding_repo_id_is_valid_rejects_path_traversal() {
2057        assert!(!binding_repo_id_is_valid("../evil"));
2058    }
2059
2060    #[test]
2061    fn binding_repo_id_is_valid_rejects_empty() {
2062        assert!(!binding_repo_id_is_valid(""));
2063    }
2064
2065    #[test]
2066    fn binding_repo_id_is_valid_rejects_non_uuid() {
2067        assert!(!binding_repo_id_is_valid("not-a-uuid"));
2068    }
2069
2070    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
2071
2072    #[test]
2073    fn stamp_agent_sets_tool_and_version() {
2074        use crate::agent::Agent;
2075        let mut req = StreamEventRequest {
2076            protocol_version: 1,
2077            tool: Some("claude-code".to_string()),
2078            event_type: StreamEventType::ToolUse,
2079            session_id: "s".into(),
2080            timestamp: chrono::Utc::now(),
2081            hook_event_name: None,
2082            tool_name: None,
2083            tool_use_id: None,
2084            tool_input: None,
2085            tool_response: None,
2086            tool_is_error: None,
2087            event_index: None,
2088            event_uuid: None,
2089            transcript_lines: None,
2090            transcript_offset: None,
2091            model: None,
2092            cwd: None,
2093            final_stats: None,
2094            flow_id: None,
2095            labels: None,
2096            params: None,
2097            billing_mode: None,
2098        };
2099        stamp_agent(&mut req, Agent::Codex);
2100        assert_eq!(req.tool.as_deref(), Some("codex"));
2101        assert_eq!(req.protocol_version, 2);
2102
2103        stamp_agent(&mut req, Agent::ClaudeCode);
2104        assert_eq!(req.tool.as_deref(), Some("claude-code"));
2105        assert_eq!(req.protocol_version, 1);
2106    }
2107
2108    // ── pending_path_for: per-target offline queue ───────────────────────────
2109
2110    fn repo_attr(repo_id: &str) -> Attribution {
2111        Attribution::Repo {
2112            repo_id: repo_id.into(),
2113            project: None,
2114        }
2115    }
2116
2117    #[test]
2118    fn pending_path_is_repo_scoped() {
2119        let dir = std::path::Path::new("/tmp/sess");
2120        assert_eq!(
2121            pending_path_for(dir, &repo_attr("repo-a")),
2122            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
2123        );
2124        assert_ne!(
2125            pending_path_for(dir, &repo_attr("repo-a")),
2126            pending_path_for(dir, &repo_attr("repo-b")),
2127        );
2128    }
2129
2130    /// A repo-less session must not share a queue file with any repo, so its
2131    /// buffered events can never be flushed to a repo endpoint.
2132    #[test]
2133    fn pending_path_for_a_project_never_collides_with_a_repo() {
2134        let dir = std::path::Path::new("/tmp/sess");
2135        let pid = uuid::Uuid::from_u128(9);
2136        assert_eq!(
2137            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2138            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
2139        );
2140        assert_ne!(
2141            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
2142            pending_path_for(dir, &repo_attr(&pid.to_string())),
2143        );
2144    }
2145
2146    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
2147
2148    #[test]
2149    fn read_new_transcript_lines_empty_path_is_noop() {
2150        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
2151        // An empty path must yield no lines and offset 0, never an error from
2152        // handing `Path::new("")` to exists()/File::open.
2153        let dir = tempfile::tempdir().unwrap();
2154        let offset_path = dir.path().join(".stream_offset");
2155        let (lines, start_offset, end_offset) =
2156            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
2157        assert!(
2158            lines.is_empty(),
2159            "empty path must yield no transcript lines"
2160        );
2161        assert_eq!(start_offset, 0);
2162        assert_eq!(end_offset, 0);
2163    }
2164
2165    // ── read_new_transcript_lines: start_offset is stable across a persisted
2166    //    end_offset, and equals the previous read's end_offset ─────────────────
2167
2168    #[test]
2169    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
2170        let dir = tempfile::tempdir().unwrap();
2171        let transcript_path = dir.path().join("transcript.jsonl");
2172        let offset_path = dir.path().join(".stream_offset");
2173
2174        fs::write(
2175            &transcript_path,
2176            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
2177        )
2178        .unwrap();
2179
2180        let (lines, start_offset, end_offset) =
2181            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2182        assert_eq!(lines.len(), 2);
2183        assert_eq!(start_offset, 0, "first read starts at byte 0");
2184        assert!(end_offset > 0);
2185
2186        fs::write(&offset_path, end_offset.to_string()).unwrap();
2187
2188        let mut f = OpenOptions::new()
2189            .append(true)
2190            .open(&transcript_path)
2191            .unwrap();
2192        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
2193        drop(f);
2194
2195        let (lines2, start_offset2, end_offset2) =
2196            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
2197        assert_eq!(lines2.len(), 1);
2198        assert_eq!(
2199            start_offset2, end_offset,
2200            "second read's start_offset must equal the first read's persisted end_offset"
2201        );
2202        assert!(end_offset2 > start_offset2);
2203    }
2204
2205    // ── capture_project: local-only project resolver ──────────────────────────
2206
2207    /// Holds the env lock and points the config dir (`XDG_CONFIG_HOME` on
2208    /// Linux, `HOME` for macOS's `dirs::config_dir()`) at a tempdir: the last
2209    /// tier reads `user_project.toml` from there, so without isolation this
2210    /// test fails on any machine with a real user default and races tests
2211    /// that write one.
2212    ///
2213    /// `TRACEVAULT_PROJECT` is pinned UNSET for the same reason:
2214    /// `capture_project` reads it (rung 3, above `session.active_project`),
2215    /// and other tests in this same binary SET it. The crate lock only
2216    /// serializes mutators against each other, so a non-locking reader still
2217    /// races them — and `std::env::set_var` concurrent with `std::env::var`
2218    /// is exactly the UB the `unsafe` blocks in `EnvVarGuard` are annotated
2219    /// against. Holding the lock AND declaring the value is what makes the
2220    /// precedence assertions below describe the tiers they name rather than
2221    /// whatever the ambient shell happens to export.
2222    #[tokio::test]
2223    async fn capture_project_precedence_local_only() {
2224        use crate::session_state::{ProjectBinding, SessionState};
2225        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2226        let tmp = tempfile::tempdir().unwrap();
2227        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2228        _guard.set("XDG_CONFIG_HOME", tmp.path());
2229        _guard.set("HOME", tmp.path());
2230        _guard.remove("TRACEVAULT_PROJECT");
2231
2232        let pb = |id: &str| ProjectBinding {
2233            project_id: id.into(),
2234            project_name: "n".into(),
2235            updated_at: "".into(),
2236            forced_until: None,
2237        };
2238        let u = uuid::Uuid::from_u128;
2239        // session active only
2240        let s = SessionState {
2241            active_project: Some(pb(&u(2).to_string())),
2242            ..Default::default()
2243        };
2244        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
2245        // subagent worktree beats session
2246        let mut s = s;
2247        s.subagent_projects
2248            .insert("/wt".into(), pb(&u(1).to_string()));
2249        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
2250        // no worktree match -> session active
2251        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
2252        // empty session, no user_project.toml in the isolated config dir -> None
2253        assert_eq!(capture_project(&SessionState::default(), None), None);
2254        // malformed stored id -> None (defensive)
2255        let bad = SessionState {
2256            active_project: Some(pb("not-a-uuid")),
2257            ..Default::default()
2258        };
2259        assert_eq!(capture_project(&bad, None), None);
2260        // a valid user_project.toml in the isolated config dir is the last tier
2261        let path = crate::user_project_default::default_project_path().unwrap();
2262        assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
2263        crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
2264        assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
2265    }
2266
2267    /// The full binding — not just its id — survives `capture_binding`: this
2268    /// is what lets `attribution_mode` see a session-scoped `forced_until`
2269    /// (Important finding 1 in the VIS-305 Part C review: the old
2270    /// process-global disk read never saw a force written into SESSION
2271    /// state, which is where a plain `project switch --project-attribution
2272    /// explicit` — no `--user` — writes it).
2273    /// ENV ISOLATION: see `capture_project_precedence_local_only` — this
2274    /// test also goes through the capture chain, which reads
2275    /// `TRACEVAULT_PROJECT` at a rung ABOVE the session-active binding it is
2276    /// asserting on.
2277    #[test]
2278    fn capture_binding_preserves_forced_until_from_the_winning_tier() {
2279        use crate::session_state::{ProjectBinding, SessionState};
2280        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2281        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2282        _guard.remove("TRACEVAULT_PROJECT");
2283        let pid = uuid::Uuid::from_u128(2);
2284        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2285        let s = SessionState {
2286            active_project: Some(ProjectBinding {
2287                project_id: pid.to_string(),
2288                project_name: "n".into(),
2289                updated_at: "".into(),
2290                forced_until: Some(future.clone()),
2291            }),
2292            ..Default::default()
2293        };
2294        let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
2295        assert_eq!(got.forced_until, Some(future));
2296    }
2297
2298    /// `_env_lock` serializes this against other tests in the crate that
2299    /// mutate `TRACEVAULT_PROJECT` (see `test_helpers::lock_env_mutation_sync`),
2300    /// including any that call `commands::project::status`, which reads the
2301    /// same var.
2302    #[test]
2303    fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
2304        // A name would need a `list_projects` round trip, and this path runs
2305        // per-event in a short-lived hook process. Same rule already excludes
2306        // `config_default` here.
2307        let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
2308
2309        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2310        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2311
2312        _guard.set("TRACEVAULT_PROJECT", uuid);
2313        let got = env_project_binding().expect("uuid form is honoured");
2314        assert_eq!(got.project_id, uuid);
2315
2316        _guard.set("TRACEVAULT_PROJECT", "my-project");
2317        assert!(
2318            env_project_binding().is_none(),
2319            "a name is ignored on the network-free capture path"
2320        );
2321
2322        _guard.remove("TRACEVAULT_PROJECT");
2323        assert!(env_project_binding().is_none());
2324    }
2325
2326    // ── attribution_mode ───────────────────────────────────────────────────
2327    //
2328    // `attribution_mode` no longer touches disk at all: it takes the WINNING
2329    // binding (as resolved by `capture_project`) as a parameter, so these
2330    // tests only need to isolate `TRACEVAULT_PROJECT_ATTRIBUTION` via the
2331    // crate's env-mutation lock/guard, not `XDG_CONFIG_HOME`.
2332
2333    fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2334        crate::session_state::ProjectBinding {
2335            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2336            project_name: "p".into(),
2337            updated_at: chrono::Utc::now().to_rfc3339(),
2338            forced_until: forced_until.map(str::to_string),
2339        }
2340    }
2341
2342    #[test]
2343    fn env_force_is_explicit_and_needs_no_expiry() {
2344        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2345        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2346        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2347
2348        assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2349    }
2350
2351    #[test]
2352    fn absent_or_unrecognised_env_is_derived() {
2353        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2354        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2355
2356        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2357        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2358
2359        // The CLI does not forward a value it does not recognise: the server
2360        // would 400 it, and failing a hook over a typo'd env var helps
2361        // nobody. The server's strictness is for callers that bypass the
2362        // CLI.
2363        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2364        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2365    }
2366
2367    /// The binding-persisted half of `attribution_mode`: a LIVE `forced_until`
2368    /// on the WINNING binding (no env var involved) must also read as
2369    /// `explicit` — this is what `project switch --project-attribution
2370    /// explicit` ultimately drives, whether that binding lives in session
2371    /// state or the user-level default.
2372    #[test]
2373    fn live_binding_force_is_explicit_without_env() {
2374        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2375        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2376        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2377
2378        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2379        let binding = forced_binding(Some(&future));
2380
2381        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2382    }
2383
2384    /// This is the test that would fail if a lapsed persisted force still
2385    /// made it onto the wire: with no env override, a `forced_until` in the
2386    /// past on the winning binding must make `attribution_mode` — the exact
2387    /// function that supplies the header — report `derived`, not `explicit`.
2388    /// Not sending an `explicit` header IS the fallback to derived
2389    /// attribution.
2390    #[test]
2391    fn lapsed_binding_force_is_derived_without_env() {
2392        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2393        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2394        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2395
2396        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2397        let binding = forced_binding(Some(&past));
2398
2399        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2400    }
2401
2402    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
2403    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
2404    /// read as `derived`, never panic or, worse, read as `explicit`. Pins the
2405    /// fail-safe direction against a future refactor to `.expect(...)`.
2406    #[test]
2407    fn unparseable_forced_until_is_derived() {
2408        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2409        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2410        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2411
2412        let binding = forced_binding(Some("not-a-timestamp"));
2413
2414        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2415    }
2416
2417    /// Env-provided force must be exempt from expiry in fact, not just by
2418    /// coincidence of the OR: pairing it with a binding force that has
2419    /// ALREADY LAPSED still yields `explicit`. If `attribution_mode` were
2420    /// refactored to gate the env branch on any timestamp, this is the test
2421    /// that would catch it — `lapsed_binding_force_is_derived_without_env`
2422    /// alone couldn't, since it never sets the env var.
2423    #[test]
2424    fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2425        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2426        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2427        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2428
2429        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2430        let binding = forced_binding(Some(&past));
2431
2432        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2433    }
2434
2435    /// VIS-305 Part C review, Important finding 1: a SESSION-scoped force
2436    /// (`project switch --project-attribution explicit` WITHOUT `--user`,
2437    /// which is the default whenever a session id is set — i.e. the ordinary
2438    /// case inside every instrumented agent session) must actually reach the
2439    /// wire as `explicit`. The old process-global `attribution_mode` only
2440    /// ever consulted the user-level default store and never saw a force
2441    /// written into session state at all, so this would have silently sent
2442    /// `derived` while `project switch`'s own success message claimed
2443    /// membership was not being checked. Exercised end-to-end through
2444    /// `send_stream_event` and a real captured request header, not just the
2445    /// pure `attribution_mode` function, so a regression anywhere in the
2446    /// plumbing between `capture_project` and the wire is caught.
2447    #[tokio::test]
2448    async fn session_scoped_force_is_honoured_on_the_wire() {
2449        use crate::session_state::{ProjectBinding, SessionState};
2450
2451        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2452        let tmp = tempfile::tempdir().unwrap();
2453        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2454        // No user-level default at all: the force under test lives ONLY in
2455        // session state, so a pass here can't be explained by an ambient or
2456        // accidentally-written user_project.toml.
2457        _guard.set("XDG_CONFIG_HOME", tmp.path());
2458        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2459        // `capture_project` reads `TRACEVAULT_PROJECT` ABOVE the
2460        // session-active tier this test pins the force on; unset it so an
2461        // ambient export can't redirect the capture at another project.
2462        _guard.remove("TRACEVAULT_PROJECT");
2463
2464        let pid = uuid::Uuid::from_u128(321);
2465        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2466        let session = SessionState {
2467            active_project: Some(ProjectBinding {
2468                project_id: pid.to_string(),
2469                project_name: "proj".into(),
2470                updated_at: "".into(),
2471                forced_until: Some(future),
2472            }),
2473            ..Default::default()
2474        };
2475        let capture_binding = capture_binding(&session, None);
2476
2477        let resp = ok_stream_response();
2478        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2479        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2480        let req = sample_stream_event_request();
2481        let mut warned = false;
2482
2483        let got = send_stream_event(
2484            &client,
2485            &Attribution::ProjectOnly { project_id: pid },
2486            attribution_force(capture_binding.as_ref()),
2487            &req,
2488            &mut warned,
2489        )
2490        .await
2491        .expect("send_stream_event must succeed");
2492        assert_eq!(
2493            got.expect("a successful send returns a response").status,
2494            "accepted"
2495        );
2496
2497        let captured = rx
2498            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2499            .expect("no request captured");
2500        assert!(
2501            captured
2502                .to_lowercase()
2503                .contains("x-tracevault-project-attribution: explicit"),
2504            "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2505        );
2506    }
2507
2508    /// VIS-305 Part C review, Important finding 2: a LIVE force sitting on
2509    /// the machine-global user-level default must NOT leak onto a different,
2510    /// higher-precedence project that resolves instead. The old
2511    /// process-global `attribution_mode` couldn't tell the two apart — it
2512    /// declared `explicit` for ANY project as long as SOME force existed
2513    /// anywhere on disk. Here the user-default's force belongs to project A,
2514    /// but `TRACEVAULT_PROJECT` (a higher-precedence local tier) points this
2515    /// capture at project B, which was never forced.
2516    #[test]
2517    fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2518        use crate::session_state::{ProjectBinding, SessionState};
2519
2520        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2521        let tmp = tempfile::tempdir().unwrap();
2522        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2523        _guard.set("XDG_CONFIG_HOME", tmp.path());
2524        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2525
2526        let project_a = uuid::Uuid::from_u128(1);
2527        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2528        crate::user_project_default::save(&ProjectBinding {
2529            project_id: project_a.to_string(),
2530            project_name: "a".into(),
2531            updated_at: chrono::Utc::now().to_rfc3339(),
2532            forced_until: Some(future),
2533        })
2534        .unwrap();
2535
2536        let project_b = uuid::Uuid::from_u128(2);
2537        _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2538
2539        let capture_binding = capture_binding(&SessionState::default(), None);
2540        assert_eq!(
2541            capture_binding.as_ref().map(|b| b.project_id.as_str()),
2542            Some(project_b.to_string()).as_deref(),
2543            "TRACEVAULT_PROJECT must outrank the user-level default"
2544        );
2545
2546        assert_eq!(
2547            attribution_mode(capture_binding.as_ref()),
2548            AttributionMode::Derived,
2549            "a force on the user-default project must not leak onto a DIFFERENT, \
2550             higher-precedence project that never asked to be forced"
2551        );
2552    }
2553
2554    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
2555
2556    use std::io::BufReader;
2557    use std::net::TcpListener;
2558    use std::sync::mpsc;
2559    use std::thread;
2560    use std::time::{Duration, Instant};
2561
2562    /// How long an accept loop waits for a connection that never arrives
2563    /// (e.g. a regression that stops the client from making an expected
2564    /// request) before giving up, so the server thread exits cleanly
2565    /// instead of blocking in `accept()` forever.
2566    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2567
2568    /// Poll a non-blocking `listener` for a connection until one arrives or
2569    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
2570    /// `WouldBlock` accept error) so callers can stop cleanly rather than
2571    /// block forever.
2572    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2573        let deadline = Instant::now() + ACCEPT_DEADLINE;
2574        loop {
2575            match listener.accept() {
2576                Ok((stream, _)) => {
2577                    // The accepted stream's blocking mode isn't guaranteed to
2578                    // be inherited from the (non-blocking) listener across
2579                    // platforms — make it explicitly blocking so the
2580                    // subsequent read/write calls behave as before.
2581                    let _ = stream.set_nonblocking(false);
2582                    return Some(stream);
2583                }
2584                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2585                    if Instant::now() >= deadline {
2586                        return None;
2587                    }
2588                    thread::sleep(Duration::from_millis(20));
2589                }
2590                Err(_) => return None,
2591            }
2592        }
2593    }
2594
2595    /// How long a test waits for the captured request before failing (rather
2596    /// than hanging forever if the client never connects). Mirrors the
2597    /// harness in `tests/stream_event_project_test.rs`.
2598    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2599
2600    /// Read one request's line and headers off `stream`, hand the pair to
2601    /// `tx` as a single string, then write `response` back.
2602    ///
2603    /// Shared by [`spawn_once_capturing_request`] and
2604    /// [`spawn_n_capturing_requests`], which grew this same capture
2605    /// independently and disagreed only on `trim()` vs `trim_end()` for the
2606    /// blank-line terminator (equivalent, since a bare CRLF trims empty
2607    /// either way).
2608    ///
2609    /// Deliberately NOT `test_helpers::read_request`: that one is private to
2610    /// its module and blocks in `accept()`, where these two use
2611    /// `set_nonblocking` plus a deadline.
2612    ///
2613    /// Headers are captured, not just the request line, so a test can assert
2614    /// on `x-tracevault-project-attribution` — without them a regression that
2615    /// hardcoded `"derived"` at a `stream_event_for_project` call site would
2616    /// pass the whole suite, since nothing in-crate ever looked at the header
2617    /// actually sent. They are appended AFTER the request line, leaving
2618    /// `starts_with`/`contains` assertions on the line itself unaffected.
2619    fn capture_request_and_respond(
2620        stream: std::net::TcpStream,
2621        tx: &mpsc::Sender<String>,
2622        response: &str,
2623    ) {
2624        let mut reader = BufReader::new(stream);
2625        let mut captured = String::new();
2626        let _ = reader.read_line(&mut captured);
2627        loop {
2628            let mut header = String::new();
2629            if reader.read_line(&mut header).unwrap_or(0) == 0 {
2630                break;
2631            }
2632            if header.trim().is_empty() {
2633                break;
2634            }
2635            captured.push_str(&header);
2636        }
2637        let _ = tx.send(captured);
2638        let mut stream = reader.into_inner();
2639        let _ = stream.write_all(response.as_bytes());
2640        let _ = stream.flush();
2641    }
2642
2643    /// Spawn a one-shot server that returns `response` (a full HTTP response)
2644    /// to the first request, capturing it via
2645    /// [`capture_request_and_respond`]. Mirrors the harness in
2646    /// `tests/stream_event_project_test.rs` / `tests/resolve_remote_test.rs`.
2647    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2648        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2649        listener.set_nonblocking(true).unwrap();
2650        let addr = listener.local_addr().unwrap();
2651        let (tx, rx) = mpsc::channel();
2652        thread::spawn(move || {
2653            if let Some(stream) = accept_with_deadline(&listener) {
2654                capture_request_and_respond(stream, &tx, response);
2655            }
2656        });
2657        (format!("http://{addr}"), rx)
2658    }
2659
2660    fn ok_stream_response() -> String {
2661        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2662            session_db_id: uuid::Uuid::nil(),
2663            event_db_id: Some(uuid::Uuid::nil()),
2664            status: "accepted".to_string(),
2665        })
2666        .unwrap();
2667        format!(
2668            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2669            body.len(),
2670            body
2671        )
2672    }
2673
2674    fn sample_stream_event_request() -> StreamEventRequest {
2675        StreamEventRequest {
2676            protocol_version: 2,
2677            tool: Some("claude-code".to_string()),
2678            event_type: StreamEventType::ToolUse,
2679            session_id: "sess-1".into(),
2680            timestamp: chrono::Utc::now(),
2681            hook_event_name: Some("PostToolUse".into()),
2682            tool_name: None,
2683            tool_use_id: None,
2684            tool_input: None,
2685            tool_response: None,
2686            tool_is_error: None,
2687            event_index: None,
2688            event_uuid: None,
2689            transcript_lines: None,
2690            transcript_offset: None,
2691            model: None,
2692            cwd: None,
2693            final_stats: None,
2694            flow_id: None,
2695            labels: None,
2696            params: None,
2697            billing_mode: None,
2698        }
2699    }
2700
2701    /// With a `SessionState` whose `active_project` is set, `capture_project`
2702    /// resolves a `capture_pid`, and `send_stream_event` must route to the
2703    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
2704    /// than the repo-scoped one.
2705    #[tokio::test]
2706    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2707        use crate::session_state::{ProjectBinding, SessionState};
2708
2709        // Isolate from any ambient user-level project default so this test's
2710        // `capture_project` call depends only on the SessionState below —
2711        // mirrors the isolation pattern in `commands::project`'s tests.
2712        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2713        let tmp = tempfile::tempdir().unwrap();
2714        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2715        _guard.set("XDG_CONFIG_HOME", tmp.path());
2716        // `capture_project` reads `TRACEVAULT_PROJECT` above the
2717        // session-active tier asserted below — pin it unset. Ditto
2718        // `TRACEVAULT_PROJECT_ATTRIBUTION`, which the `derived` header
2719        // assertion at the end of this test depends on.
2720        _guard.remove("TRACEVAULT_PROJECT");
2721        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2722
2723        let pid = uuid::Uuid::from_u128(99);
2724        let session = SessionState {
2725            active_project: Some(ProjectBinding {
2726                project_id: pid.to_string(),
2727                project_name: "proj".into(),
2728                updated_at: "".into(),
2729                forced_until: None,
2730            }),
2731            ..Default::default()
2732        };
2733        let capture_binding = capture_binding(&session, None);
2734        let capture_pid = capture_binding
2735            .as_ref()
2736            .and_then(crate::resolution::capture_project_id);
2737        assert_eq!(capture_pid, Some(pid));
2738
2739        let resp = ok_stream_response();
2740        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2741        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2742        let req = sample_stream_event_request();
2743
2744        let mut warned = false;
2745        let got = send_stream_event(
2746            &client,
2747            &Attribution::Repo {
2748                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2749                project: capture_pid,
2750            },
2751            attribution_force(capture_binding.as_ref()),
2752            &req,
2753            &mut warned,
2754        )
2755        .await
2756        .expect("send_stream_event must succeed");
2757        assert_eq!(
2758            got.expect("a successful send returns a response").status,
2759            "accepted"
2760        );
2761
2762        let line = rx
2763            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2764            .expect("no request captured");
2765        assert!(
2766            line.starts_with(&format!(
2767                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2768            )),
2769            "an active project binding must route to the project-scoped endpoint, got: {line}"
2770        );
2771        // Covers the `Attribution::Repo { project: Some(_) }` call site of
2772        // `stream_event_for_project` (the `ProjectOnly` call site is covered
2773        // by `session_scoped_force_is_honoured_on_the_wire` and
2774        // `send_stream_event_project_only_omits_repo_id`) — an unforced
2775        // binding must still send the header, declaring `derived`.
2776        assert!(
2777            line.to_lowercase()
2778                .contains("x-tracevault-project-attribution: derived"),
2779            "got: {line}"
2780        );
2781    }
2782
2783    /// With an empty binding (default `SessionState`, no worktree override)
2784    /// and no user-level default present in the test env, `capture_project`
2785    /// resolves `None` and `send_stream_event` must fall back to the
2786    /// repo-scoped endpoint.
2787    #[tokio::test]
2788    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2789        use crate::session_state::SessionState;
2790
2791        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2792        let tmp = tempfile::tempdir().unwrap();
2793        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2794        // No user_project.toml under this isolated config dir, so there is no
2795        // ambient user-level default to leak in — and no `TRACEVAULT_PROJECT`
2796        // either, which `capture_project` would otherwise honour and turn
2797        // this "nothing resolves" case into a project-scoped send.
2798        _guard.set("XDG_CONFIG_HOME", tmp.path());
2799        _guard.remove("TRACEVAULT_PROJECT");
2800
2801        let capture_binding = capture_binding(&SessionState::default(), None);
2802        assert_eq!(capture_binding, None);
2803
2804        let resp = ok_stream_response();
2805        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2806        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2807        let req = sample_stream_event_request();
2808
2809        let mut warned = false;
2810        let got = send_stream_event(
2811            &client,
2812            &Attribution::Repo {
2813                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2814                project: None,
2815            },
2816            attribution_force(capture_binding.as_ref()),
2817            &req,
2818            &mut warned,
2819        )
2820        .await
2821        .expect("send_stream_event must succeed");
2822        assert_eq!(
2823            got.expect("a successful send returns a response").status,
2824            "accepted"
2825        );
2826
2827        let line = rx
2828            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2829            .expect("no request captured");
2830        assert!(
2831            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
2832            "no binding must fall back to the repo-scoped endpoint, got: {line}"
2833        );
2834    }
2835
2836    // ── I1/I2: refused project-scoped send is an error + transient no-fallback ───
2837
2838    /// Spawn a server that replies to up to `responses.len()` sequential
2839    /// connections with the given full HTTP responses, in order, capturing
2840    /// each request (line + headers, via [`capture_request_and_respond`])
2841    /// over the channel. The listening socket itself is dropped (closing it)
2842    /// once all responses have been served, so any further connection attempt
2843    /// fails fast (connection refused) rather than hanging for the client's
2844    /// request timeout — this lets a test assert "no further request was
2845    /// sent" cheaply.
2846    fn spawn_n_capturing_requests(
2847        responses: Vec<&'static str>,
2848    ) -> (String, mpsc::Receiver<String>) {
2849        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2850        listener.set_nonblocking(true).unwrap();
2851        let addr = listener.local_addr().unwrap();
2852        let (tx, rx) = mpsc::channel();
2853        thread::spawn(move || {
2854            for response in responses {
2855                // If a regression stops the client from making this request
2856                // (e.g. the expected Nth call never happens), don't block
2857                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
2858                // and let the thread end so the test process can't hang.
2859                let Some(stream) = accept_with_deadline(&listener) else {
2860                    break;
2861                };
2862                capture_request_and_respond(stream, &tx, response);
2863            }
2864            // `listener` (and `tx`) drop here, closing the socket and the
2865            // channel — a stray extra request gets ECONNREFUSED immediately
2866            // instead of hanging, and a stray extra `rx.recv` returns
2867            // Disconnected immediately instead of blocking.
2868        });
2869        (format!("http://{addr}"), rx)
2870    }
2871
2872    /// I1: a deterministic 400 ("is not a member of project ...") from the
2873    /// project-scoped endpoint must be an error, not a silent second send to
2874    /// the repo-scoped endpoint. TWO responses (400 then 200) are staged so
2875    /// the "no second request" check is non-vacuous — see the comment in
2876    /// `send_stream_event_project_only_drops_on_scoping_4xx` for why a single
2877    /// staged response would make that assertion pass vacuously.
2878    #[tokio::test]
2879    async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
2880        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
2881        let resp_400 = format!(
2882            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2883            body_400.len(),
2884            body_400
2885        );
2886        let resp_200 = ok_stream_response();
2887
2888        let (base, rx) = spawn_n_capturing_requests(vec![
2889            Box::leak(resp_400.into_boxed_str()),
2890            Box::leak(resp_200.into_boxed_str()),
2891        ]);
2892        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2893        let req = sample_stream_event_request();
2894        let pid = uuid::Uuid::from_u128(42);
2895
2896        let mut warned = false;
2897        let err = send_stream_event(
2898            &client,
2899            &Attribution::Repo {
2900                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2901                project: Some(pid),
2902            },
2903            attribution_force(None),
2904            &req,
2905            &mut warned,
2906        )
2907        .await
2908        .expect_err("a refused declared project must be an error, not a silent fallback");
2909        assert!(
2910            err.to_string().contains("400"),
2911            "propagated error must reflect the status, got: {err}"
2912        );
2913        assert!(
2914            warned,
2915            "the refusal must be printed (gated on `warned`) so it is visible"
2916        );
2917
2918        let first = rx
2919            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2920            .expect("no first request captured");
2921        assert!(
2922            first.contains(&format!("/projects/{pid}/stream")),
2923            "first request must hit the project-scoped endpoint, got: {first}"
2924        );
2925        assert!(
2926            first.contains("repo_id="),
2927            "first request must carry repo_id, got: {first}"
2928        );
2929
2930        assert!(
2931            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2932            "no second (repo-scoped fallback) request must be sent"
2933        );
2934    }
2935
2936    /// A 403 from the project-scoped endpoint must likewise be an error, not a
2937    /// silent second send to the repo-scoped endpoint.
2938    #[tokio::test]
2939    async fn send_stream_event_errors_on_403_without_fallback() {
2940        let body_403 = "forbidden";
2941        let resp_403 = format!(
2942            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2943            body_403.len(),
2944            body_403
2945        );
2946        let resp_200 = ok_stream_response();
2947
2948        let (base, rx) = spawn_n_capturing_requests(vec![
2949            Box::leak(resp_403.into_boxed_str()),
2950            Box::leak(resp_200.into_boxed_str()),
2951        ]);
2952        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2953        let req = sample_stream_event_request();
2954        let pid = uuid::Uuid::from_u128(43);
2955
2956        let mut warned = false;
2957        let err = send_stream_event(
2958            &client,
2959            &Attribution::Repo {
2960                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2961                project: Some(pid),
2962            },
2963            attribution_force(None),
2964            &req,
2965            &mut warned,
2966        )
2967        .await
2968        .expect_err("a refused declared project must be an error, not a silent fallback");
2969        assert!(
2970            err.to_string().contains("403"),
2971            "propagated error must reflect the status, got: {err}"
2972        );
2973        assert!(
2974            warned,
2975            "the refusal must be printed (gated on `warned`) so it is visible"
2976        );
2977
2978        let first = rx
2979            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2980            .expect("no first request captured");
2981        assert!(
2982            first.contains(&format!("/projects/{pid}/stream")),
2983            "first request must hit the project-scoped endpoint, got: {first}"
2984        );
2985        assert!(
2986            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2987            "no second (repo-scoped fallback) request must be sent"
2988        );
2989    }
2990
2991    /// The refusal error must be printed at most once per hook invocation
2992    /// (i.e. per shared `warned` flag), even across multiple calls sharing
2993    /// it — mirroring how the pending-flush loop and the live send share one
2994    /// `warned` for a single invocation.
2995    #[tokio::test]
2996    async fn refused_error_is_printed_once_per_invocation() {
2997        let body_400 = "not a member";
2998        let resp_400 = || {
2999            format!(
3000                "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3001                body_400.len(),
3002                body_400
3003            )
3004        };
3005        let (base, _rx) = spawn_n_capturing_requests(vec![
3006            Box::leak(resp_400().into_boxed_str()),
3007            Box::leak(resp_400().into_boxed_str()),
3008        ]);
3009        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3010        let req = sample_stream_event_request();
3011        let pid = uuid::Uuid::from_u128(44);
3012        let attribution = Attribution::Repo {
3013            repo_id: "11111111-1111-1111-1111-111111111111".into(),
3014            project: Some(pid),
3015        };
3016
3017        let mut warned = false;
3018        assert!(
3019            send_stream_event(
3020                &client,
3021                &attribution,
3022                attribution_force(None),
3023                &req,
3024                &mut warned
3025            )
3026            .await
3027            .is_err(),
3028            "a refused declared project must be an error"
3029        );
3030        assert!(warned, "the flag must be set after the first refusal");
3031
3032        assert!(
3033            send_stream_event(
3034                &client,
3035                &attribution,
3036                attribution_force(None),
3037                &req,
3038                &mut warned
3039            )
3040            .await
3041            .is_err(),
3042            "a second refusal must also be an error"
3043        );
3044        assert!(warned, "the flag stays set across the shared invocation");
3045    }
3046
3047    /// Finding 5's scenario end to end, on the repo-bound path, as VIS-316
3048    /// leaves it: a live persisted force makes this send declare `explicit`,
3049    /// the force gate refuses it with a 403 — and the event is now an ERROR
3050    /// queued for retry, never re-sent to the repo-scoped endpoint where the
3051    /// server would DEDUCE a project that is precisely not the one the
3052    /// operator forced.
3053    ///
3054    /// Pins the fact the refusal clause depends on: the mode that went on
3055    /// the wire really is `explicit`, and it is the same value
3056    /// `refused_error` is handed — the message and the wire cannot disagree.
3057    /// A spare 200 is staged so "no second request" is non-vacuous.
3058    #[tokio::test]
3059    async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
3060        let body_403 = "forbidden";
3061        let resp_403 = format!(
3062            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3063            body_403.len(),
3064            body_403
3065        );
3066        let resp_200 = ok_stream_response();
3067
3068        let (base, rx) = spawn_n_capturing_requests(vec![
3069            Box::leak(resp_403.into_boxed_str()),
3070            Box::leak(resp_200.into_boxed_str()),
3071        ]);
3072        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3073        let req = sample_stream_event_request();
3074        let pid = uuid::Uuid::from_u128(42);
3075
3076        // A live persisted force on the winning binding — no env var needed,
3077        // so this test takes no env lock.
3078        let forced = crate::session_state::ProjectBinding {
3079            project_id: pid.to_string(),
3080            project_name: "forced".into(),
3081            updated_at: "".into(),
3082            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
3083        };
3084
3085        let mut warned = false;
3086        let err = send_stream_event(
3087            &client,
3088            &Attribution::Repo {
3089                repo_id: "11111111-1111-1111-1111-111111111111".into(),
3090                project: Some(pid),
3091            },
3092            attribution_force(Some(&forced)),
3093            &req,
3094            &mut warned,
3095        )
3096        .await
3097        .expect_err("a refused force must be an error, not a silent fallback");
3098        assert!(
3099            err.to_string().contains("403"),
3100            "propagated error must reflect the status, got: {err}"
3101        );
3102        assert!(warned, "the refusal must be printed exactly once");
3103
3104        let first = rx
3105            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3106            .expect("no first request captured");
3107        assert!(
3108            first.contains(&format!("/projects/{pid}/stream")),
3109            "first request must hit the project-scoped endpoint, got: {first}"
3110        );
3111        assert!(
3112            first
3113                .to_lowercase()
3114                .contains("x-tracevault-project-attribution: explicit"),
3115            "the refused send must have DECLARED explicit — this is the mode \
3116             `refused_error` is handed: {first}"
3117        );
3118
3119        assert!(
3120            rx.recv_timeout(Duration::from_millis(500)).is_err(),
3121            "a refused force must NOT be re-attributed via the repo-scoped endpoint"
3122        );
3123    }
3124
3125    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
3126    /// project endpoint with NO `repo_id` query pair. This is the wire shape
3127    /// the server documents as "repo-less (0-repo) projects are supported".
3128    ///
3129    /// Takes the env lock and pins `TRACEVAULT_PROJECT_ATTRIBUTION` unset:
3130    /// this test also asserts the `derived` attribution header, and
3131    /// `attribution_mode` reads that variable even when the binding passed
3132    /// in is `None`.
3133    #[tokio::test]
3134    async fn send_stream_event_project_only_omits_repo_id() {
3135        let _env_lock = crate::test_helpers::lock_env_mutation().await;
3136        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3137        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3138
3139        let resp = ok_stream_response();
3140        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
3141        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3142        let req = sample_stream_event_request();
3143        let pid = uuid::Uuid::from_u128(11);
3144
3145        let mut warned = false;
3146        let got = send_stream_event(
3147            &client,
3148            &Attribution::ProjectOnly { project_id: pid },
3149            attribution_force(None),
3150            &req,
3151            &mut warned,
3152        )
3153        .await
3154        .expect("a repo-less project send must succeed");
3155        assert_eq!(
3156            got.expect("a successful send returns a response").status,
3157            "accepted"
3158        );
3159
3160        let line = rx
3161            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3162            .expect("no request captured");
3163        assert!(
3164            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
3165            "expected a bare project path with no query string, got: {line}"
3166        );
3167        assert!(
3168            line.to_lowercase()
3169                .contains("x-tracevault-project-attribution: derived"),
3170            "with no forced binding, the header must declare `derived`, got: {line}"
3171        );
3172        assert!(
3173            !warned,
3174            "a repo-less send has no fallback and must not warn about one"
3175        );
3176    }
3177
3178    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
3179    /// the queue is keyed by the very project id the server says does not
3180    /// resolve, so a corrected binding writes to a different file and these
3181    /// events would never be retried — they would just accumulate, one per
3182    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
3183    /// trigger a second, impossible request.
3184    #[tokio::test]
3185    async fn send_stream_event_project_only_drops_on_scoping_4xx() {
3186        let body = "no such project";
3187        let resp_404 = format!(
3188            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3189            body.len(),
3190            body
3191        );
3192        // TWO responses are staged although only one request is expected. With
3193        // a single response the helper drops its sender the moment the list is
3194        // exhausted, so the "no second request" assertion below would pass on
3195        // `Disconnected` whether or not a second request happened — a vacuous
3196        // check. Staging a spare keeps the server accepting, so a stray
3197        // request really is captured and really fails the test.
3198        let (base, rx) = spawn_n_capturing_requests(vec![
3199            Box::leak(resp_404.clone().into_boxed_str()),
3200            Box::leak(resp_404.into_boxed_str()),
3201        ]);
3202        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3203        let req = sample_stream_event_request();
3204        let pid = uuid::Uuid::from_u128(12);
3205
3206        let mut warned = false;
3207        let got = send_stream_event(
3208            &client,
3209            &Attribution::ProjectOnly { project_id: pid },
3210            attribution_force(None),
3211            &req,
3212            &mut warned,
3213        )
3214        .await
3215        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
3216        assert!(
3217            got.is_none(),
3218            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
3219        );
3220        assert!(
3221            warned,
3222            "dropping data silently is the failure mode to avoid"
3223        );
3224
3225        let first = rx
3226            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3227            .expect("no request captured");
3228        assert!(
3229            first.contains(&format!("/projects/{pid}/stream")),
3230            "must hit the project-scoped endpoint, got: {first}"
3231        );
3232        assert!(
3233            rx.recv_timeout(Duration::from_millis(500)).is_err(),
3234            "a repo-less send must make exactly one request — no fallback exists"
3235        );
3236    }
3237
3238    /// A 403 is NOT dropped. It can mean the account has no `tracevault` grant,
3239    /// which an administrator can grant — after which the buffered events do
3240    /// deliver. It must propagate so the caller queues them.
3241    #[tokio::test]
3242    async fn send_stream_event_project_only_buffers_on_403() {
3243        let body = "forbidden";
3244        let resp_403 = format!(
3245            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3246            body.len(),
3247            body
3248        );
3249        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
3250        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3251        let req = sample_stream_event_request();
3252
3253        let mut warned = false;
3254        let err = send_stream_event(
3255            &client,
3256            &Attribution::ProjectOnly {
3257                project_id: uuid::Uuid::from_u128(13),
3258            },
3259            attribution_force(None),
3260            &req,
3261            &mut warned,
3262        )
3263        .await
3264        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
3265        assert!(
3266            err.to_string().contains("403"),
3267            "propagated error must reflect the status, got: {err}"
3268        );
3269    }
3270
3271    /// I2: a transient 503 from the project-scoped endpoint must propagate as
3272    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
3273    /// existing buffer/retry logic in `run_stream` still handles it. Only one
3274    /// request (to the project endpoint) may be observed.
3275    #[tokio::test]
3276    async fn send_stream_event_does_not_fall_back_on_transient_503() {
3277        let body_503 = "internal error";
3278        let resp_503 = format!(
3279            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3280            body_503.len(),
3281            body_503
3282        );
3283        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
3284        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3285        let req = sample_stream_event_request();
3286        let pid = uuid::Uuid::from_u128(7);
3287
3288        let mut warned = false;
3289        let err = send_stream_event(
3290            &client,
3291            &Attribution::Repo {
3292                repo_id: "11111111-1111-1111-1111-111111111111".into(),
3293                project: Some(pid),
3294            },
3295            attribution_force(None),
3296            &req,
3297            &mut warned,
3298        )
3299        .await
3300        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
3301        assert!(
3302            err.to_string().contains("503"),
3303            "propagated error must reflect the transient status, got: {err}"
3304        );
3305        assert!(
3306            deterministic_client_error_kind(err.as_ref()).is_none(),
3307            "a 503 must not be classified as a deterministic client error"
3308        );
3309
3310        let first = rx
3311            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
3312            .expect("no request captured");
3313        assert!(
3314            first.contains(&format!("/projects/{pid}/stream")),
3315            "must hit the project-scoped endpoint, got: {first}"
3316        );
3317
3318        // The mock server only serves ONE response and then drops its
3319        // listener/sender — a stray fallback request would either fail the
3320        // `expect_err` above (if it somehow succeeded) or, if it also failed,
3321        // would still mean a second request was attempted. Confirming the
3322        // channel is immediately disconnected (rather than blocking) proves
3323        // no second request was ever sent.
3324        assert!(
3325            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3326            "no second (fallback) request should have been sent for a transient error"
3327        );
3328    }
3329
3330    /// A 403 must be classified apart from the binding/scoping statuses: since
3331    /// Keycloak it has a second, now more common cause (no `tracevault` grant
3332    /// at all) whose advice is completely different.
3333    #[test]
3334    fn a_403_is_classified_apart_from_the_scoping_statuses() {
3335        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3336        assert_eq!(
3337            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3338            Some(ClientErrorKind::Forbidden)
3339        );
3340        for scoping in [
3341            "Stream failed (400 Bad Request): {}",
3342            "Stream failed (404 Not Found): {}",
3343            "Stream failed (409 Conflict): {}",
3344        ] {
3345            assert_eq!(
3346                deterministic_client_error_kind(err(scoping).as_ref()),
3347                Some(ClientErrorKind::Scoping),
3348                "{scoping}"
3349            );
3350        }
3351        // Unchanged: 401 and transient failures are not deterministic client
3352        // errors and must keep propagating to buffer/retry.
3353        for transient in [
3354            "Stream failed (401 Unauthorized): {}",
3355            "Stream failed (503 Service Unavailable): {}",
3356            "error sending request for url (http://x/stream)",
3357        ] {
3358            assert_eq!(
3359                deterministic_client_error_kind(err(transient).as_ref()),
3360                None,
3361                "{transient}"
3362            );
3363        }
3364    }
3365
3366    /// The 403 error must not tell a user whose account has no `tracevault` grant
3367    /// to switch projects, which cannot possibly help. It names both causes,
3368    /// and — since the CLI no longer re-attributes to another project — must
3369    /// never claim it did.
3370    #[test]
3371    fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3372        let pid = uuid::Uuid::from_u128(7);
3373
3374        let forbidden = refused_error(
3375            pid,
3376            &ClientErrorKind::Forbidden,
3377            AttributionForce::default(),
3378        );
3379        assert!(forbidden.contains("403"), "{forbidden}");
3380        assert!(
3381            forbidden.contains("no `tracevault` grant in Control Plane"),
3382            "must offer the missing-role explanation: {forbidden}"
3383        );
3384        assert!(
3385            forbidden.contains("no `Operator` role on it"),
3386            "must still offer the project explanation: {forbidden}"
3387        );
3388        assert!(
3389            forbidden.starts_with("tracevault: error:"),
3390            "a refusal is an error, not a warning: {forbidden}"
3391        );
3392        assert!(forbidden.contains(&pid.to_string()));
3393
3394        // A 400/404/409 genuinely IS a binding problem, so that wording stays
3395        // unhedged — hedging everything would dilute the useful case.
3396        let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3397        assert!(scoping.contains("project switch"), "{scoping}");
3398        assert!(
3399            !scoping.contains("`tracevault` grant"),
3400            "the scoping case must not mention the `tracevault` grant: {scoping}"
3401        );
3402
3403        for s in [&forbidden, &scoping] {
3404            // A machine-wide default is rebound with `--user`; without the
3405            // hint, `project switch` in a session only shadows it.
3406            assert!(s.contains("--user"), "must name the --user fix: {s}");
3407            assert!(
3408                s.contains("user_project.toml"),
3409                "must name the machine-wide default's file: {s}"
3410            );
3411            assert!(
3412                !s.contains("repo deduction"),
3413                "must never describe re-attribution to another project: {s}"
3414            );
3415            assert!(
3416                !s.contains("Attributing via"),
3417                "must never claim the event was re-attributed: {s}"
3418            );
3419        }
3420    }
3421
3422    /// VIS-305 whole-branch review, Important finding 5: a REFUSED FORCE
3423    /// said nothing about the force. The 403 the force gate returns for "not
3424    /// Operator on the project" or "`explicit` from a `tvk_` key" is
3425    /// indistinguishable from here (see `ClientErrorKind`) from a membership
3426    /// 403, so an operator who asked for `explicit` got a message about
3427    /// membership and realm roles and was never told the force itself was
3428    /// what got refused. Failing closed on trust is right; failing closed
3429    /// silently is the defect. (VIS-316 made the refusal an error rather
3430    /// than a fallback; the missing explanation is orthogonal to that and
3431    /// still has to be given.)
3432    #[test]
3433    fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3434        let pid = uuid::Uuid::from_u128(7);
3435
3436        let explicit = refused_error(
3437            pid,
3438            &ClientErrorKind::Forbidden,
3439            AttributionForce {
3440                env: false,
3441                binding: true,
3442            },
3443        );
3444        assert!(
3445            explicit.contains("FORCE"),
3446            "the refusal of the force itself must be named: {explicit}"
3447        );
3448        assert!(
3449            explicit.contains("Operator"),
3450            "must name the grant forcing requires: {explicit}"
3451        );
3452        assert!(
3453            explicit.contains("Control Plane"),
3454            "must name the identity forcing requires: {explicit}"
3455        );
3456        // `main`'s Forbidden wording is ADDED TO, not replaced: the
3457        // membership causes it already names must survive alongside the
3458        // force clause.
3459        assert!(
3460            explicit.contains("`tracevault` grant")
3461                && explicit.contains("no `Operator` role on it"),
3462            "the membership causes must still be named: {explicit}"
3463        );
3464        // The event is queued, not re-attributed — the force clause must not
3465        // reintroduce the claim VIS-316 removed.
3466        assert!(
3467            !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3468            "must never claim the event was re-attributed: {explicit}"
3469        );
3470
3471        // Same 403, `derived` mode: no force was asked for, so none was
3472        // refused and the clause must not appear. This is the discriminating
3473        // half — without it the test would pass on a message that blamed the
3474        // force unconditionally, which is just a different wrong story.
3475        let derived = refused_error(
3476            pid,
3477            &ClientErrorKind::Forbidden,
3478            AttributionForce::default(),
3479        );
3480        assert!(
3481            !derived.contains("FORCE"),
3482            "a `derived` send never forced anything: {derived}"
3483        );
3484    }
3485
3486    /// The force clause belongs to the 403 the force gate returns, and to
3487    /// nothing else: a 400/404/409 means the project id does not resolve, so
3488    /// the gate never ran. Blaming the force there would be a new wrong
3489    /// explanation of the same family as the one finding 5 reports.
3490    #[test]
3491    fn an_explicit_scoping_failure_does_not_blame_the_force() {
3492        let pid = uuid::Uuid::from_u128(7);
3493        let scoping = refused_error(
3494            pid,
3495            &ClientErrorKind::Scoping,
3496            AttributionForce {
3497                env: true,
3498                binding: true,
3499            },
3500        );
3501        assert!(!scoping.contains("FORCE"), "{scoping}");
3502        assert_eq!(
3503            scoping,
3504            refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3505            "the scoping wording does not depend on the mode"
3506        );
3507    }
3508
3509    /// Copilot on PR #54: the remediation told EVERY forced sender to switch
3510    /// again without `--project-attribution explicit`. That clears a
3511    /// persisted `forced_until` and nothing else — so when the force came
3512    /// from `TRACEVAULT_PROJECT_ATTRIBUTION`, [`attribution_force`] goes on
3513    /// reading the environment, every later send still declares `explicit`,
3514    /// and the advice silently does nothing. On the one code path a confused
3515    /// operator reaches.
3516    ///
3517    /// Each case is driven through `attribution_force` and a REAL exported
3518    /// variable rather than a hand-built struct, so what this pins is the
3519    /// whole path: the value that decides the header is the value the
3520    /// wording is derived from, and the two cannot describe different
3521    /// worlds.
3522    ///
3523    /// Discriminating in both directions — each case asserts the fix that
3524    /// applies AND the absence of the one that doesn't — because a message
3525    /// that simply listed both remediations every time would pass a
3526    /// one-sided test while being the same "advice that may not apply"
3527    /// defect in a longer form.
3528    #[test]
3529    fn the_403_remediation_names_the_force_source_actually_in_effect() {
3530        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3531        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3532        let pid = uuid::Uuid::from_u128(7);
3533        let live = forced_binding(Some(
3534            &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3535        ));
3536        let never_forced = forced_binding(None);
3537
3538        // ENV ONLY. The binding carries no force at all, so "switch again
3539        // without the flag" would change precisely nothing: the next send
3540        // reads the same variable and declares `explicit` again.
3541        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3542        let env_only = refused_error(
3543            pid,
3544            &ClientErrorKind::Forbidden,
3545            attribution_force(Some(&never_forced)),
3546        );
3547        assert!(
3548            env_only.contains("FORCE"),
3549            "an env-sourced force is still a force: {env_only}"
3550        );
3551        assert!(
3552            env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3553            "must name the variable that is doing the forcing: {env_only}"
3554        );
3555        assert!(
3556            !env_only.contains("--project-attribution"),
3557            "must NOT tell the operator to drop a flag that would change \
3558             nothing here — this is the bug: {env_only}"
3559        );
3560
3561        // BINDING ONLY. Now the flag advice is the right one, and naming the
3562        // env var would send the operator hunting for an export that isn't
3563        // set.
3564        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3565        let binding_only = refused_error(
3566            pid,
3567            &ClientErrorKind::Forbidden,
3568            attribution_force(Some(&live)),
3569        );
3570        assert!(
3571            binding_only.contains("--project-attribution"),
3572            "a persisted force IS cleared by switching without the flag: {binding_only}"
3573        );
3574        assert!(
3575            !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3576            "must not send the operator after an unset variable: {binding_only}"
3577        );
3578
3579        // BOTH. Removing either one alone leaves the other forcing, which
3580        // would look exactly like the fix not working — so the message has
3581        // to say both must go.
3582        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3583        let both = refused_error(
3584            pid,
3585            &ClientErrorKind::Forbidden,
3586            attribution_force(Some(&live)),
3587        );
3588        assert!(
3589            both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3590                && both.contains("--project-attribution"),
3591            "both sources are in effect and both must be named: {both}"
3592        );
3593        assert!(
3594            both.contains("BOTH"),
3595            "must say that removing only one is not enough: {both}"
3596        );
3597    }
3598
3599    /// The remediation is built from the same `AttributionForce` the header
3600    /// is, so it can never describe a force the send did not declare: with
3601    /// no source set there is no force clause at all, whatever the wording
3602    /// of the fixes would have been.
3603    #[test]
3604    fn no_force_means_no_remediation_clause() {
3605        let pid = uuid::Uuid::from_u128(7);
3606        let none = refused_error(
3607            pid,
3608            &ClientErrorKind::Forbidden,
3609            AttributionForce::default(),
3610        );
3611        assert!(
3612            !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3613                && !none.contains("--project-attribution"),
3614            "a derived send has no force to remove: {none}"
3615        );
3616    }
3617
3618    // ── VIS-1018: a batch over the request cap is split, never dropped ────────
3619
3620    /// A transcript of `n` lines, each about `line_bytes` long, written to
3621    /// `dir/transcript.jsonl`.
3622    fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
3623        let path = dir.join("transcript.jsonl");
3624        let mut body = String::new();
3625        for i in 0..n {
3626            let line = serde_json::json!({
3627                "type": "user",
3628                "n": i,
3629                "message": {"content": "x".repeat(line_bytes)},
3630            });
3631            body.push_str(&line.to_string());
3632            body.push('\n');
3633        }
3634        fs::write(&path, body).unwrap();
3635        path
3636    }
3637
3638    /// The tool event a hook would build around a transcript batch.
3639    fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
3640        StreamEventRequest {
3641            tool_name: Some("Bash".into()),
3642            tool_use_id: Some("toolu_1".into()),
3643            tool_input: Some(serde_json::json!({"command": "ls"})),
3644            event_uuid: Some(uuid::Uuid::now_v7()),
3645            transcript_lines: Some(lines),
3646            transcript_offset: Some(offset),
3647            ..sample_stream_event_request()
3648        }
3649    }
3650
3651    fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
3652        part.transcript_lines.clone().unwrap_or_default()
3653    }
3654
3655    /// `(chunk_index, line)` for every line of `parts`, as the server derives
3656    /// it: `transcript_offset + index within the request`.
3657    fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
3658        parts
3659            .iter()
3660            .flat_map(|p| {
3661                let offset = p.transcript_offset.unwrap();
3662                part_lines(p)
3663                    .into_iter()
3664                    .enumerate()
3665                    .map(move |(i, l)| (offset + i as i64, l))
3666            })
3667            .collect()
3668    }
3669
3670    /// `n` lines of about `bytes` each.
3671    fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
3672        (0..n)
3673            .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
3674            .collect()
3675    }
3676
3677    #[test]
3678    fn split_leaves_a_request_under_the_cap_unchanged() {
3679        let req = event_with_lines(big_lines(3, 100), 0);
3680
3681        let parts = split_into_parts(req.clone());
3682
3683        assert_eq!(parts.len(), 1);
3684        assert_eq!(
3685            serde_json::to_value(&parts[0]).unwrap(),
3686            serde_json::to_value(&req).unwrap()
3687        );
3688    }
3689
3690    /// The prod loss: a batch over 512 KiB used to go out with
3691    /// `transcript_lines = None` while `.stream_offset` moved past it. Every
3692    /// line must now arrive, in order, in requests that each fit the cap.
3693    #[test]
3694    fn split_carries_every_line_of_a_batch_over_the_cap() {
3695        let dir = tempfile::tempdir().unwrap();
3696        // ~1.5 MiB: three to four requests' worth.
3697        let transcript = write_transcript(dir.path(), 300, 5_000);
3698        let (lines, start, _) =
3699            read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
3700        let req = event_with_lines(lines.clone(), start);
3701        assert!(req.serialized_len() > MAX_REQUEST_BYTES);
3702
3703        let parts = split_into_parts(req.clone());
3704
3705        assert!(parts.len() >= 3, "got {} parts", parts.len());
3706        for part in &parts {
3707            assert!(
3708                part.serialized_len() <= MAX_REQUEST_BYTES,
3709                "part of {} bytes exceeds the cap",
3710                part.serialized_len()
3711            );
3712        }
3713        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3714        assert_eq!(sent, lines, "every line, once, in order");
3715
3716        // The event goes once, last; the parts before it are lines only.
3717        let (event, transcript_parts) = parts.split_last().unwrap();
3718        assert_eq!(event.event_type, StreamEventType::ToolUse);
3719        assert_eq!(event.event_uuid, req.event_uuid);
3720        assert_eq!(event.tool_input, req.tool_input);
3721        for part in transcript_parts {
3722            assert_eq!(part.event_type, StreamEventType::Transcript);
3723            assert!(part.event_uuid.is_none());
3724            assert!(part.tool_input.is_none());
3725            assert!(part.tool_name.is_none());
3726        }
3727        assert!(
3728            !part_lines(event).is_empty(),
3729            "the event keeps the lines that fit beside it"
3730        );
3731    }
3732
3733    /// Every line gets the chunk_index it has unsplit (`batch offset + its
3734    /// index in the batch`), so the server stores the same rows as for one
3735    /// request.
3736    #[test]
3737    fn split_keeps_each_lines_unsplit_chunk_index() {
3738        let lines = big_lines(300, 5_000);
3739        let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));
3740
3741        let expected: Vec<_> = lines
3742            .into_iter()
3743            .enumerate()
3744            .map(|(i, l)| (1_000 + i as i64, l))
3745            .collect();
3746        assert_eq!(chunk_indexes(&parts), expected);
3747    }
3748
3749    /// Two hooks of one session read from the same offset concurrently and
3750    /// see different lengths, so they cut the batch at different places: a
3751    /// line shared by both must still get one chunk_index, or ON CONFLICT
3752    /// keeps both copies.
3753    #[test]
3754    fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
3755        let lines = big_lines(10, 200_000);
3756        let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
3757        let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));
3758
3759        for (index, line) in &short {
3760            let in_long = long.iter().find(|(_, l)| l == line).unwrap();
3761            assert_eq!(in_long.0, *index, "line {line} indexed differently");
3762        }
3763    }
3764
3765    /// A single line over the cap cannot be split: it goes alone rather than
3766    /// being dropped, and the lines around it still travel.
3767    #[test]
3768    fn split_sends_a_single_oversized_line_alone() {
3769        let lines = vec![
3770            serde_json::json!({"n": 0}),
3771            serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
3772            serde_json::json!({"n": 2}),
3773        ];
3774
3775        let parts = split_into_parts(event_with_lines(lines.clone(), 0));
3776
3777        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
3778        assert_eq!(sent, lines);
3779        let big = parts
3780            .iter()
3781            .find(|p| part_lines(p).contains(&lines[1]))
3782            .unwrap();
3783        assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
3784        assert_eq!(big.transcript_offset, Some(1));
3785    }
3786
3787    fn far_deadline() -> std::time::Instant {
3788        std::time::Instant::now() + Duration::from_secs(60)
3789    }
3790
3791    fn captured_body(captured: &str) -> StreamEventRequest {
3792        let body = captured.splitn(3, " | ").nth(2).expect("captured body");
3793        serde_json::from_str(body).expect("request body is a StreamEventRequest")
3794    }
3795
3796    /// Every part reaches the server, in order, with its own offset.
3797    #[tokio::test]
3798    async fn deliver_parts_sends_every_part() {
3799        let dir = tempfile::tempdir().unwrap();
3800        let pending_path = dir.path().join("pending.jsonl");
3801        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3802        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3803        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3804
3805        let all_accepted = deliver_parts(
3806            &client,
3807            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3808            AttributionForce::default(),
3809            parts.clone(),
3810            &pending_path,
3811            false,
3812            far_deadline(),
3813            &mut false,
3814        )
3815        .await
3816        .unwrap();
3817
3818        assert!(all_accepted);
3819        for part in &parts {
3820            let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
3821            assert_eq!(got.transcript_offset, part.transcript_offset);
3822            assert_eq!(got.transcript_lines, part.transcript_lines);
3823        }
3824        assert!(drain_pending(&pending_path).unwrap().is_empty());
3825    }
3826
3827    /// A part that fails is queued with the parts after it, in order and
3828    /// unsent, and the delivery reports that not everything was accepted (so
3829    /// a file-based hook keeps `.stream_offset` where it was).
3830    #[tokio::test]
3831    async fn deliver_parts_queues_the_failed_part_and_the_rest() {
3832        let dir = tempfile::tempdir().unwrap();
3833        let pending_path = dir.path().join("pending.jsonl");
3834        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3835        assert!(parts.len() >= 3);
3836        let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
3837        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
3838        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3839
3840        let all_accepted = deliver_parts(
3841            &client,
3842            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3843            AttributionForce::default(),
3844            parts.clone(),
3845            &pending_path,
3846            false,
3847            far_deadline(),
3848            &mut false,
3849        )
3850        .await
3851        .unwrap();
3852
3853        assert!(!all_accepted);
3854        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3855        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
3856        assert!(
3857            rx.recv_timeout(Duration::from_millis(300)).is_err(),
3858            "nothing is sent after the first failure"
3859        );
3860        let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
3861            .unwrap()
3862            .iter()
3863            .map(|j| serde_json::from_str(j).unwrap())
3864            .collect();
3865        assert_eq!(queued.len(), parts.len() - 1);
3866        for (q, part) in queued.iter().zip(&parts[1..]) {
3867            assert_eq!(q.transcript_offset, part.transcript_offset);
3868            assert_eq!(q.transcript_lines, part.transcript_lines);
3869        }
3870    }
3871
3872    /// Older events still queued (`send_failed`): the new parts queue behind
3873    /// them without a send.
3874    #[tokio::test]
3875    async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
3876        let dir = tempfile::tempdir().unwrap();
3877        let pending_path = dir.path().join("pending.jsonl");
3878        let parts = split_into_parts(sample_stream_event_request());
3879        let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));
3880
3881        let all_accepted = deliver_parts(
3882            &client,
3883            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3884            AttributionForce::default(),
3885            parts,
3886            &pending_path,
3887            true,
3888            far_deadline(),
3889            &mut false,
3890        )
3891        .await
3892        .unwrap();
3893
3894        assert!(!all_accepted);
3895        assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
3896    }
3897
3898    /// Past the delivery budget nothing more is sent: the parts are queued
3899    /// before the agent can kill the hook at its timeout and lose them.
3900    #[tokio::test]
3901    async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
3902        let dir = tempfile::tempdir().unwrap();
3903        let pending_path = dir.path().join("pending.jsonl");
3904        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
3905        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
3906        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3907
3908        let all_accepted = deliver_parts(
3909            &client,
3910            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3911            AttributionForce::default(),
3912            parts.clone(),
3913            &pending_path,
3914            false,
3915            std::time::Instant::now(),
3916            &mut false,
3917        )
3918        .await
3919        .unwrap();
3920
3921        assert!(!all_accepted);
3922        assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
3923        assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
3924    }
3925
3926    /// A request that hangs is given up shortly after the budget and its part
3927    /// queued, rather than held until the client's 60 s timeout: the agent
3928    /// kills the hook first (losing the part), and the hook would keep a
3929    /// subagent file's lock a final hook is waiting for.
3930    #[tokio::test]
3931    async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
3932        let dir = tempfile::tempdir().unwrap();
3933        let pending_path = dir.path().join("pending.jsonl");
3934        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3935        let base = format!("http://{}", listener.local_addr().unwrap());
3936        // Accepts (the kernel backlog does) but never answers.
3937        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
3938        let started = Instant::now();
3939
3940        let all_accepted = deliver_parts(
3941            &client,
3942            &repo_attr(&uuid::Uuid::new_v4().to_string()),
3943            AttributionForce::default(),
3944            vec![event_with_lines(big_lines(1, 10), 0)],
3945            &pending_path,
3946            false,
3947            started + Duration::from_millis(100),
3948            &mut false,
3949        )
3950        .await
3951        .unwrap();
3952
3953        assert!(!all_accepted);
3954        assert!(started.elapsed() < Duration::from_secs(10));
3955        assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
3956        drop(listener);
3957    }
3958
3959    // ── VIS-1078: subagent transcripts, one file per request ─────────────────
3960
3961    const PARENT_SESSION: &str = "parent-session";
3962    const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";
3963
3964    /// A Claude Code session laid out as 2.1.x writes it: the main transcript
3965    /// `<dir>/<session>.jsonl` and its subagents' `<dir>/<session>/subagents/`.
3966    /// Returns `(main transcript, subagents dir, tracevault session dir)`.
3967    fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
3968        let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
3969        fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
3970        let subagents = dir.join(PARENT_SESSION).join("subagents");
3971        fs::create_dir_all(&subagents).unwrap();
3972        let session_dir = dir.join("tv-session");
3973        fs::create_dir_all(&session_dir).unwrap();
3974        (main, subagents, session_dir)
3975    }
3976
3977    fn subagent_line(agent: &str, n: usize) -> String {
3978        serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
3979    }
3980
3981    fn append_raw(path: &Path, text: &str) {
3982        let mut f = fs::OpenOptions::new()
3983            .create(true)
3984            .append(true)
3985            .open(path)
3986            .unwrap();
3987        f.write_all(text.as_bytes()).unwrap();
3988    }
3989
3990    fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
3991        let path = subagents.join(format!("agent-{agent}.jsonl"));
3992        for n in ns {
3993            append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
3994        }
3995    }
3996
3997    /// One hook's sweep against a server that answers `responses` and then
3998    /// stops listening, so any request beyond them fails (and is queued).
3999    /// Returns the requests the server received, in order.
4000    async fn sweep(
4001        responses: Vec<String>,
4002        main: &Path,
4003        session_dir: &Path,
4004        pending_path: &Path,
4005    ) -> Vec<StreamEventRequest> {
4006        sweep_waiting(responses, main, session_dir, pending_path, None).await
4007    }
4008
4009    /// [`sweep`] as a final hook, waiting for a busy file's lock until
4010    /// `wait_for_lock`.
4011    async fn sweep_waiting(
4012        responses: Vec<String>,
4013        main: &Path,
4014        session_dir: &Path,
4015        pending_path: &Path,
4016        wait_for_lock: Option<Instant>,
4017    ) -> Vec<StreamEventRequest> {
4018        let expected = responses.len();
4019        let (base, rx) = crate::test_helpers::spawn_seq(responses);
4020        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
4021        let event = StreamEventRequest {
4022            session_id: PARENT_SESSION.into(),
4023            ..sample_stream_event_request()
4024        };
4025        deliver_subagent_transcripts(
4026            &client,
4027            &repo_attr(SUBAGENT_REPO),
4028            AttributionForce::default(),
4029            &transcript_template(&event),
4030            main,
4031            session_dir,
4032            pending_path,
4033            false,
4034            Instant::now() + Duration::from_secs(60),
4035            wait_for_lock,
4036            &mut false,
4037        )
4038        .await
4039        .unwrap();
4040        (0..expected)
4041            .map(|_| {
4042                let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
4043                assert!(
4044                    captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
4045                    "{captured}"
4046                );
4047                let body = captured.splitn(3, " | ").nth(2).unwrap();
4048                serde_json::from_str(body).unwrap()
4049            })
4050            .collect()
4051    }
4052
4053    fn agent_of(line: &serde_json::Value) -> &str {
4054        line["agentId"].as_str().unwrap()
4055    }
4056
4057    /// Every request carries the lines of exactly one subagent, under the
4058    /// parent session, as lines only, and its `transcript_offset` is the byte
4059    /// offset of its first line in that subagent's own file.
4060    fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
4061        for req in reqs {
4062            assert_eq!(req.event_type, StreamEventType::Transcript);
4063            assert_eq!(req.session_id, PARENT_SESSION);
4064            assert!(req.event_uuid.is_none() && req.tool_name.is_none());
4065            let lines = part_lines(req);
4066            let agent = agent_of(&lines[0]);
4067            assert!(
4068                lines.iter().all(|l| agent_of(l) == agent),
4069                "a request mixes subagent files: {lines:?}"
4070            );
4071            let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
4072            let first = file.find(&lines[0].to_string()).unwrap() as i64;
4073            assert_eq!(req.transcript_offset, Some(first));
4074        }
4075    }
4076
4077    #[tokio::test]
4078    async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
4079        let dir = tempfile::tempdir().unwrap();
4080        let (main, subagents, session_dir) = claude_session(dir.path());
4081        let pending = session_dir.join("pending.jsonl");
4082        let ok = ok_stream_response;
4083        let mut all = Vec::new();
4084
4085        // Hook 1: both subagents have started.
4086        append_subagent_lines(&subagents, "a1", 0..2);
4087        append_subagent_lines(&subagents, "b2", 0..1);
4088        fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
4089        let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4090        assert_eq!(reqs.len(), 2);
4091        all.extend(reqs);
4092
4093        // Hook 2: both appended; b2 is caught mid-line.
4094        append_subagent_lines(&subagents, "a1", 2..3);
4095        append_subagent_lines(&subagents, "b2", 1..2);
4096        let partial = subagent_line("b2", 2);
4097        let (head, tail) = partial.split_at(10);
4098        append_raw(&subagents.join("agent-b2.jsonl"), head);
4099        let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
4100        assert_eq!(reqs.len(), 2);
4101        all.extend(reqs);
4102
4103        // Hook 3: b2 finishes the line; a1 is idle.
4104        append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
4105        let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
4106        assert_eq!(reqs.len(), 1);
4107        all.extend(reqs);
4108
4109        // Hook 4: nothing new, nothing sent.
4110        assert!(sweep(vec![], &main, &session_dir, &pending)
4111            .await
4112            .is_empty());
4113        assert!(!pending.exists(), "nothing may have failed and been queued");
4114
4115        assert_one_file_per_request(&subagents, &all);
4116        let mut sent: Vec<(String, u64)> = all
4117            .iter()
4118            .flat_map(part_lines)
4119            .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
4120            .collect();
4121        sent.sort();
4122        let expected: Vec<(String, u64)> = [
4123            ("a1", 0),
4124            ("a1", 1),
4125            ("a1", 2),
4126            ("b2", 0),
4127            ("b2", 1),
4128            ("b2", 2),
4129        ]
4130        .into_iter()
4131        .map(|(a, n)| (a.to_string(), n))
4132        .collect();
4133        assert_eq!(sent, expected, "each line exactly once");
4134    }
4135
4136    #[tokio::test]
4137    async fn a_session_without_subagents_sends_nothing_extra() {
4138        let dir = tempfile::tempdir().unwrap();
4139        let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
4140        fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
4141        let session_dir = dir.path().join("tv-session");
4142        fs::create_dir_all(&session_dir).unwrap();
4143        let pending = session_dir.join("pending.jsonl");
4144
4145        assert!(sweep(vec![], &main, &session_dir, &pending)
4146            .await
4147            .is_empty());
4148        assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
4149    }
4150
4151    /// A failed send queues the file's batch and leaves its offset alone, so
4152    /// the next hook sends the same lines under the same chunk_indexes (the
4153    /// server dedupes the queued copy). Files after the failure are queued
4154    /// too, behind it, rather than sent out of order.
4155    #[tokio::test]
4156    async fn a_failed_subagent_send_is_queued_and_resent_with_the_same_offsets() {
4157        let dir = tempfile::tempdir().unwrap();
4158        let (main, subagents, session_dir) = claude_session(dir.path());
4159        let pending = session_dir.join("pending.jsonl");
4160        append_subagent_lines(&subagents, "a1", 0..2);
4161        append_subagent_lines(&subagents, "b2", 0..1);
4162
4163        let error =
4164            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
4165        let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
4166        assert_eq!(failed.len(), 1);
4167        let queued: Vec<StreamEventRequest> = drain_pending(&pending)
4168            .unwrap()
4169            .iter()
4170            .map(|j| serde_json::from_str(j).unwrap())
4171            .collect();
4172        assert_eq!(queued.len(), 2, "the failed batch and the one behind it");
4173
4174        let resent = sweep(
4175            vec![ok_stream_response(), ok_stream_response()],
4176            &main,
4177            &session_dir,
4178            &pending,
4179        )
4180        .await;
4181        assert_one_file_per_request(&subagents, &resent);
4182        let key = |r: &StreamEventRequest| (r.transcript_offset, part_lines(r));
4183        assert_eq!(
4184            resent.iter().map(key).collect::<Vec<_>>(),
4185            queued.iter().map(key).collect::<Vec<_>>()
4186        );
4187        assert!(sweep(vec![], &main, &session_dir, &pending)
4188            .await
4189            .is_empty());
4190    }
4191
4192    /// A file another hook of the session is sending is left to it: not read,
4193    /// not sent, its offset untouched. The other files still go.
4194    #[tokio::test]
4195    async fn a_subagent_file_another_hook_is_sending_is_skipped() {
4196        let dir = tempfile::tempdir().unwrap();
4197        let (main, subagents, session_dir) = claude_session(dir.path());
4198        let pending = session_dir.join("pending.jsonl");
4199        append_subagent_lines(&subagents, "a1", 0..2);
4200        append_subagent_lines(&subagents, "b2", 0..1);
4201        let a1_offset =
4202            crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4203        let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4204
4205        let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4206        assert_eq!(reqs.len(), 1);
4207        assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
4208        assert!(!a1_offset.exists());
4209
4210        drop(held);
4211        let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
4212        assert_eq!(reqs.len(), 1);
4213        assert_eq!(part_lines(&reqs[0]).len(), 2);
4214        assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
4215    }
4216
4217    /// A final hook does not skip a busy file: it waits for the holder, then
4218    /// sends what the holder left, here every line.
4219    #[tokio::test]
4220    async fn a_final_hook_waits_for_a_busy_subagent_file() {
4221        let dir = tempfile::tempdir().unwrap();
4222        let (main, subagents, session_dir) = claude_session(dir.path());
4223        let pending = session_dir.join("pending.jsonl");
4224        append_subagent_lines(&subagents, "a1", 0..2);
4225        let a1_offset =
4226            crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
4227        let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
4228        let release = thread::spawn(move || {
4229            thread::sleep(Duration::from_millis(300));
4230            drop(held);
4231        });
4232
4233        let reqs = sweep_waiting(
4234            vec![ok_stream_response()],
4235            &main,
4236            &session_dir,
4237            &pending,
4238            Some(Instant::now() + Duration::from_secs(10)),
4239        )
4240        .await;
4241        release.join().unwrap();
4242        assert_eq!(reqs.len(), 1);
4243        assert_eq!(part_lines(&reqs[0]).len(), 2);
4244    }
4245
4246    /// A subagent batch over the request cap is split like any other, within
4247    /// its own file: every part holds that file's lines only and every line
4248    /// keeps the chunk_index it would have had unsplit.
4249    #[tokio::test]
4250    async fn a_large_subagent_batch_is_split_within_its_file() {
4251        let dir = tempfile::tempdir().unwrap();
4252        let (main, subagents, session_dir) = claude_session(dir.path());
4253        let pending = session_dir.join("pending.jsonl");
4254        let big = subagents.join("agent-a1.jsonl");
4255        for n in 0..300 {
4256            let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
4257            append_raw(&big, &format!("{line}\n"));
4258        }
4259        append_subagent_lines(&subagents, "b2", 0..1);
4260
4261        let scratch = dir.path().join("scratch-offset");
4262        let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
4263        let unsplit = StreamEventRequest {
4264            transcript_lines: Some(lines.clone()),
4265            transcript_offset: Some(start),
4266            ..transcript_template(&sample_stream_event_request())
4267        };
4268        let a1_parts = split_into_parts(unsplit).len();
4269        assert!(a1_parts > 1, "the batch must exceed the cap");
4270
4271        let reqs = sweep(
4272            vec![ok_stream_response(); a1_parts + 1],
4273            &main,
4274            &session_dir,
4275            &pending,
4276        )
4277        .await;
4278        assert!(!pending.exists());
4279        let (a1, b2) = reqs.split_at(a1_parts);
4280        assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
4281        assert_eq!(
4282            chunk_indexes(a1),
4283            lines
4284                .into_iter()
4285                .enumerate()
4286                .map(|(i, l)| (start + i as i64, l))
4287                .collect::<Vec<_>>()
4288        );
4289        assert_eq!(b2.len(), 1);
4290        assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
4291        assert_eq!(b2[0].transcript_offset, Some(0));
4292    }
4293}