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