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