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