Skip to main content

tracevault_cli/commands/
stream.rs

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