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
43 changes: 43 additions & 0 deletions atomic-agent/src/turn/orchestrator/attestation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,49 @@ impl TurnOrchestrator {
// unattested operation and no durable refusal (review R3/R6 probe).
match repo.save_attestation(&attestation) {
Ok(hash) => {
// CB-12B: a remote sandbox's owner never sees its cache. Hand
// the attestation — and the session state file its MAC
// signature verifies under — to the repository, or every
// managed change this session recorded fails the owner's
// publication gate with `MissingAttestation` (its gate reads
// the key from the owner's `.atomic/sessions/<id>.json`,
// which never leaves the sandbox any other way). A
// DID-signed attestation rides without a MAC key too: the
// host may resolve DID keys later, and signature policy is
// not the transport's to decide. Failure is a typed error —
// an unattested session is exactly the failure mode this
// submission exists to prevent (review R3/R6).
if repo.is_remote_sandbox() {
let bytes = attestation.serialize().map_err(|e| {
crate::error::AgentError::AttestationFailed {
session_id: session.session_id.clone(),
reason: format!(
"failed to serialize the attestation for the owner: {e}"
),
}
})?;
// Exactly the JSON the session store writes — the owner
// files it verbatim where its gate reads it.
let session_json = serde_json::to_string_pretty(&*session).map_err(|e| {
crate::error::AgentError::AttestationFailed {
session_id: session.session_id.clone(),
reason: format!(
"failed to serialize the session state for the owner: {e}"
),
}
})?;
repo.submit_remote_sandbox_attestation(
&session.session_id,
&bytes,
&session_json,
)
.map_err(|e| {
crate::error::AgentError::AttestationFailed {
session_id: session.session_id.clone(),
reason: format!("failed to submit the attestation to the owner: {e}"),
}
})?;
}
log::info!(
"Created signed attestation {} for session {} ({}{} changes, {} models, +{} -{}, wall: {})",
hash.to_base32(),
Expand Down
11 changes: 11 additions & 0 deletions atomic-agent/src/turn/orchestrator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,17 @@ pub struct JournalTurnStatus {
pub provenance_id: u64,
pub generation: u64,
pub lifecycle: JournalTurnLifecycle,
/// The change hashes this turn's checkpoint claim explains — the
/// durable record of what the turn recorded. A resumed session's
/// fresh local state adopts these so its attestation knows what the
/// session's earlier turns already covered (and can chain to them).
/// Empty for a turn that never reached its checkpoint claim.
pub checkpoint_change_hashes: Vec<Hash>,
/// The provenance graph hash this turn published (`final_hash`) — the
/// chain link a resumed round's checkpoint needs when its local ledger
/// read (a remote sandbox's cache) holds no previous turn. `None` for
/// a turn that never bound its graph.
pub final_provenance_hash: Option<Hash>,
}

/// Committed provenance-journal boundary supplied by the CLI owner client.
Expand Down
34 changes: 33 additions & 1 deletion atomic-agent/src/turn/orchestrator/provenance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -911,14 +911,46 @@ impl TurnOrchestrator {
}
})?
};
let (previous_provenance, ledger_turn_number) = ledger
let (mut previous_provenance, ledger_turn_number) = ledger
.map(|(_, turns)| {
(
turns.last().map(|turn| turn.provenance_hash),
turns.len() as u32,
)
})
.unwrap_or((None, 0));
// CB-12B: a resumed round runs in a NEW sandbox whose cache holds
// no session turns, so the ledger read above yields no chain link
// — and the owner would refuse the checkpoint's append as
// non-contiguous ("turn N is not an append"). The durable journal
// (reachable through the sink's provenance RPCs, which a sandbox's
// cache does not shadow) knows the session's previous turn and its
// published graph hash: derive the link from there. A genuinely
// fresh session has no previous turn anywhere and stays unchained.
if previous_provenance.is_none() {
if let Some(sink) = &self.journal_sink {
let mut probe = session.turn_count.max(1);
while previous_provenance.is_none() && probe > 0 {
match sink.turn_status(session_id, probe) {
Ok(Some(status)) => {
previous_provenance = status.final_provenance_hash;
}
Ok(None) => break,
Err(error) => {
log::debug!(
"Could not probe the durable journal for session {} turn \
{} while chaining the checkpoint: {} (non-fatal)",
session_id,
probe,
error
);
break;
}
}
probe -= 1;
}
}
}
let source = super::JournalCheckpointSource {
agent_name: session.agent_name.clone(),
agent_display_name: session.agent_display_name.clone(),
Expand Down
138 changes: 138 additions & 0 deletions atomic-agent/src/turn/orchestrator/session_start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ impl TurnOrchestrator {
}
};

// CB-12B: a resumed dispatch creates a fresh local session state —
// the previous round ran in a different (since-destroyed) sandbox,
// so the session JSON never carried over. Adopt the durable history
// from the repository's session ledger before anything else runs.
self.hydrate_session_from_durable_ledger(&mut session)?;

// Only sessions CREATED here get the run stamp — the early return
// above keeps pre-existing sessions out of the run's attribution.
if let Some(stamp) = self.managed_stamp() {
Expand Down Expand Up @@ -379,6 +385,133 @@ impl TurnOrchestrator {
Ok(DispatchResult::new(session_id, session.phase).with_message(message))
}

/// Hydrate a freshly created session from the durable session ledger.
///
/// A resumed dispatch starts a fresh local session state: the previous
/// round ran in a different (since-destroyed) sandbox, so
/// `.atomic/sessions/<id>.json` — the runtime fallback — is gone, and a
/// session created for the same id starts at zero turns with no
/// recorded changes. The DURABLE evidence of the previous round
/// survives in the repository's session ledger (a remote sandbox's
/// ledger lives with its owner), so that is what a fresh session for an
/// existing id must adopt:
///
/// - `turn_count` — the number of published ledger turns — so the next
/// turn numbers past the durable history instead of colliding with
/// the previous round's journal turn. A colliding reservation hits
/// the previous checkpoint's `ProvenanceCheckpointConflict`, the
/// turn-end hook fails BEFORE its session save, and the round's
/// recorded change hashes — and with them its same-session
/// attestation — are lost;
/// - `recorded_change_hashes` — each published turn's changes — so the
/// session-end attestation knows what the earlier rounds of this
/// same session already covered, attests only the new round's
/// changes, and chains to the session's latest attestation via
/// `previous_attestation`.
///
/// A session id with no durable ledger (a genuinely fresh session) is
/// left untouched. Best-effort on read failures, matching
/// [`Self::sync_session_lifecycle`]: the JSON state remains the
/// runtime fallback either way.
pub(crate) fn hydrate_session_from_durable_ledger(
&self,
session: &mut AgentSession,
) -> AgentResult<()> {
// The journal sink reaches the durable owner store wherever the
// session runs — in a remote sandbox the provenance RPCs carry it
// to the repository's owner (the local cache holds no journal).
// Probe upward from the local count while durable turns exist:
// each answered turn is history this same session already
// published, so adopt its number and its checkpoint's changes.
if let Some(sink) = &self.journal_sink {
let mut turn_number = session.turn_count.saturating_add(1);
loop {
match sink.turn_status(&session.session_id, turn_number) {
Ok(Some(status)) => {
log::info!(
"Resumed session {}: durable journal turn {} exists ({:?}) — \
adopting it into a fresh local state",
session.session_id,
turn_number,
status.lifecycle,
);
session.turn_count = turn_number;
for hash in status.checkpoint_change_hashes {
if !session.recorded_change_hashes.contains(&hash) {
session.recorded_change_hashes.push(hash);
}
}
turn_number = turn_number.saturating_add(1);
}
Ok(None) => break,
Err(error) => {
log::debug!(
"Could not probe the durable journal for session {} turn {}: \
{} (non-fatal)",
session.session_id,
turn_number,
error
);
break;
}
}
}
}

// The repository's session ledger is the authoritative local
// record; where the journal is remote (a sandbox's cache) it holds
// no turns and this is a no-op, and where it is local it is the
// source of truth for a resumed same-machine session.
let repo = match atomic_repository::Repository::open_readonly_wait(
&self.repo_root,
wait_budget::database_wait(),
) {
Ok(repo) => repo,
Err(error) => {
log::debug!(
"Could not open the repository to hydrate session {} from its \
durable ledger: {} (non-fatal)",
session.session_id,
error,
);
return Ok(());
}
};
let ledger = match repo.get_session_ledger(&session.session_id) {
Ok(ledger) => ledger,
Err(error) => {
log::warn!(
"Could not read the durable session ledger for {}: {} (non-fatal)",
session.session_id,
error
);
return Ok(());
}
};
let Some((_record, turns)) = ledger else {
return Ok(());
};
if turns.is_empty() {
return Ok(());
}
let durable_turn_count = turns.len() as u32;
if durable_turn_count > session.turn_count {
log::info!(
"Resumed session {}: adopting {} durable ledger turn(s) into a \
fresh local state",
session.session_id,
durable_turn_count,
);
session.turn_count = durable_turn_count;
}
for hash in turns.iter().flat_map(|turn| turn.change_hashes.iter()) {
if !session.recorded_change_hashes.contains(hash) {
session.recorded_change_hashes.push(*hash);
}
}
Ok(())
}

/// Best-effort lifecycle reconciliation into the Atomic session ledger.
///
/// `ended_at: None` marks the session active (clearing a stale end
Expand Down Expand Up @@ -586,6 +719,11 @@ impl TurnOrchestrator {
}
}

// CB-12B: a resumed dispatch has fresh local state — adopt
// the durable ledger before persisting, exactly as
// `handle_session_start` does.
self.hydrate_session_from_durable_ledger(&mut session)?;

self.coordinate_session_view(&session.view_name)?;

// Persist so subsequent hooks find this session.
Expand Down
Loading
Loading