Skip to main content

lean_ctx/core/context_checkpoint/adapters/
contract.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Stable adapter contract types and validated wire envelopes.
4
5use 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/// The deployed legacy wire families this slice adapts.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum ContextCheckpointLegacyTargetV1 {
22    /// Deployed core Session Bundle v1 (`CcpSessionBundleV1`).
23    SessionBundle,
24    /// Deployed core Handoff Transfer Bundle v1.
25    HandoffBundle,
26    /// Deployed `.ctxpkg` context package (v1 and v2).
27    Ctxpkg,
28    /// Deployed core Context Snapshot v1.
29    ContextSnapshot,
30}
31
32impl ContextCheckpointLegacyTargetV1 {
33    /// Return the legacy families in canonical order.
34    pub const fn all() -> [Self; 4] {
35        [
36            Self::SessionBundle,
37            Self::HandoffBundle,
38            Self::Ctxpkg,
39            Self::ContextSnapshot,
40        ]
41    }
42
43    /// The projection target this legacy family reuses.
44    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    /// Stable target identifier shared with the projection plans.
54    pub const fn target_id(self) -> &'static str {
55        self.projection_target().target_id()
56    }
57
58    /// The single schema version this slice materializes for the family.
59    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    /// Every schema version the family accepts as an inspection input.
69    ///
70    /// `.ctxpkg` is the only deployed family with two live versions.
71    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/// Canonical field names used by adapter errors and refusals.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum ContextCheckpointLegacyFieldV1 {
86    /// The whole encoded legacy payload.
87    Payload,
88    /// The adapter provenance binding for a legacy payload.
89    SourceIdentity,
90    /// Task title / description.
91    TaskTitle,
92    /// Decision list.
93    Decisions,
94    /// Finding list.
95    Findings,
96    /// Next-step list.
97    NextSteps,
98    /// Per-decision observation timestamps.
99    DecisionObservedAt,
100    /// Per-finding observation timestamps.
101    FindingObservedAt,
102    /// Portable session identity.
103    SessionId,
104    /// Portable session revision.
105    SessionRevision,
106    /// Session evidence records.
107    Evidence,
108    /// Touched-file records.
109    Files,
110    /// Progress entries.
111    Progress,
112    /// Test snapshot.
113    TestResults,
114    /// Handoff tool-call summary.
115    ToolCalls,
116    /// Handoff knowledge excerpt.
117    Knowledge,
118    /// Handoff curated references.
119    CuratedRefs,
120    /// Handoff artifacts excerpt.
121    Artifacts,
122    /// Handoff workflow run.
123    Workflow,
124    /// Handoff embedded session snapshot.
125    SessionSnapshot,
126    /// Handoff active overlays.
127    ActiveOverlays,
128    /// `.ctxpkg` carrier binding on the checkpoint.
129    CarrierBinding,
130    /// `.ctxpkg` carrier schema identity.
131    CarrierSchemaId,
132    /// `.ctxpkg` carrier workspace identity.
133    CarrierWorkspaceId,
134    /// `.ctxpkg` carrier logical-state digest.
135    CarrierStateDigest,
136    /// `.ctxpkg` carrier envelope digest.
137    CarrierEnvelopeDigest,
138}
139
140/// Typed, fail-closed adapter errors.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "snake_case", deny_unknown_fields)]
143pub enum ContextCheckpointLegacyErrorV1 {
144    /// The request declares an adapter contract this build does not implement.
145    UnsupportedAdapterVersion { actual: u32, expected: u32 },
146    /// The source checkpoint declares an unknown or newer schema version.
147    UnsupportedSourceVersion { actual: u32, expected: u32 },
148    /// The requested target schema version is unknown or newer.
149    UnsupportedTargetVersion {
150        target: ContextCheckpointLegacyTargetV1,
151        requested: u32,
152        supported: u32,
153    },
154    /// The request target and the supplied input payload disagree.
155    TargetInputsMismatch {
156        target: ContextCheckpointLegacyTargetV1,
157        inputs_target: ContextCheckpointLegacyTargetV1,
158    },
159    /// The source checkpoint failed its own invariants.
160    InvalidSource,
161    /// A caller-supplied input failed validation.
162    InvalidInputs {
163        field: ContextCheckpointLegacyFieldV1,
164    },
165    /// A caller-supplied list does not match the source arity exactly.
166    InputArityMismatch {
167        field: ContextCheckpointLegacyFieldV1,
168        expected: u32,
169        actual: u32,
170    },
171    /// The source exceeds a deployed legacy capacity; truncation is refused.
172    LegacyCapacityExceeded {
173        field: ContextCheckpointLegacyFieldV1,
174        limit: u64,
175        actual: u64,
176    },
177    /// A legacy payload identity disagrees with the checkpoint identity.
178    IdentityMismatch {
179        field: ContextCheckpointLegacyFieldV1,
180    },
181    /// Signature material is present but not verifiable.
182    MalformedSignature,
183    /// Reverse conversion would silently drop legacy semantics.
184    LossyReverseConversion {
185        field: ContextCheckpointLegacyFieldV1,
186    },
187    /// Reverse conversion would replace anchor-authenticated semantics.
188    SemanticOverwrite {
189        field: ContextCheckpointLegacyFieldV1,
190    },
191    /// A legacy field required by the checkpoint contract is absent.
192    MissingLegacySource {
193        field: ContextCheckpointLegacyFieldV1,
194    },
195    /// A legacy list repeats a value the checkpoint requires to be unique.
196    DuplicateLegacyInput {
197        field: ContextCheckpointLegacyFieldV1,
198    },
199    /// A legacy payload is malformed for its declared version.
200    InvalidLegacyPayload {
201        field: ContextCheckpointLegacyFieldV1,
202    },
203    /// The deployed encoder or parser rejected the materialized payload.
204    LegacyOwnerRejected,
205}
206
207/// Why an adapter refuses a target instead of emitting a payload.
208#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
209#[serde(rename_all = "snake_case")]
210pub enum ContextCheckpointLegacyRefusalReasonV1 {
211    /// The target payload is owned by code outside this slice.
212    TargetOwnerDependency,
213    /// The target requires portable session state the checkpoint does not carry.
214    MissingSessionState,
215    /// The checkpoint carries no `.ctxpkg` carrier binding to admit against.
216    MissingCarrierBinding,
217    /// The family has no lossless reverse conversion into a checkpoint.
218    ReverseNotRepresentable,
219}
220
221/// An explicit typed refusal with the precise unmet dependency.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
223#[serde(deny_unknown_fields)]
224pub struct ContextCheckpointLegacyRefusalV1 {
225    /// Refused target family.
226    pub target: ContextCheckpointLegacyTargetV1,
227    /// Target schema version the caller requested.
228    pub target_schema_version: u32,
229    /// Structured refusal reason; no free-form warning text is permitted.
230    pub reason: ContextCheckpointLegacyRefusalReasonV1,
231    /// Stable module path of the owner this slice depends on.
232    pub dependency: String,
233    /// Target-owned inputs still required, in canonical order.
234    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/// Provenance binding carried beside a legacy wire payload.
246///
247/// Legacy targets do not carry the checkpoint security boundary fields.  The
248/// adapter envelope therefore records the complete source identity and a
249/// content digest so reverse adoption cannot cross tenant, project, workspace,
250/// task, or plan boundaries even when the target wire bytes happen to match.
251#[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/// A materialized legacy payload plus its residual semantic losses.
263#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
264#[serde(deny_unknown_fields)]
265pub struct ContextCheckpointLegacyPayloadV1 {
266    /// Schema version of this adapter contract.
267    pub adapter_schema_version: u32,
268    /// Authenticated source checkpoint identity and lineage boundary.
269    pub source_identity: ContextCheckpointLegacySourceIdentityV1,
270    /// Materialized target family.
271    pub target: ContextCheckpointLegacyTargetV1,
272    /// Materialized target schema version.
273    pub target_schema_version: u32,
274    /// Compact canonical JSON accepted by the deployed wire owner.
275    pub canonical_json: String,
276    /// Content hash of `canonical_json`, from the deployed hasher.
277    pub payload_content_hash: ContextCheckpointLegacyHashV1,
278    /// Sorted, unique losses that survive materialization.
279    pub losses: Vec<ContextCheckpointProjectionLossV1>,
280}
281
282impl ContextCheckpointLegacyPayloadV1 {
283    /// Validate canonical bytes, target/version pairing, hash, and loss order.
284    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/// Outcome of a forward (checkpoint to legacy) adapter call.
394#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
395#[serde(rename_all = "snake_case")]
396pub enum ContextCheckpointLegacyMaterializationV1 {
397    /// The target was materialized from validated inputs.
398    Materialized(ContextCheckpointLegacyPayloadV1),
399    /// The target was refused; the payload owner is named.
400    Refused(ContextCheckpointLegacyRefusalV1),
401}
402
403/// Outcome of a reverse (legacy to checkpoint) adapter call.
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum ContextCheckpointLegacyAdoptionV1 {
406    /// The legacy payload was adopted into the anchor checkpoint.
407    Adopted(Box<ContextCheckpointV1>),
408    /// The family has no safe reverse conversion.
409    Refused(ContextCheckpointLegacyRefusalV1),
410}
411
412/// Lowercase hexadecimal content hash produced by the deployed hasher.
413#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
414#[serde(transparent)]
415pub struct ContextCheckpointLegacyHashV1(String);
416
417impl ContextCheckpointLegacyHashV1 {
418    /// Construct the hash after applying the wire invariants.
419    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    /// Borrow the validated hexadecimal value.
430    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/// Bounded, single-line label supplied by a legacy wire owner.
446#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
447#[serde(transparent)]
448pub struct ContextCheckpointLegacyLabelV1(String);
449
450impl ContextCheckpointLegacyLabelV1 {
451    /// Construct the label after applying the wire invariants.
452    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    /// Borrow the validated label.
470    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/// Short lowercase hexadecimal git commit identity supplied by the caller.
518#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
519#[serde(transparent)]
520pub struct ContextCheckpointLegacyCommitV1(String);
521
522impl ContextCheckpointLegacyCommitV1 {
523    /// Construct the commit identity after applying the wire invariants.
524    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    /// Borrow the validated commit identity.
535    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}