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