1use std::collections::BTreeSet;
6use std::fmt;
7
8use lean_ctx_protocol::{
9 AcceptedOutcomeV1, ContextCheckpointBranchIdV1, ContextCheckpointDeviceIdV1,
10 ContextCheckpointIdV1, ContextCheckpointIdentityV1, ContextCheckpointMergePolicyV1,
11 ContextCheckpointV1, ContextCheckpointV2, ExecutionPlanV1, Sha256Digest, TaskEnvelopeV1,
12 UtcTimestamp,
13};
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value};
16
17use super::{
18 VerifiedContextCheckpointV2, VerifiedReceiptDocumentV1, validate_checkpoint_lineage,
19 verify_checkpoint_v2,
20};
21
22const MERGE_SIGNATURE_DOMAIN_V1: &[u8] = b"leanctx/context-checkpoint-merge/v1\0";
23const MERGE_SIGNATURE_DOMAIN_V2: &[u8] = b"leanctx/context-checkpoint-merge/v2\0";
24const MAX_MERGE_CONFLICTS: usize = 256;
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct ContextCheckpointChildSpecV1 {
29 pub checkpoint_id: ContextCheckpointIdV1,
30 pub branch_id: ContextCheckpointBranchIdV1,
31 pub device_id: ContextCheckpointDeviceIdV1,
32 pub device_sequence: u64,
33 pub created_at: UtcTimestamp,
34}
35
36#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
38#[serde(rename_all = "snake_case")]
39pub enum ContextCheckpointConflictPolicyV1 {
40 Fail,
41 PreferLeft,
42 PreferRight,
43}
44
45#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
47#[serde(rename_all = "snake_case")]
48pub enum ContextCheckpointConflictResolutionV1 {
49 Unresolved,
50 Left,
51 Right,
52}
53
54#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
56#[serde(deny_unknown_fields)]
57pub struct ContextCheckpointMergeConflictV1 {
58 pub field_path: String,
59 pub resolution: ContextCheckpointConflictResolutionV1,
60}
61
62#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
64#[serde(deny_unknown_fields)]
65pub struct ContextCheckpointMergeReceiptV1 {
66 schema_version: u32,
67 ancestor_digest: Sha256Digest,
68 left_digest: Sha256Digest,
69 right_digest: Sha256Digest,
70 output_digest: Sha256Digest,
71 policy: ContextCheckpointConflictPolicyV1,
72 conflicts: Vec<ContextCheckpointMergeConflictV1>,
73}
74
75impl ContextCheckpointMergeReceiptV1 {
76 pub const SCHEMA_VERSION: u32 = 1;
77
78 pub fn ancestor_digest(&self) -> &Sha256Digest {
79 &self.ancestor_digest
80 }
81 pub fn left_digest(&self) -> &Sha256Digest {
82 &self.left_digest
83 }
84 pub fn right_digest(&self) -> &Sha256Digest {
85 &self.right_digest
86 }
87 pub fn output_digest(&self) -> &Sha256Digest {
88 &self.output_digest
89 }
90 pub fn conflicts(&self) -> &[ContextCheckpointMergeConflictV1] {
91 &self.conflicts
92 }
93
94 pub fn signing_payload(&self) -> Vec<u8> {
96 let mut bytes = MERGE_SIGNATURE_DOMAIN_V1.to_vec();
97 bytes.extend(crate::core::canonical::canonical_serialize(self));
98 bytes
99 }
100}
101
102#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
107#[serde(deny_unknown_fields)]
108pub struct ContextCheckpointMergeReceiptV2 {
109 schema_version: u32,
110 ancestor_digest: Sha256Digest,
111 left_digest: Sha256Digest,
112 right_digest: Sha256Digest,
113 output_digest: Sha256Digest,
114 policy: ContextCheckpointConflictPolicyV1,
115 conflicts: Vec<ContextCheckpointMergeConflictV1>,
116}
117
118impl ContextCheckpointMergeReceiptV2 {
119 pub const SCHEMA_VERSION: u32 = 2;
120
121 pub fn ancestor_digest(&self) -> &Sha256Digest {
122 &self.ancestor_digest
123 }
124 pub fn left_digest(&self) -> &Sha256Digest {
125 &self.left_digest
126 }
127 pub fn right_digest(&self) -> &Sha256Digest {
128 &self.right_digest
129 }
130 pub fn output_digest(&self) -> &Sha256Digest {
131 &self.output_digest
132 }
133 pub fn conflicts(&self) -> &[ContextCheckpointMergeConflictV1] {
134 &self.conflicts
135 }
136
137 pub fn signing_payload(&self) -> Vec<u8> {
139 let mut bytes = MERGE_SIGNATURE_DOMAIN_V2.to_vec();
140 bytes.extend(crate::core::canonical::canonical_serialize(self));
141 bytes
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct ContextCheckpointMergeResultV1 {
148 checkpoint: ContextCheckpointV1,
149 receipt: ContextCheckpointMergeReceiptV1,
150}
151
152#[derive(Clone, Debug, PartialEq, Eq)]
154pub struct VerifiedContextCheckpointMergeResultV2 {
155 checkpoint: VerifiedContextCheckpointV2,
156 receipt: ContextCheckpointMergeReceiptV2,
157}
158
159impl VerifiedContextCheckpointMergeResultV2 {
160 pub fn checkpoint(&self) -> &VerifiedContextCheckpointV2 {
161 &self.checkpoint
162 }
163
164 pub fn receipt(&self) -> &ContextCheckpointMergeReceiptV2 {
165 &self.receipt
166 }
167
168 pub fn into_parts(self) -> (VerifiedContextCheckpointV2, ContextCheckpointMergeReceiptV2) {
169 (self.checkpoint, self.receipt)
170 }
171}
172
173impl ContextCheckpointMergeResultV1 {
174 pub fn checkpoint(&self) -> &ContextCheckpointV1 {
175 &self.checkpoint
176 }
177 pub fn receipt(&self) -> &ContextCheckpointMergeReceiptV1 {
178 &self.receipt
179 }
180 pub fn into_parts(self) -> (ContextCheckpointV1, ContextCheckpointMergeReceiptV1) {
181 (self.checkpoint, self.receipt)
182 }
183}
184
185#[derive(Clone, Debug, PartialEq, Eq)]
187pub enum ContextCheckpointMergeErrorV1 {
188 InvalidCheckpoint(String),
189 ScopeMismatch,
190 InvalidAncestry,
191 NonMonotonicTimestamp,
192 TooManyConflicts,
193 Conflicts(Vec<ContextCheckpointMergeConflictV1>),
194}
195
196impl fmt::Display for ContextCheckpointMergeErrorV1 {
197 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(formatter, "{self:?}")
199 }
200}
201
202impl std::error::Error for ContextCheckpointMergeErrorV1 {}
203
204pub fn branch_checkpoint_v1(
206 parent: &ContextCheckpointV1,
207 spec: &ContextCheckpointChildSpecV1,
208) -> Result<ContextCheckpointV1, ContextCheckpointMergeErrorV1> {
209 parent.validate().map_err(invalid)?;
210 if spec.created_at < parent.updated_at {
211 return Err(ContextCheckpointMergeErrorV1::NonMonotonicTimestamp);
212 }
213 let mut child = parent.clone();
214 child.identity = child_identity_from(&parent.identity, spec)?;
215 child.created_at = spec.created_at.clone();
216 child.updated_at = spec.created_at.clone();
217 child.validate().map_err(invalid)?;
218 Ok(child)
219}
220
221pub fn branch_verified_checkpoint_v2(
223 parent: &VerifiedContextCheckpointV2,
224 spec: &ContextCheckpointChildSpecV1,
225 task: &TaskEnvelopeV1,
226 plan: Option<&ExecutionPlanV1>,
227 receipts: &[VerifiedReceiptDocumentV1],
228 outcomes: &[AcceptedOutcomeV1],
229) -> Result<VerifiedContextCheckpointV2, ContextCheckpointMergeErrorV1> {
230 if spec.created_at < parent.updated_at {
231 return Err(ContextCheckpointMergeErrorV1::NonMonotonicTimestamp);
232 }
233 let mut child = parent.checkpoint().clone();
234 child.identity = child_identity_from(&parent.identity, spec)?;
235 child.created_at = spec.created_at.clone();
236 child.updated_at = spec.created_at.clone();
237 child.validate().map_err(invalid)?;
238 verify_checkpoint_v2(child, task, plan, receipts, outcomes).map_err(invalid)
239}
240
241pub fn merge_checkpoints_v1(
243 ancestor: &ContextCheckpointV1,
244 left_chain: &[ContextCheckpointV1],
245 left: &ContextCheckpointV1,
246 right_chain: &[ContextCheckpointV1],
247 right: &ContextCheckpointV1,
248 spec: &ContextCheckpointChildSpecV1,
249 policy: ContextCheckpointConflictPolicyV1,
250) -> Result<ContextCheckpointMergeResultV1, ContextCheckpointMergeErrorV1> {
251 for checkpoint in [ancestor, left, right] {
252 checkpoint.validate().map_err(invalid)?;
253 if !same_scope(ancestor, checkpoint) {
254 return Err(ContextCheckpointMergeErrorV1::ScopeMismatch);
255 }
256 }
257 validate_chain(ancestor, left_chain, left)?;
258 validate_chain(ancestor, right_chain, right)?;
259 if spec.created_at < left.updated_at || spec.created_at < right.updated_at {
260 return Err(ContextCheckpointMergeErrorV1::NonMonotonicTimestamp);
261 }
262
263 let mut ancestor_value = semantic_value(ancestor)?;
264 let left_value = semantic_value(left)?;
265 let right_value = semantic_value(right)?;
266 let mut conflicts = Vec::new();
267 ancestor_value = merge_node(
268 "",
269 Some(&ancestor_value),
270 Some(&left_value),
271 Some(&right_value),
272 policy,
273 &mut conflicts,
274 )
275 .expect("three present root objects always produce a value");
276 if conflicts.len() > MAX_MERGE_CONFLICTS {
277 return Err(ContextCheckpointMergeErrorV1::TooManyConflicts);
278 }
279 if policy == ContextCheckpointConflictPolicyV1::Fail && !conflicts.is_empty() {
280 return Err(ContextCheckpointMergeErrorV1::Conflicts(conflicts));
281 }
282
283 let object = ancestor_value.as_object_mut().ok_or_else(|| {
284 ContextCheckpointMergeErrorV1::InvalidCheckpoint("checkpoint root is not object".into())
285 })?;
286 object.insert(
287 "identity".into(),
288 serde_json::to_value(child_identity_from(&left.identity, spec)?).map_err(json_invalid)?,
289 );
290 object.insert(
291 "created_at".into(),
292 serde_json::to_value(&spec.created_at).map_err(json_invalid)?,
293 );
294 object.insert(
295 "updated_at".into(),
296 serde_json::to_value(&spec.created_at).map_err(json_invalid)?,
297 );
298 let checkpoint: ContextCheckpointV1 =
299 serde_json::from_value(ancestor_value).map_err(json_invalid)?;
300 checkpoint.validate().map_err(invalid)?;
301
302 conflicts.sort_by(|a, b| a.field_path.cmp(&b.field_path));
303 if conflicts
304 .windows(2)
305 .any(|pair| pair[0].field_path == pair[1].field_path)
306 {
307 return Err(ContextCheckpointMergeErrorV1::InvalidCheckpoint(
308 "duplicate merge conflict path".into(),
309 ));
310 }
311 let receipt = ContextCheckpointMergeReceiptV1 {
312 schema_version: ContextCheckpointMergeReceiptV1::SCHEMA_VERSION,
313 ancestor_digest: ancestor.digest().map_err(invalid)?,
314 left_digest: left.digest().map_err(invalid)?,
315 right_digest: right.digest().map_err(invalid)?,
316 output_digest: checkpoint.digest().map_err(invalid)?,
317 policy,
318 conflicts,
319 };
320 Ok(ContextCheckpointMergeResultV1 {
321 checkpoint,
322 receipt,
323 })
324}
325
326#[allow(clippy::too_many_arguments)]
328pub fn merge_verified_checkpoints_v2(
329 ancestor: &VerifiedContextCheckpointV2,
330 left_chain: &[VerifiedContextCheckpointV2],
331 left: &VerifiedContextCheckpointV2,
332 right_chain: &[VerifiedContextCheckpointV2],
333 right: &VerifiedContextCheckpointV2,
334 spec: &ContextCheckpointChildSpecV1,
335 policy: ContextCheckpointConflictPolicyV1,
336 task: &TaskEnvelopeV1,
337 plan: Option<&ExecutionPlanV1>,
338 receipts: &[VerifiedReceiptDocumentV1],
339 outcomes: &[AcceptedOutcomeV1],
340) -> Result<VerifiedContextCheckpointMergeResultV2, ContextCheckpointMergeErrorV1> {
341 for checkpoint in [ancestor, left, right] {
342 validate_checkpoint_lineage(checkpoint, task, plan, receipts, outcomes).map_err(invalid)?;
343 if !same_scope_v2(ancestor, checkpoint) {
344 return Err(ContextCheckpointMergeErrorV1::ScopeMismatch);
345 }
346 }
347 validate_chain_v2(ancestor, left_chain, left)?;
348 validate_chain_v2(ancestor, right_chain, right)?;
349 if spec.created_at < left.updated_at || spec.created_at < right.updated_at {
350 return Err(ContextCheckpointMergeErrorV1::NonMonotonicTimestamp);
351 }
352
353 let ancestor_value = semantic_value_v2(ancestor)?;
354 let left_value = semantic_value_v2(left)?;
355 let right_value = semantic_value_v2(right)?;
356 let mut conflicts = Vec::new();
357 let mut output_value = merge_node(
358 "",
359 Some(&ancestor_value),
360 Some(&left_value),
361 Some(&right_value),
362 policy,
363 &mut conflicts,
364 )
365 .expect("three present root objects always produce a value");
366 if conflicts.len() > MAX_MERGE_CONFLICTS {
367 return Err(ContextCheckpointMergeErrorV1::TooManyConflicts);
368 }
369 if policy == ContextCheckpointConflictPolicyV1::Fail && !conflicts.is_empty() {
370 return Err(ContextCheckpointMergeErrorV1::Conflicts(conflicts));
371 }
372
373 let object = output_value.as_object_mut().ok_or_else(|| {
374 ContextCheckpointMergeErrorV1::InvalidCheckpoint("checkpoint root is not object".into())
375 })?;
376 object.insert(
377 "identity".into(),
378 serde_json::to_value(child_identity_from(&left.identity, spec)?).map_err(json_invalid)?,
379 );
380 object.insert(
381 "created_at".into(),
382 serde_json::to_value(&spec.created_at).map_err(json_invalid)?,
383 );
384 object.insert(
385 "updated_at".into(),
386 serde_json::to_value(&spec.created_at).map_err(json_invalid)?,
387 );
388 let checkpoint: ContextCheckpointV2 =
389 serde_json::from_value(output_value).map_err(json_invalid)?;
390 let checkpoint =
391 verify_checkpoint_v2(checkpoint, task, plan, receipts, outcomes).map_err(invalid)?;
392
393 conflicts.sort_by(|left, right| left.field_path.cmp(&right.field_path));
394 if conflicts
395 .windows(2)
396 .any(|pair| pair[0].field_path == pair[1].field_path)
397 {
398 return Err(ContextCheckpointMergeErrorV1::InvalidCheckpoint(
399 "duplicate merge conflict path".into(),
400 ));
401 }
402 let receipt = ContextCheckpointMergeReceiptV2 {
403 schema_version: ContextCheckpointMergeReceiptV2::SCHEMA_VERSION,
404 ancestor_digest: ancestor.digest().map_err(invalid)?,
405 left_digest: left.digest().map_err(invalid)?,
406 right_digest: right.digest().map_err(invalid)?,
407 output_digest: checkpoint.digest().map_err(invalid)?,
408 policy,
409 conflicts,
410 };
411 Ok(VerifiedContextCheckpointMergeResultV2 {
412 checkpoint,
413 receipt,
414 })
415}
416
417#[derive(Clone, Debug)]
419pub struct DeterministicContextCheckpointMergePolicyV1 {
420 pub output: ContextCheckpointChildSpecV1,
421 pub conflicts: ContextCheckpointConflictPolicyV1,
422}
423
424impl ContextCheckpointMergePolicyV1 for DeterministicContextCheckpointMergePolicyV1 {
425 type Error = ContextCheckpointMergeErrorV1;
426
427 fn merge(
428 &self,
429 ancestor: &ContextCheckpointV1,
430 left: &ContextCheckpointV1,
431 right: &ContextCheckpointV1,
432 ) -> Result<ContextCheckpointV1, Self::Error> {
433 merge_checkpoints_v1(
434 ancestor,
435 &[],
436 left,
437 &[],
438 right,
439 &self.output,
440 self.conflicts,
441 )
442 .map(|result| result.checkpoint)
443 }
444}
445
446fn child_identity_from(
447 parent: &ContextCheckpointIdentityV1,
448 spec: &ContextCheckpointChildSpecV1,
449) -> Result<ContextCheckpointIdentityV1, ContextCheckpointMergeErrorV1> {
450 ContextCheckpointIdentityV1::try_new(
451 spec.checkpoint_id.clone(),
452 Some(parent.checkpoint_id.clone()),
453 Some(parent.device_id.clone()),
454 Some(parent.branch_id.clone()),
455 Some(parent.device_sequence),
456 spec.branch_id.clone(),
457 spec.device_id.clone(),
458 spec.device_sequence,
459 )
460 .map_err(invalid)
461}
462
463fn same_scope(left: &ContextCheckpointV1, right: &ContextCheckpointV1) -> bool {
464 left.lineage.tenant_id == right.lineage.tenant_id
465 && left.lineage.project_id == right.lineage.project_id
466 && left.lineage.workspace_id == right.lineage.workspace_id
467 && left.lineage.task_id == right.lineage.task_id
468 && left.lineage.plan_id == right.lineage.plan_id
469}
470
471fn same_scope_v2(left: &ContextCheckpointV2, right: &ContextCheckpointV2) -> bool {
472 left.lineage.tenant_id == right.lineage.tenant_id
473 && left.lineage.project_id == right.lineage.project_id
474 && left.lineage.workspace_id == right.lineage.workspace_id
475 && left.lineage.task_id == right.lineage.task_id
476 && left.lineage.plan_id == right.lineage.plan_id
477}
478
479fn validate_chain(
480 ancestor: &ContextCheckpointV1,
481 intermediates: &[ContextCheckpointV1],
482 tip: &ContextCheckpointV1,
483) -> Result<(), ContextCheckpointMergeErrorV1> {
484 if tip.identity.checkpoint_id == ancestor.identity.checkpoint_id {
485 return intermediates
486 .is_empty()
487 .then_some(())
488 .ok_or(ContextCheckpointMergeErrorV1::InvalidAncestry);
489 }
490 let mut previous = ancestor;
491 let mut seen = BTreeSet::from([ancestor.identity.checkpoint_id.as_str().to_owned()]);
492 for current in intermediates.iter().chain(std::iter::once(tip)) {
493 current.validate().map_err(invalid)?;
494 if !same_scope(ancestor, current)
495 || !seen.insert(current.identity.checkpoint_id.as_str().to_owned())
496 || current.identity.parent_checkpoint_id.as_ref()
497 != Some(&previous.identity.checkpoint_id)
498 || current.identity.parent_device_id.as_ref() != Some(&previous.identity.device_id)
499 || current.identity.parent_branch_id.as_ref() != Some(&previous.identity.branch_id)
500 || current.identity.parent_device_sequence != Some(previous.identity.device_sequence)
501 || current.updated_at < previous.updated_at
502 {
503 return Err(ContextCheckpointMergeErrorV1::InvalidAncestry);
504 }
505 previous = current;
506 }
507 Ok(())
508}
509
510fn validate_chain_v2(
511 ancestor: &VerifiedContextCheckpointV2,
512 intermediates: &[VerifiedContextCheckpointV2],
513 tip: &VerifiedContextCheckpointV2,
514) -> Result<(), ContextCheckpointMergeErrorV1> {
515 if tip.identity.checkpoint_id == ancestor.identity.checkpoint_id {
516 return intermediates
517 .is_empty()
518 .then_some(())
519 .ok_or(ContextCheckpointMergeErrorV1::InvalidAncestry);
520 }
521 let mut previous: &ContextCheckpointV2 = ancestor;
522 let mut seen = BTreeSet::from([ancestor.identity.checkpoint_id.as_str().to_owned()]);
523 for current in intermediates.iter().chain(std::iter::once(tip)) {
524 current.validate().map_err(invalid)?;
525 if !same_scope_v2(ancestor, current)
526 || !seen.insert(current.identity.checkpoint_id.as_str().to_owned())
527 || current.identity.parent_checkpoint_id.as_ref()
528 != Some(&previous.identity.checkpoint_id)
529 || current.identity.parent_device_id.as_ref() != Some(&previous.identity.device_id)
530 || current.identity.parent_branch_id.as_ref() != Some(&previous.identity.branch_id)
531 || current.identity.parent_device_sequence != Some(previous.identity.device_sequence)
532 || current.updated_at < previous.updated_at
533 {
534 return Err(ContextCheckpointMergeErrorV1::InvalidAncestry);
535 }
536 previous = current;
537 }
538 Ok(())
539}
540
541fn semantic_value(
542 checkpoint: &ContextCheckpointV1,
543) -> Result<Value, ContextCheckpointMergeErrorV1> {
544 let mut value = serde_json::to_value(checkpoint).map_err(json_invalid)?;
545 let object = value.as_object_mut().ok_or_else(|| {
546 ContextCheckpointMergeErrorV1::InvalidCheckpoint("checkpoint root is not object".into())
547 })?;
548 for field in ["identity", "created_at", "updated_at"] {
549 object.remove(field);
550 }
551 Ok(value)
552}
553
554fn semantic_value_v2(
555 checkpoint: &ContextCheckpointV2,
556) -> Result<Value, ContextCheckpointMergeErrorV1> {
557 let mut value = serde_json::to_value(checkpoint).map_err(json_invalid)?;
558 let object = value.as_object_mut().ok_or_else(|| {
559 ContextCheckpointMergeErrorV1::InvalidCheckpoint("checkpoint root is not object".into())
560 })?;
561 for field in ["identity", "created_at", "updated_at"] {
562 object.remove(field);
563 }
564 Ok(value)
565}
566
567fn merge_node(
568 path: &str,
569 ancestor: Option<&Value>,
570 left: Option<&Value>,
571 right: Option<&Value>,
572 policy: ContextCheckpointConflictPolicyV1,
573 conflicts: &mut Vec<ContextCheckpointMergeConflictV1>,
574) -> Option<Value> {
575 if left == right {
576 return left.cloned();
577 }
578 if left == ancestor {
579 return right.cloned();
580 }
581 if right == ancestor {
582 return left.cloned();
583 }
584 if let (Some(Value::Object(a)), Some(Value::Object(l)), Some(Value::Object(r))) =
585 (ancestor, left, right)
586 {
587 let keys: BTreeSet<&String> = a.keys().chain(l.keys()).chain(r.keys()).collect();
588 let mut output = Map::new();
589 for key in keys {
590 let child_path = if path.is_empty() {
591 format!("/{key}")
592 } else {
593 format!("{path}/{key}")
594 };
595 if let Some(value) = merge_node(
596 &child_path,
597 a.get(key),
598 l.get(key),
599 r.get(key),
600 policy,
601 conflicts,
602 ) {
603 output.insert(key.clone(), value);
604 }
605 }
606 return Some(Value::Object(output));
607 }
608 let resolution = match policy {
609 ContextCheckpointConflictPolicyV1::Fail => {
610 ContextCheckpointConflictResolutionV1::Unresolved
611 }
612 ContextCheckpointConflictPolicyV1::PreferLeft => {
613 ContextCheckpointConflictResolutionV1::Left
614 }
615 ContextCheckpointConflictPolicyV1::PreferRight => {
616 ContextCheckpointConflictResolutionV1::Right
617 }
618 };
619 conflicts.push(ContextCheckpointMergeConflictV1 {
620 field_path: path.to_owned(),
621 resolution,
622 });
623 match policy {
624 ContextCheckpointConflictPolicyV1::PreferRight => right.cloned(),
625 ContextCheckpointConflictPolicyV1::Fail | ContextCheckpointConflictPolicyV1::PreferLeft => {
626 left.cloned()
627 }
628 }
629}
630
631fn invalid(error: impl fmt::Display) -> ContextCheckpointMergeErrorV1 {
632 ContextCheckpointMergeErrorV1::InvalidCheckpoint(error.to_string())
633}
634
635fn json_invalid(error: impl fmt::Display) -> ContextCheckpointMergeErrorV1 {
636 invalid(error)
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642 use crate::core::context_checkpoint::{
643 ContextCheckpointMigrationErrorV1, ContextCheckpointMigrationKindV1,
644 StrictContextCheckpointMigratorV1,
645 };
646 use lean_ctx_protocol::{
647 ContextCheckpointLineageV1, ContextCheckpointLiveStateV1, ContextCheckpointProgressV1,
648 ContextCheckpointTaskStatusV1, ContextCheckpointTaskV1, ContextCheckpointTextV1, PlanId,
649 ProjectId, SemanticVersion, TaskId, TenantId, WorkspaceId,
650 };
651
652 fn id<T>(value: &str) -> T
653 where
654 T: TryFrom<String>,
655 <T as TryFrom<String>>::Error: fmt::Debug,
656 {
657 T::try_from(value.to_owned()).expect("fixture id")
658 }
659
660 fn checkpoint() -> ContextCheckpointV1 {
661 let task_id: TaskId = id("task-merge");
662 let plan_id: PlanId = id("plan-merge");
663 ContextCheckpointV1::try_new(
664 ContextCheckpointIdentityV1::try_new(
665 id("11111111-2222-4333-8444-555555555555"),
666 None,
667 None,
668 None,
669 None,
670 id("main"),
671 id("device-a"),
672 1,
673 )
674 .unwrap(),
675 ContextCheckpointLineageV1 {
676 project_id: id::<ProjectId>("project-merge"),
677 workspace_id: id::<WorkspaceId>("aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"),
678 tenant_id: id::<TenantId>("tenant-merge"),
679 task_id: task_id.clone(),
680 plan_id: Some(plan_id.clone()),
681 receipt_ids: Vec::new(),
682 context_ir_digest: None,
683 hosted_index_digest: None,
684 evidence_refs: Vec::new(),
685 knowledge_refs: Vec::new(),
686 gotcha_refs: Vec::new(),
687 snapshot_refs: Vec::new(),
688 },
689 ContextCheckpointLiveStateV1 {
690 schema_version: 1,
691 task: ContextCheckpointTaskV1 {
692 task_id,
693 title: ContextCheckpointTextV1::new("merge task").unwrap(),
694 status: ContextCheckpointTaskStatusV1::InProgress,
695 plan_id: Some(plan_id),
696 },
697 progress: ContextCheckpointProgressV1 {
698 completed_steps: 0,
699 total_steps: 2,
700 confidence_milliunits: 500,
701 summary: ContextCheckpointTextV1::new("start").unwrap(),
702 },
703 decisions: Vec::new(),
704 findings: Vec::new(),
705 next_steps: vec![ContextCheckpointTextV1::new("continue").unwrap()],
706 handoff_summary: ContextCheckpointTextV1::new("start").unwrap(),
707 files: Vec::new(),
708 profile_id: None,
709 policy_pins: Vec::new(),
710 package_pins: Vec::new(),
711 session_state: None,
712 learning_state: None,
713 },
714 None,
715 SemanticVersion::new("4.0.0").unwrap(),
716 UtcTimestamp::new("2026-09-07T12:00:00Z").unwrap(),
717 )
718 .unwrap()
719 }
720
721 fn spec(
722 uuid: &str,
723 branch: &str,
724 device: &str,
725 sequence: u64,
726 time: &str,
727 ) -> ContextCheckpointChildSpecV1 {
728 ContextCheckpointChildSpecV1 {
729 checkpoint_id: id(uuid),
730 branch_id: id(branch),
731 device_id: id(device),
732 device_sequence: sequence,
733 created_at: UtcTimestamp::new(time).unwrap(),
734 }
735 }
736
737 #[test]
738 fn branching_binds_complete_parent_identity_and_sequence() {
739 let parent = checkpoint();
740 let child = branch_checkpoint_v1(
741 &parent,
742 &spec(
743 "22222222-2222-4333-8444-555555555555",
744 "feature",
745 "device-a",
746 2,
747 "2026-09-07T12:01:00Z",
748 ),
749 )
750 .unwrap();
751 assert_eq!(
752 child.identity.parent_checkpoint_id,
753 Some(parent.identity.checkpoint_id.clone())
754 );
755 assert_eq!(
756 child.identity.parent_device_id,
757 Some(parent.identity.device_id.clone())
758 );
759 assert_eq!(
760 child.identity.parent_branch_id,
761 Some(parent.identity.branch_id.clone())
762 );
763 assert_eq!(child.identity.parent_device_sequence, Some(1));
764 assert!(
765 branch_checkpoint_v1(
766 &parent,
767 &spec(
768 "33333333-2222-4333-8444-555555555555",
769 "main",
770 "device-a",
771 3,
772 "2026-09-07T12:01:00Z",
773 )
774 )
775 .is_err()
776 );
777 }
778
779 #[test]
780 fn merge_combines_independent_changes_and_binds_both_tips() {
781 let base = checkpoint();
782 let mut left = branch_checkpoint_v1(
783 &base,
784 &spec(
785 "22222222-2222-4333-8444-555555555555",
786 "left",
787 "device-b",
788 1,
789 "2026-09-07T12:01:00Z",
790 ),
791 )
792 .unwrap();
793 left.live_state.progress.summary = ContextCheckpointTextV1::new("left progress").unwrap();
794 let mut right = branch_checkpoint_v1(
795 &base,
796 &spec(
797 "33333333-2222-4333-8444-555555555555",
798 "right",
799 "device-c",
800 1,
801 "2026-09-07T12:02:00Z",
802 ),
803 )
804 .unwrap();
805 right.live_state.handoff_summary = ContextCheckpointTextV1::new("right handoff").unwrap();
806 let result = merge_checkpoints_v1(
807 &base,
808 &[],
809 &left,
810 &[],
811 &right,
812 &spec(
813 "44444444-2222-4333-8444-555555555555",
814 "merged",
815 "device-b",
816 2,
817 "2026-09-07T12:03:00Z",
818 ),
819 ContextCheckpointConflictPolicyV1::Fail,
820 )
821 .unwrap();
822 assert_eq!(
823 result.checkpoint().live_state.progress.summary.as_str(),
824 "left progress"
825 );
826 assert_eq!(
827 result.checkpoint().live_state.handoff_summary.as_str(),
828 "right handoff"
829 );
830 {
831 let found = &result.receipt().conflicts();
832 assert!(found.is_empty(), "{found:?}");
833 }
834 assert_eq!(result.receipt().left_digest(), &left.digest().unwrap());
835 assert_eq!(result.receipt().right_digest(), &right.digest().unwrap());
836 assert!(
837 result
838 .receipt()
839 .signing_payload()
840 .starts_with(MERGE_SIGNATURE_DOMAIN_V1)
841 );
842 }
843
844 #[test]
845 fn merge_conflicts_fail_or_are_explicitly_resolved() {
846 let base = checkpoint();
847 let mut left = branch_checkpoint_v1(
848 &base,
849 &spec(
850 "22222222-2222-4333-8444-555555555555",
851 "left",
852 "device-b",
853 1,
854 "2026-09-07T12:01:00Z",
855 ),
856 )
857 .unwrap();
858 left.live_state.handoff_summary = ContextCheckpointTextV1::new("left").unwrap();
859 let mut right = branch_checkpoint_v1(
860 &base,
861 &spec(
862 "33333333-2222-4333-8444-555555555555",
863 "right",
864 "device-c",
865 1,
866 "2026-09-07T12:02:00Z",
867 ),
868 )
869 .unwrap();
870 right.live_state.handoff_summary = ContextCheckpointTextV1::new("right").unwrap();
871 let output = spec(
872 "44444444-2222-4333-8444-555555555555",
873 "merged",
874 "device-b",
875 2,
876 "2026-09-07T12:03:00Z",
877 );
878 let error = merge_checkpoints_v1(
879 &base,
880 &[],
881 &left,
882 &[],
883 &right,
884 &output,
885 ContextCheckpointConflictPolicyV1::Fail,
886 )
887 .unwrap_err();
888 assert!(matches!(error, ContextCheckpointMergeErrorV1::Conflicts(_)));
889 let resolved = merge_checkpoints_v1(
890 &base,
891 &[],
892 &left,
893 &[],
894 &right,
895 &output,
896 ContextCheckpointConflictPolicyV1::PreferRight,
897 )
898 .unwrap();
899 assert_eq!(
900 resolved.checkpoint().live_state.handoff_summary.as_str(),
901 "right"
902 );
903 assert_eq!(
904 resolved.receipt().conflicts()[0].field_path,
905 "/live_state/handoff_summary"
906 );
907 assert_eq!(
908 resolved.receipt().conflicts()[0].resolution,
909 ContextCheckpointConflictResolutionV1::Right
910 );
911 }
912
913 #[test]
914 fn v2_merge_receipt_round_trips_and_rejects_unknown_fields() {
915 let digest = || Sha256Digest::new(format!("sha256:{}", "a".repeat(64))).unwrap();
916 let receipt = ContextCheckpointMergeReceiptV2 {
917 schema_version: ContextCheckpointMergeReceiptV2::SCHEMA_VERSION,
918 ancestor_digest: digest(),
919 left_digest: digest(),
920 right_digest: digest(),
921 output_digest: digest(),
922 policy: ContextCheckpointConflictPolicyV1::Fail,
923 conflicts: Vec::new(),
924 };
925 let value = serde_json::to_value(&receipt).unwrap();
926 assert_eq!(
927 serde_json::from_value::<ContextCheckpointMergeReceiptV2>(value.clone()).unwrap(),
928 receipt
929 );
930 let mut unknown = value;
931 unknown["unexpected"] = Value::Bool(true);
932 assert!(serde_json::from_value::<ContextCheckpointMergeReceiptV2>(unknown).is_err());
933 }
934
935 #[test]
936 fn ancestry_and_scope_fail_closed() {
937 let base = checkpoint();
938 let left = branch_checkpoint_v1(
939 &base,
940 &spec(
941 "22222222-2222-4333-8444-555555555555",
942 "left",
943 "device-b",
944 1,
945 "2026-09-07T12:01:00Z",
946 ),
947 )
948 .unwrap();
949 let mut foreign = left.clone();
950 foreign.lineage.tenant_id = id("other-tenant");
951 let output = spec(
952 "44444444-2222-4333-8444-555555555555",
953 "merged",
954 "device-b",
955 2,
956 "2026-09-07T12:03:00Z",
957 );
958 assert_eq!(
959 merge_checkpoints_v1(
960 &base,
961 &[],
962 &left,
963 &[],
964 &foreign,
965 &output,
966 ContextCheckpointConflictPolicyV1::Fail
967 ),
968 Err(ContextCheckpointMergeErrorV1::ScopeMismatch)
969 );
970 assert_eq!(
971 merge_checkpoints_v1(
972 &base,
973 std::slice::from_ref(&left),
974 &left,
975 &[],
976 &left,
977 &output,
978 ContextCheckpointConflictPolicyV1::Fail
979 ),
980 Err(ContextCheckpointMergeErrorV1::InvalidAncestry)
981 );
982 }
983
984 #[test]
985 fn migration_accepts_only_canonical_current_or_exact_legacy_shape() {
986 let checkpoint = checkpoint();
987 let migrator = StrictContextCheckpointMigratorV1;
988 let canonical = checkpoint.canonical_bytes().unwrap();
989 let current = migrator.migrate_with_receipt(&canonical).unwrap();
990 assert_eq!(
991 current.receipt().kind(),
992 ContextCheckpointMigrationKindV1::CanonicalV1
993 );
994 assert_eq!(
995 current.receipt().output_digest(),
996 &checkpoint.digest().unwrap()
997 );
998 assert!(
999 current
1000 .receipt()
1001 .signing_payload()
1002 .starts_with(super::super::migration::MIGRATION_SIGNATURE_DOMAIN)
1003 );
1004
1005 let mut legacy: Value = serde_json::from_slice(&canonical).unwrap();
1006 legacy.as_object_mut().unwrap().remove("updated_at");
1007 let legacy_bytes = serde_json::to_vec(&legacy).unwrap();
1008 let migrated = migrator.migrate_with_receipt(&legacy_bytes).unwrap();
1009 assert_eq!(
1010 migrated.receipt().kind(),
1011 ContextCheckpointMigrationKindV1::LegacyV1MissingUpdatedAt
1012 );
1013 assert_eq!(
1014 migrated.checkpoint().updated_at,
1015 migrated.checkpoint().created_at
1016 );
1017
1018 let pretty = serde_json::to_vec_pretty(&legacy).unwrap();
1019 assert_eq!(
1020 migrator.migrate_with_receipt(&pretty).unwrap_err(),
1021 ContextCheckpointMigrationErrorV1::NonCanonicalSource
1022 );
1023 legacy["schema_version"] = Value::from(2);
1024 assert_eq!(
1025 migrator
1026 .migrate_with_receipt(&serde_json::to_vec(&legacy).unwrap())
1027 .unwrap_err(),
1028 ContextCheckpointMigrationErrorV1::UnsupportedSchema
1029 );
1030 }
1031}