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
42pub fn read_new_transcript_lines(
43    transcript_path: &Path,
44    offset_path: &Path,
45) -> Result<(Vec<serde_json::Value>, i64), io::Error> {
46    // An empty path means "no transcript yet" — Codex documents `transcript_path`
47    // as nullable (e.g. on SessionStart before a rollout exists), and the hook
48    // payload deserializes null/absent to "". Guard explicitly so we never hand
49    // `Path::new("")` to `exists()`/`File::open` (whose behavior on an empty path
50    // is platform-dependent); treat it as a clean no-op.
51    if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
52        return Ok((vec![], 0));
53    }
54
55    let offset: i64 = if offset_path.exists() {
56        let content = fs::read_to_string(offset_path)?;
57        content
58            .trim()
59            .parse::<i64>()
60            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
61    } else {
62        0
63    };
64
65    let mut file = fs::File::open(transcript_path)?;
66    file.seek(SeekFrom::Start(offset as u64))?;
67
68    let reader = io::BufReader::new(file);
69    let mut lines = Vec::new();
70    let mut bytes_read = offset;
71
72    for line_result in reader.lines() {
73        let line = line_result?;
74        // +1 for the newline character
75        bytes_read += line.len() as i64 + 1;
76        if line.trim().is_empty() {
77            continue;
78        }
79        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
80            lines.push(value);
81        }
82    }
83
84    Ok((lines, bytes_read))
85}
86
87pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
88    let mut file = OpenOptions::new()
89        .create(true)
90        .append(true)
91        .open(pending_path)?;
92    writeln!(file, "{json}")?;
93    Ok(())
94}
95
96pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
97    if !pending_path.exists() {
98        return Ok(vec![]);
99    }
100    let content = fs::read_to_string(pending_path)?;
101    let lines: Vec<String> = content
102        .lines()
103        .filter(|l| !l.trim().is_empty())
104        .map(String::from)
105        .collect();
106    fs::remove_file(pending_path)?;
107    Ok(lines)
108}
109
110/// Offline-queue path for a specific repo binding. Keyed by repo id so a
111/// mid-session rebind (workspace mode) can never flush one repo's queued
112/// events to another.
113fn pending_path_for(session_dir: &Path, repo_id: &str) -> std::path::PathBuf {
114    session_dir.join(format!("pending-{repo_id}.jsonl"))
115}
116
117/// Resolve the project root and session directory for a stream hook invocation.
118///
119/// This is the pure, testable core of `run_stream`'s path resolution. It uses
120/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
121/// --git-common-dir` first, so it correctly resolves to the **primary**
122/// `.tracevault/` directory from any worktree — including sibling linked
123/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
124///
125/// Returns `(resolved, session_dir)` — the resolved
126/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
127/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
128/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
129pub fn resolve_session_paths(
130    hook_cwd: &Path,
131    session_id: &str,
132) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
133    let resolved = crate::paths::resolve_project_root(hook_cwd);
134    let session_dir = resolved
135        .root
136        .join(".tracevault")
137        .join("sessions")
138        .join(session_id);
139    (resolved, session_dir)
140}
141
142/// A resolved binding is usable for hook attribution only if its repo_id is a
143/// real UUID — guards against a corrupted/edited session-state file injecting
144/// path separators into the pending-<repo_id>.jsonl filename.
145fn binding_repo_id_is_valid(repo_id: &str) -> bool {
146    uuid::Uuid::parse_str(repo_id).is_ok()
147}
148
149/// The effective repo binding for a stream event, given the loaded session
150/// state, the event's worktree, and the bound-config fallback. Pure — the
151/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
152pub(crate) fn resolve_stream_binding(
153    session: &crate::session_state::SessionState,
154    worktree: &str,
155    bound: Option<crate::session_state::RepoBinding>,
156    user_default: Option<crate::session_state::RepoBinding>,
157) -> Option<crate::session_state::RepoBinding> {
158    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
159        repo_flag: None,
160        session,
161        worktree_path: Some(worktree),
162        bound,
163        user_default,
164    })
165    .map(|(b, _)| b)
166}
167
168/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
169/// Factored out so the mapping is testable without the network/FS-bound
170/// `run_stream`.
171pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
172    req.tool = Some(agent.tool_name().to_string());
173    req.protocol_version = agent.protocol_version() as u32;
174}
175
176pub async fn run_stream(
177    event_type: &str,
178    agent: crate::agent::Agent,
179) -> Result<(), Box<dyn std::error::Error>> {
180    // 1. Read HookEvent from stdin
181    let mut input = String::new();
182    io::stdin().read_to_string(&mut input)?;
183    let hook_event = parse_hook_event(&input)?;
184
185    // Resolve project_root and session_dir via the shared git-aware resolver.
186    //
187    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
188    // the primary worktree root, so it works correctly from a primary checkout,
189    // a nested worktree, AND a sibling linked worktree (where the primary
190    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
191    // would fall back to hook_cwd itself, fail to load config, and silently
192    // drop the event).
193    //
194    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
195    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
196    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
197    // just below runs BEFORE the config/credentials check and can itself
198    // `?`-exit early — that remains graceful because `main.rs` catches all
199    // `Err` from `run_stream` and exits 0 without blocking the tool.
200    let hook_cwd = Path::new(&hook_event.cwd);
201    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
202    if resolved.source == crate::paths::ProjectRootSource::Fallback {
203        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
204        // we are about to create a fresh `.tracevault/` at the hook's working
205        // directory — which is how stray per-subdirectory `.tracevault/` dirs
206        // appear. Surface it (best-effort; stderr never blocks the hook).
207        eprintln!(
208            "tracevault: warning: could not resolve a git project root from {}; \
209             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
210             that it runs inside the repository to keep sessions under the repo root.",
211            hook_cwd.display()
212        );
213    }
214    let project_root = resolved.root;
215
216    // 2. Create session dir
217    fs::create_dir_all(&session_dir)?;
218
219    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
220    // inside whatever `.tracevault/` we just created — including a per-subproject
221    // one. `tracevault init` writes this for the root dir, but runtime-created
222    // dirs would otherwise have no .gitignore and leak sessions into commits.
223    // Best-effort: never fail the hook on this.
224    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
225
226    // Write origin marker so verify-start can disambiguate sessions by worktree.
227    // Best-effort: never fail the hook on marker errors. Uses the shared
228    // canonicalizing helper so the value matches what verify-start compares
229    // against on the read side.
230    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
231    let _ = fs::write(session_dir.join("origin"), &worktree_top);
232
233    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
234    //    it both orders events and is a stable idempotency key — no shared
235    //    `.event_counter` file (which raced between concurrent parallel-tool
236    //    hooks and could collide/drop events).
237    let event_uuid = uuid::Uuid::now_v7();
238
239    // 4. Read new transcript lines
240    let transcript_path = Path::new(&hook_event.transcript_path);
241    let offset_path = session_dir.join(".stream_offset");
242    let (transcript_lines, new_offset) = read_new_transcript_lines(transcript_path, &offset_path)?;
243
244    // 5. Build StreamEventRequest
245    let stream_event_type = match event_type {
246        "notification" => StreamEventType::SessionStart,
247        "stop" => StreamEventType::SessionEnd,
248        _ => StreamEventType::ToolUse,
249    };
250
251    // Extract is_error from transcript for this tool_use_id
252    let tool_is_error = hook_event
253        .tool_use_id
254        .as_deref()
255        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines));
256
257    // Load config once, up front, so it can back both the user-level context
258    // layer resolution below and the org_slug/repo_id lookup further down —
259    // avoids a redundant second read of the same file. `try_load` keeps the
260    // missing/malformed distinction so the required-config error further down
261    // can report which one it is.
262    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
263    // user context" — `resolve_user_context` below falls back to the user-level
264    // config in that case. A malformed repo config is surfaced as an error
265    // later (the required-config check), not silently dropped here.
266    let config = crate::config::TracevaultConfig::try_load(&project_root);
267    // Repo config's user_context wins when the repo configured it; otherwise
268    // fall back to the user-level ~/.config/tracevault/config.toml. This is
269    // what lets a detached session (no checkout) still carry user context.
270    let repo_uc = config
271        .as_ref()
272        .ok()
273        .and_then(|opt| opt.as_ref())
274        .and_then(|c| c.user_context.clone());
275    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
276
277    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
278    // global and per-worktree) and extract fields before building the
279    // request.  Using `effective` means parallel sessions in different linked
280    // worktrees each stamp their own per-worktree context without
281    // interfering with each other.
282    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
283    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
284
285    let mut req = StreamEventRequest {
286        protocol_version: 1,
287        tool: Some("claude-code".to_string()),
288        event_type: stream_event_type,
289        session_id: hook_event.session_id.clone(),
290        timestamp: chrono::Utc::now(),
291        hook_event_name: Some(hook_event.hook_event_name.clone()),
292        tool_name: hook_event.tool_name.clone(),
293        tool_use_id: hook_event.tool_use_id.clone(),
294        tool_input: hook_event.tool_input.clone(),
295        tool_response: hook_event.tool_response.clone(),
296        tool_is_error,
297        event_index: None,
298        event_uuid: Some(event_uuid),
299        transcript_lines: if transcript_lines.is_empty() {
300            None
301        } else {
302            Some(transcript_lines)
303        },
304        transcript_offset: Some(new_offset),
305        model: None,
306        cwd: Some(hook_event.cwd.clone()),
307        final_stats: None,
308        flow_id: ctx_flow_id,
309        labels: ctx_labels,
310        params: ctx_params,
311    };
312
313    stamp_agent(&mut req, agent);
314
315    req.truncate_large_fields();
316
317    // 6. Resolve credentials
318    let (server_url, token) = crate::api_client::resolve_credentials(&project_root);
319
320    // 7. Config (loaded above, alongside the user-level context layer
321    // resolution) no longer directly gates org_slug/repo_id — a missing
322    // config is not fatal on its own, since the repo may instead resolve via
323    // the workspace-mode precedence chain (session binding / subagent
324    // worktree override) below. A malformed config is still surfaced here —
325    // that's easy to miss in hook output otherwise. Only a bound
326    // `config.toml`'s org_slug/repo_id feed the lowest-precedence tier
327    // (via `binding_from_config` below).
328    if let Err(e) = &config {
329        return Err(format!("malformed .tracevault/config.toml: {e}").into());
330    }
331
332    // Resolve the effective repo binding (workspace/detached mode). Bound
333    // mode (a pinned config.toml) still works — it's the lowest-precedence
334    // tier, wired below via `binding_from_config`, fed from the `config`
335    // already loaded above (no second read of config.toml on this hot path).
336    let session = crate::session_state::load(&hook_event.session_id);
337    let bound = config
338        .as_ref()
339        .ok()
340        .and_then(|opt| opt.as_ref())
341        .and_then(crate::resolution::binding_from_config);
342    let user_default = crate::user_default::load();
343    let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
344    // Graceful no-op, exactly like the hook's normal success path. Do NOT
345    // error: a failing hook would block the tool.
346    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
347        let response = HookResponse::allow();
348        println!("{}", serde_json::to_string(&response)?);
349        Ok(())
350    };
351    let Some(binding) = binding else {
352        // No repo resolves.
353        no_op_allow()?;
354        return Ok(());
355    };
356    if !binding_repo_id_is_valid(&binding.repo_id) {
357        // A corrupted/hand-edited session-state file could contain a
358        // repo_id with path separators, which would otherwise land in the
359        // `pending-<repo_id>.jsonl` filename below.
360        no_op_allow()?;
361        return Ok(());
362    }
363    let org_slug = binding.org_slug.as_str();
364    let repo_id = binding.repo_id.as_str();
365
366    // 8. Create ApiClient
367    let server_url = server_url.ok_or("server_url not configured")?;
368    let client = crate::api_client::ApiClient::new(&server_url, token.as_deref());
369
370    // 9. Try drain pending queue and send
371    let pending_path = pending_path_for(&session_dir, repo_id);
372    let pending_events = drain_pending(&pending_path)?;
373
374    let mut send_failed = false;
375
376    // Send pending events first
377    for pending_json in &pending_events {
378        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
379            if client
380                .stream_event(org_slug, repo_id, &pending_req)
381                .await
382                .is_err()
383            {
384                // Re-queue all remaining pending events
385                for evt in &pending_events {
386                    append_pending(&pending_path, evt)?;
387                }
388                send_failed = true;
389                break;
390            }
391        }
392    }
393
394    // Send current event
395    let req_json = serde_json::to_string(&req)?;
396    if send_failed {
397        append_pending(&pending_path, &req_json)?;
398    } else {
399        match client.stream_event(org_slug, repo_id, &req).await {
400            Ok(_) => {
401                // 10. On success update .stream_offset
402                fs::write(&offset_path, new_offset.to_string())?;
403            }
404            Err(_) => {
405                // 11. On failure append to pending.jsonl
406                append_pending(&pending_path, &req_json)?;
407            }
408        }
409    }
410
411    // 12. Always print HookResponse::allow() to stdout
412    let response = HookResponse::allow();
413    println!("{}", serde_json::to_string(&response)?);
414
415    Ok(())
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::config::UserContext;
422    use crate::context::{Context, EffectiveContext};
423    use std::collections::BTreeMap;
424
425    // ── user layer resolution: disabled config → no user layer ────────────────
426
427    #[test]
428    fn disabled_user_context_resolves_to_none() {
429        // Default/disabled `user_context` (the `Toggle(false)` variant) must
430        // resolve to `None`, matching the pre-existing hook behavior of
431        // stamping without a user layer when it isn't configured.
432        assert!(UserContext::Toggle(false).resolve().is_none());
433    }
434
435    #[test]
436    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
437        // With no user layer and no global/worktree context files present,
438        // `Context::effective` must yield a default (empty) `EffectiveContext`
439        // — i.e. passing `None` for `user_layer` is behavior-preserving.
440        let dir = tempfile::tempdir().unwrap();
441        let effective = Context::effective(dir.path(), None);
442        assert_eq!(effective, EffectiveContext::default());
443    }
444
445    // ── apply_context: all three fields populated ─────────────────────────────
446
447    #[test]
448    fn apply_context_stamps_all_fields() {
449        let dir = tempfile::tempdir().unwrap();
450        let mut params = BTreeMap::new();
451        params.insert("env".to_string(), "prod".to_string());
452        params.insert("region".to_string(), "eu-west-1".to_string());
453
454        let ctx = EffectiveContext {
455            flow_id: Some("flow-xyz".to_string()),
456            labels: vec!["backend".to_string(), "urgent".to_string()],
457            params,
458        };
459
460        let (flow_id, labels, params_out) = apply_context(ctx);
461
462        assert_eq!(flow_id, Some("flow-xyz".to_string()));
463        assert_eq!(
464            labels,
465            Some(vec!["backend".to_string(), "urgent".to_string()])
466        );
467        let p = params_out.expect("params should be Some");
468        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
469        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
470
471        // Verify the stored context round-trips through save_to → load_from →
472        // merge_layers → apply_context (stored params are now `Option<String>`).
473        let written = Context {
474            flow_id: Some("flow-xyz".to_string()),
475            labels: vec!["backend".to_string(), "urgent".to_string()],
476            params: {
477                let mut m = BTreeMap::new();
478                m.insert("env".to_string(), Some("prod".to_string()));
479                m.insert("region".to_string(), Some("eu-west-1".to_string()));
480                m
481            },
482        };
483        let ctx_path = dir.path().join(".tracevault").join("context.json");
484        written.save_to(&ctx_path).unwrap();
485        let loaded = Context::load_from(&ctx_path);
486        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
487        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
488        assert!(labels2.is_some());
489        assert!(params2.is_some());
490    }
491
492    // ── apply_context: missing context file → all None ────────────────────────
493
494    #[test]
495    fn apply_context_missing_file_all_none() {
496        let dir = tempfile::tempdir().unwrap();
497        let missing_path = dir.path().join(".tracevault").join("context.json");
498        let ctx = Context::load_from(&missing_path); // no context.json → default
499        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
500        assert!(flow_id.is_none(), "flow_id should be None");
501        assert!(labels.is_none(), "labels should be None");
502        assert!(params.is_none(), "params should be None");
503    }
504
505    // ── apply_context: empty labels vec / empty params map → None ─────────────
506
507    #[test]
508    fn apply_context_empty_collections_are_none() {
509        let ctx = EffectiveContext {
510            flow_id: None,
511            labels: vec![],
512            params: BTreeMap::new(),
513        };
514        let (flow_id, labels, params) = apply_context(ctx);
515        assert!(flow_id.is_none());
516        assert!(
517            labels.is_none(),
518            "empty labels should be None, not Some([])"
519        );
520        assert!(
521            params.is_none(),
522            "empty params should be None, not Some({{}})"
523        );
524    }
525
526    // ── apply_context: flow_id only, collections empty ────────────────────────
527
528    #[test]
529    fn apply_context_flow_id_only() {
530        let ctx = EffectiveContext {
531            flow_id: Some("my-flow".to_string()),
532            labels: vec![],
533            params: BTreeMap::new(),
534        };
535        let (flow_id, labels, params) = apply_context(ctx);
536        assert_eq!(flow_id, Some("my-flow".to_string()));
537        assert!(labels.is_none());
538        assert!(params.is_none());
539    }
540
541    // ── resolve_session_paths tests ───────────────────────────────────────────
542    //
543    // These tests verify that `resolve_session_paths` routes through the
544    // git-aware resolver so that sibling linked worktrees capture events under
545    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
546
547    use crate::test_helpers::{add_worktree, init_git_repo};
548
549    /// Primary checkout: project_root resolves to the repo root; session_dir is
550    /// under `<repo>/.tracevault/sessions/<id>/`.
551    #[test]
552    fn resolve_session_paths_primary_checkout() {
553        let tmp = tempfile::tempdir().unwrap();
554        let repo = tmp.path().join("repo");
555        std::fs::create_dir_all(&repo).unwrap();
556        init_git_repo(&repo);
557        // Create a .tracevault/ in the primary root to match a real init.
558        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
559
560        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
561        let project_root = resolved.root;
562
563        assert_eq!(
564            project_root.canonicalize().unwrap(),
565            repo.canonicalize().unwrap(),
566            "primary checkout: project_root must be repo root"
567        );
568        assert_eq!(
569            session_dir.canonicalize().unwrap_or(session_dir.clone()),
570            repo.join(".tracevault")
571                .join("sessions")
572                .join("sess-primary-123"),
573            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
574        );
575        // session_dir must be INSIDE the primary repo, not elsewhere.
576        assert!(
577            session_dir.starts_with(&repo),
578            "session_dir must be under the primary repo root"
579        );
580    }
581
582    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
583    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
584    /// git-aware resolver must return the PRIMARY root.
585    #[test]
586    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
587        let tmp = tempfile::tempdir().unwrap();
588        let repo = tmp.path().join("repo");
589        // Sibling worktree lives outside the primary repo directory.
590        let wt = tmp.path().join("sibling-wt");
591
592        std::fs::create_dir_all(&repo).unwrap();
593        init_git_repo(&repo);
594        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
595        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
596        add_worktree(&repo, &wt);
597
598        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
599        let project_root = resolved.root;
600
601        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
602        assert_eq!(
603            project_root.canonicalize().unwrap(),
604            repo.canonicalize().unwrap(),
605            "sibling worktree: project_root must be primary repo root (not worktree dir)"
606        );
607        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
608        assert!(
609            session_dir.starts_with(&repo),
610            "sibling worktree: session_dir must be under the PRIMARY repo root"
611        );
612        assert!(
613            !session_dir.starts_with(&wt),
614            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
615        );
616        assert!(
617            session_dir.ends_with(
618                std::path::Path::new(".tracevault")
619                    .join("sessions")
620                    .join("sess-sibling-456")
621            ),
622            "session_dir must end with .tracevault/sessions/<session_id>"
623        );
624    }
625
626    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
627    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
628    #[test]
629    fn resolve_session_paths_non_git_fallback() {
630        let tmp = tempfile::tempdir().unwrap();
631        // No git repo, no .tracevault/ anywhere.
632        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
633        let project_root = resolved.root;
634
635        assert_eq!(
636            project_root,
637            tmp.path(),
638            "non-git: project_root must fall back to hook_cwd"
639        );
640        assert_eq!(
641            session_dir,
642            tmp.path()
643                .join(".tracevault")
644                .join("sessions")
645                .join("sess-fallback-789"),
646            "non-git: session_dir must be relative to the fallback root"
647        );
648    }
649
650    /// The origin marker written by run_stream contains the worktree toplevel.
651    /// This test exercises the same `paths::worktree_toplevel` helper the hook
652    /// uses (can't call run_stream end-to-end without a real server) so the
653    /// marker content is computed and canonicalized exactly as in production.
654    #[test]
655    fn origin_marker_written_in_session_dir() {
656        let tmp = tempfile::tempdir().unwrap();
657        let repo = tmp.path().join("repo");
658        std::fs::create_dir_all(&repo).unwrap();
659        init_git_repo(&repo);
660
661        let session_dir = repo
662            .join(".tracevault")
663            .join("sessions")
664            .join("test-sess-001");
665        std::fs::create_dir_all(&session_dir).unwrap();
666
667        let hook_cwd = &repo;
668        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
669        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
670
671        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
672        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
673        assert_eq!(
674            origin_content.trim(),
675            expected.as_str(),
676            "origin marker must contain the canonicalized worktree toplevel"
677        );
678    }
679
680    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
681
682    use crate::session_state::{RepoBinding, SessionState};
683
684    fn binding(id: &str) -> RepoBinding {
685        RepoBinding {
686            org_slug: "org".into(),
687            repo_id: id.into(),
688            git_url: None,
689            updated_at: "t".into(),
690        }
691    }
692
693    /// Workspace mode: no pinned config, but the session is bound (e.g. via
694    /// `tracevault repo switch`) — the stream event attributes to that repo.
695    #[test]
696    fn resolve_stream_binding_uses_session_active_when_unbound() {
697        let session = SessionState {
698            active: Some(binding("session-repo")),
699            subagents: HashMap::new(),
700            ..Default::default()
701        };
702        let got = resolve_stream_binding(&session, "/wt/top", None, None);
703        assert_eq!(got.unwrap().repo_id, "session-repo");
704    }
705
706    /// Bound-mode regression: an empty session (no `repo switch` ever run)
707    /// with a bound config.toml still resolves via the config.
708    #[test]
709    fn resolve_stream_binding_falls_back_to_bound_config() {
710        let session = SessionState::default();
711        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
712        assert_eq!(got.unwrap().repo_id, "bound-repo");
713    }
714
715    /// No session binding and no bound config: nothing resolves, which is
716    /// exactly what should trigger `run_stream`'s graceful no-op.
717    #[test]
718    fn resolve_stream_binding_none_when_nothing_resolves() {
719        let session = SessionState::default();
720        let got = resolve_stream_binding(&session, "/wt/top", None, None);
721        assert!(got.is_none());
722    }
723
724    /// Subagent override precedence: a per-worktree override for the current
725    /// worktree wins over the session's `active` binding.
726    #[test]
727    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
728        let session = SessionState {
729            active: Some(binding("session-repo")),
730            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
731            ..Default::default()
732        };
733        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
734        assert_eq!(got.unwrap().repo_id, "subagent-repo");
735    }
736
737    /// Workspace mode: no bound config, but a user-level default is set (e.g.
738    /// via `tracevault repo switch --user`) — the stream event attributes to
739    /// that repo when nothing more specific resolves.
740    #[test]
741    fn resolve_stream_binding_falls_back_to_user_default() {
742        let session = SessionState::default();
743        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
744        assert_eq!(got.unwrap().repo_id, "userdef");
745    }
746
747    /// The user-level default is the LOWEST-precedence tier: a bound config
748    /// still wins over it.
749    #[test]
750    fn resolve_stream_binding_prefers_bound_over_user_default() {
751        let session = SessionState::default();
752        let got = resolve_stream_binding(
753            &session,
754            "/wt/x",
755            Some(binding("bound")),
756            Some(binding("userdef")),
757        );
758        assert_eq!(got.unwrap().repo_id, "bound");
759    }
760
761    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
762
763    #[test]
764    fn binding_repo_id_is_valid_accepts_real_uuid() {
765        assert!(binding_repo_id_is_valid(
766            "550e8400-e29b-41d4-a716-446655440000"
767        ));
768    }
769
770    #[test]
771    fn binding_repo_id_is_valid_rejects_path_traversal() {
772        assert!(!binding_repo_id_is_valid("../evil"));
773    }
774
775    #[test]
776    fn binding_repo_id_is_valid_rejects_empty() {
777        assert!(!binding_repo_id_is_valid(""));
778    }
779
780    #[test]
781    fn binding_repo_id_is_valid_rejects_non_uuid() {
782        assert!(!binding_repo_id_is_valid("not-a-uuid"));
783    }
784
785    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
786
787    #[test]
788    fn stamp_agent_sets_tool_and_version() {
789        use crate::agent::Agent;
790        let mut req = StreamEventRequest {
791            protocol_version: 1,
792            tool: Some("claude-code".to_string()),
793            event_type: StreamEventType::ToolUse,
794            session_id: "s".into(),
795            timestamp: chrono::Utc::now(),
796            hook_event_name: None,
797            tool_name: None,
798            tool_use_id: None,
799            tool_input: None,
800            tool_response: None,
801            tool_is_error: None,
802            event_index: None,
803            event_uuid: None,
804            transcript_lines: None,
805            transcript_offset: None,
806            model: None,
807            cwd: None,
808            final_stats: None,
809            flow_id: None,
810            labels: None,
811            params: None,
812        };
813        stamp_agent(&mut req, Agent::Codex);
814        assert_eq!(req.tool.as_deref(), Some("codex"));
815        assert_eq!(req.protocol_version, 2);
816
817        stamp_agent(&mut req, Agent::ClaudeCode);
818        assert_eq!(req.tool.as_deref(), Some("claude-code"));
819        assert_eq!(req.protocol_version, 1);
820    }
821
822    // ── pending_path_for: repo-scoped offline queue ──────────────────────────
823
824    #[test]
825    fn pending_path_is_repo_scoped() {
826        let dir = std::path::Path::new("/tmp/sess");
827        assert_eq!(
828            pending_path_for(dir, "repo-a"),
829            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
830        );
831        assert_ne!(
832            pending_path_for(dir, "repo-a"),
833            pending_path_for(dir, "repo-b"),
834        );
835    }
836
837    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
838
839    #[test]
840    fn read_new_transcript_lines_empty_path_is_noop() {
841        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
842        // An empty path must yield no lines and offset 0, never an error from
843        // handing `Path::new("")` to exists()/File::open.
844        let dir = tempfile::tempdir().unwrap();
845        let offset_path = dir.path().join(".stream_offset");
846        let (lines, new_offset) =
847            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
848        assert!(
849            lines.is_empty(),
850            "empty path must yield no transcript lines"
851        );
852        assert_eq!(new_offset, 0);
853    }
854}