返回 CodeWhale
lifecycle_outbox.rs
根目录 / crates / hooks / src / lifecycle_outbox.rs
1 //! Lifecycle event outbox: a local JSONL log of session/turn/subagent
2 //! lifecycle events plus an optional webhook fan-out.
3 //!
4 //! This is the machine-readable sibling of the TUI shell-hook system. Hooks
5 //! fire shell commands per event and are TUI-only; the outbox appends one
6 //! JSON line per event to a config-gated file and needs no per-event
7 //! configuration. It is additive and opt-in: with no path configured,
8 //! [`LifecycleOutbox::emit`] is a no-op.
9 //!
10 //! # Line schema
11 //!
12 //! Every line is a `codewhale_app_server_protocol::runtime::RuntimeEventEnvelope`:
13 //!
14 //! ```json
15 //! {"schema_version": 1, "seq": 3, "event": "turn_start", "kind": "turn.started",
16 //! "thread_id": "…", "turn_id": "…", "item_id": null, "timestamp": "…",
17 //! "created_at": "…", "payload": {…}}
18 //! ```
19 //!
20 //! - `seq` is monotonic per outbox file. On the first write the writer
21 //! recovers the `seq` of the file's last complete line (bounded tail scan,
22 // so an outbox that grows unbounded is never re-read in full) and continues
23 //! from `last + 1`.
24 //! - `event` is the snake-case lifecycle name (`turn_start`, `turn_end`, …);
25 //! `kind` is the dotted kind (`turn.started`, `turn.failed`, …).
26 //! - Payloads are constructed by the emit sites from bounded, pre-redacted
27 //! fields only — never raw tool arguments, environment, or full transcript
28 //! text. [`bounded_text`] enforces the same ceilings as the desktop
29 //! notification payloads: headline ≤ 80, detail ≤ 120, preview ≤ 200
30 //! characters.
31 //!
32 //! # Delivery model
33 //!
34 //! [`LifecycleOutbox::emit`] never blocks the caller: it enqueues the event
35 //! on an internal channel and a single writer task appends lines in order.
36 //! If no tokio runtime is available the event is dropped with a warning.
37 //! Webhook POSTs (`{"at": …, "event": …}`) are attempted after the local
38 //! append; failures are logged and dropped, never retried into the agent
39 //! loop. Process owners call [`LifecycleOutbox::flush`] before runtime teardown
40 //! to give queued terminal events a bounded opportunity to finish delivery.
41
42 use std::collections::BTreeMap;
43 use std::io::{Read, Seek, SeekFrom, Write};
44 use std::path::{Path, PathBuf};
45 use std::sync::atomic::{AtomicBool, Ordering};
46 use std::sync::{Arc, Mutex};
47 use std::time::Duration;
48
49 use anyhow::{Context, Result};
50 use chrono::Utc;
51 use codewhale_app_server_protocol::runtime::{
52 RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION, RuntimeEventEnvelope,
53 };
54 use serde_json::{Value, json};
55 use tokio::sync::mpsc::error::TrySendError;
56 use tokio::sync::mpsc::{Receiver, Sender};
57 use tokio::sync::oneshot;
58
59 use crate::WebhookHookSink;
60
61 const OUTBOX_NONCE_FIELD: &str = "outbox_nonce";
62
63 /// Text-length ceilings for outbox payload fields. Mirrors the desktop
64 /// notification payload limits so the outbox never carries more than the
65 /// lock-screen-capable surface already does.
66 pub const OUTBOX_HEADLINE_MAX_CHARS: usize = 80;
67 pub const OUTBOX_DETAIL_MAX_CHARS: usize = 120;
68 pub const OUTBOX_PREVIEW_MAX_CHARS: usize = 200;
69
70 /// Suffix appended when [`bounded_text`] truncates a field.
71 pub const OUTBOX_TRUNCATION_MARKER: &str = "…";
72
73 /// How far back from EOF the seq-recovery scan reads. Outbox lines are
74 /// bounded (payload ceilings above plus envelope overhead), so a line can
75 /// never approach this window and the last complete line is always inside it.
76 const SEQ_RECOVERY_TAIL_BYTES: u64 = 64 * 1024;
77
78 /// Queue capacity from emit sites to the writer (#6212). The outbox is
79 /// observability, not control flow: when a consumer is wedged longer than
80 /// this backlog, further events are dropped with a warning instead of
81 /// retaining unbounded snapshots in memory. Flush commands are never dropped
82 /// silently — a full queue fails the flush fast rather than timing it out.
83 const OUTBOX_QUEUE_CAPACITY: usize = 1024;
84
85 /// Events gathered per writer drain before one batched append. Batching only
86 /// affects how many queued events share a single file open/write/flush; each
87 /// line still lands as its own complete JSONL record.
88 const OUTBOX_MAX_BATCH: usize = 64;
89
90 /// Concurrent webhook posts the writer allows in flight. A stalled webhook
91 /// delays only its own event (plus the flush barrier, which the caller's
92 /// timeout bounds) — never the audit-log appends of later events.
93 const WEBHOOK_MAX_INFLIGHT: usize = 8;
94
95 /// One lifecycle event destined for the outbox.
96 ///
97 /// Construct one per emit site. `payload` must only contain bounded,
98 /// pre-redacted fields; apply [`bounded_text`] to anything free-form (error
99 /// messages, previews) before inserting it.
100 #[derive(Debug, Clone)]
101 pub struct LifecycleEvent {
102 /// Snake-case event name, e.g. `"turn_start"`.
103 pub event: String,
104 /// Dotted event kind, e.g. `"turn.started"` or `"turn.failed"`.
105 pub kind: String,
106 /// Owning session/thread id. Empty when the producer has none.
107 pub thread_id: String,
108 /// Current turn id, when known.
109 pub turn_id: Option<String>,
110 /// Current item id, when known.
111 pub item_id: Option<String>,
112 /// Bounded, redacted event payload.
113 pub payload: Value,
114 }
115
116 /// The lifecycle outbox handle.
117 ///
118 /// Cheap to clone (an `Arc`). When constructed without a path the outbox is
119 /// disabled and every `emit` is a no-op.
120 #[derive(Clone)]
121 pub struct LifecycleOutbox {
122 inner: Option<Arc<OutboxInner>>,
123 }
124
125 impl Default for LifecycleOutbox {
126 fn default() -> Self {
127 Self::disabled()
128 }
129 }
130
131 impl LifecycleOutbox {
132 /// Create an outbox writing to `path` when set and non-empty.
133 ///
134 /// `webhook_url` optionally adds a webhook fan-out (POST `{"at", "event"}`,
135 /// best-effort); `webhook_token` is its optional bearer token. Webhook
136 /// delivery is configured independently of the file: it only ever runs
137 /// when `webhook_url` is set, and it never replaces the local append.
138 pub fn new(
139 path: Option<PathBuf>,
140 webhook_url: Option<String>,
141 webhook_token: Option<String>,
142 ) -> Self {
143 let path = match path {
144 Some(path) if !path.as_os_str().is_empty() => crate::expand_home(path),
145 _ => return Self::disabled(),
146 };
147 let webhook = webhook_url
148 .as_deref()
149 .map(str::trim)
150 .filter(|url| !url.is_empty())
151 .map(|url| WebhookHookSink::new_with_token(url.to_string(), webhook_token));
152 let (sender, receiver) = tokio::sync::mpsc::channel(OUTBOX_QUEUE_CAPACITY);
153 Self {
154 inner: Some(Arc::new(OutboxInner {
155 path,
156 webhook,
157 sender,
158 receiver: Mutex::new(Some(receiver)),
159 writer_spawned: AtomicBool::new(false),
160 spawn_lock: Mutex::new(()),
161 })),
162 }
163 }
164
165 /// A disabled outbox that drops every event.
166 pub fn disabled() -> Self {
167 Self { inner: None }
168 }
169
170 /// True when a path was configured and events will be written.
171 pub fn is_enabled(&self) -> bool {
172 self.inner.is_some()
173 }
174
175 /// Emit one lifecycle event.
176 ///
177 /// Never blocks: the event is queued for the outbox's writer task (spawned
178 /// lazily on the current tokio runtime on first use). Events queued with
179 /// no runtime available — or after the writer task is gone — are dropped
180 /// with a warning. Delivery failures inside the writer are logged and
181 /// dropped as well; the outbox is observability, not control flow.
182 pub fn emit(&self, event: LifecycleEvent) {
183 let Some(inner) = self.inner.clone() else {
184 return;
185 };
186 if let Err(error) = inner.enqueue(OutboxCommand::Event(event)) {
187 tracing::warn!(target: "lifecycle_outbox", %error, "lifecycle event dropped");
188 }
189 }
190
191 /// Wait for events queued before this call to finish their delivery attempt.
192 ///
193 /// Local writes are flushed before the writer acknowledges this barrier.
194 /// Delivery errors remain logged and best effort; a stalled writer/webhook
195 /// or a stopped runtime returns an error within `timeout` instead of holding
196 /// process teardown indefinitely. This does not close other cloned handles.
197 pub async fn flush(&self, timeout: Duration) -> Result<()> {
198 let Some(inner) = self.inner.as_ref() else {
199 return Ok(());
200 };
201 let (reply, completed) = oneshot::channel();
202 inner.enqueue(OutboxCommand::Flush(reply))?;
203 let outcome = tokio::time::timeout(timeout, completed)
204 .await
205 .context("lifecycle outbox flush timed out; queued events may be incomplete")?
206 .context("lifecycle outbox writer stopped before flush completed")?;
207 outcome.map_err(anyhow::Error::msg)
208 }
209 }
210
211 enum OutboxCommand {
212 Event(LifecycleEvent),
213 Flush(oneshot::Sender<std::result::Result<(), String>>),
214 }
215
216 struct OutboxInner {
217 path: PathBuf,
218 webhook: Option<WebhookHookSink>,
219 sender: Sender<OutboxCommand>,
220 /// The writer task's receive half. Taken exactly once by the writer task.
221 receiver: Mutex<Option<Receiver<OutboxCommand>>>,
222 writer_spawned: AtomicBool,
223 /// Serializes the lazy writer-task spawn so two racing first emits cannot
224 /// start two writers.
225 spawn_lock: Mutex<()>,
226 }
227
228 impl OutboxInner {
229 /// Queue an event and make sure the writer task exists to drain it.
230 ///
231 /// Ordering: `send` happens before the spawn so events queued before the
232 /// writer starts are drained first, preserving enqueue order. The queue
233 /// is bounded: a wedged consumer drops further events with a warning
234 /// (observability, not control flow) but fails a flush fast instead of
235 /// dropping its reply channel.
236 fn enqueue(self: &Arc<Self>, command: OutboxCommand) -> Result<()> {
237 let is_flush = matches!(command, OutboxCommand::Flush(_));
238 match self.sender.try_send(command) {
239 Ok(()) => {}
240 Err(TrySendError::Full(_)) if !is_flush => {
241 tracing::warn!(
242 target: "lifecycle_outbox",
243 queue_capacity = OUTBOX_QUEUE_CAPACITY,
244 "lifecycle event dropped: outbox queue is full"
245 );
246 }
247 Err(TrySendError::Full(_)) => {
248 anyhow::bail!("lifecycle outbox queue is full; flush rejected");
249 }
250 Err(TrySendError::Closed(_)) => {
251 anyhow::bail!("lifecycle outbox writer task is gone");
252 }
253 }
254 self.ensure_writer_spawned();
255 Ok(())
256 }
257
258 fn ensure_writer_spawned(self: &Arc<Self>) {
259 if self.writer_spawned.load(Ordering::Acquire) {
260 return;
261 }
262 let _guard = self
263 .spawn_lock
264 .lock()
265 .unwrap_or_else(|poisoned| poisoned.into_inner());
266 if self.writer_spawned.load(Ordering::Acquire) {
267 return;
268 }
269 let Ok(handle) = tokio::runtime::Handle::try_current() else {
270 tracing::warn!(
271 target: "lifecycle_outbox",
272 "no tokio runtime available; lifecycle events are queued but will not be written"
273 );
274 return;
275 };
276 let receiver = self
277 .receiver
278 .lock()
279 .unwrap_or_else(|poisoned| poisoned.into_inner())
280 .take();
281 let Some(receiver) = receiver else {
282 return;
283 };
284 let mut state = WriterState {
285 path: self.path.clone(),
286 webhook: self.webhook.clone(),
287 next_seq: 1,
288 fallback_nonce: uuid::Uuid::new_v4().simple().to_string(),
289 pending_write_error: None,
290 receiver,
291 };
292 self.writer_spawned.store(true, Ordering::Release);
293 handle.spawn(async move {
294 state.run().await;
295 });
296 }
297 }
298
299 /// The outbox writer: owns the file state and the event queue drain loop.
300 struct WriterState {
301 path: PathBuf,
302 webhook: Option<WebhookHookSink>,
303 /// Fallback seq used only if local outbox recovery fails so webhook
304 /// fan-out still proceeds monotonically.
305 next_seq: u64,
306 fallback_nonce: String,
307 pending_write_error: Option<String>,
308 receiver: Receiver<OutboxCommand>,
309 }
310
311 struct OutboxTailState {
312 next_seq: u64,
313 nonce: Option<String>,
314 needs_leading_newline: bool,
315 }
316
317 struct LockedAppendOutcome {
318 next_seq: u64,
319 webhook_posts: Vec<(String, Value)>,
320 append_result: Result<()>,
321 }
322
323 impl WriterState {
324 /// Drain the queue until every sender is dropped, then exit.
325 ///
326 /// Events are gathered into batches ([`OUTBOX_MAX_BATCH`]) so a burst
327 /// shares one file open/write/flush. Webhook posts fan out through a
328 /// bounded [`JoinSet`](tokio::task::JoinSet) and never delay the appends
329 /// of later batches — a stalled webhook only holds back its own event
330 /// plus the flush barrier, which the caller's timeout bounds (#6212).
331 async fn run(&mut self) {
332 let mut batch: Vec<OutboxCommand> = Vec::with_capacity(OUTBOX_MAX_BATCH);
333 let mut webhooks = tokio::task::JoinSet::new();
334 while self.receiver.recv_many(&mut batch, OUTBOX_MAX_BATCH).await > 0 {
335 let mut events = Vec::new();
336 let mut replies = Vec::new();
337 for command in batch.drain(..) {
338 match command {
339 OutboxCommand::Event(event) => events.push(event),
340 OutboxCommand::Flush(reply) => replies.push(reply),
341 }
342 }
343 if let Err(error) = self.deliver_batch(&events, &mut webhooks).await {
344 tracing::warn!(
345 target: "lifecycle_outbox",
346 %error,
347 path = %self.path.display(),
348 "lifecycle outbox write failed"
349 );
350 self.pending_write_error = Some(error.to_string());
351 }
352 if !replies.is_empty() {
353 // The flush barrier covers every delivery attempt queued
354 // before it — appends above plus webhook attempts already
355 // spawned (mirroring the pre-batching serial writer, where
356 // a Flush was only reached after prior webhooks finished).
357 while webhooks.join_next().await.is_some() {}
358 let outcome = match self.pending_write_error.take() {
359 Some(error) => Err(error),
360 None => Ok(()),
361 };
362 for reply in replies {
363 let _ = reply.send(outcome.clone());
364 }
365 }
366 }
367 }
368
369 /// Assign monotonic seqs under a sibling advisory lock, append and fsync
370 /// the batch locally, and fan out webhook posts with stable idempotency
371 /// keys independently of whether the local write succeeded.
372 async fn deliver_batch(
373 &mut self,
374 events: &[LifecycleEvent],
375 webhooks: &mut tokio::task::JoinSet<()>,
376 ) -> Result<()> {
377 if events.is_empty() {
378 return Ok(());
379 }
380
381 let path = self.path.clone();
382 let events_owned = events.to_vec();
383 let fallback_next_seq = self.next_seq;
384 let fallback_nonce = self.fallback_nonce.clone();
385 let include_webhooks = self.webhook.is_some();
386
387 let outcome = tokio::task::spawn_blocking(move || {
388 append_batch_locked_sync(
389 &path,
390 &events_owned,
391 fallback_next_seq,
392 &fallback_nonce,
393 include_webhooks,
394 )
395 })
396 .await
397 .context("lifecycle outbox writer task panicked")?;
398
399 self.next_seq = outcome.next_seq;
400
401 if let Some(webhook) = &self.webhook {
402 for (idempotency_key, payload) in outcome.webhook_posts {
403 while webhooks.len() >= WEBHOOK_MAX_INFLIGHT {
404 let _ = webhooks.join_next().await;
405 }
406 let sink = webhook.clone();
407 webhooks.spawn(async move {
408 if let Err(error) = sink.post_payload(payload, &idempotency_key).await {
409 tracing::warn!(
410 target: "lifecycle_outbox",
411 %error,
412 "lifecycle webhook delivery failed (dropped)"
413 );
414 }
415 });
416 }
417 }
418
419 outcome.append_result
420 }
421 }
422
423 struct OutboxLockGuard(std::fs::File);
424
425 impl Drop for OutboxLockGuard {
426 fn drop(&mut self) {
427 let _ = self.0.unlock();
428 }
429 }
430
431 fn acquire_outbox_lock_sync(outbox_path: &Path) -> Result<Option<OutboxLockGuard>> {
432 let lock_file = crate::open_private_lock_file_sync(outbox_path)?;
433 match lock_file.lock() {
434 Ok(()) => Ok(Some(OutboxLockGuard(lock_file))),
435 #[cfg(unix)]
436 Err(error)
437 if !codewhale_util::lock::is_contention(&error)
438 && codewhale_util::lock::advisory_locking_unavailable(&error) =>
439 {
440 tracing::debug!(
441 target: "lifecycle_outbox",
442 %error,
443 path = %outbox_path.display(),
444 "advisory locking unavailable on filesystem; appending without lock"
445 );
446 Ok(None)
447 }
448 Err(error) => Err(error).with_context(|| {
449 format!(
450 "failed to acquire outbox lock for {}",
451 outbox_path.display()
452 )
453 }),
454 }
455 }
456
457 struct BuiltBatch {
458 next_seq: u64,
459 lines: Vec<String>,
460 webhook_posts: Vec<(String, Value)>,
461 }
462
463 fn build_batch_envelopes(
464 path: &Path,
465 events: &[LifecycleEvent],
466 start_seq: u64,
467 nonce: &str,
468 include_webhooks: bool,
469 ) -> Result<BuiltBatch> {
470 let path_hash = codewhale_paths::stable_hex(path);
471 let mut next_seq = start_seq;
472 let mut lines = Vec::with_capacity(events.len());
473 let mut webhook_posts = Vec::new();
474 for event in events {
475 let seq = next_seq;
476 next_seq = next_seq.saturating_add(1);
477
478 let mut extra = BTreeMap::new();
479 extra.insert(
480 OUTBOX_NONCE_FIELD.to_string(),
481 Value::String(nonce.to_string()),
482 );
483 let now = Utc::now().to_rfc3339();
484 let envelope = RuntimeEventEnvelope {
485 schema_version: RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION,
486 seq,
487 event: event.event.clone(),
488 kind: event.kind.clone(),
489 thread_id: event.thread_id.clone(),
490 turn_id: event.turn_id.clone(),
491 item_id: event.item_id.clone(),
492 timestamp: now.clone(),
493 created_at: Some(now),
494 payload: event.payload.clone(),
495 extra,
496 };
497 if include_webhooks {
498 let key = format!("outbox-{path_hash}-{nonce}:{seq}");
499 webhook_posts.push((
500 key,
501 json!({
502 "at": envelope.timestamp,
503 "event": envelope,
504 }),
505 ));
506 }
507 lines.push(serde_json::to_string(&envelope).context("failed to encode outbox event")?);
508 }
509 Ok(BuiltBatch {
510 next_seq,
511 lines,
512 webhook_posts,
513 })
514 }
515
516 fn append_batch_locked_sync(
517 path: &Path,
518 events: &[LifecycleEvent],
519 fallback_next_seq: u64,
520 fallback_nonce: &str,
521 include_webhooks: bool,
522 ) -> LockedAppendOutcome {
523 let lock_guard = match acquire_outbox_lock_sync(path) {
524 Ok(guard) => guard,
525 Err(error) => {
526 let BuiltBatch {
527 next_seq,
528 webhook_posts,
529 ..
530 } = build_batch_envelopes(
531 path,
532 events,
533 fallback_next_seq,
534 fallback_nonce,
535 include_webhooks,
536 )
537 .unwrap_or_else(|_| BuiltBatch {
538 next_seq: fallback_next_seq,
539 lines: Vec::new(),
540 webhook_posts: Vec::new(),
541 });
542 return LockedAppendOutcome {
543 next_seq,
544 webhook_posts,
545 append_result: Err(error),
546 };
547 }
548 };
549
550 let (start_seq, nonce, needs_leading_newline, recover_error) =
551 match recover_tail_state_sync(path) {
552 Ok(tail) => (
553 tail.next_seq,
554 tail.nonce
555 .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string()),
556 tail.needs_leading_newline,
557 None,
558 ),
559 Err(error) => (
560 fallback_next_seq,
561 fallback_nonce.to_string(),
562 false,
563 Some(error),
564 ),
565 };
566
567 let BuiltBatch {
568 next_seq,
569 lines,
570 webhook_posts,
571 } = match build_batch_envelopes(path, events, start_seq, &nonce, include_webhooks) {
572 Ok(built) => built,
573 Err(error) => {
574 drop(lock_guard);
575 return LockedAppendOutcome {
576 next_seq: fallback_next_seq,
577 webhook_posts: Vec::new(),
578 append_result: Err(error),
579 };
580 }
581 };
582
583 let append_result = if let Some(error) = recover_error {
584 Err(error)
585 } else {
586 (|| -> Result<()> {
587 let mut file = crate::open_private_append_sync(path)?;
588 if needs_leading_newline {
589 file.write_all(b"\n")
590 .context("failed to terminate torn outbox line")?;
591 }
592 for line in &lines {
593 let mut record = Vec::with_capacity(line.len() + 1);
594 record.extend_from_slice(line.as_bytes());
595 record.push(b'\n');
596 file.write_all(&record)
597 .context("failed to write outbox event")?;
598 }
599 file.flush().context("failed to flush outbox event")?;
600 file.sync_all().context("failed to sync outbox event")?;
601 Ok(())
602 })()
603 };
604
605 drop(lock_guard);
606 LockedAppendOutcome {
607 next_seq,
608 webhook_posts,
609 append_result,
610 }
611 }
612
613 /// Recover the seq and per-file nonce from the tail of `path`, skipping any
614 /// torn or corrupt trailing lines so a partial write can never wedge future
615 /// appends.
616 fn recover_tail_state_sync(path: &Path) -> Result<OutboxTailState> {
617 let mut file = match std::fs::File::open(path) {
618 Ok(file) => file,
619 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
620 return Ok(OutboxTailState {
621 next_seq: 1,
622 nonce: None,
623 needs_leading_newline: false,
624 });
625 }
626 Err(error) => {
627 return Err(error).with_context(|| format!("failed to open outbox {}", path.display()));
628 }
629 };
630 let len = file
631 .metadata()
632 .with_context(|| format!("failed to stat outbox {}", path.display()))?
633 .len();
634 if len == 0 {
635 return Ok(OutboxTailState {
636 next_seq: 1,
637 nonce: None,
638 needs_leading_newline: false,
639 });
640 }
641 let start = len.saturating_sub(SEQ_RECOVERY_TAIL_BYTES);
642 file.seek(SeekFrom::Start(start))?;
643 let mut tail = vec![0u8; (len - start) as usize];
644 file.read_exact(&mut tail)?;
645
646 let needs_leading_newline = tail.last() != Some(&b'\n');
647 let mut scan = match tail.iter().rposition(|byte| *byte == b'\n') {
648 // Bytes after the final newline are a torn trailing line from a crash
649 // mid-write; scan only complete newline-terminated lines before it.
650 Some(last_nl) => &tail[..last_nl],
651 None => {
652 return Ok(OutboxTailState {
653 next_seq: 1,
654 nonce: None,
655 needs_leading_newline,
656 });
657 }
658 };
659
660 loop {
661 let (line_bytes, rest) = match scan.iter().rposition(|byte| *byte == b'\n') {
662 Some(idx) => (&scan[idx + 1..], Some(&scan[..idx])),
663 None => (scan, None),
664 };
665 if let Ok(line) = std::str::from_utf8(line_bytes) {
666 let trimmed = line.trim();
667 if !trimmed.is_empty()
668 && let Ok(envelope) = serde_json::from_str::<RuntimeEventEnvelope>(trimmed)
669 {
670 let nonce = envelope
671 .extra
672 .get(OUTBOX_NONCE_FIELD)
673 .and_then(Value::as_str)
674 .filter(|value| !value.is_empty())
675 .map(ToOwned::to_owned);
676 return Ok(OutboxTailState {
677 next_seq: envelope.seq.saturating_add(1),
678 nonce,
679 needs_leading_newline,
680 });
681 }
682 }
683 match rest {
684 Some(next_scan) => scan = next_scan,
685 None => {
686 return Ok(OutboxTailState {
687 next_seq: 1,
688 nonce: None,
689 needs_leading_newline,
690 });
691 }
692 }
693 }
694 }
695
696 /// Recover the seq to continue from: the `seq` of the outbox file's last
697 /// complete line, plus 1 — or 1 for a missing/empty file.
698 #[cfg(test)]
699 async fn recover_last_seq(path: &Path) -> Result<u64> {
700 let path = path.to_path_buf();
701 tokio::task::spawn_blocking(move || recover_tail_state_sync(&path).map(|tail| tail.next_seq))
702 .await
703 .context("recover_last_seq task panicked")?
704 }
705
706 /// Bound free-form text to at most `max_chars` characters, stripping control
707 /// bytes and ANSI escape sequences and collapsing whitespace runs first.
708 ///
709 /// The limit counts Unicode scalar values, not bytes, so multi-byte text gets
710 /// the same ceiling as ASCII. The result is safe to embed in an outbox
711 /// payload. Callers remain responsible for only ever passing non-secret
712 /// fields (error messages, previews, model/provider labels — never raw tool
713 /// arguments, environment, or full transcript text), the same discipline the
714 /// desktop notification payloads enforce.
715 pub fn bounded_text(text: &str, max_chars: usize) -> String {
716 let cleaned: String = text
717 .chars()
718 .filter(|ch| !ch.is_control())
719 .collect::<String>()
720 .split_whitespace()
721 .collect::<Vec<_>>()
722 .join(" ");
723 let mut truncated = false;
724 let mut out = String::new();
725 let mut char_count = 0usize;
726 for ch in cleaned.chars() {
727 if char_count + 1 > max_chars {
728 truncated = true;
729 break;
730 }
731 out.push(ch);
732 char_count += 1;
733 }
734 if truncated {
735 // Make room for the marker while staying under the character ceiling.
736 let marker_chars = OUTBOX_TRUNCATION_MARKER.chars().count();
737 while char_count + marker_chars > max_chars {
738 out.pop();
739 char_count -= 1;
740 }
741 out.push_str(OUTBOX_TRUNCATION_MARKER);
742 }
743 out
744 }
745
746 #[cfg(test)]
747 mod tests {
748 use super::*;
749
750 fn temp_outbox_path(name: &str) -> (tempfile::TempDir, PathBuf) {
751 let dir = tempfile::tempdir().expect("tempdir");
752 let path = dir.path().join(name);
753 (dir, path)
754 }
755
756 fn event(name: &str, kind: &str) -> LifecycleEvent {
757 LifecycleEvent {
758 event: name.to_string(),
759 kind: kind.to_string(),
760 thread_id: "session-1".to_string(),
761 turn_id: Some("turn-1".to_string()),
762 item_id: None,
763 payload: json!({"status": "completed"}),
764 }
765 }
766
767 async fn deliver_all(state: &mut WriterState, events: Vec<LifecycleEvent>) {
768 let mut webhooks = tokio::task::JoinSet::new();
769 state
770 .deliver_batch(&events, &mut webhooks)
771 .await
772 .expect("deliver");
773 while webhooks.join_next().await.is_some() {}
774 }
775
776 async fn read_lines(path: &Path) -> Vec<Value> {
777 let text = tokio::fs::read_to_string(path).await.expect("read outbox");
778 text.lines()
779 .map(|line| serde_json::from_str::<Value>(line).expect("json line"))
780 .collect()
781 }
782
783 #[test]
784 fn flush_persists_queued_turn_boundaries_before_runtime_teardown() {
785 let (_dir, path) = temp_outbox_path("shutdown.jsonl");
786 let runtime = tokio::runtime::Builder::new_current_thread()
787 .enable_all()
788 .build()
789 .expect("runtime");
790 runtime.block_on(async {
791 let outbox = LifecycleOutbox::new(Some(path.clone()), None, None);
792 outbox.emit(event("turn_start", "turn.started"));
793 let clone = outbox.clone();
794 clone.emit(event("turn_end", "turn.completed"));
795 outbox.flush(Duration::from_secs(2)).await.expect("flush");
796 });
797 drop(runtime);
798
799 let contents = std::fs::read_to_string(path).expect("outbox persisted before exit");
800 let lines: Vec<Value> = contents
801 .lines()
802 .map(|line| serde_json::from_str(line).expect("complete JSONL record"))
803 .collect();
804 assert_eq!(lines.len(), 2);
805 assert_eq!(lines[0]["event"], "turn_start");
806 assert_eq!(lines[0]["seq"], 1);
807 assert_eq!(lines[1]["event"], "turn_end");
808 assert_eq!(lines[1]["seq"], 2);
809 }
810
811 #[tokio::test]
812 async fn flush_disabled_or_unused_outbox_creates_no_file() {
813 let (_dir, path) = temp_outbox_path("unused.jsonl");
814 LifecycleOutbox::disabled()
815 .flush(Duration::ZERO)
816 .await
817 .expect("disabled flush");
818 LifecycleOutbox::new(Some(path.clone()), None, None)
819 .flush(Duration::from_secs(2))
820 .await
821 .expect("unused flush");
822 assert!(!path.exists());
823 }
824
825 /// A stalled webhook must not head-of-line block the audit log: the
826 /// appends of later events land while the slow post is still in flight
827 /// (#6212). The pre-batching writer awaited each webhook inline, so the
828 /// second event's line could not appear until the first post resolved.
829 #[tokio::test]
830 async fn stalled_webhook_does_not_block_later_appends() {
831 let (_dir, path) = temp_outbox_path("webhook-head-of-line.jsonl");
832 let server = wiremock::MockServer::start().await;
833 wiremock::Mock::given(wiremock::matchers::method("POST"))
834 .respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(5)))
835 .mount(&server)
836 .await;
837 let outbox = LifecycleOutbox::new(Some(path.clone()), Some(server.uri()), None);
838
839 outbox.emit(event("turn_start", "turn.started"));
840 // Give the writer time to start the stalled webhook post for the
841 // first event before queueing the second.
842 tokio::time::sleep(Duration::from_millis(100)).await;
843 outbox.emit(event("turn_end", "turn.completed"));
844
845 for _ in 0..300 {
846 let appended = tokio::fs::read_to_string(&path)
847 .await
848 .is_ok_and(|text| text.lines().count() >= 2);
849 if appended {
850 break;
851 }
852 tokio::time::sleep(Duration::from_millis(10)).await;
853 }
854 let lines = read_lines(&path).await;
855 assert_eq!(
856 lines.len(),
857 2,
858 "the second event must be appended while the first webhook is still stalled"
859 );
860 assert_eq!(lines[1]["event"], "turn_end");
861 }
862
863 #[tokio::test]
864 async fn flush_is_bounded_when_webhook_delivery_stalls() {
865 let (_dir, path) = temp_outbox_path("stalled.jsonl");
866 let server = wiremock::MockServer::start().await;
867 wiremock::Mock::given(wiremock::matchers::method("POST"))
868 .respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(5)))
869 .mount(&server)
870 .await;
871 let outbox = LifecycleOutbox::new(Some(path), Some(server.uri()), None);
872 outbox.emit(event("turn_start", "turn.started"));
873 let error = tokio::time::timeout(
874 Duration::from_secs(1),
875 outbox.flush(Duration::from_millis(20)),
876 )
877 .await
878 .expect("the flush deadline must bound a blocked writer")
879 .expect_err("stalled delivery must report incomplete drain");
880 assert!(error.to_string().contains("flush timed out"));
881 }
882
883 #[test]
884 fn flush_reports_a_writer_lost_with_its_runtime() {
885 let (_dir, path) = temp_outbox_path("stopped.jsonl");
886 let outbox = LifecycleOutbox::new(Some(path), None, None);
887 let runtime = tokio::runtime::Builder::new_current_thread()
888 .enable_all()
889 .build()
890 .expect("first runtime");
891 runtime.block_on(async {
892 outbox.emit(event("turn_start", "turn.started"));
893 outbox
894 .flush(Duration::from_secs(2))
895 .await
896 .expect("first flush");
897 });
898 drop(runtime);
899 let runtime = tokio::runtime::Builder::new_current_thread()
900 .enable_all()
901 .build()
902 .expect("second runtime");
903 let error = runtime
904 .block_on(outbox.flush(Duration::from_secs(2)))
905 .expect_err("a closed writer cannot acknowledge delivery");
906 assert!(error.to_string().contains("writer task is gone"));
907 }
908
909 #[tokio::test]
910 async fn flush_reports_failed_local_write() {
911 let dir = tempfile::tempdir().expect("tempdir");
912 let path = dir.path().join("outbox-dir");
913 std::fs::create_dir_all(&path).expect("create directory at outbox path");
914 let outbox = LifecycleOutbox::new(Some(path), None, None);
915 outbox.emit(event("turn_start", "turn.started"));
916 let error = outbox
917 .flush(Duration::from_secs(2))
918 .await
919 .expect_err("failed local outbox write must fail flush");
920 assert!(!error.to_string().is_empty());
921 }
922
923 #[tokio::test]
924 async fn appends_one_jsonl_line_per_event_with_envelope_schema() {
925 let (_dir, path) = temp_outbox_path("schema.jsonl");
926 let mut state = WriterState {
927 path: path.clone(),
928 webhook: None,
929 next_seq: 0,
930 fallback_nonce: "test-nonce".to_string(),
931 pending_write_error: None,
932 receiver: tokio::sync::mpsc::channel(OUTBOX_QUEUE_CAPACITY).1,
933 };
934 deliver_all(&mut state, vec![event("turn_start", "turn.started")]).await;
935
936 let lines = read_lines(&path).await;
937 assert_eq!(lines.len(), 1);
938 let line = &lines[0];
939 assert_eq!(line["schema_version"], 1);
940 assert_eq!(line["seq"], 1);
941 assert_eq!(line["event"], "turn_start");
942 assert_eq!(line["kind"], "turn.started");
943 assert_eq!(line["thread_id"], "session-1");
944 assert_eq!(line["turn_id"], "turn-1");
945 assert_eq!(line["item_id"], Value::Null);
946 assert!(line["timestamp"].as_str().is_some());
947 assert!(line["payload"]["status"].as_str() == Some("completed"));
948 }
949
950 /// Every emit site now carries `payload.workspace` (and subagent events
951 /// additionally `payload.subagent`) for consumer-side routing. The writer
952 /// must preserve those fields verbatim through the envelope round trip
953 /// for every event type.
954 #[tokio::test]
955 async fn payload_workspace_and_subagent_fields_survive_the_round_trip() {
956 let (_dir, path) = temp_outbox_path("routing-fields.jsonl");
957 let mut state = WriterState {
958 path: path.clone(),
959 webhook: None,
960 next_seq: 0,
961 fallback_nonce: "test-nonce".to_string(),
962 pending_write_error: None,
963 receiver: tokio::sync::mpsc::channel(OUTBOX_QUEUE_CAPACITY).1,
964 };
965 let workspace = "/home/cw/wt-lane";
966 let subagent = "explore-1";
967 let subagent_payload = json!({ "workspace": workspace, "subagent": subagent });
968 deliver_all(
969 &mut state,
970 vec![
971 LifecycleEvent {
972 event: "session_start".to_string(),
973 kind: "session.started".to_string(),
974 thread_id: "session-1".to_string(),
975 turn_id: None,
976 item_id: None,
977 payload: json!({ "workspace": workspace }),
978 },
979 LifecycleEvent {
980 event: "turn_start".to_string(),
981 kind: "turn.started".to_string(),
982 thread_id: "session-1".to_string(),
983 turn_id: Some("turn-1".to_string()),
984 item_id: None,
985 payload: json!({ "workspace": workspace }),
986 },
987 LifecycleEvent {
988 event: "turn_end".to_string(),
989 kind: "turn.completed".to_string(),
990 thread_id: "session-1".to_string(),
991 turn_id: Some("turn-1".to_string()),
992 item_id: None,
993 payload: json!({ "workspace": workspace }),
994 },
995 LifecycleEvent {
996 event: "turn_stalled".to_string(),
997 kind: "turn.stalled".to_string(),
998 thread_id: "session-1".to_string(),
999 turn_id: Some("turn-1".to_string()),
1000 item_id: None,
1001 payload: json!({ "workspace": workspace }),
1002 },
1003 LifecycleEvent {
1004 event: "subagent_spawn".to_string(),
1005 kind: "subagent.spawned".to_string(),
1006 thread_id: "session-1".to_string(),
1007 turn_id: Some("turn-1".to_string()),
1008 item_id: None,
1009 payload: subagent_payload.clone(),
1010 },
1011 LifecycleEvent {
1012 event: "subagent_complete".to_string(),
1013 kind: "subagent.completed".to_string(),
1014 thread_id: "session-1".to_string(),
1015 turn_id: Some("turn-1".to_string()),
1016 item_id: None,
1017 payload: subagent_payload.clone(),
1018 },
1019 LifecycleEvent {
1020 event: "session_end".to_string(),
1021 kind: "session.ended".to_string(),
1022 thread_id: "session-1".to_string(),
1023 turn_id: None,
1024 item_id: None,
1025 payload: json!({ "workspace": workspace }),
1026 },
1027 ],
1028 )
1029 .await;
1030
1031 let lines = read_lines(&path).await;
1032 let events: Vec<&str> = lines
1033 .iter()
1034 .map(|line| line["event"].as_str().expect("event"))
1035 .collect();
1036 assert_eq!(
1037 events,
1038 vec![
1039 "session_start",
1040 "turn_start",
1041 "turn_end",
1042 "turn_stalled",
1043 "subagent_spawn",
1044 "subagent_complete",
1045 "session_end",
1046 ],
1047 "the routing-field contract must cover every lifecycle event type"
1048 );
1049 for line in &lines {
1050 assert_eq!(
1051 line["payload"]["workspace"],
1052 json!(workspace),
1053 "workspace must survive the round trip for event {}",
1054 line["event"]
1055 );
1056 }
1057 for event in ["subagent_spawn", "subagent_complete"] {
1058 let line = lines
1059 .iter()
1060 .find(|line| line["event"] == event)
1061 .expect(event);
1062 assert_eq!(
1063 line["payload"]["subagent"],
1064 json!(subagent),
1065 "subagent must survive the round trip for event {event}"
1066 );
1067 }
1068 }
1069
1070 #[tokio::test]
1071 async fn seq_is_monotonic_and_recovers_across_reopen() {
1072 let (_dir, path) = temp_outbox_path("seq.jsonl");
1073 let mut state = WriterState {
1074 path: path.clone(),
1075 webhook: None,
1076 next_seq: 0,
1077 fallback_nonce: "test-nonce".to_string(),
1078 pending_write_error: None,
1079 receiver: tokio::sync::mpsc::channel(OUTBOX_QUEUE_CAPACITY).1,
1080 };
1081 deliver_all(
1082 &mut state,
1083 vec![
1084 event("session_start", "session.started"),
1085 event("turn_start", "turn.started"),
1086 event("turn_end", "turn.completed"),
1087 ],
1088 )
1089 .await;
1090
1091 // A fresh writer (new process, same file) continues the sequence.
1092 let mut reopened = WriterState {
1093 path: path.clone(),
1094 webhook: None,
1095 next_seq: 0,
1096 fallback_nonce: "test-nonce".to_string(),
1097 pending_write_error: None,
1098 receiver: tokio::sync::mpsc::channel(OUTBOX_QUEUE_CAPACITY).1,
1099 };
1100 deliver_all(&mut reopened, vec![event("turn_start", "turn.started")]).await;
1101
1102 let lines = read_lines(&path).await;
1103 let seqs: Vec<u64> = lines
1104 .iter()
1105 .map(|line| line["seq"].as_u64().expect("seq"))
1106 .collect();
1107 assert_eq!(seqs, vec![1, 2, 3, 4]);
1108 }
1109
1110 #[tokio::test]
1111 async fn missing_and_empty_files_start_at_seq_1() {
1112 let (_dir, path) = temp_outbox_path("empty.jsonl");
1113 assert_eq!(recover_last_seq(&path).await.expect("missing file"), 1);
1114
1115 tokio::fs::write(&path, "").await.expect("empty file");
1116 assert_eq!(recover_last_seq(&path).await.expect("empty file"), 1);
1117 }
1118
1119 #[tokio::test]
1120 async fn partial_trailing_line_is_ignored_during_recovery() {
1121 let (_dir, path) = temp_outbox_path("partial.jsonl");
1122 tokio::fs::write(
1123 &path,
1124 format!(
1125 "{}\n{}\n{{\"schema_version\":1,\"seq\":3,\"event\":\"turn_",
1126 r#"{"schema_version":1,"seq":1,"event":"session_start","kind":"session.started","thread_id":"s","turn_id":null,"item_id":null,"timestamp":"t","payload":{}}"#,
1127 r#"{"schema_version":1,"seq":2,"event":"turn_start","kind":"turn.started","thread_id":"s","turn_id":null,"item_id":null,"timestamp":"t","payload":{}}"#,
1128 ),
1129 )
1130 .await
1131 .expect("write partial outbox");
1132 // The torn trailing line is not a complete record; recovery continues
1133 // from the last complete line's seq (2) → next seq 3.
1134 assert_eq!(recover_last_seq(&path).await.expect("recover"), 3);
1135 }
1136
1137 #[tokio::test]
1138 async fn emit_queues_and_writes_in_order_without_blocking() {
1139 let (_dir, path) = temp_outbox_path("emit.jsonl");
1140 let outbox = LifecycleOutbox::new(Some(path.clone()), None, None);
1141 assert!(outbox.is_enabled());
1142
1143 outbox.emit(event("session_start", "session.started"));
1144 outbox.emit(event("turn_start", "turn.started"));
1145 outbox.emit(event("turn_end", "turn.completed"));
1146
1147 // The writer task drains asynchronously; wait for the lines to land.
1148 for _ in 0..100 {
1149 if tokio::fs::metadata(&path)
1150 .await
1151 .is_ok_and(|meta| meta.len() > 0)
1152 && read_lines(&path).await.len() >= 3
1153 {
1154 break;
1155 }
1156 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1157 }
1158 let lines = read_lines(&path).await;
1159 assert_eq!(lines.len(), 3, "expected all queued events to be written");
1160 let events: Vec<&str> = lines
1161 .iter()
1162 .map(|line| line["event"].as_str().expect("event"))
1163 .collect();
1164 assert_eq!(events, vec!["session_start", "turn_start", "turn_end"]);
1165 let seqs: Vec<u64> = lines
1166 .iter()
1167 .map(|line| line["seq"].as_u64().expect("seq"))
1168 .collect();
1169 assert_eq!(seqs, vec![1, 2, 3], "seq must be assigned in emit order");
1170 }
1171
1172 #[test]
1173 fn disabled_outbox_drops_events_and_reports_disabled() {
1174 let outbox = LifecycleOutbox::new(None, None, None);
1175 assert!(!outbox.is_enabled());
1176 outbox.emit(event("turn_start", "turn.started")); // must not panic
1177
1178 let empty_path = LifecycleOutbox::new(Some(PathBuf::new()), None, None);
1179 assert!(!empty_path.is_enabled());
1180
1181 let default = LifecycleOutbox::default();
1182 assert!(!default.is_enabled());
1183 }
1184
1185 #[test]
1186 fn webhook_only_configures_without_a_file_path() {
1187 // `webhook_url` without `path` is stored losslessly in config; the
1188 // outbox handle itself only activates on a path.
1189 let outbox = LifecycleOutbox::new(
1190 None,
1191 Some("https://example.com/hook".to_string()),
1192 Some("token".to_string()),
1193 );
1194 assert!(!outbox.is_enabled());
1195 }
1196
1197 #[test]
1198 fn bounded_text_truncates_to_limit_with_marker() {
1199 assert_eq!(bounded_text("short", 80), "short");
1200 let long = "x".repeat(200);
1201 let bounded = bounded_text(&long, OUTBOX_DETAIL_MAX_CHARS);
1202 assert_eq!(bounded.chars().count(), OUTBOX_DETAIL_MAX_CHARS);
1203 assert!(bounded.ends_with(OUTBOX_TRUNCATION_MARKER));
1204 assert!(bounded.starts_with('x'));
1205 }
1206
1207 #[test]
1208 fn bounded_text_strips_controls_and_collapses_whitespace() {
1209 assert_eq!(
1210 bounded_text("line\x1b[31m one\n\n two\t", 80),
1211 "line[31m one two"
1212 );
1213 assert_eq!(bounded_text("", 80), "");
1214 assert_eq!(bounded_text(" \n\t ", 80), "");
1215 }
1216
1217 #[test]
1218 fn bounded_text_respects_utf8_boundaries() {
1219 // 30 multi-byte emoji (4 bytes each) = 120 bytes but only 30 chars.
1220 let emoji = "🦈".repeat(30);
1221 let bounded = bounded_text(&emoji, OUTBOX_DETAIL_MAX_CHARS);
1222 assert!(bounded.chars().count() <= OUTBOX_DETAIL_MAX_CHARS);
1223 assert!(bounded.starts_with('🦈'));
1224 }
1225
1226 /// The webhook transport must POST `{"at", "event"}` JSON and, when a
1227 /// token is configured, send it as `Authorization: Bearer <token>`.
1228 #[tokio::test]
1229 async fn webhook_posts_at_event_payload_with_bearer_token() {
1230 let server = wiremock::MockServer::start().await;
1231 wiremock::Mock::given(wiremock::matchers::method("POST"))
1232 .and(wiremock::matchers::path("/hook"))
1233 .and(wiremock::matchers::header(
1234 "authorization",
1235 "Bearer secret-token",
1236 ))
1237 .and(wiremock::matchers::body_partial_json(json!({
1238 "event": {"kind": "turn.started"}
1239 })))
1240 .respond_with(wiremock::ResponseTemplate::new(200))
1241 .mount(&server)
1242 .await;
1243
1244 let webhook = WebhookHookSink::new_with_token(
1245 format!("{}/hook", server.uri()),
1246 Some("secret-token".to_string()),
1247 );
1248 webhook
1249 .post_payload(
1250 json!(
1251 {"at": "2026-08-19T00:00:00Z", "event": {"kind": "turn.started"}}
1252 ),
1253 "test-idempotency-key-1",
1254 )
1255 .await
1256 .expect("webhook delivery");
1257
1258 let requests = server.received_requests().await.expect("requests");
1259 assert_eq!(requests.len(), 1, "exactly one webhook POST");
1260 assert_eq!(
1261 requests[0]
1262 .headers
1263 .get(crate::WEBHOOK_IDEMPOTENCY_KEY_HEADER)
1264 .and_then(|v| v.to_str().ok()),
1265 Some("test-idempotency-key-1")
1266 );
1267 }
1268
1269 /// A webhook that always fails must surface its error to the caller
1270 /// (which logs and drops it) — never panic, never retry forever.
1271 #[tokio::test]
1272 async fn webhook_failure_is_an_error_not_a_panic() {
1273 let server = wiremock::MockServer::start().await;
1274 wiremock::Mock::given(wiremock::matchers::method("POST"))
1275 .respond_with(wiremock::ResponseTemplate::new(500))
1276 .mount(&server)
1277 .await;
1278
1279 let webhook = WebhookHookSink::new_with_token(format!("{}/hook", server.uri()), None);
1280 let result = webhook.post_payload(json!({}), "test-fail-key").await;
1281 assert!(result.is_err(), "expected the failure to be reported");
1282 }
1283
1284 #[tokio::test]
1285 async fn interleaved_writers_assign_monotonic_unique_seqs() {
1286 let dir = tempfile::tempdir().expect("tempdir");
1287 let path = dir.path().join("events.jsonl");
1288
1289 let outbox_a = LifecycleOutbox::new(Some(path.clone()), None, None);
1290 let outbox_b = LifecycleOutbox::new(Some(path.clone()), None, None);
1291
1292 outbox_a.emit(event("a_1", "turn.started"));
1293 outbox_a.flush(Duration::from_secs(5)).await.expect("flush");
1294 outbox_b.emit(event("b_1", "turn.started"));
1295 outbox_b.flush(Duration::from_secs(5)).await.expect("flush");
1296 outbox_a.emit(event("a_2", "turn.completed"));
1297 outbox_a.flush(Duration::from_secs(5)).await.expect("flush");
1298 outbox_b.emit(event("b_2", "turn.completed"));
1299 outbox_b.flush(Duration::from_secs(5)).await.expect("flush");
1300
1301 let raw = std::fs::read_to_string(&path).expect("read outbox");
1302 let seqs: Vec<u64> = raw
1303 .lines()
1304 .map(|line| {
1305 serde_json::from_str::<RuntimeEventEnvelope>(line)
1306 .expect("parse envelope")
1307 .seq
1308 })
1309 .collect();
1310 assert_eq!(seqs, vec![1, 2, 3, 4]);
1311 }
1312
1313 #[tokio::test]
1314 async fn torn_trailing_line_does_not_glue_or_wedge_later_appends() {
1315 let dir = tempfile::tempdir().expect("tempdir");
1316 let path = dir.path().join("events.jsonl");
1317
1318 let first = LifecycleOutbox::new(Some(path.clone()), None, None);
1319 first.emit(event("turn_start", "turn.started"));
1320 first.flush(Duration::from_secs(5)).await.expect("flush");
1321
1322 // Simulate a crash leaving an unterminated torn JSON fragment at EOF.
1323 let mut file = std::fs::OpenOptions::new()
1324 .append(true)
1325 .open(&path)
1326 .expect("open for torn write");
1327 file.write_all(br#"{"schema_version":1,"seq":2,"trun"#)
1328 .expect("write torn tail");
1329 drop(file);
1330
1331 let second = LifecycleOutbox::new(Some(path.clone()), None, None);
1332 second.emit(event("turn_end", "turn.completed"));
1333 second.flush(Duration::from_secs(5)).await.expect("flush");
1334 second.emit(event("turn_end_2", "turn.completed"));
1335 second.flush(Duration::from_secs(5)).await.expect("flush");
1336
1337 let raw = std::fs::read_to_string(&path).expect("read outbox");
1338 let parsed: Vec<RuntimeEventEnvelope> = raw
1339 .lines()
1340 .filter_map(|line| serde_json::from_str::<RuntimeEventEnvelope>(line).ok())
1341 .collect();
1342 let seqs: Vec<u64> = parsed.iter().map(|env| env.seq).collect();
1343 assert_eq!(seqs, vec![1, 2, 3]);
1344 }
1345
1346 #[tokio::test]
1347 async fn webhook_delivery_still_fires_when_local_outbox_append_fails() {
1348 let dir = tempfile::tempdir().expect("tempdir");
1349 // Pointing the outbox path at an existing directory forces local open/append to fail.
1350 let dir_as_file = dir.path().join("cannot-open-as-file");
1351 std::fs::create_dir(&dir_as_file).expect("create blocking dir");
1352
1353 let server = wiremock::MockServer::start().await;
1354 wiremock::Mock::given(wiremock::matchers::method("POST"))
1355 .and(wiremock::matchers::path("/hook"))
1356 .respond_with(wiremock::ResponseTemplate::new(200))
1357 .mount(&server)
1358 .await;
1359
1360 let outbox = LifecycleOutbox::new(
1361 Some(dir_as_file),
1362 Some(format!("{}/hook", server.uri())),
1363 None,
1364 );
1365 outbox.emit(event("turn_start", "turn.started"));
1366 let error = outbox
1367 .flush(Duration::from_secs(5))
1368 .await
1369 .expect_err("failed local outbox write must fail flush");
1370 assert!(!error.to_string().is_empty());
1371
1372 let requests = server.received_requests().await.expect("requests");
1373 assert_eq!(
1374 requests.len(),
1375 1,
1376 "webhook must still fire on local write error"
1377 );
1378 assert!(
1379 requests[0]
1380 .headers
1381 .get(crate::WEBHOOK_IDEMPOTENCY_KEY_HEADER)
1382 .is_some()
1383 );
1384 }
1385
1386 #[tokio::test]
1387 async fn webhook_retries_reuse_key_and_file_rotation_generates_distinct_key() {
1388 let dir = tempfile::tempdir().expect("tempdir");
1389 let path = dir.path().join("events.jsonl");
1390
1391 let server = wiremock::MockServer::start().await;
1392 wiremock::Mock::given(wiremock::matchers::method("POST"))
1393 .and(wiremock::matchers::path("/hook"))
1394 .respond_with(wiremock::ResponseTemplate::new(503))
1395 .up_to_n_times(1)
1396 .mount(&server)
1397 .await;
1398 wiremock::Mock::given(wiremock::matchers::method("POST"))
1399 .and(wiremock::matchers::path("/hook"))
1400 .respond_with(wiremock::ResponseTemplate::new(200))
1401 .mount(&server)
1402 .await;
1403
1404 let outbox = LifecycleOutbox::new(
1405 Some(path.clone()),
1406 Some(format!("{}/hook", server.uri())),
1407 None,
1408 );
1409 outbox.emit(event("turn_start", "turn.started"));
1410 outbox.flush(Duration::from_secs(5)).await.expect("flush");
1411
1412 // Rotate/remove the outbox file; seq restarts at 1 with a fresh nonce.
1413 std::fs::remove_file(&path).expect("rotate outbox file");
1414 outbox.emit(event("turn_start", "turn.started"));
1415 outbox.flush(Duration::from_secs(5)).await.expect("flush");
1416
1417 let requests = server.received_requests().await.expect("requests");
1418 assert_eq!(
1419 requests.len(),
1420 3,
1421 "2 attempts for first event + 1 for rotated"
1422 );
1423 let key = |idx: usize| {
1424 requests[idx]
1425 .headers
1426 .get(crate::WEBHOOK_IDEMPOTENCY_KEY_HEADER)
1427 .and_then(|v| v.to_str().ok())
1428 .expect("Idempotency-Key header")
1429 .to_string()
1430 };
1431 assert_eq!(key(0), key(1), "retry must reuse identical Idempotency-Key");
1432 assert!(key(0).ends_with(":1"));
1433 assert!(key(2).ends_with(":1"));
1434 assert_ne!(
1435 key(0),
1436 key(2),
1437 "file rotation must generate a fresh nonce so seq=1 gets a new Idempotency-Key"
1438 );
1439 }
1440 }
1441
1441 lines RUST