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,
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    let meta_path = session_dir.join("metadata.json");
107    let mut meta = fs::read_to_string(&meta_path)
108        .ok()
109        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
110        .filter(serde_json::Value::is_object)
111        .unwrap_or_else(|| serde_json::json!({}));
112    if meta.get("transcript_path").and_then(|v| v.as_str()) == Some(transcript_path) {
113        return Ok(());
114    }
115    meta["transcript_path"] = serde_json::Value::String(transcript_path.to_string());
116    let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
117    fs::write(&tmp, meta.to_string())?;
118    fs::rename(&tmp, &meta_path).inspect_err(|_| {
119        let _ = fs::remove_file(&tmp);
120    })
121}
122
123/// Fileless agents (OpenCode) have no transcript for `tracevault check` to
124/// count tool calls from: their records ride inline on each hook event. Append
125/// one slim `toolCall` record per tool called in `records` to the session's
126/// `tool_calls.jsonl` and record that file as the session's transcript. Only
127/// the tool name is kept — arguments and outputs (file contents, bash stdout)
128/// would grow the file for nothing. Records with no tool call write nothing.
129pub fn record_inline_tool_calls(
130    session_dir: &Path,
131    records: &[serde_json::Value],
132) -> Result<(), io::Error> {
133    let lines: String = records
134        .iter()
135        .flat_map(crate::transcript::tool_call_names)
136        .map(|name| {
137            let record = serde_json::json!({
138                "type": "message",
139                "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
140            });
141            format!("{record}\n")
142        })
143        .collect();
144    if lines.is_empty() {
145        return Ok(());
146    }
147    let log_path = session_dir.join("tool_calls.jsonl");
148    OpenOptions::new()
149        .create(true)
150        .append(true)
151        .open(&log_path)?
152        .write_all(lines.as_bytes())?;
153    record_transcript_path(session_dir, &log_path.to_string_lossy())
154}
155
156pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
157    let mut file = OpenOptions::new()
158        .create(true)
159        .append(true)
160        .open(pending_path)?;
161    writeln!(file, "{json}")?;
162    Ok(())
163}
164
165pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
166    if !pending_path.exists() {
167        return Ok(vec![]);
168    }
169    let content = fs::read_to_string(pending_path)?;
170    let lines: Vec<String> = content
171        .lines()
172        .filter(|l| !l.trim().is_empty())
173        .map(String::from)
174        .collect();
175    fs::remove_file(pending_path)?;
176    Ok(lines)
177}
178
179/// How a stream event is attributed on the wire, resolved from the local repo
180/// and project bindings before anything is sent.
181///
182/// The rule this type encodes: an event ships when EITHER a repo or a project
183/// resolves. Before this existed the hook required a repo binding and dropped
184/// the event otherwise, which silently discarded every event of a repo-less
185/// session even when its project was bound — despite the server supporting
186/// exactly that shape (`ProjectStreamQuery::repo_id` is `Option<Uuid>`:
187/// "repo-less (0-repo) projects are supported").
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub(crate) enum Attribution {
190    /// A usable repo binding resolved. `project` is the capture-time project
191    /// overlay; when `None` the server deduces the project from the repo.
192    Repo {
193        repo_id: String,
194        project: Option<uuid::Uuid>,
195    },
196    /// No usable repo binding, but a project did — repo-less project-scoped
197    /// ingest.
198    ProjectOnly { project_id: uuid::Uuid },
199}
200
201impl Attribution {
202    /// Offline-queue filename for this attribution. Keyed by whatever
203    /// identifies the target so a mid-session rebind (workspace mode) can
204    /// never flush one target's queued events to another.
205    ///
206    /// The `project-` infix is load-bearing for back-compat: an older CLI's
207    /// `repo_id_from_pending_filename` extracts `project-<uuid>` from this
208    /// name, fails its UUID check, and skips the file — so a downgrade leaves
209    /// these queues alone instead of trying to POST them at a repo endpoint.
210    pub(crate) fn pending_file_name(&self) -> String {
211        use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
212        match self {
213            Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
214            Self::ProjectOnly { project_id } => {
215                format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
216            }
217        }
218    }
219}
220
221/// Pure attribution resolver: fold the repo binding and the capture-time
222/// project into the target this event will be sent to. `None` means neither
223/// resolved and the hook must no-op.
224///
225/// A binding whose `repo_id` is not a UUID degrades to `ProjectOnly` rather
226/// than dropping the event — a corrupted session-state file should cost the
227/// repo attribution, not the whole trace, when a project is available.
228///
229/// `project` here is whatever `capture_project` resolved, and its lowest tier
230/// is the MACHINE-GLOBAL `project switch --user` default — not just
231/// session-scoped bindings. That tier is therefore now a sufficient condition
232/// for an event to ship, where previously it could only redirect an event that
233/// was already shipping because a repo bound. This is deliberate: it is the
234/// only binding a container can establish before the agent session exists and
235/// before the repo is cloned, which is the case this whole path serves.
236/// `resolve_stream_binding` has the same machine-global tier for repos, so the
237/// two sides stay symmetric. Consequence worth knowing: a session started in an
238/// unrelated directory, with no repo and no `.tracevault/`, will attribute to
239/// that default project.
240pub(crate) fn attribution_for(
241    binding: Option<&crate::session_state::RepoBinding>,
242    project: Option<uuid::Uuid>,
243) -> Option<Attribution> {
244    match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
245        Some(b) => Some(Attribution::Repo {
246            repo_id: b.repo_id.clone(),
247            project,
248        }),
249        None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
250    }
251}
252
253/// Offline-queue path for an attribution target.
254fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
255    session_dir.join(attribution.pending_file_name())
256}
257
258/// Resolve the project root and session directory for a stream hook invocation.
259///
260/// This is the pure, testable core of `run_stream`'s path resolution. It uses
261/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
262/// --git-common-dir` first, so it correctly resolves to the **primary**
263/// `.tracevault/` directory from any worktree — including sibling linked
264/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
265///
266/// Returns `(resolved, session_dir)` — the resolved
267/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
268/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
269/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
270pub fn resolve_session_paths(
271    hook_cwd: &Path,
272    session_id: &str,
273) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
274    let resolved = crate::paths::resolve_project_root(hook_cwd);
275    let session_dir = resolved
276        .root
277        .join(".tracevault")
278        .join("sessions")
279        .join(session_id);
280    (resolved, session_dir)
281}
282
283/// A resolved binding is usable for hook attribution only if its repo_id is a
284/// real UUID — guards against a corrupted/edited session-state file injecting
285/// path separators into the pending-<repo_id>.jsonl filename.
286///
287/// `pub(crate)`: also called by `commands::status`, so a binding with a
288/// malformed `repo_id` is never displayed as bound (`Check::ok`) when this
289/// same check means the hook will not actually honor it.
290pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
291    uuid::Uuid::parse_str(repo_id).is_ok()
292}
293
294/// The effective repo binding for a stream event, given the loaded session
295/// state, the event's worktree, and the bound-config fallback. Pure — the
296/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
297pub(crate) fn resolve_stream_binding(
298    session: &crate::session_state::SessionState,
299    worktree: &str,
300    bound: Option<crate::session_state::RepoBinding>,
301    user_default: Option<crate::session_state::RepoBinding>,
302) -> Option<crate::session_state::RepoBinding> {
303    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
304        repo_flag: None,
305        session,
306        worktree_path: Some(worktree),
307        bound,
308        user_default,
309    })
310    .map(|(b, _)| b)
311}
312
313/// `TRACEVAULT_PROJECT` as a binding, UUID form only.
314///
315/// A project NAME would require a `list_projects` round trip, and the capture
316/// path fires per event in a short-lived process — the same reason
317/// `capture_project` already ignores the repo config's `default_project`. The
318/// name form is honoured by the interactive commands, which already have a
319/// client in hand.
320pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
321    let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
322    let raw = raw.trim();
323    let parsed = raw.parse::<uuid::Uuid>().ok()?;
324    Some(crate::session_state::ProjectBinding {
325        project_id: parsed.to_string(),
326        project_name: String::new(),
327        updated_at: String::new(),
328        forced_until: None,
329    })
330}
331
332/// WHICH of the two force sources put a send into `explicit` attribution —
333/// the reason behind [`attribution_mode`]'s verdict, not a second opinion on
334/// it.
335///
336/// The two sources are not interchangeable and, crucially, are not undone
337/// the same way: the env var is process-wide and cleared by unsetting it,
338/// while a persisted force lives on the binding and is cleared by switching
339/// again without the flag. Any message that tells an operator how to STOP
340/// forcing therefore has to know which one is actually in effect — telling
341/// someone whose force came from `TRACEVAULT_PROJECT_ATTRIBUTION` to drop a
342/// CLI flag is advice that silently changes nothing (Copilot on PR #54).
343///
344/// This carries the reason alongside the verdict instead of letting the
345/// message-building code re-derive it, because re-deriving it would mean a
346/// second copy of the env-var read and the `forced_until` parse — exactly
347/// the two-codepaths-for-one-fact shape whose removal is the whole point of
348/// [`attribution_mode`] taking the winning binding as a parameter.
349///
350/// `Default` is "neither source is forcing", i.e. plain derived attribution
351/// — the ordinary case, and what a test that cares about routing rather
352/// than attribution wants to pass.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
354pub(crate) struct AttributionForce {
355    /// `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` is set in this process's
356    /// environment. Never expires; only unsetting it stops the forcing.
357    pub(crate) env: bool,
358    /// The winning binding carries a LIVE `forced_until`. Lapses on its own
359    /// (~12h); `project switch` without `--project-attribution explicit`
360    /// clears it immediately.
361    pub(crate) binding: bool,
362}
363
364impl AttributionForce {
365    /// The verdict these sources add up to. Either source alone forces;
366    /// neither does not.
367    pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
368        if self.env || self.binding {
369            crate::api_client::AttributionMode::Explicit
370        } else {
371            crate::api_client::AttributionMode::Derived
372        }
373    }
374}
375
376/// Which attribution mode THIS PARTICULAR winning binding declares.
377///
378/// `explicit` comes either from `TRACEVAULT_PROJECT_ATTRIBUTION` (per-process,
379/// re-asserted at every launch, no expiry — genuinely global, by design) OR
380/// from a LIVE `forced_until` carried by `effective` — the exact
381/// [`crate::session_state::ProjectBinding`] that [`capture_project`] resolved
382/// as the one this event is being attributed to.
383///
384/// `forced_until` is stored PER-BINDING (see that field's own doc comment:
385/// "the FORCE lapses (the binding itself survives)"), so this must read the
386/// force off THAT binding and no other. An earlier version of this function
387/// instead did a process-global disk read
388/// (`user_project_default::load_with_force()`), which had it backwards two
389/// ways at once: a session-scoped force (`project switch` without `--user`,
390/// which is the ordinary case whenever a session id is set) is written into
391/// session state and was never read there at all, so it silently never took
392/// effect while still telling the user membership was not being checked; and
393/// a live force sitting on the user-level default leaked onto ANY
394/// higher-precedence project that happened to resolve instead (subagent
395/// override, `TRACEVAULT_PROJECT`, session active), stamping `explicit` for a
396/// project nobody forced. Taking `effective` as a parameter — the actual
397/// winning binding — makes both mistakes impossible: a force can only apply
398/// when it is attached to the binding actually being used.
399///
400/// Whether that force is live is [`crate::session_state::force_status`]'s
401/// answer, not this function's: `commands::project`'s status line reads the
402/// same field and must never disagree with the header this fills, so there is
403/// exactly one parse and one `Utc::now()` comparison. A lapsed persisted
404/// force reads as `derived` — not sending an `explicit` header IS the
405/// fallback, so ingest never starts failing because a force was forgotten —
406/// and so does an unparseable one, for the same fail-safe reason.
407///
408/// An unrecognised (or absent) `TRACEVAULT_PROJECT_ATTRIBUTION` also reads as
409/// `derived`, deliberately asymmetric with the server, which 400s an unknown
410/// value: that strictness is for callers that bypass the CLI entirely, and
411/// failing a hook over a typo'd env var helps nobody — silently falling back
412/// to the always-checked default is the safe direction to fail in.
413///
414/// This always returns one of the two variants and the caller always sends
415/// it as the header — including the
416/// [`crate::api_client::AttributionMode::Derived`] case. The
417/// server treats an absent header and an explicit `derived` value
418/// identically, but nothing here omits the header; "always emits one of two
419/// values" is simpler to reason about than "sometimes sends a header,
420/// sometimes doesn't."
421///
422/// A verdict only. Callers that must also explain THE REASON — the refusal
423/// remediation, which has to name the force source it is telling the
424/// operator to remove — take [`attribution_force`] instead and call
425/// [`AttributionForce::mode`] on it; both spellings run the one evaluation
426/// below.
427pub(crate) fn attribution_mode(
428    effective: Option<&crate::session_state::ProjectBinding>,
429) -> crate::api_client::AttributionMode {
430    attribution_force(effective).mode()
431}
432
433/// The single evaluation behind [`attribution_mode`]: reads both force
434/// sources ONCE and reports each separately, so the verdict and any
435/// explanation of it are the same fact viewed twice rather than two facts
436/// that can drift. See [`AttributionForce`] for why the distinction is
437/// load-bearing, and [`attribution_mode`]'s doc comment for why each source
438/// is read the way it is.
439pub(crate) fn attribution_force(
440    effective: Option<&crate::session_state::ProjectBinding>,
441) -> AttributionForce {
442    AttributionForce {
443        env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
444            .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
445            .unwrap_or(false),
446        binding: effective
447            .and_then(|b| b.forced_until.as_deref())
448            .is_some_and(|s| {
449                matches!(
450                    crate::session_state::force_status(s),
451                    crate::session_state::ForceStatus::Live(_)
452                )
453            }),
454    }
455}
456
457/// The capture-time project BINDING for a stream event: a thin wrapper over
458/// the shared chain [`crate::resolution::capture_project_binding`] (subagent
459/// worktree override -> `TRACEVAULT_PROJECT` -> session `active_project` ->
460/// user-level default; no `--project` flag on the hook path), with a binding
461/// whose stored id is not a UUID dropped exactly as
462/// [`crate::resolution::capture_project_id`] drops it. Local only — no
463/// network (the hook fires per event in a short-lived process), which is why
464/// repo config `default_project` (a name) is not a tier and why
465/// `TRACEVAULT_PROJECT` is honoured in its UUID form only.
466/// `commands::project::status` calls the same shared chain, so it reports
467/// exactly what this returns.
468///
469/// Returns the full [`crate::session_state::ProjectBinding`], not just its
470/// id: `forced_until` travels with whichever binding actually wins this
471/// precedence chain, so a caller can ask THAT binding — via
472/// [`attribution_mode`] — whether it is currently forced, rather than
473/// consulting some other, unrelated binding (see `attribution_mode`'s doc
474/// comment for why that distinction matters). Callers that only need the id
475/// use [`capture_project`].
476pub(crate) fn capture_binding(
477    session: &crate::session_state::SessionState,
478    worktree_path: Option<&str>,
479) -> Option<crate::session_state::ProjectBinding> {
480    use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
481    let (binding, _) = capture_project_binding(&CaptureProjectInputs {
482        project_flag: None,
483        env_project: env_project_binding(),
484        session,
485        worktree_path,
486        user_default: crate::user_project_default::load(),
487    })?;
488    // Defensive: a corrupted/hand-edited binding whose id isn't a real UUID
489    // must not be usable for attribution at all (mirrors
490    // `binding_repo_id_is_valid` for the repo side) — checked here, once, so
491    // every caller gets the same guarantee rather than re-deriving it.
492    capture_project_id(&binding)?;
493    Some(binding)
494}
495
496/// The capture-time project ID for a stream event: [`capture_binding`]
497/// projected down to its id. `None` -> fall back to the repo-scoped stream
498/// (server deduces).
499///
500/// `pub(crate)`: also called by `commands::status`, which reuses this
501/// function (plus `resolve_stream_binding`/`attribution_for`) as the
502/// authoritative "will this session record anything" gate, so the status
503/// verdict can never drift from what this hook actually does. `commands::flush`
504/// and `commands::project::status` call it for the same reason.
505pub(crate) fn capture_project(
506    session: &crate::session_state::SessionState,
507    worktree_path: Option<&str>,
508) -> Option<uuid::Uuid> {
509    capture_binding(session, worktree_path)
510        .as_ref()
511        .and_then(crate::resolution::capture_project_id)
512}
513
514/// The one-line warning printed when a repo-less event is dropped as
515/// permanently undeliverable. Pure, so the wording is asserted directly.
516fn undeliverable_warning(pid: uuid::Uuid) -> String {
517    format!(
518        "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
519         repo binding, so there is nothing to attribute these events to and they are being \
520         DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
521         that exists."
522    )
523}
524
525/// True when a stream-send error's rendered message carries a `(4xx ...)`
526/// status marker — i.e. the server deterministically rejected the request in
527/// a way that will never succeed on blind retry (bad binding, missing
528/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
529/// transport/network/timeout failures (which have no `(NNN ` marker at all,
530/// or a 5xx one) — those remain transient and must keep propagating so the
531/// existing buffer/retry logic in `run_stream` still applies to them.
532///
533/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
534/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
535///
536/// COUPLING: the `"(NNN "` markers below must byte-for-byte match what
537/// `ApiClient::authed_send_json`'s `err_prefix` closures render (e.g.
538/// `stream_event`'s `"Stream failed ({status})"`, where `{status}` Displays
539/// as `"404 Not Found"`, yielding `"Stream failed (404 Not Found): ..."` —
540/// hence the `"(404 "` marker below matching on the open-paren + code + the
541/// space before the reason phrase). If that error-formatting ever changes,
542/// update this list (and its tests) to match.
543/// Which deterministic client error this is, so the refusal error can name a
544/// cause that is actually possible instead of assuming one.
545#[derive(Debug, PartialEq, Eq)]
546pub(crate) enum ClientErrorKind {
547    /// 403, which now has TWO plausible causes — see [`send_stream_event`].
548    Forbidden,
549    /// 400/404/409: a binding/scoping problem, and only that.
550    Scoping,
551}
552
553/// The one-line error printed when the server refuses a project-scoped send.
554/// Pure, so the wording is asserted directly rather than by capturing stderr.
555///
556/// `force` is the force situation this send actually declared — the exact
557/// [`AttributionForce`] whose [`AttributionForce::mode`] filled the
558/// `x-tracevault-project-attribution` header, so the message and the wire
559/// can never disagree. It matters because the force gate also refuses with a
560/// 403: "not Operator on the project", or "`explicit` from a `tvk_` key".
561/// Without naming it, an operator who asked for `explicit` got an error about
562/// membership and realm roles and was never told the force itself was what
563/// got refused. Failing closed on trust is right; failing closed silently is
564/// the defect.
565///
566/// The force clause takes the whole `AttributionForce`, not just the mode,
567/// because its remediation has to name the source ACTUALLY in effect. The
568/// two are undone differently and only one of them by a CLI flag: an earlier
569/// wording told everyone to switch again without `--project-attribution
570/// explicit`, which for an env-sourced force clears a persisted
571/// `forced_until` that may not even exist while [`attribution_force`] goes
572/// on reading `TRACEVAULT_PROJECT_ATTRIBUTION` and every subsequent send
573/// keeps declaring `explicit` — advice that silently does nothing, handed
574/// out on the one code path a confused operator reaches (Copilot on PR #54).
575/// [`force_remediation`] derives the fix from the same struct the header
576/// came from, so it cannot name a source that is not set, or miss one that
577/// is.
578///
579/// The extra clause is attached to `Forbidden` ONLY. A `Scoping` 4xx
580/// (400/404/409) means the project id itself does not resolve — the force
581/// gate never ran — so blaming the force there would be a new wrong
582/// explanation of exactly the kind this fixes.
583pub(crate) fn refused_error(
584    pid: uuid::Uuid,
585    kind: &ClientErrorKind,
586    force: AttributionForce,
587) -> String {
588    let base = match kind {
589        // Since Keycloak, a 403 has a SECOND and now more common cause: the
590        // account has no `tracevault` grant in Control Plane, in which case nothing this
591        // hook does will work and `project switch` is confidently wrong advice —
592        // on the code path users hit most. The server's 403 envelope is not
593        // distinguishable from here (see `ClientErrorKind`), so name both.
594        ClientErrorKind::Forbidden => format!(
595            "tracevault: error: the server refused to attribute this event to active project \
596             {pid} (403). Either that project does not apply to this repo (not a member, or \
597             no `Operator` role on it) — run `tracevault project switch <name>` (add `--user` if the \
598             binding is the machine-wide default in `user_project.toml`) — or this account has \
599             no `tracevault` grant in Control Plane at all, which an administrator must grant. \
600             The event was NOT re-attributed elsewhere; it has been queued and will be retried \
601             once the binding or the grant is fixed."
602        ),
603        ClientErrorKind::Scoping => format!(
604            "tracevault: error: active project {pid} does not apply to this repo (not a member, \
605             missing permission, or the project no longer exists). The event was NOT \
606             re-attributed elsewhere; it has been queued and will be retried once the binding is \
607             fixed. Run `tracevault project switch <name>` (add `--user` if the binding is the \
608             machine-wide default in `user_project.toml`) to update it."
609        ),
610    };
611    if force.mode() == crate::api_client::AttributionMode::Explicit
612        && matches!(kind, ClientErrorKind::Forbidden)
613    {
614        return format!(
615            "{base} This send declared `explicit` attribution, so the refusal may be of the \
616             FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
617             identity (a `tvk_` API key can never force). If membership attribution is what \
618             you want, {}",
619            force_remediation(force)
620        );
621    }
622    base
623}
624
625/// How to STOP forcing, given which source(s) are doing it.
626///
627/// A sentence fragment completing "If membership attribution is what you
628/// want, ...", so the caller keeps the framing and this keeps the facts.
629///
630/// Only ever reached with at least one source set (see [`refused_error`]'s
631/// guard, which is `force.mode() == Explicit` — i.e. `env || binding`), so
632/// the all-false arm is unreachable in practice. It still has to say
633/// something rather than panic: this runs while printing an error on the
634/// capture path, and a hook that panics mid-diagnostic is strictly worse
635/// than one that prints a slightly vague line. The fallback names both ways,
636/// which is wrong about emphasis but never wrong about the fix.
637///
638/// When BOTH are set the message says so explicitly: removing one alone
639/// leaves the other still forcing, which would look exactly like the fix not
640/// working.
641fn force_remediation(force: AttributionForce) -> String {
642    let env_fix = "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
643                   process-wide and never expires, so no switch clears it)";
644    let binding_fix = "run `tracevault project switch <name>` WITHOUT \
645                       `--project-attribution explicit` (add `--user` if the forced binding \
646                       is the machine-wide default in `user_project.toml`)";
647    match (force.env, force.binding) {
648        (true, false) => format!("{env_fix}."),
649        (false, true) => format!("{binding_fix}."),
650        // Both: neither fix is sufficient alone.
651        (true, true) => {
652            format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
653        }
654        (false, false) => format!("{env_fix}, or {binding_fix}."),
655    }
656}
657
658pub(crate) fn deterministic_client_error_kind(
659    e: &dyn std::error::Error,
660) -> Option<ClientErrorKind> {
661    let s = e.to_string();
662    // 401 is deliberately excluded: it's an authentication failure (bad/expired
663    // token), not a project-scoping problem, and the buffer/retry path already
664    // handles it correctly without a misleading project-scoping message. 403
665    // stays in: it can mean the token is valid but lacks `Operator` on the bound
666    // project (or the account has no `tracevault` grant at all), and the refusal
667    // line can name both possible causes.
668    if s.contains("(403 ") {
669        return Some(ClientErrorKind::Forbidden);
670    }
671    if ["(400 ", "(404 ", "(409 "]
672        .iter()
673        .any(|marker| s.contains(marker))
674    {
675        return Some(ClientErrorKind::Scoping);
676    }
677    None
678}
679
680/// Send a single stream event, routing to the project-scoped endpoint when a
681/// local project binding resolved (`capture_pid = Some(_)`), else the
682/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
683/// the pending-flush loop and the live send share one branch.
684///
685/// Routing is decided by the [`Attribution`] resolved before the send:
686/// `Repo` with no project goes to the repo-scoped endpoint (the server
687/// deduces the project); `Repo` with a project goes to the project-scoped
688/// endpoint carrying `repo_id`; `ProjectOnly` goes to the project-scoped
689/// endpoint with no `repo_id` at all. Having no fallback endpoint, it decides
690/// instead between buffering and dropping: a `Scoping` 4xx (the project does
691/// not resolve) can never succeed on retry — the offline queue is keyed by
692/// that same project id — so it warns and returns `Ok(None)`, while a 403 or
693/// any transient error propagates to be buffered. See the arm itself for why
694/// the two differ.
695///
696/// `Ok(None)` therefore means "deliberately dropped, do not queue": callers
697/// must treat it like a success for offset/queue purposes, not like an error.
698///
699/// When the attribution carries BOTH a repo and a project, the project was
700/// explicitly declared (by binding or by `project switch`), so the server's
701/// refusal of it is an error, never re-derived elsewhere: a deterministic
702/// client error (the bound project doesn't apply to this repo: not a member,
703/// or the caller lacks `Operator` on it) prints the refusal line to stderr
704/// and returns `Err(e)` with the original error, unchanged, so the caller's
705/// existing buffer/retry logic queues it in the REPO's pending file
706/// (`pending-<repo_id>.jsonl`, see [`Attribution::pending_file_name`]); the
707/// next drain (the hook's or `tracevault flush`'s) re-applies whatever capture
708/// project is in force at that time (mirrors the server-side rule from VIS-305: a declared project the server
709/// refuses is not silently re-attributed). A transient error (5xx,
710/// network/transport, timeout) also propagates as `Err`, and is handled
711/// identically by that same buffer/retry path.
712///
713/// `warned` is shared across every call made for a single hook
714/// invocation (both the pending-flush loop and the live send). The
715/// pending-flush loop only `break`s on `Err`, so without this flag a stale,
716/// refused binding would print the refusal line once per buffered event
717/// before the loop breaks. Gating on `*warned` caps stderr at one line per
718/// invocation. The repo-less drop warning shares the flag for the same
719/// reason: draining a queue of undeliverable events would otherwise print one
720/// line per buffered event.
721///
722/// `force` is the invocation's attribution force — [`attribution_force`]
723/// applied to the capture binding. Its [`AttributionForce::mode`] goes on
724/// every project-scoped send as the `x-tracevault-project-attribution`
725/// header, and the same value is handed to [`refused_error`], which needs
726/// the SOURCES and not only the verdict to tell the operator how to stop
727/// forcing. Taken as a parameter rather than derived here because the
728/// binding is invariant across a whole hook invocation while this function
729/// runs once per buffered event, and the evaluation costs an env read plus
730/// an RFC3339 parse. `commands::flush` resolves it once per queue for the
731/// same reason.
732async fn send_stream_event(
733    client: &crate::api_client::ApiClient,
734    attribution: &Attribution,
735    force: AttributionForce,
736    req: &StreamEventRequest,
737    warned: &mut bool,
738) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
739{
740    let (repo_id, capture_pid) = match attribution {
741        // Repo-less: there is no repo-scoped endpoint to fall back TO, so the
742        // only choice is buffer-for-retry vs. drop, and that turns on whether
743        // a retry could EVER succeed.
744        //
745        // `Scoping` (400/404/409) means the project itself does not resolve.
746        // The offline queue is keyed by that same project id
747        // (`pending-project-<uuid>.jsonl`), so re-binding to a project that
748        // does exist writes to a DIFFERENT file and these events are never
749        // retried under the corrected binding — they would accumulate forever,
750        // one per tool call, each hook fire re-reading and re-appending the
751        // whole queue. Warn and drop instead: undeliverable is undeliverable,
752        // and a growing queue only hides it.
753        //
754        // `Forbidden` (403) is deliberately NOT dropped. It can mean the
755        // account has no `tracevault` grant at all, which an administrator can
756        // grant — after which the buffered events do deliver. Same for any
757        // transient error. Both propagate so the caller queues them.
758        Attribution::ProjectOnly { project_id } => {
759            let attempt = client
760                .stream_event_for_project(*project_id, None, force.mode(), req)
761                .await;
762            return match attempt {
763                Ok(r) => Ok(Some(r)),
764                Err(e) => match deterministic_client_error_kind(e.as_ref()) {
765                    Some(ClientErrorKind::Scoping) => {
766                        if !*warned {
767                            eprintln!("{}", undeliverable_warning(*project_id));
768                            *warned = true;
769                        }
770                        Ok(None)
771                    }
772                    _ => Err(e),
773                },
774            };
775        }
776        Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
777    };
778    match capture_pid {
779        None => client.stream_event(repo_id, req).await.map(Some),
780        Some(pid) => {
781            let attempt = client
782                .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
783                .await;
784            let kind = match &attempt {
785                Ok(_) => None,
786                Err(e) => deterministic_client_error_kind(e.as_ref()),
787            };
788            match (attempt, kind) {
789                (Ok(r), _) => Ok(Some(r)),
790                (Err(e), Some(kind)) => {
791                    if !*warned {
792                        // Since Keycloak, a 403 has a SECOND and now more common
793                        // cause: the account has no `tracevault` grant at all,
794                        // in which case nothing this hook does will work and
795                        // `project switch` is confidently wrong advice — on the
796                        // code path users hit most. The server's 403 envelope
797                        // isn't distinguishable from here (see
798                        // `ClientErrorKind`), so the wording names both.
799                        eprintln!("{}", refused_error(pid, &kind, force));
800                        *warned = true;
801                    }
802                    // The caller declared this project; the server refused it.
803                    // Do NOT re-attribute to another project by falling back to
804                    // the repo-scoped endpoint — propagate so the caller queues
805                    // this event for retry under the same (or a corrected)
806                    // binding.
807                    Err(e)
808                }
809                // transient — propagate for buffer/retry
810                (Err(e), None) => Err(e),
811            }
812        }
813    }
814}
815
816/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
817/// byte-offset semantics of `read_new_transcript_lines`: returns
818/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
819/// `transcript_offset` (base for the server's per-line `chunk_index`) and
820/// `next_offset` is persisted to `.stream_offset`.
821pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
822    (start_offset, start_offset + records_len)
823}
824
825/// Choose the transcript source for a stream event. Inline records (from a
826/// plugin-based agent like OpenCode) win over the file-read result whenever the
827/// hook event carries them — INCLUDING an empty vec, so an event with no new
828/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
829/// instead of resetting it to the file-path's 0.
830pub fn resolve_transcript_source(
831    inline_records: Option<Vec<serde_json::Value>>,
832    prior_offset: i64,
833    file_result: (Vec<serde_json::Value>, i64, i64),
834) -> (Vec<serde_json::Value>, i64, i64) {
835    match inline_records {
836        Some(records) => {
837            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
838            (records, send, next)
839        }
840        None => file_result,
841    }
842}
843
844/// Derive the event-level tool-error flag from inline transcript records.
845/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
846/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
847/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
848/// record found, or `None` when there is none (non-tool events).
849pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
850    lines.iter().find_map(|line| {
851        let msg = line.get("message")?;
852        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
853            Some(
854                msg.get("isError")
855                    .and_then(|v| v.as_bool())
856                    .unwrap_or(false),
857            )
858        } else {
859            None
860        }
861    })
862}
863
864/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
865/// Factored out so the mapping is testable without the network/FS-bound
866/// `run_stream`.
867pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
868    req.tool = Some(agent.tool_name().to_string());
869    req.protocol_version = agent.protocol_version() as u32;
870}
871
872pub async fn run_stream(
873    event_type: &str,
874    agent: crate::agent::Agent,
875) -> Result<(), Box<dyn std::error::Error>> {
876    // 1. Read HookEvent from stdin
877    let mut input = String::new();
878    io::stdin().read_to_string(&mut input)?;
879    let mut hook_event = parse_hook_event(&input)?;
880
881    // Resolve project_root and session_dir via the shared git-aware resolver.
882    //
883    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
884    // the primary worktree root, so it works correctly from a primary checkout,
885    // a nested worktree, AND a sibling linked worktree (where the primary
886    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
887    // would fall back to hook_cwd itself, fail to load config, and silently
888    // drop the event).
889    //
890    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
891    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
892    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
893    // just below runs BEFORE the config/credentials check and can itself
894    // `?`-exit early — that remains graceful because `main.rs` catches all
895    // `Err` from `run_stream` and exits 0 without blocking the tool.
896    let hook_cwd = Path::new(&hook_event.cwd);
897    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
898    if resolved.source == crate::paths::ProjectRootSource::Fallback {
899        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
900        // we are about to create a fresh `.tracevault/` at the hook's working
901        // directory — which is how stray per-subdirectory `.tracevault/` dirs
902        // appear. Surface it (best-effort; stderr never blocks the hook).
903        eprintln!(
904            "tracevault: warning: could not resolve a git project root from {}; \
905             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
906             that it runs inside the repository to keep sessions under the repo root.",
907            hook_cwd.display()
908        );
909    }
910    let project_root = resolved.root;
911
912    // 2. Create session dir
913    fs::create_dir_all(&session_dir)?;
914
915    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
916    // inside whatever `.tracevault/` we just created — including a per-subproject
917    // one. `tracevault init` writes this for the root dir, but runtime-created
918    // dirs would otherwise have no .gitignore and leak sessions into commits.
919    // Best-effort: never fail the hook on this.
920    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
921
922    // Write origin marker so verify-start can disambiguate sessions by worktree.
923    // Best-effort: never fail the hook on marker errors. Uses the shared
924    // canonicalizing helper so the value matches what verify-start compares
925    // against on the read side.
926    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
927    let _ = fs::write(session_dir.join("origin"), &worktree_top);
928
929    // Record where the transcript lives: `tracevault check` counts the
930    // session's tool calls from it, and finds it only through metadata.json.
931    // Best-effort, like the origin marker.
932    let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
933    // Inline records (OpenCode) reach no transcript file `check` could read,
934    // so keep their tool calls locally for it. Done here, before the
935    // `.stream_offset` read below can fail the hook, so a corrupt offset file
936    // never costs `check` a tool call.
937    if let Some(records) = &hook_event.transcript_records {
938        let _ = record_inline_tool_calls(&session_dir, records);
939    }
940
941    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
942    //    it both orders events and is a stable idempotency key — no shared
943    //    `.event_counter` file (which raced between concurrent parallel-tool
944    //    hooks and could collide/drop events).
945    let event_uuid = uuid::Uuid::now_v7();
946
947    // 4. Read new transcript lines
948    let transcript_path = Path::new(&hook_event.transcript_path);
949    let offset_path = session_dir.join(".stream_offset");
950    // transcript_offset carries the batch START byte offset so the server
951    // derives a stable per-line chunk_index across overlapping/retried reads;
952    // .stream_offset persists the END (next read position).
953    let (transcript_lines, start_offset, new_offset) =
954        read_new_transcript_lines(transcript_path, &offset_path)?;
955
956    // Fileless inline path (OpenCode): a plugin-based agent with no single
957    // tailable transcript supplies records directly on the hook event. When
958    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
959    // sends `transcript_records: []`) — they take priority over the file-read
960    // result. `.stream_offset` is reused as a per-session RECORD counter so
961    // the server's chunk_index stays stable/monotonic across retries, exactly
962    // as with the byte-offset path. Treating an empty vec as "no new
963    // records" rather than "fall back to the file" matters: OpenCode's
964    // `transcript_path` is always "", so the file-read result is always
965    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
966    // offset back to 0 and collide with earlier turns' chunk_index on the
967    // server.
968    // Only inline (plugin-based) events override the file-read result, and only
969    // they need `.stream_offset` re-read as a record counter. File-based agents
970    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
971    // the byte-offset values from `read_new_transcript_lines` above.
972    let is_inline = hook_event.transcript_records.is_some();
973    let (transcript_lines, start_offset, new_offset) = if is_inline {
974        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
975        // `.stream_offset` must NOT silently reset to 0 — that would restart the
976        // record counter and collide with earlier turns' chunk_index on the
977        // server (the offset-clobber failure mode). Propagate the error instead;
978        // `main` treats a hook error as non-fatal (exits 0 without blocking the
979        // tool call). Negatives are clamped to 0 defensively.
980        let prior_offset: i64 = if offset_path.exists() {
981            let content = fs::read_to_string(&offset_path)?;
982            content
983                .trim()
984                .parse::<i64>()
985                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
986                .max(0)
987        } else {
988            0
989        };
990        // `take()` moves the records out (nothing below reads
991        // `transcript_records` again) — avoids deep-cloning a potentially
992        // large payload (full bash stdout / file contents) on the hook path.
993        resolve_transcript_source(
994            hook_event.transcript_records.take(),
995            prior_offset,
996            (transcript_lines, start_offset, new_offset),
997        )
998    } else {
999        (transcript_lines, start_offset, new_offset)
1000    };
1001
1002    // 5. Build StreamEventRequest
1003    let stream_event_type = match event_type {
1004        "notification" => StreamEventType::SessionStart,
1005        "stop" => StreamEventType::SessionEnd,
1006        _ => StreamEventType::ToolUse,
1007    };
1008
1009    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
1010    // events have no tool_use_id, so fall back to a forwarded `toolResult`
1011    // record's `isError` — otherwise a failed OpenCode tool would render as
1012    // successful (the event-level flag file-based agents populate would be None).
1013    let tool_is_error = hook_event
1014        .tool_use_id
1015        .as_deref()
1016        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
1017        .or_else(|| inline_tool_is_error(&transcript_lines));
1018
1019    // Load config once, up front, so it can back both the user-level context
1020    // layer resolution below and the repo_id lookup further down — avoids a
1021    // redundant second read of the same file. `try_load` keeps the
1022    // missing/malformed distinction so the required-config error further down
1023    // can report which one it is.
1024    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
1025    // user context" — `resolve_user_context` below falls back to the user-level
1026    // config in that case. A malformed repo config is surfaced as an error
1027    // later (the required-config check), not silently dropped here.
1028    let config = crate::config::TracevaultConfig::try_load(&project_root);
1029    // Repo config's user_context wins when the repo configured it; otherwise
1030    // fall back to the user-level ~/.config/tracevault/config.toml. This is
1031    // what lets a detached session (no checkout) still carry user context.
1032    let repo_uc = config
1033        .as_ref()
1034        .ok()
1035        .and_then(|opt| opt.as_ref())
1036        .and_then(|c| c.user_context.clone());
1037    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
1038
1039    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
1040    // global and per-worktree) and extract fields before building the
1041    // request.  Using `effective` means parallel sessions in different linked
1042    // worktrees each stamp their own per-worktree context without
1043    // interfering with each other.
1044    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
1045    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
1046
1047    let mut req = StreamEventRequest {
1048        protocol_version: 1,
1049        tool: Some("claude-code".to_string()),
1050        event_type: stream_event_type,
1051        session_id: hook_event.session_id.clone(),
1052        timestamp: chrono::Utc::now(),
1053        hook_event_name: Some(hook_event.hook_event_name.clone()),
1054        tool_name: hook_event.tool_name.clone(),
1055        tool_use_id: hook_event.tool_use_id.clone(),
1056        tool_input: hook_event.tool_input.clone(),
1057        tool_response: hook_event.tool_response.clone(),
1058        tool_is_error,
1059        event_index: None,
1060        event_uuid: Some(event_uuid),
1061        transcript_lines: if transcript_lines.is_empty() {
1062            None
1063        } else {
1064            Some(transcript_lines)
1065        },
1066        transcript_offset: Some(start_offset),
1067        model: None,
1068        cwd: Some(hook_event.cwd.clone()),
1069        final_stats: None,
1070        flow_id: ctx_flow_id,
1071        labels: ctx_labels,
1072        params: ctx_params,
1073    };
1074
1075    stamp_agent(&mut req, agent);
1076
1077    req.truncate_large_fields();
1078
1079    // 6. Resolve credentials
1080    let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
1081
1082    // 7. Config (loaded above, alongside the user-level context layer
1083    // resolution) no longer directly gates repo_id — a missing config is not
1084    // fatal on its own, since the repo may instead resolve via the
1085    // workspace-mode precedence chain (session binding / subagent worktree
1086    // override) below. A malformed config is still surfaced here — that's
1087    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
1088    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
1089    // below).
1090    if let Err(e) = &config {
1091        return Err(format!("malformed .tracevault/config.toml: {e}").into());
1092    }
1093
1094    // Resolve the effective repo binding (workspace/detached mode). Bound
1095    // mode (a pinned config.toml) still works — it's the lowest-precedence
1096    // tier, wired below via `binding_from_config`, fed from the `config`
1097    // already loaded above (no second read of config.toml on this hot path).
1098    let session = crate::session_state::load(&hook_event.session_id);
1099    let bound = config
1100        .as_ref()
1101        .ok()
1102        .and_then(|opt| opt.as_ref())
1103        .and_then(crate::resolution::binding_from_config);
1104    let user_default = crate::user_default::load();
1105    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
1106    // Graceful no-op, exactly like the hook's normal success path. Do NOT
1107    // error: a failing hook would block the tool.
1108    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
1109        let response = HookResponse::allow();
1110        println!("{}", serde_json::to_string(&response)?);
1111        Ok(())
1112    };
1113    // Explicit local project binding (if any) overrides server-side repo
1114    // deduction. Computed BEFORE the attribution gate below, reusing the
1115    // already-loaded session + worktree used just above for the repo-binding
1116    // resolution: a repo-less session is attributable by project alone, so the
1117    // project must be known before deciding whether this event can be sent.
1118    // The full binding (not just its id) is resolved: `attribution_mode`
1119    // reads its `forced_until`, and this is the binding that actually decided
1120    // the target project, so it's the only one whose force is allowed to
1121    // apply (see `attribution_mode`'s doc comment).
1122    let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1123    let capture_pid = capture_binding
1124        .as_ref()
1125        .and_then(crate::resolution::capture_project_id);
1126    // Resolved once per invocation, not per event — the binding is invariant
1127    // across the pending-flush loop and the live send below, while the
1128    // evaluation costs an env read and an RFC3339 parse. `commands::flush`
1129    // resolves it once per queue for the same reason. The whole
1130    // `AttributionForce` travels, not just its mode: a refusal has to name
1131    // the force source it is telling the operator to remove.
1132    let force = attribution_force(capture_binding.as_ref());
1133
1134    // Ship if EITHER a repo or a project resolved; no-op only when neither
1135    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
1136    // session-state file whose repo_id could carry path separators into the
1137    // pending filename — such a binding degrades to project-only inside
1138    // `attribution_for` rather than dropping the event.)
1139    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1140        no_op_allow()?;
1141        return Ok(());
1142    };
1143
1144    // 8. Create ApiClient
1145    let server_url = server_url.ok_or("server_url not configured")?;
1146    let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
1147
1148    // 9. Try drain pending queue and send
1149    let pending_path = pending_path_for(&session_dir, &attribution);
1150    let pending_events = drain_pending(&pending_path)?;
1151
1152    let mut send_failed = false;
1153    // Spans the whole invocation (pending-flush loop + live send below) so a
1154    // refused project binding prints its error at most once per invocation,
1155    // not once per buffered event.
1156    let mut warned = false;
1157
1158    // Send pending events first
1159    for (i, pending_json) in pending_events.iter().enumerate() {
1160        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1161            if send_stream_event(&client, &attribution, force, &pending_req, &mut warned)
1162                .await
1163                .is_err()
1164            {
1165                // Re-queue only the failed event and the ones after it that
1166                // were never attempted, in order. Events before `i` already
1167                // got a server response and must NOT be re-queued here — a
1168                // prior iteration already appended them if IT failed, and if
1169                // it succeeded, re-adding them would deliver them twice on
1170                // the next drain.
1171                for evt in &pending_events[i..] {
1172                    append_pending(&pending_path, evt)?;
1173                }
1174                send_failed = true;
1175                break;
1176            }
1177        }
1178    }
1179
1180    // Send current event
1181    let req_json = serde_json::to_string(&req)?;
1182    // The inline (OpenCode) path CONSUMES its records from the hook event — they
1183    // are not re-readable like a transcript file — so its `.stream_offset` record
1184    // counter must advance whenever the event is accepted for delivery, INCLUDING
1185    // when it is queued after a failure. Otherwise the next inline event reuses
1186    // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
1187    // queued request already carries this event's `transcript_offset`, so the
1188    // records keep their indices on drain. (File-based agents must NOT advance on
1189    // failure: their next read re-covers these lines cumulatively/idempotently.)
1190    if send_failed {
1191        append_pending(&pending_path, &req_json)?;
1192        if is_inline {
1193            fs::write(&offset_path, new_offset.to_string())?;
1194        }
1195    } else {
1196        match send_stream_event(&client, &attribution, force, &req, &mut warned).await {
1197            Ok(_) => {
1198                // 10. On success update .stream_offset
1199                fs::write(&offset_path, new_offset.to_string())?;
1200            }
1201            Err(_) => {
1202                // 11. On failure append to pending.jsonl (advance the inline
1203                // record counter regardless — see the note above).
1204                append_pending(&pending_path, &req_json)?;
1205                if is_inline {
1206                    fs::write(&offset_path, new_offset.to_string())?;
1207                }
1208            }
1209        }
1210    }
1211
1212    // 12. Always print HookResponse::allow() to stdout
1213    let response = HookResponse::allow();
1214    println!("{}", serde_json::to_string(&response)?);
1215
1216    Ok(())
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221    use super::*;
1222    use crate::api_client::AttributionMode;
1223    use crate::config::UserContext;
1224    use crate::context::{Context, EffectiveContext};
1225    use std::collections::BTreeMap;
1226
1227    // ── user layer resolution: disabled config → no user layer ────────────────
1228
1229    #[test]
1230    fn disabled_user_context_resolves_to_none() {
1231        // Default/disabled `user_context` (the `Toggle(false)` variant) must
1232        // resolve to `None`, matching the pre-existing hook behavior of
1233        // stamping without a user layer when it isn't configured.
1234        assert!(UserContext::Toggle(false).resolve().is_none());
1235    }
1236
1237    #[test]
1238    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1239        // With no user layer and no global/worktree context files present,
1240        // `Context::effective` must yield a default (empty) `EffectiveContext`
1241        // — i.e. passing `None` for `user_layer` is behavior-preserving.
1242        let dir = tempfile::tempdir().unwrap();
1243        let effective = Context::effective(dir.path(), None);
1244        assert_eq!(effective, EffectiveContext::default());
1245    }
1246
1247    // ── apply_context: all three fields populated ─────────────────────────────
1248
1249    #[test]
1250    fn apply_context_stamps_all_fields() {
1251        let dir = tempfile::tempdir().unwrap();
1252        let mut params = BTreeMap::new();
1253        params.insert("env".to_string(), "prod".to_string());
1254        params.insert("region".to_string(), "eu-west-1".to_string());
1255
1256        let ctx = EffectiveContext {
1257            flow_id: Some("flow-xyz".to_string()),
1258            labels: vec!["backend".to_string(), "urgent".to_string()],
1259            params,
1260        };
1261
1262        let (flow_id, labels, params_out) = apply_context(ctx);
1263
1264        assert_eq!(flow_id, Some("flow-xyz".to_string()));
1265        assert_eq!(
1266            labels,
1267            Some(vec!["backend".to_string(), "urgent".to_string()])
1268        );
1269        let p = params_out.expect("params should be Some");
1270        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1271        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1272
1273        // Verify the stored context round-trips through save_to → load_from →
1274        // merge_layers → apply_context (stored params are now `Option<String>`).
1275        let written = Context {
1276            flow_id: Some("flow-xyz".to_string()),
1277            labels: vec!["backend".to_string(), "urgent".to_string()],
1278            params: {
1279                let mut m = BTreeMap::new();
1280                m.insert("env".to_string(), Some("prod".to_string()));
1281                m.insert("region".to_string(), Some("eu-west-1".to_string()));
1282                m
1283            },
1284        };
1285        let ctx_path = dir.path().join(".tracevault").join("context.json");
1286        written.save_to(&ctx_path).unwrap();
1287        let loaded = Context::load_from(&ctx_path);
1288        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1289        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1290        assert!(labels2.is_some());
1291        assert!(params2.is_some());
1292    }
1293
1294    // ── apply_context: missing context file → all None ────────────────────────
1295
1296    #[test]
1297    fn apply_context_missing_file_all_none() {
1298        let dir = tempfile::tempdir().unwrap();
1299        let missing_path = dir.path().join(".tracevault").join("context.json");
1300        let ctx = Context::load_from(&missing_path); // no context.json → default
1301        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1302        assert!(flow_id.is_none(), "flow_id should be None");
1303        assert!(labels.is_none(), "labels should be None");
1304        assert!(params.is_none(), "params should be None");
1305    }
1306
1307    // ── apply_context: empty labels vec / empty params map → None ─────────────
1308
1309    #[test]
1310    fn apply_context_empty_collections_are_none() {
1311        let ctx = EffectiveContext {
1312            flow_id: None,
1313            labels: vec![],
1314            params: BTreeMap::new(),
1315        };
1316        let (flow_id, labels, params) = apply_context(ctx);
1317        assert!(flow_id.is_none());
1318        assert!(
1319            labels.is_none(),
1320            "empty labels should be None, not Some([])"
1321        );
1322        assert!(
1323            params.is_none(),
1324            "empty params should be None, not Some({{}})"
1325        );
1326    }
1327
1328    // ── apply_context: flow_id only, collections empty ────────────────────────
1329
1330    #[test]
1331    fn apply_context_flow_id_only() {
1332        let ctx = EffectiveContext {
1333            flow_id: Some("my-flow".to_string()),
1334            labels: vec![],
1335            params: BTreeMap::new(),
1336        };
1337        let (flow_id, labels, params) = apply_context(ctx);
1338        assert_eq!(flow_id, Some("my-flow".to_string()));
1339        assert!(labels.is_none());
1340        assert!(params.is_none());
1341    }
1342
1343    // ── resolve_session_paths tests ───────────────────────────────────────────
1344    //
1345    // These tests verify that `resolve_session_paths` routes through the
1346    // git-aware resolver so that sibling linked worktrees capture events under
1347    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
1348
1349    use crate::test_helpers::{add_worktree, init_git_repo};
1350
1351    /// Primary checkout: project_root resolves to the repo root; session_dir is
1352    /// under `<repo>/.tracevault/sessions/<id>/`.
1353    #[test]
1354    fn resolve_session_paths_primary_checkout() {
1355        let tmp = tempfile::tempdir().unwrap();
1356        let repo = tmp.path().join("repo");
1357        std::fs::create_dir_all(&repo).unwrap();
1358        init_git_repo(&repo);
1359        // Create a .tracevault/ in the primary root to match a real init.
1360        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1361
1362        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1363        let project_root = resolved.root;
1364
1365        assert_eq!(
1366            project_root.canonicalize().unwrap(),
1367            repo.canonicalize().unwrap(),
1368            "primary checkout: project_root must be repo root"
1369        );
1370        assert_eq!(
1371            session_dir.canonicalize().unwrap_or(session_dir.clone()),
1372            repo.join(".tracevault")
1373                .join("sessions")
1374                .join("sess-primary-123"),
1375            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1376        );
1377        // session_dir must be INSIDE the primary repo, not elsewhere.
1378        assert!(
1379            session_dir.starts_with(&repo),
1380            "session_dir must be under the primary repo root"
1381        );
1382    }
1383
1384    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1385    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1386    /// git-aware resolver must return the PRIMARY root.
1387    #[test]
1388    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1389        let tmp = tempfile::tempdir().unwrap();
1390        let repo = tmp.path().join("repo");
1391        // Sibling worktree lives outside the primary repo directory.
1392        let wt = tmp.path().join("sibling-wt");
1393
1394        std::fs::create_dir_all(&repo).unwrap();
1395        init_git_repo(&repo);
1396        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1397        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1398        add_worktree(&repo, &wt);
1399
1400        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1401        let project_root = resolved.root;
1402
1403        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1404        assert_eq!(
1405            project_root.canonicalize().unwrap(),
1406            repo.canonicalize().unwrap(),
1407            "sibling worktree: project_root must be primary repo root (not worktree dir)"
1408        );
1409        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1410        assert!(
1411            session_dir.starts_with(&repo),
1412            "sibling worktree: session_dir must be under the PRIMARY repo root"
1413        );
1414        assert!(
1415            !session_dir.starts_with(&wt),
1416            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1417        );
1418        assert!(
1419            session_dir.ends_with(
1420                std::path::Path::new(".tracevault")
1421                    .join("sessions")
1422                    .join("sess-sibling-456")
1423            ),
1424            "session_dir must end with .tracevault/sessions/<session_id>"
1425        );
1426    }
1427
1428    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1429    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1430    #[test]
1431    fn resolve_session_paths_non_git_fallback() {
1432        let tmp = tempfile::tempdir().unwrap();
1433        // No git repo, no .tracevault/ anywhere.
1434        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1435        let project_root = resolved.root;
1436
1437        assert_eq!(
1438            project_root,
1439            tmp.path(),
1440            "non-git: project_root must fall back to hook_cwd"
1441        );
1442        assert_eq!(
1443            session_dir,
1444            tmp.path()
1445                .join(".tracevault")
1446                .join("sessions")
1447                .join("sess-fallback-789"),
1448            "non-git: session_dir must be relative to the fallback root"
1449        );
1450    }
1451
1452    /// The origin marker written by run_stream contains the worktree toplevel.
1453    /// This test exercises the same `paths::worktree_toplevel` helper the hook
1454    /// uses (can't call run_stream end-to-end without a real server) so the
1455    /// marker content is computed and canonicalized exactly as in production.
1456    #[test]
1457    fn origin_marker_written_in_session_dir() {
1458        let tmp = tempfile::tempdir().unwrap();
1459        let repo = tmp.path().join("repo");
1460        std::fs::create_dir_all(&repo).unwrap();
1461        init_git_repo(&repo);
1462
1463        let session_dir = repo
1464            .join(".tracevault")
1465            .join("sessions")
1466            .join("test-sess-001");
1467        std::fs::create_dir_all(&session_dir).unwrap();
1468
1469        let hook_cwd = &repo;
1470        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1471        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1472
1473        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1474        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1475        assert_eq!(
1476            origin_content.trim(),
1477            expected.as_str(),
1478            "origin marker must contain the canonicalized worktree toplevel"
1479        );
1480    }
1481
1482    fn metadata(session_dir: &Path) -> serde_json::Value {
1483        serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
1484            .unwrap()
1485    }
1486
1487    #[test]
1488    fn record_transcript_path_writes_metadata_for_check() {
1489        let tmp = tempfile::tempdir().unwrap();
1490        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1491        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1492    }
1493
1494    #[test]
1495    fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
1496        let tmp = tempfile::tempdir().unwrap();
1497        std::fs::write(
1498            tmp.path().join("metadata.json"),
1499            r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
1500        )
1501        .unwrap();
1502        record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
1503        let m = metadata(tmp.path());
1504        assert_eq!(m["transcript_path"], "/t/new.jsonl");
1505        assert_eq!(m["model"], "m");
1506        let leftovers = std::fs::read_dir(tmp.path())
1507            .unwrap()
1508            .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
1509            .count();
1510        assert_eq!(leftovers, 0, "the temp file is renamed into place");
1511    }
1512
1513    #[test]
1514    fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
1515        let tmp = tempfile::tempdir().unwrap();
1516        record_transcript_path(tmp.path(), "").unwrap();
1517        assert!(!tmp.path().join("metadata.json").exists());
1518
1519        std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
1520        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1521        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1522    }
1523
1524    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1525
1526    use crate::session_state::{RepoBinding, SessionState};
1527
1528    fn binding(id: &str) -> RepoBinding {
1529        RepoBinding {
1530            repo_id: id.into(),
1531            git_url: None,
1532            remote_id: None,
1533            codebase_name: None,
1534            updated_at: "t".into(),
1535        }
1536    }
1537
1538    /// Workspace mode: no pinned config, but the session is bound (e.g. via
1539    /// `tracevault repo switch`) — the stream event attributes to that repo.
1540    #[test]
1541    fn resolve_stream_binding_uses_session_active_when_unbound() {
1542        let session = SessionState {
1543            active: Some(binding("session-repo")),
1544            subagents: HashMap::new(),
1545            ..Default::default()
1546        };
1547        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1548        assert_eq!(got.unwrap().repo_id, "session-repo");
1549    }
1550
1551    /// Bound-mode regression: an empty session (no `repo switch` ever run)
1552    /// with a bound config.toml still resolves via the config.
1553    #[test]
1554    fn resolve_stream_binding_falls_back_to_bound_config() {
1555        let session = SessionState::default();
1556        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1557        assert_eq!(got.unwrap().repo_id, "bound-repo");
1558    }
1559
1560    /// No session binding and no bound config: nothing resolves, which is
1561    /// exactly what should trigger `run_stream`'s graceful no-op.
1562    #[test]
1563    fn resolve_stream_binding_none_when_nothing_resolves() {
1564        let session = SessionState::default();
1565        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1566        assert!(got.is_none());
1567    }
1568
1569    /// Subagent override precedence: a per-worktree override for the current
1570    /// worktree wins over the session's `active` binding.
1571    #[test]
1572    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1573        let session = SessionState {
1574            active: Some(binding("session-repo")),
1575            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1576            ..Default::default()
1577        };
1578        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1579        assert_eq!(got.unwrap().repo_id, "subagent-repo");
1580    }
1581
1582    /// Workspace mode: no bound config, but a user-level default is set (e.g.
1583    /// via `tracevault repo switch --user`) — the stream event attributes to
1584    /// that repo when nothing more specific resolves.
1585    #[test]
1586    fn resolve_stream_binding_falls_back_to_user_default() {
1587        let session = SessionState::default();
1588        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1589        assert_eq!(got.unwrap().repo_id, "userdef");
1590    }
1591
1592    /// The user-level default is the LOWEST-precedence tier: a bound config
1593    /// still wins over it.
1594    #[test]
1595    fn resolve_stream_binding_prefers_bound_over_user_default() {
1596        let session = SessionState::default();
1597        let got = resolve_stream_binding(
1598            &session,
1599            "/wt/x",
1600            Some(binding("bound")),
1601            Some(binding("userdef")),
1602        );
1603        assert_eq!(got.unwrap().repo_id, "bound");
1604    }
1605
1606    // ── attribution_for: repo-or-project gate ────────────────────────────────
1607
1608    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1609        crate::session_state::RepoBinding {
1610            repo_id: repo_id.into(),
1611            git_url: None,
1612            remote_id: None,
1613            codebase_name: None,
1614            updated_at: String::new(),
1615        }
1616    }
1617
1618    /// The regression this whole change exists for: a session with a project
1619    /// binding and NO repo binding must still ship, repo-less, instead of
1620    /// being dropped by the hook.
1621    #[test]
1622    fn attribution_falls_back_to_project_when_no_repo_binds() {
1623        let pid = uuid::Uuid::new_v4();
1624        assert_eq!(
1625            attribution_for(None, Some(pid)),
1626            Some(Attribution::ProjectOnly { project_id: pid })
1627        );
1628    }
1629
1630    /// Neither binding resolves — the only case that may still no-op.
1631    #[test]
1632    fn attribution_is_none_when_neither_repo_nor_project_binds() {
1633        assert_eq!(attribution_for(None, None), None);
1634    }
1635
1636    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1637    /// server left to deduce the project.
1638    #[test]
1639    fn attribution_uses_repo_with_no_project_overlay() {
1640        let repo = uuid::Uuid::new_v4().to_string();
1641        let b = binding_with(&repo);
1642        assert_eq!(
1643            attribution_for(Some(&b), None),
1644            Some(Attribution::Repo {
1645                repo_id: repo,
1646                project: None
1647            })
1648        );
1649    }
1650
1651    /// Both bound: the project overlays the repo (project-scoped ingest
1652    /// carrying repo_id), unchanged from before.
1653    #[test]
1654    fn attribution_overlays_project_on_repo() {
1655        let repo = uuid::Uuid::new_v4().to_string();
1656        let pid = uuid::Uuid::new_v4();
1657        let b = binding_with(&repo);
1658        assert_eq!(
1659            attribution_for(Some(&b), Some(pid)),
1660            Some(Attribution::Repo {
1661                repo_id: repo,
1662                project: Some(pid)
1663            })
1664        );
1665    }
1666
1667    /// A corrupted repo_id costs the repo attribution, not the trace: it
1668    /// degrades to project-only rather than dropping the event.
1669    #[test]
1670    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
1671        let pid = uuid::Uuid::new_v4();
1672        let b = binding_with("../../escape");
1673        assert_eq!(
1674            attribution_for(Some(&b), Some(pid)),
1675            Some(Attribution::ProjectOnly { project_id: pid })
1676        );
1677    }
1678
1679    /// ...but with no project to fall back to, a corrupt repo_id still drops,
1680    /// so it can never reach the pending filename.
1681    #[test]
1682    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
1683        let b = binding_with("../../escape");
1684        assert_eq!(attribution_for(Some(&b), None), None);
1685    }
1686
1687    // ── pending queue filenames ──────────────────────────────────────────────
1688
1689    /// The repo filename is unchanged, so queues buffered by earlier releases
1690    /// are still found and drained after this upgrade.
1691    #[test]
1692    fn pending_file_name_for_a_repo_is_unchanged() {
1693        let repo = uuid::Uuid::new_v4().to_string();
1694        assert_eq!(
1695            Attribution::Repo {
1696                repo_id: repo.clone(),
1697                project: Some(uuid::Uuid::new_v4())
1698            }
1699            .pending_file_name(),
1700            format!("pending-{repo}.jsonl")
1701        );
1702    }
1703
1704    /// Repo-less queues carry the `project-` infix, which an older CLI reads
1705    /// as a non-UUID repo id and skips (see the doc comment).
1706    #[test]
1707    fn pending_file_name_for_a_project_is_distinct() {
1708        let pid = uuid::Uuid::new_v4();
1709        assert_eq!(
1710            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
1711            format!("pending-project-{pid}.jsonl")
1712        );
1713    }
1714
1715    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1716
1717    #[test]
1718    fn binding_repo_id_is_valid_accepts_real_uuid() {
1719        assert!(binding_repo_id_is_valid(
1720            "550e8400-e29b-41d4-a716-446655440000"
1721        ));
1722    }
1723
1724    #[test]
1725    fn binding_repo_id_is_valid_rejects_path_traversal() {
1726        assert!(!binding_repo_id_is_valid("../evil"));
1727    }
1728
1729    #[test]
1730    fn binding_repo_id_is_valid_rejects_empty() {
1731        assert!(!binding_repo_id_is_valid(""));
1732    }
1733
1734    #[test]
1735    fn binding_repo_id_is_valid_rejects_non_uuid() {
1736        assert!(!binding_repo_id_is_valid("not-a-uuid"));
1737    }
1738
1739    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1740
1741    #[test]
1742    fn stamp_agent_sets_tool_and_version() {
1743        use crate::agent::Agent;
1744        let mut req = StreamEventRequest {
1745            protocol_version: 1,
1746            tool: Some("claude-code".to_string()),
1747            event_type: StreamEventType::ToolUse,
1748            session_id: "s".into(),
1749            timestamp: chrono::Utc::now(),
1750            hook_event_name: None,
1751            tool_name: None,
1752            tool_use_id: None,
1753            tool_input: None,
1754            tool_response: None,
1755            tool_is_error: None,
1756            event_index: None,
1757            event_uuid: None,
1758            transcript_lines: None,
1759            transcript_offset: None,
1760            model: None,
1761            cwd: None,
1762            final_stats: None,
1763            flow_id: None,
1764            labels: None,
1765            params: None,
1766        };
1767        stamp_agent(&mut req, Agent::Codex);
1768        assert_eq!(req.tool.as_deref(), Some("codex"));
1769        assert_eq!(req.protocol_version, 2);
1770
1771        stamp_agent(&mut req, Agent::ClaudeCode);
1772        assert_eq!(req.tool.as_deref(), Some("claude-code"));
1773        assert_eq!(req.protocol_version, 1);
1774    }
1775
1776    // ── pending_path_for: per-target offline queue ───────────────────────────
1777
1778    fn repo_attr(repo_id: &str) -> Attribution {
1779        Attribution::Repo {
1780            repo_id: repo_id.into(),
1781            project: None,
1782        }
1783    }
1784
1785    #[test]
1786    fn pending_path_is_repo_scoped() {
1787        let dir = std::path::Path::new("/tmp/sess");
1788        assert_eq!(
1789            pending_path_for(dir, &repo_attr("repo-a")),
1790            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1791        );
1792        assert_ne!(
1793            pending_path_for(dir, &repo_attr("repo-a")),
1794            pending_path_for(dir, &repo_attr("repo-b")),
1795        );
1796    }
1797
1798    /// A repo-less session must not share a queue file with any repo, so its
1799    /// buffered events can never be flushed to a repo endpoint.
1800    #[test]
1801    fn pending_path_for_a_project_never_collides_with_a_repo() {
1802        let dir = std::path::Path::new("/tmp/sess");
1803        let pid = uuid::Uuid::from_u128(9);
1804        assert_eq!(
1805            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1806            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
1807        );
1808        assert_ne!(
1809            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1810            pending_path_for(dir, &repo_attr(&pid.to_string())),
1811        );
1812    }
1813
1814    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1815
1816    #[test]
1817    fn read_new_transcript_lines_empty_path_is_noop() {
1818        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1819        // An empty path must yield no lines and offset 0, never an error from
1820        // handing `Path::new("")` to exists()/File::open.
1821        let dir = tempfile::tempdir().unwrap();
1822        let offset_path = dir.path().join(".stream_offset");
1823        let (lines, start_offset, end_offset) =
1824            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1825        assert!(
1826            lines.is_empty(),
1827            "empty path must yield no transcript lines"
1828        );
1829        assert_eq!(start_offset, 0);
1830        assert_eq!(end_offset, 0);
1831    }
1832
1833    // ── read_new_transcript_lines: start_offset is stable across a persisted
1834    //    end_offset, and equals the previous read's end_offset ─────────────────
1835
1836    #[test]
1837    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1838        let dir = tempfile::tempdir().unwrap();
1839        let transcript_path = dir.path().join("transcript.jsonl");
1840        let offset_path = dir.path().join(".stream_offset");
1841
1842        fs::write(
1843            &transcript_path,
1844            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1845        )
1846        .unwrap();
1847
1848        let (lines, start_offset, end_offset) =
1849            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1850        assert_eq!(lines.len(), 2);
1851        assert_eq!(start_offset, 0, "first read starts at byte 0");
1852        assert!(end_offset > 0);
1853
1854        fs::write(&offset_path, end_offset.to_string()).unwrap();
1855
1856        let mut f = OpenOptions::new()
1857            .append(true)
1858            .open(&transcript_path)
1859            .unwrap();
1860        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1861        drop(f);
1862
1863        let (lines2, start_offset2, end_offset2) =
1864            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1865        assert_eq!(lines2.len(), 1);
1866        assert_eq!(
1867            start_offset2, end_offset,
1868            "second read's start_offset must equal the first read's persisted end_offset"
1869        );
1870        assert!(end_offset2 > start_offset2);
1871    }
1872
1873    // ── capture_project: local-only project resolver ──────────────────────────
1874
1875    /// Holds the env lock and points the config dir (`XDG_CONFIG_HOME` on
1876    /// Linux, `HOME` for macOS's `dirs::config_dir()`) at a tempdir: the last
1877    /// tier reads `user_project.toml` from there, so without isolation this
1878    /// test fails on any machine with a real user default and races tests
1879    /// that write one.
1880    ///
1881    /// `TRACEVAULT_PROJECT` is pinned UNSET for the same reason:
1882    /// `capture_project` reads it (rung 3, above `session.active_project`),
1883    /// and other tests in this same binary SET it. The crate lock only
1884    /// serializes mutators against each other, so a non-locking reader still
1885    /// races them — and `std::env::set_var` concurrent with `std::env::var`
1886    /// is exactly the UB the `unsafe` blocks in `EnvVarGuard` are annotated
1887    /// against. Holding the lock AND declaring the value is what makes the
1888    /// precedence assertions below describe the tiers they name rather than
1889    /// whatever the ambient shell happens to export.
1890    #[tokio::test]
1891    async fn capture_project_precedence_local_only() {
1892        use crate::session_state::{ProjectBinding, SessionState};
1893        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1894        let tmp = tempfile::tempdir().unwrap();
1895        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1896        _guard.set("XDG_CONFIG_HOME", tmp.path());
1897        _guard.set("HOME", tmp.path());
1898        _guard.remove("TRACEVAULT_PROJECT");
1899
1900        let pb = |id: &str| ProjectBinding {
1901            project_id: id.into(),
1902            project_name: "n".into(),
1903            updated_at: "".into(),
1904            forced_until: None,
1905        };
1906        let u = uuid::Uuid::from_u128;
1907        // session active only
1908        let s = SessionState {
1909            active_project: Some(pb(&u(2).to_string())),
1910            ..Default::default()
1911        };
1912        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
1913        // subagent worktree beats session
1914        let mut s = s;
1915        s.subagent_projects
1916            .insert("/wt".into(), pb(&u(1).to_string()));
1917        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
1918        // no worktree match -> session active
1919        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
1920        // empty session, no user_project.toml in the isolated config dir -> None
1921        assert_eq!(capture_project(&SessionState::default(), None), None);
1922        // malformed stored id -> None (defensive)
1923        let bad = SessionState {
1924            active_project: Some(pb("not-a-uuid")),
1925            ..Default::default()
1926        };
1927        assert_eq!(capture_project(&bad, None), None);
1928        // a valid user_project.toml in the isolated config dir is the last tier
1929        let path = crate::user_project_default::default_project_path().unwrap();
1930        assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
1931        crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
1932        assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
1933    }
1934
1935    /// The full binding — not just its id — survives `capture_binding`: this
1936    /// is what lets `attribution_mode` see a session-scoped `forced_until`
1937    /// (Important finding 1 in the VIS-305 Part C review: the old
1938    /// process-global disk read never saw a force written into SESSION
1939    /// state, which is where a plain `project switch --project-attribution
1940    /// explicit` — no `--user` — writes it).
1941    /// ENV ISOLATION: see `capture_project_precedence_local_only` — this
1942    /// test also goes through the capture chain, which reads
1943    /// `TRACEVAULT_PROJECT` at a rung ABOVE the session-active binding it is
1944    /// asserting on.
1945    #[test]
1946    fn capture_binding_preserves_forced_until_from_the_winning_tier() {
1947        use crate::session_state::{ProjectBinding, SessionState};
1948        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1949        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1950        _guard.remove("TRACEVAULT_PROJECT");
1951        let pid = uuid::Uuid::from_u128(2);
1952        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
1953        let s = SessionState {
1954            active_project: Some(ProjectBinding {
1955                project_id: pid.to_string(),
1956                project_name: "n".into(),
1957                updated_at: "".into(),
1958                forced_until: Some(future.clone()),
1959            }),
1960            ..Default::default()
1961        };
1962        let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
1963        assert_eq!(got.forced_until, Some(future));
1964    }
1965
1966    /// `_env_lock` serializes this against other tests in the crate that
1967    /// mutate `TRACEVAULT_PROJECT` (see `test_helpers::lock_env_mutation_sync`),
1968    /// including any that call `commands::project::status`, which reads the
1969    /// same var.
1970    #[test]
1971    fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
1972        // A name would need a `list_projects` round trip, and this path runs
1973        // per-event in a short-lived hook process. Same rule already excludes
1974        // `config_default` here.
1975        let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1976
1977        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1978        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1979
1980        _guard.set("TRACEVAULT_PROJECT", uuid);
1981        let got = env_project_binding().expect("uuid form is honoured");
1982        assert_eq!(got.project_id, uuid);
1983
1984        _guard.set("TRACEVAULT_PROJECT", "my-project");
1985        assert!(
1986            env_project_binding().is_none(),
1987            "a name is ignored on the network-free capture path"
1988        );
1989
1990        _guard.remove("TRACEVAULT_PROJECT");
1991        assert!(env_project_binding().is_none());
1992    }
1993
1994    // ── attribution_mode ───────────────────────────────────────────────────
1995    //
1996    // `attribution_mode` no longer touches disk at all: it takes the WINNING
1997    // binding (as resolved by `capture_project`) as a parameter, so these
1998    // tests only need to isolate `TRACEVAULT_PROJECT_ATTRIBUTION` via the
1999    // crate's env-mutation lock/guard, not `XDG_CONFIG_HOME`.
2000
2001    fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2002        crate::session_state::ProjectBinding {
2003            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2004            project_name: "p".into(),
2005            updated_at: chrono::Utc::now().to_rfc3339(),
2006            forced_until: forced_until.map(str::to_string),
2007        }
2008    }
2009
2010    #[test]
2011    fn env_force_is_explicit_and_needs_no_expiry() {
2012        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2013        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2014        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2015
2016        assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2017    }
2018
2019    #[test]
2020    fn absent_or_unrecognised_env_is_derived() {
2021        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2022        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2023
2024        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2025        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2026
2027        // The CLI does not forward a value it does not recognise: the server
2028        // would 400 it, and failing a hook over a typo'd env var helps
2029        // nobody. The server's strictness is for callers that bypass the
2030        // CLI.
2031        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2032        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2033    }
2034
2035    /// The binding-persisted half of `attribution_mode`: a LIVE `forced_until`
2036    /// on the WINNING binding (no env var involved) must also read as
2037    /// `explicit` — this is what `project switch --project-attribution
2038    /// explicit` ultimately drives, whether that binding lives in session
2039    /// state or the user-level default.
2040    #[test]
2041    fn live_binding_force_is_explicit_without_env() {
2042        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2043        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2044        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2045
2046        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2047        let binding = forced_binding(Some(&future));
2048
2049        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2050    }
2051
2052    /// This is the test that would fail if a lapsed persisted force still
2053    /// made it onto the wire: with no env override, a `forced_until` in the
2054    /// past on the winning binding must make `attribution_mode` — the exact
2055    /// function that supplies the header — report `derived`, not `explicit`.
2056    /// Not sending an `explicit` header IS the fallback to derived
2057    /// attribution.
2058    #[test]
2059    fn lapsed_binding_force_is_derived_without_env() {
2060        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2061        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2062        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2063
2064        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2065        let binding = forced_binding(Some(&past));
2066
2067        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2068    }
2069
2070    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
2071    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
2072    /// read as `derived`, never panic or, worse, read as `explicit`. Pins the
2073    /// fail-safe direction against a future refactor to `.expect(...)`.
2074    #[test]
2075    fn unparseable_forced_until_is_derived() {
2076        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2077        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2078        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2079
2080        let binding = forced_binding(Some("not-a-timestamp"));
2081
2082        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2083    }
2084
2085    /// Env-provided force must be exempt from expiry in fact, not just by
2086    /// coincidence of the OR: pairing it with a binding force that has
2087    /// ALREADY LAPSED still yields `explicit`. If `attribution_mode` were
2088    /// refactored to gate the env branch on any timestamp, this is the test
2089    /// that would catch it — `lapsed_binding_force_is_derived_without_env`
2090    /// alone couldn't, since it never sets the env var.
2091    #[test]
2092    fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2093        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2094        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2095        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2096
2097        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2098        let binding = forced_binding(Some(&past));
2099
2100        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2101    }
2102
2103    /// VIS-305 Part C review, Important finding 1: a SESSION-scoped force
2104    /// (`project switch --project-attribution explicit` WITHOUT `--user`,
2105    /// which is the default whenever a session id is set — i.e. the ordinary
2106    /// case inside every instrumented agent session) must actually reach the
2107    /// wire as `explicit`. The old process-global `attribution_mode` only
2108    /// ever consulted the user-level default store and never saw a force
2109    /// written into session state at all, so this would have silently sent
2110    /// `derived` while `project switch`'s own success message claimed
2111    /// membership was not being checked. Exercised end-to-end through
2112    /// `send_stream_event` and a real captured request header, not just the
2113    /// pure `attribution_mode` function, so a regression anywhere in the
2114    /// plumbing between `capture_project` and the wire is caught.
2115    #[tokio::test]
2116    async fn session_scoped_force_is_honoured_on_the_wire() {
2117        use crate::session_state::{ProjectBinding, SessionState};
2118
2119        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2120        let tmp = tempfile::tempdir().unwrap();
2121        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2122        // No user-level default at all: the force under test lives ONLY in
2123        // session state, so a pass here can't be explained by an ambient or
2124        // accidentally-written user_project.toml.
2125        _guard.set("XDG_CONFIG_HOME", tmp.path());
2126        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2127        // `capture_project` reads `TRACEVAULT_PROJECT` ABOVE the
2128        // session-active tier this test pins the force on; unset it so an
2129        // ambient export can't redirect the capture at another project.
2130        _guard.remove("TRACEVAULT_PROJECT");
2131
2132        let pid = uuid::Uuid::from_u128(321);
2133        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2134        let session = SessionState {
2135            active_project: Some(ProjectBinding {
2136                project_id: pid.to_string(),
2137                project_name: "proj".into(),
2138                updated_at: "".into(),
2139                forced_until: Some(future),
2140            }),
2141            ..Default::default()
2142        };
2143        let capture_binding = capture_binding(&session, None);
2144
2145        let resp = ok_stream_response();
2146        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2147        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2148        let req = sample_stream_event_request();
2149        let mut warned = false;
2150
2151        let got = send_stream_event(
2152            &client,
2153            &Attribution::ProjectOnly { project_id: pid },
2154            attribution_force(capture_binding.as_ref()),
2155            &req,
2156            &mut warned,
2157        )
2158        .await
2159        .expect("send_stream_event must succeed");
2160        assert_eq!(
2161            got.expect("a successful send returns a response").status,
2162            "accepted"
2163        );
2164
2165        let captured = rx
2166            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2167            .expect("no request captured");
2168        assert!(
2169            captured
2170                .to_lowercase()
2171                .contains("x-tracevault-project-attribution: explicit"),
2172            "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2173        );
2174    }
2175
2176    /// VIS-305 Part C review, Important finding 2: a LIVE force sitting on
2177    /// the machine-global user-level default must NOT leak onto a different,
2178    /// higher-precedence project that resolves instead. The old
2179    /// process-global `attribution_mode` couldn't tell the two apart — it
2180    /// declared `explicit` for ANY project as long as SOME force existed
2181    /// anywhere on disk. Here the user-default's force belongs to project A,
2182    /// but `TRACEVAULT_PROJECT` (a higher-precedence local tier) points this
2183    /// capture at project B, which was never forced.
2184    #[test]
2185    fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2186        use crate::session_state::{ProjectBinding, SessionState};
2187
2188        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2189        let tmp = tempfile::tempdir().unwrap();
2190        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2191        _guard.set("XDG_CONFIG_HOME", tmp.path());
2192        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2193
2194        let project_a = uuid::Uuid::from_u128(1);
2195        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2196        crate::user_project_default::save(&ProjectBinding {
2197            project_id: project_a.to_string(),
2198            project_name: "a".into(),
2199            updated_at: chrono::Utc::now().to_rfc3339(),
2200            forced_until: Some(future),
2201        })
2202        .unwrap();
2203
2204        let project_b = uuid::Uuid::from_u128(2);
2205        _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2206
2207        let capture_binding = capture_binding(&SessionState::default(), None);
2208        assert_eq!(
2209            capture_binding.as_ref().map(|b| b.project_id.as_str()),
2210            Some(project_b.to_string()).as_deref(),
2211            "TRACEVAULT_PROJECT must outrank the user-level default"
2212        );
2213
2214        assert_eq!(
2215            attribution_mode(capture_binding.as_ref()),
2216            AttributionMode::Derived,
2217            "a force on the user-default project must not leak onto a DIFFERENT, \
2218             higher-precedence project that never asked to be forced"
2219        );
2220    }
2221
2222    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
2223
2224    use std::io::BufReader;
2225    use std::net::TcpListener;
2226    use std::sync::mpsc;
2227    use std::thread;
2228    use std::time::{Duration, Instant};
2229
2230    /// How long an accept loop waits for a connection that never arrives
2231    /// (e.g. a regression that stops the client from making an expected
2232    /// request) before giving up, so the server thread exits cleanly
2233    /// instead of blocking in `accept()` forever.
2234    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2235
2236    /// Poll a non-blocking `listener` for a connection until one arrives or
2237    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
2238    /// `WouldBlock` accept error) so callers can stop cleanly rather than
2239    /// block forever.
2240    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2241        let deadline = Instant::now() + ACCEPT_DEADLINE;
2242        loop {
2243            match listener.accept() {
2244                Ok((stream, _)) => {
2245                    // The accepted stream's blocking mode isn't guaranteed to
2246                    // be inherited from the (non-blocking) listener across
2247                    // platforms — make it explicitly blocking so the
2248                    // subsequent read/write calls behave as before.
2249                    let _ = stream.set_nonblocking(false);
2250                    return Some(stream);
2251                }
2252                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2253                    if Instant::now() >= deadline {
2254                        return None;
2255                    }
2256                    thread::sleep(Duration::from_millis(20));
2257                }
2258                Err(_) => return None,
2259            }
2260        }
2261    }
2262
2263    /// How long a test waits for the captured request before failing (rather
2264    /// than hanging forever if the client never connects). Mirrors the
2265    /// harness in `tests/stream_event_project_test.rs`.
2266    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2267
2268    /// Read one request's line and headers off `stream`, hand the pair to
2269    /// `tx` as a single string, then write `response` back.
2270    ///
2271    /// Shared by [`spawn_once_capturing_request`] and
2272    /// [`spawn_n_capturing_requests`], which grew this same capture
2273    /// independently and disagreed only on `trim()` vs `trim_end()` for the
2274    /// blank-line terminator (equivalent, since a bare CRLF trims empty
2275    /// either way).
2276    ///
2277    /// Deliberately NOT `test_helpers::read_request`: that one is private to
2278    /// its module and blocks in `accept()`, where these two use
2279    /// `set_nonblocking` plus a deadline.
2280    ///
2281    /// Headers are captured, not just the request line, so a test can assert
2282    /// on `x-tracevault-project-attribution` — without them a regression that
2283    /// hardcoded `"derived"` at a `stream_event_for_project` call site would
2284    /// pass the whole suite, since nothing in-crate ever looked at the header
2285    /// actually sent. They are appended AFTER the request line, leaving
2286    /// `starts_with`/`contains` assertions on the line itself unaffected.
2287    fn capture_request_and_respond(
2288        stream: std::net::TcpStream,
2289        tx: &mpsc::Sender<String>,
2290        response: &str,
2291    ) {
2292        let mut reader = BufReader::new(stream);
2293        let mut captured = String::new();
2294        let _ = reader.read_line(&mut captured);
2295        loop {
2296            let mut header = String::new();
2297            if reader.read_line(&mut header).unwrap_or(0) == 0 {
2298                break;
2299            }
2300            if header.trim().is_empty() {
2301                break;
2302            }
2303            captured.push_str(&header);
2304        }
2305        let _ = tx.send(captured);
2306        let mut stream = reader.into_inner();
2307        let _ = stream.write_all(response.as_bytes());
2308        let _ = stream.flush();
2309    }
2310
2311    /// Spawn a one-shot server that returns `response` (a full HTTP response)
2312    /// to the first request, capturing it via
2313    /// [`capture_request_and_respond`]. Mirrors the harness in
2314    /// `tests/stream_event_project_test.rs` / `tests/resolve_remote_test.rs`.
2315    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2316        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2317        listener.set_nonblocking(true).unwrap();
2318        let addr = listener.local_addr().unwrap();
2319        let (tx, rx) = mpsc::channel();
2320        thread::spawn(move || {
2321            if let Some(stream) = accept_with_deadline(&listener) {
2322                capture_request_and_respond(stream, &tx, response);
2323            }
2324        });
2325        (format!("http://{addr}"), rx)
2326    }
2327
2328    fn ok_stream_response() -> String {
2329        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2330            session_db_id: uuid::Uuid::nil(),
2331            event_db_id: Some(uuid::Uuid::nil()),
2332            status: "accepted".to_string(),
2333        })
2334        .unwrap();
2335        format!(
2336            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2337            body.len(),
2338            body
2339        )
2340    }
2341
2342    fn sample_stream_event_request() -> StreamEventRequest {
2343        StreamEventRequest {
2344            protocol_version: 2,
2345            tool: Some("claude-code".to_string()),
2346            event_type: StreamEventType::ToolUse,
2347            session_id: "sess-1".into(),
2348            timestamp: chrono::Utc::now(),
2349            hook_event_name: Some("PostToolUse".into()),
2350            tool_name: None,
2351            tool_use_id: None,
2352            tool_input: None,
2353            tool_response: None,
2354            tool_is_error: None,
2355            event_index: None,
2356            event_uuid: None,
2357            transcript_lines: None,
2358            transcript_offset: None,
2359            model: None,
2360            cwd: None,
2361            final_stats: None,
2362            flow_id: None,
2363            labels: None,
2364            params: None,
2365        }
2366    }
2367
2368    /// With a `SessionState` whose `active_project` is set, `capture_project`
2369    /// resolves a `capture_pid`, and `send_stream_event` must route to the
2370    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
2371    /// than the repo-scoped one.
2372    #[tokio::test]
2373    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2374        use crate::session_state::{ProjectBinding, SessionState};
2375
2376        // Isolate from any ambient user-level project default so this test's
2377        // `capture_project` call depends only on the SessionState below —
2378        // mirrors the isolation pattern in `commands::project`'s tests.
2379        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2380        let tmp = tempfile::tempdir().unwrap();
2381        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2382        _guard.set("XDG_CONFIG_HOME", tmp.path());
2383        // `capture_project` reads `TRACEVAULT_PROJECT` above the
2384        // session-active tier asserted below — pin it unset. Ditto
2385        // `TRACEVAULT_PROJECT_ATTRIBUTION`, which the `derived` header
2386        // assertion at the end of this test depends on.
2387        _guard.remove("TRACEVAULT_PROJECT");
2388        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2389
2390        let pid = uuid::Uuid::from_u128(99);
2391        let session = SessionState {
2392            active_project: Some(ProjectBinding {
2393                project_id: pid.to_string(),
2394                project_name: "proj".into(),
2395                updated_at: "".into(),
2396                forced_until: None,
2397            }),
2398            ..Default::default()
2399        };
2400        let capture_binding = capture_binding(&session, None);
2401        let capture_pid = capture_binding
2402            .as_ref()
2403            .and_then(crate::resolution::capture_project_id);
2404        assert_eq!(capture_pid, Some(pid));
2405
2406        let resp = ok_stream_response();
2407        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2408        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2409        let req = sample_stream_event_request();
2410
2411        let mut warned = false;
2412        let got = send_stream_event(
2413            &client,
2414            &Attribution::Repo {
2415                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2416                project: capture_pid,
2417            },
2418            attribution_force(capture_binding.as_ref()),
2419            &req,
2420            &mut warned,
2421        )
2422        .await
2423        .expect("send_stream_event must succeed");
2424        assert_eq!(
2425            got.expect("a successful send returns a response").status,
2426            "accepted"
2427        );
2428
2429        let line = rx
2430            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2431            .expect("no request captured");
2432        assert!(
2433            line.starts_with(&format!(
2434                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2435            )),
2436            "an active project binding must route to the project-scoped endpoint, got: {line}"
2437        );
2438        // Covers the `Attribution::Repo { project: Some(_) }` call site of
2439        // `stream_event_for_project` (the `ProjectOnly` call site is covered
2440        // by `session_scoped_force_is_honoured_on_the_wire` and
2441        // `send_stream_event_project_only_omits_repo_id`) — an unforced
2442        // binding must still send the header, declaring `derived`.
2443        assert!(
2444            line.to_lowercase()
2445                .contains("x-tracevault-project-attribution: derived"),
2446            "got: {line}"
2447        );
2448    }
2449
2450    /// With an empty binding (default `SessionState`, no worktree override)
2451    /// and no user-level default present in the test env, `capture_project`
2452    /// resolves `None` and `send_stream_event` must fall back to the
2453    /// repo-scoped endpoint.
2454    #[tokio::test]
2455    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2456        use crate::session_state::SessionState;
2457
2458        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2459        let tmp = tempfile::tempdir().unwrap();
2460        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2461        // No user_project.toml under this isolated config dir, so there is no
2462        // ambient user-level default to leak in — and no `TRACEVAULT_PROJECT`
2463        // either, which `capture_project` would otherwise honour and turn
2464        // this "nothing resolves" case into a project-scoped send.
2465        _guard.set("XDG_CONFIG_HOME", tmp.path());
2466        _guard.remove("TRACEVAULT_PROJECT");
2467
2468        let capture_binding = capture_binding(&SessionState::default(), None);
2469        assert_eq!(capture_binding, None);
2470
2471        let resp = ok_stream_response();
2472        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2473        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2474        let req = sample_stream_event_request();
2475
2476        let mut warned = false;
2477        let got = send_stream_event(
2478            &client,
2479            &Attribution::Repo {
2480                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2481                project: None,
2482            },
2483            attribution_force(capture_binding.as_ref()),
2484            &req,
2485            &mut warned,
2486        )
2487        .await
2488        .expect("send_stream_event must succeed");
2489        assert_eq!(
2490            got.expect("a successful send returns a response").status,
2491            "accepted"
2492        );
2493
2494        let line = rx
2495            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2496            .expect("no request captured");
2497        assert!(
2498            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
2499            "no binding must fall back to the repo-scoped endpoint, got: {line}"
2500        );
2501    }
2502
2503    // ── I1/I2: refused project-scoped send is an error + transient no-fallback ───
2504
2505    /// Spawn a server that replies to up to `responses.len()` sequential
2506    /// connections with the given full HTTP responses, in order, capturing
2507    /// each request (line + headers, via [`capture_request_and_respond`])
2508    /// over the channel. The listening socket itself is dropped (closing it)
2509    /// once all responses have been served, so any further connection attempt
2510    /// fails fast (connection refused) rather than hanging for the client's
2511    /// request timeout — this lets a test assert "no further request was
2512    /// sent" cheaply.
2513    fn spawn_n_capturing_requests(
2514        responses: Vec<&'static str>,
2515    ) -> (String, mpsc::Receiver<String>) {
2516        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2517        listener.set_nonblocking(true).unwrap();
2518        let addr = listener.local_addr().unwrap();
2519        let (tx, rx) = mpsc::channel();
2520        thread::spawn(move || {
2521            for response in responses {
2522                // If a regression stops the client from making this request
2523                // (e.g. the expected Nth call never happens), don't block
2524                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
2525                // and let the thread end so the test process can't hang.
2526                let Some(stream) = accept_with_deadline(&listener) else {
2527                    break;
2528                };
2529                capture_request_and_respond(stream, &tx, response);
2530            }
2531            // `listener` (and `tx`) drop here, closing the socket and the
2532            // channel — a stray extra request gets ECONNREFUSED immediately
2533            // instead of hanging, and a stray extra `rx.recv` returns
2534            // Disconnected immediately instead of blocking.
2535        });
2536        (format!("http://{addr}"), rx)
2537    }
2538
2539    /// I1: a deterministic 400 ("is not a member of project ...") from the
2540    /// project-scoped endpoint must be an error, not a silent second send to
2541    /// the repo-scoped endpoint. TWO responses (400 then 200) are staged so
2542    /// the "no second request" check is non-vacuous — see the comment in
2543    /// `send_stream_event_project_only_drops_on_scoping_4xx` for why a single
2544    /// staged response would make that assertion pass vacuously.
2545    #[tokio::test]
2546    async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
2547        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
2548        let resp_400 = format!(
2549            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2550            body_400.len(),
2551            body_400
2552        );
2553        let resp_200 = ok_stream_response();
2554
2555        let (base, rx) = spawn_n_capturing_requests(vec![
2556            Box::leak(resp_400.into_boxed_str()),
2557            Box::leak(resp_200.into_boxed_str()),
2558        ]);
2559        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2560        let req = sample_stream_event_request();
2561        let pid = uuid::Uuid::from_u128(42);
2562
2563        let mut warned = false;
2564        let err = send_stream_event(
2565            &client,
2566            &Attribution::Repo {
2567                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2568                project: Some(pid),
2569            },
2570            attribution_force(None),
2571            &req,
2572            &mut warned,
2573        )
2574        .await
2575        .expect_err("a refused declared project must be an error, not a silent fallback");
2576        assert!(
2577            err.to_string().contains("400"),
2578            "propagated error must reflect the status, got: {err}"
2579        );
2580        assert!(
2581            warned,
2582            "the refusal must be printed (gated on `warned`) so it is visible"
2583        );
2584
2585        let first = rx
2586            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2587            .expect("no first request captured");
2588        assert!(
2589            first.contains(&format!("/projects/{pid}/stream")),
2590            "first request must hit the project-scoped endpoint, got: {first}"
2591        );
2592        assert!(
2593            first.contains("repo_id="),
2594            "first request must carry repo_id, got: {first}"
2595        );
2596
2597        assert!(
2598            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2599            "no second (repo-scoped fallback) request must be sent"
2600        );
2601    }
2602
2603    /// A 403 from the project-scoped endpoint must likewise be an error, not a
2604    /// silent second send to the repo-scoped endpoint.
2605    #[tokio::test]
2606    async fn send_stream_event_errors_on_403_without_fallback() {
2607        let body_403 = "forbidden";
2608        let resp_403 = format!(
2609            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2610            body_403.len(),
2611            body_403
2612        );
2613        let resp_200 = ok_stream_response();
2614
2615        let (base, rx) = spawn_n_capturing_requests(vec![
2616            Box::leak(resp_403.into_boxed_str()),
2617            Box::leak(resp_200.into_boxed_str()),
2618        ]);
2619        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2620        let req = sample_stream_event_request();
2621        let pid = uuid::Uuid::from_u128(43);
2622
2623        let mut warned = false;
2624        let err = send_stream_event(
2625            &client,
2626            &Attribution::Repo {
2627                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2628                project: Some(pid),
2629            },
2630            attribution_force(None),
2631            &req,
2632            &mut warned,
2633        )
2634        .await
2635        .expect_err("a refused declared project must be an error, not a silent fallback");
2636        assert!(
2637            err.to_string().contains("403"),
2638            "propagated error must reflect the status, got: {err}"
2639        );
2640        assert!(
2641            warned,
2642            "the refusal must be printed (gated on `warned`) so it is visible"
2643        );
2644
2645        let first = rx
2646            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2647            .expect("no first request captured");
2648        assert!(
2649            first.contains(&format!("/projects/{pid}/stream")),
2650            "first request must hit the project-scoped endpoint, got: {first}"
2651        );
2652        assert!(
2653            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2654            "no second (repo-scoped fallback) request must be sent"
2655        );
2656    }
2657
2658    /// The refusal error must be printed at most once per hook invocation
2659    /// (i.e. per shared `warned` flag), even across multiple calls sharing
2660    /// it — mirroring how the pending-flush loop and the live send share one
2661    /// `warned` for a single invocation.
2662    #[tokio::test]
2663    async fn refused_error_is_printed_once_per_invocation() {
2664        let body_400 = "not a member";
2665        let resp_400 = || {
2666            format!(
2667                "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2668                body_400.len(),
2669                body_400
2670            )
2671        };
2672        let (base, _rx) = spawn_n_capturing_requests(vec![
2673            Box::leak(resp_400().into_boxed_str()),
2674            Box::leak(resp_400().into_boxed_str()),
2675        ]);
2676        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2677        let req = sample_stream_event_request();
2678        let pid = uuid::Uuid::from_u128(44);
2679        let attribution = Attribution::Repo {
2680            repo_id: "11111111-1111-1111-1111-111111111111".into(),
2681            project: Some(pid),
2682        };
2683
2684        let mut warned = false;
2685        assert!(
2686            send_stream_event(
2687                &client,
2688                &attribution,
2689                attribution_force(None),
2690                &req,
2691                &mut warned
2692            )
2693            .await
2694            .is_err(),
2695            "a refused declared project must be an error"
2696        );
2697        assert!(warned, "the flag must be set after the first refusal");
2698
2699        assert!(
2700            send_stream_event(
2701                &client,
2702                &attribution,
2703                attribution_force(None),
2704                &req,
2705                &mut warned
2706            )
2707            .await
2708            .is_err(),
2709            "a second refusal must also be an error"
2710        );
2711        assert!(warned, "the flag stays set across the shared invocation");
2712    }
2713
2714    /// Finding 5's scenario end to end, on the repo-bound path, as VIS-316
2715    /// leaves it: a live persisted force makes this send declare `explicit`,
2716    /// the force gate refuses it with a 403 — and the event is now an ERROR
2717    /// queued for retry, never re-sent to the repo-scoped endpoint where the
2718    /// server would DEDUCE a project that is precisely not the one the
2719    /// operator forced.
2720    ///
2721    /// Pins the fact the refusal clause depends on: the mode that went on
2722    /// the wire really is `explicit`, and it is the same value
2723    /// `refused_error` is handed — the message and the wire cannot disagree.
2724    /// A spare 200 is staged so "no second request" is non-vacuous.
2725    #[tokio::test]
2726    async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
2727        let body_403 = "forbidden";
2728        let resp_403 = format!(
2729            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2730            body_403.len(),
2731            body_403
2732        );
2733        let resp_200 = ok_stream_response();
2734
2735        let (base, rx) = spawn_n_capturing_requests(vec![
2736            Box::leak(resp_403.into_boxed_str()),
2737            Box::leak(resp_200.into_boxed_str()),
2738        ]);
2739        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2740        let req = sample_stream_event_request();
2741        let pid = uuid::Uuid::from_u128(42);
2742
2743        // A live persisted force on the winning binding — no env var needed,
2744        // so this test takes no env lock.
2745        let forced = crate::session_state::ProjectBinding {
2746            project_id: pid.to_string(),
2747            project_name: "forced".into(),
2748            updated_at: "".into(),
2749            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
2750        };
2751
2752        let mut warned = false;
2753        let err = send_stream_event(
2754            &client,
2755            &Attribution::Repo {
2756                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2757                project: Some(pid),
2758            },
2759            attribution_force(Some(&forced)),
2760            &req,
2761            &mut warned,
2762        )
2763        .await
2764        .expect_err("a refused force must be an error, not a silent fallback");
2765        assert!(
2766            err.to_string().contains("403"),
2767            "propagated error must reflect the status, got: {err}"
2768        );
2769        assert!(warned, "the refusal must be printed exactly once");
2770
2771        let first = rx
2772            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2773            .expect("no first request captured");
2774        assert!(
2775            first.contains(&format!("/projects/{pid}/stream")),
2776            "first request must hit the project-scoped endpoint, got: {first}"
2777        );
2778        assert!(
2779            first
2780                .to_lowercase()
2781                .contains("x-tracevault-project-attribution: explicit"),
2782            "the refused send must have DECLARED explicit — this is the mode \
2783             `refused_error` is handed: {first}"
2784        );
2785
2786        assert!(
2787            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2788            "a refused force must NOT be re-attributed via the repo-scoped endpoint"
2789        );
2790    }
2791
2792    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
2793    /// project endpoint with NO `repo_id` query pair. This is the wire shape
2794    /// the server documents as "repo-less (0-repo) projects are supported".
2795    ///
2796    /// Takes the env lock and pins `TRACEVAULT_PROJECT_ATTRIBUTION` unset:
2797    /// this test also asserts the `derived` attribution header, and
2798    /// `attribution_mode` reads that variable even when the binding passed
2799    /// in is `None`.
2800    #[tokio::test]
2801    async fn send_stream_event_project_only_omits_repo_id() {
2802        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2803        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2804        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2805
2806        let resp = ok_stream_response();
2807        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2808        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2809        let req = sample_stream_event_request();
2810        let pid = uuid::Uuid::from_u128(11);
2811
2812        let mut warned = false;
2813        let got = send_stream_event(
2814            &client,
2815            &Attribution::ProjectOnly { project_id: pid },
2816            attribution_force(None),
2817            &req,
2818            &mut warned,
2819        )
2820        .await
2821        .expect("a repo-less project send must succeed");
2822        assert_eq!(
2823            got.expect("a successful send returns a response").status,
2824            "accepted"
2825        );
2826
2827        let line = rx
2828            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2829            .expect("no request captured");
2830        assert!(
2831            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
2832            "expected a bare project path with no query string, got: {line}"
2833        );
2834        assert!(
2835            line.to_lowercase()
2836                .contains("x-tracevault-project-attribution: derived"),
2837            "with no forced binding, the header must declare `derived`, got: {line}"
2838        );
2839        assert!(
2840            !warned,
2841            "a repo-less send has no fallback and must not warn about one"
2842        );
2843    }
2844
2845    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
2846    /// the queue is keyed by the very project id the server says does not
2847    /// resolve, so a corrected binding writes to a different file and these
2848    /// events would never be retried — they would just accumulate, one per
2849    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
2850    /// trigger a second, impossible request.
2851    #[tokio::test]
2852    async fn send_stream_event_project_only_drops_on_scoping_4xx() {
2853        let body = "no such project";
2854        let resp_404 = format!(
2855            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2856            body.len(),
2857            body
2858        );
2859        // TWO responses are staged although only one request is expected. With
2860        // a single response the helper drops its sender the moment the list is
2861        // exhausted, so the "no second request" assertion below would pass on
2862        // `Disconnected` whether or not a second request happened — a vacuous
2863        // check. Staging a spare keeps the server accepting, so a stray
2864        // request really is captured and really fails the test.
2865        let (base, rx) = spawn_n_capturing_requests(vec![
2866            Box::leak(resp_404.clone().into_boxed_str()),
2867            Box::leak(resp_404.into_boxed_str()),
2868        ]);
2869        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2870        let req = sample_stream_event_request();
2871        let pid = uuid::Uuid::from_u128(12);
2872
2873        let mut warned = false;
2874        let got = send_stream_event(
2875            &client,
2876            &Attribution::ProjectOnly { project_id: pid },
2877            attribution_force(None),
2878            &req,
2879            &mut warned,
2880        )
2881        .await
2882        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
2883        assert!(
2884            got.is_none(),
2885            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
2886        );
2887        assert!(
2888            warned,
2889            "dropping data silently is the failure mode to avoid"
2890        );
2891
2892        let first = rx
2893            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2894            .expect("no request captured");
2895        assert!(
2896            first.contains(&format!("/projects/{pid}/stream")),
2897            "must hit the project-scoped endpoint, got: {first}"
2898        );
2899        assert!(
2900            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2901            "a repo-less send must make exactly one request — no fallback exists"
2902        );
2903    }
2904
2905    /// A 403 is NOT dropped. It can mean the account has no `tracevault` grant,
2906    /// which an administrator can grant — after which the buffered events do
2907    /// deliver. It must propagate so the caller queues them.
2908    #[tokio::test]
2909    async fn send_stream_event_project_only_buffers_on_403() {
2910        let body = "forbidden";
2911        let resp_403 = format!(
2912            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2913            body.len(),
2914            body
2915        );
2916        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
2917        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2918        let req = sample_stream_event_request();
2919
2920        let mut warned = false;
2921        let err = send_stream_event(
2922            &client,
2923            &Attribution::ProjectOnly {
2924                project_id: uuid::Uuid::from_u128(13),
2925            },
2926            attribution_force(None),
2927            &req,
2928            &mut warned,
2929        )
2930        .await
2931        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
2932        assert!(
2933            err.to_string().contains("403"),
2934            "propagated error must reflect the status, got: {err}"
2935        );
2936    }
2937
2938    /// I2: a transient 503 from the project-scoped endpoint must propagate as
2939    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
2940    /// existing buffer/retry logic in `run_stream` still handles it. Only one
2941    /// request (to the project endpoint) may be observed.
2942    #[tokio::test]
2943    async fn send_stream_event_does_not_fall_back_on_transient_503() {
2944        let body_503 = "internal error";
2945        let resp_503 = format!(
2946            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2947            body_503.len(),
2948            body_503
2949        );
2950        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
2951        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2952        let req = sample_stream_event_request();
2953        let pid = uuid::Uuid::from_u128(7);
2954
2955        let mut warned = false;
2956        let err = send_stream_event(
2957            &client,
2958            &Attribution::Repo {
2959                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2960                project: Some(pid),
2961            },
2962            attribution_force(None),
2963            &req,
2964            &mut warned,
2965        )
2966        .await
2967        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
2968        assert!(
2969            err.to_string().contains("503"),
2970            "propagated error must reflect the transient status, got: {err}"
2971        );
2972        assert!(
2973            deterministic_client_error_kind(err.as_ref()).is_none(),
2974            "a 503 must not be classified as a deterministic client error"
2975        );
2976
2977        let first = rx
2978            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2979            .expect("no request captured");
2980        assert!(
2981            first.contains(&format!("/projects/{pid}/stream")),
2982            "must hit the project-scoped endpoint, got: {first}"
2983        );
2984
2985        // The mock server only serves ONE response and then drops its
2986        // listener/sender — a stray fallback request would either fail the
2987        // `expect_err` above (if it somehow succeeded) or, if it also failed,
2988        // would still mean a second request was attempted. Confirming the
2989        // channel is immediately disconnected (rather than blocking) proves
2990        // no second request was ever sent.
2991        assert!(
2992            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
2993            "no second (fallback) request should have been sent for a transient error"
2994        );
2995    }
2996
2997    /// A 403 must be classified apart from the binding/scoping statuses: since
2998    /// Keycloak it has a second, now more common cause (no `tracevault` grant
2999    /// at all) whose advice is completely different.
3000    #[test]
3001    fn a_403_is_classified_apart_from_the_scoping_statuses() {
3002        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3003        assert_eq!(
3004            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3005            Some(ClientErrorKind::Forbidden)
3006        );
3007        for scoping in [
3008            "Stream failed (400 Bad Request): {}",
3009            "Stream failed (404 Not Found): {}",
3010            "Stream failed (409 Conflict): {}",
3011        ] {
3012            assert_eq!(
3013                deterministic_client_error_kind(err(scoping).as_ref()),
3014                Some(ClientErrorKind::Scoping),
3015                "{scoping}"
3016            );
3017        }
3018        // Unchanged: 401 and transient failures are not deterministic client
3019        // errors and must keep propagating to buffer/retry.
3020        for transient in [
3021            "Stream failed (401 Unauthorized): {}",
3022            "Stream failed (503 Service Unavailable): {}",
3023            "error sending request for url (http://x/stream)",
3024        ] {
3025            assert_eq!(
3026                deterministic_client_error_kind(err(transient).as_ref()),
3027                None,
3028                "{transient}"
3029            );
3030        }
3031    }
3032
3033    /// The 403 error must not tell a user whose account has no `tracevault` grant
3034    /// to switch projects, which cannot possibly help. It names both causes,
3035    /// and — since the CLI no longer re-attributes to another project — must
3036    /// never claim it did.
3037    #[test]
3038    fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3039        let pid = uuid::Uuid::from_u128(7);
3040
3041        let forbidden = refused_error(
3042            pid,
3043            &ClientErrorKind::Forbidden,
3044            AttributionForce::default(),
3045        );
3046        assert!(forbidden.contains("403"), "{forbidden}");
3047        assert!(
3048            forbidden.contains("no `tracevault` grant in Control Plane"),
3049            "must offer the missing-role explanation: {forbidden}"
3050        );
3051        assert!(
3052            forbidden.contains("no `Operator` role on it"),
3053            "must still offer the project explanation: {forbidden}"
3054        );
3055        assert!(
3056            forbidden.starts_with("tracevault: error:"),
3057            "a refusal is an error, not a warning: {forbidden}"
3058        );
3059        assert!(forbidden.contains(&pid.to_string()));
3060
3061        // A 400/404/409 genuinely IS a binding problem, so that wording stays
3062        // unhedged — hedging everything would dilute the useful case.
3063        let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3064        assert!(scoping.contains("project switch"), "{scoping}");
3065        assert!(
3066            !scoping.contains("`tracevault` grant"),
3067            "the scoping case must not mention the `tracevault` grant: {scoping}"
3068        );
3069
3070        for s in [&forbidden, &scoping] {
3071            // A machine-wide default is rebound with `--user`; without the
3072            // hint, `project switch` in a session only shadows it.
3073            assert!(s.contains("--user"), "must name the --user fix: {s}");
3074            assert!(
3075                s.contains("user_project.toml"),
3076                "must name the machine-wide default's file: {s}"
3077            );
3078            assert!(
3079                !s.contains("repo deduction"),
3080                "must never describe re-attribution to another project: {s}"
3081            );
3082            assert!(
3083                !s.contains("Attributing via"),
3084                "must never claim the event was re-attributed: {s}"
3085            );
3086        }
3087    }
3088
3089    /// VIS-305 whole-branch review, Important finding 5: a REFUSED FORCE
3090    /// said nothing about the force. The 403 the force gate returns for "not
3091    /// Operator on the project" or "`explicit` from a `tvk_` key" is
3092    /// indistinguishable from here (see `ClientErrorKind`) from a membership
3093    /// 403, so an operator who asked for `explicit` got a message about
3094    /// membership and realm roles and was never told the force itself was
3095    /// what got refused. Failing closed on trust is right; failing closed
3096    /// silently is the defect. (VIS-316 made the refusal an error rather
3097    /// than a fallback; the missing explanation is orthogonal to that and
3098    /// still has to be given.)
3099    #[test]
3100    fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3101        let pid = uuid::Uuid::from_u128(7);
3102
3103        let explicit = refused_error(
3104            pid,
3105            &ClientErrorKind::Forbidden,
3106            AttributionForce {
3107                env: false,
3108                binding: true,
3109            },
3110        );
3111        assert!(
3112            explicit.contains("FORCE"),
3113            "the refusal of the force itself must be named: {explicit}"
3114        );
3115        assert!(
3116            explicit.contains("Operator"),
3117            "must name the grant forcing requires: {explicit}"
3118        );
3119        assert!(
3120            explicit.contains("Control Plane"),
3121            "must name the identity forcing requires: {explicit}"
3122        );
3123        // `main`'s Forbidden wording is ADDED TO, not replaced: the
3124        // membership causes it already names must survive alongside the
3125        // force clause.
3126        assert!(
3127            explicit.contains("`tracevault` grant")
3128                && explicit.contains("no `Operator` role on it"),
3129            "the membership causes must still be named: {explicit}"
3130        );
3131        // The event is queued, not re-attributed — the force clause must not
3132        // reintroduce the claim VIS-316 removed.
3133        assert!(
3134            !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3135            "must never claim the event was re-attributed: {explicit}"
3136        );
3137
3138        // Same 403, `derived` mode: no force was asked for, so none was
3139        // refused and the clause must not appear. This is the discriminating
3140        // half — without it the test would pass on a message that blamed the
3141        // force unconditionally, which is just a different wrong story.
3142        let derived = refused_error(
3143            pid,
3144            &ClientErrorKind::Forbidden,
3145            AttributionForce::default(),
3146        );
3147        assert!(
3148            !derived.contains("FORCE"),
3149            "a `derived` send never forced anything: {derived}"
3150        );
3151    }
3152
3153    /// The force clause belongs to the 403 the force gate returns, and to
3154    /// nothing else: a 400/404/409 means the project id does not resolve, so
3155    /// the gate never ran. Blaming the force there would be a new wrong
3156    /// explanation of the same family as the one finding 5 reports.
3157    #[test]
3158    fn an_explicit_scoping_failure_does_not_blame_the_force() {
3159        let pid = uuid::Uuid::from_u128(7);
3160        let scoping = refused_error(
3161            pid,
3162            &ClientErrorKind::Scoping,
3163            AttributionForce {
3164                env: true,
3165                binding: true,
3166            },
3167        );
3168        assert!(!scoping.contains("FORCE"), "{scoping}");
3169        assert_eq!(
3170            scoping,
3171            refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3172            "the scoping wording does not depend on the mode"
3173        );
3174    }
3175
3176    /// Copilot on PR #54: the remediation told EVERY forced sender to switch
3177    /// again without `--project-attribution explicit`. That clears a
3178    /// persisted `forced_until` and nothing else — so when the force came
3179    /// from `TRACEVAULT_PROJECT_ATTRIBUTION`, [`attribution_force`] goes on
3180    /// reading the environment, every later send still declares `explicit`,
3181    /// and the advice silently does nothing. On the one code path a confused
3182    /// operator reaches.
3183    ///
3184    /// Each case is driven through `attribution_force` and a REAL exported
3185    /// variable rather than a hand-built struct, so what this pins is the
3186    /// whole path: the value that decides the header is the value the
3187    /// wording is derived from, and the two cannot describe different
3188    /// worlds.
3189    ///
3190    /// Discriminating in both directions — each case asserts the fix that
3191    /// applies AND the absence of the one that doesn't — because a message
3192    /// that simply listed both remediations every time would pass a
3193    /// one-sided test while being the same "advice that may not apply"
3194    /// defect in a longer form.
3195    #[test]
3196    fn the_403_remediation_names_the_force_source_actually_in_effect() {
3197        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3198        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3199        let pid = uuid::Uuid::from_u128(7);
3200        let live = forced_binding(Some(
3201            &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3202        ));
3203        let never_forced = forced_binding(None);
3204
3205        // ENV ONLY. The binding carries no force at all, so "switch again
3206        // without the flag" would change precisely nothing: the next send
3207        // reads the same variable and declares `explicit` again.
3208        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3209        let env_only = refused_error(
3210            pid,
3211            &ClientErrorKind::Forbidden,
3212            attribution_force(Some(&never_forced)),
3213        );
3214        assert!(
3215            env_only.contains("FORCE"),
3216            "an env-sourced force is still a force: {env_only}"
3217        );
3218        assert!(
3219            env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3220            "must name the variable that is doing the forcing: {env_only}"
3221        );
3222        assert!(
3223            !env_only.contains("--project-attribution"),
3224            "must NOT tell the operator to drop a flag that would change \
3225             nothing here — this is the bug: {env_only}"
3226        );
3227
3228        // BINDING ONLY. Now the flag advice is the right one, and naming the
3229        // env var would send the operator hunting for an export that isn't
3230        // set.
3231        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3232        let binding_only = refused_error(
3233            pid,
3234            &ClientErrorKind::Forbidden,
3235            attribution_force(Some(&live)),
3236        );
3237        assert!(
3238            binding_only.contains("--project-attribution"),
3239            "a persisted force IS cleared by switching without the flag: {binding_only}"
3240        );
3241        assert!(
3242            !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3243            "must not send the operator after an unset variable: {binding_only}"
3244        );
3245
3246        // BOTH. Removing either one alone leaves the other forcing, which
3247        // would look exactly like the fix not working — so the message has
3248        // to say both must go.
3249        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3250        let both = refused_error(
3251            pid,
3252            &ClientErrorKind::Forbidden,
3253            attribution_force(Some(&live)),
3254        );
3255        assert!(
3256            both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3257                && both.contains("--project-attribution"),
3258            "both sources are in effect and both must be named: {both}"
3259        );
3260        assert!(
3261            both.contains("BOTH"),
3262            "must say that removing only one is not enough: {both}"
3263        );
3264    }
3265
3266    /// The remediation is built from the same `AttributionForce` the header
3267    /// is, so it can never describe a force the send did not declare: with
3268    /// no source set there is no force clause at all, whatever the wording
3269    /// of the fixes would have been.
3270    #[test]
3271    fn no_force_means_no_remediation_clause() {
3272        let pid = uuid::Uuid::from_u128(7);
3273        let none = refused_error(
3274            pid,
3275            &ClientErrorKind::Forbidden,
3276            AttributionForce::default(),
3277        );
3278        assert!(
3279            !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3280                && !none.contains("--project-attribution"),
3281            "a derived send has no force to remove: {none}"
3282        );
3283    }
3284}