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