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.validate().map_err(|_| {
442            CloudError::Refused(format!(
443                "{} evidence {:?} was refused: {}",
444                self.kind,
445                shown(self.reference.trim()),
446                reference_form(&self.kind)
447            ))
448        })?;
449        Ok(evidence)
450    }
451}
452
453/// What a reference of `kind` looks like, in plain words (rc4-103: an agent
454/// needed four tries because a refusal never said which form was expected).
455fn reference_form(kind: &str) -> &'static str {
456    match kind {
457        "commit" => "a commit reference is a commit SHA, 7 to 64 lowercase hex characters.",
458        "receipt" => "a receipt reference is a LeanCTX receipt id, 64 lowercase hex characters.",
459        "ci_run" => "a ci_run reference is an https:// link to the CI run, or its run id.",
460        "url" => "a url reference is an https:// link without spaces.",
461        "fact" => {
462            "a fact reference is the short id of a fact saved with ctx_knowledge (letters, digits and . _ : - only, no spaces), not a sentence. To cite a sentence, write it in the summary instead."
463        }
464        _ => "see the evidence kinds in the ctx_tasks tool description.",
465    }
466}
467
468/// A reference as a refusal quotes it: at most 80 characters.
469fn shown(reference: &str) -> String {
470    const MAX: usize = 80;
471    if reference.chars().count() <= MAX {
472        return reference.to_owned();
473    }
474    let mut cut: String = reference.chars().take(MAX).collect();
475    cut.push('…');
476    cut
477}
478
479/// Whether every link on the way to `path` (relative, plain names) leads
480/// to a place inside `root`. A link that leads out, or nowhere, is refused
481/// whatever its target is, so the answer never depends on what exists
482/// outside the folder.
483fn links_stay_inside(root: &Path, path: &str) -> bool {
484    let Ok(base) = std::fs::canonicalize(root) else {
485        return true;
486    };
487    let mut at = root.to_path_buf();
488    for part in Path::new(path).components() {
489        at.push(part);
490        match std::fs::symlink_metadata(&at) {
491            Ok(meta) if meta.file_type().is_symlink() => match std::fs::canonicalize(&at) {
492                Ok(target) if target.starts_with(&base) => {}
493                _ => return false,
494            },
495            Ok(_) => {}
496            // Nothing exists here, so nothing below it does either.
497            Err(_) => return true,
498        }
499    }
500    true
501}
502
503/// Why `path` cannot be cited, in plain words; `codes` are the reason codes
504/// of the refused read.
505fn anchor_refusal(root: &Path, path: &str, codes: &str) -> String {
506    use std::path::Component;
507    // Only plain names (and `.`): a Windows prefix like `C:foo`, a root or
508    // `..` never names a file inside the project folder.
509    let relative = !path.is_empty()
510        && Path::new(path)
511            .components()
512            .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
513    let joined = root.join(path);
514    let inside = relative && links_stay_inside(root, path);
515    if !relative || !inside {
516        return "the path must be relative to the project folder and stay inside it".to_owned();
517    }
518    if !std::fs::symlink_metadata(&joined).is_ok_and(|m| m.is_file() || m.file_type().is_symlink())
519    {
520        return format!(
521            "there is no file {path} in the project folder {}",
522            root.display()
523        );
524    }
525    if codes.contains("restricted") {
526        return "the project's rules keep this file's content private".to_owned();
527    }
528    "the project's rules do not allow citing this file, or it is not a text file".to_owned()
529}
530
531/// The anchor of `spec` in `root`: the file is admitted like a source
532/// binding first (a restricted, withheld or unreadable file is never
533/// digested), then digested as it is now.
534fn file_anchor(root: &Path, spec: &str) -> Result<EvidenceV1, CloudError> {
535    use lean_ctx::core::knowledge::anchors;
536    let (path, symbol) = anchors::parse_spec(spec);
537    let root_text = root.to_string_lossy();
538    if let Err(codes) = lean_ctx::core::archive::bindings::source_at(&root_text, path, "ctx_tasks")
539    {
540        return Err(CloudError::Refused(format!(
541            "file_anchor {path:?} was refused: {}. Name a file by its path inside the project folder, for example README.md or src/main.rs (add ::name to point at one function or type).",
542            anchor_refusal(root, path, &codes)
543        )));
544    }
545    let anchor = anchors::capture(root, path, symbol).map_err(CloudError::Refused)?;
546    let evidence = EvidenceV1 {
547        kind: EvidenceKind::FileAnchor,
548        reference: None,
549        anchor: Some(anchor),
550    };
551    evidence
552        .validate()
553        .map_err(|e| CloudError::Refused(format!("evidence: {e}")))?;
554    Ok(evidence)
555}
556
557/// A task list as the Instance shows it.
558///
559/// `partial`: a Cloud answer came back full ([`MAX_TASKS_PAGE`] tasks), so
560/// older tasks of these filters may be missing. The list says so, never
561/// silently incomplete. A list cached before 3.12.3 reads as whole.
562#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]
563pub struct TaskListing {
564    #[serde(flatten)]
565    pub list: TaskListV1,
566    #[serde(default)]
567    pub partial: bool,
568}
569
570/// The project's tasks (shared and coalesced per Instance, [`reads`]).
571/// Only a current list: when Cloud holds reads or is not reachable this is
572/// an error, not the last good list ([`list_read`] serves that with its
573/// age), so no caller takes tasks since claimed or closed for current.
574pub fn list(project_root: &Path, filter: &ListFilter) -> Result<TaskListing, CloudError> {
575    list_read(project_root, filter).and_then(reads::current)
576}
577
578/// [`list`] and, when Cloud holds reads (429) or is not reachable, the age
579/// of the last good list served instead.
580pub fn list_read(
581    project_root: &Path,
582    filter: &ListFilter,
583) -> Result<reads::Read<TaskListing>, CloudError> {
584    let c = connected(project_root, CloudRight::TasksRead)?;
585    list_cached(&c.link(), filter)
586}
587
588fn list_cached(
589    link: &Link<'_>,
590    filter: &ListFilter,
591) -> Result<reads::Read<TaskListing>, CloudError> {
592    let key = format!("list{}", filter.query()?);
593    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
594        list_via(link, filter)
595    })
596}
597
598/// The listing in board order ([`fields::sort_by_priority`]).
599///
600/// Cloud answers one page, the newest tasks by number, so an older high task
601/// can fall off it: the high tasks of the same filters are fetched too and
602/// merged in, each task once, before the sort. That answer is a page too, so
603/// a full one marks the listing `partial`.
604fn list_via(link: &Link<'_>, filter: &ListFilter) -> Result<TaskListing, CloudError> {
605    let mut list = link.call_read(|api| api.list(filter))?;
606    let mut partial = list.tasks.len() >= MAX_TASKS_PAGE;
607    if filter.priority.is_none() {
608        let high = ListFilter {
609            priority: Some(TaskPriority::High),
610            ..filter.clone()
611        };
612        let high = link.call_read(|api| api.list(&high))?;
613        partial |= high.tasks.len() >= MAX_TASKS_PAGE;
614        let seen: std::collections::HashSet<u64> = list.tasks.iter().map(|t| t.number).collect();
615        list.tasks
616            .extend(high.tasks.into_iter().filter(|t| !seen.contains(&t.number)));
617    }
618    fields::sort_by_priority(&mut list.tasks);
619    Ok(TaskListing { list, partial })
620}
621
622/// One task (shared and coalesced per Instance, [`reads`]). Only a current
623/// answer: when Cloud holds reads or is not reachable this is an error, not
624/// the last good answer ([`show_read`] serves that with its age).
625pub fn show(project_root: &Path, number: u64) -> Result<TaskView, CloudError> {
626    show_read(project_root, number).and_then(reads::current)
627}
628
629/// [`show`] and, when Cloud holds reads (429) or is not reachable, the age
630/// of the last good answer served instead. A task Cloud does not know is
631/// [`CloudError::NotFound`]; a rate limit never reads as one.
632pub fn show_read(project_root: &Path, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
633    let c = connected(project_root, CloudRight::TasksRead)?;
634    let link = c.link();
635    show_cached(&link, number)
636}
637
638fn show_cached(link: &Link<'_>, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
639    let key = format!("task#{number}");
640    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
641        link.call_read(|api| api.show(number))
642    })
643    .map(|read| read.map(|task| view_of(link, task)))
644}
645
646/// `task` as the caller sees it, with its local claim (no request).
647fn view_of(link: &Link<'_>, task: TaskV1) -> TaskView {
648    let held_until = claims::find(link.data_dir, link.vault_id, task.number).map(|held| held.until);
649    TaskView { task, held_until }
650}
651
652/// A granted claim, as the caller may see it (no lease id, no token).
653#[derive(Debug, Clone, PartialEq, Eq)]
654pub struct ClaimGranted {
655    pub number: u64,
656    pub until: String,
657    pub minutes: u32,
658}
659
660/// Claim task `number` for bus agent `agent` in session `session_id`.
661pub fn claim(
662    project_root: &Path,
663    number: u64,
664    agent: &str,
665    session_id: &str,
666    minutes: Option<u32>,
667) -> Result<ClaimGranted, CloudError> {
668    let c = connected(project_root, CloudRight::TasksWork)?;
669    let local = lean_ctx::core::config::Config::load().cloud.worker.clone();
670    // The whole claim (opt-in read, claim, its one retry) ends within one
671    // BUDGET, like every task call from a tool.
672    let deadline = std::cell::Cell::new(Instant::now() + BUDGET);
673    // Whether the gate let a request go to Cloud: then an `Ok` is Cloud's
674    // grant (a claim this machine already holds never reaches the gate).
675    let asked = std::cell::Cell::new(false);
676    let gate = |scope: &TaskScope| {
677        let unavailable = |e: CloudError| Refusal::Unavailable(e.to_string());
678        let client = c
679            .session
680            .bounded_client(deadline.get())
681            .map_err(unavailable)?;
682        let optin = worker::fetch_optin_via(&client).map_err(unavailable)?;
683        let admission = worker::admit_claim_for(&c.store, &local, scope, &optin)?;
684        asked.set(true);
685        Ok(admission)
686    };
687    let link = c.link();
688    link.deadline.set(Some(deadline.get()));
689    // A claim tried again after the relay announced gets a fresh BUDGET,
690    // its opt-in read too.
691    let restart = || {
692        deadline.set(Instant::now() + BUDGET);
693        link.deadline.set(Some(deadline.get()));
694    };
695    let granted = claim_via(&link, number, agent, session_id, minutes, &gate, &restart)
696        .inspect_err(|error| record_claim_friction(error, agent, project_root))?;
697    // Counted only once granted: a refused claim costs no task today. The
698    // claim stands either way; Cloud counts it too.
699    if asked.get()
700        && let Err(error) = worker::count_claim(&c.store)
701    {
702        tracing::warn!("cloud worker: a granted claim was not counted here: {error}");
703    }
704    keeper::ensure_running();
705    Ok(granted)
706}
707
708/// Count a claim Cloud refused for presence, role or consent (local
709/// friction log, the retro loop's input; ids, no content).
710fn record_claim_friction(error: &CloudError, agent: &str, root: &Path) {
711    use lean_ctx::core::agents::friction;
712    if let CloudError::Task {
713        refusal: TaskRefusal::NotPermitted(check),
714        ..
715    } = error
716    {
717        let signal = match check {
718            crate::error::PermitCheck::Presence => friction::CLAIM_REFUSED_PRESENCE,
719            crate::error::PermitCheck::Role => friction::CLAIM_REFUSED_ROLE,
720            crate::error::PermitCheck::Unknown => friction::CLAIM_REFUSED_PERMIT,
721        };
722        friction::record_for(signal, Some(agent), root.to_str());
723    }
724}
725
726/// Cloud refused for presence or role: whom it found on the bus.
727fn is_permit_refusal(error: &CloudError) -> bool {
728    matches!(
729        error,
730        CloudError::Task {
731            refusal: TaskRefusal::NotPermitted(
732                crate::error::PermitCheck::Presence | crate::error::PermitCheck::Role
733            ),
734            ..
735        }
736    )
737}
738
739/// A presence or role refusal that names whom Cloud looked up: the id the
740/// claim sent, the bus agent it stands for and that worker's role, and
741/// whether the relay announced before the claim was tried again (Cloud
742/// task #27). Any other error stays as it is.
743fn looked_up(link: &Link<'_>, agent: &str, error: CloudError, announced: bool) -> CloudError {
744    let CloudError::Task {
745        refusal,
746        number,
747        detail,
748    } = error
749    else {
750        return error;
751    };
752    if !matches!(refusal, TaskRefusal::NotPermitted(_)) {
753        return CloudError::Task {
754            refusal,
755            number,
756            detail,
757        };
758    }
759    let (sent, role) = link.cloud_identity(agent);
760    let mut line = detail.unwrap_or_else(|| refusal.to_string());
761    line.push_str(&match role {
762        Some(role) => {
763            format!(" LeanCTX Cloud looked up {sent} (the worker of bus agent {agent}, role {role}).")
764        }
765        None if sent == agent && !crate::bus::address::is_worker_id(agent) => format!(
766            " LeanCTX Cloud looked up {sent} as given: this machine's worker book has no worker for it."
767        ),
768        None => format!(" LeanCTX Cloud looked up {sent}."),
769    });
770    if link.announce.is_some() {
771        line.push_str(if announced {
772            " The relay announced again and the claim was tried once more."
773        } else {
774            " No relay answered the request to announce."
775        });
776    }
777    CloudError::Task {
778        refusal,
779        number,
780        detail: Some(line),
781    }
782}
783
784/// The worker gate of a claim (L1): the opt-in it works under, or why not.
785type ClaimGate<'g> = &'g dyn Fn(&TaskScope) -> Result<Admission, Refusal>;
786
787fn claim_via(
788    link: &Link<'_>,
789    number: u64,
790    agent: &str,
791    session_id: &str,
792    minutes: Option<u32>,
793    gate: ClaimGate<'_>,
794    restart: &dyn Fn(),
795) -> Result<ClaimGranted, CloudError> {
796    let minutes = minutes
797        .unwrap_or(DEFAULT_CLAIM_MINUTES)
798        .clamp(MIN_CLAIM_MINUTES, MAX_CLAIM_MINUTES);
799    if let Some(held) = claims::find(link.data_dir, link.vault_id, number)
800        && held.until().is_some_and(|until| until > link.now())
801    {
802        if held.agent != agent {
803            return Err(CloudError::Refused(format!(
804                "task #{number} is claimed on this machine by another agent"
805            )));
806        }
807        // The holder claiming again wants more time: renew, so the answer is
808        // a fresh expiry, not the one it already had. A running session that
809        // holds the claim renews it itself; it is reported as it stands.
810        if held.pid != std::process::id() && lean_ctx::ipc::process::is_alive(held.pid) {
811            return Ok(ClaimGranted {
812                number,
813                until: held.until,
814                minutes: held.minutes,
815            });
816        }
817        let renewed = renew_via(link, number, agent)?;
818        return Ok(ClaimGranted {
819            number,
820            until: renewed.until,
821            minutes: renewed.minutes,
822        });
823    }
824    // The worker gate first (opt-in, scope, pause, today's budget); Cloud
825    // then checks the same opt-in (C0 1.9 §4: `optin_scope`,
826    // `optin_inactive`, `daily_budget`, `optin_changed`). An opt-in that
827    // changed since it was read is read again, once. Every send of this
828    // claim (a resend, the retries below) carries its one key; Cloud keeps
829    // only a granted claim's answer under it, so a refusal is asked anew.
830    let key = write_key();
831    let attempt = || {
832        let admission = gate(&link.scope(number))
833            .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
834        let request = TaskClaimRequestV1 {
835            schema: TASK_CLAIM_REQUEST_SCHEMA.into(),
836            agent: link.cloud_agent(agent),
837            // Without the local key the claim is not sent at all.
838            session_ref: crate::session_ref::uploaded_ses_ref(link.data_dir, session_id)?,
839            minutes,
840            optin_id: admission.optin_id,
841        };
842        link.write_once(&key, |key| {
843            link.call_claim(|api| api.claim(number, &request, key))
844        })
845    };
846    let answer = || match attempt() {
847        Err(CloudError::Task {
848            refusal: TaskRefusal::OptinChanged,
849            ..
850        }) => attempt(),
851        answer => answer,
852    };
853    // Refused for presence or role (task #27): Cloud's presence of the
854    // worker may be stale (a relay that reconnected, a role announced
855    // late). The relay announces now and the claim is tried once more
856    // when it did; a refusal that stands says whom Cloud looked up.
857    let ack = match answer() {
858        Err(error) if is_permit_refusal(&error) => {
859            let announced = link.announce.and_then(|announce| announce(ANNOUNCE_WAIT));
860            let retried = if announced.is_some() {
861                restart();
862                answer()
863            } else {
864                Err(error)
865            };
866            retried.map_err(|error| looked_up(link, agent, error, announced.is_some()))?
867        }
868        answer => answer?,
869    };
870    let until = ack.until.as_str().to_owned();
871    claims::put(
872        link.data_dir,
873        HeldClaim {
874            vault_id: link.vault_id.to_owned(),
875            number,
876            root: link.root.to_string_lossy().into_owned(),
877            agent: agent.to_owned(),
878            claim: ack.claim,
879            until: until.clone(),
880            minutes,
881            pid: std::process::id(),
882        },
883    )?;
884    // The commit this claim starts from (G6 of an S task pins it), and the
885    // session that holds it (it never checks this task's result).
886    claims::trace_claim(
887        link.data_dir,
888        link.vault_id,
889        number,
890        process::acting_identity(agent, link.presence),
891        gate::head_commit(link.root).ok(),
892    )?;
893    Ok(ClaimGranted {
894        number,
895        until,
896        minutes,
897    })
898}
899
900/// Renew the claim this machine holds on `number`.
901fn renew_via(link: &Link<'_>, number: u64, agent: &str) -> Result<HeldClaim, CloudError> {
902    let mut held = link.held(number, agent)?;
903    let request = TaskClaimRenewRequestV1 {
904        schema: TASK_CLAIM_RENEW_SCHEMA.into(),
905        claim: held.claim.clone(),
906        minutes: held.minutes,
907    };
908    let ack = link.settle(number, link.call_claim(|api| api.renew(number, &request)))?;
909    held.claim = ack.claim;
910    ack.until.as_str().clone_into(&mut held.until);
911    if !claims::renewed(link.data_dir, &held)? {
912        return Err(CloudError::Refused(format!(
913            "task #{number} was given back meanwhile; its renewal is not kept"
914        )));
915    }
916    Ok(held)
917}
918
919/// Check the submitted result of task `number` as `agent` (C0 2.2 E48):
920/// `accept` makes it done, `reject` (with its reason) opens it again. The
921/// agent names itself as on its claims; Cloud refuses the agent that did the
922/// work (`self_verify`) and a task that is not submitted.
923pub fn verify(
924    project_root: &Path,
925    number: u64,
926    agent: &str,
927    verdict: TaskVerdict,
928    reason: Option<&str>,
929) -> Result<TaskAckV1, CloudError> {
930    let c = connected(project_root, CloudRight::TasksWork)?;
931    verify_via(&c.link(), number, agent, verdict, reason)
932}
933
934fn verify_via(
935    link: &Link<'_>,
936    number: u64,
937    agent: &str,
938    verdict: TaskVerdict,
939    reason: Option<&str>,
940) -> Result<TaskAckV1, CloudError> {
941    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
942    screened(&[("verify reason", reason)])?;
943    // Checker ≠ author by the per-session identity (process v1 §3.1), and
944    // for a process task a green G6 record of the judged commit with its
945    // locked paths still unchanged (§5): decided here, before anything is
946    // sent.
947    // The checker is the live bus presence `agent`, held by this process
948    // or its app session; never a free string.
949    let task = link.call(|api| api.show(number))?;
950    let checker = process::checker_identity(agent, (link.presence)(agent), task.process.is_some())?;
951    let trace = claims::trace(link.data_dir, link.vault_id, number);
952    process::checker_not_author(&task, &checker, trace.as_ref())?;
953    process::verify_gate(&task, link.root, &link.gate_dirs().work)?;
954    let request = TaskVerifyRequestV1 {
955        schema: TASK_VERIFY_SCHEMA.into(),
956        worker_id: link.cloud_agent(agent),
957        verdict,
958        reason: reason.map(str::to_owned),
959    };
960    let key = blake3::hash(
961        serde_json::to_string(&(link.vault_id, number, &request))
962            .unwrap_or_default()
963            .as_bytes(),
964    )
965    .to_hex()[..32]
966        .to_string();
967    link.call(|api| api.verify(number, &request, &key))
968}
969
970/// [`screened`] for a result: its texts, and every path or symbol name of
971/// its evidence (they leave the machine too).
972fn screened_result(
973    texts: &[(&str, Option<&str>)],
974    evidence: &[EvidenceV1],
975) -> Result<(), CloudError> {
976    let mut fields = texts.to_vec();
977    for item in evidence {
978        let anchor = item.anchor.as_ref();
979        for reference in [
980            item.reference.as_deref(),
981            anchor.map(|a| a.path.as_str()),
982            anchor.and_then(|a| a.symbol.as_deref()),
983        ]
984        .into_iter()
985        .flatten()
986        {
987            fields.push(("evidence", Some(reference)));
988        }
989    }
990    screened(&fields)
991}
992
993/// What an amendment of a result says (see [`amend`]).
994#[derive(Default)]
995pub struct AmendInput {
996    pub summary: Option<String>,
997    pub evidence: Vec<EvidenceInput>,
998    /// A `done` task's merge commit (the merge record).
999    pub merge_commit: Option<String>,
1000    pub reason: Option<String>,
1001    /// The caller checked this process runs for a registered Queen session
1002    /// (`crate::queens::this_session_is_queen`): it may record a merge.
1003    pub queen: bool,
1004}
1005
1006/// The Cloud route an amendment needs and no Cloud serves yet.
1007pub const AMEND_ROUTE: &str = "POST /v1/vaults/{vault_id}/tasks/{number}/amend";
1008
1009/// Amend the result of vault task `number` as `agent` (the rules of
1010/// [`lean_ctx_protocol::cloud::tasks::amend_rule`] and `may_amend`). Fails
1011/// closed: it checks the request, the screening and the task (read only)
1012/// and then refuses, sending nothing, because no Cloud serves
1013/// [`AMEND_ROUTE`] yet; the task stays unchanged.
1014pub fn amend(
1015    project_root: &Path,
1016    number: u64,
1017    agent: &str,
1018    input: AmendInput,
1019) -> Result<TaskAckV1, CloudError> {
1020    let c = connected(project_root, CloudRight::TasksWork)?;
1021    amend_via(&c.link(), number, agent, input)
1022}
1023
1024fn amend_via(
1025    link: &Link<'_>,
1026    number: u64,
1027    agent: &str,
1028    input: AmendInput,
1029) -> Result<TaskAckV1, CloudError> {
1030    let input_queen = input.queen;
1031    let trimmed =
1032        |text: Option<String>| text.map(|t| t.trim().to_owned()).filter(|t| !t.is_empty());
1033    let summary = trimmed(input.summary);
1034    let reason = trimmed(input.reason);
1035    let merge_commit = trimmed(input.merge_commit);
1036    let evidence = input
1037        .evidence
1038        .into_iter()
1039        .map(|item| item.into_evidence(link.root))
1040        .collect::<Result<Vec<_>, _>>()?;
1041    let worker_id = link.cloud_agent(agent);
1042    let request = TaskAmendRequestV1 {
1043        schema: TASK_AMEND_SCHEMA.into(),
1044        worker_id: worker_id.clone(),
1045        summary,
1046        evidence,
1047        merge_commit,
1048        reason,
1049    };
1050    request
1051        .validate()
1052        .map_err(|e| CloudError::Refused(format!("amendment of task #{number}: {e}")))?;
1053    screened_result(
1054        &[
1055            ("summary", request.summary.as_deref()),
1056            ("amend reason", request.reason.as_deref()),
1057        ],
1058        &request.evidence,
1059    )?;
1060    let task = link.call(|api| api.show(number))?;
1061    let mine = |by: &lean_ctx_protocol::cloud::tasks::TaskActorV1| {
1062        by.kind == TaskActorKind::Instance
1063            && by.mine
1064            && by
1065                .agent
1066                .as_deref()
1067                .is_some_and(|a| a == agent || a == worker_id)
1068    };
1069    let caller = lean_ctx_protocol::cloud::tasks::AmendCaller {
1070        submitter: task.result.as_ref().is_some_and(|r| mine(&r.by)),
1071        reviewer: task.verified_by.as_ref().is_some_and(mine),
1072        // A vault write always comes from an agent of this Instance.
1073        person: false,
1074        queen: input_queen,
1075    };
1076    lean_ctx_protocol::cloud::tasks::may_amend(&request, caller).map_err(|refusal| {
1077        CloudError::Refused(format!(
1078            "task #{number}: only its submitter corrects a result; a merge record also a person or a coordinator session, never the reviewer ({})",
1079            refusal.code()
1080        ))
1081    })?;
1082    lean_ctx_protocol::cloud::tasks::amend_rule(&task, &request).map_err(|refusal| {
1083        CloudError::Refused(format!(
1084            "task #{number} is {:?}: its result cannot be amended like this ({})",
1085            task.state,
1086            refusal.code()
1087        ))
1088    })?;
1089    Err(CloudError::Refused(format!(
1090        "not supported by LeanCTX Cloud yet: this LeanCTX Cloud server has no route to amend a result ({AMEND_ROUTE}); task #{number} is unchanged"
1091    )))
1092}
1093
1094/// Give task `number` back; `reason` is one line.
1095pub fn release(
1096    project_root: &Path,
1097    number: u64,
1098    agent: &str,
1099    reason: Option<&str>,
1100) -> Result<TaskAckV1, CloudError> {
1101    let c = connected(
1102        &claim_root(project_root, number, agent),
1103        CloudRight::TasksWork,
1104    )?;
1105    release_via(&c.link(), number, agent, reason)
1106}
1107
1108fn release_via(
1109    link: &Link<'_>,
1110    number: u64,
1111    agent: &str,
1112    reason: Option<&str>,
1113) -> Result<TaskAckV1, CloudError> {
1114    let held = link.held(number, agent)?;
1115    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
1116    screened(&[("release reason", reason)])?;
1117    let request = TaskReleaseRequestV1 {
1118        schema: TASK_RELEASE_SCHEMA.into(),
1119        claim: held.claim,
1120        reason: reason.map(str::to_owned),
1121    };
1122    let sent = link.write_once(&write_key(), |key| {
1123        link.call(|api| api.release(number, &request, key))
1124    });
1125    let ack = link.settle(number, sent)?;
1126    claims::remove(link.data_dir, link.vault_id, number)?;
1127    Ok(ack)
1128}
1129
1130/// Report one short summary on the claimed task `number`. When the claim
1131/// lapsed while the agent worked (Cloud: stale claim), the task is claimed
1132/// again for it and the summary sent once more; another agent's claim
1133/// refuses that.
1134pub fn update(
1135    project_root: &Path,
1136    number: u64,
1137    agent: &str,
1138    session_id: &str,
1139    summary: &str,
1140    usage: Option<UsageV1>,
1141) -> Result<TaskAckV1, CloudError> {
1142    let project_root = &claim_root(project_root, number, agent);
1143    let c = connected(project_root, CloudRight::TasksWork)?;
1144    let usage = engine_usage(&c, number, usage);
1145    update_or_reclaim_via(&c.link(), number, agent, summary, usage, || {
1146        claim(project_root, number, agent, session_id, None)
1147    })
1148}
1149
1150fn update_or_reclaim_via(
1151    link: &Link<'_>,
1152    number: u64,
1153    agent: &str,
1154    summary: &str,
1155    usage: Option<UsageV1>,
1156    reclaim: impl FnOnce() -> Result<ClaimGranted, CloudError>,
1157) -> Result<TaskAckV1, CloudError> {
1158    match update_via(link, number, agent, summary, usage) {
1159        Err(CloudError::Task {
1160            refusal: TaskRefusal::StaleClaim,
1161            ..
1162        }) => {
1163            reclaim()?;
1164            update_via(link, number, agent, summary, usage)
1165        }
1166        answer => answer,
1167    }
1168}
1169
1170/// C9: the usage a write carries is the engine's own measure of the claim
1171/// (host sessions at list price), at least what the agent reported; only
1172/// where this machine recorded nothing does the report stand alone.
1173fn engine_usage(c: &Connected, number: u64, reported: Option<UsageV1>) -> Option<UsageV1> {
1174    let measured = dirs::home_dir().and_then(|home| {
1175        let others: Vec<String> = VaultMap::load(c.store.data_dir())
1176            .vaults
1177            .into_values()
1178            .filter(|p| p.vault_id != c.project.vault_id)
1179            .flat_map(|p| p.roots)
1180            .collect();
1181        let now = UtcDateTime::now();
1182        let usage = cloud_use::host_window(&home, &c.project.roots, &others, now);
1183        cloud_use::claim_usage(c.store.data_dir(), &c.project.vault_id, number, now, &usage)
1184    });
1185    match (measured, reported) {
1186        (Some(measured), reported) => Some(UsageV1 {
1187            tokens: measured.tokens.max(reported.map_or(0, |r| r.tokens)),
1188            usd_micros: measured.usd_micros,
1189        }),
1190        (None, reported) => reported,
1191    }
1192}
1193
1194fn update_via(
1195    link: &Link<'_>,
1196    number: u64,
1197    agent: &str,
1198    summary: &str,
1199    usage: Option<UsageV1>,
1200) -> Result<TaskAckV1, CloudError> {
1201    let held = link.held(number, agent)?;
1202    let summary = summary.trim();
1203    screened(&[("summary", Some(summary))])?;
1204    let request = TaskUpdateRequestV1 {
1205        schema: TASK_UPDATE_SCHEMA.into(),
1206        claim: held.claim,
1207        summary: Some(summary.to_owned()),
1208        usage,
1209    };
1210    let sent = link.write_once(&write_key(), |key| {
1211        link.call(|api| api.update(number, &request, key))
1212    });
1213    link.settle(number, sent)
1214}
1215
1216/// Submit the result of the claimed task `number`: it ends the claim. The
1217/// task waits for a second agent's check (`submitted`), or ends at once
1218/// (`done`, or `failed` for [`TaskOutcome::Failed`]).
1219///
1220/// A result never carries a draft: knowledge the work produced travels
1221/// through the capture gate and `cloud sync` like any other (signed E5
1222/// events on a C0 2.0 Cloud, the draft path on 1.x).
1223pub fn submit(
1224    project_root: &Path,
1225    number: u64,
1226    agent: &str,
1227    summary: &str,
1228    evidence: Vec<EvidenceInput>,
1229    usage: Option<UsageV1>,
1230    outcome: TaskOutcome,
1231) -> Result<TaskAckV1, CloudError> {
1232    let c = connected(
1233        &claim_root(project_root, number, agent),
1234        CloudRight::TasksWork,
1235    )?;
1236    let usage = engine_usage(&c, number, usage);
1237    // The gate decides before anything is sent; the usage counts against
1238    // today's budget only once Cloud accepted the result (a refused or
1239    // repeated submit is not counted twice).
1240    let decided = std::cell::RefCell::new(None);
1241    let gate = |_: &TaskScope, evidence: &EvidenceSummary| {
1242        *decided.borrow_mut() = Some(evidence.clone());
1243        Ok(())
1244    };
1245    let ack = submit_via(
1246        &c.link(),
1247        number,
1248        agent,
1249        Submission {
1250            summary,
1251            evidence,
1252            usage,
1253            outcome,
1254        },
1255        &gate,
1256    )?;
1257    if let Some(evidence) = decided.take() {
1258        let _ = worker::admit_submit(&c.store, &evidence);
1259    }
1260    Ok(ack)
1261}
1262
1263/// The worker gate of a result (L1): what it cites and costs, admitted
1264/// before anything is sent.
1265type SubmitGate<'g> = &'g dyn Fn(&TaskScope, &EvidenceSummary) -> Result<(), Refusal>;
1266
1267/// What a result says.
1268struct Submission<'s> {
1269    summary: &'s str,
1270    evidence: Vec<EvidenceInput>,
1271    usage: Option<UsageV1>,
1272    outcome: TaskOutcome,
1273}
1274
1275/// `outcome` as the request carries it. `completed` is never sent (absent
1276/// means completed on every line). `failed` goes only to a Cloud whose
1277/// task views carry the v5 `lifecycle`: a 1.x Cloud denies the unknown
1278/// field, so against it the failure is refused here, before anything is
1279/// sent, and the agent releases the task instead.
1280fn negotiated_outcome(
1281    task: &TaskV1,
1282    number: u64,
1283    outcome: TaskOutcome,
1284) -> Result<Option<TaskOutcome>, CloudError> {
1285    if outcome == TaskOutcome::Completed {
1286        return Ok(None);
1287    }
1288    if task.lifecycle.is_none() {
1289        return Err(CloudError::Refused(format!(
1290            "this LeanCTX Cloud server does not take failed results yet; release task #{number} with a reason instead"
1291        )));
1292    }
1293    Ok(Some(outcome))
1294}
1295
1296fn submit_via(
1297    link: &Link<'_>,
1298    number: u64,
1299    agent: &str,
1300    submission: Submission<'_>,
1301    gate: SubmitGate<'_>,
1302) -> Result<TaskAckV1, CloudError> {
1303    let Submission {
1304        summary,
1305        evidence,
1306        usage,
1307        outcome,
1308    } = submission;
1309    let held = link.held(number, agent)?;
1310    let summary = summary.trim();
1311    let evidence = evidence
1312        .into_iter()
1313        .map(|item| item.into_evidence(link.root))
1314        .collect::<Result<Vec<_>, _>>()?;
1315    screened_result(&[("summary", Some(summary))], &evidence)?;
1316    gate(
1317        &link.scope(number),
1318        &EvidenceSummary {
1319            usage_tokens: usage.map_or(0, |usage| usage.tokens),
1320            usage_usd_micros: usage.and_then(|usage| usage.usd_micros).unwrap_or(0),
1321        },
1322    )
1323    .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
1324    // The task as Cloud has it: its v5 lifecycle (a failed result) and, for
1325    // a process task, what G6 runs. G6 runs here, in the Instance, on the
1326    // claim's worktree; only a green record goes out with the result.
1327    let task = link.call(|api| api.show(number))?;
1328    let trace = claims::trace(link.data_dir, link.vault_id, number);
1329    let gate_record = process::submit_gate(
1330        &task,
1331        link.root,
1332        &link.gate_dirs(),
1333        &evidence,
1334        outcome,
1335        trace.as_ref(),
1336    )?;
1337    let outcome = negotiated_outcome(&task, number, outcome)?;
1338    let commit = gate_record.as_ref().map_or_else(
1339        || {
1340            evidence
1341                .iter()
1342                .find(|e| e.kind == EvidenceKind::Commit)
1343                .and_then(|e| e.reference.clone())
1344        },
1345        |record| Some(record.artifact_commit.clone()),
1346    );
1347    let request = TaskResultRequestV1 {
1348        schema: TASK_RESULT_SCHEMA.into(),
1349        claim: held.claim,
1350        summary: Some(summary.to_owned()),
1351        evidence,
1352        draft: None,
1353        usage,
1354        outcome,
1355        gate_record,
1356    };
1357    let sent = link.write_once(&write_key(), |key| {
1358        link.call(|api| api.result(number, &request, key))
1359    });
1360    let ack = link.settle(number, sent)?;
1361    claims::remove(link.data_dir, link.vault_id, number)?;
1362    // The session that submitted it: a verify on this Instance is checked
1363    // against it (checker ≠ author per session, §3.1). A trace that cannot
1364    // be written leaves the verify refused (no per-session identity),
1365    // never allowed.
1366    let _ = claims::trace_submit(
1367        link.data_dir,
1368        link.vault_id,
1369        number,
1370        process::acting_identity(agent, link.presence),
1371        commit,
1372    );
1373    Ok(ack)
1374}
1375
1376/// Give back every claim this process holds (worker stop, shutdown);
1377/// returns how many Cloud released. A claim Cloud cannot be reached for is
1378/// forgotten here and ends at its expiry there.
1379pub fn release_own_claims(reason: &str) -> usize {
1380    let Ok(store) = CloudStore::open() else {
1381        return 0;
1382    };
1383    let mut released = 0;
1384    for held in claims::own(store.data_dir()) {
1385        let answer = connected(Path::new(&held.root), CloudRight::TasksWork)
1386            .and_then(|c| release_via(&c.link(), held.number, &held.agent, Some(reason)));
1387        if answer.is_ok() {
1388            released += 1;
1389        }
1390        let _ = claims::remove(store.data_dir(), &held.vault_id, held.number);
1391    }
1392    released
1393}
1394
1395/// How many claims this process holds.
1396fn own_claims() -> usize {
1397    CloudStore::open().map_or(0, |store| claims::own(store.data_dir()).len())
1398}
1399
1400/// A session idle this long no longer keeps its claims alive: they end at
1401/// their expiry in Cloud, so a silent agent frees its task quickly.
1402const RENEW_IDLE: std::time::Duration = std::time::Duration::from_mins(30);
1403
1404/// How long the MCP session this process serves has had no tool call in
1405/// flight; `None` while a call runs or when no session is served.
1406pub type IdleClock = fn() -> Option<Duration>;
1407
1408static IDLE_CLOCK: std::sync::OnceLock<IdleClock> = std::sync::OnceLock::new();
1409
1410/// Register the idle clock of the served MCP session (`server::mcp_idle`,
1411/// when it starts serving). The first registration wins. Without one the
1412/// process serves no session and is never idle, so claim renewal runs.
1413pub fn register_idle_clock(clock: IdleClock) {
1414    let _ = IDLE_CLOCK.set(clock);
1415}
1416
1417/// Renew the claims of this process whose half-time has passed, unless the
1418/// process has been idle for [`RENEW_IDLE`] or worker mode is paused here;
1419/// returns how many this process still holds.
1420fn renew_own_due() -> usize {
1421    let Ok(store) = CloudStore::open() else {
1422        return 0;
1423    };
1424    let idle = IDLE_CLOCK
1425        .get()
1426        .and_then(|clock| clock())
1427        .is_some_and(|idle| idle >= RENEW_IDLE);
1428    if idle || crate::worker::read_state(&store).paused {
1429        return claims::own(store.data_dir()).len();
1430    }
1431    for held in claims::own(store.data_dir()) {
1432        let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) else {
1433            continue;
1434        };
1435        let link = c.link();
1436        if held.renew_due(link.now()) {
1437            let _ = renew_via(&link, held.number, &held.agent);
1438        }
1439    }
1440    claims::own(store.data_dir()).len()
1441}
1442
1443/// Take over the unexpired claims `agent` holds on this machine (a new
1444/// session of the same agent) and keep them renewed.
1445pub fn adopt_claims(agent: &str) {
1446    let Ok(store) = CloudStore::open() else {
1447        return;
1448    };
1449    let now = UtcDateTime::now();
1450    if claims::adopt(store.data_dir(), agent, now).is_ok_and(|held| !held.is_empty()) {
1451        keeper::ensure_running();
1452    }
1453}
1454
1455/// Keep CLI claims alive (lean-ctx #3): `lean-ctx cloud tasks claim` ends
1456/// right after claiming, so nothing renewed its claim and an agent running
1457/// a long gate lost it before submitting. The bus relay's process renews a
1458/// claim whose holder has ended at half-time while the claiming agent still
1459/// works on this machine (registered, not finished, active within
1460/// `RENEW_IDLE`), without becoming its holder; once the agent stops
1461/// working the claim ends at its expiry in Cloud. Returns how many such
1462/// claims it kept.
1463pub fn keep_cli_claims() -> usize {
1464    let Ok(store) = CloudStore::open() else {
1465        return 0;
1466    };
1467    if crate::worker::read_state(&store).paused {
1468        return 0;
1469    }
1470    let now = UtcDateTime::now();
1471    let working = working_agents(now);
1472    keep_orphaned(
1473        store.data_dir(),
1474        now,
1475        |agent| working.contains(agent),
1476        |held| {
1477            if let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) {
1478                let _ = renew_via(&c.link(), held.number, &held.agent);
1479            }
1480        },
1481    )
1482}
1483
1484/// Renew the orphaned claims of `working` agents whose half-time has
1485/// passed; returns how many orphaned claims of `working` agents there are.
1486fn keep_orphaned(
1487    data_dir: &Path,
1488    now: lean_ctx_time::UtcDateTime,
1489    working: impl Fn(&str) -> bool,
1490    renew: impl Fn(&HeldClaim),
1491) -> usize {
1492    let kept: Vec<HeldClaim> = claims::orphaned(data_dir, now)
1493        .into_iter()
1494        .filter(|held| working(&held.agent))
1495        .collect();
1496    for held in kept.iter().filter(|held| held.renew_due(now)) {
1497        renew(held);
1498    }
1499    kept.len()
1500}
1501
1502/// The reason Cloud records when the daemon gives an abandoned claim back.
1503pub const ABANDONED_REASON: &str = "the claiming session ended on its machine";
1504
1505/// Give back the claims nobody works on any more (k2 E2E: an ended
1506/// session's claim was neither renewed nor released, so nobody else could
1507/// take the task): a claim that has expired, or whose holding process has
1508/// ended while its agent no longer works on this machine. Runs in the
1509/// daemon (the bus relay's process); returns how many Cloud released.
1510pub fn release_abandoned_claims() -> usize {
1511    let Ok(store) = CloudStore::open() else {
1512        return 0;
1513    };
1514    let now = UtcDateTime::now();
1515    let working = working_agents(now);
1516    give_back_abandoned(
1517        store.data_dir(),
1518        now,
1519        |agent| working.contains(agent),
1520        |held| {
1521            connected(Path::new(&held.root), CloudRight::TasksWork).and_then(|c| {
1522                release_via(&c.link(), held.number, &held.agent, Some(ABANDONED_REASON)).map(|_| ())
1523            })
1524        },
1525    )
1526}
1527
1528/// The bus agents of this machine at work (registered, not finished,
1529/// active within [`RENEW_IDLE`]).
1530fn working_agents(now: lean_ctx_time::UtcDateTime) -> std::collections::HashSet<String> {
1531    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
1532    let idle =
1533        lean_ctx_time::Duration::from_std(RENEW_IDLE).unwrap_or(lean_ctx_time::Duration::MAX);
1534    registry
1535        .list_active(None)
1536        .into_iter()
1537        .filter(|agent| now - agent.last_active < idle)
1538        .map(|agent| agent.agent_id.clone())
1539        .collect()
1540}
1541
1542/// Whether `held` is abandoned at `now`: expired, or its holder process
1543/// ended (not this one) and its agent is not `working`.
1544fn abandoned(
1545    held: &HeldClaim,
1546    now: lean_ctx_time::UtcDateTime,
1547    working: &impl Fn(&str) -> bool,
1548) -> bool {
1549    let expired = held.until().is_none_or(|until| until <= now);
1550    let holder_gone = held.pid != std::process::id() && !lean_ctx::ipc::process::is_alive(held.pid);
1551    expired || (holder_gone && !working(&held.agent))
1552}
1553
1554/// [`release_abandoned_claims`] with the agents at work and the release
1555/// given. A claim Cloud released is gone from the file (`release_via`); an
1556/// expired one Cloud refused is dropped here too (it is over on this
1557/// machine; nothing can renew it). An unexpired one that could not be
1558/// released (offline) is tried again on the next pass.
1559fn give_back_abandoned(
1560    data_dir: &Path,
1561    now: lean_ctx_time::UtcDateTime,
1562    working: impl Fn(&str) -> bool,
1563    release: impl Fn(&HeldClaim) -> Result<(), CloudError>,
1564) -> usize {
1565    let mut released = 0;
1566    for held in claims::all(data_dir)
1567        .into_iter()
1568        .filter(|held| abandoned(held, now, &working))
1569    {
1570        match release(&held) {
1571            Ok(()) => {
1572                released += 1;
1573                // `release_via` removes it; a fake release may not.
1574                let _ = claims::remove(data_dir, &held.vault_id, held.number);
1575            }
1576            Err(error) if held.until().is_none_or(|until| until <= now) => {
1577                tracing::info!(
1578                    "cloud: expired claim of task #{} dropped (LeanCTX Cloud: {error})",
1579                    held.number
1580                );
1581                let _ = claims::remove(data_dir, &held.vault_id, held.number);
1582                crate::metrics::cloud_use::claim_ended(
1583                    data_dir,
1584                    &held.vault_id,
1585                    held.number,
1586                    held.until().unwrap_or(now),
1587                );
1588            }
1589            Err(error) => {
1590                tracing::debug!(
1591                    "cloud: abandoned claim of task #{} kept: {error}",
1592                    held.number
1593                );
1594            }
1595        }
1596    }
1597    released
1598}
1599
1600/// The checkout to act on claim `number` from: `project_root`, unless its
1601/// vault holds no claim of `agent` on `number` while exactly one other
1602/// vault does. An agent's session often runs in another repository than the
1603/// one it claimed in (the claim names its checkout), and the task number
1604/// alone then finds the claim the agent holds.
1605#[must_use]
1606pub fn claim_root(project_root: &Path, number: u64, agent: &str) -> PathBuf {
1607    let Ok(store) = CloudStore::open() else {
1608        return project_root.to_path_buf();
1609    };
1610    claim_root_in(store.data_dir(), project_root, number, agent)
1611}
1612
1613fn claim_root_in(data_dir: &Path, project_root: &Path, number: u64, agent: &str) -> PathBuf {
1614    let here = VaultMap::load(data_dir)
1615        .for_root(&project_root.to_string_lossy())
1616        .map(|vault| vault.vault_id.clone());
1617    let mine: Vec<HeldClaim> = claims::all(data_dir)
1618        .into_iter()
1619        .filter(|held| held.number == number && held.agent == agent)
1620        .collect();
1621    let held_here = mine
1622        .iter()
1623        .any(|held| here.as_deref() == Some(held.vault_id.as_str()));
1624    match mine.as_slice() {
1625        [only] if !held_here => PathBuf::from(&only.root),
1626        _ => project_root.to_path_buf(),
1627    }
1628}
1629
1630/// What a session starts with (H2): the claims this machine holds in the
1631/// project, then its open tasks from the task cache (a refresh is queued
1632/// when they are stale; [`cache`]). `None` when Cloud does not apply or
1633/// there is nothing to say. Never waits for Cloud.
1634pub fn briefing(project_root: &Path) -> Option<String> {
1635    let c = connected(project_root, CloudRight::TasksRead).ok()?;
1636    let mut lines: Vec<String> = {
1637        let link = c.link();
1638        let now = link.now();
1639        claims::all(link.data_dir)
1640            .into_iter()
1641            .filter(|held| {
1642                held.vault_id == link.vault_id && held.until().is_some_and(|until| until > now)
1643            })
1644            .map(|held| {
1645                format!(
1646                    "LeanCTX Cloud task #{} is claimed on this machine for agent {} until {}.",
1647                    held.number, held.agent, held.until
1648                )
1649            })
1650            .collect()
1651    };
1652    lines.extend(cache::open_tasks(c));
1653    (!lines.is_empty()).then(|| lines.join("\n"))
1654}
1655
1656#[cfg(test)]
1657#[path = "tests.rs"]
1658mod tests;