Skip to main content

lean_ctx_cloud/capture/
derived.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Provenance of captured claims (Cloud v5 CHECKLIST 2.2.2, 2.6.1): a claim
3//! that names a vault node itself (`node:<id>` reference) builds on it, and
4//! its `node.add` is followed by a `derived_from` edge to that node. The
5//! edge is ordinary vault content: signed, queued with the claim (offline
6//! too) and pushed by the next sync.
7//!
8//! Only an explicit reference counts. The server counts verified
9//! cross-engine reuse from these edges, and only where the claim's own body
10//! carries the `node:` reference, so a guessed link (shared words with
11//! something delivered earlier) is no provenance and is never written.
12//!
13//! Not telemetry: there are no counters, no usage pings and no local
14//! delivery log; only the edges reach the vault, as the claim's provenance.
15
16use super::CapturedFact;
17use crate::replica::fold::Graph;
18
19/// Fill each claim's `derived_from` with the live nodes it names itself
20/// (`node:<id>` references), once each, in reference order.
21pub fn link(facts: &mut [CapturedFact], graph: &Graph) {
22    let live = |id: &str| {
23        graph
24            .nodes
25            .get(id)
26            .is_some_and(|n| !n.retracted && !n.purged)
27    };
28    for f in facts.iter_mut() {
29        let mut named: Vec<String> = Vec::new();
30        for id in f.refs.iter().filter_map(|r| r.strip_prefix("node:")) {
31            if live(id) && !named.iter().any(|n| n == id) {
32                named.push(id.to_string());
33            }
34        }
35        f.derived_from = named;
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use serde_json::json;
42
43    use super::*;
44    use crate::capture::CaptureCandidate;
45    use crate::replica::fold::Node;
46    use lean_ctx::core::knowledge::{EvidenceLevel, NodeType};
47    use lean_ctx::core::sensitivity::SensitivityLevel;
48
49    fn node(statement: &str) -> Node {
50        Node {
51            node_type: "fact".into(),
52            fields: json!({"statement": statement, "applies_to": []})
53                .as_object()
54                .unwrap()
55                .clone(),
56            ..Node::default()
57        }
58    }
59
60    fn claim(statement: &str, refs: &[&str]) -> CapturedFact {
61        CapturedFact {
62            candidate: CaptureCandidate {
63                node_type: NodeType::Fact,
64                statement: statement.into(),
65                steps: vec![],
66                commands: vec![],
67                refs: vec![],
68                evidence: EvidenceLevel::Observed,
69                sensitivity: SensitivityLevel::Public,
70            },
71            refs: refs.iter().map(ToString::to_string).collect(),
72            category: "arch".into(),
73            key: "k".into(),
74            value: statement.into(),
75            derived_from: vec![],
76            session: None,
77        }
78    }
79
80    #[test]
81    fn only_nodes_a_claim_names_itself_become_provenance() {
82        let mut g = Graph::default();
83        g.nodes.insert(
84            "n_lock".into(),
85            node("Ledger close takes the advisory lock 42 before it reads balances."),
86        );
87        g.nodes.insert(
88            "n_retry".into(),
89            node("Payment retries back off exponentially, capped at 64 seconds."),
90        );
91        let mut gone = node("Ledger balances are read without any advisory lock.");
92        gone.retracted = true;
93        g.nodes.insert("n_gone".into(), gone);
94        let mut facts = vec![
95            // Shares most words with n_lock but names nothing: no link (a
96            // guess is no provenance, v5 2.6.1).
97            claim(
98                "The nightly export waits for advisory lock 42 so the ledger close reads stable balances.",
99                &["file:src/ledger.rs"],
100            ),
101            // Names two live nodes (one twice), a retracted and an unknown
102            // one: the live ones, once each, in reference order.
103            claim(
104                "The nightly export waits for the ledger lock and retries with backoff.",
105                &[
106                    "node:n_retry",
107                    "node:n_gone",
108                    "node:n_lock",
109                    "node:n_retry",
110                    "node:n_unknown",
111                ],
112            ),
113        ];
114        link(&mut facts, &g);
115        assert!(facts[0].derived_from.is_empty());
116        assert_eq!(facts[1].derived_from, ["n_retry", "n_lock"]);
117        // Deterministic: the same claims and graph give the same links.
118        let mut again = facts.clone();
119        link(&mut again, &g);
120        assert_eq!(again, facts);
121    }
122}