Skip to main content

mj_transcript/
handoff.rs

1//! Durable provenance for a hidden, model-produced handoff.
2
3use anyhow::{Context, Result, ensure};
4use mj_core::archive::{CanonicalSessionSnapshot, CanonicalTranscriptBody};
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7
8pub const HANDOFF_STATE_KEY: &str = "mj_handoff_state";
9pub const MODEL_HANDOFF_OPENING: &str = "You are continuing a coding session previously run by another ACP harness. The restored workspace is authoritative. Your current harness's tools and system instructions are authoritative; ignore historical notes about missing tools on the prior harness. Use the historical state below for continuity, and do not repeat completed work unless verification requires it.\n\n";
10const LEGACY_MODEL_HANDOFF_OPENING: &str = "You are continuing a coding session previously run by another ACP harness. The restored workspace is authoritative. Use the historical state below for continuity, and do not repeat completed work unless verification requires it.\n\n";
11pub const RETAINED_OPEN: &str = "\n\n<retained_recent_context>\n";
12pub const RETAINED_CLOSE: &str = "</retained_recent_context>";
13const MARKER_OPEN: &str = "\n\n<mj_handoff_state>";
14const MARKER_CLOSE: &str = "</mj_handoff_state>";
15const VERSION: u32 = 1;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct HandoffState {
19    pub version: u32,
20    pub through_position: u64,
21    pub prefix_sha256: String,
22    pub summary: String,
23}
24
25#[derive(Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27struct Marker {
28    version: u32,
29    through_position: u64,
30    prefix_sha256: String,
31}
32
33impl HandoffState {
34    pub fn capture(snapshot: &CanonicalSessionSnapshot, summary: String) -> Result<Self> {
35        let through_position = snapshot.event_frontier.max(
36            snapshot
37                .transcript
38                .iter()
39                .map(|item| item.position)
40                .max()
41                .unwrap_or(0),
42        );
43        Ok(Self {
44            version: VERSION,
45            through_position,
46            prefix_sha256: prefix_digest(snapshot, through_position)?,
47            summary,
48        })
49    }
50
51    pub fn validate(&self, snapshot: &CanonicalSessionSnapshot) -> Result<bool> {
52        if self.version != VERSION || snapshot.current_context_start() > self.through_position {
53            return Ok(false);
54        }
55        Ok(self.prefix_sha256 == prefix_digest(snapshot, self.through_position)?)
56    }
57
58    pub fn attach_to_text(&self, text: &str) -> Result<String> {
59        let summary = model_body(text).context("not a complete model handoff")?;
60        ensure!(
61            summary == self.summary,
62            "handoff body differs from captured state"
63        );
64        let marker = Marker {
65            version: self.version,
66            through_position: self.through_position,
67            prefix_sha256: self.prefix_sha256.clone(),
68        };
69        Ok(format!(
70            "{text}{MARKER_OPEN}{}{MARKER_CLOSE}",
71            serde_json::to_string(&marker)?
72        ))
73    }
74
75    pub fn from_handoff_text(text: &str) -> Option<Self> {
76        let (body_text, marker) = text.rsplit_once(MARKER_OPEN)?;
77        let marker: Marker = serde_json::from_str(marker.strip_suffix(MARKER_CLOSE)?).ok()?;
78        if marker.version != VERSION
79            || marker.prefix_sha256.len() != 64
80            || !marker
81                .prefix_sha256
82                .bytes()
83                .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
84        {
85            return None;
86        }
87        let summary = model_body(body_text)?;
88        Some(Self {
89            version: marker.version,
90            through_position: marker.through_position,
91            prefix_sha256: marker.prefix_sha256,
92            summary: summary.to_owned(),
93        })
94    }
95}
96
97pub fn encode_handoff(snapshot: &CanonicalSessionSnapshot, text: &str) -> Result<String> {
98    let summary = model_body(text).context("not a complete model handoff")?;
99    HandoffState::capture(snapshot, summary.to_owned())?.attach_to_text(text)
100}
101
102pub fn parse_handoff(text: &str) -> Option<HandoffState> {
103    HandoffState::from_handoff_text(text)
104}
105
106pub fn reusable_handoff(snapshot: &CanonicalSessionSnapshot) -> Option<HandoffState> {
107    let value = snapshot
108        .session
109        .configuration
110        .values
111        .get(HANDOFF_STATE_KEY)?;
112    let state: HandoffState = match serde_json::from_value(value.clone()) {
113        Ok(state) => state,
114        Err(error) => {
115            tracing::warn!(%error, "stored handoff state is malformed");
116            return None;
117        }
118    };
119    match state.validate(snapshot) {
120        Ok(true) => Some(state),
121        Ok(false) => None,
122        Err(error) => {
123            tracing::warn!(%error, "could not validate stored handoff state");
124            None
125        }
126    }
127}
128
129fn model_body(text: &str) -> Option<&str> {
130    let body = text
131        .strip_prefix(MODEL_HANDOFF_OPENING)
132        .or_else(|| text.strip_prefix(LEGACY_MODEL_HANDOFF_OPENING))?;
133    let (summary, retained) = body.rsplit_once(RETAINED_OPEN)?;
134    if summary.trim().is_empty() || !retained.ends_with(RETAINED_CLOSE) {
135        return None;
136    }
137    Some(body)
138}
139
140fn prefix_digest(snapshot: &CanonicalSessionSnapshot, through_position: u64) -> Result<String> {
141    let start = snapshot.current_context_start();
142    let mut hash = Sha256::new();
143    hash.update(b"mj-handoff-prefix-v1\0");
144    hash.update(start.to_le_bytes());
145    for item in snapshot
146        .transcript
147        .iter()
148        .filter(|item| item.position > start && item.position <= through_position)
149    {
150        hash.update(item.position.to_le_bytes());
151        hash.update((item.stable_id.len() as u64).to_le_bytes());
152        hash.update(item.stable_id.as_bytes());
153        let mut body = item.body.clone();
154        match &mut body {
155            CanonicalTranscriptBody::Agent { streaming, .. }
156            | CanonicalTranscriptBody::Thought { streaming, .. } => *streaming = false,
157            _ => {}
158        }
159        let encoded = serde_json::to_vec(&body)?;
160        hash.update((encoded.len() as u64).to_le_bytes());
161        hash.update(encoded);
162    }
163    Ok(mj_core::hex::lower_hex(hash.finalize()))
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn parse_handoff_accepts_the_legacy_model_opening() {
172        let text = concat!(
173            "You are continuing a coding session previously run by another ACP harness. ",
174            "The restored workspace is authoritative. Use the historical state below for ",
175            "continuity, and do not repeat completed work unless verification requires it.\n\n",
176            "Previous work\n\n<retained_recent_context>\nrecent work</retained_recent_context>",
177            "\n\n<mj_handoff_state>{\"version\":1,\"through_position\":7,",
178            "\"prefix_sha256\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}",
179            "</mj_handoff_state>"
180        );
181        let state = parse_handoff(text).unwrap();
182        assert_eq!(state.through_position, 7);
183        assert_eq!(
184            state.summary,
185            "Previous work\n\n<retained_recent_context>\nrecent work</retained_recent_context>"
186        );
187    }
188}