Skip to main content

lean_ctx/core/context_checkpoint/
session_storage.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Versioned canonical continuation at the existing session persistence boundary.
3
4use crate::core::session::SessionState;
5use anyhow::{Result, ensure};
6use lean_ctx_protocol::{
7    ContextCheckpointDecisionStatusV1, ContextCheckpointDecisionV1, ContextCheckpointDecisionV2,
8    ContextCheckpointDeviceIdV1, ContextCheckpointIdV1, ContextCheckpointLiveStateV1,
9    ContextCheckpointLiveStateV2, ContextCheckpointProgressV1, ContextCheckpointTaskV1,
10    ContextCheckpointTextV1, ContextCheckpointTextV2, ContextCheckpointV2, ContextCheckpointV3,
11    DecisionId, Sha256Digest, UtcTimestamp, ValidationError,
12};
13use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
14use serde_json::value::RawValue;
15
16const SCHEMA: &str = "leanctx.session-checkpoint/v1";
17const NO_RATIONALE: &str = "No rationale supplied";
18const MAX_BYTES: usize = 4 * 1024 * 1024;
19
20/// One canonical checkpoint value carried by the existing session envelope.
21///
22/// The enum is an internal version dispatch only. It is serialized as the
23/// selected checkpoint object itself, never as an externally tagged enum.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub(crate) enum CanonicalCheckpoint {
26    V2(ContextCheckpointV2),
27    V3(ContextCheckpointV3),
28}
29
30impl CanonicalCheckpoint {
31    pub(crate) fn as_v2(&self) -> Option<&ContextCheckpointV2> {
32        match self {
33            Self::V2(checkpoint) => Some(checkpoint),
34            Self::V3(_) => None,
35        }
36    }
37
38    pub(crate) fn as_v3(&self) -> Option<&ContextCheckpointV3> {
39        match self {
40            Self::V2(_) => None,
41            Self::V3(checkpoint) => Some(checkpoint),
42        }
43    }
44
45    pub(crate) fn validate(&self) -> Result<(), ValidationError> {
46        match self {
47            Self::V2(checkpoint) => checkpoint.validate(),
48            Self::V3(checkpoint) => checkpoint.validate(),
49        }
50    }
51
52    pub(crate) fn digest(&self) -> Result<Sha256Digest, ValidationError> {
53        match self {
54            Self::V2(checkpoint) => checkpoint.digest(),
55            Self::V3(checkpoint) => checkpoint.digest(),
56        }
57    }
58
59    pub(crate) fn identity(&self) -> &lean_ctx_protocol::ContextCheckpointIdentityV1 {
60        match self {
61            Self::V2(checkpoint) => &checkpoint.identity,
62            Self::V3(checkpoint) => &checkpoint.identity,
63        }
64    }
65
66    pub(crate) fn identity_mut(&mut self) -> &mut lean_ctx_protocol::ContextCheckpointIdentityV1 {
67        match self {
68            Self::V2(checkpoint) => &mut checkpoint.identity,
69            Self::V3(checkpoint) => &mut checkpoint.identity,
70        }
71    }
72
73    pub(crate) fn set_updated_at(&mut self, updated_at: UtcTimestamp) {
74        match self {
75            Self::V2(checkpoint) => checkpoint.updated_at = updated_at,
76            Self::V3(checkpoint) => checkpoint.updated_at = updated_at,
77        }
78    }
79
80    /// Clear protected/carrier metadata after a local plaintext revision.
81    pub(crate) fn clear_protected_metadata(&mut self) {
82        match self {
83            Self::V2(checkpoint) => {
84                checkpoint.carrier = None;
85                checkpoint.encryption_metadata = None;
86            }
87            Self::V3(checkpoint) => {
88                checkpoint.carrier = None;
89                checkpoint.encryption_metadata = None;
90            }
91        }
92    }
93
94    /// Return the live state through the Unicode adapter without establishing
95    /// artifact ownership or signing authority.
96    pub(crate) fn unicode_live_state(
97        &self,
98    ) -> Result<ContextCheckpointLiveStateV2, ValidationError> {
99        match self {
100            Self::V2(checkpoint) => {
101                Ok(ContextCheckpointV3::from_v2_unverified(checkpoint.clone())?.live_state)
102            }
103            Self::V3(checkpoint) => Ok(checkpoint.live_state.clone()),
104        }
105    }
106
107    /// Replace live state while keeping the stored wire version unchanged.
108    /// V2 therefore fails closed if a Unicode edit cannot be represented.
109    pub(crate) fn replace_unicode_live_state(
110        &mut self,
111        live_state: ContextCheckpointLiveStateV2,
112    ) -> Result<(), ValidationError> {
113        match self {
114            Self::V2(checkpoint) => {
115                checkpoint.live_state = unicode_live_state_to_v1(live_state)?;
116                checkpoint.validate()
117            }
118            Self::V3(checkpoint) => {
119                live_state.validate()?;
120                checkpoint.live_state = live_state;
121                checkpoint.validate()
122            }
123        }
124    }
125}
126
127impl Serialize for CanonicalCheckpoint {
128    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129    where
130        S: Serializer,
131    {
132        match self {
133            Self::V2(checkpoint) => checkpoint.serialize(serializer),
134            Self::V3(checkpoint) => checkpoint.serialize(serializer),
135        }
136    }
137}
138
139impl<'de> Deserialize<'de> for CanonicalCheckpoint {
140    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
141    where
142        D: Deserializer<'de>,
143    {
144        #[derive(Deserialize)]
145        struct SchemaDiscriminator {
146            schema_version: u32,
147        }
148
149        let raw = Box::<RawValue>::deserialize(deserializer)?;
150        let schema_version = serde_json::from_str::<SchemaDiscriminator>(raw.get())
151            .map_err(DeError::custom)?
152            .schema_version;
153        match schema_version {
154            2 => serde_json::from_str::<ContextCheckpointV2>(raw.get())
155                .map(Self::V2)
156                .map_err(DeError::custom),
157            3 => serde_json::from_str::<ContextCheckpointV3>(raw.get())
158                .map(Self::V3)
159                .map_err(DeError::custom),
160            _ => Err(DeError::custom(format!(
161                "unsupported canonical checkpoint schema_version {schema_version}"
162            ))),
163        }
164    }
165}
166
167fn unicode_live_state_to_v1(
168    live: ContextCheckpointLiveStateV2,
169) -> Result<ContextCheckpointLiveStateV1, ValidationError> {
170    Ok(ContextCheckpointLiveStateV1 {
171        schema_version: ContextCheckpointLiveStateV1::SCHEMA_VERSION,
172        task: ContextCheckpointTaskV1 {
173            task_id: live.task.task_id,
174            title: ContextCheckpointTextV1::new(live.task.title.into_inner())?,
175            status: live.task.status,
176            plan_id: live.task.plan_id,
177        },
178        progress: ContextCheckpointProgressV1 {
179            completed_steps: live.progress.completed_steps,
180            total_steps: live.progress.total_steps,
181            confidence_milliunits: live.progress.confidence_milliunits,
182            summary: ContextCheckpointTextV1::new(live.progress.summary.into_inner())?,
183        },
184        decisions: live
185            .decisions
186            .into_iter()
187            .map(|decision| {
188                Ok(ContextCheckpointDecisionV1 {
189                    decision_id: decision.decision_id,
190                    statement: ContextCheckpointTextV1::new(decision.statement.into_inner())?,
191                    rationale: ContextCheckpointTextV1::new(decision.rationale.into_inner())?,
192                    status: decision.status,
193                    evidence_refs: decision.evidence_refs,
194                })
195            })
196            .collect::<Result<_, ValidationError>>()?,
197        findings: live
198            .findings
199            .into_iter()
200            .map(|text| ContextCheckpointTextV1::new(text.into_inner()))
201            .collect::<Result<_, ValidationError>>()?,
202        next_steps: live
203            .next_steps
204            .into_iter()
205            .map(|text| ContextCheckpointTextV1::new(text.into_inner()))
206            .collect::<Result<_, ValidationError>>()?,
207        handoff_summary: ContextCheckpointTextV1::new(live.handoff_summary.into_inner())?,
208        files: live.files,
209        profile_id: live.profile_id,
210        policy_pins: live.policy_pins,
211        package_pins: live.package_pins,
212        session_state: live.session_state,
213        learning_state: live.learning_state,
214    })
215}
216
217#[derive(Clone, Debug, Serialize, Deserialize)]
218#[serde(deny_unknown_fields)]
219pub(crate) struct CanonicalSession {
220    /// Exact committed primary bytes observed by this reader; not a wire field.
221    #[serde(skip)]
222    pub(crate) storage_digest: Option<Sha256Digest>,
223    pub(crate) checkpoint: CanonicalCheckpoint,
224    source_artifact_digest: Sha256Digest,
225    local_device: ContextCheckpointDeviceIdV1,
226    project_root: String,
227}
228
229/// Opaque canonical checkpoint identity retained as personal history only.
230#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
231#[serde(deny_unknown_fields)]
232pub(crate) struct PersonalCheckpointLineageV1 {
233    pub(crate) checkpoint_id: String,
234    pub(crate) parent_checkpoint_id: Option<String>,
235    pub(crate) parent_device_id: Option<String>,
236    pub(crate) parent_branch_id: Option<String>,
237    pub(crate) branch_id: String,
238    pub(crate) device_id: String,
239    pub(crate) device_sequence: u64,
240}
241
242impl PersonalCheckpointLineageV1 {
243    pub(crate) fn validate(&self) -> anyhow::Result<()> {
244        let valid = |value: &str| {
245            !value.is_empty()
246                && value.len() <= 256
247                && value.chars().all(|character| !character.is_control())
248        };
249        anyhow::ensure!(
250            valid(&self.checkpoint_id)
251                && valid(&self.branch_id)
252                && valid(&self.device_id)
253                && self.device_sequence > 0
254                && self.parent_checkpoint_id.as_deref().is_none_or(valid)
255                && self.parent_device_id.as_deref().is_none_or(valid)
256                && self.parent_branch_id.as_deref().is_none_or(valid)
257                && (self.parent_checkpoint_id.is_some() == self.parent_device_id.is_some())
258                && (self.parent_checkpoint_id.is_some() == self.parent_branch_id.is_some()),
259            "invalid historical checkpoint identity"
260        );
261        Ok(())
262    }
263}
264
265#[derive(Serialize, Deserialize)]
266#[serde(deny_unknown_fields)]
267struct StoredSession {
268    storage_schema: String,
269    version: u32,
270    canonical: CanonicalSession,
271    checkpoint_digest: Sha256Digest,
272    #[serde(default)]
273    previous_storage_digest: Option<Sha256Digest>,
274    view: SessionState,
275}
276
277impl CanonicalSession {
278    pub(crate) fn admitted(
279        verified: &super::VerifiedContextCheckpointV2,
280        source_artifact_digest: Sha256Digest,
281        project_root: String,
282    ) -> Result<Self> {
283        let checkpoint = CanonicalCheckpoint::V2(verified.checkpoint().clone());
284        Self::admitted_checkpoint(checkpoint, source_artifact_digest, project_root)
285    }
286
287    pub(crate) fn admitted_v3(
288        verified: &super::VerifiedContextCheckpointV3,
289        source_artifact_digest: Sha256Digest,
290        project_root: String,
291    ) -> Result<Self> {
292        let checkpoint = CanonicalCheckpoint::V3(verified.checkpoint().clone());
293        Self::admitted_checkpoint(checkpoint, source_artifact_digest, project_root)
294    }
295
296    /// Keep structural identity as user history without verifying or adopting it.
297    pub(crate) fn historical_personal_lineage(&self) -> PersonalCheckpointLineageV1 {
298        let identity = self.checkpoint.identity();
299        PersonalCheckpointLineageV1 {
300            checkpoint_id: identity.checkpoint_id.as_str().to_owned(),
301            parent_checkpoint_id: identity
302                .parent_checkpoint_id
303                .as_ref()
304                .map(|value| value.as_str().to_owned()),
305            parent_device_id: identity
306                .parent_device_id
307                .as_ref()
308                .map(|value| value.as_str().to_owned()),
309            parent_branch_id: identity
310                .parent_branch_id
311                .as_ref()
312                .map(|value| value.as_str().to_owned()),
313            branch_id: identity.branch_id.as_str().to_owned(),
314            device_id: identity.device_id.as_str().to_owned(),
315            device_sequence: identity.device_sequence,
316        }
317    }
318
319    fn admitted_checkpoint(
320        checkpoint: CanonicalCheckpoint,
321        source_artifact_digest: Sha256Digest,
322        project_root: String,
323    ) -> Result<Self> {
324        checkpoint.validate()?;
325        Ok(Self {
326            storage_digest: None,
327            checkpoint,
328            source_artifact_digest,
329            local_device: ContextCheckpointDeviceIdV1::new(format!(
330                "local-{}",
331                uuid::Uuid::new_v4()
332            ))?,
333            project_root,
334        })
335    }
336
337    fn synchronize(&self, session: &SessionState) -> Result<CanonicalCheckpoint> {
338        ensure!(
339            session.project_root.as_ref() == Some(&self.project_root),
340            "canonical session scope changed"
341        );
342        let mut next = self.checkpoint.clone();
343        let mut live = next.unicode_live_state()?;
344        let task = session
345            .task
346            .as_ref()
347            .ok_or_else(|| anyhow::anyhow!("canonical task cannot be cleared"))?;
348        live.task.title = ContextCheckpointTextV2::new(task.description.clone())?;
349        let current_pct = if live.progress.total_steps == 0 {
350            None
351        } else {
352            Some(u8::try_from(
353                u64::from(live.progress.completed_steps) * 100
354                    / u64::from(live.progress.total_steps),
355            )?)
356        };
357        if task.progress_pct != current_pct {
358            if let Some(percent) = task.progress_pct {
359                ensure!(percent <= 100, "invalid progress percentage");
360                live.progress.completed_steps = u32::from(percent);
361                live.progress.total_steps = 100;
362            } else {
363                anyhow::bail!("canonical progress cannot be cleared");
364            }
365        }
366        live.findings = session
367            .findings
368            .iter()
369            .map(|finding| ContextCheckpointTextV2::new(finding.summary.clone()))
370            .collect::<std::result::Result<_, _>>()?;
371        live.next_steps = session
372            .next_steps
373            .iter()
374            .map(|step| ContextCheckpointTextV2::new(step.clone()))
375            .collect::<std::result::Result<_, _>>()?;
376        let accepted: Vec<_> = live
377            .decisions
378            .iter()
379            .filter(|decision| decision.status == ContextCheckpointDecisionStatusV1::Accepted)
380            .collect();
381        let decisions_unchanged = accepted.len() == session.decisions.len()
382            && accepted
383                .iter()
384                .zip(&session.decisions)
385                .all(|(canonical, view)| {
386                    canonical.statement.as_str() == view.summary
387                        && canonical.rationale.as_str()
388                            == view.rationale.as_deref().unwrap_or(NO_RATIONALE)
389                });
390        if !decisions_unchanged {
391            let mut decisions: Vec<_> = live
392                .decisions
393                .iter()
394                .filter(|decision| decision.status != ContextCheckpointDecisionStatusV1::Accepted)
395                .cloned()
396                .collect();
397            for view in &session.decisions {
398                let rationale = view.rationale.as_deref().unwrap_or(NO_RATIONALE);
399                let existing = accepted.iter().find(|decision| {
400                    decision.statement.as_str() == view.summary
401                        && decision.rationale.as_str() == rationale
402                });
403                decisions.push(if let Some(existing) = existing {
404                    (*existing).clone()
405                } else {
406                    ContextCheckpointDecisionV2 {
407                        decision_id: DecisionId::new(format!("decision-{}", uuid::Uuid::new_v4()))?,
408                        statement: ContextCheckpointTextV2::new(view.summary.clone())?,
409                        rationale: ContextCheckpointTextV2::new(rationale.to_owned())?,
410                        status: ContextCheckpointDecisionStatusV1::Accepted,
411                        evidence_refs: Vec::new(),
412                    }
413                });
414            }
415            decisions.sort_by(|left, right| left.decision_id.cmp(&right.decision_id));
416            live.decisions = decisions;
417        }
418        live.validate()?;
419        next.replace_unicode_live_state(live)?;
420        next.validate()?;
421        Ok(next)
422    }
423
424    fn advance(&self, session: &SessionState) -> Result<Self> {
425        let mut next = self.synchronize(session)?;
426        if next != self.checkpoint {
427            let live = next.unicode_live_state()?;
428            if let Some(lifecycle) = &live.session_state {
429                use lean_ctx_protocol::{ContextSessionPhaseV1, ContextSessionRecoveryStateV1};
430                ensure!(
431                    !matches!(
432                        lifecycle.state.phase,
433                        ContextSessionPhaseV1::Closed | ContextSessionPhaseV1::Aborted
434                    ) && !matches!(
435                        lifecycle.state.recovery_state,
436                        ContextSessionRecoveryStateV1::InspectOnly
437                            | ContextSessionRecoveryStateV1::Corrupt
438                    ),
439                    "checkpoint lifecycle refuses local continuation"
440                );
441            }
442            let parent = self.checkpoint.identity();
443            *next.identity_mut() = lean_ctx_protocol::ContextCheckpointIdentityV1::try_new(
444                ContextCheckpointIdV1::new(uuid::Uuid::new_v4().to_string())?,
445                Some(parent.checkpoint_id.clone()),
446                Some(parent.device_id.clone()),
447                Some(parent.branch_id.clone()),
448                Some(parent.device_sequence),
449                parent.branch_id.clone(),
450                self.local_device.clone(),
451                if parent.device_id == self.local_device {
452                    parent
453                        .device_sequence
454                        .checked_add(1)
455                        .ok_or_else(|| anyhow::anyhow!("checkpoint sequence exhausted"))?
456                } else {
457                    1
458                },
459            )?;
460            next.set_updated_at(UtcTimestamp::new(
461                chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
462            )?);
463            // Changed plaintext is not the old protected/carrier projection.
464            next.clear_protected_metadata();
465            next.validate()?;
466        }
467        Ok(Self {
468            checkpoint: next,
469            ..self.clone()
470        })
471    }
472}
473
474impl SessionState {
475    /// Export only a validated committed checkpoint, never a pending view or legacy projection.
476    pub(crate) fn canonical_checkpoint_for_export(
477        id: &str,
478    ) -> Result<(CanonicalCheckpoint, String), String> {
479        let session = Self::load_by_id(id).ok_or("canonical session cannot be loaded")?;
480        let binding = session
481            .canonical_checkpoint
482            .ok_or("session has no canonical checkpoint; use the legacy export path")?;
483        Ok((binding.checkpoint, binding.project_root))
484    }
485
486    /// Decode the current canonical storage envelope or the historical flat shape.
487    /// This is local state, never signer admission or a policy/entitlement grant.
488    pub fn from_storage_json(json: &str) -> Result<Self, String> {
489        decode(json).map_err(|error| error.to_string())
490    }
491
492    pub(crate) fn storage_json(&self) -> Result<(String, Option<Box<CanonicalSession>>), String> {
493        let mut view = self.clone();
494        view.stats.unsaved_changes = 0;
495        let Some(current) = self.canonical_checkpoint.as_ref() else {
496            return serde_json::to_string_pretty(&view)
497                .map(|json| (json, None))
498                .map_err(|error| error.to_string());
499        };
500        let advanced = current.advance(self).map_err(|error| error.to_string())?;
501        let checkpoint_digest = advanced
502            .checkpoint
503            .digest()
504            .map_err(|error| error.to_string())?;
505        let stored = StoredSession {
506            storage_schema: SCHEMA.into(),
507            version: self.version,
508            canonical: advanced.clone(),
509            checkpoint_digest,
510            previous_storage_digest: current.storage_digest.clone(),
511            view,
512        };
513        let json = serde_json::to_string_pretty(&stored).map_err(|error| error.to_string())?;
514        if json.len() > MAX_BYTES {
515            return Err("canonical session exceeds storage bound".into());
516        }
517        Ok((json, Some(Box::new(advanced))))
518    }
519}
520
521fn decode(json: &str) -> Result<SessionState> {
522    let value: serde_json::Value = serde_json::from_str(json)?;
523    if value.get("storage_schema").is_none() {
524        return Ok(serde_json::from_str(json)?);
525    }
526    ensure!(json.len() <= MAX_BYTES, "session exceeds storage bound");
527    let mut stored: StoredSession = serde_json::from_str(json)?;
528    ensure!(
529        stored.storage_schema == SCHEMA,
530        "unsupported session storage schema"
531    );
532    ensure!(
533        stored.version == stored.view.version,
534        "session version mismatch"
535    );
536    ensure!(
537        stored.checkpoint_digest == stored.canonical.checkpoint.digest()?,
538        "checkpoint digest mismatch"
539    );
540    ensure!(
541        stored.canonical.synchronize(&stored.view)? == stored.canonical.checkpoint,
542        "session view disagrees with canonical checkpoint"
543    );
544    stored.canonical.storage_digest = Some(storage_digest(json.as_bytes())?);
545    stored.view.canonical_checkpoint = Some(Box::new(stored.canonical));
546    Ok(stored.view)
547}
548
549fn storage_digest(bytes: &[u8]) -> Result<Sha256Digest> {
550    use sha2::{Digest as _, Sha256};
551    Ok(Sha256Digest::new(format!(
552        "sha256:{}",
553        crate::core::agent_identity::hex_encode(&Sha256::digest(bytes))
554    ))?)
555}
556
557/// The existing per-session writer calls this while holding its save lock.
558/// Final lineage follows the actually committed head, not a deferred snapshot.
559pub(crate) fn prepare_commit(candidate: &str, previous: Option<&[u8]>) -> Result<String, String> {
560    commit(candidate, previous).map_err(|error| error.to_string())
561}
562
563fn commit(candidate: &str, previous: Option<&[u8]>) -> Result<String> {
564    let mut incoming = decode(candidate)?;
565    let prior = previous
566        .map(|bytes| -> Result<SessionState> { decode(std::str::from_utf8(bytes)?) })
567        .transpose()?;
568    let Some(binding) = incoming.canonical_checkpoint.as_ref() else {
569        ensure!(
570            prior
571                .as_ref()
572                .is_none_or(|state| state.canonical_checkpoint.is_none()),
573            "refusing canonical session downgrade"
574        );
575        return Ok(candidate.into());
576    };
577    let mut stored: StoredSession = serde_json::from_str(candidate)?;
578    ensure!(
579        stored.previous_storage_digest == previous.map(storage_digest).transpose()?,
580        "canonical session changed since it was read; reload before retrying"
581    );
582    if let Some(prior) = prior {
583        ensure!(
584            prior.id == incoming.id,
585            "canonical session identity mismatch"
586        );
587        let head = prior
588            .canonical_checkpoint
589            .as_ref()
590            .ok_or_else(|| anyhow::anyhow!("canonical adoption requires a fresh session"))?;
591        ensure!(
592            head.source_artifact_digest == binding.source_artifact_digest
593                && head.project_root == binding.project_root
594                && head.local_device == binding.local_device,
595            "canonical session authority changed"
596        );
597        stored.canonical = head.advance(&incoming)?;
598        ensure!(
599            prior.version < incoming.version || stored.canonical.checkpoint == head.checkpoint,
600            "conflicting canonical session revision"
601        );
602        stored.checkpoint_digest = stored.canonical.checkpoint.digest()?;
603        if let Some(bytes) = previous {
604            let hash = storage_digest(bytes)?;
605            drop(
606                crate::core::engine_artifact::persist_content(
607                    "sessions/checkpoints",
608                    hash.hex(),
609                    "json",
610                    bytes,
611                )
612                .map_err(anyhow::Error::msg)?,
613            );
614            stored.previous_storage_digest = Some(hash);
615        }
616    }
617    // The view is an explicitly checked compatibility cache, never a fallback
618    // authority when it disagrees with the checkpoint.
619    incoming.canonical_checkpoint = None;
620    stored.view = incoming;
621    let encoded = serde_json::to_string_pretty(&stored)?;
622    ensure!(
623        encoded.len() <= MAX_BYTES,
624        "canonical session exceeds storage bound"
625    );
626    Ok(encoded)
627}