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/// Offline-queue path for a specific repo binding. Keyed by repo id so a
119/// mid-session rebind (workspace mode) can never flush one repo's queued
120/// events to another.
121fn pending_path_for(session_dir: &Path, repo_id: &str) -> std::path::PathBuf {
122    session_dir.join(format!("pending-{repo_id}.jsonl"))
123}
124
125/// Resolve the project root and session directory for a stream hook invocation.
126///
127/// This is the pure, testable core of `run_stream`'s path resolution. It uses
128/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
129/// --git-common-dir` first, so it correctly resolves to the **primary**
130/// `.tracevault/` directory from any worktree — including sibling linked
131/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
132///
133/// Returns `(resolved, session_dir)` — the resolved
134/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
135/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
136/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
137pub fn resolve_session_paths(
138    hook_cwd: &Path,
139    session_id: &str,
140) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
141    let resolved = crate::paths::resolve_project_root(hook_cwd);
142    let session_dir = resolved
143        .root
144        .join(".tracevault")
145        .join("sessions")
146        .join(session_id);
147    (resolved, session_dir)
148}
149
150/// A resolved binding is usable for hook attribution only if its repo_id is a
151/// real UUID — guards against a corrupted/edited session-state file injecting
152/// path separators into the pending-<repo_id>.jsonl filename.
153fn binding_repo_id_is_valid(repo_id: &str) -> bool {
154    uuid::Uuid::parse_str(repo_id).is_ok()
155}
156
157/// The effective repo binding for a stream event, given the loaded session
158/// state, the event's worktree, and the bound-config fallback. Pure — the
159/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
160pub(crate) fn resolve_stream_binding(
161    session: &crate::session_state::SessionState,
162    worktree: &str,
163    bound: Option<crate::session_state::RepoBinding>,
164    user_default: Option<crate::session_state::RepoBinding>,
165) -> Option<crate::session_state::RepoBinding> {
166    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
167        repo_flag: None,
168        session,
169        worktree_path: Some(worktree),
170        bound,
171        user_default,
172    })
173    .map(|(b, _)| b)
174}
175
176/// Resolve the capture-time project from LOCAL, UUID-bearing bindings only — no
177/// network (the hook fires per event in a short-lived process). Precedence:
178/// subagent worktree override -> session `active_project` -> user-level default.
179/// Repo config `default_project` (a name) is intentionally excluded: honoring it
180/// would need a per-event `list_projects` call. `None` -> fall back to the
181/// repo-scoped stream (server deduces).
182fn capture_project(
183    session: &crate::session_state::SessionState,
184    worktree_path: Option<&str>,
185) -> Option<uuid::Uuid> {
186    use crate::resolution::{effective_project, ProjectResolveInputs};
187    let local = effective_project(&ProjectResolveInputs {
188        project_flag: None,
189        session,
190        worktree_path,
191        config_default: None,
192    })
193    .map(|(b, _)| b)
194    .or_else(crate::user_project_default::load)?;
195    local.project_id.parse::<uuid::Uuid>().ok()
196}
197
198/// True when a stream-send error's rendered message carries a `(4xx ...)`
199/// status marker — i.e. the server deterministically rejected the request in
200/// a way that will never succeed on blind retry (bad binding, missing
201/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
202/// transport/network/timeout failures (which have no `(NNN ` marker at all,
203/// or a 5xx one) — those remain transient and must keep propagating so the
204/// existing buffer/retry logic in `run_stream` still applies to them.
205///
206/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
207/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
208fn is_deterministic_client_error(e: &dyn std::error::Error) -> bool {
209    let s = e.to_string();
210    // 401 is deliberately excluded: it's an authentication failure (bad/expired
211    // token), not a project-scoping problem, and the repo-scoped fallback uses
212    // the SAME token — it would also 401, so falling back just wastes a
213    // request before the error propagates to buffer/retry. 403 stays in: it
214    // means the token is valid but lacks TracePush on the bound project, and
215    // the repo-scoped fallback (a different authorization check) can help.
216    ["(400 ", "(403 ", "(404 ", "(409 "]
217        .iter()
218        .any(|marker| s.contains(marker))
219}
220
221/// Send a single stream event, routing to the project-scoped endpoint when a
222/// local project binding resolved (`capture_pid = Some(_)`), else the
223/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
224/// the pending-flush loop and the live send share one branch.
225///
226/// When `capture_pid` is `Some(_)` and the project-scoped send fails with a
227/// deterministic client error (the bound project doesn't apply to this repo:
228/// not a member, or the caller lacks `TracePush` on it, or — after a prior
229/// fallback — the repo-scoped 409 multi-project refusal), this falls back to
230/// the repo-scoped endpoint ONCE and lets the server deduce the repo's
231/// project, warning so the miss is visible. A transient error (5xx,
232/// network/transport, timeout) is NOT retried here — it propagates so the
233/// caller's existing buffer/retry logic runs unchanged.
234///
235/// `fallback_warned` is shared across every call made for a single hook
236/// invocation (both the pending-flush loop and the live send). The
237/// pending-flush loop only `break`s on `Err`, not on a fallback that itself
238/// returns `Ok` — so a stale binding whose repo-scoped fallback keeps
239/// succeeding would otherwise print the warning once per buffered event.
240/// Gating on `*fallback_warned` caps it at one warning per invocation while
241/// leaving the fallback behavior itself unchanged.
242async fn send_stream_event(
243    client: &crate::api_client::ApiClient,
244    org_slug: &str,
245    repo_id: &str,
246    capture_pid: Option<uuid::Uuid>,
247    req: &StreamEventRequest,
248    fallback_warned: &mut bool,
249) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn std::error::Error>> {
250    match capture_pid {
251        None => client.stream_event(org_slug, repo_id, req).await,
252        Some(pid) => match client
253            .stream_event_for_project(org_slug, pid, repo_id, req)
254            .await
255        {
256            Ok(r) => Ok(r),
257            Err(e) if is_deterministic_client_error(e.as_ref()) => {
258                if !*fallback_warned {
259                    eprintln!(
260                        "tracevault: warning: active project {pid} does not apply to this repo (not a member, or missing permission); attributing via repo deduction instead. Run `tracevault project switch <name>` to update."
261                    );
262                    *fallback_warned = true;
263                }
264                // Repo-scoped fallback: the server deduces the project itself.
265                client.stream_event(org_slug, repo_id, req).await
266            }
267            Err(e) => Err(e), // transient — propagate for buffer/retry
268        },
269    }
270}
271
272/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
273/// byte-offset semantics of `read_new_transcript_lines`: returns
274/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
275/// `transcript_offset` (base for the server's per-line `chunk_index`) and
276/// `next_offset` is persisted to `.stream_offset`.
277pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
278    (start_offset, start_offset + records_len)
279}
280
281/// Choose the transcript source for a stream event. Inline records (from a
282/// plugin-based agent like OpenCode) win over the file-read result whenever the
283/// hook event carries them — INCLUDING an empty vec, so an event with no new
284/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
285/// instead of resetting it to the file-path's 0.
286pub fn resolve_transcript_source(
287    inline_records: Option<Vec<serde_json::Value>>,
288    prior_offset: i64,
289    file_result: (Vec<serde_json::Value>, i64, i64),
290) -> (Vec<serde_json::Value>, i64, i64) {
291    match inline_records {
292        Some(records) => {
293            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
294            (records, send, next)
295        }
296        None => file_result,
297    }
298}
299
300/// Derive the event-level tool-error flag from inline transcript records.
301/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
302/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
303/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
304/// record found, or `None` when there is none (non-tool events).
305pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
306    lines.iter().find_map(|line| {
307        let msg = line.get("message")?;
308        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
309            Some(
310                msg.get("isError")
311                    .and_then(|v| v.as_bool())
312                    .unwrap_or(false),
313            )
314        } else {
315            None
316        }
317    })
318}
319
320/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
321/// Factored out so the mapping is testable without the network/FS-bound
322/// `run_stream`.
323pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
324    req.tool = Some(agent.tool_name().to_string());
325    req.protocol_version = agent.protocol_version() as u32;
326}
327
328pub async fn run_stream(
329    event_type: &str,
330    agent: crate::agent::Agent,
331) -> Result<(), Box<dyn std::error::Error>> {
332    // 1. Read HookEvent from stdin
333    let mut input = String::new();
334    io::stdin().read_to_string(&mut input)?;
335    let mut hook_event = parse_hook_event(&input)?;
336
337    // Resolve project_root and session_dir via the shared git-aware resolver.
338    //
339    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
340    // the primary worktree root, so it works correctly from a primary checkout,
341    // a nested worktree, AND a sibling linked worktree (where the primary
342    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
343    // would fall back to hook_cwd itself, fail to load config, and silently
344    // drop the event).
345    //
346    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
347    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
348    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
349    // just below runs BEFORE the config/credentials check and can itself
350    // `?`-exit early — that remains graceful because `main.rs` catches all
351    // `Err` from `run_stream` and exits 0 without blocking the tool.
352    let hook_cwd = Path::new(&hook_event.cwd);
353    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
354    if resolved.source == crate::paths::ProjectRootSource::Fallback {
355        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
356        // we are about to create a fresh `.tracevault/` at the hook's working
357        // directory — which is how stray per-subdirectory `.tracevault/` dirs
358        // appear. Surface it (best-effort; stderr never blocks the hook).
359        eprintln!(
360            "tracevault: warning: could not resolve a git project root from {}; \
361             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
362             that it runs inside the repository to keep sessions under the repo root.",
363            hook_cwd.display()
364        );
365    }
366    let project_root = resolved.root;
367
368    // 2. Create session dir
369    fs::create_dir_all(&session_dir)?;
370
371    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
372    // inside whatever `.tracevault/` we just created — including a per-subproject
373    // one. `tracevault init` writes this for the root dir, but runtime-created
374    // dirs would otherwise have no .gitignore and leak sessions into commits.
375    // Best-effort: never fail the hook on this.
376    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
377
378    // Write origin marker so verify-start can disambiguate sessions by worktree.
379    // Best-effort: never fail the hook on marker errors. Uses the shared
380    // canonicalizing helper so the value matches what verify-start compares
381    // against on the read side.
382    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
383    let _ = fs::write(session_dir.join("origin"), &worktree_top);
384
385    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
386    //    it both orders events and is a stable idempotency key — no shared
387    //    `.event_counter` file (which raced between concurrent parallel-tool
388    //    hooks and could collide/drop events).
389    let event_uuid = uuid::Uuid::now_v7();
390
391    // 4. Read new transcript lines
392    let transcript_path = Path::new(&hook_event.transcript_path);
393    let offset_path = session_dir.join(".stream_offset");
394    // transcript_offset carries the batch START byte offset so the server
395    // derives a stable per-line chunk_index across overlapping/retried reads;
396    // .stream_offset persists the END (next read position).
397    let (transcript_lines, start_offset, new_offset) =
398        read_new_transcript_lines(transcript_path, &offset_path)?;
399
400    // Fileless inline path (OpenCode): a plugin-based agent with no single
401    // tailable transcript supplies records directly on the hook event. When
402    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
403    // sends `transcript_records: []`) — they take priority over the file-read
404    // result. `.stream_offset` is reused as a per-session RECORD counter so
405    // the server's chunk_index stays stable/monotonic across retries, exactly
406    // as with the byte-offset path. Treating an empty vec as "no new
407    // records" rather than "fall back to the file" matters: OpenCode's
408    // `transcript_path` is always "", so the file-read result is always
409    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
410    // offset back to 0 and collide with earlier turns' chunk_index on the
411    // server.
412    // Only inline (plugin-based) events override the file-read result, and only
413    // they need `.stream_offset` re-read as a record counter. File-based agents
414    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
415    // the byte-offset values from `read_new_transcript_lines` above.
416    let is_inline = hook_event.transcript_records.is_some();
417    let (transcript_lines, start_offset, new_offset) = if is_inline {
418        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
419        // `.stream_offset` must NOT silently reset to 0 — that would restart the
420        // record counter and collide with earlier turns' chunk_index on the
421        // server (the offset-clobber failure mode). Propagate the error instead;
422        // `main` treats a hook error as non-fatal (exits 0 without blocking the
423        // tool call). Negatives are clamped to 0 defensively.
424        let prior_offset: i64 = if offset_path.exists() {
425            let content = fs::read_to_string(&offset_path)?;
426            content
427                .trim()
428                .parse::<i64>()
429                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
430                .max(0)
431        } else {
432            0
433        };
434        // `take()` moves the records out (nothing below reads
435        // `transcript_records` again) — avoids deep-cloning a potentially
436        // large payload (full bash stdout / file contents) on the hook path.
437        resolve_transcript_source(
438            hook_event.transcript_records.take(),
439            prior_offset,
440            (transcript_lines, start_offset, new_offset),
441        )
442    } else {
443        (transcript_lines, start_offset, new_offset)
444    };
445
446    // 5. Build StreamEventRequest
447    let stream_event_type = match event_type {
448        "notification" => StreamEventType::SessionStart,
449        "stop" => StreamEventType::SessionEnd,
450        _ => StreamEventType::ToolUse,
451    };
452
453    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
454    // events have no tool_use_id, so fall back to a forwarded `toolResult`
455    // record's `isError` — otherwise a failed OpenCode tool would render as
456    // successful (the event-level flag file-based agents populate would be None).
457    let tool_is_error = hook_event
458        .tool_use_id
459        .as_deref()
460        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
461        .or_else(|| inline_tool_is_error(&transcript_lines));
462
463    // Load config once, up front, so it can back both the user-level context
464    // layer resolution below and the org_slug/repo_id lookup further down —
465    // avoids a redundant second read of the same file. `try_load` keeps the
466    // missing/malformed distinction so the required-config error further down
467    // can report which one it is.
468    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
469    // user context" — `resolve_user_context` below falls back to the user-level
470    // config in that case. A malformed repo config is surfaced as an error
471    // later (the required-config check), not silently dropped here.
472    let config = crate::config::TracevaultConfig::try_load(&project_root);
473    // Repo config's user_context wins when the repo configured it; otherwise
474    // fall back to the user-level ~/.config/tracevault/config.toml. This is
475    // what lets a detached session (no checkout) still carry user context.
476    let repo_uc = config
477        .as_ref()
478        .ok()
479        .and_then(|opt| opt.as_ref())
480        .and_then(|c| c.user_context.clone());
481    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
482
483    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
484    // global and per-worktree) and extract fields before building the
485    // request.  Using `effective` means parallel sessions in different linked
486    // worktrees each stamp their own per-worktree context without
487    // interfering with each other.
488    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
489    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
490
491    let mut req = StreamEventRequest {
492        protocol_version: 1,
493        tool: Some("claude-code".to_string()),
494        event_type: stream_event_type,
495        session_id: hook_event.session_id.clone(),
496        timestamp: chrono::Utc::now(),
497        hook_event_name: Some(hook_event.hook_event_name.clone()),
498        tool_name: hook_event.tool_name.clone(),
499        tool_use_id: hook_event.tool_use_id.clone(),
500        tool_input: hook_event.tool_input.clone(),
501        tool_response: hook_event.tool_response.clone(),
502        tool_is_error,
503        event_index: None,
504        event_uuid: Some(event_uuid),
505        transcript_lines: if transcript_lines.is_empty() {
506            None
507        } else {
508            Some(transcript_lines)
509        },
510        transcript_offset: Some(start_offset),
511        model: None,
512        cwd: Some(hook_event.cwd.clone()),
513        final_stats: None,
514        flow_id: ctx_flow_id,
515        labels: ctx_labels,
516        params: ctx_params,
517    };
518
519    stamp_agent(&mut req, agent);
520
521    req.truncate_large_fields();
522
523    // 6. Resolve credentials
524    let (server_url, token) = crate::api_client::resolve_credentials(&project_root);
525
526    // 7. Config (loaded above, alongside the user-level context layer
527    // resolution) no longer directly gates org_slug/repo_id — a missing
528    // config is not fatal on its own, since the repo may instead resolve via
529    // the workspace-mode precedence chain (session binding / subagent
530    // worktree override) below. A malformed config is still surfaced here —
531    // that's easy to miss in hook output otherwise. Only a bound
532    // `config.toml`'s org_slug/repo_id feed the lowest-precedence tier
533    // (via `binding_from_config` below).
534    if let Err(e) = &config {
535        return Err(format!("malformed .tracevault/config.toml: {e}").into());
536    }
537
538    // Resolve the effective repo binding (workspace/detached mode). Bound
539    // mode (a pinned config.toml) still works — it's the lowest-precedence
540    // tier, wired below via `binding_from_config`, fed from the `config`
541    // already loaded above (no second read of config.toml on this hot path).
542    let session = crate::session_state::load(&hook_event.session_id);
543    let bound = config
544        .as_ref()
545        .ok()
546        .and_then(|opt| opt.as_ref())
547        .and_then(crate::resolution::binding_from_config);
548    let user_default = crate::user_default::load();
549    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
550    // Graceful no-op, exactly like the hook's normal success path. Do NOT
551    // error: a failing hook would block the tool.
552    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
553        let response = HookResponse::allow();
554        println!("{}", serde_json::to_string(&response)?);
555        Ok(())
556    };
557    let Some(binding) = binding else {
558        // No repo resolves.
559        no_op_allow()?;
560        return Ok(());
561    };
562    if !binding_repo_id_is_valid(&binding.repo_id) {
563        // A corrupted/hand-edited session-state file could contain a
564        // repo_id with path separators, which would otherwise land in the
565        // `pending-<repo_id>.jsonl` filename below.
566        no_op_allow()?;
567        return Ok(());
568    }
569    let org_slug = binding.org_slug.as_str();
570    let repo_id = binding.repo_id.as_str();
571
572    // Explicit local project binding (if any) overrides server-side repo
573    // deduction. Computed once, reusing the already-loaded session + worktree
574    // used just above for the repo-binding resolution.
575    let capture_pid = capture_project(&session, Some(worktree_top.as_str()));
576
577    // 8. Create ApiClient
578    let server_url = server_url.ok_or("server_url not configured")?;
579    let client = crate::api_client::ApiClient::new(&server_url, token.as_deref());
580
581    // 9. Try drain pending queue and send
582    let pending_path = pending_path_for(&session_dir, repo_id);
583    let pending_events = drain_pending(&pending_path)?;
584
585    let mut send_failed = false;
586    // Spans the whole invocation (pending-flush loop + live send below) so a
587    // stale binding whose repo-scoped fallback keeps succeeding warns at most
588    // once, not once per buffered event.
589    let mut fallback_warned = false;
590
591    // Send pending events first
592    for pending_json in &pending_events {
593        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
594            if send_stream_event(
595                &client,
596                org_slug,
597                repo_id,
598                capture_pid,
599                &pending_req,
600                &mut fallback_warned,
601            )
602            .await
603            .is_err()
604            {
605                // Re-queue all remaining pending events
606                for evt in &pending_events {
607                    append_pending(&pending_path, evt)?;
608                }
609                send_failed = true;
610                break;
611            }
612        }
613    }
614
615    // Send current event
616    let req_json = serde_json::to_string(&req)?;
617    // The inline (OpenCode) path CONSUMES its records from the hook event — they
618    // are not re-readable like a transcript file — so its `.stream_offset` record
619    // counter must advance whenever the event is accepted for delivery, INCLUDING
620    // when it is queued after a failure. Otherwise the next inline event reuses
621    // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
622    // queued request already carries this event's `transcript_offset`, so the
623    // records keep their indices on drain. (File-based agents must NOT advance on
624    // failure: their next read re-covers these lines cumulatively/idempotently.)
625    if send_failed {
626        append_pending(&pending_path, &req_json)?;
627        if is_inline {
628            fs::write(&offset_path, new_offset.to_string())?;
629        }
630    } else {
631        match send_stream_event(
632            &client,
633            org_slug,
634            repo_id,
635            capture_pid,
636            &req,
637            &mut fallback_warned,
638        )
639        .await
640        {
641            Ok(_) => {
642                // 10. On success update .stream_offset
643                fs::write(&offset_path, new_offset.to_string())?;
644            }
645            Err(_) => {
646                // 11. On failure append to pending.jsonl (advance the inline
647                // record counter regardless — see the note above).
648                append_pending(&pending_path, &req_json)?;
649                if is_inline {
650                    fs::write(&offset_path, new_offset.to_string())?;
651                }
652            }
653        }
654    }
655
656    // 12. Always print HookResponse::allow() to stdout
657    let response = HookResponse::allow();
658    println!("{}", serde_json::to_string(&response)?);
659
660    Ok(())
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666    use crate::config::UserContext;
667    use crate::context::{Context, EffectiveContext};
668    use std::collections::BTreeMap;
669
670    // ── user layer resolution: disabled config → no user layer ────────────────
671
672    #[test]
673    fn disabled_user_context_resolves_to_none() {
674        // Default/disabled `user_context` (the `Toggle(false)` variant) must
675        // resolve to `None`, matching the pre-existing hook behavior of
676        // stamping without a user layer when it isn't configured.
677        assert!(UserContext::Toggle(false).resolve().is_none());
678    }
679
680    #[test]
681    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
682        // With no user layer and no global/worktree context files present,
683        // `Context::effective` must yield a default (empty) `EffectiveContext`
684        // — i.e. passing `None` for `user_layer` is behavior-preserving.
685        let dir = tempfile::tempdir().unwrap();
686        let effective = Context::effective(dir.path(), None);
687        assert_eq!(effective, EffectiveContext::default());
688    }
689
690    // ── apply_context: all three fields populated ─────────────────────────────
691
692    #[test]
693    fn apply_context_stamps_all_fields() {
694        let dir = tempfile::tempdir().unwrap();
695        let mut params = BTreeMap::new();
696        params.insert("env".to_string(), "prod".to_string());
697        params.insert("region".to_string(), "eu-west-1".to_string());
698
699        let ctx = EffectiveContext {
700            flow_id: Some("flow-xyz".to_string()),
701            labels: vec!["backend".to_string(), "urgent".to_string()],
702            params,
703        };
704
705        let (flow_id, labels, params_out) = apply_context(ctx);
706
707        assert_eq!(flow_id, Some("flow-xyz".to_string()));
708        assert_eq!(
709            labels,
710            Some(vec!["backend".to_string(), "urgent".to_string()])
711        );
712        let p = params_out.expect("params should be Some");
713        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
714        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
715
716        // Verify the stored context round-trips through save_to → load_from →
717        // merge_layers → apply_context (stored params are now `Option<String>`).
718        let written = Context {
719            flow_id: Some("flow-xyz".to_string()),
720            labels: vec!["backend".to_string(), "urgent".to_string()],
721            params: {
722                let mut m = BTreeMap::new();
723                m.insert("env".to_string(), Some("prod".to_string()));
724                m.insert("region".to_string(), Some("eu-west-1".to_string()));
725                m
726            },
727        };
728        let ctx_path = dir.path().join(".tracevault").join("context.json");
729        written.save_to(&ctx_path).unwrap();
730        let loaded = Context::load_from(&ctx_path);
731        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
732        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
733        assert!(labels2.is_some());
734        assert!(params2.is_some());
735    }
736
737    // ── apply_context: missing context file → all None ────────────────────────
738
739    #[test]
740    fn apply_context_missing_file_all_none() {
741        let dir = tempfile::tempdir().unwrap();
742        let missing_path = dir.path().join(".tracevault").join("context.json");
743        let ctx = Context::load_from(&missing_path); // no context.json → default
744        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
745        assert!(flow_id.is_none(), "flow_id should be None");
746        assert!(labels.is_none(), "labels should be None");
747        assert!(params.is_none(), "params should be None");
748    }
749
750    // ── apply_context: empty labels vec / empty params map → None ─────────────
751
752    #[test]
753    fn apply_context_empty_collections_are_none() {
754        let ctx = EffectiveContext {
755            flow_id: None,
756            labels: vec![],
757            params: BTreeMap::new(),
758        };
759        let (flow_id, labels, params) = apply_context(ctx);
760        assert!(flow_id.is_none());
761        assert!(
762            labels.is_none(),
763            "empty labels should be None, not Some([])"
764        );
765        assert!(
766            params.is_none(),
767            "empty params should be None, not Some({{}})"
768        );
769    }
770
771    // ── apply_context: flow_id only, collections empty ────────────────────────
772
773    #[test]
774    fn apply_context_flow_id_only() {
775        let ctx = EffectiveContext {
776            flow_id: Some("my-flow".to_string()),
777            labels: vec![],
778            params: BTreeMap::new(),
779        };
780        let (flow_id, labels, params) = apply_context(ctx);
781        assert_eq!(flow_id, Some("my-flow".to_string()));
782        assert!(labels.is_none());
783        assert!(params.is_none());
784    }
785
786    // ── resolve_session_paths tests ───────────────────────────────────────────
787    //
788    // These tests verify that `resolve_session_paths` routes through the
789    // git-aware resolver so that sibling linked worktrees capture events under
790    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
791
792    use crate::test_helpers::{add_worktree, init_git_repo};
793
794    /// Primary checkout: project_root resolves to the repo root; session_dir is
795    /// under `<repo>/.tracevault/sessions/<id>/`.
796    #[test]
797    fn resolve_session_paths_primary_checkout() {
798        let tmp = tempfile::tempdir().unwrap();
799        let repo = tmp.path().join("repo");
800        std::fs::create_dir_all(&repo).unwrap();
801        init_git_repo(&repo);
802        // Create a .tracevault/ in the primary root to match a real init.
803        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
804
805        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
806        let project_root = resolved.root;
807
808        assert_eq!(
809            project_root.canonicalize().unwrap(),
810            repo.canonicalize().unwrap(),
811            "primary checkout: project_root must be repo root"
812        );
813        assert_eq!(
814            session_dir.canonicalize().unwrap_or(session_dir.clone()),
815            repo.join(".tracevault")
816                .join("sessions")
817                .join("sess-primary-123"),
818            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
819        );
820        // session_dir must be INSIDE the primary repo, not elsewhere.
821        assert!(
822            session_dir.starts_with(&repo),
823            "session_dir must be under the primary repo root"
824        );
825    }
826
827    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
828    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
829    /// git-aware resolver must return the PRIMARY root.
830    #[test]
831    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
832        let tmp = tempfile::tempdir().unwrap();
833        let repo = tmp.path().join("repo");
834        // Sibling worktree lives outside the primary repo directory.
835        let wt = tmp.path().join("sibling-wt");
836
837        std::fs::create_dir_all(&repo).unwrap();
838        init_git_repo(&repo);
839        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
840        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
841        add_worktree(&repo, &wt);
842
843        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
844        let project_root = resolved.root;
845
846        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
847        assert_eq!(
848            project_root.canonicalize().unwrap(),
849            repo.canonicalize().unwrap(),
850            "sibling worktree: project_root must be primary repo root (not worktree dir)"
851        );
852        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
853        assert!(
854            session_dir.starts_with(&repo),
855            "sibling worktree: session_dir must be under the PRIMARY repo root"
856        );
857        assert!(
858            !session_dir.starts_with(&wt),
859            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
860        );
861        assert!(
862            session_dir.ends_with(
863                std::path::Path::new(".tracevault")
864                    .join("sessions")
865                    .join("sess-sibling-456")
866            ),
867            "session_dir must end with .tracevault/sessions/<session_id>"
868        );
869    }
870
871    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
872    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
873    #[test]
874    fn resolve_session_paths_non_git_fallback() {
875        let tmp = tempfile::tempdir().unwrap();
876        // No git repo, no .tracevault/ anywhere.
877        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
878        let project_root = resolved.root;
879
880        assert_eq!(
881            project_root,
882            tmp.path(),
883            "non-git: project_root must fall back to hook_cwd"
884        );
885        assert_eq!(
886            session_dir,
887            tmp.path()
888                .join(".tracevault")
889                .join("sessions")
890                .join("sess-fallback-789"),
891            "non-git: session_dir must be relative to the fallback root"
892        );
893    }
894
895    /// The origin marker written by run_stream contains the worktree toplevel.
896    /// This test exercises the same `paths::worktree_toplevel` helper the hook
897    /// uses (can't call run_stream end-to-end without a real server) so the
898    /// marker content is computed and canonicalized exactly as in production.
899    #[test]
900    fn origin_marker_written_in_session_dir() {
901        let tmp = tempfile::tempdir().unwrap();
902        let repo = tmp.path().join("repo");
903        std::fs::create_dir_all(&repo).unwrap();
904        init_git_repo(&repo);
905
906        let session_dir = repo
907            .join(".tracevault")
908            .join("sessions")
909            .join("test-sess-001");
910        std::fs::create_dir_all(&session_dir).unwrap();
911
912        let hook_cwd = &repo;
913        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
914        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
915
916        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
917        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
918        assert_eq!(
919            origin_content.trim(),
920            expected.as_str(),
921            "origin marker must contain the canonicalized worktree toplevel"
922        );
923    }
924
925    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
926
927    use crate::session_state::{RepoBinding, SessionState};
928
929    fn binding(id: &str) -> RepoBinding {
930        RepoBinding {
931            org_slug: "org".into(),
932            repo_id: id.into(),
933            git_url: None,
934            remote_id: None,
935            codebase_name: None,
936            updated_at: "t".into(),
937        }
938    }
939
940    /// Workspace mode: no pinned config, but the session is bound (e.g. via
941    /// `tracevault repo switch`) — the stream event attributes to that repo.
942    #[test]
943    fn resolve_stream_binding_uses_session_active_when_unbound() {
944        let session = SessionState {
945            active: Some(binding("session-repo")),
946            subagents: HashMap::new(),
947            ..Default::default()
948        };
949        let got = resolve_stream_binding(&session, "/wt/top", None, None);
950        assert_eq!(got.unwrap().repo_id, "session-repo");
951    }
952
953    /// Bound-mode regression: an empty session (no `repo switch` ever run)
954    /// with a bound config.toml still resolves via the config.
955    #[test]
956    fn resolve_stream_binding_falls_back_to_bound_config() {
957        let session = SessionState::default();
958        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
959        assert_eq!(got.unwrap().repo_id, "bound-repo");
960    }
961
962    /// No session binding and no bound config: nothing resolves, which is
963    /// exactly what should trigger `run_stream`'s graceful no-op.
964    #[test]
965    fn resolve_stream_binding_none_when_nothing_resolves() {
966        let session = SessionState::default();
967        let got = resolve_stream_binding(&session, "/wt/top", None, None);
968        assert!(got.is_none());
969    }
970
971    /// Subagent override precedence: a per-worktree override for the current
972    /// worktree wins over the session's `active` binding.
973    #[test]
974    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
975        let session = SessionState {
976            active: Some(binding("session-repo")),
977            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
978            ..Default::default()
979        };
980        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
981        assert_eq!(got.unwrap().repo_id, "subagent-repo");
982    }
983
984    /// Workspace mode: no bound config, but a user-level default is set (e.g.
985    /// via `tracevault repo switch --user`) — the stream event attributes to
986    /// that repo when nothing more specific resolves.
987    #[test]
988    fn resolve_stream_binding_falls_back_to_user_default() {
989        let session = SessionState::default();
990        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
991        assert_eq!(got.unwrap().repo_id, "userdef");
992    }
993
994    /// The user-level default is the LOWEST-precedence tier: a bound config
995    /// still wins over it.
996    #[test]
997    fn resolve_stream_binding_prefers_bound_over_user_default() {
998        let session = SessionState::default();
999        let got = resolve_stream_binding(
1000            &session,
1001            "/wt/x",
1002            Some(binding("bound")),
1003            Some(binding("userdef")),
1004        );
1005        assert_eq!(got.unwrap().repo_id, "bound");
1006    }
1007
1008    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1009
1010    #[test]
1011    fn binding_repo_id_is_valid_accepts_real_uuid() {
1012        assert!(binding_repo_id_is_valid(
1013            "550e8400-e29b-41d4-a716-446655440000"
1014        ));
1015    }
1016
1017    #[test]
1018    fn binding_repo_id_is_valid_rejects_path_traversal() {
1019        assert!(!binding_repo_id_is_valid("../evil"));
1020    }
1021
1022    #[test]
1023    fn binding_repo_id_is_valid_rejects_empty() {
1024        assert!(!binding_repo_id_is_valid(""));
1025    }
1026
1027    #[test]
1028    fn binding_repo_id_is_valid_rejects_non_uuid() {
1029        assert!(!binding_repo_id_is_valid("not-a-uuid"));
1030    }
1031
1032    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1033
1034    #[test]
1035    fn stamp_agent_sets_tool_and_version() {
1036        use crate::agent::Agent;
1037        let mut req = StreamEventRequest {
1038            protocol_version: 1,
1039            tool: Some("claude-code".to_string()),
1040            event_type: StreamEventType::ToolUse,
1041            session_id: "s".into(),
1042            timestamp: chrono::Utc::now(),
1043            hook_event_name: None,
1044            tool_name: None,
1045            tool_use_id: None,
1046            tool_input: None,
1047            tool_response: None,
1048            tool_is_error: None,
1049            event_index: None,
1050            event_uuid: None,
1051            transcript_lines: None,
1052            transcript_offset: None,
1053            model: None,
1054            cwd: None,
1055            final_stats: None,
1056            flow_id: None,
1057            labels: None,
1058            params: None,
1059        };
1060        stamp_agent(&mut req, Agent::Codex);
1061        assert_eq!(req.tool.as_deref(), Some("codex"));
1062        assert_eq!(req.protocol_version, 2);
1063
1064        stamp_agent(&mut req, Agent::ClaudeCode);
1065        assert_eq!(req.tool.as_deref(), Some("claude-code"));
1066        assert_eq!(req.protocol_version, 1);
1067    }
1068
1069    // ── pending_path_for: repo-scoped offline queue ──────────────────────────
1070
1071    #[test]
1072    fn pending_path_is_repo_scoped() {
1073        let dir = std::path::Path::new("/tmp/sess");
1074        assert_eq!(
1075            pending_path_for(dir, "repo-a"),
1076            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1077        );
1078        assert_ne!(
1079            pending_path_for(dir, "repo-a"),
1080            pending_path_for(dir, "repo-b"),
1081        );
1082    }
1083
1084    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1085
1086    #[test]
1087    fn read_new_transcript_lines_empty_path_is_noop() {
1088        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1089        // An empty path must yield no lines and offset 0, never an error from
1090        // handing `Path::new("")` to exists()/File::open.
1091        let dir = tempfile::tempdir().unwrap();
1092        let offset_path = dir.path().join(".stream_offset");
1093        let (lines, start_offset, end_offset) =
1094            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1095        assert!(
1096            lines.is_empty(),
1097            "empty path must yield no transcript lines"
1098        );
1099        assert_eq!(start_offset, 0);
1100        assert_eq!(end_offset, 0);
1101    }
1102
1103    // ── read_new_transcript_lines: start_offset is stable across a persisted
1104    //    end_offset, and equals the previous read's end_offset ─────────────────
1105
1106    #[test]
1107    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1108        let dir = tempfile::tempdir().unwrap();
1109        let transcript_path = dir.path().join("transcript.jsonl");
1110        let offset_path = dir.path().join(".stream_offset");
1111
1112        fs::write(
1113            &transcript_path,
1114            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1115        )
1116        .unwrap();
1117
1118        let (lines, start_offset, end_offset) =
1119            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1120        assert_eq!(lines.len(), 2);
1121        assert_eq!(start_offset, 0, "first read starts at byte 0");
1122        assert!(end_offset > 0);
1123
1124        fs::write(&offset_path, end_offset.to_string()).unwrap();
1125
1126        let mut f = OpenOptions::new()
1127            .append(true)
1128            .open(&transcript_path)
1129            .unwrap();
1130        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1131        drop(f);
1132
1133        let (lines2, start_offset2, end_offset2) =
1134            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1135        assert_eq!(lines2.len(), 1);
1136        assert_eq!(
1137            start_offset2, end_offset,
1138            "second read's start_offset must equal the first read's persisted end_offset"
1139        );
1140        assert!(end_offset2 > start_offset2);
1141    }
1142
1143    // ── capture_project: local-only project resolver ──────────────────────────
1144
1145    #[test]
1146    fn capture_project_precedence_local_only() {
1147        use crate::session_state::{ProjectBinding, SessionState};
1148        let pb = |id: &str| ProjectBinding {
1149            org_slug: "o".into(),
1150            project_id: id.into(),
1151            project_name: "n".into(),
1152            updated_at: "".into(),
1153        };
1154        let u = uuid::Uuid::from_u128;
1155        // session active only
1156        let s = SessionState {
1157            active_project: Some(pb(&u(2).to_string())),
1158            ..Default::default()
1159        };
1160        assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
1161        // subagent worktree beats session
1162        let mut s = s;
1163        s.subagent_projects
1164            .insert("/wt".into(), pb(&u(1).to_string()));
1165        assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
1166        // no worktree match -> session active
1167        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
1168        // empty session -> None (user-default file is not present in this unit test env)
1169        assert_eq!(capture_project(&SessionState::default(), None), None);
1170        // malformed stored id -> None (defensive)
1171        let bad = SessionState {
1172            active_project: Some(pb("not-a-uuid")),
1173            ..Default::default()
1174        };
1175        assert_eq!(capture_project(&bad, None), None);
1176    }
1177
1178    // ── send_stream_event: endpoint routing based on capture_pid ──────────────
1179
1180    use std::io::BufReader;
1181    use std::net::TcpListener;
1182    use std::sync::mpsc;
1183    use std::thread;
1184    use std::time::{Duration, Instant};
1185
1186    /// How long an accept loop waits for a connection that never arrives
1187    /// (e.g. a regression that stops the client from making an expected
1188    /// request) before giving up, so the server thread exits cleanly
1189    /// instead of blocking in `accept()` forever.
1190    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
1191
1192    /// Poll a non-blocking `listener` for a connection until one arrives or
1193    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
1194    /// `WouldBlock` accept error) so callers can stop cleanly rather than
1195    /// block forever.
1196    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
1197        let deadline = Instant::now() + ACCEPT_DEADLINE;
1198        loop {
1199            match listener.accept() {
1200                Ok((stream, _)) => {
1201                    // The accepted stream's blocking mode isn't guaranteed to
1202                    // be inherited from the (non-blocking) listener across
1203                    // platforms — make it explicitly blocking so the
1204                    // subsequent read/write calls behave as before.
1205                    let _ = stream.set_nonblocking(false);
1206                    return Some(stream);
1207                }
1208                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1209                    if Instant::now() >= deadline {
1210                        return None;
1211                    }
1212                    thread::sleep(Duration::from_millis(20));
1213                }
1214                Err(_) => return None,
1215            }
1216        }
1217    }
1218
1219    /// How long a test waits for the captured request before failing (rather
1220    /// than hanging forever if the client never connects). Mirrors the
1221    /// harness in `tests/stream_event_project_test.rs`.
1222    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
1223
1224    /// Spawn a one-shot server that returns `response` (a full HTTP response)
1225    /// to the first request. Captures the HTTP request line (method + path +
1226    /// query) over the returned channel before writing the response. Mirrors
1227    /// the harness in `tests/stream_event_project_test.rs` /
1228    /// `tests/resolve_remote_test.rs`.
1229    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
1230        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1231        listener.set_nonblocking(true).unwrap();
1232        let addr = listener.local_addr().unwrap();
1233        let (tx, rx) = mpsc::channel();
1234        thread::spawn(move || {
1235            if let Some(stream) = accept_with_deadline(&listener) {
1236                let mut reader = BufReader::new(stream);
1237                let mut request_line = String::new();
1238                let _ = reader.read_line(&mut request_line);
1239                let _ = tx.send(request_line);
1240                let mut stream = reader.into_inner();
1241                let _ = stream.write_all(response.as_bytes());
1242                let _ = stream.flush();
1243            }
1244        });
1245        (format!("http://{addr}"), rx)
1246    }
1247
1248    fn ok_stream_response() -> String {
1249        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
1250            session_db_id: uuid::Uuid::nil(),
1251            event_db_id: Some(uuid::Uuid::nil()),
1252            status: "accepted".to_string(),
1253        })
1254        .unwrap();
1255        format!(
1256            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1257            body.len(),
1258            body
1259        )
1260    }
1261
1262    fn sample_stream_event_request() -> StreamEventRequest {
1263        StreamEventRequest {
1264            protocol_version: 2,
1265            tool: Some("claude-code".to_string()),
1266            event_type: StreamEventType::ToolUse,
1267            session_id: "sess-1".into(),
1268            timestamp: chrono::Utc::now(),
1269            hook_event_name: Some("PostToolUse".into()),
1270            tool_name: None,
1271            tool_use_id: None,
1272            tool_input: None,
1273            tool_response: None,
1274            tool_is_error: None,
1275            event_index: None,
1276            event_uuid: None,
1277            transcript_lines: None,
1278            transcript_offset: None,
1279            model: None,
1280            cwd: None,
1281            final_stats: None,
1282            flow_id: None,
1283            labels: None,
1284            params: None,
1285        }
1286    }
1287
1288    /// With a `SessionState` whose `active_project` is set, `capture_project`
1289    /// resolves a `capture_pid`, and `send_stream_event` must route to the
1290    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
1291    /// than the repo-scoped one.
1292    #[tokio::test]
1293    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
1294        use crate::session_state::{ProjectBinding, SessionState};
1295
1296        // Isolate from any ambient user-level project default so this test's
1297        // `capture_project` call depends only on the SessionState below —
1298        // mirrors the isolation pattern in `commands::project`'s tests.
1299        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1300        let tmp = tempfile::tempdir().unwrap();
1301        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1302        _guard.set("XDG_CONFIG_HOME", tmp.path());
1303
1304        let pid = uuid::Uuid::from_u128(99);
1305        let session = SessionState {
1306            active_project: Some(ProjectBinding {
1307                org_slug: "org".into(),
1308                project_id: pid.to_string(),
1309                project_name: "proj".into(),
1310                updated_at: "".into(),
1311            }),
1312            ..Default::default()
1313        };
1314        let capture_pid = capture_project(&session, None);
1315        assert_eq!(capture_pid, Some(pid));
1316
1317        let resp = ok_stream_response();
1318        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1319        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1320        let req = sample_stream_event_request();
1321
1322        let mut fallback_warned = false;
1323        let got = send_stream_event(
1324            &client,
1325            "org",
1326            "11111111-1111-1111-1111-111111111111",
1327            capture_pid,
1328            &req,
1329            &mut fallback_warned,
1330        )
1331        .await
1332        .expect("send_stream_event must succeed");
1333        assert_eq!(got.status, "accepted");
1334
1335        let line = rx
1336            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1337            .expect("no request captured");
1338        assert!(
1339            line.starts_with(&format!(
1340                "POST /api/v1/orgs/org/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
1341            )),
1342            "an active project binding must route to the project-scoped endpoint, got: {line}"
1343        );
1344    }
1345
1346    /// With an empty binding (default `SessionState`, no worktree override)
1347    /// and no user-level default present in the test env, `capture_project`
1348    /// resolves `None` and `send_stream_event` must fall back to the
1349    /// repo-scoped endpoint.
1350    #[tokio::test]
1351    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
1352        use crate::session_state::SessionState;
1353
1354        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1355        let tmp = tempfile::tempdir().unwrap();
1356        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1357        // No user_project.toml under this isolated config dir, so there is no
1358        // ambient user-level default to leak in.
1359        _guard.set("XDG_CONFIG_HOME", tmp.path());
1360
1361        let capture_pid = capture_project(&SessionState::default(), None);
1362        assert_eq!(capture_pid, None);
1363
1364        let resp = ok_stream_response();
1365        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1366        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1367        let req = sample_stream_event_request();
1368
1369        let mut fallback_warned = false;
1370        let got = send_stream_event(
1371            &client,
1372            "org",
1373            "11111111-1111-1111-1111-111111111111",
1374            capture_pid,
1375            &req,
1376            &mut fallback_warned,
1377        )
1378        .await
1379        .expect("send_stream_event must succeed");
1380        assert_eq!(got.status, "accepted");
1381
1382        let line = rx
1383            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1384            .expect("no request captured");
1385        assert!(
1386            line.starts_with(
1387                "POST /api/v1/orgs/org/repos/11111111-1111-1111-1111-111111111111/stream "
1388            ),
1389            "no binding must fall back to the repo-scoped endpoint, got: {line}"
1390        );
1391    }
1392
1393    // ── I1/I2: deterministic-client-error fallback + transient no-fallback ───
1394
1395    /// Spawn a server that replies to up to `responses.len()` sequential
1396    /// connections with the given full HTTP responses, in order, capturing
1397    /// each request line over the channel. The listening socket itself is
1398    /// dropped (closing it) once all responses have been served, so any
1399    /// further connection attempt fails fast (connection refused) rather than
1400    /// hanging for the client's request timeout — this lets a test assert
1401    /// "no further request was sent" cheaply.
1402    fn spawn_n_capturing_requests(
1403        responses: Vec<&'static str>,
1404    ) -> (String, mpsc::Receiver<String>) {
1405        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1406        listener.set_nonblocking(true).unwrap();
1407        let addr = listener.local_addr().unwrap();
1408        let (tx, rx) = mpsc::channel();
1409        thread::spawn(move || {
1410            for response in responses {
1411                // If a regression stops the client from making this request
1412                // (e.g. the expected Nth call never happens), don't block
1413                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
1414                // and let the thread end so the test process can't hang.
1415                let Some(stream) = accept_with_deadline(&listener) else {
1416                    break;
1417                };
1418                let mut reader = BufReader::new(stream);
1419                let mut request_line = String::new();
1420                let _ = reader.read_line(&mut request_line);
1421                let _ = tx.send(request_line);
1422                let mut stream = reader.into_inner();
1423                let _ = stream.write_all(response.as_bytes());
1424                let _ = stream.flush();
1425            }
1426            // `listener` (and `tx`) drop here, closing the socket and the
1427            // channel — a stray extra request gets ECONNREFUSED immediately
1428            // instead of hanging, and a stray extra `rx.recv` returns
1429            // Disconnected immediately instead of blocking.
1430        });
1431        (format!("http://{addr}"), rx)
1432    }
1433
1434    /// I1: a deterministic 400 ("is not a member of project ...") from the
1435    /// project-scoped endpoint must fall back to the repo-scoped endpoint —
1436    /// which then succeeds — rather than being buffered/retried forever. Both
1437    /// endpoints must be hit, project first, then repo.
1438    #[tokio::test]
1439    async fn send_stream_event_falls_back_to_repo_scoped_on_deterministic_400() {
1440        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
1441        let resp_400 = format!(
1442            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1443            body_400.len(),
1444            body_400
1445        );
1446        let resp_200 = ok_stream_response();
1447
1448        let (base, rx) = spawn_n_capturing_requests(vec![
1449            Box::leak(resp_400.into_boxed_str()),
1450            Box::leak(resp_200.into_boxed_str()),
1451        ]);
1452        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1453        let req = sample_stream_event_request();
1454        let pid = uuid::Uuid::from_u128(42);
1455
1456        let mut fallback_warned = false;
1457        let got = send_stream_event(
1458            &client,
1459            "org",
1460            "11111111-1111-1111-1111-111111111111",
1461            Some(pid),
1462            &req,
1463            &mut fallback_warned,
1464        )
1465        .await
1466        .expect("a deterministic 400 must fall back to repo-scoped and succeed");
1467        assert_eq!(got.status, "accepted");
1468
1469        let first = rx
1470            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1471            .expect("no first request captured");
1472        assert!(
1473            first.contains(&format!("/projects/{pid}/stream")),
1474            "first request must hit the project-scoped endpoint, got: {first}"
1475        );
1476
1477        let second = rx
1478            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1479            .expect("no second (fallback) request captured");
1480        assert!(
1481            second.starts_with(
1482                "POST /api/v1/orgs/org/repos/11111111-1111-1111-1111-111111111111/stream "
1483            ),
1484            "second request must fall back to the repo-scoped endpoint, got: {second}"
1485        );
1486    }
1487
1488    /// I2: a transient 503 from the project-scoped endpoint must propagate as
1489    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
1490    /// existing buffer/retry logic in `run_stream` still handles it. Only one
1491    /// request (to the project endpoint) may be observed.
1492    #[tokio::test]
1493    async fn send_stream_event_does_not_fall_back_on_transient_503() {
1494        let body_503 = "internal error";
1495        let resp_503 = format!(
1496            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1497            body_503.len(),
1498            body_503
1499        );
1500        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
1501        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1502        let req = sample_stream_event_request();
1503        let pid = uuid::Uuid::from_u128(7);
1504
1505        let mut fallback_warned = false;
1506        let err = send_stream_event(
1507            &client,
1508            "org",
1509            "11111111-1111-1111-1111-111111111111",
1510            Some(pid),
1511            &req,
1512            &mut fallback_warned,
1513        )
1514        .await
1515        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
1516        assert!(
1517            err.to_string().contains("503"),
1518            "propagated error must reflect the transient status, got: {err}"
1519        );
1520        assert!(
1521            !is_deterministic_client_error(err.as_ref()),
1522            "a 503 must not be classified as a deterministic client error"
1523        );
1524
1525        let first = rx
1526            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1527            .expect("no request captured");
1528        assert!(
1529            first.contains(&format!("/projects/{pid}/stream")),
1530            "must hit the project-scoped endpoint, got: {first}"
1531        );
1532
1533        // The mock server only serves ONE response and then drops its
1534        // listener/sender — a stray fallback request would either fail the
1535        // `expect_err` above (if it somehow succeeded) or, if it also failed,
1536        // would still mean a second request was attempted. Confirming the
1537        // channel is immediately disconnected (rather than blocking) proves
1538        // no second request was ever sent.
1539        assert!(
1540            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
1541            "no second (fallback) request should have been sent for a transient error"
1542        );
1543    }
1544}