Skip to main content

lean_ctx/core/context_checkpoint/
projections.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Versioned, fail-closed projection plans for `ContextCheckpointV1`.
4//!
5//! A plan is intentionally not an adapter.  The deployed Session Bundle,
6//! Handoff Bundle, `.ctxpkg`, and Context Snapshot wire owners still require
7//! inputs that a checkpoint does not contain (timestamps, policy identity,
8//! ledger state, package contents, git/ROI state, and similar material).
9//! Returning those plans makes the boundary explicit without fabricating a
10//! default identity or silently discarding checkpoint semantics.
11
12use std::collections::BTreeSet;
13
14use serde::{Deserialize, Deserializer, Serialize};
15
16use crate::core::contracts::{
17    CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION, CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
18    CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION, HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
19};
20use lean_ctx_protocol::{
21    ContextCheckpointCarrierBindingV1, ContextCheckpointIdentityV1, ContextCheckpointV1,
22    ContextSessionRecoveryStateV1,
23};
24
25/// Schema version of this projection result contract.
26pub const CONTEXT_CHECKPOINT_PROJECTION_SCHEMA_VERSION: u32 = 1;
27
28/// Stable identifier for the deployed Session Bundle target.
29pub const SESSION_BUNDLE_TARGET_ID: &str = "leanctx.session-bundle";
30/// Stable identifier for the deployed Handoff Bundle target.
31pub const HANDOFF_BUNDLE_TARGET_ID: &str = "leanctx.handoff-bundle";
32/// Stable identifier for the deployed `.ctxpkg` target.
33pub const CTXPKG_TARGET_ID: &str = "leanctx.ctxpkg";
34/// Stable identifier for the deployed Context Snapshot target.
35pub const CONTEXT_SNAPSHOT_TARGET_ID: &str = "leanctx.context-snapshot";
36/// Stable identifier for the checkpoint identity/self target.
37pub const CONTEXT_CHECKPOINT_IDENTITY_TARGET_ID: &str = "leanctx.context-checkpoint-identity";
38
39/// The only target shapes covered by this slice.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum ContextCheckpointProjectionTargetV1 {
43    /// Existing core Session Bundle v1.
44    SessionBundle,
45    /// Existing core Handoff Transfer Bundle v1.
46    HandoffBundle,
47    /// Existing `.ctxpkg` checkpoint carrier v2.
48    Ctxpkg,
49    /// Existing core Context Snapshot v1.
50    ContextSnapshot,
51    /// The checkpoint identity/self subset.
52    ContextCheckpointIdentity,
53}
54
55impl ContextCheckpointProjectionTargetV1 {
56    /// Return targets in canonical output order.
57    pub const fn all() -> [Self; 5] {
58        [
59            Self::SessionBundle,
60            Self::HandoffBundle,
61            Self::Ctxpkg,
62            Self::ContextSnapshot,
63            Self::ContextCheckpointIdentity,
64        ]
65    }
66
67    /// Stable target identifier used in diagnostics and manifests.
68    pub const fn target_id(self) -> &'static str {
69        match self {
70            Self::SessionBundle => SESSION_BUNDLE_TARGET_ID,
71            Self::HandoffBundle => HANDOFF_BUNDLE_TARGET_ID,
72            Self::Ctxpkg => CTXPKG_TARGET_ID,
73            Self::ContextSnapshot => CONTEXT_SNAPSHOT_TARGET_ID,
74            Self::ContextCheckpointIdentity => CONTEXT_CHECKPOINT_IDENTITY_TARGET_ID,
75        }
76    }
77
78    /// Deployed schema version accepted for the target.
79    pub const fn schema_version(self) -> u32 {
80        match self {
81            Self::SessionBundle => CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
82            Self::HandoffBundle => HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
83            Self::Ctxpkg => CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
84            Self::ContextSnapshot => CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION,
85            Self::ContextCheckpointIdentity => ContextCheckpointV1::SCHEMA_VERSION,
86        }
87    }
88
89    const fn is_identity(self) -> bool {
90        matches!(self, Self::ContextCheckpointIdentity)
91    }
92}
93
94/// Target-side input that must be supplied by a downstream wire owner.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
96#[serde(rename_all = "snake_case")]
97pub enum ContextCheckpointProjectionInputV1 {
98    SessionBundleExportedAt,
99    SessionBundlePolicyIdentities,
100    SessionBundleSessionExcerpt,
101    HandoffBundleExportedAt,
102    HandoffBundleLedger,
103    HandoffBundleProjectIdentity,
104    CtxpkgManifest,
105    CtxpkgLogicalState,
106    CtxpkgIntegrity,
107    ContextSnapshotCreatedAt,
108    ContextSnapshotGitAnchor,
109    ContextSnapshotRoi,
110    ContextSnapshotLineage,
111    ContextSnapshotLedger,
112    ContextSnapshotSession,
113}
114
115impl ContextCheckpointProjectionInputV1 {
116    const fn target(self) -> ContextCheckpointProjectionTargetV1 {
117        match self {
118            Self::SessionBundleExportedAt
119            | Self::SessionBundlePolicyIdentities
120            | Self::SessionBundleSessionExcerpt => {
121                ContextCheckpointProjectionTargetV1::SessionBundle
122            }
123            Self::HandoffBundleExportedAt
124            | Self::HandoffBundleLedger
125            | Self::HandoffBundleProjectIdentity => {
126                ContextCheckpointProjectionTargetV1::HandoffBundle
127            }
128            Self::CtxpkgManifest | Self::CtxpkgLogicalState | Self::CtxpkgIntegrity => {
129                ContextCheckpointProjectionTargetV1::Ctxpkg
130            }
131            Self::ContextSnapshotCreatedAt
132            | Self::ContextSnapshotGitAnchor
133            | Self::ContextSnapshotRoi
134            | Self::ContextSnapshotLineage
135            | Self::ContextSnapshotLedger
136            | Self::ContextSnapshotSession => ContextCheckpointProjectionTargetV1::ContextSnapshot,
137        }
138    }
139
140    const fn field_path(self) -> &'static str {
141        match self {
142            Self::SessionBundleExportedAt | Self::HandoffBundleExportedAt => "target.exported_at",
143            Self::SessionBundlePolicyIdentities => "target.role_profile",
144            Self::SessionBundleSessionExcerpt | Self::ContextSnapshotSession => "target.session",
145            Self::HandoffBundleLedger | Self::ContextSnapshotLedger => "target.ledger",
146            Self::HandoffBundleProjectIdentity => "target.project",
147            Self::CtxpkgManifest => "target.manifest",
148            Self::CtxpkgLogicalState => "target.logical_state",
149            Self::CtxpkgIntegrity => "target.integrity",
150            Self::ContextSnapshotCreatedAt => "target.created_at",
151            Self::ContextSnapshotGitAnchor => "target.git",
152            Self::ContextSnapshotRoi => "target.roi",
153            Self::ContextSnapshotLineage => "target.lineage",
154        }
155    }
156}
157
158/// Why one semantic field is not emitted in a target wire payload.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum ContextCheckpointProjectionLossReasonV1 {
162    /// The target has no semantically equivalent field.
163    NotRepresentable,
164    /// A target field exists, but the required downstream input is absent.
165    RequiredInput,
166}
167
168/// One structured, canonical loss record.
169#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
170#[serde(deny_unknown_fields)]
171pub struct ContextCheckpointProjectionLossV1 {
172    /// Canonical source or target field path.
173    pub field_path: String,
174    /// Structured reason; no free-form warning text is permitted.
175    pub reason: ContextCheckpointProjectionLossReasonV1,
176    /// Required input when `reason` is `required_input`.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub required_input: Option<ContextCheckpointProjectionInputV1>,
179}
180
181impl<'de> Deserialize<'de> for ContextCheckpointProjectionLossV1 {
182    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183    where
184        D: Deserializer<'de>,
185    {
186        #[derive(Deserialize)]
187        #[serde(deny_unknown_fields)]
188        struct Raw {
189            field_path: String,
190            reason: ContextCheckpointProjectionLossReasonV1,
191            #[serde(default)]
192            required_input: Option<ContextCheckpointProjectionInputV1>,
193        }
194
195        let raw = Raw::deserialize(deserializer)?;
196        let value = Self {
197            field_path: raw.field_path,
198            reason: raw.reason,
199            required_input: raw.required_input,
200        };
201        validate_loss(&value, None)
202            .then_some(value)
203            .ok_or_else(|| serde::de::Error::custom("invalid checkpoint projection loss"))
204    }
205}
206
207impl ContextCheckpointProjectionLossV1 {
208    fn new(
209        field_path: &'static str,
210        reason: ContextCheckpointProjectionLossReasonV1,
211        required_input: Option<ContextCheckpointProjectionInputV1>,
212    ) -> Self {
213        Self {
214            field_path: field_path.to_owned(),
215            reason,
216            required_input,
217        }
218    }
219}
220
221/// Whether the emitted target subset has a proven round trip.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
223#[serde(rename_all = "snake_case")]
224pub enum ContextCheckpointProjectionFidelityV1 {
225    /// Decode(Encode(subset)) equals the source subset.
226    Lossless,
227    /// The target is a lossy plan and requires downstream materialization.
228    Lossy,
229}
230
231/// Typed plan shared by all non-identity target payloads.
232#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
233#[serde(deny_unknown_fields)]
234pub struct ContextCheckpointProjectionPlanV1 {
235    /// Source checkpoint identity; never default-filled.
236    pub source_checkpoint_id: lean_ctx_protocol::ContextCheckpointIdV1,
237    /// Source schema version observed by the plan.
238    pub source_schema_version: u32,
239    /// Inputs that the downstream target owner must supply.
240    pub required_inputs: Vec<ContextCheckpointProjectionInputV1>,
241    /// Source fields with a direct semantic slot in the target plan.
242    pub represented_source_fields: Vec<String>,
243}
244
245impl<'de> Deserialize<'de> for ContextCheckpointProjectionPlanV1 {
246    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
247    where
248        D: Deserializer<'de>,
249    {
250        #[derive(Deserialize)]
251        #[serde(deny_unknown_fields)]
252        struct Raw {
253            source_checkpoint_id: lean_ctx_protocol::ContextCheckpointIdV1,
254            source_schema_version: u32,
255            required_inputs: Vec<ContextCheckpointProjectionInputV1>,
256            represented_source_fields: Vec<String>,
257        }
258
259        let raw = Raw::deserialize(deserializer)?;
260        let value = Self {
261            source_checkpoint_id: raw.source_checkpoint_id,
262            source_schema_version: raw.source_schema_version,
263            required_inputs: raw.required_inputs,
264            represented_source_fields: raw.represented_source_fields,
265        };
266        validate_plan(&value, None)
267            .then_some(value)
268            .ok_or_else(|| serde::de::Error::custom("invalid checkpoint projection plan"))
269    }
270}
271
272/// `.ctxpkg` plan plus the already validated carrier binding, when present.
273#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
274#[serde(deny_unknown_fields)]
275pub struct ContextCheckpointCtxpkgProjectionV1 {
276    pub plan: ContextCheckpointProjectionPlanV1,
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub carrier_binding: Option<ContextCheckpointCarrierBindingV1>,
279}
280
281impl<'de> Deserialize<'de> for ContextCheckpointCtxpkgProjectionV1 {
282    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
283    where
284        D: Deserializer<'de>,
285    {
286        #[derive(Deserialize)]
287        #[serde(deny_unknown_fields)]
288        struct Raw {
289            plan: ContextCheckpointProjectionPlanV1,
290            #[serde(default)]
291            carrier_binding: Option<ContextCheckpointCarrierBindingV1>,
292        }
293
294        let raw = Raw::deserialize(deserializer)?;
295        let carrier_is_represented = raw.plan.represented_source_fields == ["carrier"];
296        (validate_plan(&raw.plan, Some(ContextCheckpointProjectionTargetV1::Ctxpkg))
297            && raw.carrier_binding.is_some() == carrier_is_represented)
298            .then_some(Self {
299                plan: raw.plan,
300                carrier_binding: raw.carrier_binding,
301            })
302            .ok_or_else(|| serde::de::Error::custom("invalid ctxpkg checkpoint projection"))
303    }
304}
305
306/// Lossless identity/self projection payload.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308#[serde(deny_unknown_fields)]
309pub struct ContextCheckpointIdentityProjectionV1 {
310    pub identity: ContextCheckpointIdentityV1,
311}
312
313impl<'de> Deserialize<'de> for ContextCheckpointIdentityProjectionV1 {
314    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
315    where
316        D: Deserializer<'de>,
317    {
318        #[derive(Deserialize)]
319        #[serde(deny_unknown_fields)]
320        struct Raw {
321            identity: ContextCheckpointIdentityV1,
322        }
323
324        let raw = Raw::deserialize(deserializer)?;
325        Ok(Self {
326            identity: raw.identity,
327        })
328    }
329}
330
331/// Typed target payload.  Non-identity variants are plans, not wire claims.
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
333pub enum ContextCheckpointProjectionPayloadV1 {
334    SessionBundle(ContextCheckpointProjectionPlanV1),
335    HandoffBundle(ContextCheckpointProjectionPlanV1),
336    Ctxpkg(ContextCheckpointCtxpkgProjectionV1),
337    ContextSnapshot(ContextCheckpointProjectionPlanV1),
338    ContextCheckpointIdentity(ContextCheckpointIdentityProjectionV1),
339}
340
341/// Versioned result returned by every target projection.
342#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
343#[serde(deny_unknown_fields)]
344pub struct ContextCheckpointProjectionResultV1 {
345    pub projection_schema_version: u32,
346    pub target: ContextCheckpointProjectionTargetV1,
347    pub target_schema_version: u32,
348    pub payload: ContextCheckpointProjectionPayloadV1,
349    /// Sorted and unique by `(field_path, reason, required_input)`.
350    pub losses: Vec<ContextCheckpointProjectionLossV1>,
351    pub fidelity: ContextCheckpointProjectionFidelityV1,
352}
353
354impl<'de> Deserialize<'de> for ContextCheckpointProjectionResultV1 {
355    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
356    where
357        D: Deserializer<'de>,
358    {
359        #[derive(Deserialize)]
360        #[serde(deny_unknown_fields)]
361        struct Raw {
362            projection_schema_version: u32,
363            target: ContextCheckpointProjectionTargetV1,
364            target_schema_version: u32,
365            payload: ContextCheckpointProjectionPayloadV1,
366            losses: Vec<ContextCheckpointProjectionLossV1>,
367            fidelity: ContextCheckpointProjectionFidelityV1,
368        }
369
370        let raw = Raw::deserialize(deserializer)?;
371        let value = Self {
372            projection_schema_version: raw.projection_schema_version,
373            target: raw.target,
374            target_schema_version: raw.target_schema_version,
375            payload: raw.payload,
376            losses: raw.losses,
377            fidelity: raw.fidelity,
378        };
379        validate_result(&value)
380            .then_some(value)
381            .ok_or_else(|| serde::de::Error::custom("invalid checkpoint projection result"))
382    }
383}
384
385/// State that this projection slice refuses to reinterpret.
386#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
387#[serde(rename_all = "snake_case")]
388pub enum ContextCheckpointProjectionUnsupportedStateV1 {
389    InspectOnly,
390    Corrupt,
391}
392
393/// Typed fail-closed projection errors.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
395#[serde(rename_all = "snake_case", deny_unknown_fields)]
396pub enum ContextCheckpointProjectionErrorV1 {
397    UnsupportedSourceVersion {
398        actual: u32,
399        expected: u32,
400    },
401    UnsupportedTargetVersion {
402        target: ContextCheckpointProjectionTargetV1,
403        requested: u32,
404        supported: u32,
405    },
406    InvalidSource,
407    UnsupportedState {
408        target: ContextCheckpointProjectionTargetV1,
409        state: ContextCheckpointProjectionUnsupportedStateV1,
410    },
411    InvalidProjectionResult,
412}
413
414/// Borrowed projection façade over one validated checkpoint.
415#[derive(Debug)]
416pub struct ContextCheckpointProjections<'a> {
417    checkpoint: &'a ContextCheckpointV1,
418}
419
420impl<'a> ContextCheckpointProjections<'a> {
421    /// Validate the source before exposing the projection façade.
422    pub fn new(
423        checkpoint: &'a ContextCheckpointV1,
424    ) -> Result<Self, ContextCheckpointProjectionErrorV1> {
425        validate_source(checkpoint)?;
426        Ok(Self { checkpoint })
427    }
428
429    /// Project one explicit target/version pair.
430    pub fn project(
431        &self,
432        target: ContextCheckpointProjectionTargetV1,
433        target_schema_version: u32,
434    ) -> Result<ContextCheckpointProjectionResultV1, ContextCheckpointProjectionErrorV1> {
435        validate_source(self.checkpoint)?;
436        validate_target_version(target, target_schema_version)?;
437        validate_target_state(self.checkpoint, target)?;
438
439        let result = build_result(self.checkpoint, target)?;
440        validate_result(&result)
441            .then_some(result)
442            .ok_or(ContextCheckpointProjectionErrorV1::InvalidProjectionResult)
443    }
444
445    /// Project every target in canonical target order.
446    pub fn project_all(
447        &self,
448    ) -> Vec<Result<ContextCheckpointProjectionResultV1, ContextCheckpointProjectionErrorV1>> {
449        ContextCheckpointProjectionTargetV1::all()
450            .into_iter()
451            .map(|target| self.project(target, target.schema_version()))
452            .collect()
453    }
454}
455
456/// Convenience entry point for one projection.
457pub fn project_checkpoint(
458    checkpoint: &ContextCheckpointV1,
459    target: ContextCheckpointProjectionTargetV1,
460    target_schema_version: u32,
461) -> Result<ContextCheckpointProjectionResultV1, ContextCheckpointProjectionErrorV1> {
462    ContextCheckpointProjections::new(checkpoint)?.project(target, target_schema_version)
463}
464
465fn validate_source(
466    checkpoint: &ContextCheckpointV1,
467) -> Result<(), ContextCheckpointProjectionErrorV1> {
468    if checkpoint.schema_version != ContextCheckpointV1::SCHEMA_VERSION {
469        return Err(
470            ContextCheckpointProjectionErrorV1::UnsupportedSourceVersion {
471                actual: checkpoint.schema_version,
472                expected: ContextCheckpointV1::SCHEMA_VERSION,
473            },
474        );
475    }
476    checkpoint
477        .validate()
478        .map_err(|_| ContextCheckpointProjectionErrorV1::InvalidSource)
479}
480
481fn validate_target_version(
482    target: ContextCheckpointProjectionTargetV1,
483    requested: u32,
484) -> Result<(), ContextCheckpointProjectionErrorV1> {
485    let supported = target.schema_version();
486    if requested != supported {
487        return Err(
488            ContextCheckpointProjectionErrorV1::UnsupportedTargetVersion {
489                target,
490                requested,
491                supported,
492            },
493        );
494    }
495    Ok(())
496}
497
498fn validate_target_state(
499    checkpoint: &ContextCheckpointV1,
500    target: ContextCheckpointProjectionTargetV1,
501) -> Result<(), ContextCheckpointProjectionErrorV1> {
502    if target.is_identity() {
503        return Ok(());
504    }
505    if let Some(session) = &checkpoint.live_state.session_state {
506        let state = match session.state.recovery_state {
507            ContextSessionRecoveryStateV1::InspectOnly => {
508                Some(ContextCheckpointProjectionUnsupportedStateV1::InspectOnly)
509            }
510            ContextSessionRecoveryStateV1::Corrupt => {
511                Some(ContextCheckpointProjectionUnsupportedStateV1::Corrupt)
512            }
513            _ => None,
514        };
515        if let Some(state) = state {
516            return Err(ContextCheckpointProjectionErrorV1::UnsupportedState { target, state });
517        }
518    }
519    Ok(())
520}
521
522fn build_result(
523    checkpoint: &ContextCheckpointV1,
524    target: ContextCheckpointProjectionTargetV1,
525) -> Result<ContextCheckpointProjectionResultV1, ContextCheckpointProjectionErrorV1> {
526    let represented_source_fields = represented_source_fields(target, checkpoint);
527    let required_inputs = required_inputs(target);
528    let plan = ContextCheckpointProjectionPlanV1 {
529        source_checkpoint_id: checkpoint.identity.checkpoint_id.clone(),
530        source_schema_version: checkpoint.schema_version,
531        required_inputs,
532        represented_source_fields,
533    };
534    let (payload, fidelity) = match target {
535        ContextCheckpointProjectionTargetV1::SessionBundle => (
536            ContextCheckpointProjectionPayloadV1::SessionBundle(plan),
537            ContextCheckpointProjectionFidelityV1::Lossy,
538        ),
539        ContextCheckpointProjectionTargetV1::HandoffBundle => (
540            ContextCheckpointProjectionPayloadV1::HandoffBundle(plan),
541            ContextCheckpointProjectionFidelityV1::Lossy,
542        ),
543        ContextCheckpointProjectionTargetV1::Ctxpkg => (
544            ContextCheckpointProjectionPayloadV1::Ctxpkg(ContextCheckpointCtxpkgProjectionV1 {
545                plan,
546                carrier_binding: checkpoint.carrier.clone(),
547            }),
548            ContextCheckpointProjectionFidelityV1::Lossy,
549        ),
550        ContextCheckpointProjectionTargetV1::ContextSnapshot => (
551            ContextCheckpointProjectionPayloadV1::ContextSnapshot(plan),
552            ContextCheckpointProjectionFidelityV1::Lossy,
553        ),
554        ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity => {
555            let identity = checkpoint.identity.clone();
556            // The protocol identity type has strict serde validation.  This
557            // round trip is the proof required before claiming losslessness.
558            let encoded = serde_json::to_vec(&identity)
559                .map_err(|_| ContextCheckpointProjectionErrorV1::InvalidProjectionResult)?;
560            let decoded: ContextCheckpointIdentityV1 = serde_json::from_slice(&encoded)
561                .map_err(|_| ContextCheckpointProjectionErrorV1::InvalidProjectionResult)?;
562            debug_assert_eq!(decoded, identity);
563            (
564                ContextCheckpointProjectionPayloadV1::ContextCheckpointIdentity(
565                    ContextCheckpointIdentityProjectionV1 { identity },
566                ),
567                ContextCheckpointProjectionFidelityV1::Lossless,
568            )
569        }
570    };
571
572    let losses = canonicalize_losses(losses_for(target, &payload));
573    Ok(ContextCheckpointProjectionResultV1 {
574        projection_schema_version: CONTEXT_CHECKPOINT_PROJECTION_SCHEMA_VERSION,
575        target,
576        target_schema_version: target.schema_version(),
577        payload,
578        losses,
579        fidelity,
580    })
581}
582
583fn required_inputs(
584    target: ContextCheckpointProjectionTargetV1,
585) -> Vec<ContextCheckpointProjectionInputV1> {
586    let mut inputs: Vec<_> = ContextCheckpointProjectionInputV1::all()
587        .into_iter()
588        .filter(|input| input.target() == target)
589        .collect();
590    inputs.sort();
591    inputs
592}
593
594impl ContextCheckpointProjectionInputV1 {
595    const fn all() -> [Self; 15] {
596        [
597            Self::SessionBundleExportedAt,
598            Self::SessionBundlePolicyIdentities,
599            Self::SessionBundleSessionExcerpt,
600            Self::HandoffBundleExportedAt,
601            Self::HandoffBundleLedger,
602            Self::HandoffBundleProjectIdentity,
603            Self::CtxpkgManifest,
604            Self::CtxpkgLogicalState,
605            Self::CtxpkgIntegrity,
606            Self::ContextSnapshotCreatedAt,
607            Self::ContextSnapshotGitAnchor,
608            Self::ContextSnapshotRoi,
609            Self::ContextSnapshotLineage,
610            Self::ContextSnapshotLedger,
611            Self::ContextSnapshotSession,
612        ]
613    }
614}
615
616const SOURCE_FIELDS: &[&str] = &[
617    "carrier",
618    "created_at",
619    "encryption_metadata",
620    "engine_version",
621    "identity.branch_id",
622    "identity.checkpoint_id",
623    "identity.device_id",
624    "identity.device_sequence",
625    "identity.parent_branch_id",
626    "identity.parent_checkpoint_id",
627    "identity.parent_device_id",
628    "identity.parent_device_sequence",
629    "lineage.context_ir_digest",
630    "lineage.evidence_refs",
631    "lineage.gotcha_refs",
632    "lineage.hosted_index_digest",
633    "lineage.knowledge_refs",
634    "lineage.plan_id",
635    "lineage.project_id",
636    "lineage.receipt_ids",
637    "lineage.snapshot_refs",
638    "lineage.task_id",
639    "lineage.tenant_id",
640    "lineage.workspace_id",
641    "live_state.decisions[*].decision_id",
642    "live_state.decisions[*].evidence_refs",
643    "live_state.decisions[*].rationale",
644    "live_state.decisions[*].statement",
645    "live_state.decisions[*].status",
646    "live_state.files[*].content_digest",
647    "live_state.files[*].role",
648    "live_state.files[*].source_id",
649    "live_state.findings",
650    "live_state.handoff_summary",
651    "live_state.learning_state",
652    "live_state.next_steps",
653    "live_state.package_pins",
654    "live_state.policy_pins",
655    "live_state.profile_id",
656    "live_state.progress.completed_steps",
657    "live_state.progress.confidence_milliunits",
658    "live_state.progress.summary",
659    "live_state.progress.total_steps",
660    "live_state.schema_version",
661    "live_state.session_state",
662    "live_state.task.plan_id",
663    "live_state.task.status",
664    "live_state.task.task_id",
665    "live_state.task.title",
666    "schema_version",
667    "updated_at",
668];
669
670fn represented_source_fields(
671    target: ContextCheckpointProjectionTargetV1,
672    checkpoint: &ContextCheckpointV1,
673) -> Vec<String> {
674    let mut fields: Vec<&str> = match target {
675        ContextCheckpointProjectionTargetV1::SessionBundle => vec![
676            "live_state.decisions[*].rationale",
677            "live_state.decisions[*].statement",
678            "live_state.findings",
679            "live_state.next_steps",
680            "live_state.progress.summary",
681            "live_state.task.title",
682        ],
683        ContextCheckpointProjectionTargetV1::HandoffBundle => vec![
684            "lineage.evidence_refs",
685            "live_state.decisions[*].statement",
686            "live_state.findings",
687            "live_state.next_steps",
688            "live_state.task.title",
689        ],
690        ContextCheckpointProjectionTargetV1::Ctxpkg => {
691            if checkpoint.carrier.is_some() {
692                vec!["carrier"]
693            } else {
694                Vec::new()
695            }
696        }
697        ContextCheckpointProjectionTargetV1::ContextSnapshot => vec![
698            "live_state.decisions[*].statement",
699            "live_state.progress.summary",
700            "live_state.task.title",
701        ],
702        ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity => vec![
703            "identity.branch_id",
704            "identity.checkpoint_id",
705            "identity.device_id",
706            "identity.device_sequence",
707            "identity.parent_branch_id",
708            "identity.parent_checkpoint_id",
709            "identity.parent_device_id",
710            "identity.parent_device_sequence",
711        ],
712    };
713    fields.sort_unstable();
714    fields.dedup();
715    fields.into_iter().map(str::to_owned).collect()
716}
717
718fn losses_for(
719    target: ContextCheckpointProjectionTargetV1,
720    payload: &ContextCheckpointProjectionPayloadV1,
721) -> Vec<ContextCheckpointProjectionLossV1> {
722    let represented: BTreeSet<&str> = match payload {
723        ContextCheckpointProjectionPayloadV1::SessionBundle(plan)
724        | ContextCheckpointProjectionPayloadV1::HandoffBundle(plan)
725        | ContextCheckpointProjectionPayloadV1::ContextSnapshot(plan) => plan
726            .represented_source_fields
727            .iter()
728            .map(String::as_str)
729            .collect(),
730        ContextCheckpointProjectionPayloadV1::Ctxpkg(projection) => projection
731            .plan
732            .represented_source_fields
733            .iter()
734            .map(String::as_str)
735            .collect(),
736        ContextCheckpointProjectionPayloadV1::ContextCheckpointIdentity(_) => [
737            "identity.branch_id",
738            "identity.checkpoint_id",
739            "identity.device_id",
740            "identity.device_sequence",
741            "identity.parent_branch_id",
742            "identity.parent_checkpoint_id",
743            "identity.parent_device_id",
744            "identity.parent_device_sequence",
745        ]
746        .into_iter()
747        .collect(),
748    };
749
750    let mut losses = SOURCE_FIELDS
751        .iter()
752        .filter(|field| !represented.contains(*field))
753        .map(|field| {
754            ContextCheckpointProjectionLossV1::new(
755                field,
756                ContextCheckpointProjectionLossReasonV1::NotRepresentable,
757                None,
758            )
759        })
760        .collect::<Vec<_>>();
761
762    for input in required_inputs(target) {
763        losses.push(ContextCheckpointProjectionLossV1::new(
764            input.field_path(),
765            ContextCheckpointProjectionLossReasonV1::RequiredInput,
766            Some(input),
767        ));
768    }
769    losses
770}
771
772fn canonicalize_losses(
773    mut losses: Vec<ContextCheckpointProjectionLossV1>,
774) -> Vec<ContextCheckpointProjectionLossV1> {
775    losses.sort();
776    losses.dedup();
777    losses
778}
779
780fn validate_result(result: &ContextCheckpointProjectionResultV1) -> bool {
781    let expected_fidelity = if result.target.is_identity() {
782        ContextCheckpointProjectionFidelityV1::Lossless
783    } else {
784        ContextCheckpointProjectionFidelityV1::Lossy
785    };
786    let payload_matches = match &result.payload {
787        ContextCheckpointProjectionPayloadV1::SessionBundle(plan) => validate_plan(
788            plan,
789            Some(ContextCheckpointProjectionTargetV1::SessionBundle),
790        ),
791        ContextCheckpointProjectionPayloadV1::HandoffBundle(plan) => validate_plan(
792            plan,
793            Some(ContextCheckpointProjectionTargetV1::HandoffBundle),
794        ),
795        ContextCheckpointProjectionPayloadV1::Ctxpkg(projection) => validate_plan(
796            &projection.plan,
797            Some(ContextCheckpointProjectionTargetV1::Ctxpkg),
798        ),
799        ContextCheckpointProjectionPayloadV1::ContextSnapshot(plan) => validate_plan(
800            plan,
801            Some(ContextCheckpointProjectionTargetV1::ContextSnapshot),
802        ),
803        ContextCheckpointProjectionPayloadV1::ContextCheckpointIdentity(_) => {
804            result.target == ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity
805        }
806    } && payload_target(&result.payload) == result.target;
807    let expected_losses = canonicalize_losses(losses_for(result.target, &result.payload));
808
809    result.projection_schema_version == CONTEXT_CHECKPOINT_PROJECTION_SCHEMA_VERSION
810        && result.target_schema_version == result.target.schema_version()
811        && result.fidelity == expected_fidelity
812        && payload_matches
813        && result.losses == expected_losses
814        && result
815            .losses
816            .iter()
817            .all(|loss| validate_loss(loss, Some(result.target)))
818}
819
820fn payload_target(
821    payload: &ContextCheckpointProjectionPayloadV1,
822) -> ContextCheckpointProjectionTargetV1 {
823    match payload {
824        ContextCheckpointProjectionPayloadV1::SessionBundle(_) => {
825            ContextCheckpointProjectionTargetV1::SessionBundle
826        }
827        ContextCheckpointProjectionPayloadV1::HandoffBundle(_) => {
828            ContextCheckpointProjectionTargetV1::HandoffBundle
829        }
830        ContextCheckpointProjectionPayloadV1::Ctxpkg(_) => {
831            ContextCheckpointProjectionTargetV1::Ctxpkg
832        }
833        ContextCheckpointProjectionPayloadV1::ContextSnapshot(_) => {
834            ContextCheckpointProjectionTargetV1::ContextSnapshot
835        }
836        ContextCheckpointProjectionPayloadV1::ContextCheckpointIdentity(_) => {
837            ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity
838        }
839    }
840}
841
842fn validate_loss(
843    loss: &ContextCheckpointProjectionLossV1,
844    target: Option<ContextCheckpointProjectionTargetV1>,
845) -> bool {
846    !loss.field_path.is_empty()
847        && loss.field_path.len() <= 128
848        && loss.field_path.bytes().all(|byte| {
849            byte.is_ascii_lowercase()
850                || byte.is_ascii_digit()
851                || matches!(byte, b'.' | b'_' | b'[' | b']' | b'*')
852        })
853        && match loss.reason {
854            ContextCheckpointProjectionLossReasonV1::NotRepresentable => {
855                loss.required_input.is_none()
856                    && SOURCE_FIELDS
857                        .binary_search(&loss.field_path.as_str())
858                        .is_ok()
859            }
860            ContextCheckpointProjectionLossReasonV1::RequiredInput => {
861                loss.required_input.is_some_and(|input| {
862                    loss.field_path == input.field_path()
863                        && target.is_none_or(|expected| input.target() == expected)
864                })
865            }
866        }
867}
868
869fn validate_plan(
870    plan: &ContextCheckpointProjectionPlanV1,
871    expected_target: Option<ContextCheckpointProjectionTargetV1>,
872) -> bool {
873    let Some(first_input) = plan.required_inputs.first().copied() else {
874        return false;
875    };
876    let target = first_input.target();
877    if expected_target.is_some_and(|expected| expected != target)
878        || plan.source_schema_version != ContextCheckpointV1::SCHEMA_VERSION
879        || plan.required_inputs != required_inputs(target)
880        || !plan
881            .represented_source_fields
882            .windows(2)
883            .all(|window| window[0] < window[1])
884        || plan.represented_source_fields.len() > SOURCE_FIELDS.len()
885        || !plan
886            .represented_source_fields
887            .iter()
888            .all(|field| field.len() <= 128 && SOURCE_FIELDS.binary_search(&field.as_str()).is_ok())
889    {
890        return false;
891    }
892
893    let expected_fields = match target {
894        ContextCheckpointProjectionTargetV1::SessionBundle => [
895            "live_state.decisions[*].rationale",
896            "live_state.decisions[*].statement",
897            "live_state.findings",
898            "live_state.next_steps",
899            "live_state.progress.summary",
900            "live_state.task.title",
901        ]
902        .as_slice(),
903        ContextCheckpointProjectionTargetV1::HandoffBundle => [
904            "lineage.evidence_refs",
905            "live_state.decisions[*].statement",
906            "live_state.findings",
907            "live_state.next_steps",
908            "live_state.task.title",
909        ]
910        .as_slice(),
911        ContextCheckpointProjectionTargetV1::ContextSnapshot => [
912            "live_state.decisions[*].statement",
913            "live_state.progress.summary",
914            "live_state.task.title",
915        ]
916        .as_slice(),
917        ContextCheckpointProjectionTargetV1::Ctxpkg => {
918            return plan.represented_source_fields.is_empty()
919                || plan.represented_source_fields == ["carrier"];
920        }
921        ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity => return false,
922    };
923    plan.represented_source_fields
924        .iter()
925        .map(String::as_str)
926        .eq(expected_fields.iter().copied())
927}
928
929#[cfg(test)]
930mod tests {
931    use super::*;
932    use lean_ctx_protocol::{
933        ContextCheckpointBranchIdV1, ContextCheckpointDecisionStatusV1,
934        ContextCheckpointDecisionV1, ContextCheckpointDeviceIdV1, ContextCheckpointFileRoleV1,
935        ContextCheckpointFileV1, ContextCheckpointIdV1, ContextCheckpointIdentityV1,
936        ContextCheckpointLineageV1, ContextCheckpointLiveStateV1, ContextCheckpointProgressV1,
937        ContextCheckpointSessionStateV1, ContextCheckpointTaskStatusV1, ContextCheckpointTaskV1,
938        ContextCheckpointTextV1, ContextSessionPhaseV1, ContextSessionRecoveryStateV1,
939        ContextSessionStateV1, DecisionId, PlanId, ProtocolReference, SemanticVersion,
940        SessionIdentityV1, Sha256Digest, SourceId, TaskId, UtcTimestamp,
941    };
942
943    fn id<T>(value: &str) -> T
944    where
945        T: TryFrom<String>,
946        <T as TryFrom<String>>::Error: std::fmt::Debug,
947    {
948        T::try_from(value.to_owned()).expect("fixture identity is valid")
949    }
950
951    fn reference(value: &str) -> ProtocolReference {
952        ProtocolReference::new(value).expect("fixture reference is valid")
953    }
954
955    fn digest(value: &str) -> Sha256Digest {
956        Sha256Digest::new(format!("sha256:{value:0<64}")).expect("fixture digest is valid")
957    }
958
959    fn checkpoint() -> ContextCheckpointV1 {
960        let task_id: TaskId = id("task-1");
961        let plan_id: PlanId = id("plan-1");
962        let lineage = ContextCheckpointLineageV1 {
963            project_id: id("project-1"),
964            workspace_id: id("550e8400-e29b-41d4-a716-446655440000"),
965            tenant_id: id("tenant-1"),
966            task_id: task_id.clone(),
967            plan_id: Some(plan_id.clone()),
968            receipt_ids: vec![id("receipt-1")],
969            context_ir_digest: Some(digest("a")),
970            hosted_index_digest: Some(digest("b")),
971            evidence_refs: vec![reference("evidence:one")],
972            knowledge_refs: vec![reference("knowledge:one")],
973            gotcha_refs: vec![reference("gotcha:one")],
974            snapshot_refs: vec![reference("snapshot:one")],
975        };
976        let live_state = ContextCheckpointLiveStateV1 {
977            schema_version: 1,
978            task: ContextCheckpointTaskV1 {
979                task_id,
980                title: ContextCheckpointTextV1::new("typed projection fixture").unwrap(),
981                status: ContextCheckpointTaskStatusV1::InProgress,
982                plan_id: Some(plan_id),
983            },
984            progress: ContextCheckpointProgressV1 {
985                completed_steps: 1,
986                total_steps: 2,
987                confidence_milliunits: 750,
988                summary: ContextCheckpointTextV1::new("half complete").unwrap(),
989            },
990            decisions: vec![ContextCheckpointDecisionV1 {
991                decision_id: id::<DecisionId>("decision-1"),
992                statement: ContextCheckpointTextV1::new("retain typed source").unwrap(),
993                rationale: ContextCheckpointTextV1::new("one semantic owner").unwrap(),
994                status: ContextCheckpointDecisionStatusV1::Accepted,
995                evidence_refs: vec![reference("evidence:one")],
996            }],
997            findings: vec![ContextCheckpointTextV1::new("finding one").unwrap()],
998            next_steps: vec![ContextCheckpointTextV1::new("verify gates").unwrap()],
999            handoff_summary: ContextCheckpointTextV1::new("continue projection").unwrap(),
1000            files: vec![ContextCheckpointFileV1 {
1001                source_id: id::<SourceId>("source-1"),
1002                role: ContextCheckpointFileRoleV1::Modified,
1003                content_digest: digest("c"),
1004            }],
1005            profile_id: Some(id("profile-1")),
1006            policy_pins: vec![],
1007            package_pins: vec![],
1008            session_state: Some(
1009                ContextCheckpointSessionStateV1::try_new(
1010                    SessionIdentityV1 {
1011                        session_id: id("session-1"),
1012                        task_id: id("task-1"),
1013                        run_id: id("run-1"),
1014                        trace_id: id("trace-1"),
1015                        parent_task_id: None,
1016                        agent_id: id("agent-1"),
1017                        project_id: id("project-1"),
1018                        workspace_id: Some(id("550e8400-e29b-41d4-a716-446655440000")),
1019                        tenant_id: Some(id("tenant-1")),
1020                        project_root_ref: reference("project:root"),
1021                        project_revision_ref: None,
1022                        created_at: UtcTimestamp::new("2026-01-01T00:00:00Z").unwrap(),
1023                    },
1024                    ContextSessionStateV1 {
1025                        phase: ContextSessionPhaseV1::Executing,
1026                        revision: 1,
1027                        next_event_sequence: 2,
1028                        active_plan_id: Some(id("plan-1")),
1029                        receipt_id: None,
1030                        last_checkpoint_digest: None,
1031                        recovery_state: ContextSessionRecoveryStateV1::Resumable,
1032                        abort_reason: None,
1033                    },
1034                )
1035                .unwrap(),
1036            ),
1037            learning_state: None,
1038        };
1039        let identity = ContextCheckpointIdentityV1::try_new(
1040            id::<ContextCheckpointIdV1>("550e8400-e29b-41d4-a716-446655440001"),
1041            None,
1042            None,
1043            None,
1044            None,
1045            id::<ContextCheckpointBranchIdV1>("main"),
1046            id::<ContextCheckpointDeviceIdV1>("device-1"),
1047            1,
1048        )
1049        .unwrap();
1050        ContextCheckpointV1::try_new(
1051            identity,
1052            lineage,
1053            live_state,
1054            None,
1055            SemanticVersion::new("1.0.0").unwrap(),
1056            UtcTimestamp::new("2026-01-01T00:00:00Z").unwrap(),
1057        )
1058        .unwrap()
1059    }
1060
1061    #[test]
1062    fn all_five_targets_are_explicit_and_versioned() {
1063        let results = ContextCheckpointProjections::new(&checkpoint())
1064            .unwrap()
1065            .project_all();
1066        assert_eq!(results.len(), 5);
1067        for (target, result) in ContextCheckpointProjectionTargetV1::all()
1068            .into_iter()
1069            .zip(results)
1070        {
1071            let result = result.unwrap();
1072            assert_eq!(result.target, target);
1073            assert_eq!(result.target_schema_version, target.schema_version());
1074            assert_eq!(result.projection_schema_version, 1);
1075        }
1076    }
1077
1078    #[test]
1079    fn identity_projection_is_lossless_only_for_identity_subset() {
1080        let source = checkpoint();
1081        let result = project_checkpoint(
1082            &source,
1083            ContextCheckpointProjectionTargetV1::ContextCheckpointIdentity,
1084            1,
1085        )
1086        .unwrap();
1087        assert_eq!(
1088            result.fidelity,
1089            ContextCheckpointProjectionFidelityV1::Lossless
1090        );
1091        assert!(result.losses.iter().all(|loss| {
1092            !loss.field_path.starts_with("identity.")
1093                && loss.reason == ContextCheckpointProjectionLossReasonV1::NotRepresentable
1094        }));
1095        match result.payload {
1096            ContextCheckpointProjectionPayloadV1::ContextCheckpointIdentity(payload) => {
1097                assert_eq!(payload.identity, source.identity);
1098            }
1099            _ => panic!("wrong identity payload"),
1100        }
1101    }
1102
1103    #[test]
1104    fn losses_are_golden_sorted_and_unique() {
1105        let source = checkpoint();
1106        let result = project_checkpoint(
1107            &source,
1108            ContextCheckpointProjectionTargetV1::SessionBundle,
1109            1,
1110        )
1111        .unwrap();
1112        let paths: Vec<_> = result
1113            .losses
1114            .iter()
1115            .map(|loss| loss.field_path.as_str())
1116            .collect();
1117        assert!(result.losses.windows(2).all(|window| window[0] < window[1]));
1118        assert_eq!(paths[0], "carrier");
1119        assert_eq!(paths[1], "created_at");
1120        assert_eq!(paths.last(), Some(&"updated_at"));
1121        assert_eq!(result.losses.len(), {
1122            let mut unique = paths.clone();
1123            unique.sort_unstable();
1124            unique.dedup();
1125            unique.len()
1126        });
1127    }
1128
1129    #[test]
1130    fn target_version_fails_closed() {
1131        let error = project_checkpoint(
1132            &checkpoint(),
1133            ContextCheckpointProjectionTargetV1::Ctxpkg,
1134            1,
1135        )
1136        .unwrap_err();
1137        assert_eq!(
1138            error,
1139            ContextCheckpointProjectionErrorV1::UnsupportedTargetVersion {
1140                target: ContextCheckpointProjectionTargetV1::Ctxpkg,
1141                requested: 1,
1142                supported: 2,
1143            }
1144        );
1145    }
1146
1147    #[test]
1148    fn source_version_fails_closed() {
1149        let mut source = checkpoint();
1150        source.schema_version = 2;
1151        assert_eq!(
1152            ContextCheckpointProjections::new(&source).unwrap_err(),
1153            ContextCheckpointProjectionErrorV1::UnsupportedSourceVersion {
1154                actual: 2,
1155                expected: 1,
1156            }
1157        );
1158    }
1159
1160    #[test]
1161    fn required_input_absence_is_typed_and_explicit() {
1162        let result = project_checkpoint(
1163            &checkpoint(),
1164            ContextCheckpointProjectionTargetV1::ContextSnapshot,
1165            1,
1166        )
1167        .unwrap();
1168        let required: Vec<_> = result
1169            .losses
1170            .iter()
1171            .filter_map(|loss| loss.required_input)
1172            .collect();
1173        assert_eq!(required.len(), 6);
1174        assert!(required.contains(&ContextCheckpointProjectionInputV1::ContextSnapshotRoi));
1175        assert!(required.contains(&ContextCheckpointProjectionInputV1::ContextSnapshotLedger));
1176    }
1177
1178    #[test]
1179    fn result_is_deterministic_and_source_is_not_mutated() {
1180        let source = checkpoint();
1181        let before = source.clone();
1182        let first = project_checkpoint(
1183            &source,
1184            ContextCheckpointProjectionTargetV1::HandoffBundle,
1185            1,
1186        )
1187        .unwrap();
1188        let second = project_checkpoint(
1189            &source,
1190            ContextCheckpointProjectionTargetV1::HandoffBundle,
1191            1,
1192        )
1193        .unwrap();
1194        assert_eq!(first, second);
1195        assert_eq!(source, before);
1196    }
1197
1198    #[test]
1199    fn duplicate_losses_are_eliminated_and_unknown_fields_reject() {
1200        let duplicate = ContextCheckpointProjectionLossV1::new(
1201            "live_state.findings",
1202            ContextCheckpointProjectionLossReasonV1::NotRepresentable,
1203            None,
1204        );
1205        assert_eq!(
1206            canonicalize_losses(vec![duplicate.clone(), duplicate]).len(),
1207            1
1208        );
1209
1210        let result = project_checkpoint(
1211            &checkpoint(),
1212            ContextCheckpointProjectionTargetV1::ContextSnapshot,
1213            1,
1214        )
1215        .unwrap();
1216        let mut encoded = serde_json::to_string(&result).unwrap();
1217        encoded.pop();
1218        encoded.push_str(",\"unknown\":1}");
1219        assert!(serde_json::from_str::<ContextCheckpointProjectionResultV1>(&encoded).is_err());
1220    }
1221
1222    #[test]
1223    fn public_projection_deserialization_rejects_inconsistent_wire_state() {
1224        let result = project_checkpoint(
1225            &checkpoint(),
1226            ContextCheckpointProjectionTargetV1::SessionBundle,
1227            1,
1228        )
1229        .unwrap();
1230        let encoded = serde_json::to_value(&result).unwrap();
1231
1232        for mutation in [
1233            ("/projection_schema_version", serde_json::json!(2)),
1234            ("/target", serde_json::json!("context_snapshot")),
1235            ("/target_schema_version", serde_json::json!(2)),
1236            ("/fidelity", serde_json::json!("lossless")),
1237            (
1238                "/payload/SessionBundle/source_schema_version",
1239                serde_json::json!(2),
1240            ),
1241            (
1242                "/payload/SessionBundle/required_inputs/0",
1243                serde_json::json!("ctxpkg_manifest"),
1244            ),
1245            (
1246                "/payload/SessionBundle/represented_source_fields/0",
1247                serde_json::json!("arbitrary.unbounded.field"),
1248            ),
1249        ] {
1250            let mut invalid = encoded.clone();
1251            *invalid.pointer_mut(mutation.0).expect("mutation pointer") = mutation.1;
1252            assert!(
1253                serde_json::from_value::<ContextCheckpointProjectionResultV1>(invalid).is_err(),
1254                "mutation at {} must fail closed",
1255                mutation.0
1256            );
1257        }
1258
1259        let mut unsorted_inputs = encoded.clone();
1260        unsorted_inputs["payload"]["SessionBundle"]["required_inputs"]
1261            .as_array_mut()
1262            .unwrap()
1263            .reverse();
1264        assert!(
1265            serde_json::from_value::<ContextCheckpointProjectionResultV1>(unsorted_inputs).is_err()
1266        );
1267
1268        let mut missing_loss = encoded;
1269        missing_loss["losses"].as_array_mut().unwrap().pop();
1270        assert!(
1271            serde_json::from_value::<ContextCheckpointProjectionResultV1>(missing_loss).is_err()
1272        );
1273
1274        let ContextCheckpointProjectionPayloadV1::SessionBundle(plan) = result.payload else {
1275            unreachable!()
1276        };
1277        let mut invalid_plan = serde_json::to_value(plan).unwrap();
1278        invalid_plan["required_inputs"]
1279            .as_array_mut()
1280            .unwrap()
1281            .clear();
1282        assert!(serde_json::from_value::<ContextCheckpointProjectionPlanV1>(invalid_plan).is_err());
1283
1284        let invalid_loss = serde_json::json!({
1285            "field_path": "target.exported_at",
1286            "reason": "not_representable",
1287            "required_input": "session_bundle_exported_at"
1288        });
1289        assert!(serde_json::from_value::<ContextCheckpointProjectionLossV1>(invalid_loss).is_err());
1290
1291        for invalid_loss in [
1292            serde_json::json!({
1293                "field_path": "not_a_canonical_field",
1294                "reason": "not_representable"
1295            }),
1296            serde_json::json!({
1297                "field_path": "target.created_at",
1298                "reason": "required_input",
1299                "required_input": "session_bundle_exported_at"
1300            }),
1301        ] {
1302            assert!(
1303                serde_json::from_value::<ContextCheckpointProjectionLossV1>(invalid_loss).is_err()
1304            );
1305        }
1306
1307        let mut checkpoint_with_carrier = checkpoint();
1308        checkpoint_with_carrier.carrier = Some(
1309            ContextCheckpointCarrierBindingV1::try_new(
1310                id("550e8400-e29b-41d4-a716-446655440000"),
1311                digest("d"),
1312                digest("e"),
1313            )
1314            .unwrap(),
1315        );
1316        let ctxpkg = project_checkpoint(
1317            &checkpoint_with_carrier,
1318            ContextCheckpointProjectionTargetV1::Ctxpkg,
1319            CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
1320        )
1321        .unwrap();
1322        let ContextCheckpointProjectionPayloadV1::Ctxpkg(ctxpkg) = ctxpkg.payload else {
1323            unreachable!();
1324        };
1325        let encoded_ctxpkg = serde_json::to_value(ctxpkg).unwrap();
1326
1327        let mut carrier_not_represented = encoded_ctxpkg.clone();
1328        carrier_not_represented["plan"]["represented_source_fields"] = serde_json::json!([]);
1329        assert!(
1330            serde_json::from_value::<ContextCheckpointCtxpkgProjectionV1>(carrier_not_represented)
1331                .is_err()
1332        );
1333
1334        let mut represented_without_carrier = encoded_ctxpkg;
1335        represented_without_carrier["carrier_binding"] = serde_json::Value::Null;
1336        assert!(
1337            serde_json::from_value::<ContextCheckpointCtxpkgProjectionV1>(
1338                represented_without_carrier
1339            )
1340            .is_err()
1341        );
1342    }
1343
1344    #[test]
1345    fn corrupt_session_state_is_rejected_for_wire_targets() {
1346        let mut source = checkpoint();
1347        source
1348            .live_state
1349            .session_state
1350            .as_mut()
1351            .unwrap()
1352            .state
1353            .recovery_state = ContextSessionRecoveryStateV1::Corrupt;
1354        source
1355            .live_state
1356            .session_state
1357            .as_mut()
1358            .unwrap()
1359            .state
1360            .phase = ContextSessionPhaseV1::Closed;
1361        // The source remains valid: this is an explicit state policy failure,
1362        // not an attempt to reinterpret corrupt continuation state.
1363        let error = ContextCheckpointProjections::new(&source)
1364            .unwrap()
1365            .project(ContextCheckpointProjectionTargetV1::SessionBundle, 1)
1366            .unwrap_err();
1367        assert_eq!(
1368            error,
1369            ContextCheckpointProjectionErrorV1::UnsupportedState {
1370                target: ContextCheckpointProjectionTargetV1::SessionBundle,
1371                state: ContextCheckpointProjectionUnsupportedStateV1::Corrupt,
1372            }
1373        );
1374    }
1375
1376    #[test]
1377    fn checkpoint_identity_is_the_only_semantic_owner() {
1378        let source = checkpoint();
1379        let result = project_checkpoint(
1380            &source,
1381            ContextCheckpointProjectionTargetV1::SessionBundle,
1382            1,
1383        )
1384        .unwrap();
1385        match result.payload {
1386            ContextCheckpointProjectionPayloadV1::SessionBundle(plan) => {
1387                assert_eq!(plan.source_checkpoint_id, source.identity.checkpoint_id);
1388                assert!(
1389                    plan.represented_source_fields
1390                        .iter()
1391                        .all(|field| { field.starts_with("live_state.") })
1392                );
1393            }
1394            _ => panic!("wrong session payload"),
1395        }
1396    }
1397}