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 OR malformed config simply yields no user
245    // layer (matching the prior behavior of always passing `None`); the
246    // org_slug/repo_id requirement is still enforced later.
247    let config = crate::config::TracevaultConfig::try_load(&project_root);
248    let user_layer = config
249        .as_ref()
250        .ok()
251        .and_then(|opt| opt.as_ref())
252        .and_then(|c| c.user_context.resolve());
253
254    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
255    // global and per-worktree) and extract fields before building the
256    // request.  Using `effective` means parallel sessions in different linked
257    // worktrees each stamp their own per-worktree context without
258    // interfering with each other.
259    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
260    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
261
262    let mut req = StreamEventRequest {
263        protocol_version: 1,
264        tool: Some("claude-code".to_string()),
265        event_type: stream_event_type,
266        session_id: hook_event.session_id.clone(),
267        timestamp: chrono::Utc::now(),
268        hook_event_name: Some(hook_event.hook_event_name.clone()),
269        tool_name: hook_event.tool_name.clone(),
270        tool_use_id: hook_event.tool_use_id.clone(),
271        tool_input: hook_event.tool_input.clone(),
272        tool_response: hook_event.tool_response.clone(),
273        tool_is_error,
274        event_index: None,
275        event_uuid: Some(event_uuid),
276        transcript_lines: if transcript_lines.is_empty() {
277            None
278        } else {
279            Some(transcript_lines)
280        },
281        transcript_offset: Some(new_offset),
282        model: None,
283        cwd: Some(hook_event.cwd.clone()),
284        final_stats: None,
285        flow_id: ctx_flow_id,
286        labels: ctx_labels,
287        params: ctx_params,
288    };
289
290    req.truncate_large_fields();
291
292    // 6. Resolve credentials
293    let (server_url, token) = crate::api_client::resolve_credentials(&project_root);
294
295    // 7. Config (loaded above, alongside the user-level context layer
296    // resolution) no longer directly gates org_slug/repo_id — a missing
297    // config is not fatal on its own, since the repo may instead resolve via
298    // the workspace-mode precedence chain (session binding / subagent
299    // worktree override) below. A malformed config is still surfaced here —
300    // that's easy to miss in hook output otherwise. Only a bound
301    // `config.toml`'s org_slug/repo_id feed the lowest-precedence tier
302    // (via `binding_from_config` below).
303    if let Err(e) = &config {
304        return Err(format!("malformed .tracevault/config.toml: {e}").into());
305    }
306
307    // Resolve the effective repo binding (workspace/detached mode). Bound
308    // mode (a pinned config.toml) still works — it's the lowest-precedence
309    // tier, wired below via `binding_from_config`, fed from the `config`
310    // already loaded above (no second read of config.toml on this hot path).
311    let session = crate::session_state::load(&hook_event.session_id);
312    let bound = config
313        .as_ref()
314        .ok()
315        .and_then(|opt| opt.as_ref())
316        .and_then(crate::resolution::binding_from_config);
317    let binding = resolve_stream_binding(&session, &worktree_top, bound);
318    // Graceful no-op, exactly like the hook's normal success path. Do NOT
319    // error: a failing hook would block the tool.
320    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
321        let response = HookResponse::allow();
322        println!("{}", serde_json::to_string(&response)?);
323        Ok(())
324    };
325    let Some(binding) = binding else {
326        // No repo resolves.
327        no_op_allow()?;
328        return Ok(());
329    };
330    if !binding_repo_id_is_valid(&binding.repo_id) {
331        // A corrupted/hand-edited session-state file could contain a
332        // repo_id with path separators, which would otherwise land in the
333        // `pending-<repo_id>.jsonl` filename below.
334        no_op_allow()?;
335        return Ok(());
336    }
337    let org_slug = binding.org_slug.as_str();
338    let repo_id = binding.repo_id.as_str();
339
340    // 8. Create ApiClient
341    let server_url = server_url.ok_or("server_url not configured")?;
342    let client = crate::api_client::ApiClient::new(&server_url, token.as_deref());
343
344    // 9. Try drain pending queue and send
345    let pending_path = pending_path_for(&session_dir, repo_id);
346    let pending_events = drain_pending(&pending_path)?;
347
348    let mut send_failed = false;
349
350    // Send pending events first
351    for pending_json in &pending_events {
352        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
353            if client
354                .stream_event(org_slug, repo_id, &pending_req)
355                .await
356                .is_err()
357            {
358                // Re-queue all remaining pending events
359                for evt in &pending_events {
360                    append_pending(&pending_path, evt)?;
361                }
362                send_failed = true;
363                break;
364            }
365        }
366    }
367
368    // Send current event
369    let req_json = serde_json::to_string(&req)?;
370    if send_failed {
371        append_pending(&pending_path, &req_json)?;
372    } else {
373        match client.stream_event(org_slug, repo_id, &req).await {
374            Ok(_) => {
375                // 10. On success update .stream_offset
376                fs::write(&offset_path, new_offset.to_string())?;
377            }
378            Err(_) => {
379                // 11. On failure append to pending.jsonl
380                append_pending(&pending_path, &req_json)?;
381            }
382        }
383    }
384
385    // 12. Always print HookResponse::allow() to stdout
386    let response = HookResponse::allow();
387    println!("{}", serde_json::to_string(&response)?);
388
389    Ok(())
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::config::UserContext;
396    use crate::context::{Context, EffectiveContext};
397    use std::collections::BTreeMap;
398
399    // ── user layer resolution: disabled config → no user layer ────────────────
400
401    #[test]
402    fn disabled_user_context_resolves_to_none() {
403        // Default/disabled `user_context` (the `Toggle(false)` variant) must
404        // resolve to `None`, matching the pre-existing hook behavior of
405        // stamping without a user layer when it isn't configured.
406        assert!(UserContext::Toggle(false).resolve().is_none());
407    }
408
409    #[test]
410    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
411        // With no user layer and no global/worktree context files present,
412        // `Context::effective` must yield a default (empty) `EffectiveContext`
413        // — i.e. passing `None` for `user_layer` is behavior-preserving.
414        let dir = tempfile::tempdir().unwrap();
415        let effective = Context::effective(dir.path(), None);
416        assert_eq!(effective, EffectiveContext::default());
417    }
418
419    // ── apply_context: all three fields populated ─────────────────────────────
420
421    #[test]
422    fn apply_context_stamps_all_fields() {
423        let dir = tempfile::tempdir().unwrap();
424        let mut params = BTreeMap::new();
425        params.insert("env".to_string(), "prod".to_string());
426        params.insert("region".to_string(), "eu-west-1".to_string());
427
428        let ctx = EffectiveContext {
429            flow_id: Some("flow-xyz".to_string()),
430            labels: vec!["backend".to_string(), "urgent".to_string()],
431            params,
432        };
433
434        let (flow_id, labels, params_out) = apply_context(ctx);
435
436        assert_eq!(flow_id, Some("flow-xyz".to_string()));
437        assert_eq!(
438            labels,
439            Some(vec!["backend".to_string(), "urgent".to_string()])
440        );
441        let p = params_out.expect("params should be Some");
442        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
443        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
444
445        // Verify the stored context round-trips through save_to → load_from →
446        // merge_layers → apply_context (stored params are now `Option<String>`).
447        let written = Context {
448            flow_id: Some("flow-xyz".to_string()),
449            labels: vec!["backend".to_string(), "urgent".to_string()],
450            params: {
451                let mut m = BTreeMap::new();
452                m.insert("env".to_string(), Some("prod".to_string()));
453                m.insert("region".to_string(), Some("eu-west-1".to_string()));
454                m
455            },
456        };
457        let ctx_path = dir.path().join(".tracevault").join("context.json");
458        written.save_to(&ctx_path).unwrap();
459        let loaded = Context::load_from(&ctx_path);
460        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
461        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
462        assert!(labels2.is_some());
463        assert!(params2.is_some());
464    }
465
466    // ── apply_context: missing context file → all None ────────────────────────
467
468    #[test]
469    fn apply_context_missing_file_all_none() {
470        let dir = tempfile::tempdir().unwrap();
471        let missing_path = dir.path().join(".tracevault").join("context.json");
472        let ctx = Context::load_from(&missing_path); // no context.json → default
473        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
474        assert!(flow_id.is_none(), "flow_id should be None");
475        assert!(labels.is_none(), "labels should be None");
476        assert!(params.is_none(), "params should be None");
477    }
478
479    // ── apply_context: empty labels vec / empty params map → None ─────────────
480
481    #[test]
482    fn apply_context_empty_collections_are_none() {
483        let ctx = EffectiveContext {
484            flow_id: None,
485            labels: vec![],
486            params: BTreeMap::new(),
487        };
488        let (flow_id, labels, params) = apply_context(ctx);
489        assert!(flow_id.is_none());
490        assert!(
491            labels.is_none(),
492            "empty labels should be None, not Some([])"
493        );
494        assert!(
495            params.is_none(),
496            "empty params should be None, not Some({{}})"
497        );
498    }
499
500    // ── apply_context: flow_id only, collections empty ────────────────────────
501
502    #[test]
503    fn apply_context_flow_id_only() {
504        let ctx = EffectiveContext {
505            flow_id: Some("my-flow".to_string()),
506            labels: vec![],
507            params: BTreeMap::new(),
508        };
509        let (flow_id, labels, params) = apply_context(ctx);
510        assert_eq!(flow_id, Some("my-flow".to_string()));
511        assert!(labels.is_none());
512        assert!(params.is_none());
513    }
514
515    // ── resolve_session_paths tests ───────────────────────────────────────────
516    //
517    // These tests verify that `resolve_session_paths` routes through the
518    // git-aware resolver so that sibling linked worktrees capture events under
519    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
520
521    use crate::test_helpers::{add_worktree, init_git_repo};
522
523    /// Primary checkout: project_root resolves to the repo root; session_dir is
524    /// under `<repo>/.tracevault/sessions/<id>/`.
525    #[test]
526    fn resolve_session_paths_primary_checkout() {
527        let tmp = tempfile::tempdir().unwrap();
528        let repo = tmp.path().join("repo");
529        std::fs::create_dir_all(&repo).unwrap();
530        init_git_repo(&repo);
531        // Create a .tracevault/ in the primary root to match a real init.
532        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
533
534        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
535        let project_root = resolved.root;
536
537        assert_eq!(
538            project_root.canonicalize().unwrap(),
539            repo.canonicalize().unwrap(),
540            "primary checkout: project_root must be repo root"
541        );
542        assert_eq!(
543            session_dir.canonicalize().unwrap_or(session_dir.clone()),
544            repo.join(".tracevault")
545                .join("sessions")
546                .join("sess-primary-123"),
547            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
548        );
549        // session_dir must be INSIDE the primary repo, not elsewhere.
550        assert!(
551            session_dir.starts_with(&repo),
552            "session_dir must be under the primary repo root"
553        );
554    }
555
556    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
557    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
558    /// git-aware resolver must return the PRIMARY root.
559    #[test]
560    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
561        let tmp = tempfile::tempdir().unwrap();
562        let repo = tmp.path().join("repo");
563        // Sibling worktree lives outside the primary repo directory.
564        let wt = tmp.path().join("sibling-wt");
565
566        std::fs::create_dir_all(&repo).unwrap();
567        init_git_repo(&repo);
568        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
569        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
570        add_worktree(&repo, &wt);
571
572        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
573        let project_root = resolved.root;
574
575        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
576        assert_eq!(
577            project_root.canonicalize().unwrap(),
578            repo.canonicalize().unwrap(),
579            "sibling worktree: project_root must be primary repo root (not worktree dir)"
580        );
581        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
582        assert!(
583            session_dir.starts_with(&repo),
584            "sibling worktree: session_dir must be under the PRIMARY repo root"
585        );
586        assert!(
587            !session_dir.starts_with(&wt),
588            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
589        );
590        assert!(
591            session_dir.ends_with(
592                std::path::Path::new(".tracevault")
593                    .join("sessions")
594                    .join("sess-sibling-456")
595            ),
596            "session_dir must end with .tracevault/sessions/<session_id>"
597        );
598    }
599
600    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
601    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
602    #[test]
603    fn resolve_session_paths_non_git_fallback() {
604        let tmp = tempfile::tempdir().unwrap();
605        // No git repo, no .tracevault/ anywhere.
606        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
607        let project_root = resolved.root;
608
609        assert_eq!(
610            project_root,
611            tmp.path(),
612            "non-git: project_root must fall back to hook_cwd"
613        );
614        assert_eq!(
615            session_dir,
616            tmp.path()
617                .join(".tracevault")
618                .join("sessions")
619                .join("sess-fallback-789"),
620            "non-git: session_dir must be relative to the fallback root"
621        );
622    }
623
624    /// The origin marker written by run_stream contains the worktree toplevel.
625    /// This test exercises the same `paths::worktree_toplevel` helper the hook
626    /// uses (can't call run_stream end-to-end without a real server) so the
627    /// marker content is computed and canonicalized exactly as in production.
628    #[test]
629    fn origin_marker_written_in_session_dir() {
630        let tmp = tempfile::tempdir().unwrap();
631        let repo = tmp.path().join("repo");
632        std::fs::create_dir_all(&repo).unwrap();
633        init_git_repo(&repo);
634
635        let session_dir = repo
636            .join(".tracevault")
637            .join("sessions")
638            .join("test-sess-001");
639        std::fs::create_dir_all(&session_dir).unwrap();
640
641        let hook_cwd = &repo;
642        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
643        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
644
645        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
646        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
647        assert_eq!(
648            origin_content.trim(),
649            expected.as_str(),
650            "origin marker must contain the canonicalized worktree toplevel"
651        );
652    }
653
654    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
655
656    use crate::session_state::{RepoBinding, SessionState};
657
658    fn binding(id: &str) -> RepoBinding {
659        RepoBinding {
660            org_slug: "org".into(),
661            repo_id: id.into(),
662            git_url: None,
663            updated_at: "t".into(),
664        }
665    }
666
667    /// Workspace mode: no pinned config, but the session is bound (e.g. via
668    /// `tracevault repo switch`) — the stream event attributes to that repo.
669    #[test]
670    fn resolve_stream_binding_uses_session_active_when_unbound() {
671        let session = SessionState {
672            active: Some(binding("session-repo")),
673            subagents: HashMap::new(),
674            ..Default::default()
675        };
676        let got = resolve_stream_binding(&session, "/wt/top", None);
677        assert_eq!(got.unwrap().repo_id, "session-repo");
678    }
679
680    /// Bound-mode regression: an empty session (no `repo switch` ever run)
681    /// with a bound config.toml still resolves via the config.
682    #[test]
683    fn resolve_stream_binding_falls_back_to_bound_config() {
684        let session = SessionState::default();
685        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")));
686        assert_eq!(got.unwrap().repo_id, "bound-repo");
687    }
688
689    /// No session binding and no bound config: nothing resolves, which is
690    /// exactly what should trigger `run_stream`'s graceful no-op.
691    #[test]
692    fn resolve_stream_binding_none_when_nothing_resolves() {
693        let session = SessionState::default();
694        let got = resolve_stream_binding(&session, "/wt/top", None);
695        assert!(got.is_none());
696    }
697
698    /// Subagent override precedence: a per-worktree override for the current
699    /// worktree wins over the session's `active` binding.
700    #[test]
701    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
702        let session = SessionState {
703            active: Some(binding("session-repo")),
704            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
705            ..Default::default()
706        };
707        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")));
708        assert_eq!(got.unwrap().repo_id, "subagent-repo");
709    }
710
711    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
712
713    #[test]
714    fn binding_repo_id_is_valid_accepts_real_uuid() {
715        assert!(binding_repo_id_is_valid(
716            "550e8400-e29b-41d4-a716-446655440000"
717        ));
718    }
719
720    #[test]
721    fn binding_repo_id_is_valid_rejects_path_traversal() {
722        assert!(!binding_repo_id_is_valid("../evil"));
723    }
724
725    #[test]
726    fn binding_repo_id_is_valid_rejects_empty() {
727        assert!(!binding_repo_id_is_valid(""));
728    }
729
730    #[test]
731    fn binding_repo_id_is_valid_rejects_non_uuid() {
732        assert!(!binding_repo_id_is_valid("not-a-uuid"));
733    }
734
735    // ── pending_path_for: repo-scoped offline queue ──────────────────────────
736
737    #[test]
738    fn pending_path_is_repo_scoped() {
739        let dir = std::path::Path::new("/tmp/sess");
740        assert_eq!(
741            pending_path_for(dir, "repo-a"),
742            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
743        );
744        assert_ne!(
745            pending_path_for(dir, "repo-a"),
746            pending_path_for(dir, "repo-b"),
747        );
748    }
749}