Skip to main content

lean_ctx_cloud/knowledge/
doc.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Operations on the `ctxpkg.research-context.v1` document: applying a
3//! proposal patch exactly like Cloud does on merge, and rebasing pending
4//! draft ops onto a newer revision. The wire types and their structural
5//! validation live in `lean_ctx_protocol::cloud::knowledge`.
6
7use lean_ctx_protocol::cloud::knowledge::{
8    FactV1, PageItemV1, PageV1, PatchOpV1, ResearchContextDocumentV1,
9};
10
11fn fact<'a>(doc: &'a ResearchContextDocumentV1, id: &str) -> Option<&'a FactV1> {
12    doc.facts.iter().find(|f| f.id == id)
13}
14
15fn page<'a>(doc: &'a ResearchContextDocumentV1, id: &str) -> Option<&'a PageV1> {
16    doc.pages.iter().find(|p| p.id == id)
17}
18
19/// Equality of what a person wrote, ignoring credits assigned on merge.
20pub fn same_content(a: &FactV1, b: &FactV1) -> bool {
21    a.id == b.id
22        && a.statement == b.statement
23        && a.kind == b.kind
24        && a.applies_to == b.applies_to
25        && a.sources == b.sources
26        && a.anchors == b.anchors
27}
28
29/// Apply `ops` in order; any op that does not fit the document is an error.
30pub fn apply_patch(
31    doc: &ResearchContextDocumentV1,
32    ops: &[PatchOpV1],
33) -> Result<ResearchContextDocumentV1, String> {
34    let mut d = doc.clone();
35    for op in ops {
36        match op {
37            PatchOpV1::AddFact { fact: new } => {
38                if fact(&d, &new.id).is_some() {
39                    return Err(format!("fact '{}' already exists", new.id));
40                }
41                d.facts.push(new.clone());
42            }
43            PatchOpV1::UpdateFact { id, fact: new } => {
44                let pos = d
45                    .facts
46                    .iter()
47                    .position(|f| &f.id == id)
48                    .ok_or_else(|| format!("fact '{id}' does not exist"))?;
49                let mut updated = new.clone();
50                for credit in &d.facts[pos].from_contributions {
51                    if !updated.from_contributions.contains(credit) {
52                        updated.from_contributions.push(credit.clone());
53                    }
54                }
55                d.facts[pos] = updated;
56            }
57            PatchOpV1::RetractFact { id } => {
58                let before = d.facts.len();
59                d.facts.retain(|f| &f.id != id);
60                if d.facts.len() == before {
61                    return Err(format!("fact '{id}' does not exist"));
62                }
63                d.relations.retain(|r| &r.from != id && &r.to != id);
64                for page in &mut d.pages {
65                    page.items.retain(
66                        |item| !matches!(item, PageItemV1::Fact { id: shown } if shown == id),
67                    );
68                }
69                d.pages.retain(|page| !page.items.is_empty());
70            }
71            PatchOpV1::AddRelation { relation } => {
72                if d.relations.contains(relation) {
73                    return Err(format!(
74                        "relation {} -{}-> {} already exists",
75                        relation.from, relation.kind, relation.to
76                    ));
77                }
78                d.relations.push(relation.clone());
79            }
80            PatchOpV1::RemoveRelation { relation } => {
81                let before = d.relations.len();
82                d.relations.retain(|r| r != relation);
83                if d.relations.len() == before {
84                    return Err(format!(
85                        "relation {} -{}-> {} does not exist",
86                        relation.from, relation.kind, relation.to
87                    ));
88                }
89            }
90            PatchOpV1::AddGap { text } => {
91                if !d.open_gaps.contains(text) {
92                    d.open_gaps.push(text.clone());
93                }
94            }
95            PatchOpV1::CloseGap { text } => {
96                let before = d.open_gaps.len();
97                d.open_gaps.retain(|g| g != text);
98                if d.open_gaps.len() == before {
99                    return Err(format!("open gap '{text}' does not exist"));
100                }
101            }
102            PatchOpV1::AddPage { page: new } => {
103                if page(&d, &new.id).is_some() {
104                    return Err(format!("page '{}' already exists", new.id));
105                }
106                d.pages.push(new.clone());
107            }
108            PatchOpV1::UpdatePage { id, page: new } => {
109                let pos = d
110                    .pages
111                    .iter()
112                    .position(|p| &p.id == id)
113                    .ok_or_else(|| format!("page '{id}' does not exist"))?;
114                d.pages[pos] = new.clone();
115            }
116            PatchOpV1::RemovePage { id } => {
117                let before = d.pages.len();
118                d.pages.retain(|p| &p.id != id);
119                if d.pages.len() == before {
120                    return Err(format!("page '{id}' does not exist"));
121                }
122            }
123        }
124    }
125    d.validate().map_err(|e| e.to_string())?;
126    Ok(d)
127}
128
129/// Re-apply draft ops onto a newer base, dropping ops the base already
130/// contains (the same fact was merged meanwhile). Ops that clash with the
131/// new base are an error; the caller then keeps the draft on its old base.
132pub fn rebase_ops(
133    base: &ResearchContextDocumentV1,
134    ops: &[PatchOpV1],
135) -> Result<Vec<PatchOpV1>, String> {
136    let mut d = base.clone();
137    let mut kept = Vec::new();
138    for op in ops {
139        let redundant = match op {
140            PatchOpV1::AddFact { fact: new } => match fact(&d, &new.id) {
141                Some(existing) if same_content(existing, new) => true,
142                Some(_) => {
143                    return Err(format!(
144                        "fact '{}' was added upstream with different content",
145                        new.id
146                    ));
147                }
148                None => false,
149            },
150            PatchOpV1::UpdateFact { id, fact: new } => match fact(&d, id) {
151                Some(existing) => same_content(existing, new),
152                None => return Err(format!("fact '{id}' was retracted upstream")),
153            },
154            PatchOpV1::RetractFact { id } => fact(&d, id).is_none(),
155            PatchOpV1::AddRelation { relation } => d.relations.contains(relation),
156            PatchOpV1::RemoveRelation { relation } => !d.relations.contains(relation),
157            PatchOpV1::AddGap { text } => d.open_gaps.contains(text),
158            PatchOpV1::CloseGap { text } => !d.open_gaps.contains(text),
159            PatchOpV1::AddPage { page: new } => match page(&d, &new.id) {
160                Some(existing) if existing == new => true,
161                Some(_) => {
162                    return Err(format!(
163                        "page '{}' was added upstream with different content",
164                        new.id
165                    ));
166                }
167                None => false,
168            },
169            PatchOpV1::UpdatePage { id, page: new } => match page(&d, id) {
170                Some(existing) => existing == new,
171                None => return Err(format!("page '{id}' was removed upstream")),
172            },
173            PatchOpV1::RemovePage { id } => page(&d, id).is_none(),
174        };
175        if redundant {
176            continue;
177        }
178        d = apply_patch(&d, std::slice::from_ref(op))?;
179        kept.push(op.clone());
180    }
181    Ok(kept)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use lean_ctx_protocol::cloud::knowledge::RelationV1;
188
189    fn fact(id: &str, statement: &str) -> FactV1 {
190        FactV1 {
191            id: id.into(),
192            statement: statement.into(),
193            kind: "decision".into(),
194            applies_to: vec![],
195            sources: vec![],
196            from_contributions: vec![],
197            anchors: vec![],
198        }
199    }
200
201    fn add(id: &str, statement: &str) -> PatchOpV1 {
202        PatchOpV1::AddFact {
203            fact: fact(id, statement),
204        }
205    }
206
207    #[test]
208    fn patches_apply_and_keep_credits_on_update() {
209        let mut base = ResearchContextDocumentV1::default();
210        let mut credited = fact("a", "one");
211        credited.from_contributions = vec!["p1".into()];
212        base.facts.push(credited);
213        let doc = apply_patch(
214            &base,
215            &[
216                PatchOpV1::UpdateFact {
217                    id: "a".into(),
218                    fact: fact("a", "one, revised"),
219                },
220                add("b", "two"),
221                PatchOpV1::AddRelation {
222                    relation: RelationV1 {
223                        from: "b".into(),
224                        to: "a".into(),
225                        kind: "supports".into(),
226                    },
227                },
228            ],
229        )
230        .unwrap();
231        assert_eq!(doc.facts[0].from_contributions, vec!["p1".to_string()]);
232        assert_eq!(doc.relations.len(), 1);
233        assert!(apply_patch(&doc, &[add("b", "again")]).is_err());
234        let retracted = apply_patch(&doc, &[PatchOpV1::RetractFact { id: "a".into() }]).unwrap();
235        assert!(
236            retracted.relations.is_empty(),
237            "relations of a retracted fact go too"
238        );
239    }
240
241    #[test]
242    fn rebase_drops_merged_ops_and_refuses_clashes() {
243        let ops = vec![add("a", "one"), add("b", "two")];
244        let mut base = ResearchContextDocumentV1::default();
245        base.facts.push(fact("a", "one"));
246        assert_eq!(rebase_ops(&base, &ops).unwrap(), vec![add("b", "two")]);
247        base.facts[0].statement = "different".into();
248        assert!(rebase_ops(&base, &ops).is_err());
249    }
250}