Skip to main content

lean_ctx_cloud/tasks/
claims.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The task claims this machine holds: `<data>/cloud/task-claims.json`,
3//! 0600. Only the holder ever learns a claim's lease id and fencing token,
4//! so they are kept here and never printed.
5//!
6//! Each claim names the process that holds it (`pid`): that process renews
7//! it and gives it back on stop. A new session of the same agent adopts its
8//! claims (an MCP restart within the claim's minutes).
9
10use std::path::Path;
11use std::sync::Mutex;
12
13use serde::{Deserialize, Serialize};
14
15use crate::CloudError;
16use crate::metrics::cloud_use;
17use crate::state::write_private;
18use lean_ctx_protocol::cloud::tasks::ClaimRefV1;
19
20const CLAIMS_FILE: &str = "task-claims.json";
21
22/// One claim held on this machine. Its `Debug` leaves out the lease id
23/// and fencing token (they are never printed, logs included).
24#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct HeldClaim {
26    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
27    #[serde(rename = "project_id", alias = "vault_id")]
28    pub vault_id: String,
29    pub number: u64,
30    /// The local checkout the claim was made in.
31    pub root: String,
32    /// The bus agent id the claim is for.
33    pub agent: String,
34    pub claim: ClaimRefV1,
35    /// RFC 3339, service time.
36    pub until: String,
37    pub minutes: u32,
38    pub pid: u32,
39}
40
41impl std::fmt::Debug for HeldClaim {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("HeldClaim")
44            .field("vault_id", &self.vault_id)
45            .field("number", &self.number)
46            .field("root", &self.root)
47            .field("agent", &self.agent)
48            .field("claim", &"[redacted]")
49            .field("until", &self.until)
50            .field("minutes", &self.minutes)
51            .field("pid", &self.pid)
52            .finish()
53    }
54}
55
56impl HeldClaim {
57    #[must_use]
58    pub fn until(&self) -> Option<lean_ctx_time::UtcDateTime> {
59        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&self.until)
60            .ok()
61            .map(lean_ctx_time::OffsetDateTime::to_utc)
62    }
63
64    /// Whether half of the claim's minutes have run out at `now`.
65    #[must_use]
66    pub fn renew_due(&self, now: lean_ctx_time::UtcDateTime) -> bool {
67        self.until().is_none_or(|until| {
68            until - now <= lean_ctx_time::Duration::seconds(i64::from(self.minutes) * 30)
69        })
70    }
71
72    fn same_task(&self, vault_id: &str, number: u64) -> bool {
73        self.vault_id == vault_id && self.number == number
74    }
75}
76
77#[derive(Debug, Default, Serialize, Deserialize)]
78struct ClaimsFile {
79    #[serde(default)]
80    claims: Vec<HeldClaim>,
81    /// Who on this machine worked on a task (process v1 §3.1, §5).
82    #[serde(default, skip_serializing_if = "Vec::is_empty")]
83    traces: Vec<WorkTrace>,
84}
85
86/// At most this many work traces are kept (the newest).
87const MAX_TRACES: usize = 500;
88
89/// What this Instance knows of its own work on a task, per session: the
90/// commit the claim started from (G6 of an S task pins it as
91/// `spec_commit`), and the session that submitted the result (the author
92/// a verify on this Instance is checked against: checker ≠ author by the
93/// per-session identity, never by the machine's shared worker id).
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct WorkTrace {
96    pub vault_id: String,
97    pub number: u64,
98    /// The bus agent id that claimed the task.
99    pub claimed_by: String,
100    /// The per-session identity that claimed it (its bus agent, app
101    /// session and registering process).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub claimed_session: Option<SessionIdentity>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub start_commit: Option<String>,
106    /// The per-session identity that submitted the result.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub submitted_by: Option<SessionIdentity>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub submitted_commit: Option<String>,
111}
112
113/// One session on this Instance: its bus agent id, the app's session id
114/// (`LEAN_CTX_SESSION_ID` of the process that registered the agent) when
115/// the app launched it, and that registering process (`<pid>@<start
116/// marker>`), all as the local bus registry has them.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct SessionIdentity {
119    pub agent: String,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub session: Option<String>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub process: Option<String>,
124}
125
126impl SessionIdentity {
127    /// The same session: the same bus agent; else, when both name an app
128    /// session, the same app session (sessions the app runs in one daemon
129    /// share its process); else the same registering process (a fresh
130    /// registration in the same MCP process is no other checker). Without
131    /// either on both sides, nothing shows they differ: the same.
132    #[must_use]
133    pub fn same_as(&self, other: &Self) -> bool {
134        if self.agent == other.agent {
135            return true;
136        }
137        if let (Some(a), Some(b)) = (&self.session, &other.session) {
138            return a == b;
139        }
140        match (&self.process, &other.process) {
141            (Some(a), Some(b)) => a == b,
142            _ => true,
143        }
144    }
145}
146
147/// The trace of task `number` in `vault_id`.
148#[must_use]
149pub fn trace(data_dir: &Path, vault_id: &str, number: u64) -> Option<WorkTrace> {
150    load(data_dir)
151        .traces
152        .into_iter()
153        .find(|t| t.vault_id == vault_id && t.number == number)
154}
155
156/// A new claim by the session `by` on the task, made in a checkout at
157/// `start_commit`: the trace starts over (an earlier result's author no
158/// longer applies to the work of this claim).
159pub fn trace_claim(
160    data_dir: &Path,
161    vault_id: &str,
162    number: u64,
163    by: SessionIdentity,
164    start_commit: Option<String>,
165) -> Result<(), CloudError> {
166    change_file(data_dir, |file| {
167        file.traces
168            .retain(|t| !(t.vault_id == vault_id && t.number == number));
169        file.traces.push(WorkTrace {
170            vault_id: vault_id.to_owned(),
171            number,
172            claimed_by: by.agent.clone(),
173            claimed_session: Some(by),
174            start_commit,
175            submitted_by: None,
176            submitted_commit: None,
177        });
178        let excess = file.traces.len().saturating_sub(MAX_TRACES);
179        file.traces.drain(..excess);
180    })
181}
182
183/// Cloud took the result of the task from `by`, for `commit`.
184pub fn trace_submit(
185    data_dir: &Path,
186    vault_id: &str,
187    number: u64,
188    by: SessionIdentity,
189    commit: Option<String>,
190) -> Result<(), CloudError> {
191    change_file(data_dir, |file| {
192        match file
193            .traces
194            .iter_mut()
195            .find(|t| t.vault_id == vault_id && t.number == number)
196        {
197            Some(trace) => {
198                trace.submitted_by = Some(by);
199                trace.submitted_commit = commit;
200            }
201            None => file.traces.push(WorkTrace {
202                vault_id: vault_id.to_owned(),
203                number,
204                claimed_by: by.agent.clone(),
205                claimed_session: None,
206                start_commit: None,
207                submitted_by: Some(by),
208                submitted_commit: commit,
209            }),
210        }
211        let excess = file.traces.len().saturating_sub(MAX_TRACES);
212        file.traces.drain(..excess);
213    })
214}
215
216/// One writer per process at a time (the renew thread and tool calls); the
217/// file lock below serializes the processes (every MCP session, the CLI,
218/// `cloud worker stop`).
219static LOCK: Mutex<()> = Mutex::new(());
220const LOCK_FILE: &str = "task-claims.lock";
221
222fn load(data_dir: &Path) -> ClaimsFile {
223    std::fs::read(data_dir.join(CLAIMS_FILE))
224        .ok()
225        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
226        .unwrap_or_default()
227}
228
229fn save(data_dir: &Path, file: &ClaimsFile) -> Result<(), CloudError> {
230    let bytes = serde_json::to_vec_pretty(file).map_err(|e| CloudError::Local(e.to_string()))?;
231    write_private(data_dir, CLAIMS_FILE, &bytes)
232}
233
234fn change<T>(
235    data_dir: &Path,
236    edit: impl FnOnce(&mut Vec<HeldClaim>) -> T,
237) -> Result<T, CloudError> {
238    change_file(data_dir, |file| edit(&mut file.claims))
239}
240
241fn change_file<T>(
242    data_dir: &Path,
243    edit: impl FnOnce(&mut ClaimsFile) -> T,
244) -> Result<T, CloudError> {
245    let _guard = LOCK
246        .lock()
247        .unwrap_or_else(std::sync::PoisonError::into_inner);
248    std::fs::create_dir_all(data_dir).map_err(|e| CloudError::Local(format!("claims: {e}")))?;
249    let _file_lock = lean_ctx::core::agents::FileLock::acquire(&data_dir.join(LOCK_FILE))
250        .map_err(|e| CloudError::Local(format!("claims lock: {e}")))?;
251    let mut file = load(data_dir);
252    let out = edit(&mut file);
253    save(data_dir, &file)?;
254    Ok(out)
255}
256
257/// Every claim on this machine.
258#[must_use]
259pub fn all(data_dir: &Path) -> Vec<HeldClaim> {
260    load(data_dir).claims
261}
262
263/// The claims this process holds.
264#[must_use]
265pub fn own(data_dir: &Path) -> Vec<HeldClaim> {
266    let pid = std::process::id();
267    all(data_dir)
268        .into_iter()
269        .filter(|claim| claim.pid == pid)
270        .collect()
271}
272
273#[must_use]
274pub fn find(data_dir: &Path, vault_id: &str, number: u64) -> Option<HeldClaim> {
275    all(data_dir)
276        .into_iter()
277        .find(|claim| claim.same_task(vault_id, number))
278}
279
280/// Record `claim`, replacing an earlier one on the same task (a renewal
281/// keeps the X4 claim window open; a new claim opens one).
282pub fn put(data_dir: &Path, claim: HeldClaim) -> Result<(), CloudError> {
283    let (vault_id, number) = (claim.vault_id.clone(), claim.number);
284    change(data_dir, |claims| {
285        claims.retain(|held| !held.same_task(&claim.vault_id, claim.number));
286        claims.push(claim);
287    })?;
288    cloud_use::claim_started(
289        data_dir,
290        &vault_id,
291        number,
292        lean_ctx_time::UtcDateTime::now(),
293    );
294    Ok(())
295}
296
297/// Store the renewal of `held`: only while that very claim (same lease) is
298/// still recorded here, so a renewal that crossed a release, a result or
299/// a stop never brings the claim back. Returns whether it was stored.
300pub fn renewed(data_dir: &Path, held: &HeldClaim) -> Result<bool, CloudError> {
301    change(data_dir, |claims| {
302        let Some(slot) = claims.iter_mut().find(|known| {
303            known.same_task(&held.vault_id, held.number)
304                && known.agent == held.agent
305                && known.claim.lease_id == held.claim.lease_id
306        }) else {
307            return false;
308        };
309        slot.claim = held.claim.clone();
310        slot.until.clone_from(&held.until);
311        true
312    })
313}
314
315/// Forget the claim on a task (released, submitted or lost).
316pub fn remove(data_dir: &Path, vault_id: &str, number: u64) -> Result<(), CloudError> {
317    change(data_dir, |claims| {
318        claims.retain(|held| !held.same_task(vault_id, number));
319    })?;
320    cloud_use::claim_ended(
321        data_dir,
322        vault_id,
323        number,
324        lean_ctx_time::UtcDateTime::now(),
325    );
326    Ok(())
327}
328
329/// Forget every claim on this machine (worker mode stopped: Cloud ended
330/// them all).
331pub fn clear(data_dir: &Path) -> Result<(), CloudError> {
332    let ended = change(data_dir, std::mem::take)?;
333    let now = lean_ctx_time::UtcDateTime::now();
334    for held in ended {
335        cloud_use::claim_ended(data_dir, &held.vault_id, held.number, now);
336    }
337    Ok(())
338}
339
340/// Move the unexpired claims of `agent` to this process and drop expired
341/// claims; returns the claims this process now holds for `agent`.
342pub fn adopt(
343    data_dir: &Path,
344    agent: &str,
345    now: lean_ctx_time::UtcDateTime,
346) -> Result<Vec<HeldClaim>, CloudError> {
347    let pid = std::process::id();
348    let mut expired = Vec::new();
349    let adopted = change(data_dir, |claims| {
350        let (live, gone): (Vec<_>, Vec<_>) = std::mem::take(claims)
351            .into_iter()
352            .partition(|held| held.until().is_some_and(|until| until > now));
353        *claims = live;
354        expired = gone;
355        claims
356            .iter_mut()
357            .filter(|held| held.agent == agent)
358            .map(|held| {
359                held.pid = pid;
360                held.clone()
361            })
362            .collect()
363    })?;
364    // An expired claim ended at its expiry.
365    for held in expired {
366        let until = held.until().unwrap_or(now);
367        cloud_use::claim_ended(data_dir, &held.vault_id, held.number, until);
368    }
369    Ok(adopted)
370}
371
372/// The unexpired claims whose holding process has ended (lean-ctx #3: a
373/// claim made by the CLI, whose process ends right away). They stay bound
374/// to that ended process: whoever keeps them alive (the relay, in the
375/// daemon) never becomes their holder, so the agent's next session adopts
376/// them and no command is refused for a daemon's pid.
377#[must_use]
378pub fn orphaned(data_dir: &Path, now: lean_ctx_time::UtcDateTime) -> Vec<HeldClaim> {
379    let pid = std::process::id();
380    all(data_dir)
381        .into_iter()
382        .filter(|held| {
383            held.pid != pid
384                && held.until().is_some_and(|until| until > now)
385                && !lean_ctx::ipc::process::is_alive(held.pid)
386        })
387        .collect()
388}
389
390#[cfg(test)]
391mod vault_rename_tests {
392    use super::*;
393
394    /// `HeldClaim` of the engine before the VA rename.
395    #[derive(Deserialize)]
396    #[allow(dead_code)]
397    struct PreVaHeldClaim {
398        project_id: String,
399        number: u64,
400        root: String,
401        agent: String,
402        claim: ClaimRefV1,
403        until: String,
404        minutes: u32,
405        pid: u32,
406    }
407
408    #[test]
409    fn held_claims_keep_pre_va_names() {
410        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}"#;
411        let read = crate::vault::assert_pre_va_round_trip::<HeldClaim, PreVaHeldClaim>(
412            old,
413            "project_id",
414            "vault_id",
415        );
416        assert_eq!(
417            (read.vault_id.as_str(), read.claim.fencing_token),
418            ("v1", 3)
419        );
420    }
421
422    #[test]
423    fn debug_never_prints_the_lease_id_or_fencing_token() {
424        let held: HeldClaim = serde_json::from_str(
425            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}"#,
426        )
427        .unwrap();
428        let shown = format!("{held:?}");
429        assert!(
430            !shown.contains("lse_secret") && !shown.contains("987654"),
431            "{shown}"
432        );
433        assert!(shown.contains("number: 7"), "{shown}");
434    }
435}