|
| 1 | +//! `write_stamp` — direct stamp write by exact session id or message id. |
| 2 | +//! |
| 3 | +//! Companion to `write_pending_stamp` (sidecar manifest, matched at ingest |
| 4 | +//! time by cwd + spawnerPid + spawnStartTs). When a launcher knows the |
| 5 | +//! session id up front — e.g. it preallocated a Claude `--session-id` UUID |
| 6 | +//! before spawn — calling [`write_stamp`] folds the enrichment straight |
| 7 | +//! onto the ledger by selector, skipping the manifest dance entirely. This |
| 8 | +//! is the more reliable path: no path-matching race, no orphan manifest if |
| 9 | +//! the spawn fails. |
| 10 | +//! |
| 11 | +//! The verb is exposed as a free function and as a [`LedgerHandle`] method, |
| 12 | +//! mirroring the rest of the SDK surface. |
| 13 | +//! |
| 14 | +//! Empty selectors (neither `session_id` nor `message_id` set) are |
| 15 | +//! rejected via [`crate::StampError::EmptySelector`] — a stamp with no |
| 16 | +//! selector would label every turn, which is never what the caller wants. |
| 17 | +
|
| 18 | +use std::path::PathBuf; |
| 19 | + |
| 20 | +use anyhow::Result; |
| 21 | + |
| 22 | +use crate::{Enrichment, Ledger, LedgerHandle, LedgerOpenOptions, Stamp, StampSelector}; |
| 23 | + |
| 24 | +/// Options for [`write_stamp`]. At least one of `session_id` or |
| 25 | +/// `message_id` must be set. |
| 26 | +#[derive(Debug, Clone, Default)] |
| 27 | +pub struct WriteStampOptions { |
| 28 | + pub session_id: Option<String>, |
| 29 | + pub message_id: Option<String>, |
| 30 | + pub enrichment: Enrichment, |
| 31 | + /// ISO-8601 timestamp the caller observed. Defaults to "now" formatted |
| 32 | + /// `YYYY-MM-DDTHH:MM:SSZ` when omitted. |
| 33 | + pub ts: Option<String>, |
| 34 | + pub ledger_home: Option<PathBuf>, |
| 35 | +} |
| 36 | + |
| 37 | +impl LedgerHandle { |
| 38 | + /// Append a stamp targeting the given session / message selector. |
| 39 | + pub fn write_stamp(&mut self, opts: WriteStampOptions) -> Result<()> { |
| 40 | + let stamp = build_stamp(&opts)?; |
| 41 | + self.inner.append_stamp(&stamp)?; |
| 42 | + Ok(()) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// Open the ledger, write the stamp, drop the handle. |
| 47 | +pub fn write_stamp(opts: WriteStampOptions) -> Result<()> { |
| 48 | + let stamp = build_stamp(&opts)?; |
| 49 | + let lo = match opts.ledger_home.as_deref() { |
| 50 | + Some(h) => LedgerOpenOptions::with_home(h), |
| 51 | + None => LedgerOpenOptions::default(), |
| 52 | + }; |
| 53 | + let mut handle = Ledger::open(lo)?; |
| 54 | + handle.inner.append_stamp(&stamp)?; |
| 55 | + Ok(()) |
| 56 | +} |
| 57 | + |
| 58 | +fn build_stamp(opts: &WriteStampOptions) -> Result<Stamp> { |
| 59 | + let selector = StampSelector { |
| 60 | + session_id: opts.session_id.clone(), |
| 61 | + message_id: opts.message_id.clone(), |
| 62 | + range: None, |
| 63 | + }; |
| 64 | + let ts = opts |
| 65 | + .ts |
| 66 | + .clone() |
| 67 | + .unwrap_or_else(|| now_iso(&std::time::SystemTime::now())); |
| 68 | + Stamp::new(ts, selector, opts.enrichment.clone()).map_err(Into::into) |
| 69 | +} |
| 70 | + |
| 71 | +fn now_iso(now: &std::time::SystemTime) -> String { |
| 72 | + let secs = now |
| 73 | + .duration_since(std::time::UNIX_EPOCH) |
| 74 | + .map(|d| d.as_secs()) |
| 75 | + .unwrap_or(0); |
| 76 | + let dt = time::OffsetDateTime::from_unix_timestamp(secs as i64) |
| 77 | + .unwrap_or(time::OffsetDateTime::UNIX_EPOCH); |
| 78 | + let fmt = time::macros::format_description!( |
| 79 | + "[year]-[month]-[day]T[hour]:[minute]:[second]Z" |
| 80 | + ); |
| 81 | + dt.format(&fmt).expect("format z iso") |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + use std::collections::BTreeMap; |
| 88 | + |
| 89 | + #[test] |
| 90 | + fn empty_selector_is_rejected() { |
| 91 | + let err = write_stamp(WriteStampOptions { |
| 92 | + session_id: None, |
| 93 | + message_id: None, |
| 94 | + enrichment: BTreeMap::new(), |
| 95 | + ts: None, |
| 96 | + ledger_home: Some(std::env::temp_dir()), |
| 97 | + }) |
| 98 | + .unwrap_err(); |
| 99 | + assert!( |
| 100 | + err.to_string().contains("selector"), |
| 101 | + "expected empty-selector error, got: {err}" |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + #[test] |
| 106 | + fn stamp_round_trips_session_selector() { |
| 107 | + let dir = tempfile::tempdir().unwrap(); |
| 108 | + let mut enrichment = Enrichment::new(); |
| 109 | + enrichment.insert("spawner".into(), "pear".into()); |
| 110 | + enrichment.insert("on_relay".into(), "true".into()); |
| 111 | + write_stamp(WriteStampOptions { |
| 112 | + session_id: Some("abc-123".into()), |
| 113 | + message_id: None, |
| 114 | + enrichment: enrichment.clone(), |
| 115 | + ts: Some("2026-05-21T12:00:00Z".into()), |
| 116 | + ledger_home: Some(dir.path().to_path_buf()), |
| 117 | + }) |
| 118 | + .unwrap(); |
| 119 | + |
| 120 | + let opts = LedgerOpenOptions::with_home(dir.path()); |
| 121 | + let handle = Ledger::open(opts).unwrap(); |
| 122 | + let stamps = handle.inner.list_stamps().unwrap(); |
| 123 | + assert_eq!(stamps.len(), 1, "expected exactly one stamp"); |
| 124 | + assert_eq!(stamps[0].selector.session_id.as_deref(), Some("abc-123")); |
| 125 | + assert_eq!(stamps[0].enrichment, enrichment); |
| 126 | + } |
| 127 | + |
| 128 | + #[test] |
| 129 | + fn default_ts_is_iso_z() { |
| 130 | + let dir = tempfile::tempdir().unwrap(); |
| 131 | + let mut enrichment = Enrichment::new(); |
| 132 | + enrichment.insert("k".into(), "v".into()); |
| 133 | + write_stamp(WriteStampOptions { |
| 134 | + session_id: Some("s".into()), |
| 135 | + message_id: None, |
| 136 | + enrichment, |
| 137 | + ts: None, |
| 138 | + ledger_home: Some(dir.path().to_path_buf()), |
| 139 | + }) |
| 140 | + .unwrap(); |
| 141 | + let handle = |
| 142 | + Ledger::open(LedgerOpenOptions::with_home(dir.path())).unwrap(); |
| 143 | + let stamps = handle.inner.list_stamps().unwrap(); |
| 144 | + let ts = &stamps[0].ts; |
| 145 | + assert!( |
| 146 | + ts.ends_with('Z') && ts.contains('T') && ts.len() == 20, |
| 147 | + "ts should be YYYY-MM-DDTHH:MM:SSZ, got {ts}" |
| 148 | + ); |
| 149 | + } |
| 150 | +} |
0 commit comments