Skip to main content

lean_ctx_cloud/tasks/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Tasks in the engine (H2, C0 1.9 §1): read a project's tasks, claim one,
3//! report short summaries, submit one result with evidence, give it back.
4//!
5//! The rules the engine keeps:
6//! - No tool call waits for Cloud ([`cache`]): reads answer from the last
7//!   data Cloud sent and say when it is stale; changes are queued, and what
8//!   Cloud answered comes with the caller's next call. Each queued request
9//!   ends within [`BUDGET`]; offline or a lapsed lease answers at once.
10//! - A claim passes the worker gate first ([`worker::admit_claim`], L1:
11//!   the engine's opt-in for the repo, pause, today's budget) and goes out
12//!   under that opt-in; a result passes [`worker::admit_submit`]. Cloud
13//!   checks the same opt-in again (`optin_scope`, `optin_inactive`,
14//!   `daily_budget`, `optin_changed`, `vetoed`); every refusal is shown as
15//!   it is, an `optin_changed` claim reads the opt-in again once, and a
16//!   stopped opt-in ends this machine's claims.
17//! - The claim's lease id and fencing token stay on this machine
18//!   ([`claims`], 0600) and are never printed. This process renews its
19//!   claims while it runs (`keeper`) and gives them back on stop.
20//! - Text leaving the machine (summaries, proposals, release reasons) passes
21//!   the outbox screening; a text it refuses is not sent, never rewritten.
22//! - Text arriving from Cloud (titles, goals, summaries of people and other
23//!   agents) reaches the agent only fenced as foreign data
24//!   ([`crate::untrusted::wrap`], X5).
25//! - Cloud announces claims, releases and results on the bus itself; the
26//!   engine sends no task frames.
27
28pub mod cache;
29pub mod claims;
30mod client;
31pub mod fields;
32pub mod gate;
33mod keeper;
34pub mod local;
35mod process;
36pub mod propose;
37pub mod reads;
38mod render;
39
40use crate::CloudConfigExt as _;
41use std::path::{Path, PathBuf};
42use std::time::{Duration, Instant};
43
44use lean_ctx_time::UtcDateTime;
45use serde::Deserialize;
46
47use crate::CloudError;
48use crate::TaskRefusal;
49use crate::auth::Session;
50use crate::config::CloudConfig;
51use crate::knowledge::screening::Screen;
52use crate::metrics::cloud_use;
53use crate::state::CloudStore;
54use crate::vault::{VaultMap, VaultRecord};
55use crate::worker::{self, Admission, EvidenceSummary, Refusal, TaskScope};
56use claims::HeldClaim;
57use client::TasksApi;
58use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
59use lean_ctx_protocol::cloud::tasks::{
60    EvidenceKind, EvidenceV1, MAX_CLAIM_MINUTES, MAX_TASKS_PAGE, MIN_CLAIM_MINUTES,
61    TASK_AMEND_SCHEMA, TASK_CLAIM_RENEW_SCHEMA, TASK_CLAIM_REQUEST_SCHEMA, TASK_RELEASE_SCHEMA,
62    TASK_RESULT_SCHEMA, TASK_UPDATE_SCHEMA, TASK_VERIFY_SCHEMA, TaskAckV1, TaskActorKind,
63    TaskAmendRequestV1, TaskClaimRenewRequestV1, TaskClaimRequestV1, TaskListV1, TaskOutcome,
64    TaskPriority, TaskReleaseRequestV1, TaskResultRequestV1, TaskUpdateRequestV1, TaskV1,
65    TaskVerdict, TaskVerifyRequestV1, UsageV1,
66};
67
68pub use client::ListFilter;
69pub use render::{
70    PARTIAL_NOTE, render_list, render_listing, render_result_ack, render_task, render_verify_ack,
71};
72
73/// The time one task call may take in all.
74pub const BUDGET: Duration = Duration::from_secs(5);
75/// Claim length when the caller names none.
76pub const DEFAULT_CLAIM_MINUTES: u32 = 10;
77
78/// A connected machine, its lease and the Cloud project of a local root.
79pub struct Connected {
80    pub store: CloudStore,
81    pub session: Session,
82    pub project: VaultRecord,
83    pub root: PathBuf,
84}
85
86/// Whether tasks apply to `project_root` with `right`; `Err` says why not
87/// (no request made).
88pub fn connected(project_root: &Path, right: CloudRight) -> Result<Connected, CloudError> {
89    let config = lean_ctx::core::config::Config::load().cloud.clone();
90    connected_with(&config, CloudStore::open()?, project_root, right)
91}
92
93fn connected_with(
94    config: &CloudConfig,
95    store: CloudStore,
96    project_root: &Path,
97    right: CloudRight,
98) -> Result<Connected, CloudError> {
99    if config.enabled == Some(false) {
100        return Err(CloudError::Config(
101            "LeanCTX Cloud is off ([cloud] enabled = false)".into(),
102        ));
103    }
104    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
105    let project =
106        crate::resolution::vault_for_root(store.data_dir(), project_root)?.ok_or_else(|| {
107            CloudError::Config(
108                "this repository is not linked to a vault (run `lean-ctx cloud sync` in it)".into(),
109            )
110        })?;
111    let session = Session::load(store.clone(), config.root_key(&instance.url)?)?;
112    if !matches!(
113        session.lease.state_at(UtcDateTime::now()),
114        LeaseState::Valid | LeaseState::Grace
115    ) {
116        return Err(CloudError::LeaseLapsed);
117    }
118    if !session.lease.lease.grants(right) {
119        return Err(CloudError::Forbidden);
120    }
121    Ok(Connected {
122        store,
123        session,
124        project,
125        root: project_root.to_path_buf(),
126    })
127}
128
129impl Connected {
130    fn link(&self) -> Link<'_> {
131        Link {
132            data_dir: self.store.data_dir(),
133            vault_id: &self.project.vault_id,
134            root: &self.root,
135            via: Via::Session(&self.session),
136            budget: BUDGET,
137            deadline: std::cell::Cell::new(None),
138            workers: Some(&self.store),
139            presence: &process::local_presence,
140            announce: Some(crate::bus::presence::announce_and_wait),
141        }
142    }
143}
144
145/// How a call reaches Cloud: the enrolled session, or (tests) a local fake.
146enum Via<'a> {
147    Session(&'a Session),
148    #[cfg(test)]
149    Origin(String),
150}
151
152/// Everything one task operation needs.
153struct Link<'a> {
154    data_dir: &'a Path,
155    vault_id: &'a str,
156    root: &'a Path,
157    via: Via<'a>,
158    budget: Duration,
159    /// One deadline for every request of a call (a claim: opt-in read,
160    /// claim and its one retry); `None`: each request gets `budget`. A
161    /// claim tried again after the relay announced gets a fresh one.
162    deadline: std::cell::Cell<Option<Instant>>,
163    /// Where a local bus agent's worker is looked up (`None`: the agent
164    /// goes to Cloud as given).
165    workers: Option<&'a CloudStore>,
166    /// Where a bus agent's live presence on this Instance is looked up
167    /// (the checker and the author of a verify, §3.1).
168    presence: process::PresenceLookup<'a>,
169    /// Asks the running relay to announce now and waits up to the given
170    /// time for its hello: what it announced, `None` when no relay
171    /// answered. `None` here: a claim refused for presence or role is not
172    /// tried again.
173    announce: Option<fn(Duration) -> Option<String>>,
174}
175
176/// The least time a task write's budget must still hold for its resend.
177const RESEND_MIN_LEFT: Duration = Duration::from_secs(1);
178
179/// A fresh `Idempotency-Key` for one logical task write.
180fn write_key() -> String {
181    uuid::Uuid::new_v4().simple().to_string()
182}
183
184/// Whether a write's answer may have been lost (the write may or may not
185/// have happened): only these are resent. A 429 or a refusal is an answer.
186fn lost_in_transit(error: &CloudError) -> bool {
187    matches!(
188        error,
189        CloudError::Offline(_) | CloudError::Server { status: 500.., .. }
190    )
191}
192
193/// How long a claim refused for presence or role waits for the relay's
194/// fresh announcement before it is tried once more (Cloud task #27).
195const ANNOUNCE_WAIT: Duration = Duration::from_secs(3);
196
197impl Link<'_> {
198    /// The gate's directories: private copies under the data dir, the run
199    /// tree outside `$HOME`.
200    fn gate_dirs(&self) -> gate::GateDirs {
201        gate::GateDirs::for_instance(self.data_dir)
202    }
203
204    /// The id Cloud knows `agent` by. Cloud keeps presence and claims under
205    /// the worker the relay announced (`wkr_…`), so a local bus agent id
206    /// is sent as its worker; a worker id, or a name Cloud resolves, goes
207    /// as it is.
208    fn cloud_agent(&self, agent: &str) -> String {
209        self.cloud_identity(agent).0
210    }
211
212    /// [`Self::cloud_agent`] and the role of the worker it names when the
213    /// book knows it: whom a refusal says Cloud looked up (task #27).
214    fn cloud_identity(&self, agent: &str) -> (String, Option<String>) {
215        if crate::bus::address::is_worker_id(agent) {
216            return (agent.to_owned(), None);
217        }
218        self.workers
219            .and_then(|store| crate::bus::messages_v2::known_worker_and_role_of(store, agent))
220            .map_or_else(|| (agent.to_owned(), None), |(id, role)| (id, Some(role)))
221    }
222
223    /// One request that may change the vault's tasks: what this Instance
224    /// keeps of them ([`reads`]) is outdated afterwards, so the next read
225    /// asks Cloud.
226    fn call<T>(
227        &self,
228        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
229    ) -> Result<T, CloudError> {
230        let result = self.call_read(call);
231        reads::outdate(self.data_dir, self.vault_id);
232        result
233    }
234
235    /// One logical task write (claim, release, update, result) whose
236    /// request may be lost in transit: `send` is given the write's one
237    /// `Idempotency-Key` and sent once more, with that same key, when the
238    /// answer did not arrive (offline, timeout, 5xx) and the call's time
239    /// budget still allows it. Cloud answers a resend it already applied
240    /// with the first answer, so the write happens once.
241    fn write_once<T>(
242        &self,
243        key: &str,
244        send: impl Fn(&str) -> Result<T, CloudError>,
245    ) -> Result<T, CloudError> {
246        let own_deadline = self.deadline.get().is_none();
247        if own_deadline {
248            self.deadline.set(Some(Instant::now() + self.budget));
249        }
250        let deadline = self.deadline.get().unwrap_or_else(Instant::now);
251        let mut result = send(key);
252        if result.as_ref().is_err_and(lost_in_transit)
253            && deadline.saturating_duration_since(Instant::now()) >= RESEND_MIN_LEFT
254        {
255            result = send(key);
256        }
257        if own_deadline {
258            self.deadline.set(None);
259        }
260        result
261    }
262
263    /// The Cloud the requests go to (a 429 hold is kept per Cloud).
264    fn cloud_url(&self) -> &str {
265        match &self.via {
266            Via::Session(session) => &session.instance.url,
267            #[cfg(test)]
268            Via::Origin(origin) => origin,
269        }
270    }
271
272    /// One request that only reads.
273    fn call_read<T>(
274        &self,
275        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
276    ) -> Result<T, CloudError> {
277        let deadline = self
278            .deadline
279            .get()
280            .unwrap_or_else(|| Instant::now() + self.budget);
281        let client = match &self.via {
282            Via::Session(session) => session.bounded_client(deadline)?,
283            #[cfg(test)]
284            Via::Origin(origin) => crate::transport::CloudClient::bounded(origin, self.budget)?,
285        };
286        let result = call(&TasksApi {
287            client: &client,
288            vault_id: self.vault_id,
289        });
290        match &self.via {
291            Via::Session(session) => result.map_err(|e| session.noted(e)),
292            #[cfg(test)]
293            Via::Origin(_) => result,
294        }
295    }
296
297    /// [`Self::call`] for a claim or its renewal: while a quota or policy
298    /// throttle holds task claims nothing is asked (the refusal says until
299    /// when); a `quota_exceeded`/`policy_denied` answer sets one.
300    fn call_claim<T>(
301        &self,
302        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
303    ) -> Result<T, CloudError> {
304        use crate::throttle::{self, Scope};
305        let store = match &self.via {
306            Via::Session(session) => &session.store,
307            #[cfg(test)]
308            Via::Origin(_) => return self.call(call),
309        };
310        throttle::check(store, Scope::Tasks, lean_ctx_time::UtcDateTime::now())?;
311        match self.call(call) {
312            Ok(value) => {
313                throttle::passed(store, Scope::Tasks);
314                Ok(value)
315            }
316            Err(error) => Err(throttle::note(
317                store,
318                Scope::Tasks,
319                error,
320                lean_ctx_time::UtcDateTime::now(),
321            )),
322        }
323    }
324
325    /// Now on the service's clock (claim ends are service time).
326    fn now(&self) -> UtcDateTime {
327        match &self.via {
328            Via::Session(session) => session.lease.service_time(UtcDateTime::now()).to_utc(),
329            #[cfg(test)]
330            Via::Origin(_) => UtcDateTime::now(),
331        }
332    }
333
334    /// Task `number` of this project as the worker gate sees it.
335    fn scope(&self, number: u64) -> TaskScope {
336        TaskScope {
337            task_id: number.to_string(),
338            vault_id: self.vault_id.to_owned(),
339        }
340    }
341
342    /// The claim `agent` holds on task `number`: never another agent's, so
343    /// no agent writes under another's fencing token. The process that
344    /// renews it does not matter: the agent's CLI and its session (or the
345    /// relay that kept a CLI claim alive) act for the same agent, and the
346    /// claims file is this user's alone (0600).
347    fn held(&self, number: u64, agent: &str) -> Result<HeldClaim, CloudError> {
348        match claims::find(self.data_dir, self.vault_id, number) {
349            Some(held) if held.agent == agent => Ok(held),
350            Some(_) => Err(CloudError::Refused(format!(
351                "task #{number} is claimed on this machine by another agent"
352            ))),
353            None => Err(CloudError::Refused(format!(
354                "this machine holds no claim on task #{number}"
355            ))),
356        }
357    }
358
359    /// Forget the local claim when Cloud says it is gone for good.
360    fn settle<T>(&self, number: u64, answer: Result<T, CloudError>) -> Result<T, CloudError> {
361        let gone = match &answer {
362            Err(CloudError::Task { refusal, .. }) => refusal.ends_claim(),
363            Err(CloudError::NotFound | CloudError::Vetoed) => true,
364            _ => false,
365        };
366        if gone {
367            if matches!(
368                &answer,
369                Err(CloudError::Task {
370                    refusal: TaskRefusal::StaleClaim,
371                    ..
372                })
373            ) {
374                let agent =
375                    claims::find(self.data_dir, self.vault_id, number).map(|held| held.agent);
376                lean_ctx::core::agents::friction::record_for(
377                    lean_ctx::core::agents::friction::CLAIM_EXPIRED,
378                    agent.as_deref(),
379                    self.root.to_str(),
380                );
381            }
382            let _ = claims::remove(self.data_dir, self.vault_id, number);
383        }
384        answer
385    }
386}
387
388/// A task as the agent reads it: the view and its local claim.
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub struct TaskView {
391    pub task: TaskV1,
392    /// The claim end when this machine holds the claim.
393    pub held_until: Option<String>,
394}
395
396/// Screen every outgoing `(field, text)`; the first refusal names the field
397/// and the reason, never the text.
398fn screened(fields: &[(&str, Option<&str>)]) -> Result<(), CloudError> {
399    let mut screen = Screen::for_installation();
400    for (field, text) in fields {
401        if let Some(text) = text
402            && let Err(blocked) = screen.check(text)
403        {
404            return Err(CloudError::Refused(format!(
405                "the {field} was not sent: it contains {blocked}"
406            )));
407        }
408    }
409    Ok(())
410}
411
412/// One piece of evidence as a caller names it.
413#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
414pub struct EvidenceInput {
415    pub kind: String,
416    pub reference: String,
417}
418
419impl EvidenceInput {
420    /// `root` is the checkout a `file_anchor` (`path` or `path::symbol`) is
421    /// digested in, as it is now (J2 anchors).
422    pub(crate) fn into_evidence(self, root: &Path) -> Result<EvidenceV1, CloudError> {
423        let kind = match self.kind.as_str() {
424            "receipt" => EvidenceKind::Receipt,
425            "commit" => EvidenceKind::Commit,
426            "ci_run" => EvidenceKind::CiRun,
427            "url" => EvidenceKind::Url,
428            "fact" => EvidenceKind::Fact,
429            "file_anchor" => return file_anchor(root, self.reference.trim()),
430            other => {
431                return Err(CloudError::Refused(format!(
432                    "unknown evidence kind {other:?} (receipt, commit, ci_run, file_anchor, url, fact)"
433                )));
434            }
435        };
436        let evidence = EvidenceV1 {
437            kind,
438            reference: Some(self.reference.trim().to_owned()),
439            anchor: None,
440        };
441        evidence
442            .validate()
443            .map_err(|e| CloudError::Refused(format!("evidence: {e}")))?;
444        Ok(evidence)
445    }
446}
447
448/// The anchor of `spec` in `root`: the file is admitted like a source
449/// binding first (a restricted, withheld or unreadable file is never
450/// digested), then digested as it is now.
451fn file_anchor(root: &Path, spec: &str) -> Result<EvidenceV1, CloudError> {
452    use lean_ctx::core::knowledge::anchors;
453    let (path, symbol) = anchors::parse_spec(spec);
454    let root_text = root.to_string_lossy();
455    if lean_ctx::core::archive::bindings::sources_at(&root_text, &[path], "ctx_tasks").is_none() {
456        return Err(CloudError::Refused(format!(
457            "{path}: not an admitted project file"
458        )));
459    }
460    let anchor = anchors::capture(root, path, symbol).map_err(CloudError::Refused)?;
461    let evidence = EvidenceV1 {
462        kind: EvidenceKind::FileAnchor,
463        reference: None,
464        anchor: Some(anchor),
465    };
466    evidence
467        .validate()
468        .map_err(|e| CloudError::Refused(format!("evidence: {e}")))?;
469    Ok(evidence)
470}
471
472/// A task list as the Instance shows it.
473///
474/// `partial`: a Cloud answer came back full ([`MAX_TASKS_PAGE`] tasks), so
475/// older tasks of these filters may be missing. The list says so, never
476/// silently incomplete. A list cached before 3.12.3 reads as whole.
477#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]
478pub struct TaskListing {
479    #[serde(flatten)]
480    pub list: TaskListV1,
481    #[serde(default)]
482    pub partial: bool,
483}
484
485/// The project's tasks (shared and coalesced per Instance, [`reads`]).
486/// Only a current list: when Cloud holds reads or is not reachable this is
487/// an error, not the last good list ([`list_read`] serves that with its
488/// age), so no caller takes tasks since claimed or closed for current.
489pub fn list(project_root: &Path, filter: &ListFilter) -> Result<TaskListing, CloudError> {
490    list_read(project_root, filter).and_then(reads::current)
491}
492
493/// [`list`] and, when Cloud holds reads (429) or is not reachable, the age
494/// of the last good list served instead.
495pub fn list_read(
496    project_root: &Path,
497    filter: &ListFilter,
498) -> Result<reads::Read<TaskListing>, CloudError> {
499    let c = connected(project_root, CloudRight::TasksRead)?;
500    list_cached(&c.link(), filter)
501}
502
503fn list_cached(
504    link: &Link<'_>,
505    filter: &ListFilter,
506) -> Result<reads::Read<TaskListing>, CloudError> {
507    let key = format!("list{}", filter.query()?);
508    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
509        list_via(link, filter)
510    })
511}
512
513/// The listing in board order ([`fields::sort_by_priority`]).
514///
515/// Cloud answers one page, the newest tasks by number, so an older high task
516/// can fall off it: the high tasks of the same filters are fetched too and
517/// merged in, each task once, before the sort. That answer is a page too, so
518/// a full one marks the listing `partial`.
519fn list_via(link: &Link<'_>, filter: &ListFilter) -> Result<TaskListing, CloudError> {
520    let mut list = link.call_read(|api| api.list(filter))?;
521    let mut partial = list.tasks.len() >= MAX_TASKS_PAGE;
522    if filter.priority.is_none() {
523        let high = ListFilter {
524            priority: Some(TaskPriority::High),
525            ..filter.clone()
526        };
527        let high = link.call_read(|api| api.list(&high))?;
528        partial |= high.tasks.len() >= MAX_TASKS_PAGE;
529        let seen: std::collections::HashSet<u64> = list.tasks.iter().map(|t| t.number).collect();
530        list.tasks
531            .extend(high.tasks.into_iter().filter(|t| !seen.contains(&t.number)));
532    }
533    fields::sort_by_priority(&mut list.tasks);
534    Ok(TaskListing { list, partial })
535}
536
537/// One task (shared and coalesced per Instance, [`reads`]). Only a current
538/// answer: when Cloud holds reads or is not reachable this is an error, not
539/// the last good answer ([`show_read`] serves that with its age).
540pub fn show(project_root: &Path, number: u64) -> Result<TaskView, CloudError> {
541    show_read(project_root, number).and_then(reads::current)
542}
543
544/// [`show`] and, when Cloud holds reads (429) or is not reachable, the age
545/// of the last good answer served instead. A task Cloud does not know is
546/// [`CloudError::NotFound`]; a rate limit never reads as one.
547pub fn show_read(project_root: &Path, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
548    let c = connected(project_root, CloudRight::TasksRead)?;
549    let link = c.link();
550    show_cached(&link, number)
551}
552
553fn show_cached(link: &Link<'_>, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
554    let key = format!("task#{number}");
555    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
556        link.call_read(|api| api.show(number))
557    })
558    .map(|read| read.map(|task| view_of(link, task)))
559}
560
561/// `task` as the caller sees it, with its local claim (no request).
562fn view_of(link: &Link<'_>, task: TaskV1) -> TaskView {
563    let held_until = claims::find(link.data_dir, link.vault_id, task.number).map(|held| held.until);
564    TaskView { task, held_until }
565}
566
567/// A granted claim, as the caller may see it (no lease id, no token).
568#[derive(Debug, Clone, PartialEq, Eq)]
569pub struct ClaimGranted {
570    pub number: u64,
571    pub until: String,
572    pub minutes: u32,
573}
574
575/// Claim task `number` for bus agent `agent` in session `session_id`.
576pub fn claim(
577    project_root: &Path,
578    number: u64,
579    agent: &str,
580    session_id: &str,
581    minutes: Option<u32>,
582) -> Result<ClaimGranted, CloudError> {
583    let c = connected(project_root, CloudRight::TasksWork)?;
584    let local = lean_ctx::core::config::Config::load().cloud.worker.clone();
585    // The whole claim (opt-in read, claim, its one retry) ends within one
586    // BUDGET, like every task call from a tool.
587    let deadline = std::cell::Cell::new(Instant::now() + BUDGET);
588    // Whether the gate let a request go to Cloud: then an `Ok` is Cloud's
589    // grant (a claim this machine already holds never reaches the gate).
590    let asked = std::cell::Cell::new(false);
591    let gate = |scope: &TaskScope| {
592        let unavailable = |e: CloudError| Refusal::Unavailable(e.to_string());
593        let client = c
594            .session
595            .bounded_client(deadline.get())
596            .map_err(unavailable)?;
597        let optin = worker::fetch_optin_via(&client).map_err(unavailable)?;
598        let admission = worker::admit_claim_for(&c.store, &local, scope, &optin)?;
599        asked.set(true);
600        Ok(admission)
601    };
602    let link = c.link();
603    link.deadline.set(Some(deadline.get()));
604    // A claim tried again after the relay announced gets a fresh BUDGET,
605    // its opt-in read too.
606    let restart = || {
607        deadline.set(Instant::now() + BUDGET);
608        link.deadline.set(Some(deadline.get()));
609    };
610    let granted = claim_via(&link, number, agent, session_id, minutes, &gate, &restart)
611        .inspect_err(|error| record_claim_friction(error, agent, project_root))?;
612    // Counted only once granted: a refused claim costs no task today. The
613    // claim stands either way; Cloud counts it too.
614    if asked.get()
615        && let Err(error) = worker::count_claim(&c.store)
616    {
617        tracing::warn!("cloud worker: a granted claim was not counted here: {error}");
618    }
619    keeper::ensure_running();
620    Ok(granted)
621}
622
623/// Count a claim Cloud refused for presence, role or consent (local
624/// friction log, the retro loop's input; ids, no content).
625fn record_claim_friction(error: &CloudError, agent: &str, root: &Path) {
626    use lean_ctx::core::agents::friction;
627    if let CloudError::Task {
628        refusal: TaskRefusal::NotPermitted(check),
629        ..
630    } = error
631    {
632        let signal = match check {
633            crate::error::PermitCheck::Presence => friction::CLAIM_REFUSED_PRESENCE,
634            crate::error::PermitCheck::Role => friction::CLAIM_REFUSED_ROLE,
635            crate::error::PermitCheck::Unknown => friction::CLAIM_REFUSED_PERMIT,
636        };
637        friction::record_for(signal, Some(agent), root.to_str());
638    }
639}
640
641/// Cloud refused for presence or role: whom it found on the bus.
642fn is_permit_refusal(error: &CloudError) -> bool {
643    matches!(
644        error,
645        CloudError::Task {
646            refusal: TaskRefusal::NotPermitted(
647                crate::error::PermitCheck::Presence | crate::error::PermitCheck::Role
648            ),
649            ..
650        }
651    )
652}
653
654/// A presence or role refusal that names whom Cloud looked up: the id the
655/// claim sent, the bus agent it stands for and that worker's role, and
656/// whether the relay announced before the claim was tried again (Cloud
657/// task #27). Any other error stays as it is.
658fn looked_up(link: &Link<'_>, agent: &str, error: CloudError, announced: bool) -> CloudError {
659    let CloudError::Task {
660        refusal,
661        number,
662        detail,
663    } = error
664    else {
665        return error;
666    };
667    if !matches!(refusal, TaskRefusal::NotPermitted(_)) {
668        return CloudError::Task {
669            refusal,
670            number,
671            detail,
672        };
673    }
674    let (sent, role) = link.cloud_identity(agent);
675    let mut line = detail.unwrap_or_else(|| refusal.to_string());
676    line.push_str(&match role {
677        Some(role) => {
678            format!(" LeanCTX Cloud looked up {sent} (the worker of bus agent {agent}, role {role}).")
679        }
680        None if sent == agent && !crate::bus::address::is_worker_id(agent) => format!(
681            " LeanCTX Cloud looked up {sent} as given: this machine's worker book has no worker for it."
682        ),
683        None => format!(" LeanCTX Cloud looked up {sent}."),
684    });
685    if link.announce.is_some() {
686        line.push_str(if announced {
687            " The relay announced again and the claim was tried once more."
688        } else {
689            " No relay answered the request to announce."
690        });
691    }
692    CloudError::Task {
693        refusal,
694        number,
695        detail: Some(line),
696    }
697}
698
699/// The worker gate of a claim (L1): the opt-in it works under, or why not.
700type ClaimGate<'g> = &'g dyn Fn(&TaskScope) -> Result<Admission, Refusal>;
701
702fn claim_via(
703    link: &Link<'_>,
704    number: u64,
705    agent: &str,
706    session_id: &str,
707    minutes: Option<u32>,
708    gate: ClaimGate<'_>,
709    restart: &dyn Fn(),
710) -> Result<ClaimGranted, CloudError> {
711    let minutes = minutes
712        .unwrap_or(DEFAULT_CLAIM_MINUTES)
713        .clamp(MIN_CLAIM_MINUTES, MAX_CLAIM_MINUTES);
714    if let Some(held) = claims::find(link.data_dir, link.vault_id, number)
715        && held.until().is_some_and(|until| until > link.now())
716    {
717        if held.agent != agent {
718            return Err(CloudError::Refused(format!(
719                "task #{number} is claimed on this machine by another agent"
720            )));
721        }
722        // The holder claiming again wants more time: renew, so the answer is
723        // a fresh expiry, not the one it already had. A running session that
724        // holds the claim renews it itself; it is reported as it stands.
725        if held.pid != std::process::id() && lean_ctx::ipc::process::is_alive(held.pid) {
726            return Ok(ClaimGranted {
727                number,
728                until: held.until,
729                minutes: held.minutes,
730            });
731        }
732        let renewed = renew_via(link, number, agent)?;
733        return Ok(ClaimGranted {
734            number,
735            until: renewed.until,
736            minutes: renewed.minutes,
737        });
738    }
739    // The worker gate first (opt-in, scope, pause, today's budget); Cloud
740    // then checks the same opt-in (C0 1.9 §4: `optin_scope`,
741    // `optin_inactive`, `daily_budget`, `optin_changed`). An opt-in that
742    // changed since it was read is read again, once. Every send of this
743    // claim (a resend, the retries below) carries its one key; Cloud keeps
744    // only a granted claim's answer under it, so a refusal is asked anew.
745    let key = write_key();
746    let attempt = || {
747        let admission = gate(&link.scope(number))
748            .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
749        let request = TaskClaimRequestV1 {
750            schema: TASK_CLAIM_REQUEST_SCHEMA.into(),
751            agent: link.cloud_agent(agent),
752            // Without the local key the claim is not sent at all.
753            session_ref: crate::session_ref::uploaded_ses_ref(link.data_dir, session_id)?,
754            minutes,
755            optin_id: admission.optin_id,
756        };
757        link.write_once(&key, |key| {
758            link.call_claim(|api| api.claim(number, &request, key))
759        })
760    };
761    let answer = || match attempt() {
762        Err(CloudError::Task {
763            refusal: TaskRefusal::OptinChanged,
764            ..
765        }) => attempt(),
766        answer => answer,
767    };
768    // Refused for presence or role (task #27): Cloud's presence of the
769    // worker may be stale (a relay that reconnected, a role announced
770    // late). The relay announces now and the claim is tried once more
771    // when it did; a refusal that stands says whom Cloud looked up.
772    let ack = match answer() {
773        Err(error) if is_permit_refusal(&error) => {
774            let announced = link.announce.and_then(|announce| announce(ANNOUNCE_WAIT));
775            let retried = if announced.is_some() {
776                restart();
777                answer()
778            } else {
779                Err(error)
780            };
781            retried.map_err(|error| looked_up(link, agent, error, announced.is_some()))?
782        }
783        answer => answer?,
784    };
785    let until = ack.until.as_str().to_owned();
786    claims::put(
787        link.data_dir,
788        HeldClaim {
789            vault_id: link.vault_id.to_owned(),
790            number,
791            root: link.root.to_string_lossy().into_owned(),
792            agent: agent.to_owned(),
793            claim: ack.claim,
794            until: until.clone(),
795            minutes,
796            pid: std::process::id(),
797        },
798    )?;
799    // The commit this claim starts from (G6 of an S task pins it), and the
800    // session that holds it (it never checks this task's result).
801    claims::trace_claim(
802        link.data_dir,
803        link.vault_id,
804        number,
805        process::acting_identity(agent, link.presence),
806        gate::head_commit(link.root).ok(),
807    )?;
808    Ok(ClaimGranted {
809        number,
810        until,
811        minutes,
812    })
813}
814
815/// Renew the claim this machine holds on `number`.
816fn renew_via(link: &Link<'_>, number: u64, agent: &str) -> Result<HeldClaim, CloudError> {
817    let mut held = link.held(number, agent)?;
818    let request = TaskClaimRenewRequestV1 {
819        schema: TASK_CLAIM_RENEW_SCHEMA.into(),
820        claim: held.claim.clone(),
821        minutes: held.minutes,
822    };
823    let ack = link.settle(number, link.call_claim(|api| api.renew(number, &request)))?;
824    held.claim = ack.claim;
825    ack.until.as_str().clone_into(&mut held.until);
826    if !claims::renewed(link.data_dir, &held)? {
827        return Err(CloudError::Refused(format!(
828            "task #{number} was given back meanwhile; its renewal is not kept"
829        )));
830    }
831    Ok(held)
832}
833
834/// Check the submitted result of task `number` as `agent` (C0 2.2 E48):
835/// `accept` makes it done, `reject` (with its reason) opens it again. The
836/// agent names itself as on its claims; Cloud refuses the agent that did the
837/// work (`self_verify`) and a task that is not submitted.
838pub fn verify(
839    project_root: &Path,
840    number: u64,
841    agent: &str,
842    verdict: TaskVerdict,
843    reason: Option<&str>,
844) -> Result<TaskAckV1, CloudError> {
845    let c = connected(project_root, CloudRight::TasksWork)?;
846    verify_via(&c.link(), number, agent, verdict, reason)
847}
848
849fn verify_via(
850    link: &Link<'_>,
851    number: u64,
852    agent: &str,
853    verdict: TaskVerdict,
854    reason: Option<&str>,
855) -> Result<TaskAckV1, CloudError> {
856    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
857    screened(&[("verify reason", reason)])?;
858    // Checker ≠ author by the per-session identity (process v1 §3.1), and
859    // for a process task a green G6 record of the judged commit with its
860    // locked paths still unchanged (§5): decided here, before anything is
861    // sent.
862    // The checker is the live bus presence `agent`, held by this process
863    // or its app session; never a free string.
864    let task = link.call(|api| api.show(number))?;
865    let checker = process::checker_identity(agent, (link.presence)(agent), task.process.is_some())?;
866    let trace = claims::trace(link.data_dir, link.vault_id, number);
867    process::checker_not_author(&task, &checker, trace.as_ref())?;
868    process::verify_gate(&task, link.root, &link.gate_dirs().work)?;
869    let request = TaskVerifyRequestV1 {
870        schema: TASK_VERIFY_SCHEMA.into(),
871        worker_id: link.cloud_agent(agent),
872        verdict,
873        reason: reason.map(str::to_owned),
874    };
875    let key = blake3::hash(
876        serde_json::to_string(&(link.vault_id, number, &request))
877            .unwrap_or_default()
878            .as_bytes(),
879    )
880    .to_hex()[..32]
881        .to_string();
882    link.call(|api| api.verify(number, &request, &key))
883}
884
885/// [`screened`] for a result: its texts, and every path or symbol name of
886/// its evidence (they leave the machine too).
887fn screened_result(
888    texts: &[(&str, Option<&str>)],
889    evidence: &[EvidenceV1],
890) -> Result<(), CloudError> {
891    let mut fields = texts.to_vec();
892    for item in evidence {
893        let anchor = item.anchor.as_ref();
894        for reference in [
895            item.reference.as_deref(),
896            anchor.map(|a| a.path.as_str()),
897            anchor.and_then(|a| a.symbol.as_deref()),
898        ]
899        .into_iter()
900        .flatten()
901        {
902            fields.push(("evidence", Some(reference)));
903        }
904    }
905    screened(&fields)
906}
907
908/// What an amendment of a result says (see [`amend`]).
909#[derive(Default)]
910pub struct AmendInput {
911    pub summary: Option<String>,
912    pub evidence: Vec<EvidenceInput>,
913    /// A `done` task's merge commit (the merge record).
914    pub merge_commit: Option<String>,
915    pub reason: Option<String>,
916    /// The caller checked this process runs for a registered Queen session
917    /// (`crate::queens::this_session_is_queen`): it may record a merge.
918    pub queen: bool,
919}
920
921/// The Cloud route an amendment needs and no Cloud serves yet.
922pub const AMEND_ROUTE: &str = "POST /v1/vaults/{vault_id}/tasks/{number}/amend";
923
924/// Amend the result of vault task `number` as `agent` (the rules of
925/// [`lean_ctx_protocol::cloud::tasks::amend_rule`] and `may_amend`). Fails
926/// closed: it checks the request, the screening and the task (read only)
927/// and then refuses, sending nothing, because no Cloud serves
928/// [`AMEND_ROUTE`] yet; the task stays unchanged.
929pub fn amend(
930    project_root: &Path,
931    number: u64,
932    agent: &str,
933    input: AmendInput,
934) -> Result<TaskAckV1, CloudError> {
935    let c = connected(project_root, CloudRight::TasksWork)?;
936    amend_via(&c.link(), number, agent, input)
937}
938
939fn amend_via(
940    link: &Link<'_>,
941    number: u64,
942    agent: &str,
943    input: AmendInput,
944) -> Result<TaskAckV1, CloudError> {
945    let input_queen = input.queen;
946    let trimmed =
947        |text: Option<String>| text.map(|t| t.trim().to_owned()).filter(|t| !t.is_empty());
948    let summary = trimmed(input.summary);
949    let reason = trimmed(input.reason);
950    let merge_commit = trimmed(input.merge_commit);
951    let evidence = input
952        .evidence
953        .into_iter()
954        .map(|item| item.into_evidence(link.root))
955        .collect::<Result<Vec<_>, _>>()?;
956    let worker_id = link.cloud_agent(agent);
957    let request = TaskAmendRequestV1 {
958        schema: TASK_AMEND_SCHEMA.into(),
959        worker_id: worker_id.clone(),
960        summary,
961        evidence,
962        merge_commit,
963        reason,
964    };
965    request
966        .validate()
967        .map_err(|e| CloudError::Refused(format!("amendment of task #{number}: {e}")))?;
968    screened_result(
969        &[
970            ("summary", request.summary.as_deref()),
971            ("amend reason", request.reason.as_deref()),
972        ],
973        &request.evidence,
974    )?;
975    let task = link.call(|api| api.show(number))?;
976    let mine = |by: &lean_ctx_protocol::cloud::tasks::TaskActorV1| {
977        by.kind == TaskActorKind::Instance
978            && by.mine
979            && by
980                .agent
981                .as_deref()
982                .is_some_and(|a| a == agent || a == worker_id)
983    };
984    let caller = lean_ctx_protocol::cloud::tasks::AmendCaller {
985        submitter: task.result.as_ref().is_some_and(|r| mine(&r.by)),
986        reviewer: task.verified_by.as_ref().is_some_and(mine),
987        // A vault write always comes from an agent of this Instance.
988        person: false,
989        queen: input_queen,
990    };
991    lean_ctx_protocol::cloud::tasks::may_amend(&request, caller).map_err(|refusal| {
992        CloudError::Refused(format!(
993            "task #{number}: only its submitter corrects a result; a merge record also a person or a coordinator session, never the reviewer ({})",
994            refusal.code()
995        ))
996    })?;
997    lean_ctx_protocol::cloud::tasks::amend_rule(&task, &request).map_err(|refusal| {
998        CloudError::Refused(format!(
999            "task #{number} is {:?}: its result cannot be amended like this ({})",
1000            task.state,
1001            refusal.code()
1002        ))
1003    })?;
1004    Err(CloudError::Refused(format!(
1005        "not supported by LeanCTX Cloud yet: this LeanCTX Cloud server has no route to amend a result ({AMEND_ROUTE}); task #{number} is unchanged"
1006    )))
1007}
1008
1009/// Give task `number` back; `reason` is one line.
1010pub fn release(
1011    project_root: &Path,
1012    number: u64,
1013    agent: &str,
1014    reason: Option<&str>,
1015) -> Result<TaskAckV1, CloudError> {
1016    let c = connected(
1017        &claim_root(project_root, number, agent),
1018        CloudRight::TasksWork,
1019    )?;
1020    release_via(&c.link(), number, agent, reason)
1021}
1022
1023fn release_via(
1024    link: &Link<'_>,
1025    number: u64,
1026    agent: &str,
1027    reason: Option<&str>,
1028) -> Result<TaskAckV1, CloudError> {
1029    let held = link.held(number, agent)?;
1030    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
1031    screened(&[("release reason", reason)])?;
1032    let request = TaskReleaseRequestV1 {
1033        schema: TASK_RELEASE_SCHEMA.into(),
1034        claim: held.claim,
1035        reason: reason.map(str::to_owned),
1036    };
1037    let sent = link.write_once(&write_key(), |key| {
1038        link.call(|api| api.release(number, &request, key))
1039    });
1040    let ack = link.settle(number, sent)?;
1041    claims::remove(link.data_dir, link.vault_id, number)?;
1042    Ok(ack)
1043}
1044
1045/// Report one short summary on the claimed task `number`. When the claim
1046/// lapsed while the agent worked (Cloud: stale claim), the task is claimed
1047/// again for it and the summary sent once more; another agent's claim
1048/// refuses that.
1049pub fn update(
1050    project_root: &Path,
1051    number: u64,
1052    agent: &str,
1053    session_id: &str,
1054    summary: &str,
1055    usage: Option<UsageV1>,
1056) -> Result<TaskAckV1, CloudError> {
1057    let project_root = &claim_root(project_root, number, agent);
1058    let c = connected(project_root, CloudRight::TasksWork)?;
1059    let usage = engine_usage(&c, number, usage);
1060    update_or_reclaim_via(&c.link(), number, agent, summary, usage, || {
1061        claim(project_root, number, agent, session_id, None)
1062    })
1063}
1064
1065fn update_or_reclaim_via(
1066    link: &Link<'_>,
1067    number: u64,
1068    agent: &str,
1069    summary: &str,
1070    usage: Option<UsageV1>,
1071    reclaim: impl FnOnce() -> Result<ClaimGranted, CloudError>,
1072) -> Result<TaskAckV1, CloudError> {
1073    match update_via(link, number, agent, summary, usage) {
1074        Err(CloudError::Task {
1075            refusal: TaskRefusal::StaleClaim,
1076            ..
1077        }) => {
1078            reclaim()?;
1079            update_via(link, number, agent, summary, usage)
1080        }
1081        answer => answer,
1082    }
1083}
1084
1085/// C9: the usage a write carries is the engine's own measure of the claim
1086/// (host sessions at list price), at least what the agent reported; only
1087/// where this machine recorded nothing does the report stand alone.
1088fn engine_usage(c: &Connected, number: u64, reported: Option<UsageV1>) -> Option<UsageV1> {
1089    let measured = dirs::home_dir().and_then(|home| {
1090        let others: Vec<String> = VaultMap::load(c.store.data_dir())
1091            .vaults
1092            .into_values()
1093            .filter(|p| p.vault_id != c.project.vault_id)
1094            .flat_map(|p| p.roots)
1095            .collect();
1096        let now = UtcDateTime::now();
1097        let usage = cloud_use::host_window(&home, &c.project.roots, &others, now);
1098        cloud_use::claim_usage(c.store.data_dir(), &c.project.vault_id, number, now, &usage)
1099    });
1100    match (measured, reported) {
1101        (Some(measured), reported) => Some(UsageV1 {
1102            tokens: measured.tokens.max(reported.map_or(0, |r| r.tokens)),
1103            usd_micros: measured.usd_micros,
1104        }),
1105        (None, reported) => reported,
1106    }
1107}
1108
1109fn update_via(
1110    link: &Link<'_>,
1111    number: u64,
1112    agent: &str,
1113    summary: &str,
1114    usage: Option<UsageV1>,
1115) -> Result<TaskAckV1, CloudError> {
1116    let held = link.held(number, agent)?;
1117    let summary = summary.trim();
1118    screened(&[("summary", Some(summary))])?;
1119    let request = TaskUpdateRequestV1 {
1120        schema: TASK_UPDATE_SCHEMA.into(),
1121        claim: held.claim,
1122        summary: Some(summary.to_owned()),
1123        usage,
1124    };
1125    let sent = link.write_once(&write_key(), |key| {
1126        link.call(|api| api.update(number, &request, key))
1127    });
1128    link.settle(number, sent)
1129}
1130
1131/// Submit the result of the claimed task `number`: it ends the claim. The
1132/// task waits for a second agent's check (`submitted`), or ends at once
1133/// (`done`, or `failed` for [`TaskOutcome::Failed`]).
1134///
1135/// A result never carries a draft: knowledge the work produced travels
1136/// through the capture gate and `cloud sync` like any other (signed E5
1137/// events on a C0 2.0 Cloud, the draft path on 1.x).
1138pub fn submit(
1139    project_root: &Path,
1140    number: u64,
1141    agent: &str,
1142    summary: &str,
1143    evidence: Vec<EvidenceInput>,
1144    usage: Option<UsageV1>,
1145    outcome: TaskOutcome,
1146) -> Result<TaskAckV1, CloudError> {
1147    let c = connected(
1148        &claim_root(project_root, number, agent),
1149        CloudRight::TasksWork,
1150    )?;
1151    let usage = engine_usage(&c, number, usage);
1152    // The gate decides before anything is sent; the usage counts against
1153    // today's budget only once Cloud accepted the result (a refused or
1154    // repeated submit is not counted twice).
1155    let decided = std::cell::RefCell::new(None);
1156    let gate = |_: &TaskScope, evidence: &EvidenceSummary| {
1157        *decided.borrow_mut() = Some(evidence.clone());
1158        Ok(())
1159    };
1160    let ack = submit_via(
1161        &c.link(),
1162        number,
1163        agent,
1164        Submission {
1165            summary,
1166            evidence,
1167            usage,
1168            outcome,
1169        },
1170        &gate,
1171    )?;
1172    if let Some(evidence) = decided.take() {
1173        let _ = worker::admit_submit(&c.store, &evidence);
1174    }
1175    Ok(ack)
1176}
1177
1178/// The worker gate of a result (L1): what it cites and costs, admitted
1179/// before anything is sent.
1180type SubmitGate<'g> = &'g dyn Fn(&TaskScope, &EvidenceSummary) -> Result<(), Refusal>;
1181
1182/// What a result says.
1183struct Submission<'s> {
1184    summary: &'s str,
1185    evidence: Vec<EvidenceInput>,
1186    usage: Option<UsageV1>,
1187    outcome: TaskOutcome,
1188}
1189
1190/// `outcome` as the request carries it. `completed` is never sent (absent
1191/// means completed on every line). `failed` goes only to a Cloud whose
1192/// task views carry the v5 `lifecycle`: a 1.x Cloud denies the unknown
1193/// field, so against it the failure is refused here, before anything is
1194/// sent, and the agent releases the task instead.
1195fn negotiated_outcome(
1196    task: &TaskV1,
1197    number: u64,
1198    outcome: TaskOutcome,
1199) -> Result<Option<TaskOutcome>, CloudError> {
1200    if outcome == TaskOutcome::Completed {
1201        return Ok(None);
1202    }
1203    if task.lifecycle.is_none() {
1204        return Err(CloudError::Refused(format!(
1205            "this LeanCTX Cloud server does not take failed results yet; release task #{number} with a reason instead"
1206        )));
1207    }
1208    Ok(Some(outcome))
1209}
1210
1211fn submit_via(
1212    link: &Link<'_>,
1213    number: u64,
1214    agent: &str,
1215    submission: Submission<'_>,
1216    gate: SubmitGate<'_>,
1217) -> Result<TaskAckV1, CloudError> {
1218    let Submission {
1219        summary,
1220        evidence,
1221        usage,
1222        outcome,
1223    } = submission;
1224    let held = link.held(number, agent)?;
1225    let summary = summary.trim();
1226    let evidence = evidence
1227        .into_iter()
1228        .map(|item| item.into_evidence(link.root))
1229        .collect::<Result<Vec<_>, _>>()?;
1230    screened_result(&[("summary", Some(summary))], &evidence)?;
1231    gate(
1232        &link.scope(number),
1233        &EvidenceSummary {
1234            usage_tokens: usage.map_or(0, |usage| usage.tokens),
1235            usage_usd_micros: usage.and_then(|usage| usage.usd_micros).unwrap_or(0),
1236        },
1237    )
1238    .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
1239    // The task as Cloud has it: its v5 lifecycle (a failed result) and, for
1240    // a process task, what G6 runs. G6 runs here, in the Instance, on the
1241    // claim's worktree; only a green record goes out with the result.
1242    let task = link.call(|api| api.show(number))?;
1243    let trace = claims::trace(link.data_dir, link.vault_id, number);
1244    let gate_record = process::submit_gate(
1245        &task,
1246        link.root,
1247        &link.gate_dirs(),
1248        &evidence,
1249        outcome,
1250        trace.as_ref(),
1251    )?;
1252    let outcome = negotiated_outcome(&task, number, outcome)?;
1253    let commit = gate_record.as_ref().map_or_else(
1254        || {
1255            evidence
1256                .iter()
1257                .find(|e| e.kind == EvidenceKind::Commit)
1258                .and_then(|e| e.reference.clone())
1259        },
1260        |record| Some(record.artifact_commit.clone()),
1261    );
1262    let request = TaskResultRequestV1 {
1263        schema: TASK_RESULT_SCHEMA.into(),
1264        claim: held.claim,
1265        summary: Some(summary.to_owned()),
1266        evidence,
1267        draft: None,
1268        usage,
1269        outcome,
1270        gate_record,
1271    };
1272    let sent = link.write_once(&write_key(), |key| {
1273        link.call(|api| api.result(number, &request, key))
1274    });
1275    let ack = link.settle(number, sent)?;
1276    claims::remove(link.data_dir, link.vault_id, number)?;
1277    // The session that submitted it: a verify on this Instance is checked
1278    // against it (checker ≠ author per session, §3.1). A trace that cannot
1279    // be written leaves the verify refused (no per-session identity),
1280    // never allowed.
1281    let _ = claims::trace_submit(
1282        link.data_dir,
1283        link.vault_id,
1284        number,
1285        process::acting_identity(agent, link.presence),
1286        commit,
1287    );
1288    Ok(ack)
1289}
1290
1291/// Give back every claim this process holds (worker stop, shutdown);
1292/// returns how many Cloud released. A claim Cloud cannot be reached for is
1293/// forgotten here and ends at its expiry there.
1294pub fn release_own_claims(reason: &str) -> usize {
1295    let Ok(store) = CloudStore::open() else {
1296        return 0;
1297    };
1298    let mut released = 0;
1299    for held in claims::own(store.data_dir()) {
1300        let answer = connected(Path::new(&held.root), CloudRight::TasksWork)
1301            .and_then(|c| release_via(&c.link(), held.number, &held.agent, Some(reason)));
1302        if answer.is_ok() {
1303            released += 1;
1304        }
1305        let _ = claims::remove(store.data_dir(), &held.vault_id, held.number);
1306    }
1307    released
1308}
1309
1310/// How many claims this process holds.
1311fn own_claims() -> usize {
1312    CloudStore::open().map_or(0, |store| claims::own(store.data_dir()).len())
1313}
1314
1315/// A session idle this long no longer keeps its claims alive: they end at
1316/// their expiry in Cloud, so a silent agent frees its task quickly.
1317const RENEW_IDLE: std::time::Duration = std::time::Duration::from_mins(30);
1318
1319/// How long the MCP session this process serves has had no tool call in
1320/// flight; `None` while a call runs or when no session is served.
1321pub type IdleClock = fn() -> Option<Duration>;
1322
1323static IDLE_CLOCK: std::sync::OnceLock<IdleClock> = std::sync::OnceLock::new();
1324
1325/// Register the idle clock of the served MCP session (`server::mcp_idle`,
1326/// when it starts serving). The first registration wins. Without one the
1327/// process serves no session and is never idle, so claim renewal runs.
1328pub fn register_idle_clock(clock: IdleClock) {
1329    let _ = IDLE_CLOCK.set(clock);
1330}
1331
1332/// Renew the claims of this process whose half-time has passed, unless the
1333/// process has been idle for [`RENEW_IDLE`] or worker mode is paused here;
1334/// returns how many this process still holds.
1335fn renew_own_due() -> usize {
1336    let Ok(store) = CloudStore::open() else {
1337        return 0;
1338    };
1339    let idle = IDLE_CLOCK
1340        .get()
1341        .and_then(|clock| clock())
1342        .is_some_and(|idle| idle >= RENEW_IDLE);
1343    if idle || crate::worker::read_state(&store).paused {
1344        return claims::own(store.data_dir()).len();
1345    }
1346    for held in claims::own(store.data_dir()) {
1347        let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) else {
1348            continue;
1349        };
1350        let link = c.link();
1351        if held.renew_due(link.now()) {
1352            let _ = renew_via(&link, held.number, &held.agent);
1353        }
1354    }
1355    claims::own(store.data_dir()).len()
1356}
1357
1358/// Take over the unexpired claims `agent` holds on this machine (a new
1359/// session of the same agent) and keep them renewed.
1360pub fn adopt_claims(agent: &str) {
1361    let Ok(store) = CloudStore::open() else {
1362        return;
1363    };
1364    let now = UtcDateTime::now();
1365    if claims::adopt(store.data_dir(), agent, now).is_ok_and(|held| !held.is_empty()) {
1366        keeper::ensure_running();
1367    }
1368}
1369
1370/// Keep CLI claims alive (lean-ctx #3): `lean-ctx cloud tasks claim` ends
1371/// right after claiming, so nothing renewed its claim and an agent running
1372/// a long gate lost it before submitting. The bus relay's process renews a
1373/// claim whose holder has ended at half-time while the claiming agent still
1374/// works on this machine (registered, not finished, active within
1375/// `RENEW_IDLE`), without becoming its holder; once the agent stops
1376/// working the claim ends at its expiry in Cloud. Returns how many such
1377/// claims it kept.
1378pub fn keep_cli_claims() -> usize {
1379    let Ok(store) = CloudStore::open() else {
1380        return 0;
1381    };
1382    if crate::worker::read_state(&store).paused {
1383        return 0;
1384    }
1385    let now = UtcDateTime::now();
1386    let working = working_agents(now);
1387    keep_orphaned(
1388        store.data_dir(),
1389        now,
1390        |agent| working.contains(agent),
1391        |held| {
1392            if let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) {
1393                let _ = renew_via(&c.link(), held.number, &held.agent);
1394            }
1395        },
1396    )
1397}
1398
1399/// Renew the orphaned claims of `working` agents whose half-time has
1400/// passed; returns how many orphaned claims of `working` agents there are.
1401fn keep_orphaned(
1402    data_dir: &Path,
1403    now: lean_ctx_time::UtcDateTime,
1404    working: impl Fn(&str) -> bool,
1405    renew: impl Fn(&HeldClaim),
1406) -> usize {
1407    let kept: Vec<HeldClaim> = claims::orphaned(data_dir, now)
1408        .into_iter()
1409        .filter(|held| working(&held.agent))
1410        .collect();
1411    for held in kept.iter().filter(|held| held.renew_due(now)) {
1412        renew(held);
1413    }
1414    kept.len()
1415}
1416
1417/// The reason Cloud records when the daemon gives an abandoned claim back.
1418pub const ABANDONED_REASON: &str = "the claiming session ended on its machine";
1419
1420/// Give back the claims nobody works on any more (k2 E2E: an ended
1421/// session's claim was neither renewed nor released, so nobody else could
1422/// take the task): a claim that has expired, or whose holding process has
1423/// ended while its agent no longer works on this machine. Runs in the
1424/// daemon (the bus relay's process); returns how many Cloud released.
1425pub fn release_abandoned_claims() -> usize {
1426    let Ok(store) = CloudStore::open() else {
1427        return 0;
1428    };
1429    let now = UtcDateTime::now();
1430    let working = working_agents(now);
1431    give_back_abandoned(
1432        store.data_dir(),
1433        now,
1434        |agent| working.contains(agent),
1435        |held| {
1436            connected(Path::new(&held.root), CloudRight::TasksWork).and_then(|c| {
1437                release_via(&c.link(), held.number, &held.agent, Some(ABANDONED_REASON)).map(|_| ())
1438            })
1439        },
1440    )
1441}
1442
1443/// The bus agents of this machine at work (registered, not finished,
1444/// active within [`RENEW_IDLE`]).
1445fn working_agents(now: lean_ctx_time::UtcDateTime) -> std::collections::HashSet<String> {
1446    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
1447    let idle =
1448        lean_ctx_time::Duration::from_std(RENEW_IDLE).unwrap_or(lean_ctx_time::Duration::MAX);
1449    registry
1450        .list_active(None)
1451        .into_iter()
1452        .filter(|agent| now - agent.last_active < idle)
1453        .map(|agent| agent.agent_id.clone())
1454        .collect()
1455}
1456
1457/// Whether `held` is abandoned at `now`: expired, or its holder process
1458/// ended (not this one) and its agent is not `working`.
1459fn abandoned(
1460    held: &HeldClaim,
1461    now: lean_ctx_time::UtcDateTime,
1462    working: &impl Fn(&str) -> bool,
1463) -> bool {
1464    let expired = held.until().is_none_or(|until| until <= now);
1465    let holder_gone = held.pid != std::process::id() && !lean_ctx::ipc::process::is_alive(held.pid);
1466    expired || (holder_gone && !working(&held.agent))
1467}
1468
1469/// [`release_abandoned_claims`] with the agents at work and the release
1470/// given. A claim Cloud released is gone from the file (`release_via`); an
1471/// expired one Cloud refused is dropped here too (it is over on this
1472/// machine; nothing can renew it). An unexpired one that could not be
1473/// released (offline) is tried again on the next pass.
1474fn give_back_abandoned(
1475    data_dir: &Path,
1476    now: lean_ctx_time::UtcDateTime,
1477    working: impl Fn(&str) -> bool,
1478    release: impl Fn(&HeldClaim) -> Result<(), CloudError>,
1479) -> usize {
1480    let mut released = 0;
1481    for held in claims::all(data_dir)
1482        .into_iter()
1483        .filter(|held| abandoned(held, now, &working))
1484    {
1485        match release(&held) {
1486            Ok(()) => {
1487                released += 1;
1488                // `release_via` removes it; a fake release may not.
1489                let _ = claims::remove(data_dir, &held.vault_id, held.number);
1490            }
1491            Err(error) if held.until().is_none_or(|until| until <= now) => {
1492                tracing::info!(
1493                    "cloud: expired claim of task #{} dropped (LeanCTX Cloud: {error})",
1494                    held.number
1495                );
1496                let _ = claims::remove(data_dir, &held.vault_id, held.number);
1497                crate::metrics::cloud_use::claim_ended(
1498                    data_dir,
1499                    &held.vault_id,
1500                    held.number,
1501                    held.until().unwrap_or(now),
1502                );
1503            }
1504            Err(error) => {
1505                tracing::debug!(
1506                    "cloud: abandoned claim of task #{} kept: {error}",
1507                    held.number
1508                );
1509            }
1510        }
1511    }
1512    released
1513}
1514
1515/// The checkout to act on claim `number` from: `project_root`, unless its
1516/// vault holds no claim of `agent` on `number` while exactly one other
1517/// vault does. An agent's session often runs in another repository than the
1518/// one it claimed in (the claim names its checkout), and the task number
1519/// alone then finds the claim the agent holds.
1520#[must_use]
1521pub fn claim_root(project_root: &Path, number: u64, agent: &str) -> PathBuf {
1522    let Ok(store) = CloudStore::open() else {
1523        return project_root.to_path_buf();
1524    };
1525    claim_root_in(store.data_dir(), project_root, number, agent)
1526}
1527
1528fn claim_root_in(data_dir: &Path, project_root: &Path, number: u64, agent: &str) -> PathBuf {
1529    let here = VaultMap::load(data_dir)
1530        .for_root(&project_root.to_string_lossy())
1531        .map(|vault| vault.vault_id.clone());
1532    let mine: Vec<HeldClaim> = claims::all(data_dir)
1533        .into_iter()
1534        .filter(|held| held.number == number && held.agent == agent)
1535        .collect();
1536    let held_here = mine
1537        .iter()
1538        .any(|held| here.as_deref() == Some(held.vault_id.as_str()));
1539    match mine.as_slice() {
1540        [only] if !held_here => PathBuf::from(&only.root),
1541        _ => project_root.to_path_buf(),
1542    }
1543}
1544
1545/// What a session starts with (H2): the claims this machine holds in the
1546/// project, then its open tasks from the task cache (a refresh is queued
1547/// when they are stale; [`cache`]). `None` when Cloud does not apply or
1548/// there is nothing to say. Never waits for Cloud.
1549pub fn briefing(project_root: &Path) -> Option<String> {
1550    let c = connected(project_root, CloudRight::TasksRead).ok()?;
1551    let mut lines: Vec<String> = {
1552        let link = c.link();
1553        let now = link.now();
1554        claims::all(link.data_dir)
1555            .into_iter()
1556            .filter(|held| {
1557                held.vault_id == link.vault_id && held.until().is_some_and(|until| until > now)
1558            })
1559            .map(|held| {
1560                format!(
1561                    "LeanCTX Cloud task #{} is claimed on this machine for agent {} until {}.",
1562                    held.number, held.agent, held.until
1563                )
1564            })
1565            .collect()
1566    };
1567    lines.extend(cache::open_tasks(c));
1568    (!lines.is_empty()).then(|| lines.join("\n"))
1569}
1570
1571#[cfg(test)]
1572#[path = "tests.rs"]
1573mod tests;