lean-ctx-cloud 3.12.13

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
// SPDX-License-Identifier: Apache-2.0
//! The task claims this machine holds: `<data>/cloud/task-claims.json`,
//! 0600. Only the holder ever learns a claim's lease id and fencing token,
//! so they are kept here and never printed.
//!
//! Each claim names the process that holds it (`pid`): that process renews
//! it and gives it back on stop. A new session of the same agent adopts its
//! claims (an MCP restart within the claim's minutes).

use std::path::Path;
use std::sync::Mutex;

use serde::{Deserialize, Serialize};

use crate::CloudError;
use crate::metrics::cloud_use;
use crate::state::write_private;
use lean_ctx_protocol::cloud::tasks::ClaimRefV1;

const CLAIMS_FILE: &str = "task-claims.json";

/// One claim held on this machine. Its `Debug` leaves out the lease id
/// and fencing token (they are never printed, logs included).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeldClaim {
    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
    #[serde(rename = "project_id", alias = "vault_id")]
    pub vault_id: String,
    pub number: u64,
    /// The local checkout the claim was made in.
    pub root: String,
    /// The bus agent id the claim is for.
    pub agent: String,
    pub claim: ClaimRefV1,
    /// RFC 3339, service time.
    pub until: String,
    pub minutes: u32,
    pub pid: u32,
}

impl std::fmt::Debug for HeldClaim {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HeldClaim")
            .field("vault_id", &self.vault_id)
            .field("number", &self.number)
            .field("root", &self.root)
            .field("agent", &self.agent)
            .field("claim", &"[redacted]")
            .field("until", &self.until)
            .field("minutes", &self.minutes)
            .field("pid", &self.pid)
            .finish()
    }
}

impl HeldClaim {
    #[must_use]
    pub fn until(&self) -> Option<lean_ctx_time::UtcDateTime> {
        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&self.until)
            .ok()
            .map(lean_ctx_time::OffsetDateTime::to_utc)
    }

    /// Whether half of the claim's minutes have run out at `now`.
    #[must_use]
    pub fn renew_due(&self, now: lean_ctx_time::UtcDateTime) -> bool {
        self.until().is_none_or(|until| {
            until - now <= lean_ctx_time::Duration::seconds(i64::from(self.minutes) * 30)
        })
    }

    fn same_task(&self, vault_id: &str, number: u64) -> bool {
        self.vault_id == vault_id && self.number == number
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct ClaimsFile {
    #[serde(default)]
    claims: Vec<HeldClaim>,
    /// Who on this machine worked on a task (process v1 §3.1, §5).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    traces: Vec<WorkTrace>,
}

/// At most this many work traces are kept (the newest).
const MAX_TRACES: usize = 500;

/// What this Instance knows of its own work on a task, per session: the
/// commit the claim started from (G6 of an S task pins it as
/// `spec_commit`), and the session that submitted the result (the author
/// a verify on this Instance is checked against: checker ≠ author by the
/// per-session identity, never by the machine's shared worker id).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkTrace {
    pub vault_id: String,
    pub number: u64,
    /// The bus agent id that claimed the task.
    pub claimed_by: String,
    /// The per-session identity that claimed it (its bus agent, app
    /// session and registering process).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claimed_session: Option<SessionIdentity>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_commit: Option<String>,
    /// The per-session identity that submitted the result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub submitted_by: Option<SessionIdentity>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub submitted_commit: Option<String>,
}

/// One session on this Instance: its bus agent id, the app's session id
/// (`LEAN_CTX_SESSION_ID` of the process that registered the agent) when
/// the app launched it, and that registering process (`<pid>@<start
/// marker>`), all as the local bus registry has them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionIdentity {
    pub agent: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process: Option<String>,
}

impl SessionIdentity {
    /// The same session: the same bus agent; else, when both name an app
    /// session, the same app session (sessions the app runs in one daemon
    /// share its process); else the same registering process (a fresh
    /// registration in the same MCP process is no other checker). Without
    /// either on both sides, nothing shows they differ: the same.
    #[must_use]
    pub fn same_as(&self, other: &Self) -> bool {
        if self.agent == other.agent {
            return true;
        }
        if let (Some(a), Some(b)) = (&self.session, &other.session) {
            return a == b;
        }
        match (&self.process, &other.process) {
            (Some(a), Some(b)) => a == b,
            _ => true,
        }
    }
}

/// The trace of task `number` in `vault_id`.
#[must_use]
pub fn trace(data_dir: &Path, vault_id: &str, number: u64) -> Option<WorkTrace> {
    load(data_dir)
        .traces
        .into_iter()
        .find(|t| t.vault_id == vault_id && t.number == number)
}

/// A new claim by the session `by` on the task, made in a checkout at
/// `start_commit`: the trace starts over (an earlier result's author no
/// longer applies to the work of this claim).
pub fn trace_claim(
    data_dir: &Path,
    vault_id: &str,
    number: u64,
    by: SessionIdentity,
    start_commit: Option<String>,
) -> Result<(), CloudError> {
    change_file(data_dir, |file| {
        file.traces
            .retain(|t| !(t.vault_id == vault_id && t.number == number));
        file.traces.push(WorkTrace {
            vault_id: vault_id.to_owned(),
            number,
            claimed_by: by.agent.clone(),
            claimed_session: Some(by),
            start_commit,
            submitted_by: None,
            submitted_commit: None,
        });
        let excess = file.traces.len().saturating_sub(MAX_TRACES);
        file.traces.drain(..excess);
    })
}

/// Cloud took the result of the task from `by`, for `commit`.
pub fn trace_submit(
    data_dir: &Path,
    vault_id: &str,
    number: u64,
    by: SessionIdentity,
    commit: Option<String>,
) -> Result<(), CloudError> {
    change_file(data_dir, |file| {
        match file
            .traces
            .iter_mut()
            .find(|t| t.vault_id == vault_id && t.number == number)
        {
            Some(trace) => {
                trace.submitted_by = Some(by);
                trace.submitted_commit = commit;
            }
            None => file.traces.push(WorkTrace {
                vault_id: vault_id.to_owned(),
                number,
                claimed_by: by.agent.clone(),
                claimed_session: None,
                start_commit: None,
                submitted_by: Some(by),
                submitted_commit: commit,
            }),
        }
        let excess = file.traces.len().saturating_sub(MAX_TRACES);
        file.traces.drain(..excess);
    })
}

/// One writer per process at a time (the renew thread and tool calls); the
/// file lock below serializes the processes (every MCP session, the CLI,
/// `cloud worker stop`).
static LOCK: Mutex<()> = Mutex::new(());
const LOCK_FILE: &str = "task-claims.lock";

fn load(data_dir: &Path) -> ClaimsFile {
    std::fs::read(data_dir.join(CLAIMS_FILE))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

fn save(data_dir: &Path, file: &ClaimsFile) -> Result<(), CloudError> {
    let bytes = serde_json::to_vec_pretty(file).map_err(|e| CloudError::Local(e.to_string()))?;
    write_private(data_dir, CLAIMS_FILE, &bytes)
}

fn change<T>(
    data_dir: &Path,
    edit: impl FnOnce(&mut Vec<HeldClaim>) -> T,
) -> Result<T, CloudError> {
    change_file(data_dir, |file| edit(&mut file.claims))
}

fn change_file<T>(
    data_dir: &Path,
    edit: impl FnOnce(&mut ClaimsFile) -> T,
) -> Result<T, CloudError> {
    let _guard = LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    std::fs::create_dir_all(data_dir).map_err(|e| CloudError::Local(format!("claims: {e}")))?;
    let _file_lock = lean_ctx::core::agents::FileLock::acquire(&data_dir.join(LOCK_FILE))
        .map_err(|e| CloudError::Local(format!("claims lock: {e}")))?;
    let mut file = load(data_dir);
    let out = edit(&mut file);
    save(data_dir, &file)?;
    Ok(out)
}

/// Every claim on this machine.
#[must_use]
pub fn all(data_dir: &Path) -> Vec<HeldClaim> {
    load(data_dir).claims
}

/// The claims this process holds.
#[must_use]
pub fn own(data_dir: &Path) -> Vec<HeldClaim> {
    let pid = std::process::id();
    all(data_dir)
        .into_iter()
        .filter(|claim| claim.pid == pid)
        .collect()
}

#[must_use]
pub fn find(data_dir: &Path, vault_id: &str, number: u64) -> Option<HeldClaim> {
    all(data_dir)
        .into_iter()
        .find(|claim| claim.same_task(vault_id, number))
}

/// Record `claim`, replacing an earlier one on the same task (a renewal
/// keeps the X4 claim window open; a new claim opens one).
pub fn put(data_dir: &Path, claim: HeldClaim) -> Result<(), CloudError> {
    let (vault_id, number) = (claim.vault_id.clone(), claim.number);
    change(data_dir, |claims| {
        claims.retain(|held| !held.same_task(&claim.vault_id, claim.number));
        claims.push(claim);
    })?;
    cloud_use::claim_started(
        data_dir,
        &vault_id,
        number,
        lean_ctx_time::UtcDateTime::now(),
    );
    Ok(())
}

/// Store the renewal of `held`: only while that very claim (same lease) is
/// still recorded here, so a renewal that crossed a release, a result or
/// a stop never brings the claim back. Returns whether it was stored.
pub fn renewed(data_dir: &Path, held: &HeldClaim) -> Result<bool, CloudError> {
    change(data_dir, |claims| {
        let Some(slot) = claims.iter_mut().find(|known| {
            known.same_task(&held.vault_id, held.number)
                && known.agent == held.agent
                && known.claim.lease_id == held.claim.lease_id
        }) else {
            return false;
        };
        slot.claim = held.claim.clone();
        slot.until.clone_from(&held.until);
        true
    })
}

/// Forget the claim on a task (released, submitted or lost).
pub fn remove(data_dir: &Path, vault_id: &str, number: u64) -> Result<(), CloudError> {
    change(data_dir, |claims| {
        claims.retain(|held| !held.same_task(vault_id, number));
    })?;
    cloud_use::claim_ended(
        data_dir,
        vault_id,
        number,
        lean_ctx_time::UtcDateTime::now(),
    );
    Ok(())
}

/// Forget every claim on this machine (worker mode stopped: Cloud ended
/// them all).
pub fn clear(data_dir: &Path) -> Result<(), CloudError> {
    let ended = change(data_dir, std::mem::take)?;
    let now = lean_ctx_time::UtcDateTime::now();
    for held in ended {
        cloud_use::claim_ended(data_dir, &held.vault_id, held.number, now);
    }
    Ok(())
}

/// Move the unexpired claims of `agent` to this process and drop expired
/// claims; returns the claims this process now holds for `agent`.
pub fn adopt(
    data_dir: &Path,
    agent: &str,
    now: lean_ctx_time::UtcDateTime,
) -> Result<Vec<HeldClaim>, CloudError> {
    let pid = std::process::id();
    let mut expired = Vec::new();
    let adopted = change(data_dir, |claims| {
        let (live, gone): (Vec<_>, Vec<_>) = std::mem::take(claims)
            .into_iter()
            .partition(|held| held.until().is_some_and(|until| until > now));
        *claims = live;
        expired = gone;
        claims
            .iter_mut()
            .filter(|held| held.agent == agent)
            .map(|held| {
                held.pid = pid;
                held.clone()
            })
            .collect()
    })?;
    // An expired claim ended at its expiry.
    for held in expired {
        let until = held.until().unwrap_or(now);
        cloud_use::claim_ended(data_dir, &held.vault_id, held.number, until);
    }
    Ok(adopted)
}

/// The unexpired claims whose holding process has ended (lean-ctx #3: a
/// claim made by the CLI, whose process ends right away). They stay bound
/// to that ended process: whoever keeps them alive (the relay, in the
/// daemon) never becomes their holder, so the agent's next session adopts
/// them and no command is refused for a daemon's pid.
#[must_use]
pub fn orphaned(data_dir: &Path, now: lean_ctx_time::UtcDateTime) -> Vec<HeldClaim> {
    let pid = std::process::id();
    all(data_dir)
        .into_iter()
        .filter(|held| {
            held.pid != pid
                && held.until().is_some_and(|until| until > now)
                && !lean_ctx::ipc::process::is_alive(held.pid)
        })
        .collect()
}

#[cfg(test)]
mod vault_rename_tests {
    use super::*;

    /// `HeldClaim` of the engine before the VA rename.
    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct PreVaHeldClaim {
        project_id: String,
        number: u64,
        root: String,
        agent: String,
        claim: ClaimRefV1,
        until: String,
        minutes: u32,
        pid: u32,
    }

    #[test]
    fn held_claims_keep_pre_va_names() {
        let old = r#"{"project_id":"v1","number":7,"root":"/w","agent":"a","claim":{"lease_id":"lse_1","fencing_token":3},"until":"2026-10-22T10:00:00Z","minutes":30,"pid":1}"#;
        let read = crate::vault::assert_pre_va_round_trip::<HeldClaim, PreVaHeldClaim>(
            old,
            "project_id",
            "vault_id",
        );
        assert_eq!(
            (read.vault_id.as_str(), read.claim.fencing_token),
            ("v1", 3)
        );
    }

    #[test]
    fn debug_never_prints_the_lease_id_or_fencing_token() {
        let held: HeldClaim = serde_json::from_str(
            r#"{"project_id":"v1","number":7,"root":"/w","agent":"a","claim":{"lease_id":"lse_secret","fencing_token":987654},"until":"2026-10-22T10:00:00Z","minutes":30,"pid":1}"#,
        )
        .unwrap();
        let shown = format!("{held:?}");
        assert!(
            !shown.contains("lse_secret") && !shown.contains("987654"),
            "{shown}"
        );
        assert!(shown.contains("number: 7"), "{shown}");
    }
}