1use super::{
6 CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION, CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION,
7 CONTEXT_PACKAGE_V1_SCHEMA_VERSION, CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
8 CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION, ContextCheckpointProjectionInputV1,
9 ContextCheckpointProjectionLossReasonV1, ContextCheckpointProjectionLossV1,
10 ContextCheckpointProjectionTargetV1, ContextCheckpointV1,
11 HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION, LEGACY_HASH_HEX_LENGTH,
12 MAX_CONTEXT_CHECKPOINT_LEGACY_LOSSES, MAX_CONTEXT_CHECKPOINT_LEGACY_PAYLOAD_BYTES,
13 MAX_CONTEXT_CHECKPOINT_REQUIRED_INPUTS, MAX_LEGACY_LABEL_BYTES, parse_canonical_json,
14 projection_input_field_path, projection_input_target, validate_legacy_target_value,
15};
16use serde::{Deserialize, Deserializer, Serialize, de::Error as DeError};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum ContextCheckpointLegacyTargetV1 {
22 SessionBundle,
24 HandoffBundle,
26 Ctxpkg,
28 ContextSnapshot,
30}
31
32impl ContextCheckpointLegacyTargetV1 {
33 pub const fn all() -> [Self; 4] {
35 [
36 Self::SessionBundle,
37 Self::HandoffBundle,
38 Self::Ctxpkg,
39 Self::ContextSnapshot,
40 ]
41 }
42
43 pub const fn projection_target(self) -> ContextCheckpointProjectionTargetV1 {
45 match self {
46 Self::SessionBundle => ContextCheckpointProjectionTargetV1::SessionBundle,
47 Self::HandoffBundle => ContextCheckpointProjectionTargetV1::HandoffBundle,
48 Self::Ctxpkg => ContextCheckpointProjectionTargetV1::Ctxpkg,
49 Self::ContextSnapshot => ContextCheckpointProjectionTargetV1::ContextSnapshot,
50 }
51 }
52
53 pub const fn target_id(self) -> &'static str {
55 self.projection_target().target_id()
56 }
57
58 pub const fn schema_version(self) -> u32 {
60 match self {
61 Self::SessionBundle => CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
62 Self::HandoffBundle => HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
63 Self::Ctxpkg => CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
64 Self::ContextSnapshot => CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION,
65 }
66 }
67
68 pub fn accepts_schema_version(self, version: u32) -> bool {
72 match self {
73 Self::Ctxpkg => {
74 version == CONTEXT_PACKAGE_V1_SCHEMA_VERSION
75 || version == CONTEXT_PACKAGE_V2_SCHEMA_VERSION
76 }
77 _ => version == self.schema_version(),
78 }
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum ContextCheckpointLegacyFieldV1 {
86 Payload,
88 SourceIdentity,
90 TaskTitle,
92 Decisions,
94 Findings,
96 NextSteps,
98 DecisionObservedAt,
100 FindingObservedAt,
102 SessionId,
104 SessionRevision,
106 Evidence,
108 Files,
110 Progress,
112 TestResults,
114 ToolCalls,
116 Knowledge,
118 CuratedRefs,
120 Artifacts,
122 Workflow,
124 SessionSnapshot,
126 ActiveOverlays,
128 CarrierBinding,
130 CarrierSchemaId,
132 CarrierWorkspaceId,
134 CarrierStateDigest,
136 CarrierEnvelopeDigest,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "snake_case", deny_unknown_fields)]
143pub enum ContextCheckpointLegacyErrorV1 {
144 UnsupportedAdapterVersion { actual: u32, expected: u32 },
146 UnsupportedSourceVersion { actual: u32, expected: u32 },
148 UnsupportedTargetVersion {
150 target: ContextCheckpointLegacyTargetV1,
151 requested: u32,
152 supported: u32,
153 },
154 TargetInputsMismatch {
156 target: ContextCheckpointLegacyTargetV1,
157 inputs_target: ContextCheckpointLegacyTargetV1,
158 },
159 InvalidSource,
161 InvalidInputs {
163 field: ContextCheckpointLegacyFieldV1,
164 },
165 InputArityMismatch {
167 field: ContextCheckpointLegacyFieldV1,
168 expected: u32,
169 actual: u32,
170 },
171 LegacyCapacityExceeded {
173 field: ContextCheckpointLegacyFieldV1,
174 limit: u64,
175 actual: u64,
176 },
177 IdentityMismatch {
179 field: ContextCheckpointLegacyFieldV1,
180 },
181 MalformedSignature,
183 LossyReverseConversion {
185 field: ContextCheckpointLegacyFieldV1,
186 },
187 SemanticOverwrite {
189 field: ContextCheckpointLegacyFieldV1,
190 },
191 MissingLegacySource {
193 field: ContextCheckpointLegacyFieldV1,
194 },
195 DuplicateLegacyInput {
197 field: ContextCheckpointLegacyFieldV1,
198 },
199 InvalidLegacyPayload {
201 field: ContextCheckpointLegacyFieldV1,
202 },
203 LegacyOwnerRejected,
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
209#[serde(rename_all = "snake_case")]
210pub enum ContextCheckpointLegacyRefusalReasonV1 {
211 TargetOwnerDependency,
213 MissingSessionState,
215 MissingCarrierBinding,
217 ReverseNotRepresentable,
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
223#[serde(deny_unknown_fields)]
224pub struct ContextCheckpointLegacyRefusalV1 {
225 pub target: ContextCheckpointLegacyTargetV1,
227 pub target_schema_version: u32,
229 pub reason: ContextCheckpointLegacyRefusalReasonV1,
231 pub dependency: String,
233 pub required_inputs: Vec<ContextCheckpointProjectionInputV1>,
235}
236
237validated_deserialize!(ContextCheckpointLegacyRefusalV1 {
238 target: ContextCheckpointLegacyTargetV1,
239 target_schema_version: u32,
240 reason: ContextCheckpointLegacyRefusalReasonV1,
241 dependency: String,
242 required_inputs: Vec<ContextCheckpointProjectionInputV1>,
243});
244
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252#[serde(deny_unknown_fields)]
253pub struct ContextCheckpointLegacySourceIdentityV1 {
254 pub checkpoint_id: lean_ctx_protocol::ContextCheckpointIdV1,
255 pub tenant_id: lean_ctx_protocol::TenantId,
256 pub project_id: lean_ctx_protocol::ProjectId,
257 pub workspace_id: lean_ctx_protocol::WorkspaceId,
258 pub task_id: lean_ctx_protocol::TaskId,
259 pub plan_id: Option<lean_ctx_protocol::PlanId>,
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
264#[serde(deny_unknown_fields)]
265pub struct ContextCheckpointLegacyPayloadV1 {
266 pub adapter_schema_version: u32,
268 pub source_identity: ContextCheckpointLegacySourceIdentityV1,
270 pub target: ContextCheckpointLegacyTargetV1,
272 pub target_schema_version: u32,
274 pub canonical_json: String,
276 pub payload_content_hash: ContextCheckpointLegacyHashV1,
278 pub losses: Vec<ContextCheckpointProjectionLossV1>,
280}
281
282impl ContextCheckpointLegacyPayloadV1 {
283 pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
285 if self.adapter_schema_version != CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION {
286 return Err(ContextCheckpointLegacyErrorV1::UnsupportedAdapterVersion {
287 actual: self.adapter_schema_version,
288 expected: CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION,
289 });
290 }
291 if !self
292 .target
293 .accepts_schema_version(self.target_schema_version)
294 {
295 return Err(ContextCheckpointLegacyErrorV1::UnsupportedTargetVersion {
296 target: self.target,
297 requested: self.target_schema_version,
298 supported: self.target.schema_version(),
299 });
300 }
301 if self.losses.len() > MAX_CONTEXT_CHECKPOINT_LEGACY_LOSSES {
302 return Err(ContextCheckpointLegacyErrorV1::LegacyCapacityExceeded {
303 field: ContextCheckpointLegacyFieldV1::Payload,
304 limit: MAX_CONTEXT_CHECKPOINT_LEGACY_LOSSES as u64,
305 actual: self.losses.len() as u64,
306 });
307 }
308 if self
309 .losses
310 .iter()
311 .filter(|loss| loss.reason == ContextCheckpointProjectionLossReasonV1::RequiredInput)
312 .count()
313 > MAX_CONTEXT_CHECKPOINT_REQUIRED_INPUTS
314 {
315 return Err(ContextCheckpointLegacyErrorV1::LegacyCapacityExceeded {
316 field: ContextCheckpointLegacyFieldV1::Payload,
317 limit: MAX_CONTEXT_CHECKPOINT_REQUIRED_INPUTS as u64,
318 actual: self.losses.len() as u64,
319 });
320 }
321 if self.canonical_json.len() > MAX_CONTEXT_CHECKPOINT_LEGACY_PAYLOAD_BYTES {
322 return Err(ContextCheckpointLegacyErrorV1::LegacyCapacityExceeded {
323 field: ContextCheckpointLegacyFieldV1::Payload,
324 limit: MAX_CONTEXT_CHECKPOINT_LEGACY_PAYLOAD_BYTES as u64,
325 actual: self.canonical_json.len() as u64,
326 });
327 }
328 let value = parse_canonical_json(&self.canonical_json)?;
329 validate_legacy_target_value(self.target, self.target_schema_version, &value)?;
330 if crate::core::hasher::hash_hex(self.canonical_json.as_bytes())
331 != self.payload_content_hash.as_str()
332 {
333 return Err(ContextCheckpointLegacyErrorV1::InvalidLegacyPayload {
334 field: ContextCheckpointLegacyFieldV1::Payload,
335 });
336 }
337 if self.losses.windows(2).any(|window| window[0] >= window[1]) {
338 return Err(ContextCheckpointLegacyErrorV1::DuplicateLegacyInput {
339 field: ContextCheckpointLegacyFieldV1::Payload,
340 });
341 }
342 for loss in &self.losses {
343 if loss.field_path.is_empty()
344 || loss.field_path.len() > 128
345 || !loss.field_path.bytes().all(|byte| {
346 byte.is_ascii_lowercase()
347 || byte.is_ascii_digit()
348 || matches!(byte, b'.' | b'_' | b'[' | b']' | b'*')
349 })
350 {
351 return Err(ContextCheckpointLegacyErrorV1::InvalidLegacyPayload {
352 field: ContextCheckpointLegacyFieldV1::Payload,
353 });
354 }
355 match loss.reason {
356 ContextCheckpointProjectionLossReasonV1::NotRepresentable
357 if loss.required_input.is_none() => {}
358 ContextCheckpointProjectionLossReasonV1::RequiredInput => {
359 let Some(input) = loss.required_input else {
360 return Err(ContextCheckpointLegacyErrorV1::InvalidLegacyPayload {
361 field: ContextCheckpointLegacyFieldV1::Payload,
362 });
363 };
364 if projection_input_target(input) != self.target.projection_target()
365 || projection_input_field_path(input) != loss.field_path
366 {
367 return Err(ContextCheckpointLegacyErrorV1::InvalidLegacyPayload {
368 field: ContextCheckpointLegacyFieldV1::Payload,
369 });
370 }
371 }
372 ContextCheckpointProjectionLossReasonV1::NotRepresentable => {
373 return Err(ContextCheckpointLegacyErrorV1::InvalidLegacyPayload {
374 field: ContextCheckpointLegacyFieldV1::Payload,
375 });
376 }
377 }
378 }
379 Ok(())
380 }
381}
382
383validated_deserialize!(ContextCheckpointLegacyPayloadV1 {
384 adapter_schema_version: u32,
385 source_identity: ContextCheckpointLegacySourceIdentityV1,
386 target: ContextCheckpointLegacyTargetV1,
387 target_schema_version: u32,
388 canonical_json: String,
389 payload_content_hash: ContextCheckpointLegacyHashV1,
390 losses: Vec<ContextCheckpointProjectionLossV1>,
391});
392
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
395#[serde(rename_all = "snake_case")]
396pub enum ContextCheckpointLegacyMaterializationV1 {
397 Materialized(ContextCheckpointLegacyPayloadV1),
399 Refused(ContextCheckpointLegacyRefusalV1),
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum ContextCheckpointLegacyAdoptionV1 {
406 Adopted(Box<ContextCheckpointV1>),
408 Refused(ContextCheckpointLegacyRefusalV1),
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
414#[serde(transparent)]
415pub struct ContextCheckpointLegacyHashV1(String);
416
417impl ContextCheckpointLegacyHashV1 {
418 pub fn new(value: impl Into<String>) -> Result<Self, ContextCheckpointLegacyErrorV1> {
420 let value = value.into();
421 if value.len() != LEGACY_HASH_HEX_LENGTH || !is_lowercase_hex(&value) {
422 return Err(ContextCheckpointLegacyErrorV1::InvalidInputs {
423 field: ContextCheckpointLegacyFieldV1::Payload,
424 });
425 }
426 Ok(Self(value))
427 }
428
429 pub fn as_str(&self) -> &str {
431 &self.0
432 }
433}
434
435impl<'de> Deserialize<'de> for ContextCheckpointLegacyHashV1 {
436 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
437 where
438 D: Deserializer<'de>,
439 {
440 let value = String::deserialize(deserializer)?;
441 Self::new(value).map_err(|error| DeError::custom(format!("{error:?}")))
442 }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
447#[serde(transparent)]
448pub struct ContextCheckpointLegacyLabelV1(String);
449
450impl ContextCheckpointLegacyLabelV1 {
451 pub fn new(value: impl Into<String>) -> Result<Self, ContextCheckpointLegacyErrorV1> {
453 let value = value.into();
454 let lower = value.to_ascii_lowercase();
455 let invalid = value.is_empty()
456 || value.len() > MAX_LEGACY_LABEL_BYTES
457 || value.starts_with(' ')
458 || value.ends_with(' ')
459 || !value.bytes().all(|byte| (0x20..0x7f).contains(&byte))
460 || contains_machine_local_or_secret_label(&lower);
461 if invalid {
462 return Err(ContextCheckpointLegacyErrorV1::InvalidInputs {
463 field: ContextCheckpointLegacyFieldV1::Payload,
464 });
465 }
466 Ok(Self(value))
467 }
468
469 pub fn as_str(&self) -> &str {
471 &self.0
472 }
473}
474
475fn contains_machine_local_or_secret_label(value: &str) -> bool {
476 const ASSIGNMENTS: [&str; 14] = [
477 "api_key=",
478 "authorization:",
479 "bearer ",
480 "cache_handle=",
481 "client_secret=",
482 "password=",
483 "passwd=",
484 "path=",
485 "pid=",
486 "provider_handle=",
487 "temp_dir=",
488 "tmpdir=",
489 "token=",
490 "-----begin",
491 ];
492 ASSIGNMENTS.iter().any(|marker| value.contains(marker))
493 || value.contains("://")
494 || value.split_whitespace().any(|token| {
495 let token = token.trim_matches(|character: char| {
496 matches!(character, '(' | '[' | '{' | '<' | '\'' | '"')
497 });
498 token.starts_with('/')
499 || token.starts_with("~/")
500 || (token.len() >= 3
501 && token.as_bytes()[0].is_ascii_alphabetic()
502 && token.as_bytes()[1] == b':'
503 && matches!(token.as_bytes()[2], b'/' | b'\\'))
504 })
505}
506
507impl<'de> Deserialize<'de> for ContextCheckpointLegacyLabelV1 {
508 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
509 where
510 D: Deserializer<'de>,
511 {
512 let value = String::deserialize(deserializer)?;
513 Self::new(value).map_err(|error| DeError::custom(format!("{error:?}")))
514 }
515}
516
517#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
519#[serde(transparent)]
520pub struct ContextCheckpointLegacyCommitV1(String);
521
522impl ContextCheckpointLegacyCommitV1 {
523 pub fn new(value: impl Into<String>) -> Result<Self, ContextCheckpointLegacyErrorV1> {
525 let value = value.into();
526 if !(7..=40).contains(&value.len()) || !is_lowercase_hex(&value) {
527 return Err(ContextCheckpointLegacyErrorV1::InvalidInputs {
528 field: ContextCheckpointLegacyFieldV1::Payload,
529 });
530 }
531 Ok(Self(value))
532 }
533
534 pub fn as_str(&self) -> &str {
536 &self.0
537 }
538}
539
540impl<'de> Deserialize<'de> for ContextCheckpointLegacyCommitV1 {
541 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
542 where
543 D: Deserializer<'de>,
544 {
545 let value = String::deserialize(deserializer)?;
546 Self::new(value).map_err(|error| DeError::custom(format!("{error:?}")))
547 }
548}
549
550fn is_lowercase_hex(value: &str) -> bool {
551 !value.is_empty()
552 && value
553 .bytes()
554 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
555}