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