Skip to main content

khive_changeset/
op.rs

1//! The six typed change-set operations and their stage-time payloads.
2
3use std::collections::BTreeMap;
4
5use khive_types::{
6    EdgeRelation, EntityAlias, EntityKind, Id128, Link, Namespace, Note, NoteStatus, PropertyValue,
7};
8use serde::{Deserialize, Deserializer, Serialize};
9
10use crate::strict::{StrictEntity, StrictLink, StrictNote};
11use crate::EntityRecord;
12
13/// One staged mutation, internally tagged by the snake-case `op` field.
14///
15/// See `crates/khive-changeset/docs/api/create-and-link.md` for wire examples.
16#[derive(Clone, Debug, Serialize, Deserialize)]
17#[serde(tag = "op", rename_all = "snake_case")]
18pub enum Op {
19    Create(CreateOp),
20    Link(LinkOp),
21    Update(UpdateOp),
22    Delete(DeleteOp),
23    Restore(RestoreOp),
24    Merge(MergeOp),
25}
26
27/// Creates an entity or note with an ID minted and stabilized at stage time.
28///
29/// See `crates/khive-changeset/docs/api/create-and-link.md` for field semantics.
30#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct CreateOp {
33    pub id: Id128,
34    pub namespace: Namespace,
35    pub target: CreateTarget,
36}
37
38/// Substrate-specific create fields, tagged by `kind`.
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40#[serde(tag = "kind", rename_all = "snake_case")]
41pub enum CreateTarget {
42    Entity(EntityCreateFields),
43    Note(NoteCreateFields),
44}
45
46/// Fields staged for a new entity.
47#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct EntityCreateFields {
50    pub entity_kind: EntityKind,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub entity_type: Option<String>,
53    pub name: String,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub description: Option<String>,
56    #[serde(default)]
57    pub properties: BTreeMap<String, PropertyValue>,
58    #[serde(default)]
59    pub tags: Vec<String>,
60    /// Caller key under `entity_kind`, claimed when the create lands
61    /// (ADR-221 section 1). Omitted from the wire when absent.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub key: Option<String>,
64    /// Caller aliases, stored with the `caller` origin; one equal to `name`
65    /// is not stored (ADR-221 section 2). Omitted from the wire when empty.
66    #[serde(default, skip_serializing_if = "Vec::is_empty")]
67    pub aliases: Vec<String>,
68}
69
70/// Fields staged for a new note.
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
72#[serde(deny_unknown_fields)]
73pub struct NoteCreateFields {
74    /// Pack-declared note kind string (e.g. `"observation"`); not a closed enum.
75    pub note_kind: String,
76    pub content: String,
77    #[serde(default)]
78    pub properties: BTreeMap<String, PropertyValue>,
79    #[serde(default)]
80    pub tags: Vec<String>,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub salience: Option<f64>,
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub decay_factor: Option<f64>,
85}
86
87/// Creates a directed edge whose ID is minted at stage time.
88///
89/// Endpoints may reference stage-time IDs from this or another change-set.
90/// `weight` must be finite and in `[0.0, 1.0]` when deserialized.
91/// See `crates/khive-changeset/docs/api/create-and-link.md` for field semantics.
92#[derive(Clone, Debug, PartialEq, Serialize)]
93#[serde(into = "LinkOpRaw")]
94pub struct LinkOp {
95    pub id: Id128,
96    pub namespace: Namespace,
97    pub source: Id128,
98    pub target: Id128,
99    pub relation: EdgeRelation,
100    pub weight: f64,
101    pub properties: BTreeMap<String, PropertyValue>,
102}
103
104#[derive(Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106struct LinkOpRaw {
107    id: Id128,
108    namespace: Namespace,
109    source: Id128,
110    target: Id128,
111    relation: EdgeRelation,
112    weight: f64,
113    #[serde(default)]
114    properties: BTreeMap<String, PropertyValue>,
115}
116
117impl From<LinkOp> for LinkOpRaw {
118    fn from(l: LinkOp) -> Self {
119        Self {
120            id: l.id,
121            namespace: l.namespace,
122            source: l.source,
123            target: l.target,
124            relation: l.relation,
125            weight: l.weight,
126            properties: l.properties,
127        }
128    }
129}
130
131impl TryFrom<LinkOpRaw> for LinkOp {
132    type Error = String;
133
134    fn try_from(raw: LinkOpRaw) -> Result<Self, Self::Error> {
135        if !raw.weight.is_finite() {
136            return Err(format!("LinkOp weight must be finite, got {}", raw.weight));
137        }
138        if !khive_types::validate_edge_weight(raw.weight) {
139            return Err(format!(
140                "LinkOp weight must be in [0.0, 1.0], got {}",
141                raw.weight
142            ));
143        }
144        Ok(LinkOp {
145            id: raw.id,
146            namespace: raw.namespace,
147            source: raw.source,
148            target: raw.target,
149            relation: raw.relation,
150            weight: raw.weight,
151            properties: raw.properties,
152        })
153    }
154}
155
156impl<'de> Deserialize<'de> for LinkOp {
157    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
158    where
159        D: serde::Deserializer<'de>,
160    {
161        let raw = LinkOpRaw::deserialize(deserializer)?;
162        LinkOp::try_from(raw).map_err(serde::de::Error::custom)
163    }
164}
165
166/// Patches one record with a stage-time preimage of exactly the touched fields.
167///
168/// Patch and preimage must target the same substrate and have identical field
169/// presence; both construction and deserialization enforce this invariant.
170/// See `crates/khive-changeset/docs/api/update.md` for nullable-field semantics.
171#[derive(Clone, Debug, PartialEq, Serialize)]
172pub struct UpdateOp {
173    target_id: Id128,
174    patch: UpdatePatch,
175    preimage: UpdatePreimage,
176}
177
178impl UpdateOp {
179    /// Constructs an update after validating patch/preimage congruence.
180    ///
181    /// # Errors
182    ///
183    /// Returns an error for differing substrates or field sets, or for an
184    /// invalid captured salience, decay factor, or edge weight, or an invalid
185    /// new edge weight.
186    pub fn new(
187        target_id: Id128,
188        patch: UpdatePatch,
189        preimage: UpdatePreimage,
190    ) -> Result<Self, String> {
191        validate_update_congruence(&patch, &preimage)?;
192        Ok(UpdateOp {
193            target_id,
194            patch,
195            preimage,
196        })
197    }
198
199    /// The identifier of the record this update targets.
200    pub fn target_id(&self) -> Id128 {
201        self.target_id
202    }
203
204    /// The staged patch.
205    pub fn patch(&self) -> &UpdatePatch {
206        &self.patch
207    }
208
209    /// The field-scoped prior value the patch touches.
210    pub fn preimage(&self) -> &UpdatePreimage {
211        &self.preimage
212    }
213}
214
215#[derive(Deserialize)]
216#[serde(deny_unknown_fields)]
217struct UpdateOpRaw {
218    target_id: Id128,
219    patch: UpdatePatch,
220    preimage: UpdatePreimage,
221}
222
223impl<'de> Deserialize<'de> for UpdateOp {
224    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225    where
226        D: Deserializer<'de>,
227    {
228        let raw = UpdateOpRaw::deserialize(deserializer)?;
229        UpdateOp::new(raw.target_id, raw.patch, raw.preimage).map_err(serde::de::Error::custom)
230    }
231}
232
233/// Substrate-specific patch tagged by `target`.
234///
235/// See `crates/khive-changeset/docs/api/update.md` for field-presence semantics.
236#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
237#[serde(tag = "target", rename_all = "snake_case")]
238pub enum UpdatePatch {
239    Entity(EntityPatch),
240    Note(NotePatch),
241    Edge(EdgePatch),
242}
243
244/// Entity fields to mutate; absent means unchanged and `Some(None)` clears
245/// a nullable field (ADR-014 tri-state, applied to `description` and
246/// `entity_type`).
247///
248/// `aliases` is the entity's whole alias set after the update, every origin
249/// included, as tags are the whole tag list: the apply writes exactly that set
250/// with the origins given. Without it the apply leaves the aliases as they are,
251/// and refuses a rename onto a name the entity holds as an alias, since
252/// dropping that alias would be a change no preimage records.
253#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
254#[serde(deny_unknown_fields)]
255pub struct EntityPatch {
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub name: Option<String>,
258    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
259    pub description: Option<Option<String>>,
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub properties: Option<BTreeMap<String, PropertyValue>>,
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub tags: Option<Vec<String>>,
264    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
265    pub entity_type: Option<Option<String>>,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub aliases: Option<Vec<EntityAlias>>,
268}
269
270/// Note fields to mutate; nested options distinguish unchanged, clear, and set.
271#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
272#[serde(deny_unknown_fields)]
273pub struct NotePatch {
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub content: Option<String>,
276    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
277    pub salience: Option<Option<f64>>,
278    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
279    pub decay_factor: Option<Option<f64>>,
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub properties: Option<BTreeMap<String, PropertyValue>>,
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub tags: Option<Vec<String>>,
284}
285
286/// Edge fields to mutate; weight must be finite and in `[0.0, 1.0]`.
287#[derive(Clone, Debug, PartialEq, Serialize)]
288#[serde(into = "EdgePatchRaw")]
289pub struct EdgePatch {
290    pub relation: Option<EdgeRelation>,
291    pub weight: Option<f64>,
292}
293
294#[derive(Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296struct EdgePatchRaw {
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    relation: Option<EdgeRelation>,
299    #[serde(default, skip_serializing_if = "Option::is_none")]
300    weight: Option<f64>,
301}
302
303impl From<EdgePatch> for EdgePatchRaw {
304    fn from(p: EdgePatch) -> Self {
305        Self {
306            relation: p.relation,
307            weight: p.weight,
308        }
309    }
310}
311
312impl TryFrom<EdgePatchRaw> for EdgePatch {
313    type Error = String;
314
315    fn try_from(raw: EdgePatchRaw) -> Result<Self, Self::Error> {
316        let patch = EdgePatch {
317            relation: raw.relation,
318            weight: raw.weight,
319        };
320        patch.validate_weight()?;
321        Ok(patch)
322    }
323}
324
325impl EdgePatch {
326    fn validate_weight(&self) -> Result<(), String> {
327        if let Some(w) = self.weight {
328            if !w.is_finite() {
329                return Err(format!("EdgePatch weight must be finite, got {w}"));
330            }
331            if !khive_types::validate_edge_weight(w) {
332                return Err(format!("EdgePatch weight must be in [0.0, 1.0], got {w}"));
333            }
334        }
335        Ok(())
336    }
337}
338
339impl<'de> Deserialize<'de> for EdgePatch {
340    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
341    where
342        D: Deserializer<'de>,
343    {
344        let raw = EdgePatchRaw::deserialize(deserializer)?;
345        EdgePatch::try_from(raw).map_err(serde::de::Error::custom)
346    }
347}
348
349/// Distinguishes an absent patch field from an explicit `null` clear.
350mod opt_opt {
351    use serde::{Deserialize, Deserializer, Serialize, Serializer};
352
353    pub fn serialize<T, S>(val: &Option<Option<T>>, s: S) -> Result<S::Ok, S::Error>
354    where
355        T: Serialize,
356        S: Serializer,
357    {
358        match val {
359            None => unreachable!("skip_serializing_if guards the None case"),
360            Some(inner) => inner.serialize(s),
361        }
362    }
363
364    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<Option<T>>, D::Error>
365    where
366        T: Deserialize<'de>,
367        D: Deserializer<'de>,
368    {
369        let opt: Option<T> = Option::deserialize(d)?;
370        Ok(Some(opt))
371    }
372}
373
374/// Prior entity values for exactly the fields touched by [`EntityPatch`].
375#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
376#[serde(deny_unknown_fields)]
377pub struct EntityPreimage {
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub name: Option<String>,
380    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
381    pub description: Option<Option<String>>,
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub properties: Option<BTreeMap<String, PropertyValue>>,
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub tags: Option<Vec<String>>,
386    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
387    pub entity_type: Option<Option<String>>,
388    /// The entity's whole alias set before the update, every origin included.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub aliases: Option<Vec<EntityAlias>>,
391}
392
393/// Prior note values for exactly the fields touched by [`NotePatch`].
394///
395/// Captured salience is finite in `[0.0, 1.0]`; decay factor is finite and non-negative.
396#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
397#[serde(deny_unknown_fields)]
398pub struct NotePreimage {
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub content: Option<String>,
401    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
402    pub salience: Option<Option<f64>>,
403    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_opt")]
404    pub decay_factor: Option<Option<f64>>,
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub properties: Option<BTreeMap<String, PropertyValue>>,
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub tags: Option<Vec<String>>,
409}
410
411/// Prior edge values for exactly the fields touched by [`EdgePatch`].
412///
413/// Captured weight must be finite and in `[0.0, 1.0]`.
414#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
415#[serde(deny_unknown_fields)]
416pub struct EdgePreimage {
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub relation: Option<EdgeRelation>,
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub weight: Option<f64>,
421}
422
423/// Field-scoped preimage tagged with the same `target` as [`UpdatePatch`].
424#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
425#[serde(tag = "target", rename_all = "snake_case")]
426pub enum UpdatePreimage {
427    Entity(EntityPreimage),
428    Note(NotePreimage),
429    Edge(EdgePreimage),
430}
431
432/// Enforces substrate, exact field-set, and captured numeric-value invariants.
433fn validate_update_congruence(
434    patch: &UpdatePatch,
435    preimage: &UpdatePreimage,
436) -> Result<(), String> {
437    match (patch, preimage) {
438        (UpdatePatch::Entity(p), UpdatePreimage::Entity(pre)) => {
439            check_touched("name", p.name.is_some(), pre.name.is_some())?;
440            check_touched(
441                "description",
442                p.description.is_some(),
443                pre.description.is_some(),
444            )?;
445            check_touched(
446                "properties",
447                p.properties.is_some(),
448                pre.properties.is_some(),
449            )?;
450            check_touched("tags", p.tags.is_some(), pre.tags.is_some())?;
451            check_touched(
452                "entity_type",
453                p.entity_type.is_some(),
454                pre.entity_type.is_some(),
455            )?;
456            check_touched("aliases", p.aliases.is_some(), pre.aliases.is_some())?;
457            for (side, set) in [("patch", &p.aliases), ("preimage", &pre.aliases)] {
458                if let Some(alias) = set.as_deref().and_then(repeated_alias) {
459                    return Err(format!(
460                        "UpdateOp {side} aliases name {alias:?} more than once"
461                    ));
462                }
463            }
464            Ok(())
465        }
466        (UpdatePatch::Note(p), UpdatePreimage::Note(pre)) => {
467            check_touched("content", p.content.is_some(), pre.content.is_some())?;
468            check_touched("salience", p.salience.is_some(), pre.salience.is_some())?;
469            check_touched(
470                "decay_factor",
471                p.decay_factor.is_some(),
472                pre.decay_factor.is_some(),
473            )?;
474            check_touched(
475                "properties",
476                p.properties.is_some(),
477                pre.properties.is_some(),
478            )?;
479            check_touched("tags", p.tags.is_some(), pre.tags.is_some())?;
480            if let Some(Some(s)) = pre.salience {
481                if !s.is_finite() || !(0.0..=1.0).contains(&s) {
482                    return Err(format!(
483                        "UpdateOp note preimage salience must be finite and in [0.0, 1.0], got {s}"
484                    ));
485                }
486            }
487            if let Some(Some(d)) = pre.decay_factor {
488                if !d.is_finite() || d < 0.0 {
489                    return Err(format!(
490                        "UpdateOp note preimage decay_factor must be finite and non-negative, got {d}"
491                    ));
492                }
493            }
494            Ok(())
495        }
496        (UpdatePatch::Edge(p), UpdatePreimage::Edge(pre)) => {
497            check_touched("relation", p.relation.is_some(), pre.relation.is_some())?;
498            check_touched("weight", p.weight.is_some(), pre.weight.is_some())?;
499            if let Some(w) = pre.weight {
500                if !khive_types::validate_edge_weight(w) {
501                    return Err(format!(
502                        "UpdateOp edge preimage weight must be finite and in [0.0, 1.0], got {w}"
503                    ));
504                }
505            }
506            p.validate_weight()?;
507            Ok(())
508        }
509        _ => Err(format!(
510            "UpdateOp patch target ({}) does not match preimage target ({})",
511            patch_target_name(patch),
512            preimage_target_name(preimage)
513        )),
514    }
515}
516
517/// The first alias a set names twice, whatever the origins: one entity holds
518/// one row per alias.
519fn repeated_alias(set: &[EntityAlias]) -> Option<&str> {
520    crate::record::repeated(set.iter().map(|held| held.alias.as_str()))
521}
522
523fn check_touched(field: &str, patch_touched: bool, preimage_present: bool) -> Result<(), String> {
524    match (patch_touched, preimage_present) {
525        (true, false) => Err(format!(
526            "UpdateOp preimage is missing `{field}`, which the patch sets or clears"
527        )),
528        (false, true) => Err(format!(
529            "UpdateOp preimage carries `{field}`, which the patch leaves unchanged"
530        )),
531        _ => Ok(()),
532    }
533}
534
535fn patch_target_name(patch: &UpdatePatch) -> &'static str {
536    match patch {
537        UpdatePatch::Entity(_) => "entity",
538        UpdatePatch::Note(_) => "note",
539        UpdatePatch::Edge(_) => "edge",
540    }
541}
542
543fn preimage_target_name(preimage: &UpdatePreimage) -> &'static str {
544    match preimage {
545        UpdatePreimage::Entity(_) => "entity",
546        UpdatePreimage::Note(_) => "note",
547        UpdatePreimage::Edge(_) => "edge",
548    }
549}
550
551/// Removes one record with its required, full stage-time preimage.
552///
553/// Deserialization requires `target_id` to equal the embedded record ID.
554/// See `crates/khive-changeset/docs/api/delete-and-merge.md` for strictness rules.
555#[derive(Clone, Debug, Serialize)]
556pub struct DeleteOp {
557    pub target_id: Id128,
558    pub hard: bool,
559    pub preimage: DeletePreimage,
560}
561
562#[derive(Deserialize)]
563#[serde(deny_unknown_fields)]
564struct DeleteOpRaw {
565    target_id: Id128,
566    hard: bool,
567    preimage: DeletePreimage,
568}
569
570impl<'de> Deserialize<'de> for DeleteOp {
571    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
572    where
573        D: Deserializer<'de>,
574    {
575        let raw = DeleteOpRaw::deserialize(deserializer)?;
576        let preimage_id = raw.preimage.record_id();
577        if raw.target_id != preimage_id {
578            return Err(serde::de::Error::custom(format!(
579                "DeleteOp target_id {} does not match preimage record id {preimage_id}",
580                raw.target_id
581            )));
582        }
583        Ok(DeleteOp {
584            target_id: raw.target_id,
585            hard: raw.hard,
586            preimage: raw.preimage,
587        })
588    }
589}
590
591/// Restores a soft-deleted record to its captured live content.
592///
593/// The full record uses the same strict wire mirrors as [`DeletePreimage`].
594/// See `crates/khive-changeset/docs/api/restore.md` for lifecycle semantics.
595#[derive(Clone, Debug, Serialize)]
596pub struct RestoreOp {
597    target_id: Id128,
598    record: DeletePreimage,
599}
600
601impl RestoreOp {
602    /// Checks target identity, live state, and the embedded numeric invariants.
603    ///
604    /// # Errors
605    ///
606    /// Refuses a mismatched ID, a tombstoned record, a non-active note, or invalid numeric values.
607    pub fn new(target_id: Id128, record: DeletePreimage) -> Result<Self, String> {
608        if target_id != record.record_id() {
609            return Err(format!(
610                "RestoreOp target_id {target_id} does not match record id {}",
611                record.record_id()
612            ));
613        }
614        if let DeletePreimage::Note(row) = &record {
615            if row.status != NoteStatus::Active {
616                return Err("RestoreOp note record must be active; live restore cannot recover another status".into());
617            }
618        }
619        let (live, valid) = match &record {
620            DeletePreimage::Entity(row) => (row.entity.deleted_at.is_none(), true),
621            DeletePreimage::Note(row) => (row.deleted_at.is_none(), row.is_valid()),
622            DeletePreimage::Edge(row) => (row.deleted_at.is_none(), row.is_valid()),
623        };
624        if !live {
625            return Err("RestoreOp record must have no deleted_at tombstone".into());
626        }
627        if !valid {
628            return Err("RestoreOp record has invalid numeric values".into());
629        }
630        Ok(Self { target_id, record })
631    }
632
633    /// The identifier of the existing soft-deleted record.
634    pub fn target_id(&self) -> Id128 {
635        self.target_id
636    }
637
638    /// The full expected live record, including captured lifecycle metadata.
639    pub fn record(&self) -> &DeletePreimage {
640        &self.record
641    }
642}
643
644#[derive(Deserialize)]
645#[serde(deny_unknown_fields)]
646struct RestoreOpRaw {
647    target_id: Id128,
648    record: DeletePreimage,
649}
650
651impl<'de> Deserialize<'de> for RestoreOp {
652    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
653    where
654        D: Deserializer<'de>,
655    {
656        let raw = RestoreOpRaw::deserialize(deserializer)?;
657        Self::new(raw.target_id, raw.record).map_err(serde::de::Error::custom)
658    }
659}
660
661/// Full prior record state, tagged by `substrate` to avoid its embedded `kind` field.
662///
663/// An entity is carried whole, with the keys it holds and its aliases
664/// (ADR-221 section 4), so the record a delete removes is the record a restore
665/// would bring back.
666#[derive(Clone, Debug, Serialize)]
667#[serde(tag = "substrate", rename_all = "snake_case")]
668pub enum DeletePreimage {
669    Entity(Box<EntityRecord>),
670    Note(Box<Note>),
671    Edge(Box<Link>),
672}
673
674impl DeletePreimage {
675    /// The identifier of the record this preimage was captured from.
676    fn record_id(&self) -> Id128 {
677        match self {
678            DeletePreimage::Entity(e) => e.entity.header.id,
679            DeletePreimage::Note(n) => n.header.id,
680            DeletePreimage::Edge(l) => l.id,
681        }
682    }
683}
684
685/// Strict deserialize-only mirror of [`DeletePreimage`].
686#[derive(Deserialize)]
687#[serde(tag = "substrate", rename_all = "snake_case")]
688enum DeletePreimageRaw {
689    Entity(StrictEntity),
690    Note(StrictNote),
691    Edge(StrictLink),
692}
693
694impl<'de> Deserialize<'de> for DeletePreimage {
695    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
696    where
697        D: Deserializer<'de>,
698    {
699        let raw = DeletePreimageRaw::deserialize(deserializer)?;
700        Ok(match raw {
701            DeletePreimageRaw::Entity(e) => {
702                DeletePreimage::Entity(Box::new(e.try_into().map_err(serde::de::Error::custom)?))
703            }
704            DeletePreimageRaw::Note(n) => {
705                DeletePreimage::Note(Box::new(n.try_into().map_err(serde::de::Error::custom)?))
706            }
707            DeletePreimageRaw::Edge(l) => {
708                DeletePreimage::Edge(Box::new(l.try_into().map_err(serde::de::Error::custom)?))
709            }
710        })
711    }
712}
713
714/// Merges two entities with required participant and incident-edge preimages.
715///
716/// Deserialization matches both IDs and requires every incident edge to touch
717/// at least one participant.
718/// See `crates/khive-changeset/docs/api/delete-and-merge.md` for the full contract.
719#[derive(Clone, Debug, Serialize)]
720pub struct MergeOp {
721    pub into_id: Id128,
722    pub from_id: Id128,
723    pub preimage: MergePreimage,
724}
725
726#[derive(Deserialize)]
727#[serde(deny_unknown_fields)]
728struct MergeOpRaw {
729    into_id: Id128,
730    from_id: Id128,
731    preimage: MergePreimage,
732}
733
734impl<'de> Deserialize<'de> for MergeOp {
735    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
736    where
737        D: Deserializer<'de>,
738    {
739        let raw = MergeOpRaw::deserialize(deserializer)?;
740        if raw.into_id != raw.preimage.into.entity.header.id {
741            return Err(serde::de::Error::custom(format!(
742                "MergeOp into_id {} does not match preimage.into record id {}",
743                raw.into_id, raw.preimage.into.entity.header.id
744            )));
745        }
746        if raw.from_id != raw.preimage.from.entity.header.id {
747            return Err(serde::de::Error::custom(format!(
748                "MergeOp from_id {} does not match preimage.from record id {}",
749                raw.from_id, raw.preimage.from.entity.header.id
750            )));
751        }
752        for edge in &raw.preimage.incident_edges {
753            let touches_into = edge.source == raw.into_id || edge.target == raw.into_id;
754            let touches_from = edge.source == raw.from_id || edge.target == raw.from_id;
755            if !(touches_into || touches_from) {
756                return Err(serde::de::Error::custom(format!(
757                    "MergeOp incident edge {} references neither into_id {} nor from_id {}",
758                    edge.id, raw.into_id, raw.from_id
759                )));
760            }
761        }
762        Ok(MergeOp {
763            into_id: raw.into_id,
764            from_id: raw.from_id,
765            preimage: raw.preimage,
766        })
767    }
768}
769
770/// Full prior state required to validate and rewire an entity merge.
771///
772/// Both participants are carried whole, with the keys they hold and their
773/// aliases (ADR-221 section 4). Canonical apply does not run a merge yet; the
774/// record is complete for the applier that will.
775///
776/// See `crates/khive-changeset/docs/api/delete-and-merge.md` for edge coverage rules.
777#[derive(Clone, Debug, Serialize)]
778pub struct MergePreimage {
779    pub into: Box<EntityRecord>,
780    pub from: Box<EntityRecord>,
781    pub incident_edges: Vec<Link>,
782}
783
784#[derive(Deserialize)]
785#[serde(deny_unknown_fields)]
786struct MergePreimageRaw {
787    into: StrictEntity,
788    from: StrictEntity,
789    incident_edges: Vec<StrictLink>,
790}
791
792impl<'de> Deserialize<'de> for MergePreimage {
793    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
794    where
795        D: Deserializer<'de>,
796    {
797        let raw = MergePreimageRaw::deserialize(deserializer)?;
798        let incident_edges = raw
799            .incident_edges
800            .into_iter()
801            .map(|l| l.try_into().map_err(serde::de::Error::custom))
802            .collect::<Result<Vec<Link>, D::Error>>()?;
803        Ok(MergePreimage {
804            into: Box::new(raw.into.try_into().map_err(serde::de::Error::custom)?),
805            from: Box::new(raw.from.try_into().map_err(serde::de::Error::custom)?),
806            incident_edges,
807        })
808    }
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814
815    #[test]
816    fn link_op_rejects_out_of_range_weight() {
817        let json = serde_json::json!({
818            "id": "00000000-0000-0000-0000-000000000001",
819            "namespace": "local",
820            "source": "00000000-0000-0000-0000-000000000002",
821            "target": "00000000-0000-0000-0000-000000000003",
822            "relation": "extends",
823            "weight": 1.5,
824            "properties": {}
825        });
826        let result: Result<LinkOp, _> = serde_json::from_value(json);
827        assert!(result.is_err());
828    }
829
830    #[test]
831    fn create_op_rejects_unknown_field() {
832        let json = serde_json::json!({
833            "id": "00000000-0000-0000-0000-000000000001",
834            "namespace": "local",
835            "target": {
836                "kind": "entity",
837                "entity_kind": "concept",
838                "name": "X",
839                "surprise": true
840            }
841        });
842        let result: Result<CreateOp, _> = serde_json::from_value(json);
843        assert!(result.is_err());
844    }
845
846    #[test]
847    fn entity_patch_distinguishes_absent_and_null_description() {
848        let absent: EntityPatch = serde_json::from_value(serde_json::json!({})).unwrap();
849        assert_eq!(absent.description, None);
850
851        let cleared: EntityPatch =
852            serde_json::from_value(serde_json::json!({ "description": null })).unwrap();
853        assert_eq!(cleared.description, Some(None));
854
855        let set: EntityPatch =
856            serde_json::from_value(serde_json::json!({ "description": "new" })).unwrap();
857        assert_eq!(set.description, Some(Some("new".to_string())));
858    }
859
860    #[test]
861    fn delete_op_requires_preimage() {
862        let json = serde_json::json!({
863            "target_id": "00000000-0000-0000-0000-000000000001",
864            "hard": false
865        });
866        let result: Result<DeleteOp, _> = serde_json::from_value(json);
867        assert!(result.is_err());
868    }
869
870    #[test]
871    fn merge_op_requires_preimage() {
872        let json = serde_json::json!({
873            "into_id": "00000000-0000-0000-0000-000000000001",
874            "from_id": "00000000-0000-0000-0000-000000000002"
875        });
876        let result: Result<MergeOp, _> = serde_json::from_value(json);
877        assert!(result.is_err());
878    }
879
880    #[test]
881    fn update_op_rejects_preimage_missing_touched_field() {
882        let json = serde_json::json!({
883            "target_id": "00000000-0000-0000-0000-000000000001",
884            "patch": { "target": "entity", "name": "new-name" },
885            "preimage": { "target": "entity" }
886        });
887        let result: Result<UpdateOp, _> = serde_json::from_value(json);
888        assert!(result.is_err());
889    }
890
891    #[test]
892    fn update_op_rejects_preimage_with_extra_untouched_field() {
893        let json = serde_json::json!({
894            "target_id": "00000000-0000-0000-0000-000000000001",
895            "patch": { "target": "entity", "tags": ["a"] },
896            "preimage": {
897                "target": "entity",
898                "name": "stale-prior-name",
899                "tags": ["prior-a"]
900            }
901        });
902        let result: Result<UpdateOp, _> = serde_json::from_value(json);
903        assert!(result.is_err());
904    }
905
906    #[test]
907    fn update_op_rejects_mismatched_target_variant() {
908        let json = serde_json::json!({
909            "target_id": "00000000-0000-0000-0000-000000000001",
910            "patch": { "target": "entity", "name": "n" },
911            "preimage": { "target": "note", "content": "prior" }
912        });
913        let result: Result<UpdateOp, _> = serde_json::from_value(json);
914        assert!(result.is_err());
915    }
916
917    #[test]
918    fn update_op_explicit_null_clear_captures_prior_value() {
919        let json = serde_json::json!({
920            "target_id": "00000000-0000-0000-0000-000000000001",
921            "patch": { "target": "entity", "description": null },
922            "preimage": { "target": "entity", "description": "was-set" }
923        });
924        let op: UpdateOp = serde_json::from_value(json).unwrap();
925        match op.patch {
926            UpdatePatch::Entity(p) => assert_eq!(p.description, Some(None)),
927            other => panic!("expected entity patch, got {other:?}"),
928        }
929        match op.preimage {
930            UpdatePreimage::Entity(pre) => {
931                assert_eq!(pre.description, Some(Some("was-set".to_string())))
932            }
933            other => panic!("expected entity preimage, got {other:?}"),
934        }
935    }
936
937    #[test]
938    fn update_op_accepts_congruent_preimage() {
939        let json = serde_json::json!({
940            "target_id": "00000000-0000-0000-0000-000000000001",
941            "patch": { "target": "edge", "weight": 0.5 },
942            "preimage": { "target": "edge", "weight": 0.9 }
943        });
944        let result: Result<UpdateOp, _> = serde_json::from_value(json);
945        assert!(result.is_ok());
946    }
947
948    #[test]
949    fn update_op_rejects_out_of_range_preimage_weight() {
950        let json = serde_json::json!({
951            "target_id": "00000000-0000-0000-0000-000000000001",
952            "patch": { "target": "edge", "weight": 0.5 },
953            "preimage": { "target": "edge", "weight": 1.5 }
954        });
955        let result: Result<UpdateOp, _> = serde_json::from_value(json);
956        assert!(result.is_err());
957    }
958
959    #[test]
960    fn update_op_rejects_out_of_range_preimage_salience() {
961        let json = serde_json::json!({
962            "target_id": "00000000-0000-0000-0000-000000000001",
963            "patch": { "target": "note", "salience": 0.2 },
964            "preimage": { "target": "note", "salience": 1.9 }
965        });
966        let result: Result<UpdateOp, _> = serde_json::from_value(json);
967        assert!(result.is_err());
968    }
969
970    #[test]
971    fn update_op_new_rejects_incongruent_construction() {
972        let result = UpdateOp::new(
973            Id128::from_u128(1),
974            UpdatePatch::Entity(EntityPatch {
975                name: Some("new-name".to_string()),
976                description: None,
977                properties: None,
978                tags: None,
979                entity_type: None,
980                aliases: None,
981            }),
982            UpdatePreimage::Entity(EntityPreimage {
983                name: None,
984                description: None,
985                properties: None,
986                tags: None,
987                entity_type: None,
988                aliases: None,
989            }),
990        );
991        assert!(result.is_err());
992    }
993}