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
95pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
96    let mut file = OpenOptions::new()
97        .create(true)
98        .append(true)
99        .open(pending_path)?;
100    writeln!(file, "{json}")?;
101    Ok(())
102}
103
104pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
105    if !pending_path.exists() {
106        return Ok(vec![]);
107    }
108    let content = fs::read_to_string(pending_path)?;
109    let lines: Vec<String> = content
110        .lines()
111        .filter(|l| !l.trim().is_empty())
112        .map(String::from)
113        .collect();
114    fs::remove_file(pending_path)?;
115    Ok(lines)
116}
117
118/// How a stream event is attributed on the wire, resolved from the local repo
119/// and project bindings before anything is sent.
120///
121/// The rule this type encodes: an event ships when EITHER a repo or a project
122/// resolves. Before this existed the hook required a repo binding and dropped
123/// the event otherwise, which silently discarded every event of a repo-less
124/// session even when its project was bound — despite the server supporting
125/// exactly that shape (`ProjectStreamQuery::repo_id` is `Option<Uuid>`:
126/// "repo-less (0-repo) projects are supported").
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub(crate) enum Attribution {
129    /// A usable repo binding resolved. `project` is the capture-time project
130    /// overlay; when `None` the server deduces the project from the repo.
131    Repo {
132        repo_id: String,
133        project: Option<uuid::Uuid>,
134    },
135    /// No usable repo binding, but a project did — repo-less project-scoped
136    /// ingest.
137    ProjectOnly { project_id: uuid::Uuid },
138}
139
140impl Attribution {
141    /// Offline-queue filename for this attribution. Keyed by whatever
142    /// identifies the target so a mid-session rebind (workspace mode) can
143    /// never flush one target's queued events to another.
144    ///
145    /// The `project-` infix is load-bearing for back-compat: an older CLI's
146    /// `repo_id_from_pending_filename` extracts `project-<uuid>` from this
147    /// name, fails its UUID check, and skips the file — so a downgrade leaves
148    /// these queues alone instead of trying to POST them at a repo endpoint.
149    pub(crate) fn pending_file_name(&self) -> String {
150        use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
151        match self {
152            Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
153            Self::ProjectOnly { project_id } => {
154                format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
155            }
156        }
157    }
158}
159
160/// Pure attribution resolver: fold the repo binding and the capture-time
161/// project into the target this event will be sent to. `None` means neither
162/// resolved and the hook must no-op.
163///
164/// A binding whose `repo_id` is not a UUID degrades to `ProjectOnly` rather
165/// than dropping the event — a corrupted session-state file should cost the
166/// repo attribution, not the whole trace, when a project is available.
167///
168/// `project` here is whatever `capture_project` resolved, and its lowest tier
169/// is the MACHINE-GLOBAL `project switch --user` default — not just
170/// session-scoped bindings. That tier is therefore now a sufficient condition
171/// for an event to ship, where previously it could only redirect an event that
172/// was already shipping because a repo bound. This is deliberate: it is the
173/// only binding a container can establish before the agent session exists and
174/// before the repo is cloned, which is the case this whole path serves.
175/// `resolve_stream_binding` has the same machine-global tier for repos, so the
176/// two sides stay symmetric. Consequence worth knowing: a session started in an
177/// unrelated directory, with no repo and no `.tracevault/`, will attribute to
178/// that default project.
179pub(crate) fn attribution_for(
180    binding: Option<&crate::session_state::RepoBinding>,
181    project: Option<uuid::Uuid>,
182) -> Option<Attribution> {
183    match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
184        Some(b) => Some(Attribution::Repo {
185            repo_id: b.repo_id.clone(),
186            project,
187        }),
188        None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
189    }
190}
191
192/// Offline-queue path for an attribution target.
193fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
194    session_dir.join(attribution.pending_file_name())
195}
196
197/// Resolve the project root and session directory for a stream hook invocation.
198///
199/// This is the pure, testable core of `run_stream`'s path resolution. It uses
200/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
201/// --git-common-dir` first, so it correctly resolves to the **primary**
202/// `.tracevault/` directory from any worktree — including sibling linked
203/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
204///
205/// Returns `(resolved, session_dir)` — the resolved
206/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
207/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
208/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
209pub fn resolve_session_paths(
210    hook_cwd: &Path,
211    session_id: &str,
212) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
213    let resolved = crate::paths::resolve_project_root(hook_cwd);
214    let session_dir = resolved
215        .root
216        .join(".tracevault")
217        .join("sessions")
218        .join(session_id);
219    (resolved, session_dir)
220}
221
222/// A resolved binding is usable for hook attribution only if its repo_id is a
223/// real UUID — guards against a corrupted/edited session-state file injecting
224/// path separators into the pending-<repo_id>.jsonl filename.
225fn binding_repo_id_is_valid(repo_id: &str) -> bool {
226    uuid::Uuid::parse_str(repo_id).is_ok()
227}
228
229/// The effective repo binding for a stream event, given the loaded session
230/// state, the event's worktree, and the bound-config fallback. Pure — the
231/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
232pub(crate) fn resolve_stream_binding(
233    session: &crate::session_state::SessionState,
234    worktree: &str,
235    bound: Option<crate::session_state::RepoBinding>,
236    user_default: Option<crate::session_state::RepoBinding>,
237) -> Option<crate::session_state::RepoBinding> {
238    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
239        repo_flag: None,
240        session,
241        worktree_path: Some(worktree),
242        bound,
243        user_default,
244    })
245    .map(|(b, _)| b)
246}
247
248/// Resolve the capture-time project from LOCAL, UUID-bearing bindings only — no
249/// network (the hook fires per event in a short-lived process). Precedence:
250/// subagent worktree override -> session `active_project` -> user-level default.
251/// Repo config `default_project` (a name) is intentionally excluded: honoring it
252/// would need a per-event `list_projects` call. `None` -> fall back to the
253/// repo-scoped stream (server deduces).
254fn capture_project(
255    session: &crate::session_state::SessionState,
256    worktree_path: Option<&str>,
257) -> Option<uuid::Uuid> {
258    use crate::resolution::{effective_project, ProjectResolveInputs};
259    let local = effective_project(&ProjectResolveInputs {
260        project_flag: None,
261        session,
262        worktree_path,
263        config_default: None,
264    })
265    .map(|(b, _)| b)
266    .or_else(crate::user_project_default::load)?;
267    local.project_id.parse::<uuid::Uuid>().ok()
268}
269
270/// The one-line warning printed when a repo-less event is dropped as
271/// permanently undeliverable. Pure, so the wording is asserted directly.
272fn undeliverable_warning(pid: uuid::Uuid) -> String {
273    format!(
274        "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
275         repo binding, so there is nothing to attribute these events to and they are being \
276         DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
277         that exists."
278    )
279}
280
281/// True when a stream-send error's rendered message carries a `(4xx ...)`
282/// status marker — i.e. the server deterministically rejected the request in
283/// a way that will never succeed on blind retry (bad binding, missing
284/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
285/// transport/network/timeout failures (which have no `(NNN ` marker at all,
286/// or a 5xx one) — those remain transient and must keep propagating so the
287/// existing buffer/retry logic in `run_stream` still applies to them.
288///
289/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
290/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
291///
292/// COUPLING: the `"(NNN "` markers below must byte-for-byte match what
293/// `ApiClient::authed_send_json`'s `err_prefix` closures render (e.g.
294/// `stream_event`'s `"Stream failed ({status})"`, where `{status}` Displays
295/// as `"404 Not Found"`, yielding `"Stream failed (404 Not Found): ..."` —
296/// hence the `"(404 "` marker below matching on the open-paren + code + the
297/// space before the reason phrase). If that error-formatting ever changes,
298/// update this list (and its tests) to match.
299/// Which deterministic client error this is, so the fallback warning can name a
300/// cause that is actually possible instead of assuming one.
301#[derive(Debug, PartialEq, Eq)]
302enum ClientErrorKind {
303    /// 403, which now has TWO plausible causes — see [`send_stream_event`].
304    Forbidden,
305    /// 400/404/409: a binding/scoping problem, and only that.
306    Scoping,
307}
308
309/// The one-line warning printed when a project-scoped send falls back to
310/// repo deduction. Pure, so the wording is asserted directly rather than by
311/// capturing stderr.
312fn fallback_warning(pid: uuid::Uuid, kind: &ClientErrorKind) -> String {
313    match kind {
314        // Since Keycloak, a 403 has a SECOND and now more common cause: the
315        // account has no `tracing` realm role at all, in which case nothing this
316        // hook does will work and `project switch` is confidently wrong advice —
317        // on the code path users hit most. The server's 403 envelope is not
318        // distinguishable from here (see `ClientErrorKind`), so name both.
319        ClientErrorKind::Forbidden => format!(
320            "tracevault: warning: the server refused to attribute this event to active project \
321             {pid} (403). Either that project does not apply to this repo (not a member, or \
322             missing TracePush) — run `tracevault project switch <name>` — or this account lacks \
323             the `tracing` Keycloak realm role entirely, which an administrator must grant. \
324             Attributing via repo deduction instead."
325        ),
326        ClientErrorKind::Scoping => format!(
327            "tracevault: warning: active project {pid} does not apply to this repo (not a member, \
328             or missing permission); attributing via repo deduction instead. Run `tracevault \
329             project switch <name>` to update."
330        ),
331    }
332}
333
334fn deterministic_client_error_kind(e: &dyn std::error::Error) -> Option<ClientErrorKind> {
335    let s = e.to_string();
336    // 401 is deliberately excluded: it's an authentication failure (bad/expired
337    // token), not a project-scoping problem, and the repo-scoped fallback uses
338    // the SAME token — it would also 401, so falling back just wastes a
339    // request before the error propagates to buffer/retry. 403 stays in: it can
340    // mean the token is valid but lacks TracePush on the bound project, and the
341    // repo-scoped fallback (a different authorization check) can help.
342    if s.contains("(403 ") {
343        return Some(ClientErrorKind::Forbidden);
344    }
345    if ["(400 ", "(404 ", "(409 "]
346        .iter()
347        .any(|marker| s.contains(marker))
348    {
349        return Some(ClientErrorKind::Scoping);
350    }
351    None
352}
353
354/// Send a single stream event, routing to the project-scoped endpoint when a
355/// local project binding resolved (`capture_pid = Some(_)`), else the
356/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
357/// the pending-flush loop and the live send share one branch.
358///
359/// Routing is decided by the [`Attribution`] resolved before the send:
360/// `Repo` with no project goes to the repo-scoped endpoint (the server
361/// deduces the project); `Repo` with a project goes to the project-scoped
362/// endpoint carrying `repo_id`; `ProjectOnly` goes to the project-scoped
363/// endpoint with no `repo_id` at all. Having no fallback endpoint, it decides
364/// instead between buffering and dropping: a `Scoping` 4xx (the project does
365/// not resolve) can never succeed on retry — the offline queue is keyed by
366/// that same project id — so it warns and returns `Ok(None)`, while a 403 or
367/// any transient error propagates to be buffered. See the arm itself for why
368/// the two differ.
369///
370/// `Ok(None)` therefore means "deliberately dropped, do not queue": callers
371/// must treat it like a success for offset/queue purposes, not like an error.
372///
373/// When the attribution carries BOTH a repo and a project and the
374/// project-scoped send fails with a
375/// deterministic client error (the bound project doesn't apply to this repo:
376/// not a member, or the caller lacks `TracePush` on it, or — after a prior
377/// fallback — the repo-scoped 409 multi-project refusal), this falls back to
378/// the repo-scoped endpoint ONCE and lets the server deduce the repo's
379/// project, warning so the miss is visible. A transient error (5xx,
380/// network/transport, timeout) is NOT retried here — it propagates so the
381/// caller's existing buffer/retry logic runs unchanged.
382///
383/// `warned` is shared across every call made for a single hook
384/// invocation (both the pending-flush loop and the live send). The
385/// pending-flush loop only `break`s on `Err`, not on a fallback that itself
386/// returns `Ok` — so a stale binding whose repo-scoped fallback keeps
387/// succeeding would otherwise print the warning once per buffered event.
388/// Gating on `*warned` caps it at one warning per invocation while leaving the
389/// fallback behavior itself unchanged. The repo-less drop warning shares the
390/// flag for the same reason: draining a queue of undeliverable events would
391/// otherwise print one line per buffered event.
392async fn send_stream_event(
393    client: &crate::api_client::ApiClient,
394    attribution: &Attribution,
395    req: &StreamEventRequest,
396    warned: &mut bool,
397) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
398{
399    let (repo_id, capture_pid) = match attribution {
400        // Repo-less: there is no repo-scoped endpoint to fall back TO, so the
401        // only choice is buffer-for-retry vs. drop, and that turns on whether
402        // a retry could EVER succeed.
403        //
404        // `Scoping` (400/404/409) means the project itself does not resolve.
405        // The offline queue is keyed by that same project id
406        // (`pending-project-<uuid>.jsonl`), so re-binding to a project that
407        // does exist writes to a DIFFERENT file and these events are never
408        // retried under the corrected binding — they would accumulate forever,
409        // one per tool call, each hook fire re-reading and re-appending the
410        // whole queue. Warn and drop instead: undeliverable is undeliverable,
411        // and a growing queue only hides it.
412        //
413        // `Forbidden` (403) is deliberately NOT dropped. It can mean the
414        // account lacks the realm role entirely, which an administrator can
415        // grant — after which the buffered events do deliver. Same for any
416        // transient error. Both propagate so the caller queues them.
417        Attribution::ProjectOnly { project_id } => {
418            let attempt = client
419                .stream_event_for_project(*project_id, None, req)
420                .await;
421            return match attempt {
422                Ok(r) => Ok(Some(r)),
423                Err(e) => match deterministic_client_error_kind(e.as_ref()) {
424                    Some(ClientErrorKind::Scoping) => {
425                        if !*warned {
426                            eprintln!("{}", undeliverable_warning(*project_id));
427                            *warned = true;
428                        }
429                        Ok(None)
430                    }
431                    _ => Err(e),
432                },
433            };
434        }
435        Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
436    };
437    match capture_pid {
438        None => client.stream_event(repo_id, req).await.map(Some),
439        Some(pid) => {
440            let attempt = client
441                .stream_event_for_project(pid, Some(repo_id), req)
442                .await;
443            let kind = match &attempt {
444                Ok(_) => None,
445                Err(e) => deterministic_client_error_kind(e.as_ref()),
446            };
447            match (attempt, kind) {
448                (Ok(r), _) => Ok(Some(r)),
449                (Err(_), Some(kind)) => {
450                    if !*warned {
451                        // Since Keycloak, a 403 has a SECOND and now more common
452                        // cause: the account has no `tracing` realm role at all,
453                        // in which case nothing this hook does will work and
454                        // `project switch` is confidently wrong advice — on the
455                        // code path users hit most. The server's 403 envelope
456                        // isn't distinguishable from here (see
457                        // `ClientErrorKind`), so the wording names both.
458                        eprintln!("{}", fallback_warning(pid, &kind));
459                        *warned = true;
460                    }
461                    // Repo-scoped fallback: the server deduces the project itself.
462                    client.stream_event(repo_id, req).await.map(Some)
463                }
464                // transient — propagate for buffer/retry
465                (Err(e), None) => Err(e),
466            }
467        }
468    }
469}
470
471/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
472/// byte-offset semantics of `read_new_transcript_lines`: returns
473/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
474/// `transcript_offset` (base for the server's per-line `chunk_index`) and
475/// `next_offset` is persisted to `.stream_offset`.
476pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
477    (start_offset, start_offset + records_len)
478}
479
480/// Choose the transcript source for a stream event. Inline records (from a
481/// plugin-based agent like OpenCode) win over the file-read result whenever the
482/// hook event carries them — INCLUDING an empty vec, so an event with no new
483/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
484/// instead of resetting it to the file-path's 0.
485pub fn resolve_transcript_source(
486    inline_records: Option<Vec<serde_json::Value>>,
487    prior_offset: i64,
488    file_result: (Vec<serde_json::Value>, i64, i64),
489) -> (Vec<serde_json::Value>, i64, i64) {
490    match inline_records {
491        Some(records) => {
492            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
493            (records, send, next)
494        }
495        None => file_result,
496    }
497}
498
499/// Derive the event-level tool-error flag from inline transcript records.
500/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
501/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
502/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
503/// record found, or `None` when there is none (non-tool events).
504pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
505    lines.iter().find_map(|line| {
506        let msg = line.get("message")?;
507        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
508            Some(
509                msg.get("isError")
510                    .and_then(|v| v.as_bool())
511                    .unwrap_or(false),
512            )
513        } else {
514            None
515        }
516    })
517}
518
519/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
520/// Factored out so the mapping is testable without the network/FS-bound
521/// `run_stream`.
522pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
523    req.tool = Some(agent.tool_name().to_string());
524    req.protocol_version = agent.protocol_version() as u32;
525}
526
527pub async fn run_stream(
528    event_type: &str,
529    agent: crate::agent::Agent,
530) -> Result<(), Box<dyn std::error::Error>> {
531    // 1. Read HookEvent from stdin
532    let mut input = String::new();
533    io::stdin().read_to_string(&mut input)?;
534    let mut hook_event = parse_hook_event(&input)?;
535
536    // Resolve project_root and session_dir via the shared git-aware resolver.
537    //
538    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
539    // the primary worktree root, so it works correctly from a primary checkout,
540    // a nested worktree, AND a sibling linked worktree (where the primary
541    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
542    // would fall back to hook_cwd itself, fail to load config, and silently
543    // drop the event).
544    //
545    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
546    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
547    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
548    // just below runs BEFORE the config/credentials check and can itself
549    // `?`-exit early — that remains graceful because `main.rs` catches all
550    // `Err` from `run_stream` and exits 0 without blocking the tool.
551    let hook_cwd = Path::new(&hook_event.cwd);
552    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
553    if resolved.source == crate::paths::ProjectRootSource::Fallback {
554        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
555        // we are about to create a fresh `.tracevault/` at the hook's working
556        // directory — which is how stray per-subdirectory `.tracevault/` dirs
557        // appear. Surface it (best-effort; stderr never blocks the hook).
558        eprintln!(
559            "tracevault: warning: could not resolve a git project root from {}; \
560             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
561             that it runs inside the repository to keep sessions under the repo root.",
562            hook_cwd.display()
563        );
564    }
565    let project_root = resolved.root;
566
567    // 2. Create session dir
568    fs::create_dir_all(&session_dir)?;
569
570    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
571    // inside whatever `.tracevault/` we just created — including a per-subproject
572    // one. `tracevault init` writes this for the root dir, but runtime-created
573    // dirs would otherwise have no .gitignore and leak sessions into commits.
574    // Best-effort: never fail the hook on this.
575    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
576
577    // Write origin marker so verify-start can disambiguate sessions by worktree.
578    // Best-effort: never fail the hook on marker errors. Uses the shared
579    // canonicalizing helper so the value matches what verify-start compares
580    // against on the read side.
581    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
582    let _ = fs::write(session_dir.join("origin"), &worktree_top);
583
584    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
585    //    it both orders events and is a stable idempotency key — no shared
586    //    `.event_counter` file (which raced between concurrent parallel-tool
587    //    hooks and could collide/drop events).
588    let event_uuid = uuid::Uuid::now_v7();
589
590    // 4. Read new transcript lines
591    let transcript_path = Path::new(&hook_event.transcript_path);
592    let offset_path = session_dir.join(".stream_offset");
593    // transcript_offset carries the batch START byte offset so the server
594    // derives a stable per-line chunk_index across overlapping/retried reads;
595    // .stream_offset persists the END (next read position).
596    let (transcript_lines, start_offset, new_offset) =
597        read_new_transcript_lines(transcript_path, &offset_path)?;
598
599    // Fileless inline path (OpenCode): a plugin-based agent with no single
600    // tailable transcript supplies records directly on the hook event. When
601    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
602    // sends `transcript_records: []`) — they take priority over the file-read
603    // result. `.stream_offset` is reused as a per-session RECORD counter so
604    // the server's chunk_index stays stable/monotonic across retries, exactly
605    // as with the byte-offset path. Treating an empty vec as "no new
606    // records" rather than "fall back to the file" matters: OpenCode's
607    // `transcript_path` is always "", so the file-read result is always
608    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
609    // offset back to 0 and collide with earlier turns' chunk_index on the
610    // server.
611    // Only inline (plugin-based) events override the file-read result, and only
612    // they need `.stream_offset` re-read as a record counter. File-based agents
613    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
614    // the byte-offset values from `read_new_transcript_lines` above.
615    let is_inline = hook_event.transcript_records.is_some();
616    let (transcript_lines, start_offset, new_offset) = if is_inline {
617        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
618        // `.stream_offset` must NOT silently reset to 0 — that would restart the
619        // record counter and collide with earlier turns' chunk_index on the
620        // server (the offset-clobber failure mode). Propagate the error instead;
621        // `main` treats a hook error as non-fatal (exits 0 without blocking the
622        // tool call). Negatives are clamped to 0 defensively.
623        let prior_offset: i64 = if offset_path.exists() {
624            let content = fs::read_to_string(&offset_path)?;
625            content
626                .trim()
627                .parse::<i64>()
628                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
629                .max(0)
630        } else {
631            0
632        };
633        // `take()` moves the records out (nothing below reads
634        // `transcript_records` again) — avoids deep-cloning a potentially
635        // large payload (full bash stdout / file contents) on the hook path.
636        resolve_transcript_source(
637            hook_event.transcript_records.take(),
638            prior_offset,
639            (transcript_lines, start_offset, new_offset),
640        )
641    } else {
642        (transcript_lines, start_offset, new_offset)
643    };
644
645    // 5. Build StreamEventRequest
646    let stream_event_type = match event_type {
647        "notification" => StreamEventType::SessionStart,
648        "stop" => StreamEventType::SessionEnd,
649        _ => StreamEventType::ToolUse,
650    };
651
652    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
653    // events have no tool_use_id, so fall back to a forwarded `toolResult`
654    // record's `isError` — otherwise a failed OpenCode tool would render as
655    // successful (the event-level flag file-based agents populate would be None).
656    let tool_is_error = hook_event
657        .tool_use_id
658        .as_deref()
659        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
660        .or_else(|| inline_tool_is_error(&transcript_lines));
661
662    // Load config once, up front, so it can back both the user-level context
663    // layer resolution below and the repo_id lookup further down — avoids a
664    // redundant second read of the same file. `try_load` keeps the
665    // missing/malformed distinction so the required-config error further down
666    // can report which one it is.
667    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
668    // user context" — `resolve_user_context` below falls back to the user-level
669    // config in that case. A malformed repo config is surfaced as an error
670    // later (the required-config check), not silently dropped here.
671    let config = crate::config::TracevaultConfig::try_load(&project_root);
672    // Repo config's user_context wins when the repo configured it; otherwise
673    // fall back to the user-level ~/.config/tracevault/config.toml. This is
674    // what lets a detached session (no checkout) still carry user context.
675    let repo_uc = config
676        .as_ref()
677        .ok()
678        .and_then(|opt| opt.as_ref())
679        .and_then(|c| c.user_context.clone());
680    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
681
682    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
683    // global and per-worktree) and extract fields before building the
684    // request.  Using `effective` means parallel sessions in different linked
685    // worktrees each stamp their own per-worktree context without
686    // interfering with each other.
687    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
688    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
689
690    let mut req = StreamEventRequest {
691        protocol_version: 1,
692        tool: Some("claude-code".to_string()),
693        event_type: stream_event_type,
694        session_id: hook_event.session_id.clone(),
695        timestamp: chrono::Utc::now(),
696        hook_event_name: Some(hook_event.hook_event_name.clone()),
697        tool_name: hook_event.tool_name.clone(),
698        tool_use_id: hook_event.tool_use_id.clone(),
699        tool_input: hook_event.tool_input.clone(),
700        tool_response: hook_event.tool_response.clone(),
701        tool_is_error,
702        event_index: None,
703        event_uuid: Some(event_uuid),
704        transcript_lines: if transcript_lines.is_empty() {
705            None
706        } else {
707            Some(transcript_lines)
708        },
709        transcript_offset: Some(start_offset),
710        model: None,
711        cwd: Some(hook_event.cwd.clone()),
712        final_stats: None,
713        flow_id: ctx_flow_id,
714        labels: ctx_labels,
715        params: ctx_params,
716    };
717
718    stamp_agent(&mut req, agent);
719
720    req.truncate_large_fields();
721
722    // 6. Resolve credentials
723    let (server_url, credential) = crate::credentials::resolve_credentials(&project_root)?;
724
725    // 7. Config (loaded above, alongside the user-level context layer
726    // resolution) no longer directly gates repo_id — a missing config is not
727    // fatal on its own, since the repo may instead resolve via the
728    // workspace-mode precedence chain (session binding / subagent worktree
729    // override) below. A malformed config is still surfaced here — that's
730    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
731    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
732    // below).
733    if let Err(e) = &config {
734        return Err(format!("malformed .tracevault/config.toml: {e}").into());
735    }
736
737    // Resolve the effective repo binding (workspace/detached mode). Bound
738    // mode (a pinned config.toml) still works — it's the lowest-precedence
739    // tier, wired below via `binding_from_config`, fed from the `config`
740    // already loaded above (no second read of config.toml on this hot path).
741    let session = crate::session_state::load(&hook_event.session_id);
742    let bound = config
743        .as_ref()
744        .ok()
745        .and_then(|opt| opt.as_ref())
746        .and_then(crate::resolution::binding_from_config);
747    let user_default = crate::user_default::load();
748    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
749    // Graceful no-op, exactly like the hook's normal success path. Do NOT
750    // error: a failing hook would block the tool.
751    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
752        let response = HookResponse::allow();
753        println!("{}", serde_json::to_string(&response)?);
754        Ok(())
755    };
756    // Explicit local project binding (if any) overrides server-side repo
757    // deduction. Computed BEFORE the attribution gate below, reusing the
758    // already-loaded session + worktree used just above for the repo-binding
759    // resolution: a repo-less session is attributable by project alone, so the
760    // project must be known before deciding whether this event can be sent.
761    let capture_pid = capture_project(&session, Some(worktree_top.as_str()));
762
763    // Ship if EITHER a repo or a project resolved; no-op only when neither
764    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
765    // session-state file whose repo_id could carry path separators into the
766    // pending filename — such a binding degrades to project-only inside
767    // `attribution_for` rather than dropping the event.)
768    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
769        no_op_allow()?;
770        return Ok(());
771    };
772
773    // 8. Create ApiClient
774    let server_url = server_url.ok_or("server_url not configured")?;
775    let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
776
777    // 9. Try drain pending queue and send
778    let pending_path = pending_path_for(&session_dir, &attribution);
779    let pending_events = drain_pending(&pending_path)?;
780
781    let mut send_failed = false;
782    // Spans the whole invocation (pending-flush loop + live send below) so a
783    // stale binding whose repo-scoped fallback keeps succeeding warns at most
784    // once, not once per buffered event.
785    let mut warned = false;
786
787    // Send pending events first
788    for pending_json in &pending_events {
789        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
790            if send_stream_event(&client, &attribution, &pending_req, &mut warned)
791                .await
792                .is_err()
793            {
794                // Re-queue all remaining pending events
795                for evt in &pending_events {
796                    append_pending(&pending_path, evt)?;
797                }
798                send_failed = true;
799                break;
800            }
801        }
802    }
803
804    // Send current event
805    let req_json = serde_json::to_string(&req)?;
806    // The inline (OpenCode) path CONSUMES its records from the hook event — they
807    // are not re-readable like a transcript file — so its `.stream_offset` record
808    // counter must advance whenever the event is accepted for delivery, INCLUDING
809    // when it is queued after a failure. Otherwise the next inline event reuses
810    // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
811    // queued request already carries this event's `transcript_offset`, so the
812    // records keep their indices on drain. (File-based agents must NOT advance on
813    // failure: their next read re-covers these lines cumulatively/idempotently.)
814    if send_failed {
815        append_pending(&pending_path, &req_json)?;
816        if is_inline {
817            fs::write(&offset_path, new_offset.to_string())?;
818        }
819    } else {
820        match send_stream_event(&client, &attribution, &req, &mut warned).await {
821            Ok(_) => {
822                // 10. On success update .stream_offset
823                fs::write(&offset_path, new_offset.to_string())?;
824            }
825            Err(_) => {
826                // 11. On failure append to pending.jsonl (advance the inline
827                // record counter regardless — see the note above).
828                append_pending(&pending_path, &req_json)?;
829                if is_inline {
830                    fs::write(&offset_path, new_offset.to_string())?;
831                }
832            }
833        }
834    }
835
836    // 12. Always print HookResponse::allow() to stdout
837    let response = HookResponse::allow();
838    println!("{}", serde_json::to_string(&response)?);
839
840    Ok(())
841}
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846    use crate::config::UserContext;
847    use crate::context::{Context, EffectiveContext};
848    use std::collections::BTreeMap;
849
850    // ── user layer resolution: disabled config → no user layer ────────────────
851
852    #[test]
853    fn disabled_user_context_resolves_to_none() {
854        // Default/disabled `user_context` (the `Toggle(false)` variant) must
855        // resolve to `None`, matching the pre-existing hook behavior of
856        // stamping without a user layer when it isn't configured.
857        assert!(UserContext::Toggle(false).resolve().is_none());
858    }
859
860    #[test]
861    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
862        // With no user layer and no global/worktree context files present,
863        // `Context::effective` must yield a default (empty) `EffectiveContext`
864        // — i.e. passing `None` for `user_layer` is behavior-preserving.
865        let dir = tempfile::tempdir().unwrap();
866        let effective = Context::effective(dir.path(), None);
867        assert_eq!(effective, EffectiveContext::default());
868    }
869
870    // ── apply_context: all three fields populated ─────────────────────────────
871
872    #[test]
873    fn apply_context_stamps_all_fields() {
874        let dir = tempfile::tempdir().unwrap();
875        let mut params = BTreeMap::new();
876        params.insert("env".to_string(), "prod".to_string());
877        params.insert("region".to_string(), "eu-west-1".to_string());
878
879        let ctx = EffectiveContext {
880            flow_id: Some("flow-xyz".to_string()),
881            labels: vec!["backend".to_string(), "urgent".to_string()],
882            params,
883        };
884
885        let (flow_id, labels, params_out) = apply_context(ctx);
886
887        assert_eq!(flow_id, Some("flow-xyz".to_string()));
888        assert_eq!(
889            labels,
890            Some(vec!["backend".to_string(), "urgent".to_string()])
891        );
892        let p = params_out.expect("params should be Some");
893        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
894        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
895
896        // Verify the stored context round-trips through save_to → load_from →
897        // merge_layers → apply_context (stored params are now `Option<String>`).
898        let written = Context {
899            flow_id: Some("flow-xyz".to_string()),
900            labels: vec!["backend".to_string(), "urgent".to_string()],
901            params: {
902                let mut m = BTreeMap::new();
903                m.insert("env".to_string(), Some("prod".to_string()));
904                m.insert("region".to_string(), Some("eu-west-1".to_string()));
905                m
906            },
907        };
908        let ctx_path = dir.path().join(".tracevault").join("context.json");
909        written.save_to(&ctx_path).unwrap();
910        let loaded = Context::load_from(&ctx_path);
911        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
912        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
913        assert!(labels2.is_some());
914        assert!(params2.is_some());
915    }
916
917    // ── apply_context: missing context file → all None ────────────────────────
918
919    #[test]
920    fn apply_context_missing_file_all_none() {
921        let dir = tempfile::tempdir().unwrap();
922        let missing_path = dir.path().join(".tracevault").join("context.json");
923        let ctx = Context::load_from(&missing_path); // no context.json → default
924        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
925        assert!(flow_id.is_none(), "flow_id should be None");
926        assert!(labels.is_none(), "labels should be None");
927        assert!(params.is_none(), "params should be None");
928    }
929
930    // ── apply_context: empty labels vec / empty params map → None ─────────────
931
932    #[test]
933    fn apply_context_empty_collections_are_none() {
934        let ctx = EffectiveContext {
935            flow_id: None,
936            labels: vec![],
937            params: BTreeMap::new(),
938        };
939        let (flow_id, labels, params) = apply_context(ctx);
940        assert!(flow_id.is_none());
941        assert!(
942            labels.is_none(),
943            "empty labels should be None, not Some([])"
944        );
945        assert!(
946            params.is_none(),
947            "empty params should be None, not Some({{}})"
948        );
949    }
950
951    // ── apply_context: flow_id only, collections empty ────────────────────────
952
953    #[test]
954    fn apply_context_flow_id_only() {
955        let ctx = EffectiveContext {
956            flow_id: Some("my-flow".to_string()),
957            labels: vec![],
958            params: BTreeMap::new(),
959        };
960        let (flow_id, labels, params) = apply_context(ctx);
961        assert_eq!(flow_id, Some("my-flow".to_string()));
962        assert!(labels.is_none());
963        assert!(params.is_none());
964    }
965
966    // ── resolve_session_paths tests ───────────────────────────────────────────
967    //
968    // These tests verify that `resolve_session_paths` routes through the
969    // git-aware resolver so that sibling linked worktrees capture events under
970    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
971
972    use crate::test_helpers::{add_worktree, init_git_repo};
973
974    /// Primary checkout: project_root resolves to the repo root; session_dir is
975    /// under `<repo>/.tracevault/sessions/<id>/`.
976    #[test]
977    fn resolve_session_paths_primary_checkout() {
978        let tmp = tempfile::tempdir().unwrap();
979        let repo = tmp.path().join("repo");
980        std::fs::create_dir_all(&repo).unwrap();
981        init_git_repo(&repo);
982        // Create a .tracevault/ in the primary root to match a real init.
983        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
984
985        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
986        let project_root = resolved.root;
987
988        assert_eq!(
989            project_root.canonicalize().unwrap(),
990            repo.canonicalize().unwrap(),
991            "primary checkout: project_root must be repo root"
992        );
993        assert_eq!(
994            session_dir.canonicalize().unwrap_or(session_dir.clone()),
995            repo.join(".tracevault")
996                .join("sessions")
997                .join("sess-primary-123"),
998            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
999        );
1000        // session_dir must be INSIDE the primary repo, not elsewhere.
1001        assert!(
1002            session_dir.starts_with(&repo),
1003            "session_dir must be under the primary repo root"
1004        );
1005    }
1006
1007    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1008    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1009    /// git-aware resolver must return the PRIMARY root.
1010    #[test]
1011    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1012        let tmp = tempfile::tempdir().unwrap();
1013        let repo = tmp.path().join("repo");
1014        // Sibling worktree lives outside the primary repo directory.
1015        let wt = tmp.path().join("sibling-wt");
1016
1017        std::fs::create_dir_all(&repo).unwrap();
1018        init_git_repo(&repo);
1019        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1020        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1021        add_worktree(&repo, &wt);
1022
1023        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1024        let project_root = resolved.root;
1025
1026        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1027        assert_eq!(
1028            project_root.canonicalize().unwrap(),
1029            repo.canonicalize().unwrap(),
1030            "sibling worktree: project_root must be primary repo root (not worktree dir)"
1031        );
1032        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1033        assert!(
1034            session_dir.starts_with(&repo),
1035            "sibling worktree: session_dir must be under the PRIMARY repo root"
1036        );
1037        assert!(
1038            !session_dir.starts_with(&wt),
1039            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1040        );
1041        assert!(
1042            session_dir.ends_with(
1043                std::path::Path::new(".tracevault")
1044                    .join("sessions")
1045                    .join("sess-sibling-456")
1046            ),
1047            "session_dir must end with .tracevault/sessions/<session_id>"
1048        );
1049    }
1050
1051    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1052    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1053    #[test]
1054    fn resolve_session_paths_non_git_fallback() {
1055        let tmp = tempfile::tempdir().unwrap();
1056        // No git repo, no .tracevault/ anywhere.
1057        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1058        let project_root = resolved.root;
1059
1060        assert_eq!(
1061            project_root,
1062            tmp.path(),
1063            "non-git: project_root must fall back to hook_cwd"
1064        );
1065        assert_eq!(
1066            session_dir,
1067            tmp.path()
1068                .join(".tracevault")
1069                .join("sessions")
1070                .join("sess-fallback-789"),
1071            "non-git: session_dir must be relative to the fallback root"
1072        );
1073    }
1074
1075    /// The origin marker written by run_stream contains the worktree toplevel.
1076    /// This test exercises the same `paths::worktree_toplevel` helper the hook
1077    /// uses (can't call run_stream end-to-end without a real server) so the
1078    /// marker content is computed and canonicalized exactly as in production.
1079    #[test]
1080    fn origin_marker_written_in_session_dir() {
1081        let tmp = tempfile::tempdir().unwrap();
1082        let repo = tmp.path().join("repo");
1083        std::fs::create_dir_all(&repo).unwrap();
1084        init_git_repo(&repo);
1085
1086        let session_dir = repo
1087            .join(".tracevault")
1088            .join("sessions")
1089            .join("test-sess-001");
1090        std::fs::create_dir_all(&session_dir).unwrap();
1091
1092        let hook_cwd = &repo;
1093        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1094        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1095
1096        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1097        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1098        assert_eq!(
1099            origin_content.trim(),
1100            expected.as_str(),
1101            "origin marker must contain the canonicalized worktree toplevel"
1102        );
1103    }
1104
1105    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1106
1107    use crate::session_state::{RepoBinding, SessionState};
1108
1109    fn binding(id: &str) -> RepoBinding {
1110        RepoBinding {
1111            repo_id: id.into(),
1112            git_url: None,
1113            remote_id: None,
1114            codebase_name: None,
1115            updated_at: "t".into(),
1116        }
1117    }
1118
1119    /// Workspace mode: no pinned config, but the session is bound (e.g. via
1120    /// `tracevault repo switch`) — the stream event attributes to that repo.
1121    #[test]
1122    fn resolve_stream_binding_uses_session_active_when_unbound() {
1123        let session = SessionState {
1124            active: Some(binding("session-repo")),
1125            subagents: HashMap::new(),
1126            ..Default::default()
1127        };
1128        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1129        assert_eq!(got.unwrap().repo_id, "session-repo");
1130    }
1131
1132    /// Bound-mode regression: an empty session (no `repo switch` ever run)
1133    /// with a bound config.toml still resolves via the config.
1134    #[test]
1135    fn resolve_stream_binding_falls_back_to_bound_config() {
1136        let session = SessionState::default();
1137        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1138        assert_eq!(got.unwrap().repo_id, "bound-repo");
1139    }
1140
1141    /// No session binding and no bound config: nothing resolves, which is
1142    /// exactly what should trigger `run_stream`'s graceful no-op.
1143    #[test]
1144    fn resolve_stream_binding_none_when_nothing_resolves() {
1145        let session = SessionState::default();
1146        let got = resolve_stream_binding(&session, "/wt/top", None, None);
1147        assert!(got.is_none());
1148    }
1149
1150    /// Subagent override precedence: a per-worktree override for the current
1151    /// worktree wins over the session's `active` binding.
1152    #[test]
1153    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1154        let session = SessionState {
1155            active: Some(binding("session-repo")),
1156            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1157            ..Default::default()
1158        };
1159        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1160        assert_eq!(got.unwrap().repo_id, "subagent-repo");
1161    }
1162
1163    /// Workspace mode: no bound config, but a user-level default is set (e.g.
1164    /// via `tracevault repo switch --user`) — the stream event attributes to
1165    /// that repo when nothing more specific resolves.
1166    #[test]
1167    fn resolve_stream_binding_falls_back_to_user_default() {
1168        let session = SessionState::default();
1169        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1170        assert_eq!(got.unwrap().repo_id, "userdef");
1171    }
1172
1173    /// The user-level default is the LOWEST-precedence tier: a bound config
1174    /// still wins over it.
1175    #[test]
1176    fn resolve_stream_binding_prefers_bound_over_user_default() {
1177        let session = SessionState::default();
1178        let got = resolve_stream_binding(
1179            &session,
1180            "/wt/x",
1181            Some(binding("bound")),
1182            Some(binding("userdef")),
1183        );
1184        assert_eq!(got.unwrap().repo_id, "bound");
1185    }
1186
1187    // ── attribution_for: repo-or-project gate ────────────────────────────────
1188
1189    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1190        crate::session_state::RepoBinding {
1191            repo_id: repo_id.into(),
1192            git_url: None,
1193            remote_id: None,
1194            codebase_name: None,
1195            updated_at: String::new(),
1196        }
1197    }
1198
1199    /// The regression this whole change exists for: a session with a project
1200    /// binding and NO repo binding must still ship, repo-less, instead of
1201    /// being dropped by the hook.
1202    #[test]
1203    fn attribution_falls_back_to_project_when_no_repo_binds() {
1204        let pid = uuid::Uuid::new_v4();
1205        assert_eq!(
1206            attribution_for(None, Some(pid)),
1207            Some(Attribution::ProjectOnly { project_id: pid })
1208        );
1209    }
1210
1211    /// Neither binding resolves — the only case that may still no-op.
1212    #[test]
1213    fn attribution_is_none_when_neither_repo_nor_project_binds() {
1214        assert_eq!(attribution_for(None, None), None);
1215    }
1216
1217    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1218    /// server left to deduce the project.
1219    #[test]
1220    fn attribution_uses_repo_with_no_project_overlay() {
1221        let repo = uuid::Uuid::new_v4().to_string();
1222        let b = binding_with(&repo);
1223        assert_eq!(
1224            attribution_for(Some(&b), None),
1225            Some(Attribution::Repo {
1226                repo_id: repo,
1227                project: None
1228            })
1229        );
1230    }
1231
1232    /// Both bound: the project overlays the repo (project-scoped ingest
1233    /// carrying repo_id), unchanged from before.
1234    #[test]
1235    fn attribution_overlays_project_on_repo() {
1236        let repo = uuid::Uuid::new_v4().to_string();
1237        let pid = uuid::Uuid::new_v4();
1238        let b = binding_with(&repo);
1239        assert_eq!(
1240            attribution_for(Some(&b), Some(pid)),
1241            Some(Attribution::Repo {
1242                repo_id: repo,
1243                project: Some(pid)
1244            })
1245        );
1246    }
1247
1248    /// A corrupted repo_id costs the repo attribution, not the trace: it
1249    /// degrades to project-only rather than dropping the event.
1250    #[test]
1251    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
1252        let pid = uuid::Uuid::new_v4();
1253        let b = binding_with("../../escape");
1254        assert_eq!(
1255            attribution_for(Some(&b), Some(pid)),
1256            Some(Attribution::ProjectOnly { project_id: pid })
1257        );
1258    }
1259
1260    /// ...but with no project to fall back to, a corrupt repo_id still drops,
1261    /// so it can never reach the pending filename.
1262    #[test]
1263    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
1264        let b = binding_with("../../escape");
1265        assert_eq!(attribution_for(Some(&b), None), None);
1266    }
1267
1268    // ── pending queue filenames ──────────────────────────────────────────────
1269
1270    /// The repo filename is unchanged, so queues buffered by earlier releases
1271    /// are still found and drained after this upgrade.
1272    #[test]
1273    fn pending_file_name_for_a_repo_is_unchanged() {
1274        let repo = uuid::Uuid::new_v4().to_string();
1275        assert_eq!(
1276            Attribution::Repo {
1277                repo_id: repo.clone(),
1278                project: Some(uuid::Uuid::new_v4())
1279            }
1280            .pending_file_name(),
1281            format!("pending-{repo}.jsonl")
1282        );
1283    }
1284
1285    /// Repo-less queues carry the `project-` infix, which an older CLI reads
1286    /// as a non-UUID repo id and skips (see the doc comment).
1287    #[test]
1288    fn pending_file_name_for_a_project_is_distinct() {
1289        let pid = uuid::Uuid::new_v4();
1290        assert_eq!(
1291            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
1292            format!("pending-project-{pid}.jsonl")
1293        );
1294    }
1295
1296    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1297
1298    #[test]
1299    fn binding_repo_id_is_valid_accepts_real_uuid() {
1300        assert!(binding_repo_id_is_valid(
1301            "550e8400-e29b-41d4-a716-446655440000"
1302        ));
1303    }
1304
1305    #[test]
1306    fn binding_repo_id_is_valid_rejects_path_traversal() {
1307        assert!(!binding_repo_id_is_valid("../evil"));
1308    }
1309
1310    #[test]
1311    fn binding_repo_id_is_valid_rejects_empty() {
1312        assert!(!binding_repo_id_is_valid(""));
1313    }
1314
1315    #[test]
1316    fn binding_repo_id_is_valid_rejects_non_uuid() {
1317        assert!(!binding_repo_id_is_valid("not-a-uuid"));
1318    }
1319
1320    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1321
1322    #[test]
1323    fn stamp_agent_sets_tool_and_version() {
1324        use crate::agent::Agent;
1325        let mut req = StreamEventRequest {
1326            protocol_version: 1,
1327            tool: Some("claude-code".to_string()),
1328            event_type: StreamEventType::ToolUse,
1329            session_id: "s".into(),
1330            timestamp: chrono::Utc::now(),
1331            hook_event_name: None,
1332            tool_name: None,
1333            tool_use_id: None,
1334            tool_input: None,
1335            tool_response: None,
1336            tool_is_error: None,
1337            event_index: None,
1338            event_uuid: None,
1339            transcript_lines: None,
1340            transcript_offset: None,
1341            model: None,
1342            cwd: None,
1343            final_stats: None,
1344            flow_id: None,
1345            labels: None,
1346            params: None,
1347        };
1348        stamp_agent(&mut req, Agent::Codex);
1349        assert_eq!(req.tool.as_deref(), Some("codex"));
1350        assert_eq!(req.protocol_version, 2);
1351
1352        stamp_agent(&mut req, Agent::ClaudeCode);
1353        assert_eq!(req.tool.as_deref(), Some("claude-code"));
1354        assert_eq!(req.protocol_version, 1);
1355    }
1356
1357    // ── pending_path_for: per-target offline queue ───────────────────────────
1358
1359    fn repo_attr(repo_id: &str) -> Attribution {
1360        Attribution::Repo {
1361            repo_id: repo_id.into(),
1362            project: None,
1363        }
1364    }
1365
1366    #[test]
1367    fn pending_path_is_repo_scoped() {
1368        let dir = std::path::Path::new("/tmp/sess");
1369        assert_eq!(
1370            pending_path_for(dir, &repo_attr("repo-a")),
1371            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1372        );
1373        assert_ne!(
1374            pending_path_for(dir, &repo_attr("repo-a")),
1375            pending_path_for(dir, &repo_attr("repo-b")),
1376        );
1377    }
1378
1379    /// A repo-less session must not share a queue file with any repo, so its
1380    /// buffered events can never be flushed to a repo endpoint.
1381    #[test]
1382    fn pending_path_for_a_project_never_collides_with_a_repo() {
1383        let dir = std::path::Path::new("/tmp/sess");
1384        let pid = uuid::Uuid::from_u128(9);
1385        assert_eq!(
1386            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1387            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
1388        );
1389        assert_ne!(
1390            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1391            pending_path_for(dir, &repo_attr(&pid.to_string())),
1392        );
1393    }
1394
1395    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1396
1397    #[test]
1398    fn read_new_transcript_lines_empty_path_is_noop() {
1399        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1400        // An empty path must yield no lines and offset 0, never an error from
1401        // handing `Path::new("")` to exists()/File::open.
1402        let dir = tempfile::tempdir().unwrap();
1403        let offset_path = dir.path().join(".stream_offset");
1404        let (lines, start_offset, end_offset) =
1405            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1406        assert!(
1407            lines.is_empty(),
1408            "empty path must yield no transcript lines"
1409        );
1410        assert_eq!(start_offset, 0);
1411        assert_eq!(end_offset, 0);
1412    }
1413
1414    // ── read_new_transcript_lines: start_offset is stable across a persisted
1415    //    end_offset, and equals the previous read's end_offset ─────────────────
1416
1417    #[test]
1418    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1419        let dir = tempfile::tempdir().unwrap();
1420        let transcript_path = dir.path().join("transcript.jsonl");
1421        let offset_path = dir.path().join(".stream_offset");
1422
1423        fs::write(
1424            &transcript_path,
1425            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1426        )
1427        .unwrap();
1428
1429        let (lines, start_offset, end_offset) =
1430            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1431        assert_eq!(lines.len(), 2);
1432        assert_eq!(start_offset, 0, "first read starts at byte 0");
1433        assert!(end_offset > 0);
1434
1435        fs::write(&offset_path, end_offset.to_string()).unwrap();
1436
1437        let mut f = OpenOptions::new()
1438            .append(true)
1439            .open(&transcript_path)
1440            .unwrap();
1441        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1442        drop(f);
1443
1444        let (lines2, start_offset2, end_offset2) =
1445            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1446        assert_eq!(lines2.len(), 1);
1447        assert_eq!(
1448            start_offset2, end_offset,
1449            "second read's start_offset must equal the first read's persisted end_offset"
1450        );
1451        assert!(end_offset2 > start_offset2);
1452    }
1453
1454    // ── capture_project: local-only project resolver ──────────────────────────
1455
1456    #[test]
1457    fn capture_project_precedence_local_only() {
1458        use crate::session_state::{ProjectBinding, SessionState};
1459        let pb = |id: &str| ProjectBinding {
1460            project_id: id.into(),
1461            project_name: "n".into(),
1462            updated_at: "".into(),
1463        };
1464        let u = uuid::Uuid::from_u128;
1465        // session active only
1466        let s = SessionState {
1467            active_project: Some(pb(&u(2).to_string())),
1468            ..Default::default()
1469        };
1470        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
1471        // subagent worktree beats session
1472        let mut s = s;
1473        s.subagent_projects
1474            .insert("/wt".into(), pb(&u(1).to_string()));
1475        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
1476        // no worktree match -> session active
1477        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
1478        // empty session -> None (user-default file is not present in this unit test env)
1479        assert_eq!(capture_project(&SessionState::default(), None), None);
1480        // malformed stored id -> None (defensive)
1481        let bad = SessionState {
1482            active_project: Some(pb("not-a-uuid")),
1483            ..Default::default()
1484        };
1485        assert_eq!(capture_project(&bad, None), None);
1486    }
1487
1488    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
1489
1490    use std::io::BufReader;
1491    use std::net::TcpListener;
1492    use std::sync::mpsc;
1493    use std::thread;
1494    use std::time::{Duration, Instant};
1495
1496    /// How long an accept loop waits for a connection that never arrives
1497    /// (e.g. a regression that stops the client from making an expected
1498    /// request) before giving up, so the server thread exits cleanly
1499    /// instead of blocking in `accept()` forever.
1500    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
1501
1502    /// Poll a non-blocking `listener` for a connection until one arrives or
1503    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
1504    /// `WouldBlock` accept error) so callers can stop cleanly rather than
1505    /// block forever.
1506    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
1507        let deadline = Instant::now() + ACCEPT_DEADLINE;
1508        loop {
1509            match listener.accept() {
1510                Ok((stream, _)) => {
1511                    // The accepted stream's blocking mode isn't guaranteed to
1512                    // be inherited from the (non-blocking) listener across
1513                    // platforms — make it explicitly blocking so the
1514                    // subsequent read/write calls behave as before.
1515                    let _ = stream.set_nonblocking(false);
1516                    return Some(stream);
1517                }
1518                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1519                    if Instant::now() >= deadline {
1520                        return None;
1521                    }
1522                    thread::sleep(Duration::from_millis(20));
1523                }
1524                Err(_) => return None,
1525            }
1526        }
1527    }
1528
1529    /// How long a test waits for the captured request before failing (rather
1530    /// than hanging forever if the client never connects). Mirrors the
1531    /// harness in `tests/stream_event_project_test.rs`.
1532    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
1533
1534    /// Spawn a one-shot server that returns `response` (a full HTTP response)
1535    /// to the first request. Captures the HTTP request line (method + path +
1536    /// query) over the returned channel before writing the response. Mirrors
1537    /// the harness in `tests/stream_event_project_test.rs` /
1538    /// `tests/resolve_remote_test.rs`.
1539    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
1540        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1541        listener.set_nonblocking(true).unwrap();
1542        let addr = listener.local_addr().unwrap();
1543        let (tx, rx) = mpsc::channel();
1544        thread::spawn(move || {
1545            if let Some(stream) = accept_with_deadline(&listener) {
1546                let mut reader = BufReader::new(stream);
1547                let mut request_line = String::new();
1548                let _ = reader.read_line(&mut request_line);
1549                let _ = tx.send(request_line);
1550                let mut stream = reader.into_inner();
1551                let _ = stream.write_all(response.as_bytes());
1552                let _ = stream.flush();
1553            }
1554        });
1555        (format!("http://{addr}"), rx)
1556    }
1557
1558    fn ok_stream_response() -> String {
1559        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
1560            session_db_id: uuid::Uuid::nil(),
1561            event_db_id: Some(uuid::Uuid::nil()),
1562            status: "accepted".to_string(),
1563        })
1564        .unwrap();
1565        format!(
1566            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1567            body.len(),
1568            body
1569        )
1570    }
1571
1572    fn sample_stream_event_request() -> StreamEventRequest {
1573        StreamEventRequest {
1574            protocol_version: 2,
1575            tool: Some("claude-code".to_string()),
1576            event_type: StreamEventType::ToolUse,
1577            session_id: "sess-1".into(),
1578            timestamp: chrono::Utc::now(),
1579            hook_event_name: Some("PostToolUse".into()),
1580            tool_name: None,
1581            tool_use_id: None,
1582            tool_input: None,
1583            tool_response: None,
1584            tool_is_error: None,
1585            event_index: None,
1586            event_uuid: None,
1587            transcript_lines: None,
1588            transcript_offset: None,
1589            model: None,
1590            cwd: None,
1591            final_stats: None,
1592            flow_id: None,
1593            labels: None,
1594            params: None,
1595        }
1596    }
1597
1598    /// With a `SessionState` whose `active_project` is set, `capture_project`
1599    /// resolves a `capture_pid`, and `send_stream_event` must route to the
1600    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
1601    /// than the repo-scoped one.
1602    #[tokio::test]
1603    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
1604        use crate::session_state::{ProjectBinding, SessionState};
1605
1606        // Isolate from any ambient user-level project default so this test's
1607        // `capture_project` call depends only on the SessionState below —
1608        // mirrors the isolation pattern in `commands::project`'s tests.
1609        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1610        let tmp = tempfile::tempdir().unwrap();
1611        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1612        _guard.set("XDG_CONFIG_HOME", tmp.path());
1613
1614        let pid = uuid::Uuid::from_u128(99);
1615        let session = SessionState {
1616            active_project: Some(ProjectBinding {
1617                project_id: pid.to_string(),
1618                project_name: "proj".into(),
1619                updated_at: "".into(),
1620            }),
1621            ..Default::default()
1622        };
1623        let capture_pid = capture_project(&session, None);
1624        assert_eq!(capture_pid, Some(pid));
1625
1626        let resp = ok_stream_response();
1627        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1628        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1629        let req = sample_stream_event_request();
1630
1631        let mut warned = false;
1632        let got = send_stream_event(
1633            &client,
1634            &Attribution::Repo {
1635                repo_id: "11111111-1111-1111-1111-111111111111".into(),
1636                project: capture_pid,
1637            },
1638            &req,
1639            &mut warned,
1640        )
1641        .await
1642        .expect("send_stream_event must succeed");
1643        assert_eq!(
1644            got.expect("a successful send returns a response").status,
1645            "accepted"
1646        );
1647
1648        let line = rx
1649            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1650            .expect("no request captured");
1651        assert!(
1652            line.starts_with(&format!(
1653                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
1654            )),
1655            "an active project binding must route to the project-scoped endpoint, got: {line}"
1656        );
1657    }
1658
1659    /// With an empty binding (default `SessionState`, no worktree override)
1660    /// and no user-level default present in the test env, `capture_project`
1661    /// resolves `None` and `send_stream_event` must fall back to the
1662    /// repo-scoped endpoint.
1663    #[tokio::test]
1664    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
1665        use crate::session_state::SessionState;
1666
1667        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1668        let tmp = tempfile::tempdir().unwrap();
1669        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1670        // No user_project.toml under this isolated config dir, so there is no
1671        // ambient user-level default to leak in.
1672        _guard.set("XDG_CONFIG_HOME", tmp.path());
1673
1674        let capture_pid = capture_project(&SessionState::default(), None);
1675        assert_eq!(capture_pid, None);
1676
1677        let resp = ok_stream_response();
1678        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1679        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1680        let req = sample_stream_event_request();
1681
1682        let mut warned = false;
1683        let got = send_stream_event(
1684            &client,
1685            &Attribution::Repo {
1686                repo_id: "11111111-1111-1111-1111-111111111111".into(),
1687                project: capture_pid,
1688            },
1689            &req,
1690            &mut warned,
1691        )
1692        .await
1693        .expect("send_stream_event must succeed");
1694        assert_eq!(
1695            got.expect("a successful send returns a response").status,
1696            "accepted"
1697        );
1698
1699        let line = rx
1700            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1701            .expect("no request captured");
1702        assert!(
1703            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
1704            "no binding must fall back to the repo-scoped endpoint, got: {line}"
1705        );
1706    }
1707
1708    // ── I1/I2: deterministic-client-error fallback + transient no-fallback ───
1709
1710    /// Spawn a server that replies to up to `responses.len()` sequential
1711    /// connections with the given full HTTP responses, in order, capturing
1712    /// each request line over the channel. The listening socket itself is
1713    /// dropped (closing it) once all responses have been served, so any
1714    /// further connection attempt fails fast (connection refused) rather than
1715    /// hanging for the client's request timeout — this lets a test assert
1716    /// "no further request was sent" cheaply.
1717    fn spawn_n_capturing_requests(
1718        responses: Vec<&'static str>,
1719    ) -> (String, mpsc::Receiver<String>) {
1720        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1721        listener.set_nonblocking(true).unwrap();
1722        let addr = listener.local_addr().unwrap();
1723        let (tx, rx) = mpsc::channel();
1724        thread::spawn(move || {
1725            for response in responses {
1726                // If a regression stops the client from making this request
1727                // (e.g. the expected Nth call never happens), don't block
1728                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
1729                // and let the thread end so the test process can't hang.
1730                let Some(stream) = accept_with_deadline(&listener) else {
1731                    break;
1732                };
1733                let mut reader = BufReader::new(stream);
1734                let mut request_line = String::new();
1735                let _ = reader.read_line(&mut request_line);
1736                let _ = tx.send(request_line);
1737                let mut stream = reader.into_inner();
1738                let _ = stream.write_all(response.as_bytes());
1739                let _ = stream.flush();
1740            }
1741            // `listener` (and `tx`) drop here, closing the socket and the
1742            // channel — a stray extra request gets ECONNREFUSED immediately
1743            // instead of hanging, and a stray extra `rx.recv` returns
1744            // Disconnected immediately instead of blocking.
1745        });
1746        (format!("http://{addr}"), rx)
1747    }
1748
1749    /// I1: a deterministic 400 ("is not a member of project ...") from the
1750    /// project-scoped endpoint must fall back to the repo-scoped endpoint —
1751    /// which then succeeds — rather than being buffered/retried forever. Both
1752    /// endpoints must be hit, project first, then repo.
1753    #[tokio::test]
1754    async fn send_stream_event_falls_back_to_repo_scoped_on_deterministic_400() {
1755        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
1756        let resp_400 = format!(
1757            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1758            body_400.len(),
1759            body_400
1760        );
1761        let resp_200 = ok_stream_response();
1762
1763        let (base, rx) = spawn_n_capturing_requests(vec![
1764            Box::leak(resp_400.into_boxed_str()),
1765            Box::leak(resp_200.into_boxed_str()),
1766        ]);
1767        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1768        let req = sample_stream_event_request();
1769        let pid = uuid::Uuid::from_u128(42);
1770
1771        let mut warned = false;
1772        let got = send_stream_event(
1773            &client,
1774            &Attribution::Repo {
1775                repo_id: "11111111-1111-1111-1111-111111111111".into(),
1776                project: Some(pid),
1777            },
1778            &req,
1779            &mut warned,
1780        )
1781        .await
1782        .expect("a deterministic 400 must fall back to repo-scoped and succeed");
1783        assert_eq!(
1784            got.expect("a successful send returns a response").status,
1785            "accepted"
1786        );
1787
1788        let first = rx
1789            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1790            .expect("no first request captured");
1791        assert!(
1792            first.contains(&format!("/projects/{pid}/stream")),
1793            "first request must hit the project-scoped endpoint, got: {first}"
1794        );
1795
1796        let second = rx
1797            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1798            .expect("no second (fallback) request captured");
1799        assert!(
1800            second.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
1801            "second request must fall back to the repo-scoped endpoint, got: {second}"
1802        );
1803    }
1804
1805    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
1806    /// project endpoint with NO `repo_id` query pair. This is the wire shape
1807    /// the server documents as "repo-less (0-repo) projects are supported".
1808    #[tokio::test]
1809    async fn send_stream_event_project_only_omits_repo_id() {
1810        let resp = ok_stream_response();
1811        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1812        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1813        let req = sample_stream_event_request();
1814        let pid = uuid::Uuid::from_u128(11);
1815
1816        let mut warned = false;
1817        let got = send_stream_event(
1818            &client,
1819            &Attribution::ProjectOnly { project_id: pid },
1820            &req,
1821            &mut warned,
1822        )
1823        .await
1824        .expect("a repo-less project send must succeed");
1825        assert_eq!(
1826            got.expect("a successful send returns a response").status,
1827            "accepted"
1828        );
1829
1830        let line = rx
1831            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1832            .expect("no request captured");
1833        assert!(
1834            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
1835            "expected a bare project path with no query string, got: {line}"
1836        );
1837        assert!(
1838            !warned,
1839            "a repo-less send has no fallback and must not warn about one"
1840        );
1841    }
1842
1843    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
1844    /// the queue is keyed by the very project id the server says does not
1845    /// resolve, so a corrected binding writes to a different file and these
1846    /// events would never be retried — they would just accumulate, one per
1847    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
1848    /// trigger a second, impossible request.
1849    #[tokio::test]
1850    async fn send_stream_event_project_only_drops_on_scoping_4xx() {
1851        let body = "no such project";
1852        let resp_404 = format!(
1853            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1854            body.len(),
1855            body
1856        );
1857        // TWO responses are staged although only one request is expected. With
1858        // a single response the helper drops its sender the moment the list is
1859        // exhausted, so the "no second request" assertion below would pass on
1860        // `Disconnected` whether or not a second request happened — a vacuous
1861        // check. Staging a spare keeps the server accepting, so a stray
1862        // request really is captured and really fails the test.
1863        let (base, rx) = spawn_n_capturing_requests(vec![
1864            Box::leak(resp_404.clone().into_boxed_str()),
1865            Box::leak(resp_404.into_boxed_str()),
1866        ]);
1867        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1868        let req = sample_stream_event_request();
1869        let pid = uuid::Uuid::from_u128(12);
1870
1871        let mut warned = false;
1872        let got = send_stream_event(
1873            &client,
1874            &Attribution::ProjectOnly { project_id: pid },
1875            &req,
1876            &mut warned,
1877        )
1878        .await
1879        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
1880        assert!(
1881            got.is_none(),
1882            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
1883        );
1884        assert!(
1885            warned,
1886            "dropping data silently is the failure mode to avoid"
1887        );
1888
1889        let first = rx
1890            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1891            .expect("no request captured");
1892        assert!(
1893            first.contains(&format!("/projects/{pid}/stream")),
1894            "must hit the project-scoped endpoint, got: {first}"
1895        );
1896        assert!(
1897            rx.recv_timeout(Duration::from_millis(500)).is_err(),
1898            "a repo-less send must make exactly one request — no fallback exists"
1899        );
1900    }
1901
1902    /// A 403 is NOT dropped. It can mean the account lacks the realm role,
1903    /// which an administrator can grant — after which the buffered events do
1904    /// deliver. It must propagate so the caller queues them.
1905    #[tokio::test]
1906    async fn send_stream_event_project_only_buffers_on_403() {
1907        let body = "forbidden";
1908        let resp_403 = format!(
1909            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1910            body.len(),
1911            body
1912        );
1913        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
1914        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1915        let req = sample_stream_event_request();
1916
1917        let mut warned = false;
1918        let err = send_stream_event(
1919            &client,
1920            &Attribution::ProjectOnly {
1921                project_id: uuid::Uuid::from_u128(13),
1922            },
1923            &req,
1924            &mut warned,
1925        )
1926        .await
1927        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
1928        assert!(
1929            err.to_string().contains("403"),
1930            "propagated error must reflect the status, got: {err}"
1931        );
1932    }
1933
1934    /// I2: a transient 503 from the project-scoped endpoint must propagate as
1935    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
1936    /// existing buffer/retry logic in `run_stream` still handles it. Only one
1937    /// request (to the project endpoint) may be observed.
1938    #[tokio::test]
1939    async fn send_stream_event_does_not_fall_back_on_transient_503() {
1940        let body_503 = "internal error";
1941        let resp_503 = format!(
1942            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1943            body_503.len(),
1944            body_503
1945        );
1946        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
1947        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1948        let req = sample_stream_event_request();
1949        let pid = uuid::Uuid::from_u128(7);
1950
1951        let mut warned = false;
1952        let err = send_stream_event(
1953            &client,
1954            &Attribution::Repo {
1955                repo_id: "11111111-1111-1111-1111-111111111111".into(),
1956                project: Some(pid),
1957            },
1958            &req,
1959            &mut warned,
1960        )
1961        .await
1962        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
1963        assert!(
1964            err.to_string().contains("503"),
1965            "propagated error must reflect the transient status, got: {err}"
1966        );
1967        assert!(
1968            deterministic_client_error_kind(err.as_ref()).is_none(),
1969            "a 503 must not be classified as a deterministic client error"
1970        );
1971
1972        let first = rx
1973            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1974            .expect("no request captured");
1975        assert!(
1976            first.contains(&format!("/projects/{pid}/stream")),
1977            "must hit the project-scoped endpoint, got: {first}"
1978        );
1979
1980        // The mock server only serves ONE response and then drops its
1981        // listener/sender — a stray fallback request would either fail the
1982        // `expect_err` above (if it somehow succeeded) or, if it also failed,
1983        // would still mean a second request was attempted. Confirming the
1984        // channel is immediately disconnected (rather than blocking) proves
1985        // no second request was ever sent.
1986        assert!(
1987            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
1988            "no second (fallback) request should have been sent for a transient error"
1989        );
1990    }
1991
1992    /// A 403 must be classified apart from the binding/scoping statuses: since
1993    /// Keycloak it has a second, now more common cause (no `tracing` realm role
1994    /// at all) whose advice is completely different.
1995    #[test]
1996    fn a_403_is_classified_apart_from_the_scoping_statuses() {
1997        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
1998        assert_eq!(
1999            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
2000            Some(ClientErrorKind::Forbidden)
2001        );
2002        for scoping in [
2003            "Stream failed (400 Bad Request): {}",
2004            "Stream failed (404 Not Found): {}",
2005            "Stream failed (409 Conflict): {}",
2006        ] {
2007            assert_eq!(
2008                deterministic_client_error_kind(err(scoping).as_ref()),
2009                Some(ClientErrorKind::Scoping),
2010                "{scoping}"
2011            );
2012        }
2013        // Unchanged: 401 and transient failures are not deterministic client
2014        // errors and must keep propagating to buffer/retry.
2015        for transient in [
2016            "Stream failed (401 Unauthorized): {}",
2017            "Stream failed (503 Service Unavailable): {}",
2018            "error sending request for url (http://x/stream)",
2019        ] {
2020            assert_eq!(
2021                deterministic_client_error_kind(err(transient).as_ref()),
2022                None,
2023                "{transient}"
2024            );
2025        }
2026    }
2027
2028    /// The 403 warning must not tell a user whose account has no `tracing` role
2029    /// to switch projects, which cannot possibly help. It names both causes; the
2030    /// scoping statuses keep the precise project wording.
2031    #[test]
2032    fn the_403_warning_names_the_realm_role_as_well_as_the_project() {
2033        let pid = uuid::Uuid::from_u128(7);
2034
2035        let forbidden = fallback_warning(pid, &ClientErrorKind::Forbidden);
2036        assert!(
2037            forbidden.contains("`tracing` Keycloak realm role"),
2038            "must offer the missing-role explanation: {forbidden}"
2039        );
2040        assert!(
2041            forbidden.contains("project switch"),
2042            "must still offer the project explanation: {forbidden}"
2043        );
2044        assert!(
2045            forbidden.contains("Either"),
2046            "must present them as alternatives, not assert one: {forbidden}"
2047        );
2048        assert!(forbidden.contains(&pid.to_string()));
2049
2050        // A 400/404/409 genuinely IS a binding problem, so that wording stays
2051        // unhedged — hedging everything would dilute the useful case.
2052        let scoping = fallback_warning(pid, &ClientErrorKind::Scoping);
2053        assert!(scoping.contains("project switch"), "{scoping}");
2054        assert!(
2055            !scoping.contains("realm role"),
2056            "the scoping case must not mention the realm role: {scoping}"
2057        );
2058    }
2059}