Skip to main content

lean_ctx/core/context_checkpoint/adapters/
inputs.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Caller-owned target inputs for each legacy family.
4
5use super::{
6    CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION, ContextCheckpointLegacyCommitV1,
7    ContextCheckpointLegacyErrorV1, ContextCheckpointLegacyFieldV1, ContextCheckpointLegacyHashV1,
8    ContextCheckpointLegacyLabelV1, ContextCheckpointLegacyTargetV1,
9    MAX_CONTEXT_CHECKPOINT_CARRIER_ENVELOPE_BYTES, parse_json_object, require_capacity,
10    validate_optional_label, validate_project_identity, validate_sorted_unique_timestamps,
11    validate_timestamp,
12};
13use lean_ctx_protocol::{SemanticVersion, Sha256Digest, UtcTimestamp, WorkspaceId};
14use serde::{Deserialize, Deserializer, Serialize, de::Error as DeError};
15
16/// Caller-supplied policy identity; never derived from the checkpoint.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct ContextCheckpointLegacyPolicyIdentityV1 {
20    /// Deployed policy name (role or tuning profile).
21    pub name: ContextCheckpointLegacyLabelV1,
22    /// Content hash of the resolved policy document.
23    pub policy_digest: ContextCheckpointLegacyHashV1,
24}
25
26/// Caller-supplied project identity hashes; the checkpoint carries no paths.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct ContextCheckpointLegacyProjectIdentityV1 {
30    /// Hash of the local project root, when the caller resolved one.
31    pub project_root_hash: Option<ContextCheckpointLegacyHashV1>,
32    /// Hash of the project remote identity, when the caller resolved one.
33    pub project_identity_hash: Option<ContextCheckpointLegacyHashV1>,
34}
35
36/// Caller-supplied session counters; the checkpoint carries no telemetry.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(deny_unknown_fields)]
39pub struct ContextCheckpointLegacySessionCountersV1 {
40    pub total_tool_calls: u32,
41    pub total_tokens_saved: u64,
42    pub total_tokens_input: u64,
43    pub cache_hits: u32,
44    pub files_read: u32,
45    pub commands_run: u32,
46    pub intents_inferred: u32,
47    pub intents_explicit: u32,
48    pub unsaved_changes: u32,
49}
50
51/// Caller-supplied git anchor; the checkpoint carries no repository state.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct ContextCheckpointLegacyGitAnchorV1 {
55    pub commit: Option<ContextCheckpointLegacyCommitV1>,
56    pub branch: Option<ContextCheckpointLegacyLabelV1>,
57    pub dirty: bool,
58}
59
60/// Caller-supplied token ROI; the checkpoint carries no ROI state.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct ContextCheckpointLegacyRoiV1 {
64    pub input_tokens: u64,
65    pub output_tokens: u64,
66    pub tokens_saved: u64,
67}
68
69/// Caller-supplied ledger totals; the checkpoint carries no ledger state.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(deny_unknown_fields)]
72pub struct ContextCheckpointLegacyLedgerTotalsV1 {
73    pub window_size: u32,
74    pub total_tokens_sent: u32,
75    pub total_tokens_saved: u32,
76    pub lineage_items_recorded: u64,
77}
78
79/// Target-owned inputs for the deployed Session Bundle v1.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
81#[serde(deny_unknown_fields)]
82pub struct ContextCheckpointSessionBundleInputsV1 {
83    pub exported_at: UtcTimestamp,
84    pub project: ContextCheckpointLegacyProjectIdentityV1,
85    pub role: ContextCheckpointLegacyPolicyIdentityV1,
86    pub profile: ContextCheckpointLegacyPolicyIdentityV1,
87    /// Observation time per checkpoint decision, in checkpoint order.
88    pub decision_observed_at: Vec<UtcTimestamp>,
89    /// Observation time per checkpoint finding, in checkpoint order.
90    pub finding_observed_at: Vec<UtcTimestamp>,
91    pub stats: ContextCheckpointLegacySessionCountersV1,
92    pub compression_level: Option<ContextCheckpointLegacyLabelV1>,
93    pub terse_mode: bool,
94}
95
96impl ContextCheckpointSessionBundleInputsV1 {
97    /// Validate the source-independent input bounds.
98    pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
99        require_capacity(
100            self.decision_observed_at.len(),
101            lean_ctx_protocol::MAX_CONTEXT_CHECKPOINT_DECISIONS,
102            ContextCheckpointLegacyFieldV1::DecisionObservedAt,
103        )?;
104        require_capacity(
105            self.finding_observed_at.len(),
106            lean_ctx_protocol::MAX_CONTEXT_CHECKPOINT_FINDINGS,
107            ContextCheckpointLegacyFieldV1::FindingObservedAt,
108        )?;
109        validate_sorted_unique_timestamps(
110            &self.decision_observed_at,
111            ContextCheckpointLegacyFieldV1::DecisionObservedAt,
112        )?;
113        validate_sorted_unique_timestamps(
114            &self.finding_observed_at,
115            ContextCheckpointLegacyFieldV1::FindingObservedAt,
116        )
117    }
118}
119
120validated_deserialize!(ContextCheckpointSessionBundleInputsV1 {
121    exported_at: UtcTimestamp,
122    project: ContextCheckpointLegacyProjectIdentityV1,
123    role: ContextCheckpointLegacyPolicyIdentityV1,
124    profile: ContextCheckpointLegacyPolicyIdentityV1,
125    decision_observed_at: Vec<UtcTimestamp>,
126    finding_observed_at: Vec<UtcTimestamp>,
127    stats: ContextCheckpointLegacySessionCountersV1,
128    compression_level: Option<ContextCheckpointLegacyLabelV1>,
129    terse_mode: bool,
130});
131
132/// Target-owned inputs for the deployed Handoff Transfer Bundle v1.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
134#[serde(deny_unknown_fields)]
135pub struct ContextCheckpointHandoffBundleInputsV1 {
136    pub exported_at: UtcTimestamp,
137    pub ledger_created_at: UtcTimestamp,
138    /// Content hash of the tool manifest the ledger pins.
139    pub manifest_digest: ContextCheckpointLegacyHashV1,
140    pub project: ContextCheckpointLegacyProjectIdentityV1,
141    pub agent_id: Option<ContextCheckpointLegacyLabelV1>,
142    pub client_name: Option<ContextCheckpointLegacyLabelV1>,
143}
144
145impl ContextCheckpointHandoffBundleInputsV1 {
146    /// Validate every caller-owned handoff identity and timestamp.
147    pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
148        validate_project_identity(&self.project)?;
149        validate_timestamp(&self.exported_at, ContextCheckpointLegacyFieldV1::Payload)?;
150        validate_timestamp(
151            &self.ledger_created_at,
152            ContextCheckpointLegacyFieldV1::Payload,
153        )?;
154        validate_optional_label(self.agent_id.as_ref())?;
155        validate_optional_label(self.client_name.as_ref())
156    }
157}
158
159validated_deserialize!(ContextCheckpointHandoffBundleInputsV1 {
160    exported_at: UtcTimestamp,
161    ledger_created_at: UtcTimestamp,
162    manifest_digest: ContextCheckpointLegacyHashV1,
163    project: ContextCheckpointLegacyProjectIdentityV1,
164    agent_id: Option<ContextCheckpointLegacyLabelV1>,
165    client_name: Option<ContextCheckpointLegacyLabelV1>,
166});
167
168/// Target-owned inputs for the deployed Context Snapshot v1.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
170#[serde(deny_unknown_fields)]
171pub struct ContextCheckpointContextSnapshotInputsV1 {
172    pub created_at: UtcTimestamp,
173    pub lean_ctx_version: SemanticVersion,
174    pub project: ContextCheckpointLegacyProjectIdentityV1,
175    pub parent_snapshot_id: Option<ContextCheckpointLegacyHashV1>,
176    pub git: ContextCheckpointLegacyGitAnchorV1,
177    pub roi: ContextCheckpointLegacyRoiV1,
178    pub ledger_totals: ContextCheckpointLegacyLedgerTotalsV1,
179}
180
181impl ContextCheckpointContextSnapshotInputsV1 {
182    /// Validate every caller-owned snapshot anchor and bounded counter.
183    pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
184        validate_project_identity(&self.project)?;
185        validate_timestamp(&self.created_at, ContextCheckpointLegacyFieldV1::Payload)?;
186        if let Some(parent) = &self.parent_snapshot_id {
187            ContextCheckpointLegacyHashV1::new(parent.as_str().to_owned())?;
188        }
189        if let Some(commit) = &self.git.commit {
190            ContextCheckpointLegacyCommitV1::new(commit.as_str().to_owned())?;
191        }
192        if let Some(branch) = &self.git.branch {
193            ContextCheckpointLegacyLabelV1::new(branch.as_str().to_owned())?;
194        }
195        Ok(())
196    }
197}
198
199validated_deserialize!(ContextCheckpointContextSnapshotInputsV1 {
200    created_at: UtcTimestamp,
201    lean_ctx_version: SemanticVersion,
202    project: ContextCheckpointLegacyProjectIdentityV1,
203    parent_snapshot_id: Option<ContextCheckpointLegacyHashV1>,
204    git: ContextCheckpointLegacyGitAnchorV1,
205    roi: ContextCheckpointLegacyRoiV1,
206    ledger_totals: ContextCheckpointLegacyLedgerTotalsV1,
207});
208
209/// Target-owned inputs for the deployed `.ctxpkg` carrier envelope.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
211#[serde(deny_unknown_fields)]
212pub struct ContextCheckpointCtxpkgInputsV1 {
213    /// Encoded P6 `.ctxpkg` checkpoint carrier envelope, when the caller has one.
214    pub carrier_envelope_json: Option<String>,
215}
216
217impl ContextCheckpointCtxpkgInputsV1 {
218    /// Validate the encoded envelope bound.
219    pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
220        if let Some(json) = &self.carrier_envelope_json {
221            if json.len() > MAX_CONTEXT_CHECKPOINT_CARRIER_ENVELOPE_BYTES {
222                return Err(ContextCheckpointLegacyErrorV1::LegacyCapacityExceeded {
223                    field: ContextCheckpointLegacyFieldV1::Payload,
224                    limit: MAX_CONTEXT_CHECKPOINT_CARRIER_ENVELOPE_BYTES as u64,
225                    actual: json.len() as u64,
226                });
227            }
228            parse_json_object(json)?;
229        }
230        Ok(())
231    }
232}
233
234validated_deserialize!(ContextCheckpointCtxpkgInputsV1 {
235    carrier_envelope_json: Option<String>,
236});
237
238/// Typed target inputs; the variant fixes the target family.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(rename_all = "snake_case")]
241pub enum ContextCheckpointLegacyInputsV1 {
242    SessionBundle(ContextCheckpointSessionBundleInputsV1),
243    HandoffBundle(ContextCheckpointHandoffBundleInputsV1),
244    Ctxpkg(ContextCheckpointCtxpkgInputsV1),
245    ContextSnapshot(ContextCheckpointContextSnapshotInputsV1),
246}
247
248impl ContextCheckpointLegacyInputsV1 {
249    /// The target family this payload belongs to.
250    pub const fn target(&self) -> ContextCheckpointLegacyTargetV1 {
251        match self {
252            Self::SessionBundle(_) => ContextCheckpointLegacyTargetV1::SessionBundle,
253            Self::HandoffBundle(_) => ContextCheckpointLegacyTargetV1::HandoffBundle,
254            Self::Ctxpkg(_) => ContextCheckpointLegacyTargetV1::Ctxpkg,
255            Self::ContextSnapshot(_) => ContextCheckpointLegacyTargetV1::ContextSnapshot,
256        }
257    }
258}
259
260/// One explicit forward adapter request.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
262#[serde(deny_unknown_fields)]
263pub struct ContextCheckpointLegacyRequestV1 {
264    /// Adapter contract version the caller compiled against.
265    pub adapter_schema_version: u32,
266    /// Requested target family.
267    pub target: ContextCheckpointLegacyTargetV1,
268    /// Requested target schema version.
269    pub target_schema_version: u32,
270    /// Target-owned inputs; the variant must match `target`.
271    pub inputs: ContextCheckpointLegacyInputsV1,
272}
273
274impl ContextCheckpointLegacyRequestV1 {
275    /// Validate the version and target/payload pairing.
276    pub fn validate(&self) -> Result<(), ContextCheckpointLegacyErrorV1> {
277        if self.adapter_schema_version != CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION {
278            return Err(ContextCheckpointLegacyErrorV1::UnsupportedAdapterVersion {
279                actual: self.adapter_schema_version,
280                expected: CONTEXT_CHECKPOINT_ADAPTER_SCHEMA_VERSION,
281            });
282        }
283        let inputs_target = self.inputs.target();
284        if inputs_target != self.target {
285            return Err(ContextCheckpointLegacyErrorV1::TargetInputsMismatch {
286                target: self.target,
287                inputs_target,
288            });
289        }
290        if !self
291            .target
292            .accepts_schema_version(self.target_schema_version)
293        {
294            return Err(ContextCheckpointLegacyErrorV1::UnsupportedTargetVersion {
295                target: self.target,
296                requested: self.target_schema_version,
297                supported: self.target.schema_version(),
298            });
299        }
300        match &self.inputs {
301            ContextCheckpointLegacyInputsV1::SessionBundle(inputs) => inputs.validate()?,
302            ContextCheckpointLegacyInputsV1::HandoffBundle(inputs) => inputs.validate()?,
303            ContextCheckpointLegacyInputsV1::Ctxpkg(inputs) => inputs.validate()?,
304            ContextCheckpointLegacyInputsV1::ContextSnapshot(inputs) => inputs.validate()?,
305        }
306        Ok(())
307    }
308}
309
310validated_deserialize!(ContextCheckpointLegacyRequestV1 {
311    adapter_schema_version: u32,
312    target: ContextCheckpointLegacyTargetV1,
313    target_schema_version: u32,
314    inputs: ContextCheckpointLegacyInputsV1,
315});
316
317/// The `.ctxpkg` carrier facts a checkpoint binding admitted.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(deny_unknown_fields)]
320pub struct ContextCheckpointCarrierAdmissionV1 {
321    /// Workspace identity asserted by both the binding and the envelope.
322    pub workspace_id: WorkspaceId,
323    /// Carrier logical-state digest asserted by both.
324    pub state_digest: Sha256Digest,
325    /// Carrier envelope digest asserted by both.
326    pub envelope_digest: Sha256Digest,
327}