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