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        billing_mode: Some(crate::billing::detect_current(
1074            agent,
1075            hook_cwd,
1076            &hook_event.transcript_path,
1077        )),
1078    };
1079
1080    stamp_agent(&mut req, agent);
1081
1082    req.truncate_large_fields();
1083
1084    // 6. Resolve credentials
1085    let (server_url, credential) = crate::credentials::resolve_credentials_quiet(&project_root)?;
1086
1087    // 7. Config (loaded above, alongside the user-level context layer
1088    // resolution) no longer directly gates repo_id — a missing config is not
1089    // fatal on its own, since the repo may instead resolve via the
1090    // workspace-mode precedence chain (session binding / subagent worktree
1091    // override) below. A malformed config is still surfaced here — that's
1092    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
1093    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
1094    // below).
1095    if let Err(e) = &config {
1096        return Err(format!("malformed .tracevault/config.toml: {e}").into());
1097    }
1098
1099    // Resolve the effective repo binding (workspace/detached mode). Bound
1100    // mode (a pinned config.toml) still works — it's the lowest-precedence
1101    // tier, wired below via `binding_from_config`, fed from the `config`
1102    // already loaded above (no second read of config.toml on this hot path).
1103    let session = crate::session_state::load(&hook_event.session_id);
1104    let bound = config
1105        .as_ref()
1106        .ok()
1107        .and_then(|opt| opt.as_ref())
1108        .and_then(crate::resolution::binding_from_config);
1109    let user_default = crate::user_default::load();
1110    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
1111    // Graceful no-op, exactly like the hook's normal success path. Do NOT
1112    // error: a failing hook would block the tool.
1113    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
1114        let response = HookResponse::allow();
1115        println!("{}", serde_json::to_string(&response)?);
1116        Ok(())
1117    };
1118    // Explicit local project binding (if any) overrides server-side repo
1119    // deduction. Computed BEFORE the attribution gate below, reusing the
1120    // already-loaded session + worktree used just above for the repo-binding
1121    // resolution: a repo-less session is attributable by project alone, so the
1122    // project must be known before deciding whether this event can be sent.
1123    // The full binding (not just its id) is resolved: `attribution_mode`
1124    // reads its `forced_until`, and this is the binding that actually decided
1125    // the target project, so it's the only one whose force is allowed to
1126    // apply (see `attribution_mode`'s doc comment).
1127    let capture_binding = capture_binding(&session, Some(worktree_top.as_str()));
1128    let capture_pid = capture_binding
1129        .as_ref()
1130        .and_then(crate::resolution::capture_project_id);
1131    // Resolved once per invocation, not per event — the binding is invariant
1132    // across the pending-flush loop and the live send below, while the
1133    // evaluation costs an env read and an RFC3339 parse. `commands::flush`
1134    // resolves it once per queue for the same reason. The whole
1135    // `AttributionForce` travels, not just its mode: a refusal has to name
1136    // the force source it is telling the operator to remove.
1137    let force = attribution_force(capture_binding.as_ref());
1138
1139    // Ship if EITHER a repo or a project resolved; no-op only when neither
1140    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
1141    // session-state file whose repo_id could carry path separators into the
1142    // pending filename — such a binding degrades to project-only inside
1143    // `attribution_for` rather than dropping the event.)
1144    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
1145        no_op_allow()?;
1146        return Ok(());
1147    };
1148
1149    // 8. Create ApiClient
1150    let server_url = server_url.ok_or("server_url not configured")?;
1151    let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
1152
1153    // 9. Try drain pending queue and send
1154    let pending_path = pending_path_for(&session_dir, &attribution);
1155    let pending_events = drain_pending(&pending_path)?;
1156
1157    let mut send_failed = false;
1158    // Spans the whole invocation (pending-flush loop + live send below) so a
1159    // refused project binding prints its error at most once per invocation,
1160    // not once per buffered event.
1161    let mut warned = false;
1162
1163    // Send pending events first
1164    for (i, pending_json) in pending_events.iter().enumerate() {
1165        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
1166            if send_stream_event(&client, &attribution, force, &pending_req, &mut warned)
1167                .await
1168                .is_err()
1169            {
1170                // Re-queue only the failed event and the ones after it that
1171                // were never attempted, in order. Events before `i` already
1172                // got a server response and must NOT be re-queued here — a
1173                // prior iteration already appended them if IT failed, and if
1174                // it succeeded, re-adding them would deliver them twice on
1175                // the next drain.
1176                for evt in &pending_events[i..] {
1177                    append_pending(&pending_path, evt)?;
1178                }
1179                send_failed = true;
1180                break;
1181            }
1182        }
1183    }
1184
1185    // Send current event
1186    let req_json = serde_json::to_string(&req)?;
1187    // The inline (OpenCode) path CONSUMES its records from the hook event — they
1188    // are not re-readable like a transcript file — so its `.stream_offset` record
1189    // counter must advance whenever the event is accepted for delivery, INCLUDING
1190    // when it is queued after a failure. Otherwise the next inline event reuses
1191    // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
1192    // queued request already carries this event's `transcript_offset`, so the
1193    // records keep their indices on drain. (File-based agents must NOT advance on
1194    // failure: their next read re-covers these lines cumulatively/idempotently.)
1195    if send_failed {
1196        append_pending(&pending_path, &req_json)?;
1197        if is_inline {
1198            fs::write(&offset_path, new_offset.to_string())?;
1199        }
1200    } else {
1201        match send_stream_event(&client, &attribution, force, &req, &mut warned).await {
1202            Ok(_) => {
1203                // 10. On success update .stream_offset
1204                fs::write(&offset_path, new_offset.to_string())?;
1205            }
1206            Err(_) => {
1207                // 11. On failure append to pending.jsonl (advance the inline
1208                // record counter regardless — see the note above).
1209                append_pending(&pending_path, &req_json)?;
1210                if is_inline {
1211                    fs::write(&offset_path, new_offset.to_string())?;
1212                }
1213            }
1214        }
1215    }
1216
1217    // 12. Always print HookResponse::allow() to stdout
1218    let response = HookResponse::allow();
1219    println!("{}", serde_json::to_string(&response)?);
1220
1221    Ok(())
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226    use super::*;
1227    use crate::api_client::AttributionMode;
1228    use crate::config::UserContext;
1229    use crate::context::{Context, EffectiveContext};
1230    use std::collections::BTreeMap;
1231
1232    // ── user layer resolution: disabled config → no user layer ────────────────
1233
1234    #[test]
1235    fn disabled_user_context_resolves_to_none() {
1236        // Default/disabled `user_context` (the `Toggle(false)` variant) must
1237        // resolve to `None`, matching the pre-existing hook behavior of
1238        // stamping without a user layer when it isn't configured.
1239        assert!(UserContext::Toggle(false).resolve().is_none());
1240    }
1241
1242    #[test]
1243    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
1244        // With no user layer and no global/worktree context files present,
1245        // `Context::effective` must yield a default (empty) `EffectiveContext`
1246        // — i.e. passing `None` for `user_layer` is behavior-preserving.
1247        let dir = tempfile::tempdir().unwrap();
1248        let effective = Context::effective(dir.path(), None);
1249        assert_eq!(effective, EffectiveContext::default());
1250    }
1251
1252    // ── apply_context: all three fields populated ─────────────────────────────
1253
1254    #[test]
1255    fn apply_context_stamps_all_fields() {
1256        let dir = tempfile::tempdir().unwrap();
1257        let mut params = BTreeMap::new();
1258        params.insert("env".to_string(), "prod".to_string());
1259        params.insert("region".to_string(), "eu-west-1".to_string());
1260
1261        let ctx = EffectiveContext {
1262            flow_id: Some("flow-xyz".to_string()),
1263            labels: vec!["backend".to_string(), "urgent".to_string()],
1264            params,
1265        };
1266
1267        let (flow_id, labels, params_out) = apply_context(ctx);
1268
1269        assert_eq!(flow_id, Some("flow-xyz".to_string()));
1270        assert_eq!(
1271            labels,
1272            Some(vec!["backend".to_string(), "urgent".to_string()])
1273        );
1274        let p = params_out.expect("params should be Some");
1275        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
1276        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
1277
1278        // Verify the stored context round-trips through save_to → load_from →
1279        // merge_layers → apply_context (stored params are now `Option<String>`).
1280        let written = Context {
1281            flow_id: Some("flow-xyz".to_string()),
1282            labels: vec!["backend".to_string(), "urgent".to_string()],
1283            params: {
1284                let mut m = BTreeMap::new();
1285                m.insert("env".to_string(), Some("prod".to_string()));
1286                m.insert("region".to_string(), Some("eu-west-1".to_string()));
1287                m
1288            },
1289        };
1290        let ctx_path = dir.path().join(".tracevault").join("context.json");
1291        written.save_to(&ctx_path).unwrap();
1292        let loaded = Context::load_from(&ctx_path);
1293        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
1294        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
1295        assert!(labels2.is_some());
1296        assert!(params2.is_some());
1297    }
1298
1299    // ── apply_context: missing context file → all None ────────────────────────
1300
1301    #[test]
1302    fn apply_context_missing_file_all_none() {
1303        let dir = tempfile::tempdir().unwrap();
1304        let missing_path = dir.path().join(".tracevault").join("context.json");
1305        let ctx = Context::load_from(&missing_path); // no context.json → default
1306        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
1307        assert!(flow_id.is_none(), "flow_id should be None");
1308        assert!(labels.is_none(), "labels should be None");
1309        assert!(params.is_none(), "params should be None");
1310    }
1311
1312    // ── apply_context: empty labels vec / empty params map → None ─────────────
1313
1314    #[test]
1315    fn apply_context_empty_collections_are_none() {
1316        let ctx = EffectiveContext {
1317            flow_id: None,
1318            labels: vec![],
1319            params: BTreeMap::new(),
1320        };
1321        let (flow_id, labels, params) = apply_context(ctx);
1322        assert!(flow_id.is_none());
1323        assert!(
1324            labels.is_none(),
1325            "empty labels should be None, not Some([])"
1326        );
1327        assert!(
1328            params.is_none(),
1329            "empty params should be None, not Some({{}})"
1330        );
1331    }
1332
1333    // ── apply_context: flow_id only, collections empty ────────────────────────
1334
1335    #[test]
1336    fn apply_context_flow_id_only() {
1337        let ctx = EffectiveContext {
1338            flow_id: Some("my-flow".to_string()),
1339            labels: vec![],
1340            params: BTreeMap::new(),
1341        };
1342        let (flow_id, labels, params) = apply_context(ctx);
1343        assert_eq!(flow_id, Some("my-flow".to_string()));
1344        assert!(labels.is_none());
1345        assert!(params.is_none());
1346    }
1347
1348    // ── resolve_session_paths tests ───────────────────────────────────────────
1349    //
1350    // These tests verify that `resolve_session_paths` routes through the
1351    // git-aware resolver so that sibling linked worktrees capture events under
1352    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
1353
1354    use crate::test_helpers::{add_worktree, init_git_repo};
1355
1356    /// Primary checkout: project_root resolves to the repo root; session_dir is
1357    /// under `<repo>/.tracevault/sessions/<id>/`.
1358    #[test]
1359    fn resolve_session_paths_primary_checkout() {
1360        let tmp = tempfile::tempdir().unwrap();
1361        let repo = tmp.path().join("repo");
1362        std::fs::create_dir_all(&repo).unwrap();
1363        init_git_repo(&repo);
1364        // Create a .tracevault/ in the primary root to match a real init.
1365        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1366
1367        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
1368        let project_root = resolved.root;
1369
1370        assert_eq!(
1371            project_root.canonicalize().unwrap(),
1372            repo.canonicalize().unwrap(),
1373            "primary checkout: project_root must be repo root"
1374        );
1375        assert_eq!(
1376            session_dir.canonicalize().unwrap_or(session_dir.clone()),
1377            repo.join(".tracevault")
1378                .join("sessions")
1379                .join("sess-primary-123"),
1380            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1381        );
1382        // session_dir must be INSIDE the primary repo, not elsewhere.
1383        assert!(
1384            session_dir.starts_with(&repo),
1385            "session_dir must be under the primary repo root"
1386        );
1387    }
1388
1389    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1390    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1391    /// git-aware resolver must return the PRIMARY root.
1392    #[test]
1393    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1394        let tmp = tempfile::tempdir().unwrap();
1395        let repo = tmp.path().join("repo");
1396        // Sibling worktree lives outside the primary repo directory.
1397        let wt = tmp.path().join("sibling-wt");
1398
1399        std::fs::create_dir_all(&repo).unwrap();
1400        init_git_repo(&repo);
1401        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1402        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1403        add_worktree(&repo, &wt);
1404
1405        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1406        let project_root = resolved.root;
1407
1408        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1409        assert_eq!(
1410            project_root.canonicalize().unwrap(),
1411            repo.canonicalize().unwrap(),
1412            "sibling worktree: project_root must be primary repo root (not worktree dir)"
1413        );
1414        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1415        assert!(
1416            session_dir.starts_with(&repo),
1417            "sibling worktree: session_dir must be under the PRIMARY repo root"
1418        );
1419        assert!(
1420            !session_dir.starts_with(&wt),
1421            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1422        );
1423        assert!(
1424            session_dir.ends_with(
1425                std::path::Path::new(".tracevault")
1426                    .join("sessions")
1427                    .join("sess-sibling-456")
1428            ),
1429            "session_dir must end with .tracevault/sessions/<session_id>"
1430        );
1431    }
1432
1433    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1434    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1435    #[test]
1436    fn resolve_session_paths_non_git_fallback() {
1437        let tmp = tempfile::tempdir().unwrap();
1438        // No git repo, no .tracevault/ anywhere.
1439        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1440        let project_root = resolved.root;
1441
1442        assert_eq!(
1443            project_root,
1444            tmp.path(),
1445            "non-git: project_root must fall back to hook_cwd"
1446        );
1447        assert_eq!(
1448            session_dir,
1449            tmp.path()
1450                .join(".tracevault")
1451                .join("sessions")
1452                .join("sess-fallback-789"),
1453            "non-git: session_dir must be relative to the fallback root"
1454        );
1455    }
1456
1457    /// The origin marker written by run_stream contains the worktree toplevel.
1458    /// This test exercises the same `paths::worktree_toplevel` helper the hook
1459    /// uses (can't call run_stream end-to-end without a real server) so the
1460    /// marker content is computed and canonicalized exactly as in production.
1461    #[test]
1462    fn origin_marker_written_in_session_dir() {
1463        let tmp = tempfile::tempdir().unwrap();
1464        let repo = tmp.path().join("repo");
1465        std::fs::create_dir_all(&repo).unwrap();
1466        init_git_repo(&repo);
1467
1468        let session_dir = repo
1469            .join(".tracevault")
1470            .join("sessions")
1471            .join("test-sess-001");
1472        std::fs::create_dir_all(&session_dir).unwrap();
1473
1474        let hook_cwd = &repo;
1475        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1476        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1477
1478        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1479        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1480        assert_eq!(
1481            origin_content.trim(),
1482            expected.as_str(),
1483            "origin marker must contain the canonicalized worktree toplevel"
1484        );
1485    }
1486
1487    fn metadata(session_dir: &Path) -> serde_json::Value {
1488        serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
1489            .unwrap()
1490    }
1491
1492    #[test]
1493    fn record_transcript_path_writes_metadata_for_check() {
1494        let tmp = tempfile::tempdir().unwrap();
1495        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1496        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1497    }
1498
1499    #[test]
1500    fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
1501        let tmp = tempfile::tempdir().unwrap();
1502        std::fs::write(
1503            tmp.path().join("metadata.json"),
1504            r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
1505        )
1506        .unwrap();
1507        record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
1508        let m = metadata(tmp.path());
1509        assert_eq!(m["transcript_path"], "/t/new.jsonl");
1510        assert_eq!(m["model"], "m");
1511        let leftovers = std::fs::read_dir(tmp.path())
1512            .unwrap()
1513            .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
1514            .count();
1515        assert_eq!(leftovers, 0, "the temp file is renamed into place");
1516    }
1517
1518    #[test]
1519    fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
1520        let tmp = tempfile::tempdir().unwrap();
1521        record_transcript_path(tmp.path(), "").unwrap();
1522        assert!(!tmp.path().join("metadata.json").exists());
1523
1524        std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
1525        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
1526        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
1527    }
1528
1529    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1530
1531    use crate::session_state::{RepoBinding, SessionState};
1532
1533    fn binding(id: &str) -> RepoBinding {
1534        RepoBinding {
1535            repo_id: id.into(),
1536            git_url: None,
1537            remote_id: None,
1538            codebase_name: None,
1539            updated_at: "t".into(),
1540        }
1541    }
1542
1543    /// Workspace mode: no pinned config, but the session is bound (e.g. via
1544    /// `tracevault repo switch`) — the stream event attributes to that repo.
1545    #[test]
1546    fn resolve_stream_binding_uses_session_active_when_unbound() {
1547        let session = SessionState {
1548            active: Some(binding("session-repo")),
1549            subagents: HashMap::new(),
1550            ..Default::default()
1551        };
1552        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1553        assert_eq!(got.unwrap().repo_id, "session-repo");
1554    }
1555
1556    /// Bound-mode regression: an empty session (no `repo switch` ever run)
1557    /// with a bound config.toml still resolves via the config.
1558    #[test]
1559    fn resolve_stream_binding_falls_back_to_bound_config() {
1560        let session = SessionState::default();
1561        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1562        assert_eq!(got.unwrap().repo_id, "bound-repo");
1563    }
1564
1565    /// No session binding and no bound config: nothing resolves, which is
1566    /// exactly what should trigger `run_stream`'s graceful no-op.
1567    #[test]
1568    fn resolve_stream_binding_none_when_nothing_resolves() {
1569        let session = SessionState::default();
1570        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1571        assert!(got.is_none());
1572    }
1573
1574    /// Subagent override precedence: a per-worktree override for the current
1575    /// worktree wins over the session's `active` binding.
1576    #[test]
1577    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1578        let session = SessionState {
1579            active: Some(binding("session-repo")),
1580            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1581            ..Default::default()
1582        };
1583        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1584        assert_eq!(got.unwrap().repo_id, "subagent-repo");
1585    }
1586
1587    /// Workspace mode: no bound config, but a user-level default is set (e.g.
1588    /// via `tracevault repo switch --user`) — the stream event attributes to
1589    /// that repo when nothing more specific resolves.
1590    #[test]
1591    fn resolve_stream_binding_falls_back_to_user_default() {
1592        let session = SessionState::default();
1593        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1594        assert_eq!(got.unwrap().repo_id, "userdef");
1595    }
1596
1597    /// The user-level default is the LOWEST-precedence tier: a bound config
1598    /// still wins over it.
1599    #[test]
1600    fn resolve_stream_binding_prefers_bound_over_user_default() {
1601        let session = SessionState::default();
1602        let got = resolve_stream_binding(
1603            &session,
1604            "/wt/x",
1605            Some(binding("bound")),
1606            Some(binding("userdef")),
1607        );
1608        assert_eq!(got.unwrap().repo_id, "bound");
1609    }
1610
1611    // ── attribution_for: repo-or-project gate ────────────────────────────────
1612
1613    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1614        crate::session_state::RepoBinding {
1615            repo_id: repo_id.into(),
1616            git_url: None,
1617            remote_id: None,
1618            codebase_name: None,
1619            updated_at: String::new(),
1620        }
1621    }
1622
1623    /// The regression this whole change exists for: a session with a project
1624    /// binding and NO repo binding must still ship, repo-less, instead of
1625    /// being dropped by the hook.
1626    #[test]
1627    fn attribution_falls_back_to_project_when_no_repo_binds() {
1628        let pid = uuid::Uuid::new_v4();
1629        assert_eq!(
1630            attribution_for(None, Some(pid)),
1631            Some(Attribution::ProjectOnly { project_id: pid })
1632        );
1633    }
1634
1635    /// Neither binding resolves — the only case that may still no-op.
1636    #[test]
1637    fn attribution_is_none_when_neither_repo_nor_project_binds() {
1638        assert_eq!(attribution_for(None, None), None);
1639    }
1640
1641    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1642    /// server left to deduce the project.
1643    #[test]
1644    fn attribution_uses_repo_with_no_project_overlay() {
1645        let repo = uuid::Uuid::new_v4().to_string();
1646        let b = binding_with(&repo);
1647        assert_eq!(
1648            attribution_for(Some(&b), None),
1649            Some(Attribution::Repo {
1650                repo_id: repo,
1651                project: None
1652            })
1653        );
1654    }
1655
1656    /// Both bound: the project overlays the repo (project-scoped ingest
1657    /// carrying repo_id), unchanged from before.
1658    #[test]
1659    fn attribution_overlays_project_on_repo() {
1660        let repo = uuid::Uuid::new_v4().to_string();
1661        let pid = uuid::Uuid::new_v4();
1662        let b = binding_with(&repo);
1663        assert_eq!(
1664            attribution_for(Some(&b), Some(pid)),
1665            Some(Attribution::Repo {
1666                repo_id: repo,
1667                project: Some(pid)
1668            })
1669        );
1670    }
1671
1672    /// A corrupted repo_id costs the repo attribution, not the trace: it
1673    /// degrades to project-only rather than dropping the event.
1674    #[test]
1675    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
1676        let pid = uuid::Uuid::new_v4();
1677        let b = binding_with("../../escape");
1678        assert_eq!(
1679            attribution_for(Some(&b), Some(pid)),
1680            Some(Attribution::ProjectOnly { project_id: pid })
1681        );
1682    }
1683
1684    /// ...but with no project to fall back to, a corrupt repo_id still drops,
1685    /// so it can never reach the pending filename.
1686    #[test]
1687    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
1688        let b = binding_with("../../escape");
1689        assert_eq!(attribution_for(Some(&b), None), None);
1690    }
1691
1692    // ── pending queue filenames ──────────────────────────────────────────────
1693
1694    /// The repo filename is unchanged, so queues buffered by earlier releases
1695    /// are still found and drained after this upgrade.
1696    #[test]
1697    fn pending_file_name_for_a_repo_is_unchanged() {
1698        let repo = uuid::Uuid::new_v4().to_string();
1699        assert_eq!(
1700            Attribution::Repo {
1701                repo_id: repo.clone(),
1702                project: Some(uuid::Uuid::new_v4())
1703            }
1704            .pending_file_name(),
1705            format!("pending-{repo}.jsonl")
1706        );
1707    }
1708
1709    /// Repo-less queues carry the `project-` infix, which an older CLI reads
1710    /// as a non-UUID repo id and skips (see the doc comment).
1711    #[test]
1712    fn pending_file_name_for_a_project_is_distinct() {
1713        let pid = uuid::Uuid::new_v4();
1714        assert_eq!(
1715            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
1716            format!("pending-project-{pid}.jsonl")
1717        );
1718    }
1719
1720    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1721
1722    #[test]
1723    fn binding_repo_id_is_valid_accepts_real_uuid() {
1724        assert!(binding_repo_id_is_valid(
1725            "550e8400-e29b-41d4-a716-446655440000"
1726        ));
1727    }
1728
1729    #[test]
1730    fn binding_repo_id_is_valid_rejects_path_traversal() {
1731        assert!(!binding_repo_id_is_valid("../evil"));
1732    }
1733
1734    #[test]
1735    fn binding_repo_id_is_valid_rejects_empty() {
1736        assert!(!binding_repo_id_is_valid(""));
1737    }
1738
1739    #[test]
1740    fn binding_repo_id_is_valid_rejects_non_uuid() {
1741        assert!(!binding_repo_id_is_valid("not-a-uuid"));
1742    }
1743
1744    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1745
1746    #[test]
1747    fn stamp_agent_sets_tool_and_version() {
1748        use crate::agent::Agent;
1749        let mut req = StreamEventRequest {
1750            protocol_version: 1,
1751            tool: Some("claude-code".to_string()),
1752            event_type: StreamEventType::ToolUse,
1753            session_id: "s".into(),
1754            timestamp: chrono::Utc::now(),
1755            hook_event_name: None,
1756            tool_name: None,
1757            tool_use_id: None,
1758            tool_input: None,
1759            tool_response: None,
1760            tool_is_error: None,
1761            event_index: None,
1762            event_uuid: None,
1763            transcript_lines: None,
1764            transcript_offset: None,
1765            model: None,
1766            cwd: None,
1767            final_stats: None,
1768            flow_id: None,
1769            labels: None,
1770            params: None,
1771            billing_mode: None,
1772        };
1773        stamp_agent(&mut req, Agent::Codex);
1774        assert_eq!(req.tool.as_deref(), Some("codex"));
1775        assert_eq!(req.protocol_version, 2);
1776
1777        stamp_agent(&mut req, Agent::ClaudeCode);
1778        assert_eq!(req.tool.as_deref(), Some("claude-code"));
1779        assert_eq!(req.protocol_version, 1);
1780    }
1781
1782    // ── pending_path_for: per-target offline queue ───────────────────────────
1783
1784    fn repo_attr(repo_id: &str) -> Attribution {
1785        Attribution::Repo {
1786            repo_id: repo_id.into(),
1787            project: None,
1788        }
1789    }
1790
1791    #[test]
1792    fn pending_path_is_repo_scoped() {
1793        let dir = std::path::Path::new("/tmp/sess");
1794        assert_eq!(
1795            pending_path_for(dir, &repo_attr("repo-a")),
1796            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1797        );
1798        assert_ne!(
1799            pending_path_for(dir, &repo_attr("repo-a")),
1800            pending_path_for(dir, &repo_attr("repo-b")),
1801        );
1802    }
1803
1804    /// A repo-less session must not share a queue file with any repo, so its
1805    /// buffered events can never be flushed to a repo endpoint.
1806    #[test]
1807    fn pending_path_for_a_project_never_collides_with_a_repo() {
1808        let dir = std::path::Path::new("/tmp/sess");
1809        let pid = uuid::Uuid::from_u128(9);
1810        assert_eq!(
1811            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1812            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
1813        );
1814        assert_ne!(
1815            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1816            pending_path_for(dir, &repo_attr(&pid.to_string())),
1817        );
1818    }
1819
1820    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1821
1822    #[test]
1823    fn read_new_transcript_lines_empty_path_is_noop() {
1824        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1825        // An empty path must yield no lines and offset 0, never an error from
1826        // handing `Path::new("")` to exists()/File::open.
1827        let dir = tempfile::tempdir().unwrap();
1828        let offset_path = dir.path().join(".stream_offset");
1829        let (lines, start_offset, end_offset) =
1830            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1831        assert!(
1832            lines.is_empty(),
1833            "empty path must yield no transcript lines"
1834        );
1835        assert_eq!(start_offset, 0);
1836        assert_eq!(end_offset, 0);
1837    }
1838
1839    // ── read_new_transcript_lines: start_offset is stable across a persisted
1840    //    end_offset, and equals the previous read's end_offset ─────────────────
1841
1842    #[test]
1843    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1844        let dir = tempfile::tempdir().unwrap();
1845        let transcript_path = dir.path().join("transcript.jsonl");
1846        let offset_path = dir.path().join(".stream_offset");
1847
1848        fs::write(
1849            &transcript_path,
1850            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1851        )
1852        .unwrap();
1853
1854        let (lines, start_offset, end_offset) =
1855            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1856        assert_eq!(lines.len(), 2);
1857        assert_eq!(start_offset, 0, "first read starts at byte 0");
1858        assert!(end_offset > 0);
1859
1860        fs::write(&offset_path, end_offset.to_string()).unwrap();
1861
1862        let mut f = OpenOptions::new()
1863            .append(true)
1864            .open(&transcript_path)
1865            .unwrap();
1866        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1867        drop(f);
1868
1869        let (lines2, start_offset2, end_offset2) =
1870            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1871        assert_eq!(lines2.len(), 1);
1872        assert_eq!(
1873            start_offset2, end_offset,
1874            "second read's start_offset must equal the first read's persisted end_offset"
1875        );
1876        assert!(end_offset2 > start_offset2);
1877    }
1878
1879    // ── capture_project: local-only project resolver ──────────────────────────
1880
1881    /// Holds the env lock and points the config dir (`XDG_CONFIG_HOME` on
1882    /// Linux, `HOME` for macOS's `dirs::config_dir()`) at a tempdir: the last
1883    /// tier reads `user_project.toml` from there, so without isolation this
1884    /// test fails on any machine with a real user default and races tests
1885    /// that write one.
1886    ///
1887    /// `TRACEVAULT_PROJECT` is pinned UNSET for the same reason:
1888    /// `capture_project` reads it (rung 3, above `session.active_project`),
1889    /// and other tests in this same binary SET it. The crate lock only
1890    /// serializes mutators against each other, so a non-locking reader still
1891    /// races them — and `std::env::set_var` concurrent with `std::env::var`
1892    /// is exactly the UB the `unsafe` blocks in `EnvVarGuard` are annotated
1893    /// against. Holding the lock AND declaring the value is what makes the
1894    /// precedence assertions below describe the tiers they name rather than
1895    /// whatever the ambient shell happens to export.
1896    #[tokio::test]
1897    async fn capture_project_precedence_local_only() {
1898        use crate::session_state::{ProjectBinding, SessionState};
1899        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1900        let tmp = tempfile::tempdir().unwrap();
1901        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1902        _guard.set("XDG_CONFIG_HOME", tmp.path());
1903        _guard.set("HOME", tmp.path());
1904        _guard.remove("TRACEVAULT_PROJECT");
1905
1906        let pb = |id: &str| ProjectBinding {
1907            project_id: id.into(),
1908            project_name: "n".into(),
1909            updated_at: "".into(),
1910            forced_until: None,
1911        };
1912        let u = uuid::Uuid::from_u128;
1913        // session active only
1914        let s = SessionState {
1915            active_project: Some(pb(&u(2).to_string())),
1916            ..Default::default()
1917        };
1918        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
1919        // subagent worktree beats session
1920        let mut s = s;
1921        s.subagent_projects
1922            .insert("/wt".into(), pb(&u(1).to_string()));
1923        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
1924        // no worktree match -> session active
1925        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
1926        // empty session, no user_project.toml in the isolated config dir -> None
1927        assert_eq!(capture_project(&SessionState::default(), None), None);
1928        // malformed stored id -> None (defensive)
1929        let bad = SessionState {
1930            active_project: Some(pb("not-a-uuid")),
1931            ..Default::default()
1932        };
1933        assert_eq!(capture_project(&bad, None), None);
1934        // a valid user_project.toml in the isolated config dir is the last tier
1935        let path = crate::user_project_default::default_project_path().unwrap();
1936        assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
1937        crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
1938        assert_eq!(capture_project(&SessionState::default(), None), Some(u(3)));
1939    }
1940
1941    /// The full binding — not just its id — survives `capture_binding`: this
1942    /// is what lets `attribution_mode` see a session-scoped `forced_until`
1943    /// (Important finding 1 in the VIS-305 Part C review: the old
1944    /// process-global disk read never saw a force written into SESSION
1945    /// state, which is where a plain `project switch --project-attribution
1946    /// explicit` — no `--user` — writes it).
1947    /// ENV ISOLATION: see `capture_project_precedence_local_only` — this
1948    /// test also goes through the capture chain, which reads
1949    /// `TRACEVAULT_PROJECT` at a rung ABOVE the session-active binding it is
1950    /// asserting on.
1951    #[test]
1952    fn capture_binding_preserves_forced_until_from_the_winning_tier() {
1953        use crate::session_state::{ProjectBinding, SessionState};
1954        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1955        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1956        _guard.remove("TRACEVAULT_PROJECT");
1957        let pid = uuid::Uuid::from_u128(2);
1958        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
1959        let s = SessionState {
1960            active_project: Some(ProjectBinding {
1961                project_id: pid.to_string(),
1962                project_name: "n".into(),
1963                updated_at: "".into(),
1964                forced_until: Some(future.clone()),
1965            }),
1966            ..Default::default()
1967        };
1968        let got = capture_binding(&s, Some("/wt")).expect("session-active binding resolves");
1969        assert_eq!(got.forced_until, Some(future));
1970    }
1971
1972    /// `_env_lock` serializes this against other tests in the crate that
1973    /// mutate `TRACEVAULT_PROJECT` (see `test_helpers::lock_env_mutation_sync`),
1974    /// including any that call `commands::project::status`, which reads the
1975    /// same var.
1976    #[test]
1977    fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
1978        // A name would need a `list_projects` round trip, and this path runs
1979        // per-event in a short-lived hook process. Same rule already excludes
1980        // `config_default` here.
1981        let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1982
1983        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1984        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1985
1986        _guard.set("TRACEVAULT_PROJECT", uuid);
1987        let got = env_project_binding().expect("uuid form is honoured");
1988        assert_eq!(got.project_id, uuid);
1989
1990        _guard.set("TRACEVAULT_PROJECT", "my-project");
1991        assert!(
1992            env_project_binding().is_none(),
1993            "a name is ignored on the network-free capture path"
1994        );
1995
1996        _guard.remove("TRACEVAULT_PROJECT");
1997        assert!(env_project_binding().is_none());
1998    }
1999
2000    // ── attribution_mode ───────────────────────────────────────────────────
2001    //
2002    // `attribution_mode` no longer touches disk at all: it takes the WINNING
2003    // binding (as resolved by `capture_project`) as a parameter, so these
2004    // tests only need to isolate `TRACEVAULT_PROJECT_ATTRIBUTION` via the
2005    // crate's env-mutation lock/guard, not `XDG_CONFIG_HOME`.
2006
2007    fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
2008        crate::session_state::ProjectBinding {
2009            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
2010            project_name: "p".into(),
2011            updated_at: chrono::Utc::now().to_rfc3339(),
2012            forced_until: forced_until.map(str::to_string),
2013        }
2014    }
2015
2016    #[test]
2017    fn env_force_is_explicit_and_needs_no_expiry() {
2018        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2019        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2020        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2021
2022        assert_eq!(attribution_mode(None), AttributionMode::Explicit);
2023    }
2024
2025    #[test]
2026    fn absent_or_unrecognised_env_is_derived() {
2027        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2028        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2029
2030        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2031        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2032
2033        // The CLI does not forward a value it does not recognise: the server
2034        // would 400 it, and failing a hook over a typo'd env var helps
2035        // nobody. The server's strictness is for callers that bypass the
2036        // CLI.
2037        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
2038        assert_eq!(attribution_mode(None), AttributionMode::Derived);
2039    }
2040
2041    /// The binding-persisted half of `attribution_mode`: a LIVE `forced_until`
2042    /// on the WINNING binding (no env var involved) must also read as
2043    /// `explicit` — this is what `project switch --project-attribution
2044    /// explicit` ultimately drives, whether that binding lives in session
2045    /// state or the user-level default.
2046    #[test]
2047    fn live_binding_force_is_explicit_without_env() {
2048        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2049        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2050        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2051
2052        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2053        let binding = forced_binding(Some(&future));
2054
2055        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2056    }
2057
2058    /// This is the test that would fail if a lapsed persisted force still
2059    /// made it onto the wire: with no env override, a `forced_until` in the
2060    /// past on the winning binding must make `attribution_mode` — the exact
2061    /// function that supplies the header — report `derived`, not `explicit`.
2062    /// Not sending an `explicit` header IS the fallback to derived
2063    /// attribution.
2064    #[test]
2065    fn lapsed_binding_force_is_derived_without_env() {
2066        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2067        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2068        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2069
2070        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2071        let binding = forced_binding(Some(&past));
2072
2073        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2074    }
2075
2076    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
2077    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
2078    /// read as `derived`, never panic or, worse, read as `explicit`. Pins the
2079    /// fail-safe direction against a future refactor to `.expect(...)`.
2080    #[test]
2081    fn unparseable_forced_until_is_derived() {
2082        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2083        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2084        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2085
2086        let binding = forced_binding(Some("not-a-timestamp"));
2087
2088        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
2089    }
2090
2091    /// Env-provided force must be exempt from expiry in fact, not just by
2092    /// coincidence of the OR: pairing it with a binding force that has
2093    /// ALREADY LAPSED still yields `explicit`. If `attribution_mode` were
2094    /// refactored to gate the env branch on any timestamp, this is the test
2095    /// that would catch it — `lapsed_binding_force_is_derived_without_env`
2096    /// alone couldn't, since it never sets the env var.
2097    #[test]
2098    fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
2099        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2100        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2101        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2102
2103        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
2104        let binding = forced_binding(Some(&past));
2105
2106        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
2107    }
2108
2109    /// VIS-305 Part C review, Important finding 1: a SESSION-scoped force
2110    /// (`project switch --project-attribution explicit` WITHOUT `--user`,
2111    /// which is the default whenever a session id is set — i.e. the ordinary
2112    /// case inside every instrumented agent session) must actually reach the
2113    /// wire as `explicit`. The old process-global `attribution_mode` only
2114    /// ever consulted the user-level default store and never saw a force
2115    /// written into session state at all, so this would have silently sent
2116    /// `derived` while `project switch`'s own success message claimed
2117    /// membership was not being checked. Exercised end-to-end through
2118    /// `send_stream_event` and a real captured request header, not just the
2119    /// pure `attribution_mode` function, so a regression anywhere in the
2120    /// plumbing between `capture_project` and the wire is caught.
2121    #[tokio::test]
2122    async fn session_scoped_force_is_honoured_on_the_wire() {
2123        use crate::session_state::{ProjectBinding, SessionState};
2124
2125        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2126        let tmp = tempfile::tempdir().unwrap();
2127        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2128        // No user-level default at all: the force under test lives ONLY in
2129        // session state, so a pass here can't be explained by an ambient or
2130        // accidentally-written user_project.toml.
2131        _guard.set("XDG_CONFIG_HOME", tmp.path());
2132        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2133        // `capture_project` reads `TRACEVAULT_PROJECT` ABOVE the
2134        // session-active tier this test pins the force on; unset it so an
2135        // ambient export can't redirect the capture at another project.
2136        _guard.remove("TRACEVAULT_PROJECT");
2137
2138        let pid = uuid::Uuid::from_u128(321);
2139        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2140        let session = SessionState {
2141            active_project: Some(ProjectBinding {
2142                project_id: pid.to_string(),
2143                project_name: "proj".into(),
2144                updated_at: "".into(),
2145                forced_until: Some(future),
2146            }),
2147            ..Default::default()
2148        };
2149        let capture_binding = capture_binding(&session, None);
2150
2151        let resp = ok_stream_response();
2152        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2153        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2154        let req = sample_stream_event_request();
2155        let mut warned = false;
2156
2157        let got = send_stream_event(
2158            &client,
2159            &Attribution::ProjectOnly { project_id: pid },
2160            attribution_force(capture_binding.as_ref()),
2161            &req,
2162            &mut warned,
2163        )
2164        .await
2165        .expect("send_stream_event must succeed");
2166        assert_eq!(
2167            got.expect("a successful send returns a response").status,
2168            "accepted"
2169        );
2170
2171        let captured = rx
2172            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2173            .expect("no request captured");
2174        assert!(
2175            captured
2176                .to_lowercase()
2177                .contains("x-tracevault-project-attribution: explicit"),
2178            "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
2179        );
2180    }
2181
2182    /// VIS-305 Part C review, Important finding 2: a LIVE force sitting on
2183    /// the machine-global user-level default must NOT leak onto a different,
2184    /// higher-precedence project that resolves instead. The old
2185    /// process-global `attribution_mode` couldn't tell the two apart — it
2186    /// declared `explicit` for ANY project as long as SOME force existed
2187    /// anywhere on disk. Here the user-default's force belongs to project A,
2188    /// but `TRACEVAULT_PROJECT` (a higher-precedence local tier) points this
2189    /// capture at project B, which was never forced.
2190    #[test]
2191    fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
2192        use crate::session_state::{ProjectBinding, SessionState};
2193
2194        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2195        let tmp = tempfile::tempdir().unwrap();
2196        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2197        _guard.set("XDG_CONFIG_HOME", tmp.path());
2198        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2199
2200        let project_a = uuid::Uuid::from_u128(1);
2201        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
2202        crate::user_project_default::save(&ProjectBinding {
2203            project_id: project_a.to_string(),
2204            project_name: "a".into(),
2205            updated_at: chrono::Utc::now().to_rfc3339(),
2206            forced_until: Some(future),
2207        })
2208        .unwrap();
2209
2210        let project_b = uuid::Uuid::from_u128(2);
2211        _guard.set("TRACEVAULT_PROJECT", project_b.to_string());
2212
2213        let capture_binding = capture_binding(&SessionState::default(), None);
2214        assert_eq!(
2215            capture_binding.as_ref().map(|b| b.project_id.as_str()),
2216            Some(project_b.to_string()).as_deref(),
2217            "TRACEVAULT_PROJECT must outrank the user-level default"
2218        );
2219
2220        assert_eq!(
2221            attribution_mode(capture_binding.as_ref()),
2222            AttributionMode::Derived,
2223            "a force on the user-default project must not leak onto a DIFFERENT, \
2224             higher-precedence project that never asked to be forced"
2225        );
2226    }
2227
2228    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
2229
2230    use std::io::BufReader;
2231    use std::net::TcpListener;
2232    use std::sync::mpsc;
2233    use std::thread;
2234    use std::time::{Duration, Instant};
2235
2236    /// How long an accept loop waits for a connection that never arrives
2237    /// (e.g. a regression that stops the client from making an expected
2238    /// request) before giving up, so the server thread exits cleanly
2239    /// instead of blocking in `accept()` forever.
2240    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
2241
2242    /// Poll a non-blocking `listener` for a connection until one arrives or
2243    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
2244    /// `WouldBlock` accept error) so callers can stop cleanly rather than
2245    /// block forever.
2246    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
2247        let deadline = Instant::now() + ACCEPT_DEADLINE;
2248        loop {
2249            match listener.accept() {
2250                Ok((stream, _)) => {
2251                    // The accepted stream's blocking mode isn't guaranteed to
2252                    // be inherited from the (non-blocking) listener across
2253                    // platforms — make it explicitly blocking so the
2254                    // subsequent read/write calls behave as before.
2255                    let _ = stream.set_nonblocking(false);
2256                    return Some(stream);
2257                }
2258                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2259                    if Instant::now() >= deadline {
2260                        return None;
2261                    }
2262                    thread::sleep(Duration::from_millis(20));
2263                }
2264                Err(_) => return None,
2265            }
2266        }
2267    }
2268
2269    /// How long a test waits for the captured request before failing (rather
2270    /// than hanging forever if the client never connects). Mirrors the
2271    /// harness in `tests/stream_event_project_test.rs`.
2272    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
2273
2274    /// Read one request's line and headers off `stream`, hand the pair to
2275    /// `tx` as a single string, then write `response` back.
2276    ///
2277    /// Shared by [`spawn_once_capturing_request`] and
2278    /// [`spawn_n_capturing_requests`], which grew this same capture
2279    /// independently and disagreed only on `trim()` vs `trim_end()` for the
2280    /// blank-line terminator (equivalent, since a bare CRLF trims empty
2281    /// either way).
2282    ///
2283    /// Deliberately NOT `test_helpers::read_request`: that one is private to
2284    /// its module and blocks in `accept()`, where these two use
2285    /// `set_nonblocking` plus a deadline.
2286    ///
2287    /// Headers are captured, not just the request line, so a test can assert
2288    /// on `x-tracevault-project-attribution` — without them a regression that
2289    /// hardcoded `"derived"` at a `stream_event_for_project` call site would
2290    /// pass the whole suite, since nothing in-crate ever looked at the header
2291    /// actually sent. They are appended AFTER the request line, leaving
2292    /// `starts_with`/`contains` assertions on the line itself unaffected.
2293    fn capture_request_and_respond(
2294        stream: std::net::TcpStream,
2295        tx: &mpsc::Sender<String>,
2296        response: &str,
2297    ) {
2298        let mut reader = BufReader::new(stream);
2299        let mut captured = String::new();
2300        let _ = reader.read_line(&mut captured);
2301        loop {
2302            let mut header = String::new();
2303            if reader.read_line(&mut header).unwrap_or(0) == 0 {
2304                break;
2305            }
2306            if header.trim().is_empty() {
2307                break;
2308            }
2309            captured.push_str(&header);
2310        }
2311        let _ = tx.send(captured);
2312        let mut stream = reader.into_inner();
2313        let _ = stream.write_all(response.as_bytes());
2314        let _ = stream.flush();
2315    }
2316
2317    /// Spawn a one-shot server that returns `response` (a full HTTP response)
2318    /// to the first request, capturing it via
2319    /// [`capture_request_and_respond`]. Mirrors the harness in
2320    /// `tests/stream_event_project_test.rs` / `tests/resolve_remote_test.rs`.
2321    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
2322        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2323        listener.set_nonblocking(true).unwrap();
2324        let addr = listener.local_addr().unwrap();
2325        let (tx, rx) = mpsc::channel();
2326        thread::spawn(move || {
2327            if let Some(stream) = accept_with_deadline(&listener) {
2328                capture_request_and_respond(stream, &tx, response);
2329            }
2330        });
2331        (format!("http://{addr}"), rx)
2332    }
2333
2334    fn ok_stream_response() -> String {
2335        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
2336            session_db_id: uuid::Uuid::nil(),
2337            event_db_id: Some(uuid::Uuid::nil()),
2338            status: "accepted".to_string(),
2339        })
2340        .unwrap();
2341        format!(
2342            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2343            body.len(),
2344            body
2345        )
2346    }
2347
2348    fn sample_stream_event_request() -> StreamEventRequest {
2349        StreamEventRequest {
2350            protocol_version: 2,
2351            tool: Some("claude-code".to_string()),
2352            event_type: StreamEventType::ToolUse,
2353            session_id: "sess-1".into(),
2354            timestamp: chrono::Utc::now(),
2355            hook_event_name: Some("PostToolUse".into()),
2356            tool_name: None,
2357            tool_use_id: None,
2358            tool_input: None,
2359            tool_response: None,
2360            tool_is_error: None,
2361            event_index: None,
2362            event_uuid: None,
2363            transcript_lines: None,
2364            transcript_offset: None,
2365            model: None,
2366            cwd: None,
2367            final_stats: None,
2368            flow_id: None,
2369            labels: None,
2370            params: None,
2371            billing_mode: None,
2372        }
2373    }
2374
2375    /// With a `SessionState` whose `active_project` is set, `capture_project`
2376    /// resolves a `capture_pid`, and `send_stream_event` must route to the
2377    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
2378    /// than the repo-scoped one.
2379    #[tokio::test]
2380    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
2381        use crate::session_state::{ProjectBinding, SessionState};
2382
2383        // Isolate from any ambient user-level project default so this test's
2384        // `capture_project` call depends only on the SessionState below —
2385        // mirrors the isolation pattern in `commands::project`'s tests.
2386        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2387        let tmp = tempfile::tempdir().unwrap();
2388        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2389        _guard.set("XDG_CONFIG_HOME", tmp.path());
2390        // `capture_project` reads `TRACEVAULT_PROJECT` above the
2391        // session-active tier asserted below — pin it unset. Ditto
2392        // `TRACEVAULT_PROJECT_ATTRIBUTION`, which the `derived` header
2393        // assertion at the end of this test depends on.
2394        _guard.remove("TRACEVAULT_PROJECT");
2395        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2396
2397        let pid = uuid::Uuid::from_u128(99);
2398        let session = SessionState {
2399            active_project: Some(ProjectBinding {
2400                project_id: pid.to_string(),
2401                project_name: "proj".into(),
2402                updated_at: "".into(),
2403                forced_until: None,
2404            }),
2405            ..Default::default()
2406        };
2407        let capture_binding = capture_binding(&session, None);
2408        let capture_pid = capture_binding
2409            .as_ref()
2410            .and_then(crate::resolution::capture_project_id);
2411        assert_eq!(capture_pid, Some(pid));
2412
2413        let resp = ok_stream_response();
2414        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2415        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2416        let req = sample_stream_event_request();
2417
2418        let mut warned = false;
2419        let got = send_stream_event(
2420            &client,
2421            &Attribution::Repo {
2422                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2423                project: capture_pid,
2424            },
2425            attribution_force(capture_binding.as_ref()),
2426            &req,
2427            &mut warned,
2428        )
2429        .await
2430        .expect("send_stream_event must succeed");
2431        assert_eq!(
2432            got.expect("a successful send returns a response").status,
2433            "accepted"
2434        );
2435
2436        let line = rx
2437            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2438            .expect("no request captured");
2439        assert!(
2440            line.starts_with(&format!(
2441                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
2442            )),
2443            "an active project binding must route to the project-scoped endpoint, got: {line}"
2444        );
2445        // Covers the `Attribution::Repo { project: Some(_) }` call site of
2446        // `stream_event_for_project` (the `ProjectOnly` call site is covered
2447        // by `session_scoped_force_is_honoured_on_the_wire` and
2448        // `send_stream_event_project_only_omits_repo_id`) — an unforced
2449        // binding must still send the header, declaring `derived`.
2450        assert!(
2451            line.to_lowercase()
2452                .contains("x-tracevault-project-attribution: derived"),
2453            "got: {line}"
2454        );
2455    }
2456
2457    /// With an empty binding (default `SessionState`, no worktree override)
2458    /// and no user-level default present in the test env, `capture_project`
2459    /// resolves `None` and `send_stream_event` must fall back to the
2460    /// repo-scoped endpoint.
2461    #[tokio::test]
2462    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
2463        use crate::session_state::SessionState;
2464
2465        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2466        let tmp = tempfile::tempdir().unwrap();
2467        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2468        // No user_project.toml under this isolated config dir, so there is no
2469        // ambient user-level default to leak in — and no `TRACEVAULT_PROJECT`
2470        // either, which `capture_project` would otherwise honour and turn
2471        // this "nothing resolves" case into a project-scoped send.
2472        _guard.set("XDG_CONFIG_HOME", tmp.path());
2473        _guard.remove("TRACEVAULT_PROJECT");
2474
2475        let capture_binding = capture_binding(&SessionState::default(), None);
2476        assert_eq!(capture_binding, None);
2477
2478        let resp = ok_stream_response();
2479        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2480        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2481        let req = sample_stream_event_request();
2482
2483        let mut warned = false;
2484        let got = send_stream_event(
2485            &client,
2486            &Attribution::Repo {
2487                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2488                project: None,
2489            },
2490            attribution_force(capture_binding.as_ref()),
2491            &req,
2492            &mut warned,
2493        )
2494        .await
2495        .expect("send_stream_event must succeed");
2496        assert_eq!(
2497            got.expect("a successful send returns a response").status,
2498            "accepted"
2499        );
2500
2501        let line = rx
2502            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2503            .expect("no request captured");
2504        assert!(
2505            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
2506            "no binding must fall back to the repo-scoped endpoint, got: {line}"
2507        );
2508    }
2509
2510    // ── I1/I2: refused project-scoped send is an error + transient no-fallback ───
2511
2512    /// Spawn a server that replies to up to `responses.len()` sequential
2513    /// connections with the given full HTTP responses, in order, capturing
2514    /// each request (line + headers, via [`capture_request_and_respond`])
2515    /// over the channel. The listening socket itself is dropped (closing it)
2516    /// once all responses have been served, so any further connection attempt
2517    /// fails fast (connection refused) rather than hanging for the client's
2518    /// request timeout — this lets a test assert "no further request was
2519    /// sent" cheaply.
2520    fn spawn_n_capturing_requests(
2521        responses: Vec<&'static str>,
2522    ) -> (String, mpsc::Receiver<String>) {
2523        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2524        listener.set_nonblocking(true).unwrap();
2525        let addr = listener.local_addr().unwrap();
2526        let (tx, rx) = mpsc::channel();
2527        thread::spawn(move || {
2528            for response in responses {
2529                // If a regression stops the client from making this request
2530                // (e.g. the expected Nth call never happens), don't block
2531                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
2532                // and let the thread end so the test process can't hang.
2533                let Some(stream) = accept_with_deadline(&listener) else {
2534                    break;
2535                };
2536                capture_request_and_respond(stream, &tx, response);
2537            }
2538            // `listener` (and `tx`) drop here, closing the socket and the
2539            // channel — a stray extra request gets ECONNREFUSED immediately
2540            // instead of hanging, and a stray extra `rx.recv` returns
2541            // Disconnected immediately instead of blocking.
2542        });
2543        (format!("http://{addr}"), rx)
2544    }
2545
2546    /// I1: a deterministic 400 ("is not a member of project ...") from the
2547    /// project-scoped endpoint must be an error, not a silent second send to
2548    /// the repo-scoped endpoint. TWO responses (400 then 200) are staged so
2549    /// the "no second request" check is non-vacuous — see the comment in
2550    /// `send_stream_event_project_only_drops_on_scoping_4xx` for why a single
2551    /// staged response would make that assertion pass vacuously.
2552    #[tokio::test]
2553    async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
2554        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
2555        let resp_400 = format!(
2556            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2557            body_400.len(),
2558            body_400
2559        );
2560        let resp_200 = ok_stream_response();
2561
2562        let (base, rx) = spawn_n_capturing_requests(vec![
2563            Box::leak(resp_400.into_boxed_str()),
2564            Box::leak(resp_200.into_boxed_str()),
2565        ]);
2566        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2567        let req = sample_stream_event_request();
2568        let pid = uuid::Uuid::from_u128(42);
2569
2570        let mut warned = false;
2571        let err = send_stream_event(
2572            &client,
2573            &Attribution::Repo {
2574                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2575                project: Some(pid),
2576            },
2577            attribution_force(None),
2578            &req,
2579            &mut warned,
2580        )
2581        .await
2582        .expect_err("a refused declared project must be an error, not a silent fallback");
2583        assert!(
2584            err.to_string().contains("400"),
2585            "propagated error must reflect the status, got: {err}"
2586        );
2587        assert!(
2588            warned,
2589            "the refusal must be printed (gated on `warned`) so it is visible"
2590        );
2591
2592        let first = rx
2593            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2594            .expect("no first request captured");
2595        assert!(
2596            first.contains(&format!("/projects/{pid}/stream")),
2597            "first request must hit the project-scoped endpoint, got: {first}"
2598        );
2599        assert!(
2600            first.contains("repo_id="),
2601            "first request must carry repo_id, got: {first}"
2602        );
2603
2604        assert!(
2605            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2606            "no second (repo-scoped fallback) request must be sent"
2607        );
2608    }
2609
2610    /// A 403 from the project-scoped endpoint must likewise be an error, not a
2611    /// silent second send to the repo-scoped endpoint.
2612    #[tokio::test]
2613    async fn send_stream_event_errors_on_403_without_fallback() {
2614        let body_403 = "forbidden";
2615        let resp_403 = format!(
2616            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2617            body_403.len(),
2618            body_403
2619        );
2620        let resp_200 = ok_stream_response();
2621
2622        let (base, rx) = spawn_n_capturing_requests(vec![
2623            Box::leak(resp_403.into_boxed_str()),
2624            Box::leak(resp_200.into_boxed_str()),
2625        ]);
2626        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2627        let req = sample_stream_event_request();
2628        let pid = uuid::Uuid::from_u128(43);
2629
2630        let mut warned = false;
2631        let err = send_stream_event(
2632            &client,
2633            &Attribution::Repo {
2634                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2635                project: Some(pid),
2636            },
2637            attribution_force(None),
2638            &req,
2639            &mut warned,
2640        )
2641        .await
2642        .expect_err("a refused declared project must be an error, not a silent fallback");
2643        assert!(
2644            err.to_string().contains("403"),
2645            "propagated error must reflect the status, got: {err}"
2646        );
2647        assert!(
2648            warned,
2649            "the refusal must be printed (gated on `warned`) so it is visible"
2650        );
2651
2652        let first = rx
2653            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2654            .expect("no first request captured");
2655        assert!(
2656            first.contains(&format!("/projects/{pid}/stream")),
2657            "first request must hit the project-scoped endpoint, got: {first}"
2658        );
2659        assert!(
2660            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2661            "no second (repo-scoped fallback) request must be sent"
2662        );
2663    }
2664
2665    /// The refusal error must be printed at most once per hook invocation
2666    /// (i.e. per shared `warned` flag), even across multiple calls sharing
2667    /// it — mirroring how the pending-flush loop and the live send share one
2668    /// `warned` for a single invocation.
2669    #[tokio::test]
2670    async fn refused_error_is_printed_once_per_invocation() {
2671        let body_400 = "not a member";
2672        let resp_400 = || {
2673            format!(
2674                "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2675                body_400.len(),
2676                body_400
2677            )
2678        };
2679        let (base, _rx) = spawn_n_capturing_requests(vec![
2680            Box::leak(resp_400().into_boxed_str()),
2681            Box::leak(resp_400().into_boxed_str()),
2682        ]);
2683        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2684        let req = sample_stream_event_request();
2685        let pid = uuid::Uuid::from_u128(44);
2686        let attribution = Attribution::Repo {
2687            repo_id: "11111111-1111-1111-1111-111111111111".into(),
2688            project: Some(pid),
2689        };
2690
2691        let mut warned = false;
2692        assert!(
2693            send_stream_event(
2694                &client,
2695                &attribution,
2696                attribution_force(None),
2697                &req,
2698                &mut warned
2699            )
2700            .await
2701            .is_err(),
2702            "a refused declared project must be an error"
2703        );
2704        assert!(warned, "the flag must be set after the first refusal");
2705
2706        assert!(
2707            send_stream_event(
2708                &client,
2709                &attribution,
2710                attribution_force(None),
2711                &req,
2712                &mut warned
2713            )
2714            .await
2715            .is_err(),
2716            "a second refusal must also be an error"
2717        );
2718        assert!(warned, "the flag stays set across the shared invocation");
2719    }
2720
2721    /// Finding 5's scenario end to end, on the repo-bound path, as VIS-316
2722    /// leaves it: a live persisted force makes this send declare `explicit`,
2723    /// the force gate refuses it with a 403 — and the event is now an ERROR
2724    /// queued for retry, never re-sent to the repo-scoped endpoint where the
2725    /// server would DEDUCE a project that is precisely not the one the
2726    /// operator forced.
2727    ///
2728    /// Pins the fact the refusal clause depends on: the mode that went on
2729    /// the wire really is `explicit`, and it is the same value
2730    /// `refused_error` is handed — the message and the wire cannot disagree.
2731    /// A spare 200 is staged so "no second request" is non-vacuous.
2732    #[tokio::test]
2733    async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
2734        let body_403 = "forbidden";
2735        let resp_403 = format!(
2736            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2737            body_403.len(),
2738            body_403
2739        );
2740        let resp_200 = ok_stream_response();
2741
2742        let (base, rx) = spawn_n_capturing_requests(vec![
2743            Box::leak(resp_403.into_boxed_str()),
2744            Box::leak(resp_200.into_boxed_str()),
2745        ]);
2746        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2747        let req = sample_stream_event_request();
2748        let pid = uuid::Uuid::from_u128(42);
2749
2750        // A live persisted force on the winning binding — no env var needed,
2751        // so this test takes no env lock.
2752        let forced = crate::session_state::ProjectBinding {
2753            project_id: pid.to_string(),
2754            project_name: "forced".into(),
2755            updated_at: "".into(),
2756            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
2757        };
2758
2759        let mut warned = false;
2760        let err = send_stream_event(
2761            &client,
2762            &Attribution::Repo {
2763                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2764                project: Some(pid),
2765            },
2766            attribution_force(Some(&forced)),
2767            &req,
2768            &mut warned,
2769        )
2770        .await
2771        .expect_err("a refused force must be an error, not a silent fallback");
2772        assert!(
2773            err.to_string().contains("403"),
2774            "propagated error must reflect the status, got: {err}"
2775        );
2776        assert!(warned, "the refusal must be printed exactly once");
2777
2778        let first = rx
2779            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2780            .expect("no first request captured");
2781        assert!(
2782            first.contains(&format!("/projects/{pid}/stream")),
2783            "first request must hit the project-scoped endpoint, got: {first}"
2784        );
2785        assert!(
2786            first
2787                .to_lowercase()
2788                .contains("x-tracevault-project-attribution: explicit"),
2789            "the refused send must have DECLARED explicit — this is the mode \
2790             `refused_error` is handed: {first}"
2791        );
2792
2793        assert!(
2794            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2795            "a refused force must NOT be re-attributed via the repo-scoped endpoint"
2796        );
2797    }
2798
2799    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
2800    /// project endpoint with NO `repo_id` query pair. This is the wire shape
2801    /// the server documents as "repo-less (0-repo) projects are supported".
2802    ///
2803    /// Takes the env lock and pins `TRACEVAULT_PROJECT_ATTRIBUTION` unset:
2804    /// this test also asserts the `derived` attribution header, and
2805    /// `attribution_mode` reads that variable even when the binding passed
2806    /// in is `None`.
2807    #[tokio::test]
2808    async fn send_stream_event_project_only_omits_repo_id() {
2809        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2810        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2811        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2812
2813        let resp = ok_stream_response();
2814        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
2815        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2816        let req = sample_stream_event_request();
2817        let pid = uuid::Uuid::from_u128(11);
2818
2819        let mut warned = false;
2820        let got = send_stream_event(
2821            &client,
2822            &Attribution::ProjectOnly { project_id: pid },
2823            attribution_force(None),
2824            &req,
2825            &mut warned,
2826        )
2827        .await
2828        .expect("a repo-less project send must succeed");
2829        assert_eq!(
2830            got.expect("a successful send returns a response").status,
2831            "accepted"
2832        );
2833
2834        let line = rx
2835            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2836            .expect("no request captured");
2837        assert!(
2838            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
2839            "expected a bare project path with no query string, got: {line}"
2840        );
2841        assert!(
2842            line.to_lowercase()
2843                .contains("x-tracevault-project-attribution: derived"),
2844            "with no forced binding, the header must declare `derived`, got: {line}"
2845        );
2846        assert!(
2847            !warned,
2848            "a repo-less send has no fallback and must not warn about one"
2849        );
2850    }
2851
2852    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
2853    /// the queue is keyed by the very project id the server says does not
2854    /// resolve, so a corrected binding writes to a different file and these
2855    /// events would never be retried — they would just accumulate, one per
2856    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
2857    /// trigger a second, impossible request.
2858    #[tokio::test]
2859    async fn send_stream_event_project_only_drops_on_scoping_4xx() {
2860        let body = "no such project";
2861        let resp_404 = format!(
2862            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2863            body.len(),
2864            body
2865        );
2866        // TWO responses are staged although only one request is expected. With
2867        // a single response the helper drops its sender the moment the list is
2868        // exhausted, so the "no second request" assertion below would pass on
2869        // `Disconnected` whether or not a second request happened — a vacuous
2870        // check. Staging a spare keeps the server accepting, so a stray
2871        // request really is captured and really fails the test.
2872        let (base, rx) = spawn_n_capturing_requests(vec![
2873            Box::leak(resp_404.clone().into_boxed_str()),
2874            Box::leak(resp_404.into_boxed_str()),
2875        ]);
2876        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2877        let req = sample_stream_event_request();
2878        let pid = uuid::Uuid::from_u128(12);
2879
2880        let mut warned = false;
2881        let got = send_stream_event(
2882            &client,
2883            &Attribution::ProjectOnly { project_id: pid },
2884            attribution_force(None),
2885            &req,
2886            &mut warned,
2887        )
2888        .await
2889        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
2890        assert!(
2891            got.is_none(),
2892            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
2893        );
2894        assert!(
2895            warned,
2896            "dropping data silently is the failure mode to avoid"
2897        );
2898
2899        let first = rx
2900            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2901            .expect("no request captured");
2902        assert!(
2903            first.contains(&format!("/projects/{pid}/stream")),
2904            "must hit the project-scoped endpoint, got: {first}"
2905        );
2906        assert!(
2907            rx.recv_timeout(Duration::from_millis(500)).is_err(),
2908            "a repo-less send must make exactly one request — no fallback exists"
2909        );
2910    }
2911
2912    /// A 403 is NOT dropped. It can mean the account has no `tracevault` grant,
2913    /// which an administrator can grant — after which the buffered events do
2914    /// deliver. It must propagate so the caller queues them.
2915    #[tokio::test]
2916    async fn send_stream_event_project_only_buffers_on_403() {
2917        let body = "forbidden";
2918        let resp_403 = format!(
2919            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2920            body.len(),
2921            body
2922        );
2923        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
2924        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2925        let req = sample_stream_event_request();
2926
2927        let mut warned = false;
2928        let err = send_stream_event(
2929            &client,
2930            &Attribution::ProjectOnly {
2931                project_id: uuid::Uuid::from_u128(13),
2932            },
2933            attribution_force(None),
2934            &req,
2935            &mut warned,
2936        )
2937        .await
2938        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
2939        assert!(
2940            err.to_string().contains("403"),
2941            "propagated error must reflect the status, got: {err}"
2942        );
2943    }
2944
2945    /// I2: a transient 503 from the project-scoped endpoint must propagate as
2946    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
2947    /// existing buffer/retry logic in `run_stream` still handles it. Only one
2948    /// request (to the project endpoint) may be observed.
2949    #[tokio::test]
2950    async fn send_stream_event_does_not_fall_back_on_transient_503() {
2951        let body_503 = "internal error";
2952        let resp_503 = format!(
2953            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2954            body_503.len(),
2955            body_503
2956        );
2957        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
2958        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
2959        let req = sample_stream_event_request();
2960        let pid = uuid::Uuid::from_u128(7);
2961
2962        let mut warned = false;
2963        let err = send_stream_event(
2964            &client,
2965            &Attribution::Repo {
2966                repo_id: "11111111-1111-1111-1111-111111111111".into(),
2967                project: Some(pid),
2968            },
2969            attribution_force(None),
2970            &req,
2971            &mut warned,
2972        )
2973        .await
2974        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
2975        assert!(
2976            err.to_string().contains("503"),
2977            "propagated error must reflect the transient status, got: {err}"
2978        );
2979        assert!(
2980            deterministic_client_error_kind(err.as_ref()).is_none(),
2981            "a 503 must not be classified as a deterministic client error"
2982        );
2983
2984        let first = rx
2985            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
2986            .expect("no request captured");
2987        assert!(
2988            first.contains(&format!("/projects/{pid}/stream")),
2989            "must hit the project-scoped endpoint, got: {first}"
2990        );
2991
2992        // The mock server only serves ONE response and then drops its
2993        // listener/sender — a stray fallback request would either fail the
2994        // `expect_err` above (if it somehow succeeded) or, if it also failed,
2995        // would still mean a second request was attempted. Confirming the
2996        // channel is immediately disconnected (rather than blocking) proves
2997        // no second request was ever sent.
2998        assert!(
2999            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
3000            "no second (fallback) request should have been sent for a transient error"
3001        );
3002    }
3003
3004    /// A 403 must be classified apart from the binding/scoping statuses: since
3005    /// Keycloak it has a second, now more common cause (no `tracevault` grant
3006    /// at all) whose advice is completely different.
3007    #[test]
3008    fn a_403_is_classified_apart_from_the_scoping_statuses() {
3009        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
3010        assert_eq!(
3011            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
3012            Some(ClientErrorKind::Forbidden)
3013        );
3014        for scoping in [
3015            "Stream failed (400 Bad Request): {}",
3016            "Stream failed (404 Not Found): {}",
3017            "Stream failed (409 Conflict): {}",
3018        ] {
3019            assert_eq!(
3020                deterministic_client_error_kind(err(scoping).as_ref()),
3021                Some(ClientErrorKind::Scoping),
3022                "{scoping}"
3023            );
3024        }
3025        // Unchanged: 401 and transient failures are not deterministic client
3026        // errors and must keep propagating to buffer/retry.
3027        for transient in [
3028            "Stream failed (401 Unauthorized): {}",
3029            "Stream failed (503 Service Unavailable): {}",
3030            "error sending request for url (http://x/stream)",
3031        ] {
3032            assert_eq!(
3033                deterministic_client_error_kind(err(transient).as_ref()),
3034                None,
3035                "{transient}"
3036            );
3037        }
3038    }
3039
3040    /// The 403 error must not tell a user whose account has no `tracevault` grant
3041    /// to switch projects, which cannot possibly help. It names both causes,
3042    /// and — since the CLI no longer re-attributes to another project — must
3043    /// never claim it did.
3044    #[test]
3045    fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
3046        let pid = uuid::Uuid::from_u128(7);
3047
3048        let forbidden = refused_error(
3049            pid,
3050            &ClientErrorKind::Forbidden,
3051            AttributionForce::default(),
3052        );
3053        assert!(forbidden.contains("403"), "{forbidden}");
3054        assert!(
3055            forbidden.contains("no `tracevault` grant in Control Plane"),
3056            "must offer the missing-role explanation: {forbidden}"
3057        );
3058        assert!(
3059            forbidden.contains("no `Operator` role on it"),
3060            "must still offer the project explanation: {forbidden}"
3061        );
3062        assert!(
3063            forbidden.starts_with("tracevault: error:"),
3064            "a refusal is an error, not a warning: {forbidden}"
3065        );
3066        assert!(forbidden.contains(&pid.to_string()));
3067
3068        // A 400/404/409 genuinely IS a binding problem, so that wording stays
3069        // unhedged — hedging everything would dilute the useful case.
3070        let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
3071        assert!(scoping.contains("project switch"), "{scoping}");
3072        assert!(
3073            !scoping.contains("`tracevault` grant"),
3074            "the scoping case must not mention the `tracevault` grant: {scoping}"
3075        );
3076
3077        for s in [&forbidden, &scoping] {
3078            // A machine-wide default is rebound with `--user`; without the
3079            // hint, `project switch` in a session only shadows it.
3080            assert!(s.contains("--user"), "must name the --user fix: {s}");
3081            assert!(
3082                s.contains("user_project.toml"),
3083                "must name the machine-wide default's file: {s}"
3084            );
3085            assert!(
3086                !s.contains("repo deduction"),
3087                "must never describe re-attribution to another project: {s}"
3088            );
3089            assert!(
3090                !s.contains("Attributing via"),
3091                "must never claim the event was re-attributed: {s}"
3092            );
3093        }
3094    }
3095
3096    /// VIS-305 whole-branch review, Important finding 5: a REFUSED FORCE
3097    /// said nothing about the force. The 403 the force gate returns for "not
3098    /// Operator on the project" or "`explicit` from a `tvk_` key" is
3099    /// indistinguishable from here (see `ClientErrorKind`) from a membership
3100    /// 403, so an operator who asked for `explicit` got a message about
3101    /// membership and realm roles and was never told the force itself was
3102    /// what got refused. Failing closed on trust is right; failing closed
3103    /// silently is the defect. (VIS-316 made the refusal an error rather
3104    /// than a fallback; the missing explanation is orthogonal to that and
3105    /// still has to be given.)
3106    #[test]
3107    fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
3108        let pid = uuid::Uuid::from_u128(7);
3109
3110        let explicit = refused_error(
3111            pid,
3112            &ClientErrorKind::Forbidden,
3113            AttributionForce {
3114                env: false,
3115                binding: true,
3116            },
3117        );
3118        assert!(
3119            explicit.contains("FORCE"),
3120            "the refusal of the force itself must be named: {explicit}"
3121        );
3122        assert!(
3123            explicit.contains("Operator"),
3124            "must name the grant forcing requires: {explicit}"
3125        );
3126        assert!(
3127            explicit.contains("Control Plane"),
3128            "must name the identity forcing requires: {explicit}"
3129        );
3130        // `main`'s Forbidden wording is ADDED TO, not replaced: the
3131        // membership causes it already names must survive alongside the
3132        // force clause.
3133        assert!(
3134            explicit.contains("`tracevault` grant")
3135                && explicit.contains("no `Operator` role on it"),
3136            "the membership causes must still be named: {explicit}"
3137        );
3138        // The event is queued, not re-attributed — the force clause must not
3139        // reintroduce the claim VIS-316 removed.
3140        assert!(
3141            !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
3142            "must never claim the event was re-attributed: {explicit}"
3143        );
3144
3145        // Same 403, `derived` mode: no force was asked for, so none was
3146        // refused and the clause must not appear. This is the discriminating
3147        // half — without it the test would pass on a message that blamed the
3148        // force unconditionally, which is just a different wrong story.
3149        let derived = refused_error(
3150            pid,
3151            &ClientErrorKind::Forbidden,
3152            AttributionForce::default(),
3153        );
3154        assert!(
3155            !derived.contains("FORCE"),
3156            "a `derived` send never forced anything: {derived}"
3157        );
3158    }
3159
3160    /// The force clause belongs to the 403 the force gate returns, and to
3161    /// nothing else: a 400/404/409 means the project id does not resolve, so
3162    /// the gate never ran. Blaming the force there would be a new wrong
3163    /// explanation of the same family as the one finding 5 reports.
3164    #[test]
3165    fn an_explicit_scoping_failure_does_not_blame_the_force() {
3166        let pid = uuid::Uuid::from_u128(7);
3167        let scoping = refused_error(
3168            pid,
3169            &ClientErrorKind::Scoping,
3170            AttributionForce {
3171                env: true,
3172                binding: true,
3173            },
3174        );
3175        assert!(!scoping.contains("FORCE"), "{scoping}");
3176        assert_eq!(
3177            scoping,
3178            refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
3179            "the scoping wording does not depend on the mode"
3180        );
3181    }
3182
3183    /// Copilot on PR #54: the remediation told EVERY forced sender to switch
3184    /// again without `--project-attribution explicit`. That clears a
3185    /// persisted `forced_until` and nothing else — so when the force came
3186    /// from `TRACEVAULT_PROJECT_ATTRIBUTION`, [`attribution_force`] goes on
3187    /// reading the environment, every later send still declares `explicit`,
3188    /// and the advice silently does nothing. On the one code path a confused
3189    /// operator reaches.
3190    ///
3191    /// Each case is driven through `attribution_force` and a REAL exported
3192    /// variable rather than a hand-built struct, so what this pins is the
3193    /// whole path: the value that decides the header is the value the
3194    /// wording is derived from, and the two cannot describe different
3195    /// worlds.
3196    ///
3197    /// Discriminating in both directions — each case asserts the fix that
3198    /// applies AND the absence of the one that doesn't — because a message
3199    /// that simply listed both remediations every time would pass a
3200    /// one-sided test while being the same "advice that may not apply"
3201    /// defect in a longer form.
3202    #[test]
3203    fn the_403_remediation_names_the_force_source_actually_in_effect() {
3204        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3205        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3206        let pid = uuid::Uuid::from_u128(7);
3207        let live = forced_binding(Some(
3208            &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
3209        ));
3210        let never_forced = forced_binding(None);
3211
3212        // ENV ONLY. The binding carries no force at all, so "switch again
3213        // without the flag" would change precisely nothing: the next send
3214        // reads the same variable and declares `explicit` again.
3215        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3216        let env_only = refused_error(
3217            pid,
3218            &ClientErrorKind::Forbidden,
3219            attribution_force(Some(&never_forced)),
3220        );
3221        assert!(
3222            env_only.contains("FORCE"),
3223            "an env-sourced force is still a force: {env_only}"
3224        );
3225        assert!(
3226            env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
3227            "must name the variable that is doing the forcing: {env_only}"
3228        );
3229        assert!(
3230            !env_only.contains("--project-attribution"),
3231            "must NOT tell the operator to drop a flag that would change \
3232             nothing here — this is the bug: {env_only}"
3233        );
3234
3235        // BINDING ONLY. Now the flag advice is the right one, and naming the
3236        // env var would send the operator hunting for an export that isn't
3237        // set.
3238        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
3239        let binding_only = refused_error(
3240            pid,
3241            &ClientErrorKind::Forbidden,
3242            attribution_force(Some(&live)),
3243        );
3244        assert!(
3245            binding_only.contains("--project-attribution"),
3246            "a persisted force IS cleared by switching without the flag: {binding_only}"
3247        );
3248        assert!(
3249            !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
3250            "must not send the operator after an unset variable: {binding_only}"
3251        );
3252
3253        // BOTH. Removing either one alone leaves the other forcing, which
3254        // would look exactly like the fix not working — so the message has
3255        // to say both must go.
3256        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
3257        let both = refused_error(
3258            pid,
3259            &ClientErrorKind::Forbidden,
3260            attribution_force(Some(&live)),
3261        );
3262        assert!(
3263            both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3264                && both.contains("--project-attribution"),
3265            "both sources are in effect and both must be named: {both}"
3266        );
3267        assert!(
3268            both.contains("BOTH"),
3269            "must say that removing only one is not enough: {both}"
3270        );
3271    }
3272
3273    /// The remediation is built from the same `AttributionForce` the header
3274    /// is, so it can never describe a force the send did not declare: with
3275    /// no source set there is no force clause at all, whatever the wording
3276    /// of the fixes would have been.
3277    #[test]
3278    fn no_force_means_no_remediation_clause() {
3279        let pid = uuid::Uuid::from_u128(7);
3280        let none = refused_error(
3281            pid,
3282            &ClientErrorKind::Forbidden,
3283            AttributionForce::default(),
3284        );
3285        assert!(
3286            !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
3287                && !none.contains("--project-attribution"),
3288            "a derived send has no force to remove: {none}"
3289        );
3290    }
3291}