lean-ctx-cloud 3.12.10

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// SPDX-License-Identifier: Apache-2.0
//! Task evidence (trace per change, contract §36): when this engine's agent
//! submits or verifies a Cloud task, the engine pins what it can prove about
//! the work, so LeanCTX Cloud can join a landed change to its goal, the
//! context its agent saw, and the rule that allowed it.
//!
//! The task receipt (`docs/contracts/task-receipt-v1.md`) of the task's
//! sessions is built here, on this machine, and stays here. Cloud receives
//! `leanctx.cloud.task-evidence/v1`: the receipt's sha256 digest, its
//! `chain_broken` flag, per session a keyed `session_ref` with chain heads
//! and counts, and the distinct policy digests of its deliveries. The digest
//! is over the exact bytes `lean-ctx task receipt <n> --json --session …`
//! prints, so a person recomputes it with `lean-ctx task trace <n> --json`.
//!
//! The sessions of a task are those the local work trace names (the session
//! that claimed it and the one that submitted it, as the app's
//! `LEAN_CTX_SESSION_ID`), and the session of the calling process. The
//! brief the app started a session with is known only as its digest
//! (`lean-ctx tasks update <n> --brief-digest sha256:…`, kept locally).
//!
//! The receipts switches gate it: `[cloud] receipts_upload`, the lease's
//! `receipts.upload` right, the workspace rule "Share instance metrics" and
//! the release switch (`crate::receipts`). Queued only while receipts are
//! queued and the enrolled Cloud announces `change_trace`; sent in the
//! receipts run. When any of that is off nothing is queued or sent, and
//! Cloud shows the gap `no_receipt`. Nothing here ever fails a task call.

use std::collections::BTreeSet;
use std::path::Path;
use std::sync::OnceLock;

use ed25519_dalek::Signer as _;
use lean_ctx_time::UtcDateTime;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest as _, Sha256};

use crate::CloudError;
use crate::auth::Session;
use crate::instance_key::InstanceKeys;
use crate::outbox::{CHANNEL_TASK_EVIDENCE, Outbox, OutboxItem};
use crate::receipts::ReceiptKey;
use crate::state::{CloudStore, write_private};
use crate::tasks::claims::{self, WorkTrace};
use lean_ctx_protocol::cloud::CloudUploadKind;
use lean_ctx_protocol::cloud::metrics_v2::{KeyId, SignatureHex};
pub use lean_ctx_protocol::cloud::task_evidence::FEATURE_CHANGE_TRACE;
use lean_ctx_protocol::cloud::task_evidence::{
    MAX_EVIDENCE_SESSIONS, MAX_POLICY_DIGESTS, MAX_SESSION_GAPS, SessionEvidenceV1,
    TASK_EVIDENCE_SCHEMA, TASK_RECEIPT_SCHEMA, TaskEvidenceRequestV1, TaskEvidenceV1,
    evidence_route, is_chain_hash, is_sha256_digest,
};

/// Builds the `task.receipt` document text of a task over its sessions, as
/// `lean-ctx task receipt <task> --json --session …` prints it (without the
/// final newline); `None` when no receipt can be built now.
pub type ReceiptSource = fn(&str, &[String]) -> Option<String>;

static RECEIPT_SOURCE: OnceLock<ReceiptSource> = OnceLock::new();

/// Install the receipt builder (the CLI crate owns it). Without one, no
/// evidence is queued.
pub fn set_receipt_source(source: ReceiptSource) {
    let _ = RECEIPT_SOURCE.set(source);
}

/// The receipt text of `task` over `sessions`, from the installed builder.
pub fn receipt_text(task: &str, sessions: &[String]) -> Option<String> {
    if sessions.is_empty() {
        return None;
    }
    RECEIPT_SOURCE.get().and_then(|build| build(task, sessions))
}

/// `sha256:` and the hex digest of the receipt as printed: its text and the
/// final newline (`lean-ctx task receipt … --json | sha256sum`).
#[must_use]
pub fn receipt_digest(text: &str) -> String {
    let mut hash = Sha256::new();
    hash.update(text.as_bytes());
    hash.update(b"\n");
    format!("sha256:{}", hex::encode(hash.finalize()))
}

/// The session ids of a task in order, once: the claiming session, the
/// submitting session, then `current` (the calling process's), each as the
/// app names it. At most [`MAX_EVIDENCE_SESSIONS`].
#[must_use]
pub fn sessions_of(trace: Option<&WorkTrace>, current: Option<String>) -> Vec<String> {
    let named = trace
        .into_iter()
        .flat_map(|t| [&t.claimed_session, &t.submitted_by])
        .flatten()
        .filter_map(|identity| identity.session.clone());
    let mut out: Vec<String> = Vec::new();
    for id in named.chain(current) {
        let Some(id) = crate::policy_sessions::session_id(&id) else {
            continue;
        };
        if !out.contains(&id) && out.len() < MAX_EVIDENCE_SESSIONS {
            out.push(id);
        }
    }
    out
}

const BRIEFS_FILE: &str = "task-briefs.json";
/// At most this many brief digests are kept (the newest).
const MAX_BRIEFS: usize = 500;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Brief {
    vault_id: String,
    number: u64,
    digest: String,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct Briefs {
    #[serde(default)]
    briefs: Vec<Brief>,
}

/// A damaged brief file is moved here before a new one is written, so no
/// recorded digest is lost without a trace.
const BRIEFS_CORRUPT_FILE: &str = "task-briefs.json.corrupt";

/// The recorded briefs: empty when there is no file, `Err` when the file
/// exists but cannot be read or parsed.
fn read_briefs(data_dir: &Path) -> Result<Briefs, CloudError> {
    match std::fs::read(data_dir.join(BRIEFS_FILE)) {
        Ok(bytes) => serde_json::from_slice(&bytes)
            .map_err(|e| CloudError::Local(format!("{BRIEFS_FILE}: {e}"))),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Briefs::default()),
        Err(e) => Err(CloudError::Local(format!("{BRIEFS_FILE}: {e}"))),
    }
}

/// The recorded briefs for reading: a damaged file names none.
fn load_briefs(data_dir: &Path) -> Briefs {
    read_briefs(data_dir).unwrap_or_default()
}

/// Record the digest of the brief the app started task `number`'s session
/// with. Local only: it leaves with the task's evidence.
pub fn record_brief(
    data_dir: &Path,
    vault_id: &str,
    number: u64,
    digest: &str,
) -> Result<(), CloudError> {
    if !is_sha256_digest(digest) {
        return Err(CloudError::Config(
            "--brief-digest is sha256: and 64 lowercase hex characters".into(),
        ));
    }
    let mut file = if let Ok(file) = read_briefs(data_dir) {
        file
    } else {
        // A damaged file is kept as `task-briefs.json.corrupt` (replacing an
        // older backup), never overwritten in place.
        std::fs::rename(
            data_dir.join(BRIEFS_FILE),
            data_dir.join(BRIEFS_CORRUPT_FILE),
        )
        .map_err(|e| {
            CloudError::Local(format!(
                "{BRIEFS_FILE} is damaged and could not be kept as {BRIEFS_CORRUPT_FILE}: {e}"
            ))
        })?;
        Briefs::default()
    };
    file.briefs
        .retain(|b| !(b.vault_id == vault_id && b.number == number));
    file.briefs.push(Brief {
        vault_id: vault_id.to_owned(),
        number,
        digest: digest.to_owned(),
    });
    let excess = file.briefs.len().saturating_sub(MAX_BRIEFS);
    file.briefs.drain(..excess);
    let bytes = serde_json::to_vec_pretty(&file).map_err(|e| CloudError::Local(e.to_string()))?;
    write_private(data_dir, BRIEFS_FILE, &bytes)
}

/// [`record_brief`] for task `number` of the vault of the checkout at `root`
/// (`lean-ctx tasks update <n> --brief-digest sha256:…`).
pub fn record_brief_at(root: &Path, number: u64, digest: &str) -> Result<(), CloudError> {
    let store = CloudStore::open()?;
    let vault = crate::resolution::vault_for_root(&store, root)?
        .ok_or_else(|| CloudError::Config("this checkout is not linked to a Cloud vault".into()))?;
    record_brief(store.data_dir(), &vault.vault_id, number, digest)
}

/// The brief digest recorded for task `number` of `vault_id`.
#[must_use]
pub fn brief_of(data_dir: &Path, vault_id: &str, number: u64) -> Option<String> {
    load_briefs(data_dir)
        .briefs
        .into_iter()
        .find(|b| b.vault_id == vault_id && b.number == number)
        .map(|b| b.digest)
}

/// What this machine knows of task `number` of the checkout at `root`, for
/// `lean-ctx task trace` (local only, nothing is sent).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct LocalTrace {
    /// The Cloud vault of the checkout, when Cloud resolved it here.
    pub vault: Option<String>,
    /// The task's sessions, as [`sessions_of`] names them.
    pub sessions: Vec<String>,
    pub brief_digest: Option<String>,
}

/// [`LocalTrace`] of task `number` in the checkout at `root`.
#[must_use]
pub fn local_trace(root: &Path, number: u64) -> LocalTrace {
    let current = crate::policy_sessions::current_session();
    let Ok(store) = CloudStore::open() else {
        return LocalTrace {
            sessions: sessions_of(None, current),
            ..LocalTrace::default()
        };
    };
    let data_dir = store.data_dir();
    let vault = crate::resolution::vault_for_root(&store, root)
        .ok()
        .flatten()
        .map(|record| record.vault_id);
    let trace = vault
        .as_deref()
        .and_then(|vault| claims::trace(data_dir, vault, number));
    LocalTrace {
        sessions: sessions_of(trace.as_ref(), current),
        brief_digest: vault
            .as_deref()
            .and_then(|vault| brief_of(data_dir, vault, number)),
        vault,
    }
}

/// The keyed ref of an app session: `hs_` and the first 32 hex characters
/// of HMAC-SHA256(receipts key, `session` ‖ id), the envelope ref of the
/// same session (`crate::session_ref`).
fn session_ref(key: &ReceiptKey, id: &str) -> String {
    format!(
        "{}{}",
        crate::session_ref::EVENT_REF_PREFIX,
        &key.mac_hex("session", id)[..32]
    )
}

fn count(value: &Value) -> u64 {
    value.as_u64().unwrap_or(0)
}

/// The number of distinct agents of a receipt session: by `agent_id`, or by
/// `client` for an agent without one.
fn distinct_agents(agents: &[Value]) -> u64 {
    agents
        .iter()
        .map(|agent| match agent["agent_id"].as_str() {
            Some(id) => (0u8, id.to_owned()),
            None => (1, agent["client"].as_str().unwrap_or_default().to_owned()),
        })
        .collect::<BTreeSet<_>>()
        .len() as u64
}

/// The evidence of a task receipt document `text`, or `None` when it is no
/// `task.receipt` (the evidence then is not sent). Session ids leave only as
/// keyed refs; chain heads, counts, gaps and policy digests are copied when
/// they have their closed shape. A session without a `session_id` makes the
/// whole document no receipt: nothing is sent rather than a partial trace.
pub(crate) fn evidence_from_receipt(
    key: &ReceiptKey,
    vault: &str,
    task_id: &str,
    brief_digest: Option<&str>,
    text: &str,
) -> Option<TaskEvidenceV1> {
    let doc: Value = serde_json::from_str(text).ok()?;
    if doc["kind"] != "task.receipt" || doc["receipt_schema"] != TASK_RECEIPT_SCHEMA {
        return None;
    }
    let mut policies: BTreeSet<String> = BTreeSet::new();
    let mut sessions = Vec::new();
    for session in doc["sessions"]
        .as_array()?
        .iter()
        .take(MAX_EVIDENCE_SESSIONS)
    {
        let id = session["session_id"].as_str()?;
        let (mut deliveries, mut withheld) = (0u64, 0u64);
        for delivery in session["mcp_tasks"]
            .as_array()
            .into_iter()
            .flatten()
            .flat_map(|t| t["deliveries"].as_array().into_iter().flatten())
        {
            deliveries += 1;
            let summary = &delivery["summary"];
            withheld += count(&summary["withheld"]);
            if let Some(digest) = summary["policy_digest"]
                .as_str()
                .filter(|d| is_sha256_digest(d))
            {
                policies.insert(digest.to_owned());
            }
        }
        let head = |chain: &str| {
            session[chain]["last_hash"]
                .as_str()
                .filter(|h| is_chain_hash(h))
                .map(str::to_owned)
        };
        sessions.push(SessionEvidenceV1 {
            session_ref: session_ref(key, id),
            ledger_last_hash: head("ledger_evidence"),
            audit_last_hash: head("audit_evidence"),
            deliveries,
            withheld,
            agents: session["agents"].as_array().map(|a| distinct_agents(a)),
            gaps: session["gaps"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .take(MAX_SESSION_GAPS)
                .map(str::to_owned)
                .collect(),
        });
    }
    let evidence = TaskEvidenceV1 {
        schema: TASK_EVIDENCE_SCHEMA.into(),
        vault: vault.to_owned(),
        task_id: task_id.to_owned(),
        brief_digest: brief_digest.map(str::to_owned),
        receipt_digest: receipt_digest(text),
        chain_broken: doc["chain_broken"].as_bool()?,
        sessions,
        // Sorted and once; a receipt with more names the first ones.
        policy_digests: policies.into_iter().take(MAX_POLICY_DIGESTS).collect(),
    };
    evidence.validate().ok()?;
    Some(evidence)
}

/// Note that task `number` of `vault_id` was submitted or verified by this
/// engine's agent: queue its evidence when receipts are queued and the
/// enrolled Cloud takes it. Silent and best effort.
pub fn note_task_closed(store: &CloudStore, vault_id: &str, number: u64, now: UtcDateTime) {
    if !crate::receipts::queueing(store)
        || !crate::session_ref::announced(store, FEATURE_CHANGE_TRACE)
    {
        return;
    }
    queue_evidence(
        store,
        vault_id,
        number,
        crate::policy_sessions::current_session(),
        now,
    );
}

/// Queue the evidence of task `number` of `vault_id` over its traced
/// sessions and `current`, replacing a queued one of the same task (the
/// gates of [`note_task_closed`] already allowed it).
fn queue_evidence(
    store: &CloudStore,
    vault_id: &str,
    number: u64,
    current: Option<String>,
    now: UtcDateTime,
) {
    let trace = claims::trace(store.data_dir(), vault_id, number);
    let sessions = sessions_of(trace.as_ref(), current);
    let task_id = number.to_string();
    let Some(text) = receipt_text(&task_id, &sessions) else {
        return;
    };
    let Some(key) = ReceiptKey::load_or_create(store.data_dir()) else {
        return;
    };
    let brief = brief_of(store.data_dir(), vault_id, number);
    let Some(evidence) = evidence_from_receipt(&key, vault_id, &task_id, brief.as_deref(), &text)
    else {
        return;
    };
    let Ok(evidence) = serde_json::to_value(&evidence) else {
        return;
    };
    let outbox = Outbox::at(store.data_dir());
    // A newer close of the same task replaces the queued one.
    for item in outbox.list(CHANNEL_TASK_EVIDENCE) {
        if item.payload["vault"] == vault_id && item.payload["number"] == number {
            let _ = outbox.remove(&item);
        }
    }
    let payload = json!({ "vault": vault_id, "number": number, "evidence": evidence });
    let _ = outbox.enqueue(CHANNEL_TASK_EVIDENCE, payload, now);
}

/// Drop every queued evidence (the receipts switches went off).
pub(crate) fn clear(outbox: &Outbox) {
    for item in outbox.list(CHANNEL_TASK_EVIDENCE) {
        let _ = outbox.remove(&item);
    }
}

/// The request of a queued item, signed with the instance key.
fn sign(
    keys: &InstanceKeys,
    evidence: TaskEvidenceV1,
) -> Result<TaskEvidenceRequestV1, CloudError> {
    let signer = keys.signing_key();
    let key_id = KeyId::new(&crate::workers::key_id(signer))
        .ok_or_else(|| CloudError::Local("instance key id".into()))?;
    let input = evidence
        .signing_input(&key_id)
        .map_err(|e| CloudError::Local(e.to_string()))?;
    let signature = SignatureHex::new(&hex::encode(signer.sign(&input).to_bytes()))
        .ok_or_else(|| CloudError::Local("signature".into()))?;
    Ok(evidence.signed(key_id, signature))
}

/// The evidence and route of a queued item, or `None` when it cannot be
/// sent (damaged, or of another shape). The route is built from the evidence
/// that is signed, never from the outbox's own fields: an item whose
/// `vault` or `number` names another task than its evidence is refused, so
/// signed evidence of one task never reaches the route of another.
fn wire(item: &OutboxItem) -> Option<(TaskEvidenceV1, String)> {
    let evidence: TaskEvidenceV1 = serde_json::from_value(item.payload["evidence"].clone()).ok()?;
    evidence.validate().ok()?;
    let number: u64 = evidence.task_id.parse().ok()?;
    if number.to_string() != evidence.task_id
        || item.payload["number"].as_u64() != Some(number)
        || item.payload["vault"].as_str() != Some(evidence.vault.as_str())
    {
        return None;
    }
    let route = evidence_route(&evidence.vault, number);
    Some((evidence, route))
}

fn queued_at(item: &OutboxItem) -> Option<UtcDateTime> {
    UtcDateTime::parse_from_rfc3339(&item.created_at).ok()
}

/// What one send pass did.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct EvidenceRun {
    pub sent: u64,
    pub dropped: u64,
}

/// Send the queued evidence (from the receipts run, after every receipts
/// gate allowed it). An item from before the sharing period `since`, of a
/// vault in `vaults_off`, or queued while the Cloud no longer announces
/// `change_trace` is dropped.
pub(crate) fn send(
    session: &Session,
    vaults_off: &BTreeSet<String>,
    since: Option<UtcDateTime>,
    now: UtcDateTime,
) -> Result<EvidenceRun, CloudError> {
    let store = &session.store;
    let outbox = Outbox::at(store.data_dir());
    let announced = crate::session_ref::announced(store, FEATURE_CHANGE_TRACE);
    let mut run = EvidenceRun::default();
    let mut ready = Vec::new();
    for item in outbox
        .list(CHANNEL_TASK_EVIDENCE)
        .into_iter()
        .filter(|item| item.due(now))
    {
        let allowed = |(evidence, _): &(TaskEvidenceV1, String)| {
            announced
                && !vaults_off.contains(&evidence.vault)
                && since.is_none_or(|since| queued_at(&item).is_some_and(|at| at >= since))
        };
        if let Some(wire) = wire(&item).filter(allowed) {
            ready.push((wire, item));
        } else {
            outbox.remove(&item)?;
            run.dropped += 1;
        }
    }
    if ready.is_empty() {
        return Ok(run);
    }
    let keys = InstanceKeys::load(store)?;
    for ((evidence, route), item) in ready {
        let request = sign(&keys, evidence)?;
        let bytes = serde_json::to_vec(&request).map_err(|e| CloudError::Local(e.to_string()))?;
        let body: Value =
            serde_json::from_slice(&bytes).map_err(|e| CloudError::Local(e.to_string()))?;
        // The same evidence always carries the same key: a retry is idempotent.
        let key = hex::encode(&Sha256::digest(&bytes)[..16]);
        match session.with_client(|client| client.post_idempotent(&route, &body, &key)) {
            Ok(_) => {
                outbox.remove(&item)?;
                run.sent += 1;
            }
            Err(CloudError::UploadDisabled(
                CloudUploadKind::Receipts | CloudUploadKind::Unknown,
            )) => {
                clear(&outbox);
                return Ok(run);
            }
            Err(error) if error.is_transient() => {
                let retry_after = error.retry_after_at(now);
                let mut item = item;
                outbox.retry_later(&mut item, &error.to_string(), retry_after, now)?;
                return Err(error);
            }
            Err(error) => {
                let mut item = item;
                outbox.fail(&mut item, &error.to_string())?;
            }
        }
    }
    Ok(run)
}

#[cfg(test)]
#[path = "task_evidence_tests.rs"]
mod tests;