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