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