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
42/// Returns `(lines, start_offset, end_offset)`: `start_offset` is the seek
43/// position read from `offset_path` (0 if absent), and `end_offset` is the
44/// byte offset after the last line read (the old `bytes_read`).
45///
46/// Callers should send `start_offset` as `StreamEventRequest::transcript_offset`
47/// (so the server's `chunk_index = transcript_offset + line_index` is stable
48/// per physical line across overlapping/retried reads) and persist
49/// `end_offset` to `.stream_offset` as the next read's seek position.
50pub fn read_new_transcript_lines(
51 transcript_path: &Path,
52 offset_path: &Path,
53) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
54 // An empty path means "no transcript yet" — Codex documents `transcript_path`
55 // as nullable (e.g. on SessionStart before a rollout exists), and the hook
56 // payload deserializes null/absent to "". Guard explicitly so we never hand
57 // `Path::new("")` to `exists()`/`File::open` (whose behavior on an empty path
58 // is platform-dependent); treat it as a clean no-op.
59 if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
60 return Ok((vec![], 0, 0));
61 }
62
63 let offset: i64 = if offset_path.exists() {
64 let content = fs::read_to_string(offset_path)?;
65 content
66 .trim()
67 .parse::<i64>()
68 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
69 } else {
70 0
71 };
72
73 let mut file = fs::File::open(transcript_path)?;
74 file.seek(SeekFrom::Start(offset as u64))?;
75
76 let reader = io::BufReader::new(file);
77 let mut lines = Vec::new();
78 let mut bytes_read = offset;
79
80 for line_result in reader.lines() {
81 let line = line_result?;
82 // +1 for the newline character
83 bytes_read += line.len() as i64 + 1;
84 if line.trim().is_empty() {
85 continue;
86 }
87 if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
88 lines.push(value);
89 }
90 }
91
92 Ok((lines, offset, bytes_read))
93}
94
95pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
96 let mut file = OpenOptions::new()
97 .create(true)
98 .append(true)
99 .open(pending_path)?;
100 writeln!(file, "{json}")?;
101 Ok(())
102}
103
104pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
105 if !pending_path.exists() {
106 return Ok(vec![]);
107 }
108 let content = fs::read_to_string(pending_path)?;
109 let lines: Vec<String> = content
110 .lines()
111 .filter(|l| !l.trim().is_empty())
112 .map(String::from)
113 .collect();
114 fs::remove_file(pending_path)?;
115 Ok(lines)
116}
117
118/// How a stream event is attributed on the wire, resolved from the local repo
119/// and project bindings before anything is sent.
120///
121/// The rule this type encodes: an event ships when EITHER a repo or a project
122/// resolves. Before this existed the hook required a repo binding and dropped
123/// the event otherwise, which silently discarded every event of a repo-less
124/// session even when its project was bound — despite the server supporting
125/// exactly that shape (`ProjectStreamQuery::repo_id` is `Option<Uuid>`:
126/// "repo-less (0-repo) projects are supported").
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub(crate) enum Attribution {
129 /// A usable repo binding resolved. `project` is the capture-time project
130 /// overlay; when `None` the server deduces the project from the repo.
131 Repo {
132 repo_id: String,
133 project: Option<uuid::Uuid>,
134 },
135 /// No usable repo binding, but a project did — repo-less project-scoped
136 /// ingest.
137 ProjectOnly { project_id: uuid::Uuid },
138}
139
140impl Attribution {
141 /// Offline-queue filename for this attribution. Keyed by whatever
142 /// identifies the target so a mid-session rebind (workspace mode) can
143 /// never flush one target's queued events to another.
144 ///
145 /// The `project-` infix is load-bearing for back-compat: an older CLI's
146 /// `repo_id_from_pending_filename` extracts `project-<uuid>` from this
147 /// name, fails its UUID check, and skips the file — so a downgrade leaves
148 /// these queues alone instead of trying to POST them at a repo endpoint.
149 pub(crate) fn pending_file_name(&self) -> String {
150 use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
151 match self {
152 Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
153 Self::ProjectOnly { project_id } => {
154 format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
155 }
156 }
157 }
158}
159
160/// Pure attribution resolver: fold the repo binding and the capture-time
161/// project into the target this event will be sent to. `None` means neither
162/// resolved and the hook must no-op.
163///
164/// A binding whose `repo_id` is not a UUID degrades to `ProjectOnly` rather
165/// than dropping the event — a corrupted session-state file should cost the
166/// repo attribution, not the whole trace, when a project is available.
167///
168/// `project` here is whatever `capture_project` resolved, and its lowest tier
169/// is the MACHINE-GLOBAL `project switch --user` default — not just
170/// session-scoped bindings. That tier is therefore now a sufficient condition
171/// for an event to ship, where previously it could only redirect an event that
172/// was already shipping because a repo bound. This is deliberate: it is the
173/// only binding a container can establish before the agent session exists and
174/// before the repo is cloned, which is the case this whole path serves.
175/// `resolve_stream_binding` has the same machine-global tier for repos, so the
176/// two sides stay symmetric. Consequence worth knowing: a session started in an
177/// unrelated directory, with no repo and no `.tracevault/`, will attribute to
178/// that default project.
179pub(crate) fn attribution_for(
180 binding: Option<&crate::session_state::RepoBinding>,
181 project: Option<uuid::Uuid>,
182) -> Option<Attribution> {
183 match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
184 Some(b) => Some(Attribution::Repo {
185 repo_id: b.repo_id.clone(),
186 project,
187 }),
188 None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
189 }
190}
191
192/// Offline-queue path for an attribution target.
193fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
194 session_dir.join(attribution.pending_file_name())
195}
196
197/// Resolve the project root and session directory for a stream hook invocation.
198///
199/// This is the pure, testable core of `run_stream`'s path resolution. It uses
200/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
201/// --git-common-dir` first, so it correctly resolves to the **primary**
202/// `.tracevault/` directory from any worktree — including sibling linked
203/// worktrees where the primary `.tracevault/` is not an ancestor of `hook_cwd`.
204///
205/// Returns `(resolved, session_dir)` — the resolved
206/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
207/// on a Fallback that would create a stray `.tracevault/`) and `session_dir`
208/// under `<resolved.root>/.tracevault/sessions/<session_id>/`.
209pub fn resolve_session_paths(
210 hook_cwd: &Path,
211 session_id: &str,
212) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
213 let resolved = crate::paths::resolve_project_root(hook_cwd);
214 let session_dir = resolved
215 .root
216 .join(".tracevault")
217 .join("sessions")
218 .join(session_id);
219 (resolved, session_dir)
220}
221
222/// A resolved binding is usable for hook attribution only if its repo_id is a
223/// real UUID — guards against a corrupted/edited session-state file injecting
224/// path separators into the pending-<repo_id>.jsonl filename.
225///
226/// `pub(crate)`: also called by `commands::status`, so a binding with a
227/// malformed `repo_id` is never displayed as bound (`Check::ok`) when this
228/// same check means the hook will not actually honor it.
229pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
230 uuid::Uuid::parse_str(repo_id).is_ok()
231}
232
233/// The effective repo binding for a stream event, given the loaded session
234/// state, the event's worktree, and the bound-config fallback. Pure — the
235/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
236pub(crate) fn resolve_stream_binding(
237 session: &crate::session_state::SessionState,
238 worktree: &str,
239 bound: Option<crate::session_state::RepoBinding>,
240 user_default: Option<crate::session_state::RepoBinding>,
241) -> Option<crate::session_state::RepoBinding> {
242 crate::resolution::effective_binding(crate::resolution::ResolveInputs {
243 repo_flag: None,
244 session,
245 worktree_path: Some(worktree),
246 bound,
247 user_default,
248 })
249 .map(|(b, _)| b)
250}
251
252/// Resolve the capture-time project from LOCAL, UUID-bearing bindings only — no
253/// network (the hook fires per event in a short-lived process). Precedence:
254/// subagent worktree override -> session `active_project` -> user-level default.
255/// Repo config `default_project` (a name) is intentionally excluded: honoring it
256/// would need a per-event `list_projects` call. `None` -> fall back to the
257/// repo-scoped stream (server deduces).
258///
259/// `pub(crate)`: also called by `commands::status`, which reuses this
260/// function (plus `resolve_stream_binding`/`attribution_for`) as the
261/// authoritative "will this session record anything" gate, so the status
262/// verdict can never drift from what this hook actually does.
263pub(crate) fn capture_project(
264 session: &crate::session_state::SessionState,
265 worktree_path: Option<&str>,
266) -> Option<uuid::Uuid> {
267 use crate::resolution::{effective_project, ProjectResolveInputs};
268 let local = effective_project(&ProjectResolveInputs {
269 project_flag: None,
270 session,
271 worktree_path,
272 config_default: None,
273 })
274 .map(|(b, _)| b)
275 .or_else(crate::user_project_default::load)?;
276 local.project_id.parse::<uuid::Uuid>().ok()
277}
278
279/// The one-line warning printed when a repo-less event is dropped as
280/// permanently undeliverable. Pure, so the wording is asserted directly.
281fn undeliverable_warning(pid: uuid::Uuid) -> String {
282 format!(
283 "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
284 repo binding, so there is nothing to attribute these events to and they are being \
285 DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
286 that exists."
287 )
288}
289
290/// True when a stream-send error's rendered message carries a `(4xx ...)`
291/// status marker — i.e. the server deterministically rejected the request in
292/// a way that will never succeed on blind retry (bad binding, missing
293/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
294/// transport/network/timeout failures (which have no `(NNN ` marker at all,
295/// or a 5xx one) — those remain transient and must keep propagating so the
296/// existing buffer/retry logic in `run_stream` still applies to them.
297///
298/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
299/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
300///
301/// COUPLING: the `"(NNN "` markers below must byte-for-byte match what
302/// `ApiClient::authed_send_json`'s `err_prefix` closures render (e.g.
303/// `stream_event`'s `"Stream failed ({status})"`, where `{status}` Displays
304/// as `"404 Not Found"`, yielding `"Stream failed (404 Not Found): ..."` —
305/// hence the `"(404 "` marker below matching on the open-paren + code + the
306/// space before the reason phrase). If that error-formatting ever changes,
307/// update this list (and its tests) to match.
308/// Which deterministic client error this is, so the fallback warning can name a
309/// cause that is actually possible instead of assuming one.
310#[derive(Debug, PartialEq, Eq)]
311enum ClientErrorKind {
312 /// 403, which now has TWO plausible causes — see [`send_stream_event`].
313 Forbidden,
314 /// 400/404/409: a binding/scoping problem, and only that.
315 Scoping,
316}
317
318/// The one-line warning printed when a project-scoped send falls back to
319/// repo deduction. Pure, so the wording is asserted directly rather than by
320/// capturing stderr.
321fn fallback_warning(pid: uuid::Uuid, kind: &ClientErrorKind) -> String {
322 match kind {
323 // Since Keycloak, a 403 has a SECOND and now more common cause: the
324 // account has no `tracing` realm role at all, in which case nothing this
325 // hook does will work and `project switch` is confidently wrong advice —
326 // on the code path users hit most. The server's 403 envelope is not
327 // distinguishable from here (see `ClientErrorKind`), so name both.
328 ClientErrorKind::Forbidden => format!(
329 "tracevault: warning: the server refused to attribute this event to active project \
330 {pid} (403). Either that project does not apply to this repo (not a member, or \
331 missing TracePush) — run `tracevault project switch <name>` — or this account lacks \
332 the `tracing` Keycloak realm role entirely, which an administrator must grant. \
333 Attributing via repo deduction instead."
334 ),
335 ClientErrorKind::Scoping => format!(
336 "tracevault: warning: active project {pid} does not apply to this repo (not a member, \
337 or missing permission); attributing via repo deduction instead. Run `tracevault \
338 project switch <name>` to update."
339 ),
340 }
341}
342
343fn deterministic_client_error_kind(e: &dyn std::error::Error) -> Option<ClientErrorKind> {
344 let s = e.to_string();
345 // 401 is deliberately excluded: it's an authentication failure (bad/expired
346 // token), not a project-scoping problem, and the repo-scoped fallback uses
347 // the SAME token — it would also 401, so falling back just wastes a
348 // request before the error propagates to buffer/retry. 403 stays in: it can
349 // mean the token is valid but lacks TracePush on the bound project, and the
350 // repo-scoped fallback (a different authorization check) can help.
351 if s.contains("(403 ") {
352 return Some(ClientErrorKind::Forbidden);
353 }
354 if ["(400 ", "(404 ", "(409 "]
355 .iter()
356 .any(|marker| s.contains(marker))
357 {
358 return Some(ClientErrorKind::Scoping);
359 }
360 None
361}
362
363/// Send a single stream event, routing to the project-scoped endpoint when a
364/// local project binding resolved (`capture_pid = Some(_)`), else the
365/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
366/// the pending-flush loop and the live send share one branch.
367///
368/// Routing is decided by the [`Attribution`] resolved before the send:
369/// `Repo` with no project goes to the repo-scoped endpoint (the server
370/// deduces the project); `Repo` with a project goes to the project-scoped
371/// endpoint carrying `repo_id`; `ProjectOnly` goes to the project-scoped
372/// endpoint with no `repo_id` at all. Having no fallback endpoint, it decides
373/// instead between buffering and dropping: a `Scoping` 4xx (the project does
374/// not resolve) can never succeed on retry — the offline queue is keyed by
375/// that same project id — so it warns and returns `Ok(None)`, while a 403 or
376/// any transient error propagates to be buffered. See the arm itself for why
377/// the two differ.
378///
379/// `Ok(None)` therefore means "deliberately dropped, do not queue": callers
380/// must treat it like a success for offset/queue purposes, not like an error.
381///
382/// When the attribution carries BOTH a repo and a project and the
383/// project-scoped send fails with a
384/// deterministic client error (the bound project doesn't apply to this repo:
385/// not a member, or the caller lacks `TracePush` on it, or — after a prior
386/// fallback — the repo-scoped 409 multi-project refusal), this falls back to
387/// the repo-scoped endpoint ONCE and lets the server deduce the repo's
388/// project, warning so the miss is visible. A transient error (5xx,
389/// network/transport, timeout) is NOT retried here — it propagates so the
390/// caller's existing buffer/retry logic runs unchanged.
391///
392/// `warned` is shared across every call made for a single hook
393/// invocation (both the pending-flush loop and the live send). The
394/// pending-flush loop only `break`s on `Err`, not on a fallback that itself
395/// returns `Ok` — so a stale binding whose repo-scoped fallback keeps
396/// succeeding would otherwise print the warning once per buffered event.
397/// Gating on `*warned` caps it at one warning per invocation while leaving the
398/// fallback behavior itself unchanged. The repo-less drop warning shares the
399/// flag for the same reason: draining a queue of undeliverable events would
400/// otherwise print one line per buffered event.
401async fn send_stream_event(
402 client: &crate::api_client::ApiClient,
403 attribution: &Attribution,
404 req: &StreamEventRequest,
405 warned: &mut bool,
406) -> Result<Option<tracevault_protocol::streaming::StreamEventResponse>, Box<dyn std::error::Error>>
407{
408 let (repo_id, capture_pid) = match attribution {
409 // Repo-less: there is no repo-scoped endpoint to fall back TO, so the
410 // only choice is buffer-for-retry vs. drop, and that turns on whether
411 // a retry could EVER succeed.
412 //
413 // `Scoping` (400/404/409) means the project itself does not resolve.
414 // The offline queue is keyed by that same project id
415 // (`pending-project-<uuid>.jsonl`), so re-binding to a project that
416 // does exist writes to a DIFFERENT file and these events are never
417 // retried under the corrected binding — they would accumulate forever,
418 // one per tool call, each hook fire re-reading and re-appending the
419 // whole queue. Warn and drop instead: undeliverable is undeliverable,
420 // and a growing queue only hides it.
421 //
422 // `Forbidden` (403) is deliberately NOT dropped. It can mean the
423 // account lacks the realm role entirely, which an administrator can
424 // grant — after which the buffered events do deliver. Same for any
425 // transient error. Both propagate so the caller queues them.
426 Attribution::ProjectOnly { project_id } => {
427 let attempt = client
428 .stream_event_for_project(*project_id, None, req)
429 .await;
430 return match attempt {
431 Ok(r) => Ok(Some(r)),
432 Err(e) => match deterministic_client_error_kind(e.as_ref()) {
433 Some(ClientErrorKind::Scoping) => {
434 if !*warned {
435 eprintln!("{}", undeliverable_warning(*project_id));
436 *warned = true;
437 }
438 Ok(None)
439 }
440 _ => Err(e),
441 },
442 };
443 }
444 Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
445 };
446 match capture_pid {
447 None => client.stream_event(repo_id, req).await.map(Some),
448 Some(pid) => {
449 let attempt = client
450 .stream_event_for_project(pid, Some(repo_id), req)
451 .await;
452 let kind = match &attempt {
453 Ok(_) => None,
454 Err(e) => deterministic_client_error_kind(e.as_ref()),
455 };
456 match (attempt, kind) {
457 (Ok(r), _) => Ok(Some(r)),
458 (Err(_), Some(kind)) => {
459 if !*warned {
460 // Since Keycloak, a 403 has a SECOND and now more common
461 // cause: the account has no `tracing` realm role at all,
462 // in which case nothing this hook does will work and
463 // `project switch` is confidently wrong advice — on the
464 // code path users hit most. The server's 403 envelope
465 // isn't distinguishable from here (see
466 // `ClientErrorKind`), so the wording names both.
467 eprintln!("{}", fallback_warning(pid, &kind));
468 *warned = true;
469 }
470 // Repo-scoped fallback: the server deduces the project itself.
471 client.stream_event(repo_id, req).await.map(Some)
472 }
473 // transient — propagate for buffer/retry
474 (Err(e), None) => Err(e),
475 }
476 }
477 }
478}
479
480/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
481/// byte-offset semantics of `read_new_transcript_lines`: returns
482/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
483/// `transcript_offset` (base for the server's per-line `chunk_index`) and
484/// `next_offset` is persisted to `.stream_offset`.
485pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
486 (start_offset, start_offset + records_len)
487}
488
489/// Choose the transcript source for a stream event. Inline records (from a
490/// plugin-based agent like OpenCode) win over the file-read result whenever the
491/// hook event carries them — INCLUDING an empty vec, so an event with no new
492/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
493/// instead of resetting it to the file-path's 0.
494pub fn resolve_transcript_source(
495 inline_records: Option<Vec<serde_json::Value>>,
496 prior_offset: i64,
497 file_result: (Vec<serde_json::Value>, i64, i64),
498) -> (Vec<serde_json::Value>, i64, i64) {
499 match inline_records {
500 Some(records) => {
501 let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
502 (records, send, next)
503 }
504 None => file_result,
505 }
506}
507
508/// Derive the event-level tool-error flag from inline transcript records.
509/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
510/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
511/// signals the outcome. Returns `Some(true|false)` for the first `toolResult`
512/// record found, or `None` when there is none (non-tool events).
513pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
514 lines.iter().find_map(|line| {
515 let msg = line.get("message")?;
516 if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
517 Some(
518 msg.get("isError")
519 .and_then(|v| v.as_bool())
520 .unwrap_or(false),
521 )
522 } else {
523 None
524 }
525 })
526}
527
528/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
529/// Factored out so the mapping is testable without the network/FS-bound
530/// `run_stream`.
531pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
532 req.tool = Some(agent.tool_name().to_string());
533 req.protocol_version = agent.protocol_version() as u32;
534}
535
536pub async fn run_stream(
537 event_type: &str,
538 agent: crate::agent::Agent,
539) -> Result<(), Box<dyn std::error::Error>> {
540 // 1. Read HookEvent from stdin
541 let mut input = String::new();
542 io::stdin().read_to_string(&mut input)?;
543 let mut hook_event = parse_hook_event(&input)?;
544
545 // Resolve project_root and session_dir via the shared git-aware resolver.
546 //
547 // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
548 // the primary worktree root, so it works correctly from a primary checkout,
549 // a nested worktree, AND a sibling linked worktree (where the primary
550 // `.tracevault/` is NOT an ancestor of hook_cwd — the old ancestor-walk
551 // would fall back to hook_cwd itself, fail to load config, and silently
552 // drop the event).
553 //
554 // The hook must never hard-fail (a failing hook blocks the Claude Code tool
555 // call). Genuine resolution failure (no git, no `.tracevault/`) results in
556 // a Fallback root (start dir). Note: `fs::create_dir_all(&session_dir)?`
557 // just below runs BEFORE the config/credentials check and can itself
558 // `?`-exit early — that remains graceful because `main.rs` catches all
559 // `Err` from `run_stream` and exits 0 without blocking the tool.
560 let hook_cwd = Path::new(&hook_event.cwd);
561 let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
562 if resolved.source == crate::paths::ProjectRootSource::Fallback {
563 // Neither git nor an ancestor `.tracevault/` resolved a project root, so
564 // we are about to create a fresh `.tracevault/` at the hook's working
565 // directory — which is how stray per-subdirectory `.tracevault/` dirs
566 // appear. Surface it (best-effort; stderr never blocks the hook).
567 eprintln!(
568 "tracevault: warning: could not resolve a git project root from {}; \
569 creating .tracevault/ there. Ensure `git` is on PATH for the hook and \
570 that it runs inside the repository to keep sessions under the repo root.",
571 hook_cwd.display()
572 );
573 }
574 let project_root = resolved.root;
575
576 // 2. Create session dir
577 fs::create_dir_all(&session_dir)?;
578
579 // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
580 // inside whatever `.tracevault/` we just created — including a per-subproject
581 // one. `tracevault init` writes this for the root dir, but runtime-created
582 // dirs would otherwise have no .gitignore and leak sessions into commits.
583 // Best-effort: never fail the hook on this.
584 let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));
585
586 // Write origin marker so verify-start can disambiguate sessions by worktree.
587 // Best-effort: never fail the hook on marker errors. Uses the shared
588 // canonicalizing helper so the value matches what verify-start compares
589 // against on the read side.
590 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
591 let _ = fs::write(session_dir.join("origin"), &worktree_top);
592
593 // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
594 // it both orders events and is a stable idempotency key — no shared
595 // `.event_counter` file (which raced between concurrent parallel-tool
596 // hooks and could collide/drop events).
597 let event_uuid = uuid::Uuid::now_v7();
598
599 // 4. Read new transcript lines
600 let transcript_path = Path::new(&hook_event.transcript_path);
601 let offset_path = session_dir.join(".stream_offset");
602 // transcript_offset carries the batch START byte offset so the server
603 // derives a stable per-line chunk_index across overlapping/retried reads;
604 // .stream_offset persists the END (next read position).
605 let (transcript_lines, start_offset, new_offset) =
606 read_new_transcript_lines(transcript_path, &offset_path)?;
607
608 // Fileless inline path (OpenCode): a plugin-based agent with no single
609 // tailable transcript supplies records directly on the hook event. When
610 // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
611 // sends `transcript_records: []`) — they take priority over the file-read
612 // result. `.stream_offset` is reused as a per-session RECORD counter so
613 // the server's chunk_index stays stable/monotonic across retries, exactly
614 // as with the byte-offset path. Treating an empty vec as "no new
615 // records" rather than "fall back to the file" matters: OpenCode's
616 // `transcript_path` is always "", so the file-read result is always
617 // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
618 // offset back to 0 and collide with earlier turns' chunk_index on the
619 // server.
620 // Only inline (plugin-based) events override the file-read result, and only
621 // they need `.stream_offset` re-read as a record counter. File-based agents
622 // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
623 // the byte-offset values from `read_new_transcript_lines` above.
624 let is_inline = hook_event.transcript_records.is_some();
625 let (transcript_lines, start_offset, new_offset) = if is_inline {
626 // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
627 // `.stream_offset` must NOT silently reset to 0 — that would restart the
628 // record counter and collide with earlier turns' chunk_index on the
629 // server (the offset-clobber failure mode). Propagate the error instead;
630 // `main` treats a hook error as non-fatal (exits 0 without blocking the
631 // tool call). Negatives are clamped to 0 defensively.
632 let prior_offset: i64 = if offset_path.exists() {
633 let content = fs::read_to_string(&offset_path)?;
634 content
635 .trim()
636 .parse::<i64>()
637 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
638 .max(0)
639 } else {
640 0
641 };
642 // `take()` moves the records out (nothing below reads
643 // `transcript_records` again) — avoids deep-cloning a potentially
644 // large payload (full bash stdout / file contents) on the hook path.
645 resolve_transcript_source(
646 hook_event.transcript_records.take(),
647 prior_offset,
648 (transcript_lines, start_offset, new_offset),
649 )
650 } else {
651 (transcript_lines, start_offset, new_offset)
652 };
653
654 // 5. Build StreamEventRequest
655 let stream_event_type = match event_type {
656 "notification" => StreamEventType::SessionStart,
657 "stop" => StreamEventType::SessionEnd,
658 _ => StreamEventType::ToolUse,
659 };
660
661 // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
662 // events have no tool_use_id, so fall back to a forwarded `toolResult`
663 // record's `isError` — otherwise a failed OpenCode tool would render as
664 // successful (the event-level flag file-based agents populate would be None).
665 let tool_is_error = hook_event
666 .tool_use_id
667 .as_deref()
668 .and_then(|uid| extract_is_error_from_transcript(uid, &transcript_lines))
669 .or_else(|| inline_tool_is_error(&transcript_lines));
670
671 // Load config once, up front, so it can back both the user-level context
672 // layer resolution below and the repo_id lookup further down — avoids a
673 // redundant second read of the same file. `try_load` keeps the
674 // missing/malformed distinction so the required-config error further down
675 // can report which one it is.
676 // Best-effort here: a missing/unconfigured repo config does NOT mean "no
677 // user context" — `resolve_user_context` below falls back to the user-level
678 // config in that case. A malformed repo config is surfaced as an error
679 // later (the required-config check), not silently dropped here.
680 let config = crate::config::TracevaultConfig::try_load(&project_root);
681 // Repo config's user_context wins when the repo configured it; otherwise
682 // fall back to the user-level ~/.config/tracevault/config.toml. This is
683 // what lets a detached session (no checkout) still carry user context.
684 let repo_uc = config
685 .as_ref()
686 .ok()
687 .and_then(|opt| opt.as_ref())
688 .and_then(|c| c.user_context.clone());
689 let user_layer = crate::config::resolve_user_context(repo_uc).resolve();
690
691 // Load the EFFECTIVE merged context (user layer, if enabled, merged with
692 // global and per-worktree) and extract fields before building the
693 // request. Using `effective` means parallel sessions in different linked
694 // worktrees each stamp their own per-worktree context without
695 // interfering with each other.
696 let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
697 let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);
698
699 let mut req = StreamEventRequest {
700 protocol_version: 1,
701 tool: Some("claude-code".to_string()),
702 event_type: stream_event_type,
703 session_id: hook_event.session_id.clone(),
704 timestamp: chrono::Utc::now(),
705 hook_event_name: Some(hook_event.hook_event_name.clone()),
706 tool_name: hook_event.tool_name.clone(),
707 tool_use_id: hook_event.tool_use_id.clone(),
708 tool_input: hook_event.tool_input.clone(),
709 tool_response: hook_event.tool_response.clone(),
710 tool_is_error,
711 event_index: None,
712 event_uuid: Some(event_uuid),
713 transcript_lines: if transcript_lines.is_empty() {
714 None
715 } else {
716 Some(transcript_lines)
717 },
718 transcript_offset: Some(start_offset),
719 model: None,
720 cwd: Some(hook_event.cwd.clone()),
721 final_stats: None,
722 flow_id: ctx_flow_id,
723 labels: ctx_labels,
724 params: ctx_params,
725 };
726
727 stamp_agent(&mut req, agent);
728
729 req.truncate_large_fields();
730
731 // 6. Resolve credentials
732 let (server_url, credential) = crate::credentials::resolve_credentials(&project_root)?;
733
734 // 7. Config (loaded above, alongside the user-level context layer
735 // resolution) no longer directly gates repo_id — a missing config is not
736 // fatal on its own, since the repo may instead resolve via the
737 // workspace-mode precedence chain (session binding / subagent worktree
738 // override) below. A malformed config is still surfaced here — that's
739 // easy to miss in hook output otherwise. Only a bound `config.toml`'s
740 // repo_id feeds the lowest-precedence tier (via `binding_from_config`
741 // below).
742 if let Err(e) = &config {
743 return Err(format!("malformed .tracevault/config.toml: {e}").into());
744 }
745
746 // Resolve the effective repo binding (workspace/detached mode). Bound
747 // mode (a pinned config.toml) still works — it's the lowest-precedence
748 // tier, wired below via `binding_from_config`, fed from the `config`
749 // already loaded above (no second read of config.toml on this hot path).
750 let session = crate::session_state::load(&hook_event.session_id);
751 let bound = config
752 .as_ref()
753 .ok()
754 .and_then(|opt| opt.as_ref())
755 .and_then(crate::resolution::binding_from_config);
756 let user_default = crate::user_default::load();
757 let binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
758 // Graceful no-op, exactly like the hook's normal success path. Do NOT
759 // error: a failing hook would block the tool.
760 let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
761 let response = HookResponse::allow();
762 println!("{}", serde_json::to_string(&response)?);
763 Ok(())
764 };
765 // Explicit local project binding (if any) overrides server-side repo
766 // deduction. Computed BEFORE the attribution gate below, reusing the
767 // already-loaded session + worktree used just above for the repo-binding
768 // resolution: a repo-less session is attributable by project alone, so the
769 // project must be known before deciding whether this event can be sent.
770 let capture_pid = capture_project(&session, Some(worktree_top.as_str()));
771
772 // Ship if EITHER a repo or a project resolved; no-op only when neither
773 // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
774 // session-state file whose repo_id could carry path separators into the
775 // pending filename — such a binding degrades to project-only inside
776 // `attribution_for` rather than dropping the event.)
777 let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
778 no_op_allow()?;
779 return Ok(());
780 };
781
782 // 8. Create ApiClient
783 let server_url = server_url.ok_or("server_url not configured")?;
784 let client = crate::api_client::ApiClient::with_credential(&server_url, credential);
785
786 // 9. Try drain pending queue and send
787 let pending_path = pending_path_for(&session_dir, &attribution);
788 let pending_events = drain_pending(&pending_path)?;
789
790 let mut send_failed = false;
791 // Spans the whole invocation (pending-flush loop + live send below) so a
792 // stale binding whose repo-scoped fallback keeps succeeding warns at most
793 // once, not once per buffered event.
794 let mut warned = false;
795
796 // Send pending events first
797 for pending_json in &pending_events {
798 if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
799 if send_stream_event(&client, &attribution, &pending_req, &mut warned)
800 .await
801 .is_err()
802 {
803 // Re-queue all remaining pending events
804 for evt in &pending_events {
805 append_pending(&pending_path, evt)?;
806 }
807 send_failed = true;
808 break;
809 }
810 }
811 }
812
813 // Send current event
814 let req_json = serde_json::to_string(&req)?;
815 // The inline (OpenCode) path CONSUMES its records from the hook event — they
816 // are not re-readable like a transcript file — so its `.stream_offset` record
817 // counter must advance whenever the event is accepted for delivery, INCLUDING
818 // when it is queued after a failure. Otherwise the next inline event reuses
819 // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
820 // queued request already carries this event's `transcript_offset`, so the
821 // records keep their indices on drain. (File-based agents must NOT advance on
822 // failure: their next read re-covers these lines cumulatively/idempotently.)
823 if send_failed {
824 append_pending(&pending_path, &req_json)?;
825 if is_inline {
826 fs::write(&offset_path, new_offset.to_string())?;
827 }
828 } else {
829 match send_stream_event(&client, &attribution, &req, &mut warned).await {
830 Ok(_) => {
831 // 10. On success update .stream_offset
832 fs::write(&offset_path, new_offset.to_string())?;
833 }
834 Err(_) => {
835 // 11. On failure append to pending.jsonl (advance the inline
836 // record counter regardless — see the note above).
837 append_pending(&pending_path, &req_json)?;
838 if is_inline {
839 fs::write(&offset_path, new_offset.to_string())?;
840 }
841 }
842 }
843 }
844
845 // 12. Always print HookResponse::allow() to stdout
846 let response = HookResponse::allow();
847 println!("{}", serde_json::to_string(&response)?);
848
849 Ok(())
850}
851
852#[cfg(test)]
853mod tests {
854 use super::*;
855 use crate::config::UserContext;
856 use crate::context::{Context, EffectiveContext};
857 use std::collections::BTreeMap;
858
859 // ── user layer resolution: disabled config → no user layer ────────────────
860
861 #[test]
862 fn disabled_user_context_resolves_to_none() {
863 // Default/disabled `user_context` (the `Toggle(false)` variant) must
864 // resolve to `None`, matching the pre-existing hook behavior of
865 // stamping without a user layer when it isn't configured.
866 assert!(UserContext::Toggle(false).resolve().is_none());
867 }
868
869 #[test]
870 fn effective_with_no_user_layer_on_empty_repo_is_empty() {
871 // With no user layer and no global/worktree context files present,
872 // `Context::effective` must yield a default (empty) `EffectiveContext`
873 // — i.e. passing `None` for `user_layer` is behavior-preserving.
874 let dir = tempfile::tempdir().unwrap();
875 let effective = Context::effective(dir.path(), None);
876 assert_eq!(effective, EffectiveContext::default());
877 }
878
879 // ── apply_context: all three fields populated ─────────────────────────────
880
881 #[test]
882 fn apply_context_stamps_all_fields() {
883 let dir = tempfile::tempdir().unwrap();
884 let mut params = BTreeMap::new();
885 params.insert("env".to_string(), "prod".to_string());
886 params.insert("region".to_string(), "eu-west-1".to_string());
887
888 let ctx = EffectiveContext {
889 flow_id: Some("flow-xyz".to_string()),
890 labels: vec!["backend".to_string(), "urgent".to_string()],
891 params,
892 };
893
894 let (flow_id, labels, params_out) = apply_context(ctx);
895
896 assert_eq!(flow_id, Some("flow-xyz".to_string()));
897 assert_eq!(
898 labels,
899 Some(vec!["backend".to_string(), "urgent".to_string()])
900 );
901 let p = params_out.expect("params should be Some");
902 assert_eq!(p.get("env").map(String::as_str), Some("prod"));
903 assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));
904
905 // Verify the stored context round-trips through save_to → load_from →
906 // merge_layers → apply_context (stored params are now `Option<String>`).
907 let written = Context {
908 flow_id: Some("flow-xyz".to_string()),
909 labels: vec!["backend".to_string(), "urgent".to_string()],
910 params: {
911 let mut m = BTreeMap::new();
912 m.insert("env".to_string(), Some("prod".to_string()));
913 m.insert("region".to_string(), Some("eu-west-1".to_string()));
914 m
915 },
916 };
917 let ctx_path = dir.path().join(".tracevault").join("context.json");
918 written.save_to(&ctx_path).unwrap();
919 let loaded = Context::load_from(&ctx_path);
920 let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
921 assert_eq!(flow_id2, Some("flow-xyz".to_string()));
922 assert!(labels2.is_some());
923 assert!(params2.is_some());
924 }
925
926 // ── apply_context: missing context file → all None ────────────────────────
927
928 #[test]
929 fn apply_context_missing_file_all_none() {
930 let dir = tempfile::tempdir().unwrap();
931 let missing_path = dir.path().join(".tracevault").join("context.json");
932 let ctx = Context::load_from(&missing_path); // no context.json → default
933 let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
934 assert!(flow_id.is_none(), "flow_id should be None");
935 assert!(labels.is_none(), "labels should be None");
936 assert!(params.is_none(), "params should be None");
937 }
938
939 // ── apply_context: empty labels vec / empty params map → None ─────────────
940
941 #[test]
942 fn apply_context_empty_collections_are_none() {
943 let ctx = EffectiveContext {
944 flow_id: None,
945 labels: vec![],
946 params: BTreeMap::new(),
947 };
948 let (flow_id, labels, params) = apply_context(ctx);
949 assert!(flow_id.is_none());
950 assert!(
951 labels.is_none(),
952 "empty labels should be None, not Some([])"
953 );
954 assert!(
955 params.is_none(),
956 "empty params should be None, not Some({{}})"
957 );
958 }
959
960 // ── apply_context: flow_id only, collections empty ────────────────────────
961
962 #[test]
963 fn apply_context_flow_id_only() {
964 let ctx = EffectiveContext {
965 flow_id: Some("my-flow".to_string()),
966 labels: vec![],
967 params: BTreeMap::new(),
968 };
969 let (flow_id, labels, params) = apply_context(ctx);
970 assert_eq!(flow_id, Some("my-flow".to_string()));
971 assert!(labels.is_none());
972 assert!(params.is_none());
973 }
974
975 // ── resolve_session_paths tests ───────────────────────────────────────────
976 //
977 // These tests verify that `resolve_session_paths` routes through the
978 // git-aware resolver so that sibling linked worktrees capture events under
979 // the PRIMARY `.tracevault/sessions/`, not the worktree directory.
980
981 use crate::test_helpers::{add_worktree, init_git_repo};
982
983 /// Primary checkout: project_root resolves to the repo root; session_dir is
984 /// under `<repo>/.tracevault/sessions/<id>/`.
985 #[test]
986 fn resolve_session_paths_primary_checkout() {
987 let tmp = tempfile::tempdir().unwrap();
988 let repo = tmp.path().join("repo");
989 std::fs::create_dir_all(&repo).unwrap();
990 init_git_repo(&repo);
991 // Create a .tracevault/ in the primary root to match a real init.
992 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
993
994 let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
995 let project_root = resolved.root;
996
997 assert_eq!(
998 project_root.canonicalize().unwrap(),
999 repo.canonicalize().unwrap(),
1000 "primary checkout: project_root must be repo root"
1001 );
1002 assert_eq!(
1003 session_dir.canonicalize().unwrap_or(session_dir.clone()),
1004 repo.join(".tracevault")
1005 .join("sessions")
1006 .join("sess-primary-123"),
1007 "primary checkout: session_dir must be <repo>/.tracevault/sessions/<id>/"
1008 );
1009 // session_dir must be INSIDE the primary repo, not elsewhere.
1010 assert!(
1011 session_dir.starts_with(&repo),
1012 "session_dir must be under the primary repo root"
1013 );
1014 }
1015
1016 /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
1017 /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
1018 /// git-aware resolver must return the PRIMARY root.
1019 #[test]
1020 fn resolve_session_paths_sibling_worktree_uses_primary_root() {
1021 let tmp = tempfile::tempdir().unwrap();
1022 let repo = tmp.path().join("repo");
1023 // Sibling worktree lives outside the primary repo directory.
1024 let wt = tmp.path().join("sibling-wt");
1025
1026 std::fs::create_dir_all(&repo).unwrap();
1027 init_git_repo(&repo);
1028 // Place .tracevault/ ONLY in the primary repo — not in the worktree.
1029 std::fs::create_dir_all(repo.join(".tracevault")).unwrap();
1030 add_worktree(&repo, &wt);
1031
1032 let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
1033 let project_root = resolved.root;
1034
1035 // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
1036 assert_eq!(
1037 project_root.canonicalize().unwrap(),
1038 repo.canonicalize().unwrap(),
1039 "sibling worktree: project_root must be primary repo root (not worktree dir)"
1040 );
1041 // session_dir must be inside the PRIMARY .tracevault/, not the worktree.
1042 assert!(
1043 session_dir.starts_with(&repo),
1044 "sibling worktree: session_dir must be under the PRIMARY repo root"
1045 );
1046 assert!(
1047 !session_dir.starts_with(&wt),
1048 "sibling worktree: session_dir must NOT be under the sibling worktree dir"
1049 );
1050 assert!(
1051 session_dir.ends_with(
1052 std::path::Path::new(".tracevault")
1053 .join("sessions")
1054 .join("sess-sibling-456")
1055 ),
1056 "session_dir must end with .tracevault/sessions/<session_id>"
1057 );
1058 }
1059
1060 /// Non-git directory with no `.tracevault/` ancestor: project_root falls
1061 /// back to `hook_cwd` itself (Fallback source); the function must not panic.
1062 #[test]
1063 fn resolve_session_paths_non_git_fallback() {
1064 let tmp = tempfile::tempdir().unwrap();
1065 // No git repo, no .tracevault/ anywhere.
1066 let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
1067 let project_root = resolved.root;
1068
1069 assert_eq!(
1070 project_root,
1071 tmp.path(),
1072 "non-git: project_root must fall back to hook_cwd"
1073 );
1074 assert_eq!(
1075 session_dir,
1076 tmp.path()
1077 .join(".tracevault")
1078 .join("sessions")
1079 .join("sess-fallback-789"),
1080 "non-git: session_dir must be relative to the fallback root"
1081 );
1082 }
1083
1084 /// The origin marker written by run_stream contains the worktree toplevel.
1085 /// This test exercises the same `paths::worktree_toplevel` helper the hook
1086 /// uses (can't call run_stream end-to-end without a real server) so the
1087 /// marker content is computed and canonicalized exactly as in production.
1088 #[test]
1089 fn origin_marker_written_in_session_dir() {
1090 let tmp = tempfile::tempdir().unwrap();
1091 let repo = tmp.path().join("repo");
1092 std::fs::create_dir_all(&repo).unwrap();
1093 init_git_repo(&repo);
1094
1095 let session_dir = repo
1096 .join(".tracevault")
1097 .join("sessions")
1098 .join("test-sess-001");
1099 std::fs::create_dir_all(&session_dir).unwrap();
1100
1101 let hook_cwd = &repo;
1102 let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
1103 let _ = std::fs::write(session_dir.join("origin"), &worktree_top);
1104
1105 let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
1106 let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
1107 assert_eq!(
1108 origin_content.trim(),
1109 expected.as_str(),
1110 "origin marker must contain the canonicalized worktree toplevel"
1111 );
1112 }
1113
1114 // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──
1115
1116 use crate::session_state::{RepoBinding, SessionState};
1117
1118 fn binding(id: &str) -> RepoBinding {
1119 RepoBinding {
1120 repo_id: id.into(),
1121 git_url: None,
1122 remote_id: None,
1123 codebase_name: None,
1124 updated_at: "t".into(),
1125 }
1126 }
1127
1128 /// Workspace mode: no pinned config, but the session is bound (e.g. via
1129 /// `tracevault repo switch`) — the stream event attributes to that repo.
1130 #[test]
1131 fn resolve_stream_binding_uses_session_active_when_unbound() {
1132 let session = SessionState {
1133 active: Some(binding("session-repo")),
1134 subagents: HashMap::new(),
1135 ..Default::default()
1136 };
1137 let got = resolve_stream_binding(&session, "/wt/top", None, None);
1138 assert_eq!(got.unwrap().repo_id, "session-repo");
1139 }
1140
1141 /// Bound-mode regression: an empty session (no `repo switch` ever run)
1142 /// with a bound config.toml still resolves via the config.
1143 #[test]
1144 fn resolve_stream_binding_falls_back_to_bound_config() {
1145 let session = SessionState::default();
1146 let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
1147 assert_eq!(got.unwrap().repo_id, "bound-repo");
1148 }
1149
1150 /// No session binding and no bound config: nothing resolves, which is
1151 /// exactly what should trigger `run_stream`'s graceful no-op.
1152 #[test]
1153 fn resolve_stream_binding_none_when_nothing_resolves() {
1154 let session = SessionState::default();
1155 let got = resolve_stream_binding(&session, "/wt/top", None, None);
1156 assert!(got.is_none());
1157 }
1158
1159 /// Subagent override precedence: a per-worktree override for the current
1160 /// worktree wins over the session's `active` binding.
1161 #[test]
1162 fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
1163 let session = SessionState {
1164 active: Some(binding("session-repo")),
1165 subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
1166 ..Default::default()
1167 };
1168 let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
1169 assert_eq!(got.unwrap().repo_id, "subagent-repo");
1170 }
1171
1172 /// Workspace mode: no bound config, but a user-level default is set (e.g.
1173 /// via `tracevault repo switch --user`) — the stream event attributes to
1174 /// that repo when nothing more specific resolves.
1175 #[test]
1176 fn resolve_stream_binding_falls_back_to_user_default() {
1177 let session = SessionState::default();
1178 let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
1179 assert_eq!(got.unwrap().repo_id, "userdef");
1180 }
1181
1182 /// The user-level default is the LOWEST-precedence tier: a bound config
1183 /// still wins over it.
1184 #[test]
1185 fn resolve_stream_binding_prefers_bound_over_user_default() {
1186 let session = SessionState::default();
1187 let got = resolve_stream_binding(
1188 &session,
1189 "/wt/x",
1190 Some(binding("bound")),
1191 Some(binding("userdef")),
1192 );
1193 assert_eq!(got.unwrap().repo_id, "bound");
1194 }
1195
1196 // ── attribution_for: repo-or-project gate ────────────────────────────────
1197
1198 fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
1199 crate::session_state::RepoBinding {
1200 repo_id: repo_id.into(),
1201 git_url: None,
1202 remote_id: None,
1203 codebase_name: None,
1204 updated_at: String::new(),
1205 }
1206 }
1207
1208 /// The regression this whole change exists for: a session with a project
1209 /// binding and NO repo binding must still ship, repo-less, instead of
1210 /// being dropped by the hook.
1211 #[test]
1212 fn attribution_falls_back_to_project_when_no_repo_binds() {
1213 let pid = uuid::Uuid::new_v4();
1214 assert_eq!(
1215 attribution_for(None, Some(pid)),
1216 Some(Attribution::ProjectOnly { project_id: pid })
1217 );
1218 }
1219
1220 /// Neither binding resolves — the only case that may still no-op.
1221 #[test]
1222 fn attribution_is_none_when_neither_repo_nor_project_binds() {
1223 assert_eq!(attribution_for(None, None), None);
1224 }
1225
1226 /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
1227 /// server left to deduce the project.
1228 #[test]
1229 fn attribution_uses_repo_with_no_project_overlay() {
1230 let repo = uuid::Uuid::new_v4().to_string();
1231 let b = binding_with(&repo);
1232 assert_eq!(
1233 attribution_for(Some(&b), None),
1234 Some(Attribution::Repo {
1235 repo_id: repo,
1236 project: None
1237 })
1238 );
1239 }
1240
1241 /// Both bound: the project overlays the repo (project-scoped ingest
1242 /// carrying repo_id), unchanged from before.
1243 #[test]
1244 fn attribution_overlays_project_on_repo() {
1245 let repo = uuid::Uuid::new_v4().to_string();
1246 let pid = uuid::Uuid::new_v4();
1247 let b = binding_with(&repo);
1248 assert_eq!(
1249 attribution_for(Some(&b), Some(pid)),
1250 Some(Attribution::Repo {
1251 repo_id: repo,
1252 project: Some(pid)
1253 })
1254 );
1255 }
1256
1257 /// A corrupted repo_id costs the repo attribution, not the trace: it
1258 /// degrades to project-only rather than dropping the event.
1259 #[test]
1260 fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
1261 let pid = uuid::Uuid::new_v4();
1262 let b = binding_with("../../escape");
1263 assert_eq!(
1264 attribution_for(Some(&b), Some(pid)),
1265 Some(Attribution::ProjectOnly { project_id: pid })
1266 );
1267 }
1268
1269 /// ...but with no project to fall back to, a corrupt repo_id still drops,
1270 /// so it can never reach the pending filename.
1271 #[test]
1272 fn attribution_drops_a_corrupt_repo_id_with_no_project() {
1273 let b = binding_with("../../escape");
1274 assert_eq!(attribution_for(Some(&b), None), None);
1275 }
1276
1277 // ── pending queue filenames ──────────────────────────────────────────────
1278
1279 /// The repo filename is unchanged, so queues buffered by earlier releases
1280 /// are still found and drained after this upgrade.
1281 #[test]
1282 fn pending_file_name_for_a_repo_is_unchanged() {
1283 let repo = uuid::Uuid::new_v4().to_string();
1284 assert_eq!(
1285 Attribution::Repo {
1286 repo_id: repo.clone(),
1287 project: Some(uuid::Uuid::new_v4())
1288 }
1289 .pending_file_name(),
1290 format!("pending-{repo}.jsonl")
1291 );
1292 }
1293
1294 /// Repo-less queues carry the `project-` infix, which an older CLI reads
1295 /// as a non-UUID repo id and skips (see the doc comment).
1296 #[test]
1297 fn pending_file_name_for_a_project_is_distinct() {
1298 let pid = uuid::Uuid::new_v4();
1299 assert_eq!(
1300 Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
1301 format!("pending-project-{pid}.jsonl")
1302 );
1303 }
1304
1305 // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────
1306
1307 #[test]
1308 fn binding_repo_id_is_valid_accepts_real_uuid() {
1309 assert!(binding_repo_id_is_valid(
1310 "550e8400-e29b-41d4-a716-446655440000"
1311 ));
1312 }
1313
1314 #[test]
1315 fn binding_repo_id_is_valid_rejects_path_traversal() {
1316 assert!(!binding_repo_id_is_valid("../evil"));
1317 }
1318
1319 #[test]
1320 fn binding_repo_id_is_valid_rejects_empty() {
1321 assert!(!binding_repo_id_is_valid(""));
1322 }
1323
1324 #[test]
1325 fn binding_repo_id_is_valid_rejects_non_uuid() {
1326 assert!(!binding_repo_id_is_valid("not-a-uuid"));
1327 }
1328
1329 // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────
1330
1331 #[test]
1332 fn stamp_agent_sets_tool_and_version() {
1333 use crate::agent::Agent;
1334 let mut req = StreamEventRequest {
1335 protocol_version: 1,
1336 tool: Some("claude-code".to_string()),
1337 event_type: StreamEventType::ToolUse,
1338 session_id: "s".into(),
1339 timestamp: chrono::Utc::now(),
1340 hook_event_name: None,
1341 tool_name: None,
1342 tool_use_id: None,
1343 tool_input: None,
1344 tool_response: None,
1345 tool_is_error: None,
1346 event_index: None,
1347 event_uuid: None,
1348 transcript_lines: None,
1349 transcript_offset: None,
1350 model: None,
1351 cwd: None,
1352 final_stats: None,
1353 flow_id: None,
1354 labels: None,
1355 params: None,
1356 };
1357 stamp_agent(&mut req, Agent::Codex);
1358 assert_eq!(req.tool.as_deref(), Some("codex"));
1359 assert_eq!(req.protocol_version, 2);
1360
1361 stamp_agent(&mut req, Agent::ClaudeCode);
1362 assert_eq!(req.tool.as_deref(), Some("claude-code"));
1363 assert_eq!(req.protocol_version, 1);
1364 }
1365
1366 // ── pending_path_for: per-target offline queue ───────────────────────────
1367
1368 fn repo_attr(repo_id: &str) -> Attribution {
1369 Attribution::Repo {
1370 repo_id: repo_id.into(),
1371 project: None,
1372 }
1373 }
1374
1375 #[test]
1376 fn pending_path_is_repo_scoped() {
1377 let dir = std::path::Path::new("/tmp/sess");
1378 assert_eq!(
1379 pending_path_for(dir, &repo_attr("repo-a")),
1380 std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
1381 );
1382 assert_ne!(
1383 pending_path_for(dir, &repo_attr("repo-a")),
1384 pending_path_for(dir, &repo_attr("repo-b")),
1385 );
1386 }
1387
1388 /// A repo-less session must not share a queue file with any repo, so its
1389 /// buffered events can never be flushed to a repo endpoint.
1390 #[test]
1391 fn pending_path_for_a_project_never_collides_with_a_repo() {
1392 let dir = std::path::Path::new("/tmp/sess");
1393 let pid = uuid::Uuid::from_u128(9);
1394 assert_eq!(
1395 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1396 std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
1397 );
1398 assert_ne!(
1399 pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
1400 pending_path_for(dir, &repo_attr(&pid.to_string())),
1401 );
1402 }
1403
1404 // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────
1405
1406 #[test]
1407 fn read_new_transcript_lines_empty_path_is_noop() {
1408 // Codex's nullable transcript_path deserializes to "" (see HookEvent).
1409 // An empty path must yield no lines and offset 0, never an error from
1410 // handing `Path::new("")` to exists()/File::open.
1411 let dir = tempfile::tempdir().unwrap();
1412 let offset_path = dir.path().join(".stream_offset");
1413 let (lines, start_offset, end_offset) =
1414 read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
1415 assert!(
1416 lines.is_empty(),
1417 "empty path must yield no transcript lines"
1418 );
1419 assert_eq!(start_offset, 0);
1420 assert_eq!(end_offset, 0);
1421 }
1422
1423 // ── read_new_transcript_lines: start_offset is stable across a persisted
1424 // end_offset, and equals the previous read's end_offset ─────────────────
1425
1426 #[test]
1427 fn read_new_transcript_lines_second_read_starts_at_previous_end() {
1428 let dir = tempfile::tempdir().unwrap();
1429 let transcript_path = dir.path().join("transcript.jsonl");
1430 let offset_path = dir.path().join(".stream_offset");
1431
1432 fs::write(
1433 &transcript_path,
1434 "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
1435 )
1436 .unwrap();
1437
1438 let (lines, start_offset, end_offset) =
1439 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1440 assert_eq!(lines.len(), 2);
1441 assert_eq!(start_offset, 0, "first read starts at byte 0");
1442 assert!(end_offset > 0);
1443
1444 fs::write(&offset_path, end_offset.to_string()).unwrap();
1445
1446 let mut f = OpenOptions::new()
1447 .append(true)
1448 .open(&transcript_path)
1449 .unwrap();
1450 writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
1451 drop(f);
1452
1453 let (lines2, start_offset2, end_offset2) =
1454 read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
1455 assert_eq!(lines2.len(), 1);
1456 assert_eq!(
1457 start_offset2, end_offset,
1458 "second read's start_offset must equal the first read's persisted end_offset"
1459 );
1460 assert!(end_offset2 > start_offset2);
1461 }
1462
1463 // ── capture_project: local-only project resolver ──────────────────────────
1464
1465 #[test]
1466 fn capture_project_precedence_local_only() {
1467 use crate::session_state::{ProjectBinding, SessionState};
1468 let pb = |id: &str| ProjectBinding {
1469 project_id: id.into(),
1470 project_name: "n".into(),
1471 updated_at: "".into(),
1472 };
1473 let u = uuid::Uuid::from_u128;
1474 // session active only
1475 let s = SessionState {
1476 active_project: Some(pb(&u(2).to_string())),
1477 ..Default::default()
1478 };
1479 assert_eq!(capture_project(&s, Some("/wt")), Some(u(2)));
1480 // subagent worktree beats session
1481 let mut s = s;
1482 s.subagent_projects
1483 .insert("/wt".into(), pb(&u(1).to_string()));
1484 assert_eq!(capture_project(&s, Some("/wt")), Some(u(1)));
1485 // no worktree match -> session active
1486 assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
1487 // empty session -> None (user-default file is not present in this unit test env)
1488 assert_eq!(capture_project(&SessionState::default(), None), None);
1489 // malformed stored id -> None (defensive)
1490 let bad = SessionState {
1491 active_project: Some(pb("not-a-uuid")),
1492 ..Default::default()
1493 };
1494 assert_eq!(capture_project(&bad, None), None);
1495 }
1496
1497 // ── send_stream_event: endpoint routing based on capture_pid ──────────────
1498
1499 use std::io::BufReader;
1500 use std::net::TcpListener;
1501 use std::sync::mpsc;
1502 use std::thread;
1503 use std::time::{Duration, Instant};
1504
1505 /// How long an accept loop waits for a connection that never arrives
1506 /// (e.g. a regression that stops the client from making an expected
1507 /// request) before giving up, so the server thread exits cleanly
1508 /// instead of blocking in `accept()` forever.
1509 const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);
1510
1511 /// Poll a non-blocking `listener` for a connection until one arrives or
1512 /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
1513 /// `WouldBlock` accept error) so callers can stop cleanly rather than
1514 /// block forever.
1515 fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
1516 let deadline = Instant::now() + ACCEPT_DEADLINE;
1517 loop {
1518 match listener.accept() {
1519 Ok((stream, _)) => {
1520 // The accepted stream's blocking mode isn't guaranteed to
1521 // be inherited from the (non-blocking) listener across
1522 // platforms — make it explicitly blocking so the
1523 // subsequent read/write calls behave as before.
1524 let _ = stream.set_nonblocking(false);
1525 return Some(stream);
1526 }
1527 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1528 if Instant::now() >= deadline {
1529 return None;
1530 }
1531 thread::sleep(Duration::from_millis(20));
1532 }
1533 Err(_) => return None,
1534 }
1535 }
1536 }
1537
1538 /// How long a test waits for the captured request before failing (rather
1539 /// than hanging forever if the client never connects). Mirrors the
1540 /// harness in `tests/stream_event_project_test.rs`.
1541 const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);
1542
1543 /// Spawn a one-shot server that returns `response` (a full HTTP response)
1544 /// to the first request. Captures the HTTP request line (method + path +
1545 /// query) over the returned channel before writing the response. Mirrors
1546 /// the harness in `tests/stream_event_project_test.rs` /
1547 /// `tests/resolve_remote_test.rs`.
1548 fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
1549 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1550 listener.set_nonblocking(true).unwrap();
1551 let addr = listener.local_addr().unwrap();
1552 let (tx, rx) = mpsc::channel();
1553 thread::spawn(move || {
1554 if let Some(stream) = accept_with_deadline(&listener) {
1555 let mut reader = BufReader::new(stream);
1556 let mut request_line = String::new();
1557 let _ = reader.read_line(&mut request_line);
1558 let _ = tx.send(request_line);
1559 let mut stream = reader.into_inner();
1560 let _ = stream.write_all(response.as_bytes());
1561 let _ = stream.flush();
1562 }
1563 });
1564 (format!("http://{addr}"), rx)
1565 }
1566
1567 fn ok_stream_response() -> String {
1568 let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
1569 session_db_id: uuid::Uuid::nil(),
1570 event_db_id: Some(uuid::Uuid::nil()),
1571 status: "accepted".to_string(),
1572 })
1573 .unwrap();
1574 format!(
1575 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1576 body.len(),
1577 body
1578 )
1579 }
1580
1581 fn sample_stream_event_request() -> StreamEventRequest {
1582 StreamEventRequest {
1583 protocol_version: 2,
1584 tool: Some("claude-code".to_string()),
1585 event_type: StreamEventType::ToolUse,
1586 session_id: "sess-1".into(),
1587 timestamp: chrono::Utc::now(),
1588 hook_event_name: Some("PostToolUse".into()),
1589 tool_name: None,
1590 tool_use_id: None,
1591 tool_input: None,
1592 tool_response: None,
1593 tool_is_error: None,
1594 event_index: None,
1595 event_uuid: None,
1596 transcript_lines: None,
1597 transcript_offset: None,
1598 model: None,
1599 cwd: None,
1600 final_stats: None,
1601 flow_id: None,
1602 labels: None,
1603 params: None,
1604 }
1605 }
1606
1607 /// With a `SessionState` whose `active_project` is set, `capture_project`
1608 /// resolves a `capture_pid`, and `send_stream_event` must route to the
1609 /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
1610 /// than the repo-scoped one.
1611 #[tokio::test]
1612 async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
1613 use crate::session_state::{ProjectBinding, SessionState};
1614
1615 // Isolate from any ambient user-level project default so this test's
1616 // `capture_project` call depends only on the SessionState below —
1617 // mirrors the isolation pattern in `commands::project`'s tests.
1618 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1619 let tmp = tempfile::tempdir().unwrap();
1620 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1621 _guard.set("XDG_CONFIG_HOME", tmp.path());
1622
1623 let pid = uuid::Uuid::from_u128(99);
1624 let session = SessionState {
1625 active_project: Some(ProjectBinding {
1626 project_id: pid.to_string(),
1627 project_name: "proj".into(),
1628 updated_at: "".into(),
1629 }),
1630 ..Default::default()
1631 };
1632 let capture_pid = capture_project(&session, None);
1633 assert_eq!(capture_pid, Some(pid));
1634
1635 let resp = ok_stream_response();
1636 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1637 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1638 let req = sample_stream_event_request();
1639
1640 let mut warned = false;
1641 let got = send_stream_event(
1642 &client,
1643 &Attribution::Repo {
1644 repo_id: "11111111-1111-1111-1111-111111111111".into(),
1645 project: capture_pid,
1646 },
1647 &req,
1648 &mut warned,
1649 )
1650 .await
1651 .expect("send_stream_event must succeed");
1652 assert_eq!(
1653 got.expect("a successful send returns a response").status,
1654 "accepted"
1655 );
1656
1657 let line = rx
1658 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1659 .expect("no request captured");
1660 assert!(
1661 line.starts_with(&format!(
1662 "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
1663 )),
1664 "an active project binding must route to the project-scoped endpoint, got: {line}"
1665 );
1666 }
1667
1668 /// With an empty binding (default `SessionState`, no worktree override)
1669 /// and no user-level default present in the test env, `capture_project`
1670 /// resolves `None` and `send_stream_event` must fall back to the
1671 /// repo-scoped endpoint.
1672 #[tokio::test]
1673 async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
1674 use crate::session_state::SessionState;
1675
1676 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1677 let tmp = tempfile::tempdir().unwrap();
1678 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1679 // No user_project.toml under this isolated config dir, so there is no
1680 // ambient user-level default to leak in.
1681 _guard.set("XDG_CONFIG_HOME", tmp.path());
1682
1683 let capture_pid = capture_project(&SessionState::default(), None);
1684 assert_eq!(capture_pid, None);
1685
1686 let resp = ok_stream_response();
1687 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1688 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1689 let req = sample_stream_event_request();
1690
1691 let mut warned = false;
1692 let got = send_stream_event(
1693 &client,
1694 &Attribution::Repo {
1695 repo_id: "11111111-1111-1111-1111-111111111111".into(),
1696 project: capture_pid,
1697 },
1698 &req,
1699 &mut warned,
1700 )
1701 .await
1702 .expect("send_stream_event must succeed");
1703 assert_eq!(
1704 got.expect("a successful send returns a response").status,
1705 "accepted"
1706 );
1707
1708 let line = rx
1709 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1710 .expect("no request captured");
1711 assert!(
1712 line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
1713 "no binding must fall back to the repo-scoped endpoint, got: {line}"
1714 );
1715 }
1716
1717 // ── I1/I2: deterministic-client-error fallback + transient no-fallback ───
1718
1719 /// Spawn a server that replies to up to `responses.len()` sequential
1720 /// connections with the given full HTTP responses, in order, capturing
1721 /// each request line over the channel. The listening socket itself is
1722 /// dropped (closing it) once all responses have been served, so any
1723 /// further connection attempt fails fast (connection refused) rather than
1724 /// hanging for the client's request timeout — this lets a test assert
1725 /// "no further request was sent" cheaply.
1726 fn spawn_n_capturing_requests(
1727 responses: Vec<&'static str>,
1728 ) -> (String, mpsc::Receiver<String>) {
1729 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1730 listener.set_nonblocking(true).unwrap();
1731 let addr = listener.local_addr().unwrap();
1732 let (tx, rx) = mpsc::channel();
1733 thread::spawn(move || {
1734 for response in responses {
1735 // If a regression stops the client from making this request
1736 // (e.g. the expected Nth call never happens), don't block
1737 // forever in `accept()` — give up after `ACCEPT_DEADLINE`
1738 // and let the thread end so the test process can't hang.
1739 let Some(stream) = accept_with_deadline(&listener) else {
1740 break;
1741 };
1742 let mut reader = BufReader::new(stream);
1743 let mut request_line = String::new();
1744 let _ = reader.read_line(&mut request_line);
1745 let _ = tx.send(request_line);
1746 let mut stream = reader.into_inner();
1747 let _ = stream.write_all(response.as_bytes());
1748 let _ = stream.flush();
1749 }
1750 // `listener` (and `tx`) drop here, closing the socket and the
1751 // channel — a stray extra request gets ECONNREFUSED immediately
1752 // instead of hanging, and a stray extra `rx.recv` returns
1753 // Disconnected immediately instead of blocking.
1754 });
1755 (format!("http://{addr}"), rx)
1756 }
1757
1758 /// I1: a deterministic 400 ("is not a member of project ...") from the
1759 /// project-scoped endpoint must fall back to the repo-scoped endpoint —
1760 /// which then succeeds — rather than being buffered/retried forever. Both
1761 /// endpoints must be hit, project first, then repo.
1762 #[tokio::test]
1763 async fn send_stream_event_falls_back_to_repo_scoped_on_deterministic_400() {
1764 let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
1765 let resp_400 = format!(
1766 "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1767 body_400.len(),
1768 body_400
1769 );
1770 let resp_200 = ok_stream_response();
1771
1772 let (base, rx) = spawn_n_capturing_requests(vec![
1773 Box::leak(resp_400.into_boxed_str()),
1774 Box::leak(resp_200.into_boxed_str()),
1775 ]);
1776 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1777 let req = sample_stream_event_request();
1778 let pid = uuid::Uuid::from_u128(42);
1779
1780 let mut warned = false;
1781 let got = send_stream_event(
1782 &client,
1783 &Attribution::Repo {
1784 repo_id: "11111111-1111-1111-1111-111111111111".into(),
1785 project: Some(pid),
1786 },
1787 &req,
1788 &mut warned,
1789 )
1790 .await
1791 .expect("a deterministic 400 must fall back to repo-scoped and succeed");
1792 assert_eq!(
1793 got.expect("a successful send returns a response").status,
1794 "accepted"
1795 );
1796
1797 let first = rx
1798 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1799 .expect("no first request captured");
1800 assert!(
1801 first.contains(&format!("/projects/{pid}/stream")),
1802 "first request must hit the project-scoped endpoint, got: {first}"
1803 );
1804
1805 let second = rx
1806 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1807 .expect("no second (fallback) request captured");
1808 assert!(
1809 second.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
1810 "second request must fall back to the repo-scoped endpoint, got: {second}"
1811 );
1812 }
1813
1814 /// The repo-less send: a `ProjectOnly` attribution must hit the bare
1815 /// project endpoint with NO `repo_id` query pair. This is the wire shape
1816 /// the server documents as "repo-less (0-repo) projects are supported".
1817 #[tokio::test]
1818 async fn send_stream_event_project_only_omits_repo_id() {
1819 let resp = ok_stream_response();
1820 let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
1821 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1822 let req = sample_stream_event_request();
1823 let pid = uuid::Uuid::from_u128(11);
1824
1825 let mut warned = false;
1826 let got = send_stream_event(
1827 &client,
1828 &Attribution::ProjectOnly { project_id: pid },
1829 &req,
1830 &mut warned,
1831 )
1832 .await
1833 .expect("a repo-less project send must succeed");
1834 assert_eq!(
1835 got.expect("a successful send returns a response").status,
1836 "accepted"
1837 );
1838
1839 let line = rx
1840 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1841 .expect("no request captured");
1842 assert!(
1843 line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
1844 "expected a bare project path with no query string, got: {line}"
1845 );
1846 assert!(
1847 !warned,
1848 "a repo-less send has no fallback and must not warn about one"
1849 );
1850 }
1851
1852 /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
1853 /// the queue is keyed by the very project id the server says does not
1854 /// resolve, so a corrected binding writes to a different file and these
1855 /// events would never be retried — they would just accumulate, one per
1856 /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
1857 /// trigger a second, impossible request.
1858 #[tokio::test]
1859 async fn send_stream_event_project_only_drops_on_scoping_4xx() {
1860 let body = "no such project";
1861 let resp_404 = format!(
1862 "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1863 body.len(),
1864 body
1865 );
1866 // TWO responses are staged although only one request is expected. With
1867 // a single response the helper drops its sender the moment the list is
1868 // exhausted, so the "no second request" assertion below would pass on
1869 // `Disconnected` whether or not a second request happened — a vacuous
1870 // check. Staging a spare keeps the server accepting, so a stray
1871 // request really is captured and really fails the test.
1872 let (base, rx) = spawn_n_capturing_requests(vec![
1873 Box::leak(resp_404.clone().into_boxed_str()),
1874 Box::leak(resp_404.into_boxed_str()),
1875 ]);
1876 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1877 let req = sample_stream_event_request();
1878 let pid = uuid::Uuid::from_u128(12);
1879
1880 let mut warned = false;
1881 let got = send_stream_event(
1882 &client,
1883 &Attribution::ProjectOnly { project_id: pid },
1884 &req,
1885 &mut warned,
1886 )
1887 .await
1888 .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
1889 assert!(
1890 got.is_none(),
1891 "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
1892 );
1893 assert!(
1894 warned,
1895 "dropping data silently is the failure mode to avoid"
1896 );
1897
1898 let first = rx
1899 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1900 .expect("no request captured");
1901 assert!(
1902 first.contains(&format!("/projects/{pid}/stream")),
1903 "must hit the project-scoped endpoint, got: {first}"
1904 );
1905 assert!(
1906 rx.recv_timeout(Duration::from_millis(500)).is_err(),
1907 "a repo-less send must make exactly one request — no fallback exists"
1908 );
1909 }
1910
1911 /// A 403 is NOT dropped. It can mean the account lacks the realm role,
1912 /// which an administrator can grant — after which the buffered events do
1913 /// deliver. It must propagate so the caller queues them.
1914 #[tokio::test]
1915 async fn send_stream_event_project_only_buffers_on_403() {
1916 let body = "forbidden";
1917 let resp_403 = format!(
1918 "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1919 body.len(),
1920 body
1921 );
1922 let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
1923 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1924 let req = sample_stream_event_request();
1925
1926 let mut warned = false;
1927 let err = send_stream_event(
1928 &client,
1929 &Attribution::ProjectOnly {
1930 project_id: uuid::Uuid::from_u128(13),
1931 },
1932 &req,
1933 &mut warned,
1934 )
1935 .await
1936 .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
1937 assert!(
1938 err.to_string().contains("403"),
1939 "propagated error must reflect the status, got: {err}"
1940 );
1941 }
1942
1943 /// I2: a transient 503 from the project-scoped endpoint must propagate as
1944 /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
1945 /// existing buffer/retry logic in `run_stream` still handles it. Only one
1946 /// request (to the project endpoint) may be observed.
1947 #[tokio::test]
1948 async fn send_stream_event_does_not_fall_back_on_transient_503() {
1949 let body_503 = "internal error";
1950 let resp_503 = format!(
1951 "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1952 body_503.len(),
1953 body_503
1954 );
1955 let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
1956 let client = crate::api_client::ApiClient::new(&base, Some("tok"));
1957 let req = sample_stream_event_request();
1958 let pid = uuid::Uuid::from_u128(7);
1959
1960 let mut warned = false;
1961 let err = send_stream_event(
1962 &client,
1963 &Attribution::Repo {
1964 repo_id: "11111111-1111-1111-1111-111111111111".into(),
1965 project: Some(pid),
1966 },
1967 &req,
1968 &mut warned,
1969 )
1970 .await
1971 .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
1972 assert!(
1973 err.to_string().contains("503"),
1974 "propagated error must reflect the transient status, got: {err}"
1975 );
1976 assert!(
1977 deterministic_client_error_kind(err.as_ref()).is_none(),
1978 "a 503 must not be classified as a deterministic client error"
1979 );
1980
1981 let first = rx
1982 .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
1983 .expect("no request captured");
1984 assert!(
1985 first.contains(&format!("/projects/{pid}/stream")),
1986 "must hit the project-scoped endpoint, got: {first}"
1987 );
1988
1989 // The mock server only serves ONE response and then drops its
1990 // listener/sender — a stray fallback request would either fail the
1991 // `expect_err` above (if it somehow succeeded) or, if it also failed,
1992 // would still mean a second request was attempted. Confirming the
1993 // channel is immediately disconnected (rather than blocking) proves
1994 // no second request was ever sent.
1995 assert!(
1996 rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
1997 "no second (fallback) request should have been sent for a transient error"
1998 );
1999 }
2000
2001 /// A 403 must be classified apart from the binding/scoping statuses: since
2002 /// Keycloak it has a second, now more common cause (no `tracing` realm role
2003 /// at all) whose advice is completely different.
2004 #[test]
2005 fn a_403_is_classified_apart_from_the_scoping_statuses() {
2006 let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
2007 assert_eq!(
2008 deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
2009 Some(ClientErrorKind::Forbidden)
2010 );
2011 for scoping in [
2012 "Stream failed (400 Bad Request): {}",
2013 "Stream failed (404 Not Found): {}",
2014 "Stream failed (409 Conflict): {}",
2015 ] {
2016 assert_eq!(
2017 deterministic_client_error_kind(err(scoping).as_ref()),
2018 Some(ClientErrorKind::Scoping),
2019 "{scoping}"
2020 );
2021 }
2022 // Unchanged: 401 and transient failures are not deterministic client
2023 // errors and must keep propagating to buffer/retry.
2024 for transient in [
2025 "Stream failed (401 Unauthorized): {}",
2026 "Stream failed (503 Service Unavailable): {}",
2027 "error sending request for url (http://x/stream)",
2028 ] {
2029 assert_eq!(
2030 deterministic_client_error_kind(err(transient).as_ref()),
2031 None,
2032 "{transient}"
2033 );
2034 }
2035 }
2036
2037 /// The 403 warning must not tell a user whose account has no `tracing` role
2038 /// to switch projects, which cannot possibly help. It names both causes; the
2039 /// scoping statuses keep the precise project wording.
2040 #[test]
2041 fn the_403_warning_names_the_realm_role_as_well_as_the_project() {
2042 let pid = uuid::Uuid::from_u128(7);
2043
2044 let forbidden = fallback_warning(pid, &ClientErrorKind::Forbidden);
2045 assert!(
2046 forbidden.contains("`tracing` Keycloak realm role"),
2047 "must offer the missing-role explanation: {forbidden}"
2048 );
2049 assert!(
2050 forbidden.contains("project switch"),
2051 "must still offer the project explanation: {forbidden}"
2052 );
2053 assert!(
2054 forbidden.contains("Either"),
2055 "must present them as alternatives, not assert one: {forbidden}"
2056 );
2057 assert!(forbidden.contains(&pid.to_string()));
2058
2059 // A 400/404/409 genuinely IS a binding problem, so that wording stays
2060 // unhedged — hedging everything would dilute the useful case.
2061 let scoping = fallback_warning(pid, &ClientErrorKind::Scoping);
2062 assert!(scoping.contains("project switch"), "{scoping}");
2063 assert!(
2064 !scoping.contains("realm role"),
2065 "the scoping case must not mention the realm role: {scoping}"
2066 );
2067 }
2068}