1use serde_json::{Map, Value, json};
30use sha2::{Digest as _, Sha256};
31
32use crate::CloudError;
33use crate::capture::GATE_VERSION;
34use crate::capture::refs::{Checkout, Reference};
35use crate::events::build::{EVENT_SCHEMA, Place, Signer};
36use crate::events::hlc::{self, Stamp};
37use crate::events::{ids, sign};
38use crate::replica::Replica;
39use crate::replica::fold::Graph;
40
41pub const MAINTENANCE_ROLE: &str = "maintenance";
43pub const DEFAULT_LIMIT: usize = 50;
45pub const MAX_LIMIT: usize = 200;
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Request {
50 pub vault: String,
52 pub stale: bool,
53 pub contradictions: bool,
54 pub dedupe: bool,
55 pub limit: usize,
56 pub confirm: Option<String>,
58}
59
60fn usage(what: &str) -> CloudError {
61 CloudError::Config(format!(
62 "{what}; usage: lean-ctx cloud maintain <ws>/<vault> [--stale] [--contradictions] [--dedupe] [--limit N] | <ws>/<vault> --stale --confirm <node_id>"
63 ))
64}
65
66pub fn parse(args: &[String]) -> Result<Request, CloudError> {
68 let mut vault = None;
69 let mut req = Request {
70 vault: String::new(),
71 stale: false,
72 contradictions: false,
73 dedupe: false,
74 limit: DEFAULT_LIMIT,
75 confirm: None,
76 };
77 let mut it = args.iter();
78 while let Some(arg) = it.next() {
79 match arg.as_str() {
80 "--stale" => req.stale = true,
81 "--contradictions" => req.contradictions = true,
82 "--dedupe" => req.dedupe = true,
83 "--limit" => {
84 req.limit = it
85 .next()
86 .and_then(|n| n.parse().ok())
87 .filter(|n| (1..=MAX_LIMIT).contains(n))
88 .ok_or_else(|| usage("--limit takes 1..=200"))?;
89 }
90 "--confirm" => {
91 req.confirm = Some(
92 it.next()
93 .filter(|n| n.starts_with("n_"))
94 .cloned()
95 .ok_or_else(|| usage("--confirm takes a node id (n_…)"))?,
96 );
97 }
98 other if other.starts_with("--") => return Err(usage(&format!("unknown {other}"))),
99 other if vault.is_none() && other.split_once('/').is_some() => {
100 vault = Some(other.to_string());
101 }
102 other => return Err(usage(&format!("unexpected {other:?}"))),
103 }
104 }
105 req.vault = vault.ok_or_else(|| usage("name the vault"))?;
106 if req.confirm.is_some() && (!req.stale || req.contradictions || req.dedupe) {
107 return Err(usage("--confirm goes with --stale only"));
108 }
109 if !(req.stale || req.contradictions || req.dedupe) {
110 (req.stale, req.contradictions, req.dedupe) = (true, true, true);
111 }
112 Ok(req)
113}
114
115pub fn handover_line(place: &str) -> String {
118 format!("Judgment tasks run in the review loop: lean-ctx review attach {place}")
119}
120
121#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct Counts {
124 pub done: usize,
125 pub to_verify: usize,
126 pub gone: usize,
127 pub merged: usize,
128 pub retracted: usize,
129 pub sent_to_review: usize,
130 pub skipped: usize,
131}
132
133impl Counts {
134 pub fn line(&self) -> String {
135 format!(
136 "done {} · to_verify {} · gone {} · merged {} · retracted {} · sent to review {} · skipped {}",
137 self.done,
138 self.to_verify,
139 self.gone,
140 self.merged,
141 self.retracted,
142 self.sent_to_review,
143 self.skipped
144 )
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
150pub enum AnchorVerdict {
151 Fresh,
152 ToVerify,
153 Gone,
154}
155
156impl AnchorVerdict {
157 pub fn as_str(self) -> &'static str {
158 match self {
159 Self::Fresh => "fresh",
160 Self::ToVerify => "to_verify",
161 Self::Gone => "gone",
162 }
163 }
164}
165
166fn anchored_bytes(checkout: &mut Checkout, anchor_ref: &str) -> Result<Option<Vec<u8>>, ()> {
169 match crate::capture::refs::parse(anchor_ref) {
170 Some(Reference::File { path, .. }) => Ok(checkout.blob_bytes(&path).map(<[u8]>::to_vec)),
171 Some(Reference::Symbol { path, symbol }) => Ok(checkout.symbol_span(&path, &symbol)),
172 _ => Err(()),
173 }
174}
175
176pub fn check_anchors(anchors: &[Value], checkout: &mut Checkout) -> Option<AnchorVerdict> {
185 let mut worst = None;
186 for anchor in anchors {
187 let (Some(anchor_ref), Some(digest)) = (
188 anchor.get("ref").and_then(Value::as_str),
189 anchor.get("digest").and_then(Value::as_str),
190 ) else {
191 continue;
192 };
193 if let Some(commit) = anchor.get("commit").and_then(Value::as_str)
194 && !checkout.head_contains(commit)
195 {
196 continue;
197 }
198 let Ok(bytes) = anchored_bytes(checkout, anchor_ref) else {
199 continue;
200 };
201 let verdict = match bytes {
202 None => AnchorVerdict::Gone,
203 Some(b) if hex::encode(Sha256::digest(&b)) == digest => AnchorVerdict::Fresh,
204 Some(_) => AnchorVerdict::ToVerify,
205 };
206 worst = worst.max(Some(verdict));
207 }
208 worst
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct AnchorTask {
214 pub node_id: String,
215 pub verdict: AnchorVerdict,
216}
217
218pub fn anchor_tasks(
222 graph: &Graph,
223 checkout: &mut Checkout,
224 limit: usize,
225) -> (Vec<AnchorTask>, usize) {
226 let mut tasks = Vec::new();
227 let mut skipped = 0;
228 for (id, node) in graph.live_nodes() {
229 let Some(anchors) = node.fields.get("anchors").and_then(Value::as_array) else {
230 continue;
231 };
232 let Some(verdict) = check_anchors(anchors, checkout) else {
233 continue;
234 };
235 let current = node.fields.get("anchor_state").and_then(Value::as_str);
236 if verdict == AnchorVerdict::Fresh || current == Some(verdict.as_str()) {
240 skipped += 1;
241 continue;
242 }
243 if tasks.len() == limit {
244 break;
245 }
246 tasks.push(AnchorTask {
247 node_id: id.clone(),
248 verdict,
249 });
250 }
251 (tasks, skipped)
252}
253
254pub fn reanchored(
258 anchors: &[Value],
259 checkout: &mut Checkout,
260 verified_at: u64,
261) -> Option<Vec<Value>> {
262 let commit = checkout.head()?;
263 anchors
264 .iter()
265 .map(|anchor| {
266 let anchor_ref = anchor.get("ref").and_then(Value::as_str)?;
267 let bytes = anchored_bytes(checkout, anchor_ref).ok()??;
268 Some(json!({
269 "ref": anchor_ref,
270 "digest": hex::encode(Sha256::digest(&bytes)),
271 "commit": commit,
272 "verified_at": verified_at,
273 }))
274 })
275 .collect()
276}
277
278pub(super) fn reasons_hash(task: &str) -> String {
280 blake3::hash(format!("leanctx.cloud.maintenance.v1:{task}").as_bytes())
281 .to_hex()
282 .to_string()
283}
284
285pub const FIELD_SET_FIELDS: [&str; 2] = ["anchors", "anchor_state"];
290
291pub fn field_set(
294 place: &Place,
295 target: &str,
296 field: &str,
297 value: Value,
298 verified_at: Option<u64>,
299 stamp: Stamp,
300 signer: &Signer<'_>,
301) -> Result<Value, CloudError> {
302 fn local(e: impl std::fmt::Display) -> CloudError {
303 CloudError::Local(e.to_string())
304 }
305 let mut body = Map::new();
306 body.insert("body_nonce".into(), Value::String(sign::new_body_nonce()?));
307 body.insert("field".into(), Value::from(field));
308 body.insert("value".into(), value);
309 if let Some(at) = verified_at {
310 body.insert("verified_at".into(), Value::from(at));
311 }
312 let body = Value::Object(body);
313 let body_commit = sign::body_commit(&place.pk_id, &body).map_err(local)?;
314 let mut event = json!({
315 "schema": EVENT_SCHEMA,
316 "event_id": ids::new_event_id(stamp.wall_ms)?,
317 "place": {"kind": place.kind, "id": place.id},
318 "op": "field.set",
319 "target": target,
320 "body": body,
321 "body_commit": body_commit,
322 "hlc": {"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": signer.hlc_node},
323 "causal_base": place.causal_base,
324 "actor": {"kind": "worker"},
325 "worker_id": signer.worker_id,
326 "provenance_claim": "workspace",
327 "capture": {
328 "gate_version": GATE_VERSION,
329 "evidence": "observed",
330 "reasons_passed_hash": reasons_hash(field),
331 },
332 "screening": {
333 "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
334 "scanner_version": crate::knowledge::screening::SCANNER_VERSION,
335 },
336 });
337 sign::sign(&mut event, signer.key).map_err(local)?;
338 Ok(event)
339}
340
341pub struct Target<'a> {
343 pub replica: &'a Replica,
344 pub place: &'a Place,
345 pub signer: &'a Signer<'a>,
346}
347
348pub(crate) fn queue(target: &Target<'_>, event: &Value, stamp: Stamp) -> Result<(), CloudError> {
351 let id = event["event_id"]
352 .as_str()
353 .ok_or_else(|| CloudError::Local("built event without id".into()))?
354 .to_string();
355 let bytes = serde_json::to_vec(event).map_err(|e| CloudError::Local(e.to_string()))?;
356 target
357 .replica
358 .add_pending(&id, stamp.wall_ms, stamp.counter, None, &bytes)
359}
360
361pub fn run_stale(
367 target: &Target<'_>,
368 checkout: &mut Checkout,
369 req: &Request,
370 now_ms: u64,
371) -> Result<Counts, CloudError> {
372 run_stale_at(target, checkout, req, now_ms, Stamp::default()).map(|(counts, _)| counts)
373}
374
375pub fn run_stale_at(
379 target: &Target<'_>,
380 checkout: &mut Checkout,
381 req: &Request,
382 now_ms: u64,
383 clock: Stamp,
384) -> Result<(Counts, Stamp), CloudError> {
385 let mut graph = Graph::default();
386 graph
387 .fold(&target.replica.fold_events()?)
388 .map_err(|e| CloudError::Protocol(e.to_string()))?;
389 let mut counts = Counts::default();
390 let mut clock = clock;
391 if let Some(node_id) = &req.confirm {
392 let node = graph
393 .live_nodes()
394 .find(|(id, _)| *id == node_id)
395 .map(|(_, n)| n)
396 .ok_or_else(|| CloudError::Config(format!("{node_id}: no live claim here")))?;
397 let anchors = node
398 .fields
399 .get("anchors")
400 .and_then(Value::as_array)
401 .filter(|a| !a.is_empty())
402 .ok_or_else(|| CloudError::Config(format!("{node_id}: the claim has no anchors")))?;
403 let Some(fresh) = reanchored(anchors, checkout, now_ms) else {
404 return Err(CloudError::Config(format!(
405 "{node_id}: an anchored file or symbol is gone; it cannot be confirmed at this code"
406 )));
407 };
408 clock = hlc::send(clock, now_ms);
409 let event = field_set(
410 target.place,
411 node_id,
412 "anchors",
413 Value::Array(fresh),
414 Some(now_ms),
415 clock,
416 target.signer,
417 )?;
418 queue(target, &event, clock)?;
419 counts.done = 1;
420 if matches!(
422 node.fields.get("anchor_state").and_then(Value::as_str),
423 Some("to_verify" | "gone")
424 ) {
425 clock = hlc::send(clock, now_ms);
426 let event = field_set(
427 target.place,
428 node_id,
429 "anchor_state",
430 Value::from(AnchorVerdict::Fresh.as_str()),
431 None,
432 clock,
433 target.signer,
434 )?;
435 queue(target, &event, clock)?;
436 }
437 return Ok((counts, clock));
438 }
439 let queued: std::collections::HashSet<(String, String)> = target
441 .replica
442 .pending()?
443 .iter()
444 .filter_map(|(_, bytes)| serde_json::from_slice::<Value>(bytes).ok())
445 .filter(|e| e["op"] == "field.set" && e["body"]["field"] == "anchor_state")
446 .filter_map(|e| {
447 Some((
448 e["target"].as_str()?.to_string(),
449 e["body"]["value"].as_str()?.to_string(),
450 ))
451 })
452 .collect();
453 let (tasks, skipped) = anchor_tasks(&graph, checkout, req.limit);
454 counts.skipped = skipped;
455 for task in tasks {
456 if queued.contains(&(task.node_id.clone(), task.verdict.as_str().to_string())) {
457 counts.skipped += 1;
458 continue;
459 }
460 clock = hlc::send(clock, now_ms);
461 let event = field_set(
462 target.place,
463 &task.node_id,
464 "anchor_state",
465 Value::from(task.verdict.as_str()),
466 None,
467 clock,
468 target.signer,
469 )?;
470 queue(target, &event, clock)?;
471 counts.done += 1;
472 match task.verdict {
473 AnchorVerdict::ToVerify => counts.to_verify += 1,
474 AnchorVerdict::Gone => counts.gone += 1,
475 AnchorVerdict::Fresh => {}
476 }
477 }
478 Ok((counts, clock))
479}
480
481pub fn run_host(
488 target: &Target<'_>,
489 checkout: &mut Checkout,
490 req: &Request,
491 api: Option<(&dyn crate::sync::driver::PlaceApi, &str)>,
492 now_ms: u64,
493) -> Result<(Counts, Vec<String>), CloudError> {
494 let mut lines = Vec::new();
495 let mut counts = if req.stale {
496 run_stale(target, checkout, req, now_ms)?
497 } else {
498 Counts::default()
499 };
500 if req.contradictions || req.dedupe {
501 lines.push(handover_line(&req.vault));
502 }
503 if req.contradictions {
504 lines.push(
506 "Mark a contradiction you found: lean-ctx knowledge contradict <node> <other-node>"
507 .into(),
508 );
509 }
510 if let Some((api, place_ref)) = api
511 && !target.replica.pending()?.is_empty()
512 {
513 let push = crate::sync::driver::push_pending(api, target.replica, place_ref, &[])?;
514 counts.sent_to_review += push.held;
515 if !push.failed.is_empty() {
516 lines.push(format!(
517 "{} event(s) refused: {}",
518 push.failed.len(),
519 push.failed
520 .iter()
521 .map(|(_, why)| why.as_str())
522 .collect::<Vec<_>>()
523 .join(", ")
524 ));
525 }
526 }
527 lines.push(counts.line());
528 Ok((counts, lines))
529}
530
531#[cfg(test)]
532#[path = "maintain_tests.rs"]
533pub(super) mod tests;