Skip to main content

tracevault_cli/commands/
stream.rs

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