Skip to main content

lean_ctx_cloud/capture/
lifecycle.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The lifecycle of captured knowledge after its `node.add`: what an agent
3//! does to a fact later reaches the vault, so other engines never keep
4//! receiving knowledge its author has withdrawn.
5//!
6//! Capture (step 6, [`super::emit`]) records for every node it adds which
7//! local fact it came from (`own_sources`: project, category, key, value
8//! digest). Each sync compares those own nodes with the project's knowledge
9//! store and queues, through the existing event builders:
10//!
11//! - **superseded**: the fact's value is no longer current and a current
12//!   fact of the same category and key has its own node → `edge.add
13//!   supersedes` from that node to the old one. The server derives the old
14//!   node `outdated (superseded)`; it is not retracted (one or the other).
15//! - **withdrawn**: no fact of the store carries the node's value any more
16//!   and no successor has a node → `retract` with the fixed reason
17//!   `withdrawn by author` (no content).
18//! - **re-pinned**: the vault marked the claim `to_verify`/`gone`, while the
19//!   local fact with the same value is current, not under review and its
20//!   anchors match the code here (an agent re-pinned it) → the claim is
21//!   re-anchored at `HEAD` and `anchor_state fresh`, the event `cloud
22//!   maintain --confirm` writes.
23//!
24//! The comparison reads the raw store, not a policy view: a fact a view
25//! withholds still exists and is never retracted for that. A store that
26//! cannot be read, or holds no facts while own nodes exist, plans nothing.
27//! Only `fact` sources of this checkout count; another checkout of the same
28//! vault owns its nodes. The server's retraction limits apply unchanged: a
29//! held retraction stays pending, the engine sets no threshold of its own.
30//!
31//! Every action is idempotent: an edge or retraction already in the folded
32//! place or still pending is not queued again, so a sync that ran before
33//! changes nothing.
34
35use std::collections::{BTreeMap, BTreeSet};
36
37use serde_json::Value;
38
39use super::refs::Checkout;
40use crate::CloudError;
41use crate::events::build;
42use crate::events::hlc::{self, Stamp};
43use crate::replica::Replica;
44use crate::replica::fold::Graph;
45use crate::review::{curate, maintain};
46
47/// The reason of a lifecycle retraction: stable, and no fact content.
48pub const WITHDRAWN_REASON: &str = "withdrawn by author";
49
50/// An own node and the fact it was captured from.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct OwnNode {
53    pub node_id: String,
54    pub category: String,
55    pub key: String,
56    pub value_digest: String,
57}
58
59/// A fact of the raw store, as far as the lifecycle needs it.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct StoreFact {
62    pub category: String,
63    pub key: String,
64    pub value_digest: String,
65    /// Not superseded and not expired (`valid_until` unset).
66    pub current: bool,
67    /// Current, not under review, and every anchor matches this checkout.
68    pub confirmed_here: bool,
69}
70
71/// What the vault shows of a node.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct NodeView {
74    pub live: bool,
75    /// `anchor_state` is `to_verify` or `gone`.
76    pub marked: bool,
77    pub has_anchors: bool,
78}
79
80/// One lifecycle action, in the order it is queued.
81#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
82pub enum Action {
83    Supersede { old: String, new: String },
84    Retract { node: String },
85    Confirm { node: String },
86}
87
88/// What is already in the place or pending, so nothing is queued twice.
89#[derive(Debug, Default)]
90pub struct Present {
91    /// `(from, to)` of live or pending `supersedes` edges.
92    pub supersedes: BTreeSet<(String, String)>,
93    /// Targets of pending `retract` events.
94    pub retracting: BTreeSet<String>,
95    /// Targets of pending `field.set anchors` events.
96    pub confirming: BTreeSet<String>,
97    /// Nodes queued by a pending `node.add` (this sync's captures): live for
98    /// the plan, so a successor captured in the same run supersedes its
99    /// predecessor instead of the predecessor being retracted.
100    pub adding: BTreeSet<String>,
101}
102
103impl Present {
104    /// [`node_view`] in `graph`, or a pending addition as a live node.
105    pub fn view(&self, graph: &Graph, node_id: &str) -> Option<NodeView> {
106        node_view(graph, node_id).or_else(|| {
107            self.adding.contains(node_id).then_some(NodeView {
108                live: true,
109                marked: false,
110                has_anchors: false,
111            })
112        })
113    }
114}
115
116/// The `(category, key)` of every fact the knowledge journal of the
117/// checkout at `root` records as removed.
118pub fn removed_identities(root: &str) -> BTreeSet<(String, String)> {
119    let Ok(dir) = lean_ctx::core::knowledge::knowledge_dir_of(root) else {
120        return BTreeSet::new();
121    };
122    lean_ctx::core::knowledge::journal::rows_since(&dir, 0, usize::MAX)
123        .into_iter()
124        .filter(|r| r.op == "removed")
125        .map(|r| (r.category, r.key))
126        .collect()
127}
128
129/// The actions that bring the vault in line with the store, in node id
130/// order (deterministic).
131///
132/// `removed` are the `(category, key)` identities the knowledge journal
133/// records as removed. An empty store withdraws only those: a store that
134/// was reset or could not be read never withdraws everything.
135pub fn plan(
136    own: &[OwnNode],
137    store: &[StoreFact],
138    removed: &BTreeSet<(String, String)>,
139    node: impl Fn(&str) -> Option<NodeView>,
140    present: &Present,
141) -> Vec<Action> {
142    if store.is_empty() && removed.is_empty() {
143        return Vec::new();
144    }
145    let mut by_identity: BTreeMap<(&str, &str), Vec<&StoreFact>> = BTreeMap::new();
146    for fact in store {
147        by_identity
148            .entry((fact.category.as_str(), fact.key.as_str()))
149            .or_default()
150            .push(fact);
151    }
152    // The own live node of each (category, key, value digest).
153    let mut node_of: BTreeMap<(&str, &str, &str), &str> = BTreeMap::new();
154    for n in own {
155        if node(&n.node_id).is_some_and(|v| v.live) {
156            node_of.insert(
157                (n.category.as_str(), n.key.as_str(), n.value_digest.as_str()),
158                n.node_id.as_str(),
159            );
160        }
161    }
162    let mut actions = Vec::new();
163    for n in own {
164        let Some(view) = node(&n.node_id).filter(|v| v.live) else {
165            continue;
166        };
167        let facts = by_identity
168            .get(&(n.category.as_str(), n.key.as_str()))
169            .map(Vec::as_slice)
170            .unwrap_or_default();
171        let same = facts.iter().find(|f| f.value_digest == n.value_digest);
172        if let Some(fact) = same.filter(|f| f.current) {
173            if view.marked
174                && view.has_anchors
175                && fact.confirmed_here
176                && !present.confirming.contains(&n.node_id)
177            {
178                actions.push(Action::Confirm {
179                    node: n.node_id.clone(),
180                });
181            }
182            continue;
183        }
184        // The node's value is not current any more (superseded, expired or
185        // removed). A current successor with its own node supersedes it.
186        let successor = facts
187            .iter()
188            .filter(|f| f.current && f.value_digest != n.value_digest)
189            .find_map(|f| {
190                node_of.get(&(f.category.as_str(), f.key.as_str(), f.value_digest.as_str()))
191            });
192        if let Some(&new) = successor {
193            if !present
194                .supersedes
195                .contains(&(new.to_owned(), n.node_id.clone()))
196            {
197                actions.push(Action::Supersede {
198                    old: n.node_id.clone(),
199                    new: new.to_owned(),
200                });
201            }
202        } else {
203            let journaled = removed.contains(&(n.category.clone(), n.key.clone()));
204            if (store.is_empty() && !journaled) || present.retracting.contains(&n.node_id) {
205                continue;
206            }
207            actions.push(Action::Retract {
208                node: n.node_id.clone(),
209            });
210        }
211    }
212    actions.sort();
213    actions.dedup();
214    actions
215}
216
217/// The own `fact` nodes of the checkout `project_hash`, from `own_sources`.
218pub fn own_nodes(replica: &Replica, project_hash: &str) -> Result<Vec<OwnNode>, CloudError> {
219    Ok(replica
220        .own_sources()?
221        .into_iter()
222        .filter(|(_, kind, _)| kind == "fact")
223        .filter_map(|(node_id, _, source)| {
224            if source.get("project_hash")?.as_str()? != project_hash {
225                return None;
226            }
227            Some(OwnNode {
228                node_id,
229                category: source.get("category")?.as_str()?.to_owned(),
230                key: source.get("key")?.as_str()?.to_owned(),
231                value_digest: source.get("value_digest")?.as_str()?.to_owned(),
232            })
233        })
234        .collect())
235}
236
237/// The vault's view of `node_id` in `graph`.
238pub fn node_view(graph: &Graph, node_id: &str) -> Option<NodeView> {
239    let node = graph.nodes.get(node_id)?;
240    Some(NodeView {
241        live: !node.retracted && !node.purged,
242        marked: matches!(
243            node.fields.get("anchor_state").and_then(Value::as_str),
244            Some("to_verify" | "gone")
245        ),
246        has_anchors: node
247            .fields
248            .get("anchors")
249            .and_then(Value::as_array)
250            .is_some_and(|a| !a.is_empty()),
251    })
252}
253
254/// What the folded place and the pending queue already hold.
255pub fn present(graph: &Graph, replica: &Replica) -> Result<Present, CloudError> {
256    let mut out = Present::default();
257    for edge in graph.edges.values() {
258        if edge.kind == "supersedes" && !edge.retracted {
259            out.supersedes.insert((edge.from.clone(), edge.to.clone()));
260        }
261    }
262    for (_, bytes) in replica.pending()? {
263        let Ok(event) = serde_json::from_slice::<Value>(&bytes) else {
264            continue;
265        };
266        let target = event["target"].as_str().unwrap_or_default().to_owned();
267        match event["op"].as_str() {
268            Some("retract") => {
269                out.retracting.insert(target);
270            }
271            Some("field.set") if event["body"]["field"] == "anchors" => {
272                out.confirming.insert(target);
273            }
274            Some("node.add") => {
275                out.adding.insert(target);
276            }
277            Some("edge.add") if event["body"]["kind"] == "supersedes" => {
278                if let (Some(from), Some(to)) =
279                    (event["body"]["from"].as_str(), event["body"]["to"].as_str())
280                {
281                    out.supersedes.insert((from.to_owned(), to.to_owned()));
282                }
283            }
284            _ => {}
285        }
286    }
287    Ok(out)
288}
289
290/// What [`queue`] queued.
291#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
292pub struct Queued {
293    pub superseded: usize,
294    pub retracted: usize,
295    pub confirmed: usize,
296    pub clock: Stamp,
297}
298
299/// Queue the signed events of `actions` as pending (the sync push sends
300/// them), continuing `clock`. A confirm whose anchored code is gone is
301/// skipped: a gone claim is withdrawn, not re-anchored.
302pub fn queue(
303    target: &maintain::Target<'_>,
304    graph: &Graph,
305    checkout: &mut Checkout,
306    actions: &[Action],
307    clock: Stamp,
308    now_ms: u64,
309) -> Result<Queued, CloudError> {
310    let mut out = Queued {
311        clock,
312        ..Queued::default()
313    };
314    for action in actions {
315        match action {
316            Action::Supersede { old, new } => {
317                out.clock = hlc::send(out.clock, now_ms);
318                let event = build::edge_add(
319                    "supersedes",
320                    new,
321                    old,
322                    "observed",
323                    target.place,
324                    out.clock,
325                    target.signer,
326                )?;
327                maintain::queue(target, &event, out.clock)?;
328                out.superseded += 1;
329            }
330            Action::Retract { node } => {
331                out.clock = hlc::send(out.clock, now_ms);
332                let event = curate::retract_event(
333                    target.place,
334                    node,
335                    WITHDRAWN_REASON,
336                    out.clock,
337                    target.signer,
338                )?;
339                maintain::queue(target, &event, out.clock)?;
340                out.retracted += 1;
341            }
342            Action::Confirm { node } => {
343                let Some(anchors) = graph
344                    .nodes
345                    .get(node)
346                    .and_then(|n| n.fields.get("anchors"))
347                    .and_then(Value::as_array)
348                else {
349                    continue;
350                };
351                let Some(fresh) = maintain::reanchored(anchors, checkout, now_ms) else {
352                    continue;
353                };
354                out.clock = hlc::send(out.clock, now_ms);
355                let event = maintain::field_set(
356                    target.place,
357                    node,
358                    "anchors",
359                    Value::Array(fresh),
360                    Some(now_ms),
361                    out.clock,
362                    target.signer,
363                )?;
364                maintain::queue(target, &event, out.clock)?;
365                out.clock = hlc::send(out.clock, now_ms);
366                let event = maintain::field_set(
367                    target.place,
368                    node,
369                    "anchor_state",
370                    Value::from("fresh"),
371                    None,
372                    out.clock,
373                    target.signer,
374                )?;
375                maintain::queue(target, &event, out.clock)?;
376                out.confirmed += 1;
377            }
378        }
379    }
380    Ok(out)
381}
382
383/// The raw store's facts of `project_root` for [`plan`], with value digests
384/// keyed like `own_sources` (`replica.value_digest`). `None` when the store
385/// cannot be read.
386pub fn store_facts(replica: &Replica, project_root: &str) -> Option<Vec<StoreFact>> {
387    let knowledge =
388        lean_ctx::core::knowledge::ProjectKnowledge::load_for_checked_capture(project_root).ok()?;
389    let root = std::path::Path::new(project_root);
390    Some(
391        knowledge
392            .facts
393            .iter()
394            .map(|fact| {
395                let current = fact.valid_until.is_none();
396                let anchors_here = !fact.anchors.is_empty()
397                    && lean_ctx::core::knowledge::anchors::review(root, &fact.anchors)
398                        .iter()
399                        .all(|(_, state)| {
400                            *state == lean_ctx::core::knowledge::anchors::AnchorState::Current
401                        });
402                StoreFact {
403                    category: fact.category.clone(),
404                    key: fact.key.clone(),
405                    value_digest: replica.value_digest(&fact.value),
406                    current,
407                    confirmed_here: current && fact.review.is_none() && anchors_here,
408                }
409            })
410            .collect(),
411    )
412}
413
414#[cfg(test)]
415#[path = "lifecycle_tests.rs"]
416mod tests;