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