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 loaded [`crate::context::Context`] into the three optional fields
12/// 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::Context,
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/// Resolve the project root and session directory for a stream hook invocation.
106///
107/// This is the pure, testable core of `run_stream`'s path resolution. It uses
108/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
109/// --git-common-dir` first, so it correctly resolves to the **primary**
110/// `.tracevault/` directory from any worktree — including sibling linked
111/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
112///
113/// Returns `(resolved, session_dir)` — the resolved
114/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
115/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
116/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
117pub fn resolve_session_paths(
118    hook_cwd: &Path,
119    session_id: &str,
120) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
121    let resolved = crate::paths::resolve_project_root(hook_cwd);
122    let session_dir = resolved
123        .root
124        .join(".tracevault")
125        .join("sessions")
126        .join(session_id);
127    (resolved, session_dir)
128}
129
130pub async fn run_stream(event_type: &str) -> Result<(), Box<dyn std::error::Error>> {
131    // 1. Read HookEvent from stdin
132    let mut input = String::new();
133    io::stdin().read_to_string(&mut input)?;
134    let hook_event = parse_hook_event(&input)?;
135
136    // Resolve project_root and session_dir via the shared git-aware resolver.
137    //
138    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
139    // the primary worktree root, so it works correctly from a primary checkout,
140    // a nested worktree, AND a sibling linked worktree (where the primary
141    // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
142    // would fall back to hook_cwd itself, fail to load config, and silently
143    // drop the event).
144    //
145    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
146    // call).  Genuine resolution failure (no git, no `.tracevault/`) results in
147    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
148    // just below runs BEFORE the config/credentials check and can itself
149    // `?`-exit early — that remains graceful because `main.rs` catches all
150    // `Err` from `run_stream` and exits 0 without blocking the tool.
151    let hook_cwd = Path::new(&hook_event.cwd);
152    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
153    if resolved.source == crate::paths::ProjectRootSource::Fallback {
154        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
155        // we are about to create a fresh `.tracevault/` at the hook's working
156        // directory — which is how stray per-subdirectory `.tracevault/` dirs
157        // appear. Surface it (best-effort; stderr never blocks the hook).
158        eprintln!(
159            "tracevault: warning: could not resolve a git project root from {}; \
160             creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
161             that it runs inside the repository to keep sessions under the repo root.",
162            hook_cwd.display()
163        );
164    }
165    let project_root = resolved.root;
166
167    // 2. Create session dir
168    fs::create_dir_all(&session_dir)?;
169
170    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
171    // inside whatever `.tracevault/` we just created — including a per-subproject
172    // one. `tracevault init` writes this for the root dir, but runtime-created
173    // dirs would otherwise have no .gitignore and leak sessions into commits.
174    // Best-effort: never fail the hook on this.
175    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
176
177    // Write origin marker so verify-start can disambiguate sessions by worktree.
178    // Best-effort: never fail the hook on marker errors. Uses the shared
179    // canonicalizing helper so the value matches what verify-start compares
180    // against on the read side.
181    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
182    let _ = fs::write(session_dir.join("origin"), &worktree_top);
183
184    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
185    //    it both orders events and is a stable idempotency key — no shared
186    //    `.event_counter` file (which raced between concurrent parallel-tool
187    //    hooks and could collide/drop events).
188    let event_uuid = uuid::Uuid::now_v7();
189
190    // 4. Read new transcript lines
191    let transcript_path = Path::new(&hook_event.transcript_path);
192    let offset_path = session_dir.join(".stream_offset");
193    let (transcript_lines, new_offset) = read_new_transcript_lines(transcript_path, &offset_path)?;
194
195    // 5. Build StreamEventRequest
196    let stream_event_type = match event_type {
197        "notification" => StreamEventType::SessionStart,
198        "stop" => StreamEventType::SessionEnd,
199        _ => StreamEventType::ToolUse,
200    };
201
202    // Extract is_error from transcript for this tool_use_id
203    let tool_is_error = hook_event
204        .tool_use_id
205        .as_deref()
206        .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines));
207
208    // Load the EFFECTIVE merged context (global merged with per-worktree, if any)
209    // and extract fields before building the request.  Using `effective` means
210    // parallel sessions in different linked worktrees each stamp their own
211    // per-worktree context without interfering with each other.
212    let ctx = crate::context::Context::effective(hook_cwd);
213    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
214
215    let mut req = StreamEventRequest {
216        protocol_version: 1,
217        tool: Some("claude-code".to_string()),
218        event_type: stream_event_type,
219        session_id: hook_event.session_id.clone(),
220        timestamp: chrono::Utc::now(),
221        hook_event_name: Some(hook_event.hook_event_name.clone()),
222        tool_name: hook_event.tool_name.clone(),
223        tool_use_id: hook_event.tool_use_id.clone(),
224        tool_input: hook_event.tool_input.clone(),
225        tool_response: hook_event.tool_response.clone(),
226        tool_is_error,
227        event_index: None,
228        event_uuid: Some(event_uuid),
229        transcript_lines: if transcript_lines.is_empty() {
230            None
231        } else {
232            Some(transcript_lines)
233        },
234        transcript_offset: Some(new_offset),
235        model: None,
236        cwd: Some(hook_event.cwd.clone()),
237        final_stats: None,
238        flow_id: ctx_flow_id,
239        labels: ctx_labels,
240        params: ctx_params,
241    };
242
243    req.truncate_large_fields();
244
245    // 6. Resolve credentials
246    let (server_url, token) = crate::api_client::resolve_credentials(&project_root);
247
248    // 7. Load config for org_slug and repo_id
249    let config =
250        crate::config::TracevaultConfig::load(&project_root).ok_or("TracevaultConfig not found")?;
251    let org_slug = config
252        .org_slug
253        .as_deref()
254        .ok_or("org_slug not configured")?;
255    let repo_id = config.repo_id.as_deref().ok_or("repo_id not configured")?;
256
257    // 8. Create ApiClient
258    let server_url = server_url.ok_or("server_url not configured")?;
259    let client = crate::api_client::ApiClient::new(&server_url, token.as_deref());
260
261    // 9. Try drain pending queue and send
262    let pending_path = session_dir.join("pending.jsonl");
263    let pending_events = drain_pending(&pending_path)?;
264
265    let mut send_failed = false;
266
267    // Send pending events first
268    for pending_json in &pending_events {
269        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
270            if client
271                .stream_event(org_slug, repo_id, &pending_req)
272                .await
273                .is_err()
274            {
275                // Re-queue all remaining pending events
276                for evt in &pending_events {
277                    append_pending(&pending_path, evt)?;
278                }
279                send_failed = true;
280                break;
281            }
282        }
283    }
284
285    // Send current event
286    let req_json = serde_json::to_string(&req)?;
287    if send_failed {
288        append_pending(&pending_path, &req_json)?;
289    } else {
290        match client.stream_event(org_slug, repo_id, &req).await {
291            Ok(_) => {
292                // 10. On success update .stream_offset
293                fs::write(&offset_path, new_offset.to_string())?;
294            }
295            Err(_) => {
296                // 11. On failure append to pending.jsonl
297                append_pending(&pending_path, &req_json)?;
298            }
299        }
300    }
301
302    // 12. Always print HookResponse::allow() to stdout
303    let response = HookResponse::allow();
304    println!("{}", serde_json::to_string(&response)?);
305
306    Ok(())
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312    use crate::context::Context;
313    use std::collections::BTreeMap;
314
315    // ── apply_context: all three fields populated ─────────────────────────────
316
317    #[test]
318    fn apply_context_stamps_all_fields() {
319        let dir = tempfile::tempdir().unwrap();
320        let mut params = BTreeMap::new();
321        params.insert("env".to_string(), "prod".to_string());
322        params.insert("region".to_string(), "eu-west-1".to_string());
323
324        let ctx = Context {
325            flow_id: Some("flow-xyz".to_string()),
326            labels: vec!["backend".to_string(), "urgent".to_string()],
327            params,
328        };
329
330        let (flow_id, labels, params_out) = apply_context(ctx);
331
332        assert_eq!(flow_id, Some("flow-xyz".to_string()));
333        assert_eq!(
334            labels,
335            Some(vec!["backend".to_string(), "urgent".to_string()])
336        );
337        let p = params_out.expect("params should be Some");
338        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
339        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
340
341        // Verify the context file round-trips through save_to → load_from → apply_context.
342        let written = Context {
343            flow_id: Some("flow-xyz".to_string()),
344            labels: vec!["backend".to_string(), "urgent".to_string()],
345            params: {
346                let mut m = BTreeMap::new();
347                m.insert("env".to_string(), "prod".to_string());
348                m.insert("region".to_string(), "eu-west-1".to_string());
349                m
350            },
351        };
352        let ctx_path = dir.path().join(".tracevault").join("context.json");
353        written.save_to(&ctx_path).unwrap();
354        let loaded = Context::load_from(&ctx_path);
355        let (flow_id2, labels2, params2) = apply_context(loaded);
356        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
357        assert!(labels2.is_some());
358        assert!(params2.is_some());
359    }
360
361    // ── apply_context: missing context file → all None ────────────────────────
362
363    #[test]
364    fn apply_context_missing_file_all_none() {
365        let dir = tempfile::tempdir().unwrap();
366        let missing_path = dir.path().join(".tracevault").join("context.json");
367        let ctx = Context::load_from(&missing_path); // no context.json → default
368        let (flow_id, labels, params) = apply_context(ctx);
369        assert!(flow_id.is_none(), "flow_id should be None");
370        assert!(labels.is_none(), "labels should be None");
371        assert!(params.is_none(), "params should be None");
372    }
373
374    // ── apply_context: empty labels vec / empty params map → None ─────────────
375
376    #[test]
377    fn apply_context_empty_collections_are_none() {
378        let ctx = Context {
379            flow_id: None,
380            labels: vec![],
381            params: BTreeMap::new(),
382        };
383        let (flow_id, labels, params) = apply_context(ctx);
384        assert!(flow_id.is_none());
385        assert!(
386            labels.is_none(),
387            "empty labels should be None, not Some([])"
388        );
389        assert!(
390            params.is_none(),
391            "empty params should be None, not Some({{}})"
392        );
393    }
394
395    // ── apply_context: flow_id only, collections empty ────────────────────────
396
397    #[test]
398    fn apply_context_flow_id_only() {
399        let ctx = Context {
400            flow_id: Some("my-flow".to_string()),
401            labels: vec![],
402            params: BTreeMap::new(),
403        };
404        let (flow_id, labels, params) = apply_context(ctx);
405        assert_eq!(flow_id, Some("my-flow".to_string()));
406        assert!(labels.is_none());
407        assert!(params.is_none());
408    }
409
410    // ── resolve_session_paths tests ───────────────────────────────────────────
411    //
412    // These tests verify that `resolve_session_paths` routes through the
413    // git-aware resolver so that sibling linked worktrees capture events under
414    // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
415
416    use crate::test_helpers::{add_worktree, init_git_repo};
417
418    /// Primary checkout: project_root resolves to the repo root; session_dir is
419    /// under `<repo>/.tracevault/sessions/<id>/`.
420    #[test]
421    fn resolve_session_paths_primary_checkout() {
422        let tmp = tempfile::tempdir().unwrap();
423        let repo = tmp.path().join("repo");
424        std::fs::create_dir_all(&repo).unwrap();
425        init_git_repo(&repo);
426        // Create a .tracevault/ in the primary root to match a real init.
427        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
428
429        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
430        let project_root = resolved.root;
431
432        assert_eq!(
433            project_root.canonicalize().unwrap(),
434            repo.canonicalize().unwrap(),
435            "primary checkout: project_root must be repo root"
436        );
437        assert_eq!(
438            session_dir.canonicalize().unwrap_or(session_dir.clone()),
439            repo.join(".tracevault")
440                .join("sessions")
441                .join("sess-primary-123"),
442            "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
443        );
444        // session_dir must be INSIDE the primary repo, not elsewhere.
445        assert!(
446            session_dir.starts_with(&repo),
447            "session_dir must be under the primary repo root"
448        );
449    }
450
451    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
452    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
453    /// git-aware resolver must return the PRIMARY root.
454    #[test]
455    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
456        let tmp = tempfile::tempdir().unwrap();
457        let repo = tmp.path().join("repo");
458        // Sibling worktree lives outside the primary repo directory.
459        let wt = tmp.path().join("sibling-wt");
460
461        std::fs::create_dir_all(&repo).unwrap();
462        init_git_repo(&repo);
463        // Place .tracevault/ ONLY in the primary repo — not in the worktree.
464        std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
465        add_worktree(&repo, &wt);
466
467        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
468        let project_root = resolved.root;
469
470        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
471        assert_eq!(
472            project_root.canonicalize().unwrap(),
473            repo.canonicalize().unwrap(),
474            "sibling worktree: project_root must be primary repo root (not worktree dir)"
475        );
476        // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
477        assert!(
478            session_dir.starts_with(&repo),
479            "sibling worktree: session_dir must be under the PRIMARY repo root"
480        );
481        assert!(
482            !session_dir.starts_with(&wt),
483            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
484        );
485        assert!(
486            session_dir.ends_with(
487                std::path::Path::new(".tracevault")
488                    .join("sessions")
489                    .join("sess-sibling-456")
490            ),
491            "session_dir must end with .tracevault/sessions/<session_id>"
492        );
493    }
494
495    /// Non-git directory with no `.tracevault/` ancestor: project_root falls
496    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
497    #[test]
498    fn resolve_session_paths_non_git_fallback() {
499        let tmp = tempfile::tempdir().unwrap();
500        // No git repo, no .tracevault/ anywhere.
501        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
502        let project_root = resolved.root;
503
504        assert_eq!(
505            project_root,
506            tmp.path(),
507            "non-git: project_root must fall back to hook_cwd"
508        );
509        assert_eq!(
510            session_dir,
511            tmp.path()
512                .join(".tracevault")
513                .join("sessions")
514                .join("sess-fallback-789"),
515            "non-git: session_dir must be relative to the fallback root"
516        );
517    }
518
519    /// The origin marker written by run_stream contains the worktree toplevel.
520    /// This test exercises the same `paths::worktree_toplevel` helper the hook
521    /// uses (can't call run_stream end-to-end without a real server) so the
522    /// marker content is computed and canonicalized exactly as in production.
523    #[test]
524    fn origin_marker_written_in_session_dir() {
525        let tmp = tempfile::tempdir().unwrap();
526        let repo = tmp.path().join("repo");
527        std::fs::create_dir_all(&repo).unwrap();
528        init_git_repo(&repo);
529
530        let session_dir = repo
531            .join(".tracevault")
532            .join("sessions")
533            .join("test-sess-001");
534        std::fs::create_dir_all(&session_dir).unwrap();
535
536        let hook_cwd = &repo;
537        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
538        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
539
540        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
541        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
542        assert_eq!(
543            origin_content.trim(),
544            expected.as_str(),
545            "origin marker must contain the canonicalized worktree toplevel"
546        );
547    }
548}