Skip to main content

lean_ctx_cloud/
task_evidence.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Task evidence (trace per change, contract §36): when this engine's agent
3//! submits or verifies a Cloud task, the engine pins what it can prove about
4//! the work, so LeanCTX Cloud can join a landed change to its goal, the
5//! context its agent saw, and the rule that allowed it.
6//!
7//! The task receipt (`docs/contracts/task-receipt-v1.md`) of the task's
8//! sessions is built here, on this machine, and stays here. Cloud receives
9//! `leanctx.cloud.task-evidence/v1`: the receipt's sha256 digest, its
10//! `chain_broken` flag, per session a keyed `session_ref` with chain heads
11//! and counts, and the distinct policy digests of its deliveries. The digest
12//! is over the exact bytes `lean-ctx task receipt <n> --json --session …`
13//! prints, so a person recomputes it with `lean-ctx task trace <n> --json`.
14//!
15//! The sessions of a task are those the local work trace names (the session
16//! that claimed it and the one that submitted it, as the app's
17//! `LEAN_CTX_SESSION_ID`), and the session of the calling process. The
18//! brief the app started a session with is known only as its digest
19//! (`lean-ctx tasks update <n> --brief-digest sha256:…`, kept locally).
20//!
21//! The receipts switches gate it: `[cloud] receipts_upload`, the lease's
22//! `receipts.upload` right, the workspace rule "Share instance metrics" and
23//! the release switch (`crate::receipts`). Queued only while receipts are
24//! queued and the enrolled Cloud announces `change_trace`; sent in the
25//! receipts run. When any of that is off nothing is queued or sent, and
26//! Cloud shows the gap `no_receipt`. Nothing here ever fails a task call.
27
28use std::collections::BTreeSet;
29use std::path::Path;
30use std::sync::OnceLock;
31
32use ed25519_dalek::Signer as _;
33use lean_ctx_time::UtcDateTime;
34use serde::{Deserialize, Serialize};
35use serde_json::{Value, json};
36use sha2::{Digest as _, Sha256};
37
38use crate::CloudError;
39use crate::auth::Session;
40use crate::instance_key::InstanceKeys;
41use crate::outbox::{CHANNEL_TASK_EVIDENCE, Outbox, OutboxItem};
42use crate::receipts::ReceiptKey;
43use crate::state::{CloudStore, write_private};
44use crate::tasks::claims::{self, WorkTrace};
45use lean_ctx_protocol::cloud::CloudUploadKind;
46use lean_ctx_protocol::cloud::metrics_v2::{KeyId, SignatureHex};
47pub use lean_ctx_protocol::cloud::task_evidence::FEATURE_CHANGE_TRACE;
48use lean_ctx_protocol::cloud::task_evidence::{
49    MAX_EVIDENCE_SESSIONS, MAX_POLICY_DIGESTS, MAX_SESSION_GAPS, SessionEvidenceV1,
50    TASK_EVIDENCE_SCHEMA, TASK_RECEIPT_SCHEMA, TaskEvidenceRequestV1, TaskEvidenceV1,
51    evidence_route, is_chain_hash, is_sha256_digest,
52};
53
54/// Builds the `task.receipt` document text of a task over its sessions, as
55/// `lean-ctx task receipt <task> --json --session …` prints it (without the
56/// final newline); `None` when no receipt can be built now.
57pub type ReceiptSource = fn(&str, &[String]) -> Option<String>;
58
59static RECEIPT_SOURCE: OnceLock<ReceiptSource> = OnceLock::new();
60
61/// Install the receipt builder (the CLI crate owns it). Without one, no
62/// evidence is queued.
63pub fn set_receipt_source(source: ReceiptSource) {
64    let _ = RECEIPT_SOURCE.set(source);
65}
66
67/// The receipt text of `task` over `sessions`, from the installed builder.
68pub fn receipt_text(task: &str, sessions: &[String]) -> Option<String> {
69    if sessions.is_empty() {
70        return None;
71    }
72    RECEIPT_SOURCE.get().and_then(|build| build(task, sessions))
73}
74
75/// `sha256:` and the hex digest of the receipt as printed: its text and the
76/// final newline (`lean-ctx task receipt … --json | sha256sum`).
77#[must_use]
78pub fn receipt_digest(text: &str) -> String {
79    let mut hash = Sha256::new();
80    hash.update(text.as_bytes());
81    hash.update(b"\n");
82    format!("sha256:{}", hex::encode(hash.finalize()))
83}
84
85/// The session ids of a task in order, once: the claiming session, the
86/// submitting session, then `current` (the calling process's), each as the
87/// app names it. At most [`MAX_EVIDENCE_SESSIONS`].
88#[must_use]
89pub fn sessions_of(trace: Option<&WorkTrace>, current: Option<String>) -> Vec<String> {
90    let named = trace
91        .into_iter()
92        .flat_map(|t| [&t.claimed_session, &t.submitted_by])
93        .flatten()
94        .filter_map(|identity| identity.session.clone());
95    let mut out: Vec<String> = Vec::new();
96    for id in named.chain(current) {
97        let Some(id) = crate::policy_sessions::session_id(&id) else {
98            continue;
99        };
100        if !out.contains(&id) && out.len() < MAX_EVIDENCE_SESSIONS {
101            out.push(id);
102        }
103    }
104    out
105}
106
107const BRIEFS_FILE: &str = "task-briefs.json";
108/// At most this many brief digests are kept (the newest).
109const MAX_BRIEFS: usize = 500;
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112struct Brief {
113    vault_id: String,
114    number: u64,
115    digest: String,
116}
117
118#[derive(Debug, Default, Serialize, Deserialize)]
119struct Briefs {
120    #[serde(default)]
121    briefs: Vec<Brief>,
122}
123
124/// A damaged brief file is moved here before a new one is written, so no
125/// recorded digest is lost without a trace.
126const BRIEFS_CORRUPT_FILE: &str = "task-briefs.json.corrupt";
127
128/// The recorded briefs: empty when there is no file, `Err` when the file
129/// exists but cannot be read or parsed.
130fn read_briefs(data_dir: &Path) -> Result<Briefs, CloudError> {
131    match std::fs::read(data_dir.join(BRIEFS_FILE)) {
132        Ok(bytes) => serde_json::from_slice(&bytes)
133            .map_err(|e| CloudError::Local(format!("{BRIEFS_FILE}: {e}"))),
134        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Briefs::default()),
135        Err(e) => Err(CloudError::Local(format!("{BRIEFS_FILE}: {e}"))),
136    }
137}
138
139/// The recorded briefs for reading: a damaged file names none.
140fn load_briefs(data_dir: &Path) -> Briefs {
141    read_briefs(data_dir).unwrap_or_default()
142}
143
144/// Record the digest of the brief the app started task `number`'s session
145/// with. Local only: it leaves with the task's evidence.
146pub fn record_brief(
147    data_dir: &Path,
148    vault_id: &str,
149    number: u64,
150    digest: &str,
151) -> Result<(), CloudError> {
152    if !is_sha256_digest(digest) {
153        return Err(CloudError::Config(
154            "--brief-digest is sha256: and 64 lowercase hex characters".into(),
155        ));
156    }
157    let mut file = if let Ok(file) = read_briefs(data_dir) {
158        file
159    } else {
160        // A damaged file is kept as `task-briefs.json.corrupt` (replacing an
161        // older backup), never overwritten in place.
162        std::fs::rename(
163            data_dir.join(BRIEFS_FILE),
164            data_dir.join(BRIEFS_CORRUPT_FILE),
165        )
166        .map_err(|e| {
167            CloudError::Local(format!(
168                "{BRIEFS_FILE} is damaged and could not be kept as {BRIEFS_CORRUPT_FILE}: {e}"
169            ))
170        })?;
171        Briefs::default()
172    };
173    file.briefs
174        .retain(|b| !(b.vault_id == vault_id && b.number == number));
175    file.briefs.push(Brief {
176        vault_id: vault_id.to_owned(),
177        number,
178        digest: digest.to_owned(),
179    });
180    let excess = file.briefs.len().saturating_sub(MAX_BRIEFS);
181    file.briefs.drain(..excess);
182    let bytes = serde_json::to_vec_pretty(&file).map_err(|e| CloudError::Local(e.to_string()))?;
183    write_private(data_dir, BRIEFS_FILE, &bytes)
184}
185
186/// [`record_brief`] for task `number` of the vault of the checkout at `root`
187/// (`lean-ctx tasks update <n> --brief-digest sha256:…`).
188pub fn record_brief_at(root: &Path, number: u64, digest: &str) -> Result<(), CloudError> {
189    let store = CloudStore::open()?;
190    let vault = crate::resolution::vault_for_root(&store, root)?
191        .ok_or_else(|| CloudError::Config("this checkout is not linked to a Cloud vault".into()))?;
192    record_brief(store.data_dir(), &vault.vault_id, number, digest)
193}
194
195/// The brief digest recorded for task `number` of `vault_id`.
196#[must_use]
197pub fn brief_of(data_dir: &Path, vault_id: &str, number: u64) -> Option<String> {
198    load_briefs(data_dir)
199        .briefs
200        .into_iter()
201        .find(|b| b.vault_id == vault_id && b.number == number)
202        .map(|b| b.digest)
203}
204
205/// What this machine knows of task `number` of the checkout at `root`, for
206/// `lean-ctx task trace` (local only, nothing is sent).
207#[derive(Debug, Default, Clone, PartialEq, Eq)]
208pub struct LocalTrace {
209    /// The Cloud vault of the checkout, when Cloud resolved it here.
210    pub vault: Option<String>,
211    /// The task's sessions, as [`sessions_of`] names them.
212    pub sessions: Vec<String>,
213    pub brief_digest: Option<String>,
214}
215
216/// [`LocalTrace`] of task `number` in the checkout at `root`.
217#[must_use]
218pub fn local_trace(root: &Path, number: u64) -> LocalTrace {
219    let current = crate::policy_sessions::current_session();
220    let Ok(store) = CloudStore::open() else {
221        return LocalTrace {
222            sessions: sessions_of(None, current),
223            ..LocalTrace::default()
224        };
225    };
226    let data_dir = store.data_dir();
227    let vault = crate::resolution::vault_for_root(&store, root)
228        .ok()
229        .flatten()
230        .map(|record| record.vault_id);
231    let trace = vault
232        .as_deref()
233        .and_then(|vault| claims::trace(data_dir, vault, number));
234    LocalTrace {
235        sessions: sessions_of(trace.as_ref(), current),
236        brief_digest: vault
237            .as_deref()
238            .and_then(|vault| brief_of(data_dir, vault, number)),
239        vault,
240    }
241}
242
243/// The keyed ref of an app session: `hs_` and the first 32 hex characters
244/// of HMAC-SHA256(receipts key, `session` ‖ id), the envelope ref of the
245/// same session (`crate::session_ref`).
246fn session_ref(key: &ReceiptKey, id: &str) -> String {
247    format!(
248        "{}{}",
249        crate::session_ref::EVENT_REF_PREFIX,
250        &key.mac_hex("session", id)[..32]
251    )
252}
253
254fn count(value: &Value) -> u64 {
255    value.as_u64().unwrap_or(0)
256}
257
258/// The number of distinct agents of a receipt session: by `agent_id`, or by
259/// `client` for an agent without one.
260fn distinct_agents(agents: &[Value]) -> u64 {
261    agents
262        .iter()
263        .map(|agent| match agent["agent_id"].as_str() {
264            Some(id) => (0u8, id.to_owned()),
265            None => (1, agent["client"].as_str().unwrap_or_default().to_owned()),
266        })
267        .collect::<BTreeSet<_>>()
268        .len() as u64
269}
270
271/// The evidence of a task receipt document `text`, or `None` when it is no
272/// `task.receipt` (the evidence then is not sent). Session ids leave only as
273/// keyed refs; chain heads, counts, gaps and policy digests are copied when
274/// they have their closed shape. A session without a `session_id` makes the
275/// whole document no receipt: nothing is sent rather than a partial trace.
276pub(crate) fn evidence_from_receipt(
277    key: &ReceiptKey,
278    vault: &str,
279    task_id: &str,
280    brief_digest: Option<&str>,
281    text: &str,
282) -> Option<TaskEvidenceV1> {
283    let doc: Value = serde_json::from_str(text).ok()?;
284    if doc["kind"] != "task.receipt" || doc["receipt_schema"] != TASK_RECEIPT_SCHEMA {
285        return None;
286    }
287    let mut policies: BTreeSet<String> = BTreeSet::new();
288    let mut sessions = Vec::new();
289    for session in doc["sessions"]
290        .as_array()?
291        .iter()
292        .take(MAX_EVIDENCE_SESSIONS)
293    {
294        let id = session["session_id"].as_str()?;
295        let (mut deliveries, mut withheld) = (0u64, 0u64);
296        for delivery in session["mcp_tasks"]
297            .as_array()
298            .into_iter()
299            .flatten()
300            .flat_map(|t| t["deliveries"].as_array().into_iter().flatten())
301        {
302            deliveries += 1;
303            let summary = &delivery["summary"];
304            withheld += count(&summary["withheld"]);
305            if let Some(digest) = summary["policy_digest"]
306                .as_str()
307                .filter(|d| is_sha256_digest(d))
308            {
309                policies.insert(digest.to_owned());
310            }
311        }
312        let head = |chain: &str| {
313            session[chain]["last_hash"]
314                .as_str()
315                .filter(|h| is_chain_hash(h))
316                .map(str::to_owned)
317        };
318        sessions.push(SessionEvidenceV1 {
319            session_ref: session_ref(key, id),
320            ledger_last_hash: head("ledger_evidence"),
321            audit_last_hash: head("audit_evidence"),
322            deliveries,
323            withheld,
324            agents: session["agents"].as_array().map(|a| distinct_agents(a)),
325            gaps: session["gaps"]
326                .as_array()
327                .into_iter()
328                .flatten()
329                .filter_map(Value::as_str)
330                .take(MAX_SESSION_GAPS)
331                .map(str::to_owned)
332                .collect(),
333        });
334    }
335    let evidence = TaskEvidenceV1 {
336        schema: TASK_EVIDENCE_SCHEMA.into(),
337        vault: vault.to_owned(),
338        task_id: task_id.to_owned(),
339        brief_digest: brief_digest.map(str::to_owned),
340        receipt_digest: receipt_digest(text),
341        chain_broken: doc["chain_broken"].as_bool()?,
342        sessions,
343        // Sorted and once; a receipt with more names the first ones.
344        policy_digests: policies.into_iter().take(MAX_POLICY_DIGESTS).collect(),
345    };
346    evidence.validate().ok()?;
347    Some(evidence)
348}
349
350/// Note that task `number` of `vault_id` was submitted or verified by this
351/// engine's agent: queue its evidence when receipts are queued and the
352/// enrolled Cloud takes it. Silent and best effort.
353pub fn note_task_closed(store: &CloudStore, vault_id: &str, number: u64, now: UtcDateTime) {
354    if !crate::receipts::queueing(store)
355        || !crate::session_ref::announced(store, FEATURE_CHANGE_TRACE)
356    {
357        return;
358    }
359    queue_evidence(
360        store,
361        vault_id,
362        number,
363        crate::policy_sessions::current_session(),
364        now,
365    );
366}
367
368/// Queue the evidence of task `number` of `vault_id` over its traced
369/// sessions and `current`, replacing a queued one of the same task (the
370/// gates of [`note_task_closed`] already allowed it).
371fn queue_evidence(
372    store: &CloudStore,
373    vault_id: &str,
374    number: u64,
375    current: Option<String>,
376    now: UtcDateTime,
377) {
378    let trace = claims::trace(store.data_dir(), vault_id, number);
379    let sessions = sessions_of(trace.as_ref(), current);
380    let task_id = number.to_string();
381    let Some(text) = receipt_text(&task_id, &sessions) else {
382        return;
383    };
384    let Some(key) = ReceiptKey::load_or_create(store.data_dir()) else {
385        return;
386    };
387    let brief = brief_of(store.data_dir(), vault_id, number);
388    let Some(evidence) = evidence_from_receipt(&key, vault_id, &task_id, brief.as_deref(), &text)
389    else {
390        return;
391    };
392    let Ok(evidence) = serde_json::to_value(&evidence) else {
393        return;
394    };
395    let outbox = Outbox::at(store.data_dir());
396    // A newer close of the same task replaces the queued one.
397    for item in outbox.list(CHANNEL_TASK_EVIDENCE) {
398        if item.payload["vault"] == vault_id && item.payload["number"] == number {
399            let _ = outbox.remove(&item);
400        }
401    }
402    let payload = json!({ "vault": vault_id, "number": number, "evidence": evidence });
403    let _ = outbox.enqueue(CHANNEL_TASK_EVIDENCE, payload, now);
404}
405
406/// Drop every queued evidence (the receipts switches went off).
407pub(crate) fn clear(outbox: &Outbox) {
408    for item in outbox.list(CHANNEL_TASK_EVIDENCE) {
409        let _ = outbox.remove(&item);
410    }
411}
412
413/// The request of a queued item, signed with the instance key.
414fn sign(
415    keys: &InstanceKeys,
416    evidence: TaskEvidenceV1,
417) -> Result<TaskEvidenceRequestV1, CloudError> {
418    let signer = keys.signing_key();
419    let key_id = KeyId::new(&crate::workers::key_id(signer))
420        .ok_or_else(|| CloudError::Local("instance key id".into()))?;
421    let input = evidence
422        .signing_input(&key_id)
423        .map_err(|e| CloudError::Local(e.to_string()))?;
424    let signature = SignatureHex::new(&hex::encode(signer.sign(&input).to_bytes()))
425        .ok_or_else(|| CloudError::Local("signature".into()))?;
426    Ok(evidence.signed(key_id, signature))
427}
428
429/// The evidence and route of a queued item, or `None` when it cannot be
430/// sent (damaged, or of another shape). The route is built from the evidence
431/// that is signed, never from the outbox's own fields: an item whose
432/// `vault` or `number` names another task than its evidence is refused, so
433/// signed evidence of one task never reaches the route of another.
434fn wire(item: &OutboxItem) -> Option<(TaskEvidenceV1, String)> {
435    let evidence: TaskEvidenceV1 = serde_json::from_value(item.payload["evidence"].clone()).ok()?;
436    evidence.validate().ok()?;
437    let number: u64 = evidence.task_id.parse().ok()?;
438    if number.to_string() != evidence.task_id
439        || item.payload["number"].as_u64() != Some(number)
440        || item.payload["vault"].as_str() != Some(evidence.vault.as_str())
441    {
442        return None;
443    }
444    let route = evidence_route(&evidence.vault, number);
445    Some((evidence, route))
446}
447
448fn queued_at(item: &OutboxItem) -> Option<UtcDateTime> {
449    UtcDateTime::parse_from_rfc3339(&item.created_at).ok()
450}
451
452/// What one send pass did.
453#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
454pub struct EvidenceRun {
455    pub sent: u64,
456    pub dropped: u64,
457}
458
459/// Send the queued evidence (from the receipts run, after every receipts
460/// gate allowed it). An item from before the sharing period `since`, of a
461/// vault in `vaults_off`, or queued while the Cloud no longer announces
462/// `change_trace` is dropped.
463pub(crate) fn send(
464    session: &Session,
465    vaults_off: &BTreeSet<String>,
466    since: Option<UtcDateTime>,
467    now: UtcDateTime,
468) -> Result<EvidenceRun, CloudError> {
469    let store = &session.store;
470    let outbox = Outbox::at(store.data_dir());
471    let announced = crate::session_ref::announced(store, FEATURE_CHANGE_TRACE);
472    let mut run = EvidenceRun::default();
473    let mut ready = Vec::new();
474    for item in outbox
475        .list(CHANNEL_TASK_EVIDENCE)
476        .into_iter()
477        .filter(|item| item.due(now))
478    {
479        let allowed = |(evidence, _): &(TaskEvidenceV1, String)| {
480            announced
481                && !vaults_off.contains(&evidence.vault)
482                && since.is_none_or(|since| queued_at(&item).is_some_and(|at| at >= since))
483        };
484        if let Some(wire) = wire(&item).filter(allowed) {
485            ready.push((wire, item));
486        } else {
487            outbox.remove(&item)?;
488            run.dropped += 1;
489        }
490    }
491    if ready.is_empty() {
492        return Ok(run);
493    }
494    let keys = InstanceKeys::load(store)?;
495    for ((evidence, route), item) in ready {
496        let request = sign(&keys, evidence)?;
497        let bytes = serde_json::to_vec(&request).map_err(|e| CloudError::Local(e.to_string()))?;
498        let body: Value =
499            serde_json::from_slice(&bytes).map_err(|e| CloudError::Local(e.to_string()))?;
500        // The same evidence always carries the same key: a retry is idempotent.
501        let key = hex::encode(&Sha256::digest(&bytes)[..16]);
502        match session.with_client(|client| client.post_idempotent(&route, &body, &key)) {
503            Ok(_) => {
504                outbox.remove(&item)?;
505                run.sent += 1;
506            }
507            Err(CloudError::UploadDisabled(
508                CloudUploadKind::Receipts | CloudUploadKind::Unknown,
509            )) => {
510                clear(&outbox);
511                return Ok(run);
512            }
513            Err(error) if error.is_transient() => {
514                let retry_after = error.retry_after_at(now);
515                let mut item = item;
516                outbox.retry_later(&mut item, &error.to_string(), retry_after, now)?;
517                return Err(error);
518            }
519            Err(error) => {
520                let mut item = item;
521                outbox.fail(&mut item, &error.to_string())?;
522            }
523        }
524    }
525    Ok(run)
526}
527
528#[cfg(test)]
529#[path = "task_evidence_tests.rs"]
530mod tests;