diff --git a/atomic-agent/src/event.rs b/atomic-agent/src/event.rs index e57a37cd..40ab58d8 100644 --- a/atomic-agent/src/event.rs +++ b/atomic-agent/src/event.rs @@ -316,7 +316,8 @@ pub struct TurnEvent { #[serde(default, skip_serializing_if = "Option::is_none")] pub tool_use_id: Option, - /// When this event occurred. + /// Source event time, normalized to UTC without discarding subsecond precision. + /// Hook adapters use receipt time only when the source timestamp is absent/null. pub timestamp: DateTime, /// The raw JSON input from the agent hook, preserved for debugging. diff --git a/atomic-agent/src/hooks/agy.rs b/atomic-agent/src/hooks/agy.rs index 275fb145..7a4b4736 100644 --- a/atomic-agent/src/hooks/agy.rs +++ b/atomic-agent/src/hooks/agy.rs @@ -84,7 +84,7 @@ use serde_json::Value; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; // Constants @@ -244,6 +244,8 @@ impl AgentHook for AgyHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::TurnStart => { // Antigravity: PreInvocation → TurnStart @@ -318,6 +320,7 @@ impl AgentHook for AgyHook { reason: format!("hook type {:?} is not supported by agy", hook_type), }), } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/claude_code/parse.rs b/atomic-agent/src/hooks/claude_code/parse.rs index cf25f497..3473ed0d 100644 --- a/atomic-agent/src/hooks/claude_code/parse.rs +++ b/atomic-agent/src/hooks/claude_code/parse.rs @@ -7,7 +7,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; // ============================================================================ // CLAUDE CODE JSON INPUT TYPES @@ -115,6 +115,8 @@ pub(super) fn parse_hook_event( reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(agent_name, hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => parse_session_start(agent_name, hook_type, raw_json), HookType::SessionEnd | HookType::TurnEnd => { @@ -124,6 +126,7 @@ pub(super) fn parse_hook_event( HookType::PreToolUse => parse_pre_tool(agent_name, hook_type, raw_json), HookType::PostToolUse => parse_post_tool(agent_name, hook_type, raw_json), } + .map(|event| event.with_timestamp(timestamp)) } /// Extract the session_id from parsed input, returning a default if missing. diff --git a/atomic-agent/src/hooks/cline.rs b/atomic-agent/src/hooks/cline.rs index af44955f..659c0014 100644 --- a/atomic-agent/src/hooks/cline.rs +++ b/atomic-agent/src/hooks/cline.rs @@ -62,7 +62,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; // ============================================================================= // Constants @@ -145,6 +145,7 @@ struct ClineInput { hook_name: Option, #[serde(default, alias = "clineVersion")] cline_version: Option, + /// Decimal epoch milliseconds (`Date.now().toString()` in Cline's hook factory). #[serde(default)] timestamp: Option, #[serde(default, alias = "workspaceRoots")] @@ -245,6 +246,9 @@ impl AgentHook for ClineHook { reason: e.to_string(), })?; + let timestamp = + TimestampFormat::UnixMillisString.parse(self.name(), hook_type, &raw_json)?; + let parsed: ClineInput = serde_json::from_value(raw_json.clone()).map_err(|e| AgentError::HookParseFailed { agent: self.name().to_string(), @@ -416,6 +420,7 @@ impl AgentHook for ClineHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/codex.rs b/atomic-agent/src/hooks/codex.rs index 3919fe55..5908d7f2 100644 --- a/atomic-agent/src/hooks/codex.rs +++ b/atomic-agent/src/hooks/codex.rs @@ -22,7 +22,7 @@ use serde_json::{Map, Value}; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use super::AgentHook; +use super::{timestamp::TimestampFormat, AgentHook}; const CODEX_DIR: &str = ".codex"; const HOOKS_FILE: &str = "hooks.json"; @@ -222,6 +222,7 @@ impl AgentHook for CodexHook { fn parse_event(&self, hook_type: HookType, input: &[u8]) -> AgentResult { let raw_json = self.parse_json(hook_type, input)?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; match hook_type { HookType::SessionStart => { @@ -306,6 +307,7 @@ impl AgentHook for CodexHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/copilot.rs b/atomic-agent/src/hooks/copilot.rs index 0d5bca04..bf120beb 100644 --- a/atomic-agent/src/hooks/copilot.rs +++ b/atomic-agent/src/hooks/copilot.rs @@ -61,6 +61,10 @@ //! | Command key | `command` | `bash` / `powershell` | //! | TurnEnd / Stop | `Stop` event | No `stop` event | //! | JSON fields | snake_case | camelCase with snake aliases | +//! +//! Source timestamps are integer epoch milliseconds in camelCase hook payloads +//! and RFC-3339 strings in VS Code-compatible payloads. See +//! . use std::path::Path; @@ -68,7 +72,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; // ============================================================================= // Constants @@ -87,9 +91,6 @@ const GITHUB_DIR: &str = ".github"; #[derive(Debug, Deserialize)] #[allow(dead_code)] struct SessionStartInput { - #[serde(default)] - timestamp: Option, - #[serde(default)] cwd: Option, @@ -106,9 +107,6 @@ struct SessionStartInput { #[derive(Debug, Deserialize)] #[allow(dead_code)] struct SessionEndInput { - #[serde(default)] - timestamp: Option, - #[serde(default)] cwd: Option, @@ -128,9 +126,6 @@ struct SessionEndInput { #[derive(Debug, Deserialize)] #[allow(dead_code)] struct UserPromptInput { - #[serde(default)] - timestamp: Option, - #[serde(default)] cwd: Option, @@ -150,9 +145,6 @@ struct UserPromptInput { #[derive(Debug, Deserialize)] #[allow(dead_code)] struct PreToolUseInput { - #[serde(default)] - timestamp: Option, - #[serde(default)] cwd: Option, @@ -178,9 +170,6 @@ struct PreToolUseInput { #[derive(Debug, Deserialize)] #[allow(dead_code)] struct PostToolUseInput { - #[serde(default)] - timestamp: Option, - #[serde(default)] cwd: Option, @@ -278,6 +267,9 @@ impl AgentHook for CopilotHook { reason: e.to_string(), })?; + let timestamp = + TimestampFormat::Rfc3339OrUnixMillis.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -408,6 +400,7 @@ impl AgentHook for CopilotHook { .to_string(), }), } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/cursor.rs b/atomic-agent/src/hooks/cursor.rs index fc71ef2e..355f0261 100644 --- a/atomic-agent/src/hooks/cursor.rs +++ b/atomic-agent/src/hooks/cursor.rs @@ -69,7 +69,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Cursor config directory name. const CURSOR_DIR: &str = ".cursor"; @@ -410,6 +410,8 @@ impl AgentHook for CursorHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -702,6 +704,7 @@ impl AgentHook for CursorHook { } } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/devin.rs b/atomic-agent/src/hooks/devin.rs index b26dd83c..0dc0bf5d 100644 --- a/atomic-agent/src/hooks/devin.rs +++ b/atomic-agent/src/hooks/devin.rs @@ -57,7 +57,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Devin Desktop config directory name. const DEVIN_DIR: &str = ".devin"; @@ -222,6 +222,8 @@ impl AgentHook for DevinHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -348,6 +350,7 @@ impl AgentHook for DevinHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/gemini_cli.rs b/atomic-agent/src/hooks/gemini_cli.rs index b6c2e9f9..69125636 100644 --- a/atomic-agent/src/hooks/gemini_cli.rs +++ b/atomic-agent/src/hooks/gemini_cli.rs @@ -89,7 +89,7 @@ use serde::{Deserialize, Serialize}; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; // Constants @@ -513,6 +513,8 @@ impl AgentHook for GeminiCliHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -662,6 +664,7 @@ impl AgentHook for GeminiCliHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/grok.rs b/atomic-agent/src/hooks/grok.rs index 17bee69b..896d736e 100644 --- a/atomic-agent/src/hooks/grok.rs +++ b/atomic-agent/src/hooks/grok.rs @@ -35,7 +35,7 @@ use serde_json::Value; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// User-level Grok config directory name under `$HOME`. const GROK_DIR: &str = ".grok"; @@ -170,6 +170,7 @@ impl AgentHook for GrokHook { fn parse_event(&self, hook_type: HookType, input: &[u8]) -> AgentResult { let raw_json = self.parse_json(hook_type, input)?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; let parsed = self.parse_common(hook_type, raw_json.clone())?; let mut raw_json = with_xai_provider(raw_json); @@ -220,7 +221,7 @@ impl AgentHook for GrokHook { HookType::SessionStart | HookType::SessionEnd | HookType::TurnEnd => {} } - Ok(event) + Ok(event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/hermes.rs b/atomic-agent/src/hooks/hermes.rs index 2a15cc75..527aa829 100644 --- a/atomic-agent/src/hooks/hermes.rs +++ b/atomic-agent/src/hooks/hermes.rs @@ -15,7 +15,7 @@ use serde_json::Value; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use super::AgentHook; +use super::{timestamp::TimestampFormat, AgentHook}; const HERMES_DIR: &str = ".hermes"; @@ -108,6 +108,7 @@ impl AgentHook for HermesHook { fn parse_event(&self, hook_type: HookType, input: &[u8]) -> AgentResult { let raw_json = self.parse_json(hook_type, input)?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; let mut event = TurnEvent::new(Self::extract_session_id(&raw_json), hook_type) .with_raw_json(with_hermes_provider(raw_json.clone())); @@ -130,7 +131,7 @@ impl AgentHook for HermesHook { } } - Ok(event) + Ok(event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/kilo.rs b/atomic-agent/src/hooks/kilo.rs index 7da28a5a..01fbba95 100644 --- a/atomic-agent/src/hooks/kilo.rs +++ b/atomic-agent/src/hooks/kilo.rs @@ -61,7 +61,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Kilo Code config directory name. const KILO_DIR: &str = ".kilo"; @@ -203,6 +203,8 @@ impl AgentHook for KiloHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::TurnStart => { let parsed: PromptSubmitInput = @@ -333,6 +335,7 @@ impl AgentHook for KiloHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/kiro.rs b/atomic-agent/src/hooks/kiro.rs index 82344eb8..66cdadb0 100644 --- a/atomic-agent/src/hooks/kiro.rs +++ b/atomic-agent/src/hooks/kiro.rs @@ -63,7 +63,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Kiro config directory name. const KIRO_DIR: &str = ".kiro"; @@ -232,6 +232,8 @@ impl AgentHook for KiroHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::TurnStart => { let parsed: PromptSubmitInput = @@ -363,6 +365,7 @@ impl AgentHook for KiroHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/mod.rs b/atomic-agent/src/hooks/mod.rs index 5ebe8ec9..52b274ec 100644 --- a/atomic-agent/src/hooks/mod.rs +++ b/atomic-agent/src/hooks/mod.rs @@ -31,6 +31,24 @@ //! TurnOrchestrator //! ``` //! +//! # Source Timestamps +//! +//! Every built-in adapter reads the optional top-level `timestamp` before +//! agent-specific normalization, preserves its source time in [`TurnEvent`], +//! and leaves its raw representation intact. The provenance journal stores +//! milliseconds; RFC-3339 inputs retain finer precision in the event itself. +//! +//! - Copilot accepts integer epoch milliseconds (camelCase hooks) or RFC-3339 +//! strings (VS Code-compatible hooks). +//! - Cline accepts decimal epoch-millisecond strings. +//! - Other adapters accept RFC-3339 strings when supplied. Hosts without a +//! timestamp use receipt time; Atomic cannot reconstruct their source time. +//! +//! Only missing/null timestamps fall back to receipt time. Malformed supplied +//! values return [`AgentError::HookParseFailed`], including overflow or unsupported +//! representations. New events never infer seconds versus milliseconds from +//! magnitude; legacy stored-payload compatibility remains a separate concern. +//! //! # Hook Installation //! //! When `atomic agent enable --agent claude-code` is run, the adapter's @@ -72,6 +90,7 @@ pub mod manifest; pub mod opencode; pub mod pi; pub mod sherpa; +mod timestamp; use std::fmt; use std::path::Path; @@ -148,6 +167,9 @@ pub trait AgentHook: Send + Sync + fmt::Debug { /// /// The `input` parameter is the raw bytes read from stdin when the agent /// invokes the hook. Each agent sends a different JSON format. + /// Preserve supplied source time using the adapter's explicit wire encoding; + /// use receipt time only when the timestamp is missing/null. Do not derive + /// event time from tool arguments, transcripts, or timestamp magnitude. /// /// # Arguments /// diff --git a/atomic-agent/src/hooks/opencode.rs b/atomic-agent/src/hooks/opencode.rs index 7499dc80..03f2c664 100644 --- a/atomic-agent/src/hooks/opencode.rs +++ b/atomic-agent/src/hooks/opencode.rs @@ -43,11 +43,13 @@ //! { //! "session_id": "abc-123", //! "cwd": "/path/to/project", -//! "timestamp": "2025-01-15T10:30:00Z" +//! "timestamp": "2025-01-15T10:30:00.123Z" //! } //! ``` //! //! Additional fields vary by verb (see struct definitions below). +//! Supplied RFC-3339 timestamps retain their source time and fractional precision. +//! Missing/null timestamps use receipt time; invalid supplied timestamps are errors. //! //! # Installation //! @@ -65,7 +67,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The OpenCode config directory name. const OPENCODE_DIR: &str = ".opencode"; @@ -412,6 +414,8 @@ impl AgentHook for OpenCodeHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -579,6 +583,7 @@ impl AgentHook for OpenCodeHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { @@ -738,6 +743,86 @@ mod tests { assert!(debug.contains("OpenCodeHook")); } + // Source timestamps apply uniformly across all hook verbs. + + #[test] + fn supplied_timestamps_are_preserved_for_every_hook_and_journal_event() { + let hook = make_hook(); + for hook_type in hook.supported_hooks() { + for (timestamp, millis, nanos) in [ + ("2026-10-25T09:26:19.589Z", 1_792_920_379_589, 589_000_000), + ( + "2026-10-25T11:26:19.589+02:00", + 1_792_920_379_589, + 589_000_000, + ), + ( + "2026-10-25T09:26:19.589123456Z", + 1_792_920_379_589, + 589_123_456, + ), + ("1970-01-01T00:00:00.001Z", 1, 1_000_000), + ("1970-01-01T00:00:00Z", 0, 0), + ("1969-12-31T23:59:59.999Z", -1, 999_000_000), + ] { + let input = serde_json::to_vec(&serde_json::json!({ + "session_id": "timestamp-source", + "timestamp": timestamp, + })) + .unwrap(); + let event = hook.parse_event(hook_type, &input).unwrap(); + assert_eq!(event.timestamp.timestamp_millis(), millis); + assert_eq!(event.timestamp.timestamp_subsec_nanos(), nanos); + assert_eq!(event.raw_json.as_ref().unwrap()["timestamp"], timestamp); + let envelope = crate::event::ProvenanceJournalEnvelope::from_turn_event( + "source-event", + 1, + 1, + &event, + ); + assert_eq!(envelope.timestamp_ms, millis); + } + } + } + + #[test] + fn missing_timestamps_keep_the_receipt_time_fallback() { + let hook = make_hook(); + for hook_type in hook.supported_hooks() { + for input in [ + br#"{"session_id":"timestamp-source"}"#.as_slice(), + br#"{"session_id":"timestamp-source","timestamp":null}"#.as_slice(), + ] { + let before = chrono::Utc::now(); + let event = hook.parse_event(hook_type, input).unwrap(); + let after = chrono::Utc::now(); + assert!((before..=after).contains(&event.timestamp)); + } + } + } + + #[test] + fn invalid_supplied_timestamps_are_not_silently_replaced() { + let hook = make_hook(); + for hook_type in hook.supported_hooks() { + for timestamp in [ + serde_json::json!("not a timestamp"), + serde_json::json!("2026-13-25T09:26:19.589Z"), + serde_json::json!(1_792_920_379_589_i64), + ] { + let input = serde_json::to_vec(&serde_json::json!({ + "session_id": "timestamp-source", + "timestamp": timestamp, + })) + .unwrap(); + assert!(matches!( + hook.parse_event(hook_type, &input), + Err(AgentError::HookParseFailed { .. }) + )); + } + } + } + // parse_event tests: session-start #[test] diff --git a/atomic-agent/src/hooks/pi.rs b/atomic-agent/src/hooks/pi.rs index 12d13b55..8b454949 100644 --- a/atomic-agent/src/hooks/pi.rs +++ b/atomic-agent/src/hooks/pi.rs @@ -60,7 +60,7 @@ use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Pi config directory name. const PI_DIR: &str = ".pi"; @@ -333,6 +333,8 @@ impl AgentHook for PiHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(self.name(), hook_type, &raw_json)?; + match hook_type { HookType::SessionStart => { let parsed: SessionStartInput = @@ -500,6 +502,7 @@ impl AgentHook for PiHook { Ok(event) } } + .map(|event| event.with_timestamp(timestamp)) } fn install(&self, _repo_root: &Path) -> AgentResult { diff --git a/atomic-agent/src/hooks/sherpa.rs b/atomic-agent/src/hooks/sherpa.rs index 73d7aaaa..fd21c8b2 100644 --- a/atomic-agent/src/hooks/sherpa.rs +++ b/atomic-agent/src/hooks/sherpa.rs @@ -74,11 +74,12 @@ use std::path::Path; +use chrono::{DateTime, Utc}; use serde::Deserialize; use crate::error::{AgentError, AgentResult}; use crate::event::{HookType, TurnEvent}; -use crate::hooks::AgentHook; +use crate::hooks::{timestamp::TimestampFormat, AgentHook}; /// The Sherpa sessions directory relative to home (`~/.sherpa/sessions/`). const SHERPA_SESSIONS_SUBDIR: &[&str] = &[".sherpa", "sessions"]; @@ -184,7 +185,7 @@ impl SherpaHook { agent: &str, hook_type: HookType, input: &[u8], - ) -> AgentResult<(SherpaHookInput, serde_json::Value)> { + ) -> AgentResult<(SherpaHookInput, serde_json::Value, DateTime)> { let raw: serde_json::Value = serde_json::from_slice(input).map_err(|e| AgentError::HookParseFailed { agent: agent.to_string(), @@ -192,6 +193,8 @@ impl SherpaHook { reason: e.to_string(), })?; + let timestamp = TimestampFormat::Rfc3339.parse(agent, hook_type, &raw)?; + let parsed: SherpaHookInput = serde_json::from_value(raw.clone()).map_err(|e| AgentError::HookParseFailed { agent: agent.to_string(), @@ -199,7 +202,7 @@ impl SherpaHook { reason: e.to_string(), })?; - Ok((parsed, raw)) + Ok((parsed, raw, timestamp)) } } @@ -220,7 +223,7 @@ impl AgentHook for SherpaHook { }); } - let (parsed, raw) = Self::parse_input(self.name(), hook_type, input)?; + let (parsed, raw, timestamp) = Self::parse_input(self.name(), hook_type, input)?; if parsed.session_id.is_empty() { return Err(AgentError::HookParseFailed { @@ -326,7 +329,7 @@ impl AgentHook for SherpaHook { } } - Ok(event) + Ok(event.with_timestamp(timestamp)) } /// Sherpa is self-managed — no config file to write. diff --git a/atomic-agent/src/hooks/timestamp.rs b/atomic-agent/src/hooks/timestamp.rs new file mode 100644 index 00000000..65fb8163 --- /dev/null +++ b/atomic-agent/src/hooks/timestamp.rs @@ -0,0 +1,66 @@ +//! Timestamp encodings declared by hook adapters, never inferred from magnitude. + +use chrono::{DateTime, Utc}; +use serde_json::Value; + +use crate::error::{AgentError, AgentResult}; +use crate::event::HookType; + +/// Supported wire encodings for the top-level hook `timestamp` field. +#[derive(Clone, Copy, Debug)] +pub(super) enum TimestampFormat { + Rfc3339, + /// Cline's hook factory emits `Date.now().toString()`. + UnixMillisString, + /// Copilot's camelCase hooks emit epoch milliseconds; its VS Code-compatible + /// hooks emit ISO timestamps. The JSON type distinguishes the wire formats. + Rfc3339OrUnixMillis, +} + +impl TimestampFormat { + /// Capture receipt time only when the source omits its timestamp. Call this + /// before adapter-specific normalization so user/tool data cannot supply it. + pub(super) fn parse( + self, + agent: &str, + hook_type: HookType, + raw: &Value, + ) -> AgentResult> { + let Some(value) = raw.get("timestamp").filter(|value| !value.is_null()) else { + return Ok(Utc::now()); + }; + + let timestamp = match self { + Self::Rfc3339 => parse_rfc3339(value), + Self::UnixMillisString => value + .as_str() + .and_then(|value| value.parse::().ok()) + .and_then(DateTime::from_timestamp_millis), + Self::Rfc3339OrUnixMillis => match value { + Value::String(_) => parse_rfc3339(value), + Value::Number(_) => value.as_i64().and_then(DateTime::from_timestamp_millis), + _ => None, + }, + }; + + timestamp.ok_or_else(|| AgentError::HookParseFailed { + agent: agent.to_string(), + hook_type: hook_type.as_str().to_string(), + reason: match self { + Self::Rfc3339 => "timestamp must be an RFC-3339 string", + Self::UnixMillisString => { + "timestamp must be a decimal epoch-millisecond string within the supported UTC range" + } + Self::Rfc3339OrUnixMillis => { + "timestamp must be an RFC-3339 string or integer epoch milliseconds within the supported UTC range" + } + }.to_string(), + }) + } +} + +fn parse_rfc3339(value: &Value) -> Option> { + DateTime::parse_from_rfc3339(value.as_str()?) + .ok() + .map(|timestamp| timestamp.with_timezone(&Utc)) +} diff --git a/atomic-agent/tests/hook_timestamps.rs b/atomic-agent/tests/hook_timestamps.rs new file mode 100644 index 00000000..e5b74bed --- /dev/null +++ b/atomic-agent/tests/hook_timestamps.rs @@ -0,0 +1,253 @@ +//! Source-time contracts for every registered hook adapter. + +use atomic_agent::error::AgentError; +use atomic_agent::event::{HookType, ProvenanceJournalEnvelope}; +use atomic_agent::hooks::{AgentHook, AgentRegistry}; +use chrono::Utc; +use serde_json::{json, Value}; + +fn input(timestamp: Option) -> Vec { + let mut raw = json!({ + "session_id": "source-time", + "conversation_id": "source-time", + "taskId": "source-time", + "thread_id": "source-time", + "prompt": "Keep the source time", + "tool_name": "read", + "tool_use_id": "tool-1", + // These are user data, not the hook envelope's timestamp. + "tool_input": {"timestamp": "not an event timestamp"}, + "extra": {"timestamp": "not an event timestamp"}, + }); + if let Some(timestamp) = timestamp { + raw["timestamp"] = timestamp; + } + serde_json::to_vec(&raw).unwrap() +} + +fn source_timestamps(agent: &str) -> Vec { + match agent { + "copilot" => vec![ + json!(1_792_920_379_589_i64), + json!("2026-10-25T09:26:19.589Z"), + ], + "cline" => vec![json!("1792920379589")], + _ => vec![json!("2026-10-25T09:26:19.589Z")], + } +} + +fn for_each_hook(mut test: impl FnMut(&dyn AgentHook, HookType)) { + let registry = AgentRegistry::with_defaults(); + for name in registry.list() { + let agent = registry.require(name).unwrap(); + for hook_type in agent.supported_hooks() { + test(agent, hook_type); + } + } +} + +#[test] +fn every_adapter_preserves_source_time_in_events_and_journal_envelopes() { + for_each_hook(|agent, hook_type| { + for timestamp in source_timestamps(agent.name()) { + let event = agent + .parse_event(hook_type, &input(Some(timestamp.clone()))) + .unwrap_or_else(|error| panic!("{} {hook_type}: {error}", agent.name())); + assert_eq!( + event.timestamp.timestamp_millis(), + 1_792_920_379_589, + "{} {hook_type}", + agent.name() + ); + assert_eq!( + event.raw_json.as_ref().unwrap()["timestamp"], + timestamp, + "{} {hook_type}: raw timestamp was rewritten", + agent.name() + ); + let envelope = ProvenanceJournalEnvelope::from_turn_event("source-event", 1, 1, &event); + assert_eq!( + envelope.timestamp_ms, + 1_792_920_379_589, + "{} {hook_type}: journal lost source time", + agent.name() + ); + } + }); +} + +#[test] +fn every_adapter_uses_receipt_time_for_missing_or_null_timestamps_only() { + for_each_hook(|agent, hook_type| { + for timestamp in [None, Some(Value::Null)] { + let before = Utc::now(); + let event = agent + .parse_event(hook_type, &input(timestamp)) + .unwrap_or_else(|error| panic!("{} {hook_type}: {error}", agent.name())); + let after = Utc::now(); + assert!( + (before..=after).contains(&event.timestamp), + "{} {hook_type}: missing timestamp did not use receipt time", + agent.name() + ); + } + }); +} + +#[test] +fn every_adapter_rejects_malformed_supplied_timestamps_with_context() { + for_each_hook(|agent, hook_type| { + for timestamp in [ + json!(""), + json!("not a timestamp"), + json!("2026-13-25T09:26:19.589Z"), + json!(true), + json!({}), + json!([]), + ] { + let error = agent + .parse_event(hook_type, &input(Some(timestamp.clone()))) + .expect_err("invalid source time must not silently become receipt time"); + match error { + AgentError::HookParseFailed { + agent: name, + hook_type: kind, + reason, + } => { + assert_eq!(name, agent.name()); + assert_eq!(kind, hook_type.as_str()); + assert!( + reason.contains("timestamp"), + "missing timestamp context: {reason}" + ); + } + error => panic!( + "{} {hook_type} {timestamp}: unexpected error {error}", + agent.name() + ), + } + } + }); +} + +#[test] +fn rfc3339_adapters_preserve_offsets_and_submillisecond_precision() { + for_each_hook(|agent, hook_type| { + if agent.name() == "cline" { + return; + } + for timestamp in [ + "2026-10-25T11:26:19.589123456+02:00", + "2026-10-25T09:26:19.589123456Z", + ] { + let event = agent + .parse_event(hook_type, &input(Some(json!(timestamp)))) + .unwrap(); + assert_eq!( + event.timestamp.timestamp_millis(), + 1_792_920_379_589, + "{} {hook_type}", + agent.name() + ); + assert_eq!( + event.timestamp.timestamp_subsec_nanos(), + 589_123_456, + "{} {hook_type}", + agent.name() + ); + } + }); +} + +#[test] +fn explicit_epoch_milliseconds_are_never_guessed_from_magnitude() { + let registry = AgentRegistry::with_defaults(); + for name in ["copilot", "cline"] { + let agent = registry.require(name).unwrap(); + for hook_type in agent.supported_hooks() { + for millis in [-1_i64, 0, 1, 1_700_000_000, 1_792_920_379_589] { + let timestamp = if name == "cline" { + json!(millis.to_string()) + } else { + json!(millis) + }; + let event = agent + .parse_event(hook_type, &input(Some(timestamp))) + .unwrap(); + assert_eq!( + event.timestamp.timestamp_millis(), + millis, + "{name} {hook_type}" + ); + let envelope = + ProvenanceJournalEnvelope::from_turn_event("source-event", 1, 1, &event); + assert_eq!(envelope.timestamp_ms, millis, "{name} {hook_type}"); + } + } + } +} + +#[test] +fn epoch_adapters_reject_overflow_and_nonintegral_values() { + let registry = AgentRegistry::with_defaults(); + for name in ["copilot", "cline"] { + let agent = registry.require(name).unwrap(); + for hook_type in agent.supported_hooks() { + for value in [json!(i64::MAX), json!(u64::MAX), json!(1.5)] { + let timestamp = if name == "cline" { + json!(value.to_string()) + } else { + value + }; + assert!( + matches!( + agent.parse_event(hook_type, &input(Some(timestamp))), + Err(AgentError::HookParseFailed { .. }) + ), + "{name} {hook_type}" + ); + } + } + } +} + +#[test] +fn adapters_reject_timestamp_representations_outside_their_wire_contract() { + for_each_hook(|agent, hook_type| { + let unsupported = match agent.name() { + "copilot" => json!("1792920379589"), // Not a documented Copilot string encoding. + "cline" => json!("2026-10-25T09:26:19.589Z"), // Cline strings are epoch milliseconds. + _ => json!(1_792_920_379_589_i64), // RFC-3339 contracts do not guess numeric units. + }; + assert!( + matches!( + agent.parse_event(hook_type, &input(Some(unsupported))), + Err(AgentError::HookParseFailed { .. }) + ), + "{} {hook_type}", + agent.name() + ); + }); +} + +#[test] +fn every_adapter_keeps_empty_and_malformed_json_errors() { + for_each_hook(|agent, hook_type| { + assert!( + matches!( + agent.parse_event(hook_type, b""), + Err(AgentError::HookInputEmpty { .. }) + ), + "{} {hook_type}", + agent.name() + ); + assert!( + matches!( + agent.parse_event(hook_type, b"not json"), + Err(AgentError::HookParseFailed { .. }) + ), + "{} {hook_type}", + agent.name() + ); + }); +}