1use 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. Use the historical state below for continuity, and do not repeat completed work unless verification requires it.\n\n";
10pub const RETAINED_OPEN: &str = "\n\n<retained_recent_context>\n";
11pub const RETAINED_CLOSE: &str = "</retained_recent_context>";
12const MARKER_OPEN: &str = "\n\n<mj_handoff_state>";
13const MARKER_CLOSE: &str = "</mj_handoff_state>";
14const VERSION: u32 = 1;
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct HandoffState {
18 pub version: u32,
19 pub through_position: u64,
20 pub prefix_sha256: String,
21 pub summary: String,
22}
23
24#[derive(Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26struct Marker {
27 version: u32,
28 through_position: u64,
29 prefix_sha256: String,
30}
31
32impl HandoffState {
33 pub fn capture(snapshot: &CanonicalSessionSnapshot, summary: String) -> Result<Self> {
34 let through_position = snapshot.event_frontier.max(
35 snapshot
36 .transcript
37 .iter()
38 .map(|item| item.position)
39 .max()
40 .unwrap_or(0),
41 );
42 Ok(Self {
43 version: VERSION,
44 through_position,
45 prefix_sha256: prefix_digest(snapshot, through_position)?,
46 summary,
47 })
48 }
49
50 pub fn validate(&self, snapshot: &CanonicalSessionSnapshot) -> Result<bool> {
51 if self.version != VERSION || snapshot.current_context_start() > self.through_position {
52 return Ok(false);
53 }
54 Ok(self.prefix_sha256 == prefix_digest(snapshot, self.through_position)?)
55 }
56
57 pub fn attach_to_text(&self, text: &str) -> Result<String> {
58 let summary = model_body(text).context("not a complete model handoff")?;
59 ensure!(
60 summary == self.summary,
61 "handoff body differs from captured state"
62 );
63 let marker = Marker {
64 version: self.version,
65 through_position: self.through_position,
66 prefix_sha256: self.prefix_sha256.clone(),
67 };
68 Ok(format!(
69 "{text}{MARKER_OPEN}{}{MARKER_CLOSE}",
70 serde_json::to_string(&marker)?
71 ))
72 }
73
74 pub fn from_handoff_text(text: &str) -> Option<Self> {
75 let (body_text, marker) = text.rsplit_once(MARKER_OPEN)?;
76 let marker: Marker = serde_json::from_str(marker.strip_suffix(MARKER_CLOSE)?).ok()?;
77 if marker.version != VERSION
78 || marker.prefix_sha256.len() != 64
79 || !marker
80 .prefix_sha256
81 .bytes()
82 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
83 {
84 return None;
85 }
86 let summary = model_body(body_text)?;
87 Some(Self {
88 version: marker.version,
89 through_position: marker.through_position,
90 prefix_sha256: marker.prefix_sha256,
91 summary: summary.to_owned(),
92 })
93 }
94}
95
96pub fn encode_handoff(snapshot: &CanonicalSessionSnapshot, text: &str) -> Result<String> {
97 let summary = model_body(text).context("not a complete model handoff")?;
98 HandoffState::capture(snapshot, summary.to_owned())?.attach_to_text(text)
99}
100
101pub fn parse_handoff(text: &str) -> Option<HandoffState> {
102 HandoffState::from_handoff_text(text)
103}
104
105pub fn reusable_handoff(snapshot: &CanonicalSessionSnapshot) -> Option<HandoffState> {
106 let value = snapshot
107 .session
108 .configuration
109 .values
110 .get(HANDOFF_STATE_KEY)?;
111 let state: HandoffState = match serde_json::from_value(value.clone()) {
112 Ok(state) => state,
113 Err(error) => {
114 tracing::warn!(%error, "stored handoff state is malformed");
115 return None;
116 }
117 };
118 match state.validate(snapshot) {
119 Ok(true) => Some(state),
120 Ok(false) => None,
121 Err(error) => {
122 tracing::warn!(%error, "could not validate stored handoff state");
123 None
124 }
125 }
126}
127
128fn model_body(text: &str) -> Option<&str> {
129 let body = text.strip_prefix(MODEL_HANDOFF_OPENING)?;
130 let (summary, retained) = body.rsplit_once(RETAINED_OPEN)?;
131 if summary.trim().is_empty() || !retained.ends_with(RETAINED_CLOSE) {
132 return None;
133 }
134 Some(body)
135}
136
137fn prefix_digest(snapshot: &CanonicalSessionSnapshot, through_position: u64) -> Result<String> {
138 let start = snapshot.current_context_start();
139 let mut hash = Sha256::new();
140 hash.update(b"mj-handoff-prefix-v1\0");
141 hash.update(start.to_le_bytes());
142 for item in snapshot
143 .transcript
144 .iter()
145 .filter(|item| item.position > start && item.position <= through_position)
146 {
147 hash.update(item.position.to_le_bytes());
148 hash.update((item.stable_id.len() as u64).to_le_bytes());
149 hash.update(item.stable_id.as_bytes());
150 let mut body = item.body.clone();
151 match &mut body {
152 CanonicalTranscriptBody::Agent { streaming, .. }
153 | CanonicalTranscriptBody::Thought { streaming, .. } => *streaming = false,
154 _ => {}
155 }
156 let encoded = serde_json::to_vec(&body)?;
157 hash.update((encoded.len() as u64).to_le_bytes());
158 hash.update(encoded);
159 }
160 Ok(mj_core::hex::lower_hex(hash.finalize()))
161}