1use 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
47pub const WITHDRAWN_REASON: &str = "withdrawn by author";
49
50#[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#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct StoreFact {
62 pub category: String,
63 pub key: String,
64 pub value_digest: String,
65 pub current: bool,
67 pub confirmed_here: bool,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct NodeView {
74 pub live: bool,
75 pub marked: bool,
77 pub has_anchors: bool,
78}
79
80#[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#[derive(Debug, Default)]
90pub struct Present {
91 pub supersedes: BTreeSet<(String, String)>,
93 pub retracting: BTreeSet<String>,
95 pub confirming: BTreeSet<String>,
97 pub adding: BTreeSet<String>,
101}
102
103impl Present {
104 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
116pub 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
129pub 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 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 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
217pub 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
237pub 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
254pub 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#[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
299pub 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
383pub 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;