Skip to main content

lean_ctx_cloud/review/
maintain.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Maintenance client, host mode (SPEC-ENGINE §3.15b, V9.4).
3//!
4//! `lean-ctx cloud maintain <ws>/<vault> [--stale] [--contradictions]
5//! [--dedupe] [--limit N]` and `… --stale --confirm <node_id>`.
6//!
7//! `sync_vault` runs the same `--stale` re-check after every capture, so
8//! anchors are re-checked automatically (v5 2.2.1); the command remains for
9//! `--confirm` and on-demand runs.
10//!
11//! Host mode runs only the engine-local deterministic task `anchor_changed`:
12//! every live claim with anchors is re-checked against the member's own
13//! checkout (`HEAD`), and a claim whose anchored bytes changed gets
14//! `field.set anchor_state = to_verify`, one whose file or symbol is gone
15//! `gone` — signed with the instance key as the place's maintenance worker,
16//! provenance `workspace`. No model, no cost, no server task: host mode
17//! leases no E42 kind. The judgment kinds (`--contradictions`, `--dedupe`)
18//! belong to the place's review loop and are only pointed to here.
19//!
20//! The task never re-anchors on its own; `--confirm <node_id>` is the
21//! person confirming the claim at the current code: one `field.set anchors`
22//! with the new digests, the `HEAD` commit and `verified_at` (C0 2.0
23//! `events/field.set.anchors.json`, RESOLUTIONS R121).
24//!
25//! Retractions carry no engine-side threshold: a retraction the place holds
26//! for review comes back `held`, stays pending and is counted "sent to
27//! review" (§3.15b, CONTRACT §3.16).
28
29use 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
41/// Role of the worker that writes maintenance events.
42pub const MAINTENANCE_ROLE: &str = "maintenance";
43/// `--limit` default and bounds.
44pub const DEFAULT_LIMIT: usize = 50;
45pub const MAX_LIMIT: usize = 200;
46
47/// What a run was asked to do.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Request {
50    /// `<ws>/<vault>` as given.
51    pub vault: String,
52    pub stale: bool,
53    pub contradictions: bool,
54    pub dedupe: bool,
55    pub limit: usize,
56    /// `--stale --confirm <node_id>`: re-anchor this claim.
57    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
66/// Parse the arguments after `cloud maintain`.
67pub 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
115/// The line `--contradictions` / `--dedupe` print in host mode: judgment
116/// tasks run in the place's review loop, never here (no E42 call).
117pub fn handover_line(place: &str) -> String {
118    format!("Judgment tasks run in the review loop: lean-ctx review attach {place}")
119}
120
121/// What a run did; printed as counts, never node texts.
122#[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/// Where a claim's anchors stand in the checkout.
149#[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
166/// The bytes an anchor `ref` names at `HEAD`; `Err` for a ref that is not
167/// a code anchor, `Ok(None)` when its file or symbol is gone.
168fn 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
176/// Recheck a claim's `anchors` (CodeAnchorV1 values) at the checkout: the
177/// worst state of any code anchor, `None` without one.
178///
179/// An anchor is judged only when `HEAD` contains the commit it was taken
180/// at (that commit or a descendant). An engine on an older commit, or on a
181/// branch that diverged, cannot tell a change from code it has not seen
182/// yet: its verdict is unknown, not outdated (dogfood 25.10.: two engines
183/// on different commits kept marking each other's claims `to_verify`).
184pub 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/// One `anchor_changed` task: the claim and the state it gets.
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct AnchorTask {
214    pub node_id: String,
215    pub verdict: AnchorVerdict,
216}
217
218/// The engine-local `anchor_changed` tasks of a folded place, in node id
219/// order, at most `limit`. Claims whose anchors still match, or that
220/// already carry the state, are counted as skipped (`no_change`).
221pub 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        // Matching bytes never clear a mark on their own: engines on older
237        // commits would flip it back and forth with engines on newer ones.
238        // Only `--confirm` (a person, at the current code) writes `fresh`.
239        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
254/// The claim's anchors re-taken at `HEAD` for `--confirm` (same refs, new
255/// digests, the `HEAD` commit, `verified_at`). `None` when a ref is gone
256/// (a gone claim is retracted, not re-anchored) or there is no `HEAD`.
257pub 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
278/// `reasons_passed_hash` of a maintenance event: the task that wrote it.
279pub(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
285/// Every field the engine writes with `field.set` (all through
286/// [`field_set`], on claims that carry anchors). Each must be mutable in C0
287/// `enums/node-types.json` for every node type with anchors, or the server
288/// refuses the event (`target_state`); a guard test checks both.
289pub const FIELD_SET_FIELDS: [&str; 2] = ["anchors", "anchor_state"];
290
291/// A signed class-W `field.set` by the maintenance worker (provenance
292/// `workspace`). `verified_at` goes with `field = anchors` only.
293pub 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
341/// Where a run writes: the place's replica, key and signer.
342pub struct Target<'a> {
343    pub replica: &'a Replica,
344    pub place: &'a Place,
345    pub signer: &'a Signer<'a>,
346}
347
348/// Queue a built class-W event as pending (maintenance, curation, and the
349/// capture lifecycle's retract, supersedes and confirm events).
350pub(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
361/// Run the host-mode deterministic part (`--stale`): fold the replica,
362/// derive the `anchor_changed` tasks against `checkout` and queue one
363/// signed `field.set anchor_state` per task as pending (the sync push
364/// sends them). With `confirm`, queue the re-anchoring of that claim
365/// instead. Never contacts the server.
366pub 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
375/// [`run_stale`] continuing the HLC `clock` of events queued before it in
376/// the same run (the automatic re-check in `sync_vault`); returns the clock
377/// after the last event it queued.
378pub 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        // A claim the re-check had marked is current again once confirmed.
421        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    // A state already queued and not yet folded is not queued twice.
440    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
481/// A host-mode run: `--stale` queues the deterministic events, the judgment
482/// kinds only print where they run (no E42 call in host mode, §3.15b), and
483/// with `api` the place's pending events are pushed (E5). Every pushed
484/// event goes out; the server alone holds large retractions, which stay
485/// pending and count as sent to review. Returns the counts and the lines
486/// to print.
487pub 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        // C0 2.0 places: a person marks a contradiction directly.
505        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;