Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions atomic-agent/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use std::path::Path;

use atomic_core::change::provenance_graph::{ProvenanceGraph, ProvenanceNodeKind};
use atomic_core::types::Base32;
use chrono::{DateTime, Utc};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::Value;

Expand Down Expand Up @@ -182,7 +182,8 @@ pub struct RelatedRef {
///
/// This function never fails; any missing data is silently omitted.
pub fn to_agent_trace_record(graph: &ProvenanceGraph, root: &Path) -> TraceRecord {
let timestamp = DateTime::<Utc>::from_timestamp(graph.timestamp, 0)
let timestamp = graph
.timestamp_datetime()
.unwrap_or_else(Utc::now)
.to_rfc3339();

Expand Down Expand Up @@ -603,6 +604,24 @@ mod tests {
.build()
}

#[test]
fn trace_timestamp_preserves_milliseconds_and_accepts_legacy_seconds() {
let directory = tempfile::tempdir().unwrap();
for (raw, expected) in [
(1_792_920_379, "2026-10-25T09:26:19+00:00"),
(1_792_920_379_589, "2026-10-25T09:26:19.589+00:00"),
] {
let graph = ProvenanceGraph::builder("timestamp-compat", "agent")
.timestamp(raw)
.build();
assert_eq!(
to_agent_trace_record(&graph, directory.path()).timestamp,
expected
);
assert_eq!(graph.timestamp, raw);
}
}

#[test]
fn test_record_has_required_fields() {
let graph = sherpa_graph();
Expand Down
2 changes: 2 additions & 0 deletions atomic-agent/src/provenance/accumulator/append.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ impl ProvenanceAccumulator {

/// Append a goal node (human prompt).
///
/// `timestamp` is Unix epoch milliseconds, as on every accumulator node.
///
/// Returns the new node's ID.
pub fn append_goal(&mut self, prompt: &str, timestamp: i64) -> String {
let summary = truncate_prompt(prompt, MAX_GOAL_PROMPT_LEN);
Expand Down
2 changes: 1 addition & 1 deletion atomic-agent/src/provenance/accumulator/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl ProvenanceAccumulator {
.nodes(nodes)
.edges(edges)
.changes_explained(changes_explained.to_vec())
.timestamp(timestamp);
.timestamp_millis(timestamp);
if let Some(previous) = previous {
builder = builder.previous(previous);
}
Expand Down
27 changes: 27 additions & 0 deletions atomic-agent/src/provenance/accumulator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,33 @@ fn test_from_serialized_rebuilds_commitments_since_patch() {

// ---- to_provenance_graph conversion ----

#[test]
fn graph_header_preserves_explicit_milliseconds_without_unit_guessing() {
for timestamp_ms in [-1001, 0, 1000, 1_792_920_379_589] {
let mut accumulator = ProvenanceAccumulator::new("timestamp-millis");
accumulator.append_goal("Preserve event milliseconds verbatim", timestamp_ms);
let graph = accumulator
.prepare_provenance_graph("agent", "Agent", "vendor", &[])
.graph;
assert_eq!(graph.timestamp, timestamp_ms);
assert_eq!(graph.nodes[0].timestamp, timestamp_ms);
}
}

#[test]
fn graph_header_uses_only_the_new_turns_millisecond_timestamps() {
let mut accumulator = ProvenanceAccumulator::new("timestamp-delta");
accumulator.append_goal("first", 1_792_920_379_589);
accumulator.to_provenance_graph("agent", "Agent", "vendor", &[]);
// A skewed clock must not reuse the previous turn's later timestamp.
accumulator.append_goal("second", 1_792_920_379_100);
let graph = accumulator
.prepare_provenance_graph("agent", "Agent", "vendor", &[])
.graph;
assert_eq!(graph.timestamp, 1_792_920_379_100);
assert_eq!(graph.nodes.len(), 1);
}

#[test]
fn test_to_provenance_graph_basic() {
use atomic_core::change::provenance_graph as pg;
Expand Down
9 changes: 5 additions & 4 deletions atomic-agent/src/record/provenance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub(crate) fn build_turn_provenance(options: &TurnRecordOptions<'_>) -> Provenan
_ => PromptContent::None,
};

let timestamp = options.event.timestamp.timestamp();
let timestamp = options.event.timestamp.timestamp_millis();

// Extract enriched metadata from the raw JSON payload sent by the plugin.
// The plugin accumulates data across all events within a turn and sends
Expand Down Expand Up @@ -218,9 +218,10 @@ pub(crate) fn build_turn_envelope(

let files_in_turn: Vec<String> = recorded_files.to_vec();

let session_started_at = options.session.started_at.timestamp();
let turn_ended_at = options.event.timestamp.timestamp();
let turn_started_at = turn_ended_at - (options.turn_duration_ms as i64 / 1000);
let session_started_at = options.session.started_at.timestamp_millis();
let turn_ended_at = options.event.timestamp.timestamp_millis();
let turn_started_at =
turn_ended_at.saturating_sub(i64::try_from(options.turn_duration_ms).unwrap_or(i64::MAX));

let mut builder =
SessionEnvelope::builder(&options.session.session_id, &options.session.agent_name)
Expand Down
27 changes: 24 additions & 3 deletions atomic-agent/src/record/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,11 +720,12 @@ fn test_provenance_model_fallback_unknown() {
#[test]
fn test_provenance_has_timestamp() {
let session = make_session();
let event = make_event();
let mut event = make_event();
event.timestamp = chrono::DateTime::from_timestamp_millis(1_792_920_379_589).unwrap();
let options = make_options(&session, &event);

let prov = build_turn_provenance(&options);
assert!(prov.timestamp.is_some());
assert_eq!(prov.timestamp, Some(1_792_920_379_589));
}

// build_turn_envelope tests
Expand Down Expand Up @@ -839,7 +840,27 @@ fn test_envelope_session_started_at() {
let options = make_options(&session, &event);

let env = build_turn_envelope(&options, &[]);
assert_eq!(env.session_started_at, session.started_at.timestamp());
assert_eq!(
env.session_started_at,
session.started_at.timestamp_millis()
);
}

#[test]
fn envelope_timing_preserves_subsecond_duration() {
let session = make_session();
let mut event = make_event();
event.timestamp = chrono::DateTime::from_timestamp_millis(1_792_920_379_589).unwrap();
let mut options = make_options(&session, &event);
options.turn_duration_ms = 489;
let envelope = build_turn_envelope(&options, &[]);
assert_eq!(envelope.turn_ended_at, 1_792_920_379_589);
assert_eq!(envelope.turn_started_at, 1_792_920_379_100);
assert_eq!(envelope.turn_duration_ms, 489);
assert_eq!(
SessionEnvelope::decode(&envelope.encode().unwrap()).unwrap(),
envelope
);
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions atomic-agent/src/turn/orchestrator/provenance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ impl TurnOrchestrator {
None => return,
};

let timestamp = event.timestamp.timestamp();
let timestamp = event.timestamp.timestamp_millis();

self.with_accumulator(session_id, |acc| {
let mut block_count = 0;
Expand Down Expand Up @@ -584,7 +584,7 @@ impl TurnOrchestrator {
return;
};

let timestamp = event.timestamp.timestamp();
let timestamp = event.timestamp.timestamp_millis();
self.with_accumulator(session_id, |acc| {
acc.append_llm_response(&response, timestamp);
true
Expand Down
2 changes: 1 addition & 1 deletion atomic-agent/src/turn/orchestrator/session_end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ impl TurnOrchestrator {

// Reconcile the Atomic session ledger: the session is now ended.
// Best-effort — the JSON file remains the runtime fallback.
let ended_at = session.ended_at.map(|t| t.timestamp());
let ended_at = session.ended_at.map(|t| t.timestamp_millis());
self.sync_session_lifecycle(&session, ended_at);

log::info!(
Expand Down
29 changes: 29 additions & 0 deletions atomic-agent/src/turn/orchestrator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,35 @@ async fn test_sandbox_turn_end_leaves_canonical_current_view_untouched() {

// TurnStart tests

#[tokio::test]
async fn fallback_goal_reasoning_and_response_use_millisecond_epochs() {
let dir = TempDir::new().unwrap();
let mut orch = make_orchestrator(&dir);
orch.dispatch(session_start_event("timestamp-fallback"))
.await
.unwrap();
let mut start = turn_start_event("timestamp-fallback", "Preserve subsecond actions");
start.timestamp = chrono::DateTime::from_timestamp_millis(1_792_920_379_100).unwrap();
orch.dispatch(start).await.unwrap();
let session = orch
.session_store
.load("timestamp-fallback")
.unwrap()
.unwrap();
let mut end = turn_end_event("timestamp-fallback");
end.timestamp = chrono::DateTime::from_timestamp_millis(1_792_920_379_589).unwrap();
end.raw_json = Some(serde_json::json!({
"reasoning_text": "Check the timestamp unit",
"response": "Done"
}));
orch.inject_reasoning_nodes("timestamp-fallback", &end);
orch.inject_response_node("timestamp-fallback", &session, &end);
let accumulator = orch.load_accumulator("timestamp-fallback").unwrap();
assert_eq!(accumulator.nodes()[0].timestamp, 1_792_920_379_100);
assert_eq!(accumulator.nodes()[1].timestamp, 1_792_920_379_589);
assert_eq!(accumulator.nodes()[2].timestamp, 1_792_920_379_589);
}

#[tokio::test]
async fn test_turn_start_transitions_to_active() {
let dir = TempDir::new().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion atomic-agent/src/turn/orchestrator/turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ impl TurnOrchestrator {
if let Some(ref prompt) = event.prompt {
if !prompt.is_empty() && self.journal_sink.is_none() {
if let Some(mut acc) = self.load_accumulator(session_id) {
acc.append_goal(prompt, event.timestamp.timestamp());
acc.append_goal(prompt, event.timestamp.timestamp_millis());
self.save_accumulator(session_id, &acc);
}
}
Expand Down
130 changes: 130 additions & 0 deletions atomic-agent/tests/provenance_timestamp_consistency.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
use atomic_agent::{
event::{ProvenanceJournalEnvelope, ProvenanceJournalEvent},
provenance::accumulator::ProvenanceAccumulator,
};
use atomic_core::{change::ProvenanceGraph, kg::iri};
use atomic_repository::Repository;

#[test]
fn journal_actions_in_one_second_preserve_milliseconds_through_the_ledger_and_kg() {
let directory = tempfile::tempdir().unwrap();
let repo = Repository::init(directory.path()).unwrap();
let goal = ProvenanceJournalEnvelope::new(
"goal",
"subsecond",
1,
1,
1_792_920_379_100,
ProvenanceJournalEvent::Goal {
prompt: "Preserve precision".into(),
},
);
let response = ProvenanceJournalEnvelope::new(
"response",
"subsecond",
1,
1,
1_792_920_379_589,
ProvenanceJournalEvent::Response {
text: "Done".into(),
},
)
.with_causal_parents(["goal"]);
let accumulator =
ProvenanceAccumulator::replay_provenance_journal(vec![response, goal]).unwrap();
let prepared = accumulator.prepare_provenance_graph("opencode", "OpenCode", "openrouter", &[]);
assert_eq!(prepared.graph.timestamp, 1_792_920_379_589);
assert_eq!(prepared.graph.nodes[0].timestamp, 1_792_920_379_100);
assert_eq!(prepared.graph.nodes[1].timestamp, 1_792_920_379_589);
assert_eq!(
prepared.graph.serialize().unwrap(),
accumulator
.prepare_provenance_graph("opencode", "OpenCode", "openrouter", &[])
.graph
.serialize()
.unwrap()
);
let hash = repo.save_provenance_graph(&prepared.graph).unwrap();
let (_, turns) = repo.get_session_ledger("subsecond").unwrap().unwrap();
assert_eq!(turns[0].timestamp, 1_792_920_379_589);
assert_eq!(turns[0].provenance_hash, hash);
let id = iri::mint_turn(&repo.project_id().unwrap(), "subsecond", 0);
let turn = repo.vault_kg_node(&id).unwrap().unwrap();
assert_eq!(
turn.metadata.unwrap()["created_at"],
"2026-10-25T09:26:19.589+00:00"
);
assert_eq!(
repo.pristine().read_txn().unwrap().kg_generation().unwrap(),
2
);
}

#[test]
fn mixed_unit_histories_keep_order_start_time_and_original_payloads() {
let directory = tempfile::tempdir().unwrap();
let repo = Repository::init(directory.path()).unwrap();
let earlier = ProvenanceGraph::builder("mixed", "agent")
.timestamp_millis(1_792_920_379_589)
.build();
let earlier_bytes = earlier.serialize().unwrap();
let earlier_hash = repo.save_provenance_graph(&earlier).unwrap();
// Import a legacy seconds record whose instant is later despite its
// smaller raw integer. Causal edges must still take priority over clocks.
let later = ProvenanceGraph::builder("mixed", "agent")
.timestamp(1_792_920_380)
.previous(earlier_hash)
.build();
let later_bytes = later.serialize().unwrap();
let later_hash = repo.save_provenance_graph(&later).unwrap();
let (record, turns) = repo.get_session_ledger("mixed").unwrap().unwrap();
assert_eq!(record.started_at, earlier.timestamp);
assert_eq!(turns[0].timestamp, earlier.timestamp);
assert_eq!(turns[1].timestamp, later.timestamp);
let graphs = repo.find_provenance_for_session("mixed").unwrap();
assert_eq!(graphs[0].0, earlier_hash);
assert_eq!(graphs[1].0, later_hash);
assert_eq!(
repo.load_provenance_graph(&earlier_hash)
.unwrap()
.serialize()
.unwrap(),
earlier_bytes
);
assert_eq!(
repo.load_provenance_graph(&later_hash)
.unwrap()
.serialize()
.unwrap(),
later_bytes
);
// Session-list sorting must compare instants, not integer magnitudes.
repo.save_provenance_graph(
&ProvenanceGraph::builder("newest", "agent")
.timestamp(1_792_920_381)
.build(),
)
.unwrap();
assert_eq!(
repo.list_session_ledgers(2).unwrap()[0].0.session_id,
"newest"
);
}

#[test]
fn empty_session_lifecycle_starts_in_milliseconds() {
let directory = tempfile::tempdir().unwrap();
let repo = Repository::init(directory.path()).unwrap();
let before = chrono::Utc::now().timestamp_millis();
repo.upsert_session_lifecycle("empty", None, None, Some(1_792_920_379_589))
.unwrap();
let after = chrono::Utc::now().timestamp_millis();
let (record, turns) = repo.get_session_ledger("empty").unwrap().unwrap();
assert!(turns.is_empty());
assert!((before..=after).contains(&record.started_at));
assert_eq!(record.ended_at, Some(1_792_920_379_589));
assert_eq!(
record.activity_datetime(&turns).unwrap().to_rfc3339(),
"2026-10-25T09:26:19.589+00:00"
);
}
4 changes: 2 additions & 2 deletions atomic-cli/src/commands/change/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ pub struct JsonChangeLedger {
/// AI vendor (e.g. "anthropic", "openai").
#[serde(skip_serializing_if = "String::is_empty")]
pub agent_vendor: String,
/// Graph creation timestamp (Unix epoch seconds).
/// Graph creation timestamp (Unix epoch milliseconds; historical values may be seconds).
pub timestamp: i64,
/// Schema profile identifier (e.g. "sherpa-trace/1.0.0"), when present.
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -487,7 +487,7 @@ pub struct JsonProvenance {
/// Temperature setting.
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Request timestamp.
/// Request timestamp (Unix epoch milliseconds; historical values may be seconds).
#[serde(skip_serializing_if = "Option::is_none")]
pub timestamp: Option<i64>,
/// Request ID from provider.
Expand Down
4 changes: 3 additions & 1 deletion atomic-cli/src/commands/provenance/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ pub(crate) fn load_graphs(
}
// Most-recent first (a change explained by >1 graph shows all; the newest
// leads). Both loaders sort/return unspecified order, so sort here.
graphs.sort_by_key(|(_, g)| std::cmp::Reverse(g.timestamp));
graphs.sort_by_key(|(_, g)| {
std::cmp::Reverse(atomic_core::types::timestamp::epoch_millis(g.timestamp))
});
Ok(graphs)
}

Expand Down
Loading
Loading