Skip to main content

lean_ctx/core/hive/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//! - Every call made from a tool call ends within [`BUDGET`]; offline or a
7//!   lapsed lease answers at once, local work is never blocked.
8//! - A claim passes the worker gate first ([`worker::admit_claim`], L1:
9//!   the engine's opt-in for the repo, pause, today's budget) and goes out
10//!   under that opt-in; a result passes [`worker::admit_submit`]. Hive
11//!   checks the same opt-in again (`optin_scope`, `optin_inactive`,
12//!   `daily_budget`, `optin_changed`, `vetoed`); every refusal is shown as
13//!   it is, an `optin_changed` claim reads the opt-in again once, and a
14//!   stopped opt-in ends this machine's claims.
15//! - The claim's lease id and fencing token stay on this machine
16//!   ([`claims`], 0600) and are never printed. This process renews its
17//!   claims while it runs (`keeper`) and gives them back on stop.
18//! - Text leaving the machine (summaries, proposals, release reasons) passes
19//!   the outbox screening; a text it refuses is not sent, never rewritten.
20//!   Sealed projects send it sealed (AAD `vault_id|number|epoch|schema`).
21//! - Text arriving from Hive (titles, goals, summaries of people and other
22//!   agents) reaches the agent only fenced as foreign data
23//!   ([`crate::core::hive::untrusted::wrap`], X5).
24//! - Hive announces claims, releases and results on the bus itself; the
25//!   engine sends no task frames.
26
27pub mod claims;
28mod client;
29mod keeper;
30pub mod propose;
31mod render;
32
33use std::path::{Path, PathBuf};
34use std::time::{Duration, Instant};
35
36use chrono::{DateTime, Utc};
37use serde::{Deserialize, Serialize, de::DeserializeOwned};
38
39use crate::core::hive::HiveError;
40use crate::core::hive::TaskRefusal;
41use crate::core::hive::auth::Session;
42use crate::core::hive::config::HiveConfig;
43use crate::core::hive::knowledge::screening::Screen;
44use crate::core::hive::metrics::hive_use;
45use crate::core::hive::sealed;
46use crate::core::hive::state::HiveStore;
47use crate::core::hive::vault::{VaultMap, VaultRecord};
48use crate::core::hive::worker::{self, Admission, EvidenceSummary, Refusal, TaskKind, TaskScope};
49use claims::HeldClaim;
50use client::TasksApi;
51use lean_ctx_protocol::hive::lease::{HiveRight, LeaseState};
52use lean_ctx_protocol::hive::sealed::SealedBlobV1;
53use lean_ctx_protocol::hive::tasks::{
54    EvidenceKind, EvidenceV1, MAX_CLAIM_MINUTES, MIN_CLAIM_MINUTES, SEALED_TASK_RESULT_SCHEMA,
55    SEALED_TASK_UPDATE_SCHEMA, TASK_CLAIM_RENEW_SCHEMA, TASK_CLAIM_REQUEST_SCHEMA,
56    TASK_RELEASE_SCHEMA, TASK_RESULT_SCHEMA, TASK_UPDATE_SCHEMA, TaskAckV1,
57    TaskClaimRenewRequestV1, TaskClaimRequestV1, TaskListV1, TaskOutcome, TaskReleaseRequestV1,
58    TaskResultRequestV1, TaskUpdateRequestV1, TaskV1, UsageV1,
59};
60
61pub use client::ListFilter;
62pub use render::{render_list, render_result_ack, render_task};
63
64/// The time one task call made from a tool call may take in all.
65pub const BUDGET: Duration = Duration::from_secs(5);
66/// The session-start briefing waits less: it delays the first tool call.
67pub const BRIEFING_BUDGET: Duration = Duration::from_secs(2);
68/// Claim length when the caller names none.
69pub const DEFAULT_CLAIM_MINUTES: u32 = 10;
70
71/// A connected machine, its lease and the Hive project of a local root.
72pub struct Connected {
73    pub store: HiveStore,
74    pub session: Session,
75    pub project: VaultRecord,
76    pub root: PathBuf,
77}
78
79/// Whether tasks apply to `project_root` with `right`; `Err` says why not
80/// (no request made).
81pub fn connected(project_root: &Path, right: HiveRight) -> Result<Connected, HiveError> {
82    let config = crate::core::config::Config::load().hive.clone();
83    connected_with(&config, HiveStore::open()?, project_root, right)
84}
85
86fn connected_with(
87    config: &HiveConfig,
88    store: HiveStore,
89    project_root: &Path,
90    right: HiveRight,
91) -> Result<Connected, HiveError> {
92    if config.enabled == Some(false) {
93        return Err(HiveError::Config(
94            "Hive is off ([hive] enabled = false)".into(),
95        ));
96    }
97    let instance = store.instance()?.ok_or(HiveError::NotConnected)?;
98    let root = project_root.to_string_lossy();
99    let project = VaultMap::load(store.data_dir())
100        .for_root(&root)
101        .cloned()
102        .ok_or_else(|| {
103            HiveError::Config(
104                "this repository is not linked to a vault (run `lean-ctx hive sync` in it)".into(),
105            )
106        })?;
107    let session = Session::load(store.clone(), config.root_key(&instance.url)?)?;
108    if !matches!(
109        session.lease.state_at(Utc::now()),
110        LeaseState::Valid | LeaseState::Grace
111    ) {
112        return Err(HiveError::LeaseLapsed);
113    }
114    if !session.lease.lease.grants(right) {
115        return Err(HiveError::Forbidden);
116    }
117    Ok(Connected {
118        store,
119        session,
120        project,
121        root: project_root.to_path_buf(),
122    })
123}
124
125impl Connected {
126    fn link(&self) -> Link<'_> {
127        Link {
128            data_dir: self.store.data_dir(),
129            vault_id: &self.project.vault_id,
130            sealed: self.project.sealed,
131            root: &self.root,
132            via: Via::Session(&self.session),
133            budget: BUDGET,
134            deadline: None,
135        }
136    }
137}
138
139/// How a call reaches Hive: the enrolled session, or (tests) a local fake.
140enum Via<'a> {
141    Session(&'a Session),
142    #[cfg(test)]
143    Origin(String),
144}
145
146/// Everything one task operation needs.
147struct Link<'a> {
148    data_dir: &'a Path,
149    vault_id: &'a str,
150    sealed: bool,
151    root: &'a Path,
152    via: Via<'a>,
153    budget: Duration,
154    /// One deadline for every request of a call (a claim: opt-in read,
155    /// claim and its one retry); `None`: each request gets `budget`.
156    deadline: Option<Instant>,
157}
158
159impl Link<'_> {
160    fn call<T>(
161        &self,
162        call: impl FnOnce(&TasksApi<'_>) -> Result<T, HiveError>,
163    ) -> Result<T, HiveError> {
164        let deadline = self
165            .deadline
166            .unwrap_or_else(|| Instant::now() + self.budget);
167        let client = match &self.via {
168            Via::Session(session) => session.bounded_client(deadline)?,
169            #[cfg(test)]
170            Via::Origin(origin) => {
171                crate::core::hive::transport::HiveClient::bounded(origin, self.budget)?
172            }
173        };
174        let result = call(&TasksApi {
175            client: &client,
176            vault_id: self.vault_id,
177        });
178        match &self.via {
179            Via::Session(session) => result.map_err(|e| session.noted(e)),
180            #[cfg(test)]
181            Via::Origin(_) => result,
182        }
183    }
184
185    /// [`Self::call`] for a claim or its renewal: while a quota or policy
186    /// throttle holds task claims nothing is asked (the refusal says until
187    /// when); a `quota_exceeded`/`policy_denied` answer sets one.
188    fn call_claim<T>(
189        &self,
190        call: impl FnOnce(&TasksApi<'_>) -> Result<T, HiveError>,
191    ) -> Result<T, HiveError> {
192        use crate::core::hive::throttle::{self, Scope};
193        let store = match &self.via {
194            Via::Session(session) => &session.store,
195            #[cfg(test)]
196            Via::Origin(_) => return self.call(call),
197        };
198        throttle::check(store, Scope::Tasks, chrono::Utc::now())?;
199        match self.call(call) {
200            Ok(value) => {
201                throttle::passed(store, Scope::Tasks);
202                Ok(value)
203            }
204            Err(error) => Err(throttle::note(
205                store,
206                Scope::Tasks,
207                error,
208                chrono::Utc::now(),
209            )),
210        }
211    }
212
213    /// Now on the service's clock (claim ends are service time).
214    fn now(&self) -> DateTime<Utc> {
215        match &self.via {
216            Via::Session(session) => session.lease.service_time(Utc::now()).with_timezone(&Utc),
217            #[cfg(test)]
218            Via::Origin(_) => Utc::now(),
219        }
220    }
221
222    fn session(&self) -> Result<&Session, HiveError> {
223        match &self.via {
224            Via::Session(session) => Ok(session),
225            #[cfg(test)]
226            Via::Origin(_) => Err(HiveError::NotConnected),
227        }
228    }
229
230    /// Seal `content` for task `number` (0 for a proposal).
231    fn seal<T: Serialize>(
232        &self,
233        number: u64,
234        content_schema: &str,
235        content: &T,
236    ) -> Result<SealedBlobV1, HiveError> {
237        // Only a key this machine already holds: a tool call never fetches
238        // keys or rotates the repo (that is `lean-ctx hive sync`). A key
239        // Hive has moved past is refused there, and nothing leaves.
240        let session = self.session()?;
241        let held = sealed::newest_held_epoch(&session.store, self.vault_id)?.and_then(|epoch| {
242            sealed::held_key(&session.store, self.vault_id, epoch).map(|key| (epoch, key))
243        });
244        let Some((epoch, key)) = held else {
245            return Err(HiveError::Refused(
246                "this sealed vault's key is not on this machine yet; run `lean-ctx hive sync`"
247                    .into(),
248            ));
249        };
250        let bytes = zeroize::Zeroizing::new(
251            serde_json::to_vec(content).map_err(|e| HiveError::Local(e.to_string()))?,
252        );
253        sealed::seal(&key, self.vault_id, number, epoch, content_schema, &bytes)
254    }
255
256    /// Open the sealed `blob` of task `number`; `None` when this machine
257    /// holds no key for its epoch.
258    fn open<T: DeserializeOwned>(&self, number: u64, blob: &SealedBlobV1) -> Option<T> {
259        let session = self.session().ok()?;
260        let key = sealed::held_key(&session.store, self.vault_id, blob.epoch)?;
261        let bytes = sealed::open(&key, self.vault_id, number, blob).ok()?;
262        serde_json::from_slice(&bytes).ok()
263    }
264
265    /// Task `number` of this project as the worker gate sees it.
266    fn scope(&self, number: u64) -> TaskScope {
267        TaskScope {
268            task_id: number.to_string(),
269            vault_id: self.vault_id.to_owned(),
270            kind: TaskKind::Org,
271        }
272    }
273
274    /// The claim `agent` holds on task `number`: never another agent's, so
275    /// no agent writes under another's fencing token. The process that
276    /// renews it does not matter: the agent's CLI and its session (or the
277    /// relay that kept a CLI claim alive) act for the same agent, and the
278    /// claims file is this user's alone (0600).
279    fn held(&self, number: u64, agent: &str) -> Result<HeldClaim, HiveError> {
280        match claims::find(self.data_dir, self.vault_id, number) {
281            Some(held) if held.agent == agent => Ok(held),
282            Some(_) => Err(HiveError::Refused(format!(
283                "task #{number} is claimed on this machine by another agent"
284            ))),
285            None => Err(HiveError::Refused(format!(
286                "this machine holds no claim on task #{number}"
287            ))),
288        }
289    }
290
291    /// Forget the local claim when Hive says it is gone for good.
292    fn settle<T>(&self, number: u64, answer: Result<T, HiveError>) -> Result<T, HiveError> {
293        let gone = match &answer {
294            Err(HiveError::Task { refusal, .. }) => refusal.ends_claim(),
295            Err(HiveError::NotFound | HiveError::Vetoed) => true,
296            _ => false,
297        };
298        if gone {
299            if matches!(
300                &answer,
301                Err(HiveError::Task {
302                    refusal: TaskRefusal::StaleClaim,
303                    ..
304                })
305            ) {
306                let agent =
307                    claims::find(self.data_dir, self.vault_id, number).map(|held| held.agent);
308                crate::core::agents::friction::record_for(
309                    crate::core::agents::friction::CLAIM_EXPIRED,
310                    agent.as_deref(),
311                    self.root.to_str(),
312                );
313            }
314            let _ = claims::remove(self.data_dir, self.vault_id, number);
315        }
316        answer
317    }
318}
319
320/// `{title, goal?, acceptance}` of a sealed task.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322pub struct TaskContent {
323    pub title: String,
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub goal: Option<String>,
326    pub acceptance: String,
327}
328
329/// `{summary}` of a sealed update.
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331struct SealedSummary {
332    summary: String,
333}
334
335/// `{summary, evidence}` of a sealed result.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337struct SealedResult {
338    summary: String,
339    evidence: Vec<EvidenceV1>,
340}
341
342/// A task as the agent reads it: the view, its sealed parts opened.
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct TaskView {
345    pub task: TaskV1,
346    /// The opened content of a sealed task.
347    pub content: Option<TaskContent>,
348    /// The opened summary of each sealed update, in order.
349    pub update_summaries: Vec<Option<String>>,
350    /// The claim end when this machine holds the claim.
351    pub held_until: Option<String>,
352}
353
354/// Screen every outgoing `(field, text)`; the first refusal names the field
355/// and the reason, never the text.
356fn screened(fields: &[(&str, Option<&str>)]) -> Result<(), HiveError> {
357    let mut screen = Screen::for_installation();
358    for (field, text) in fields {
359        if let Some(text) = text
360            && let Err(blocked) = screen.check(text)
361        {
362            return Err(HiveError::Refused(format!(
363                "the {field} was not sent: it contains {blocked}"
364            )));
365        }
366    }
367    Ok(())
368}
369
370/// One piece of evidence as a caller names it.
371#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
372pub struct EvidenceInput {
373    pub kind: String,
374    pub reference: String,
375}
376
377impl EvidenceInput {
378    /// `root` is the checkout a `file_anchor` (`path` or `path::symbol`) is
379    /// digested in, as it is now (J2 anchors).
380    fn into_evidence(self, root: &Path) -> Result<EvidenceV1, HiveError> {
381        let kind = match self.kind.as_str() {
382            "receipt" => EvidenceKind::Receipt,
383            "commit" => EvidenceKind::Commit,
384            "ci_run" => EvidenceKind::CiRun,
385            "url" => EvidenceKind::Url,
386            "fact" => EvidenceKind::Fact,
387            "file_anchor" => return file_anchor(root, self.reference.trim()),
388            other => {
389                return Err(HiveError::Refused(format!(
390                    "unknown evidence kind {other:?} (receipt, commit, ci_run, file_anchor, url, fact)"
391                )));
392            }
393        };
394        let evidence = EvidenceV1 {
395            kind,
396            reference: Some(self.reference.trim().to_owned()),
397            anchor: None,
398        };
399        evidence
400            .validate()
401            .map_err(|e| HiveError::Refused(format!("evidence: {e}")))?;
402        Ok(evidence)
403    }
404}
405
406/// The anchor of `spec` in `root`: the file is admitted like a source
407/// binding first (a restricted, withheld or unreadable file is never
408/// digested), then digested as it is now.
409fn file_anchor(root: &Path, spec: &str) -> Result<EvidenceV1, HiveError> {
410    use crate::core::knowledge::anchors;
411    let (path, symbol) = anchors::parse_spec(spec);
412    let root_text = root.to_string_lossy();
413    if crate::core::archive::bindings::sources_at(&root_text, &[path], "ctx_tasks").is_none() {
414        return Err(HiveError::Refused(format!(
415            "{path}: not an admitted project file"
416        )));
417    }
418    let anchor = anchors::capture(root, path, symbol).map_err(HiveError::Refused)?;
419    let evidence = EvidenceV1 {
420        kind: EvidenceKind::FileAnchor,
421        reference: None,
422        anchor: Some(anchor),
423    };
424    evidence
425        .validate()
426        .map_err(|e| HiveError::Refused(format!("evidence: {e}")))?;
427    Ok(evidence)
428}
429
430/// The project's tasks.
431pub fn list(project_root: &Path, filter: &ListFilter) -> Result<TaskListV1, HiveError> {
432    let c = connected(project_root, HiveRight::TasksRead)?;
433    list_via(&c.link(), filter)
434}
435
436fn list_via(link: &Link<'_>, filter: &ListFilter) -> Result<TaskListV1, HiveError> {
437    link.call(|api| api.list(filter))
438}
439
440/// One task, its sealed parts opened where this machine holds the key.
441pub fn show(project_root: &Path, number: u64) -> Result<TaskView, HiveError> {
442    let c = connected(project_root, HiveRight::TasksRead)?;
443    show_via(&c.link(), number)
444}
445
446fn show_via(link: &Link<'_>, number: u64) -> Result<TaskView, HiveError> {
447    let task = link.call(|api| api.show(number))?;
448    let content = task
449        .sealed
450        .as_ref()
451        .and_then(|blob| link.open::<TaskContent>(number, blob));
452    let update_summaries = task
453        .updates
454        .iter()
455        .map(|update| {
456            update.summary.clone().or_else(|| {
457                update
458                    .sealed
459                    .as_ref()
460                    .and_then(|blob| link.open::<SealedSummary>(number, blob))
461                    .map(|sealed| sealed.summary)
462            })
463        })
464        .collect();
465    let held_until = claims::find(link.data_dir, link.vault_id, number).map(|held| held.until);
466    Ok(TaskView {
467        task,
468        content,
469        update_summaries,
470        held_until,
471    })
472}
473
474/// A granted claim, as the caller may see it (no lease id, no token).
475#[derive(Debug, Clone, PartialEq, Eq)]
476pub struct ClaimGranted {
477    pub number: u64,
478    pub until: String,
479    pub minutes: u32,
480}
481
482/// Claim task `number` for bus agent `agent` in session `session_id`.
483pub fn claim(
484    project_root: &Path,
485    number: u64,
486    agent: &str,
487    session_id: &str,
488    minutes: Option<u32>,
489) -> Result<ClaimGranted, HiveError> {
490    let c = connected(project_root, HiveRight::TasksWork)?;
491    let local = crate::core::config::Config::load().hive.worker.clone();
492    // The whole claim (opt-in read, claim, its one retry) ends within one
493    // BUDGET, like every task call from a tool.
494    let deadline = Instant::now() + BUDGET;
495    // Whether the gate let a request go to Hive: then an `Ok` is Hive's
496    // grant (a claim this machine already holds never reaches the gate).
497    let asked = std::cell::Cell::new(false);
498    let gate = |scope: &TaskScope| {
499        let unavailable = |e: HiveError| Refusal::Unavailable(e.to_string());
500        let client = c.session.bounded_client(deadline).map_err(unavailable)?;
501        let optin = worker::fetch_optin_via(&client).map_err(unavailable)?;
502        let admission = worker::admit_claim_for(&c.store, &local, scope, &optin)?;
503        asked.set(true);
504        Ok(admission)
505    };
506    let mut link = c.link();
507    link.deadline = Some(deadline);
508    let granted = claim_via(&link, number, agent, session_id, minutes, &gate)
509        .inspect_err(|error| record_claim_friction(error, agent, project_root))?;
510    // Counted only once granted: a refused claim costs no task today. The
511    // claim stands either way; Hive counts it too.
512    if asked.get()
513        && let Err(error) = worker::count_claim(&c.store)
514    {
515        tracing::warn!("hive worker: a granted claim was not counted here: {error}");
516    }
517    keeper::ensure_running();
518    Ok(granted)
519}
520
521/// Count a claim Hive refused for presence, role or consent (local
522/// friction log, the retro loop's input; ids, no content).
523fn record_claim_friction(error: &HiveError, agent: &str, root: &Path) {
524    use crate::core::agents::friction;
525    if let HiveError::Task {
526        refusal: TaskRefusal::NotPermitted(check),
527        ..
528    } = error
529    {
530        let signal = match check {
531            crate::core::hive::error::PermitCheck::Presence => friction::CLAIM_REFUSED_PRESENCE,
532            crate::core::hive::error::PermitCheck::Role => friction::CLAIM_REFUSED_ROLE,
533            crate::core::hive::error::PermitCheck::Unknown => friction::CLAIM_REFUSED_PERMIT,
534        };
535        friction::record_for(signal, Some(agent), root.to_str());
536    }
537}
538
539/// The worker gate of a claim (L1): the opt-in it works under, or why not.
540type ClaimGate<'g> = &'g dyn Fn(&TaskScope) -> Result<Admission, Refusal>;
541
542fn claim_via(
543    link: &Link<'_>,
544    number: u64,
545    agent: &str,
546    session_id: &str,
547    minutes: Option<u32>,
548    gate: ClaimGate<'_>,
549) -> Result<ClaimGranted, HiveError> {
550    let minutes = minutes
551        .unwrap_or(DEFAULT_CLAIM_MINUTES)
552        .clamp(MIN_CLAIM_MINUTES, MAX_CLAIM_MINUTES);
553    if let Some(held) = claims::find(link.data_dir, link.vault_id, number)
554        && held.until().is_some_and(|until| until > link.now())
555    {
556        if held.agent != agent {
557            return Err(HiveError::Refused(format!(
558                "task #{number} is claimed on this machine by another agent"
559            )));
560        }
561        // The holder claiming again wants more time: renew, so the answer is
562        // a fresh expiry, not the one it already had. A running session that
563        // holds the claim renews it itself; it is reported as it stands.
564        if held.pid != std::process::id() && crate::ipc::process::is_alive(held.pid) {
565            return Ok(ClaimGranted {
566                number,
567                until: held.until,
568                minutes: held.minutes,
569            });
570        }
571        let renewed = renew_via(link, number, agent)?;
572        return Ok(ClaimGranted {
573            number,
574            until: renewed.until,
575            minutes: renewed.minutes,
576        });
577    }
578    // The worker gate first (opt-in, scope, pause, today's budget); Hive
579    // then checks the same opt-in (C0 1.9 §4: `optin_scope`,
580    // `optin_inactive`, `daily_budget`, `optin_changed`). An opt-in that
581    // changed since it was read is read again, once.
582    let attempt = || {
583        let admission =
584            gate(&link.scope(number)).map_err(|refusal| HiveError::Refused(refusal.to_string()))?;
585        let request = TaskClaimRequestV1 {
586            schema: TASK_CLAIM_REQUEST_SCHEMA.into(),
587            agent: agent.to_owned(),
588            session_ref: crate::core::hive::knowledge::draft::session_ref(session_id),
589            minutes,
590            optin_id: admission.optin_id,
591        };
592        link.call_claim(|api| api.claim(number, &request))
593    };
594    let ack = match attempt() {
595        Err(HiveError::Task {
596            refusal: TaskRefusal::OptinChanged,
597            ..
598        }) => attempt()?,
599        answer => answer?,
600    };
601    let until = ack.until.as_str().to_owned();
602    claims::put(
603        link.data_dir,
604        HeldClaim {
605            vault_id: link.vault_id.to_owned(),
606            number,
607            root: link.root.to_string_lossy().into_owned(),
608            agent: agent.to_owned(),
609            claim: ack.claim,
610            until: until.clone(),
611            minutes,
612            pid: std::process::id(),
613        },
614    )?;
615    Ok(ClaimGranted {
616        number,
617        until,
618        minutes,
619    })
620}
621
622/// Renew the claim this machine holds on `number`.
623fn renew_via(link: &Link<'_>, number: u64, agent: &str) -> Result<HeldClaim, HiveError> {
624    let mut held = link.held(number, agent)?;
625    let request = TaskClaimRenewRequestV1 {
626        schema: TASK_CLAIM_RENEW_SCHEMA.into(),
627        claim: held.claim.clone(),
628        minutes: held.minutes,
629    };
630    let ack = link.settle(number, link.call_claim(|api| api.renew(number, &request)))?;
631    held.claim = ack.claim;
632    ack.until.as_str().clone_into(&mut held.until);
633    if !claims::renewed(link.data_dir, &held)? {
634        return Err(HiveError::Refused(format!(
635            "task #{number} was given back meanwhile; its renewal is not kept"
636        )));
637    }
638    Ok(held)
639}
640
641/// Give task `number` back; `reason` is one line (left out in sealed
642/// projects).
643pub fn release(
644    project_root: &Path,
645    number: u64,
646    agent: &str,
647    reason: Option<&str>,
648) -> Result<TaskAckV1, HiveError> {
649    let c = connected(
650        &claim_root(project_root, number, agent),
651        HiveRight::TasksWork,
652    )?;
653    release_via(&c.link(), number, agent, reason)
654}
655
656fn release_via(
657    link: &Link<'_>,
658    number: u64,
659    agent: &str,
660    reason: Option<&str>,
661) -> Result<TaskAckV1, HiveError> {
662    let held = link.held(number, agent)?;
663    let reason = reason
664        .map(str::trim)
665        .filter(|reason| !reason.is_empty() && !link.sealed);
666    screened(&[("release reason", reason)])?;
667    let request = TaskReleaseRequestV1 {
668        schema: TASK_RELEASE_SCHEMA.into(),
669        claim: held.claim,
670        reason: reason.map(str::to_owned),
671    };
672    let ack = link.settle(number, link.call(|api| api.release(number, &request)))?;
673    claims::remove(link.data_dir, link.vault_id, number)?;
674    Ok(ack)
675}
676
677/// Report one short summary on the claimed task `number`. When the claim
678/// lapsed while the agent worked (Hive: stale claim), the task is claimed
679/// again for it and the summary sent once more; another agent's claim
680/// refuses that.
681pub fn update(
682    project_root: &Path,
683    number: u64,
684    agent: &str,
685    session_id: &str,
686    summary: &str,
687    usage: Option<UsageV1>,
688) -> Result<TaskAckV1, HiveError> {
689    let project_root = &claim_root(project_root, number, agent);
690    let c = connected(project_root, HiveRight::TasksWork)?;
691    let usage = engine_usage(&c, number, usage);
692    update_or_reclaim_via(&c.link(), number, agent, summary, usage, || {
693        claim(project_root, number, agent, session_id, None)
694    })
695}
696
697fn update_or_reclaim_via(
698    link: &Link<'_>,
699    number: u64,
700    agent: &str,
701    summary: &str,
702    usage: Option<UsageV1>,
703    reclaim: impl FnOnce() -> Result<ClaimGranted, HiveError>,
704) -> Result<TaskAckV1, HiveError> {
705    match update_via(link, number, agent, summary, usage) {
706        Err(HiveError::Task {
707            refusal: TaskRefusal::StaleClaim,
708            ..
709        }) => {
710            reclaim()?;
711            update_via(link, number, agent, summary, usage)
712        }
713        answer => answer,
714    }
715}
716
717/// C9: the usage a write carries is the engine's own measure of the claim
718/// (host sessions at list price), at least what the agent reported; only
719/// where this machine recorded nothing does the report stand alone.
720fn engine_usage(c: &Connected, number: u64, reported: Option<UsageV1>) -> Option<UsageV1> {
721    let measured = dirs::home_dir().and_then(|home| {
722        let others: Vec<String> = VaultMap::load(c.store.data_dir())
723            .vaults
724            .into_values()
725            .filter(|p| p.vault_id != c.project.vault_id)
726            .flat_map(|p| p.roots)
727            .collect();
728        let now = Utc::now();
729        let usage = hive_use::host_window(&home, &c.project.roots, &others, now);
730        hive_use::claim_usage(c.store.data_dir(), &c.project.vault_id, number, now, &usage)
731    });
732    match (measured, reported) {
733        (Some(measured), reported) => Some(UsageV1 {
734            tokens: measured.tokens.max(reported.map_or(0, |r| r.tokens)),
735            usd_micros: measured.usd_micros,
736        }),
737        (None, reported) => reported,
738    }
739}
740
741fn update_via(
742    link: &Link<'_>,
743    number: u64,
744    agent: &str,
745    summary: &str,
746    usage: Option<UsageV1>,
747) -> Result<TaskAckV1, HiveError> {
748    let held = link.held(number, agent)?;
749    let summary = summary.trim();
750    screened(&[("summary", Some(summary))])?;
751    let (summary, sealed) = if link.sealed {
752        let content = SealedSummary {
753            summary: summary.to_owned(),
754        };
755        (
756            None,
757            Some(link.seal(number, SEALED_TASK_UPDATE_SCHEMA, &content)?),
758        )
759    } else {
760        (Some(summary.to_owned()), None)
761    };
762    let request = TaskUpdateRequestV1 {
763        schema: TASK_UPDATE_SCHEMA.into(),
764        claim: held.claim,
765        summary,
766        sealed,
767        usage,
768    };
769    link.settle(number, link.call(|api| api.update(number, &request)))
770}
771
772/// Submit the result of the claimed task `number`: it ends the claim. A
773/// 1.x Hive turns it into a proposal a person (or an auto-merge threshold)
774/// decides on (`submitted`); Hive v5 ends the task (`done`, or `failed`
775/// for [`TaskOutcome::Failed`]).
776///
777/// A result never carries a draft: knowledge the work produced travels
778/// through the capture gate and `hive sync` like any other (signed E5
779/// events on a C0 2.0 Hive, the draft path on 1.x).
780pub fn submit(
781    project_root: &Path,
782    number: u64,
783    agent: &str,
784    summary: &str,
785    evidence: Vec<EvidenceInput>,
786    usage: Option<UsageV1>,
787    outcome: TaskOutcome,
788) -> Result<TaskAckV1, HiveError> {
789    let c = connected(
790        &claim_root(project_root, number, agent),
791        HiveRight::TasksWork,
792    )?;
793    let usage = engine_usage(&c, number, usage);
794    // The gate decides before anything is sent; the usage counts against
795    // today's budget only once Hive accepted the result (a refused or
796    // repeated submit is not counted twice).
797    let decided = std::cell::RefCell::new(None);
798    let gate = |_: &TaskScope, evidence: &EvidenceSummary| {
799        *decided.borrow_mut() = Some(evidence.clone());
800        Ok(())
801    };
802    let ack = submit_via(
803        &c.link(),
804        number,
805        agent,
806        Submission {
807            summary,
808            evidence,
809            usage,
810            outcome,
811        },
812        &gate,
813    )?;
814    if let Some(evidence) = decided.take() {
815        let _ = worker::admit_submit(&c.store, &evidence);
816    }
817    Ok(ack)
818}
819
820/// The worker gate of a result (L1): what it cites and costs, admitted
821/// before anything is sent.
822type SubmitGate<'g> = &'g dyn Fn(&TaskScope, &EvidenceSummary) -> Result<(), Refusal>;
823
824/// What a result says.
825struct Submission<'s> {
826    summary: &'s str,
827    evidence: Vec<EvidenceInput>,
828    usage: Option<UsageV1>,
829    outcome: TaskOutcome,
830}
831
832/// `outcome` as the request carries it. `completed` is never sent (absent
833/// means completed on every line). `failed` goes only to a Hive whose
834/// task views carry the v5 `lifecycle`: a 1.x Hive denies the unknown
835/// field, so against it the failure is refused here, before anything is
836/// sent, and the agent releases the task instead.
837fn negotiated_outcome(
838    link: &Link<'_>,
839    number: u64,
840    outcome: TaskOutcome,
841) -> Result<Option<TaskOutcome>, HiveError> {
842    if outcome == TaskOutcome::Completed {
843        return Ok(None);
844    }
845    let task = link.call(|api| api.show(number))?;
846    if task.lifecycle.is_none() {
847        return Err(HiveError::Refused(format!(
848            "this Hive does not take failed results yet; release task #{number} with a reason instead"
849        )));
850    }
851    Ok(Some(outcome))
852}
853
854fn submit_via(
855    link: &Link<'_>,
856    number: u64,
857    agent: &str,
858    submission: Submission<'_>,
859    gate: SubmitGate<'_>,
860) -> Result<TaskAckV1, HiveError> {
861    let Submission {
862        summary,
863        evidence,
864        usage,
865        outcome,
866    } = submission;
867    let held = link.held(number, agent)?;
868    let summary = summary.trim();
869    let evidence = evidence
870        .into_iter()
871        .map(|item| item.into_evidence(link.root))
872        .collect::<Result<Vec<_>, _>>()?;
873    // A path or symbol name leaves the machine too: screened like text.
874    let references: Vec<&str> = evidence
875        .iter()
876        .flat_map(|item| {
877            let anchor = item.anchor.as_ref();
878            [
879                item.reference.as_deref(),
880                anchor.map(|a| a.path.as_str()),
881                anchor.and_then(|a| a.symbol.as_deref()),
882            ]
883        })
884        .flatten()
885        .collect();
886    let mut fields = vec![("summary", Some(summary))];
887    fields.extend(
888        references
889            .iter()
890            .map(|reference| ("evidence", Some(*reference))),
891    );
892    screened(&fields)?;
893    gate(
894        &link.scope(number),
895        &EvidenceSummary {
896            usage_tokens: usage.map_or(0, |usage| usage.tokens),
897            usage_usd_micros: usage.and_then(|usage| usage.usd_micros).unwrap_or(0),
898        },
899    )
900    .map_err(|refusal| HiveError::Refused(refusal.to_string()))?;
901    let (summary, evidence, sealed) = if link.sealed {
902        let content = SealedResult {
903            summary: summary.to_owned(),
904            evidence,
905        };
906        (
907            None,
908            Vec::new(),
909            Some(link.seal(number, SEALED_TASK_RESULT_SCHEMA, &content)?),
910        )
911    } else {
912        (Some(summary.to_owned()), evidence, None)
913    };
914    let outcome = negotiated_outcome(link, number, outcome)?;
915    let request = TaskResultRequestV1 {
916        schema: TASK_RESULT_SCHEMA.into(),
917        claim: held.claim,
918        summary,
919        evidence,
920        draft: None,
921        sealed,
922        usage,
923        outcome,
924    };
925    let ack = link.settle(number, link.call(|api| api.result(number, &request)))?;
926    claims::remove(link.data_dir, link.vault_id, number)?;
927    Ok(ack)
928}
929
930/// Give back every claim this process holds (worker stop, shutdown);
931/// returns how many Hive released. A claim Hive cannot be reached for is
932/// forgotten here and ends at its expiry there.
933pub fn release_own_claims(reason: &str) -> usize {
934    let Ok(store) = HiveStore::open() else {
935        return 0;
936    };
937    let mut released = 0;
938    for held in claims::own(store.data_dir()) {
939        let answer = connected(Path::new(&held.root), HiveRight::TasksWork)
940            .and_then(|c| release_via(&c.link(), held.number, &held.agent, Some(reason)));
941        if answer.is_ok() {
942            released += 1;
943        }
944        let _ = claims::remove(store.data_dir(), &held.vault_id, held.number);
945    }
946    released
947}
948
949/// How many claims this process holds.
950fn own_claims() -> usize {
951    HiveStore::open().map_or(0, |store| claims::own(store.data_dir()).len())
952}
953
954/// A session idle this long no longer keeps its claims alive: they end at
955/// their expiry in Hive, so a silent agent frees its task quickly.
956const RENEW_IDLE: std::time::Duration = std::time::Duration::from_mins(30);
957
958/// Renew the claims of this process whose half-time has passed, unless the
959/// process has been idle for [`RENEW_IDLE`] or worker mode is paused here;
960/// returns how many this process still holds.
961fn renew_own_due() -> usize {
962    let Ok(store) = HiveStore::open() else {
963        return 0;
964    };
965    let idle = crate::server::mcp_idle::idle_for_now().is_some_and(|idle| idle >= RENEW_IDLE);
966    if idle || crate::core::hive::worker::read_state(&store).paused {
967        return claims::own(store.data_dir()).len();
968    }
969    for held in claims::own(store.data_dir()) {
970        let Ok(c) = connected(Path::new(&held.root), HiveRight::TasksWork) else {
971            continue;
972        };
973        let link = c.link();
974        if held.renew_due(link.now()) {
975            let _ = renew_via(&link, held.number, &held.agent);
976        }
977    }
978    claims::own(store.data_dir()).len()
979}
980
981/// Take over the unexpired claims `agent` holds on this machine (a new
982/// session of the same agent) and keep them renewed.
983pub fn adopt_claims(agent: &str) {
984    let Ok(store) = HiveStore::open() else {
985        return;
986    };
987    let now = Utc::now();
988    if claims::adopt(store.data_dir(), agent, now).is_ok_and(|held| !held.is_empty()) {
989        keeper::ensure_running();
990    }
991}
992
993/// Keep CLI claims alive (lean-ctx #3): `lean-ctx hive tasks claim` ends
994/// right after claiming, so nothing renewed its claim and an agent running
995/// a long gate lost it before submitting. The bus relay's process renews a
996/// claim whose holder has ended at half-time while the claiming agent still
997/// works on this machine (registered, not finished, active within
998/// `RENEW_IDLE`), without becoming its holder; once the agent stops
999/// working the claim ends at its expiry in Hive. Returns how many such
1000/// claims it kept.
1001pub fn keep_cli_claims() -> usize {
1002    let Ok(store) = HiveStore::open() else {
1003        return 0;
1004    };
1005    if crate::core::hive::worker::read_state(&store).paused {
1006        return 0;
1007    }
1008    let now = Utc::now();
1009    let registry = crate::core::agents::AgentRegistry::load_or_create();
1010    let idle = chrono::Duration::from_std(RENEW_IDLE).unwrap_or(chrono::Duration::MAX);
1011    let working: std::collections::HashSet<String> = registry
1012        .list_active(None)
1013        .into_iter()
1014        .filter(|agent| now - agent.last_active < idle)
1015        .map(|agent| agent.agent_id.clone())
1016        .collect();
1017    keep_orphaned(
1018        store.data_dir(),
1019        now,
1020        |agent| working.contains(agent),
1021        |held| {
1022            if let Ok(c) = connected(Path::new(&held.root), HiveRight::TasksWork) {
1023                let _ = renew_via(&c.link(), held.number, &held.agent);
1024            }
1025        },
1026    )
1027}
1028
1029/// Renew the orphaned claims of `working` agents whose half-time has
1030/// passed; returns how many orphaned claims of `working` agents there are.
1031fn keep_orphaned(
1032    data_dir: &Path,
1033    now: chrono::DateTime<Utc>,
1034    working: impl Fn(&str) -> bool,
1035    renew: impl Fn(&HeldClaim),
1036) -> usize {
1037    let kept: Vec<HeldClaim> = claims::orphaned(data_dir, now)
1038        .into_iter()
1039        .filter(|held| working(&held.agent))
1040        .collect();
1041    for held in kept.iter().filter(|held| held.renew_due(now)) {
1042        renew(held);
1043    }
1044    kept.len()
1045}
1046
1047/// The checkout to act on claim `number` from: `project_root`, unless its
1048/// vault holds no claim of `agent` on `number` while exactly one other
1049/// vault does. An agent's session often runs in another repository than the
1050/// one it claimed in (the claim names its checkout), and the task number
1051/// alone then finds the claim the agent holds.
1052#[must_use]
1053pub fn claim_root(project_root: &Path, number: u64, agent: &str) -> PathBuf {
1054    let Ok(store) = HiveStore::open() else {
1055        return project_root.to_path_buf();
1056    };
1057    claim_root_in(store.data_dir(), project_root, number, agent)
1058}
1059
1060fn claim_root_in(data_dir: &Path, project_root: &Path, number: u64, agent: &str) -> PathBuf {
1061    let here = VaultMap::load(data_dir)
1062        .for_root(&project_root.to_string_lossy())
1063        .map(|vault| vault.vault_id.clone());
1064    let mine: Vec<HeldClaim> = claims::all(data_dir)
1065        .into_iter()
1066        .filter(|held| held.number == number && held.agent == agent)
1067        .collect();
1068    let held_here = mine
1069        .iter()
1070        .any(|held| here.as_deref() == Some(held.vault_id.as_str()));
1071    match mine.as_slice() {
1072        [only] if !held_here => PathBuf::from(&only.root),
1073        _ => project_root.to_path_buf(),
1074    }
1075}
1076
1077/// What a session starts with (H2): the claims this machine holds in the
1078/// project, then its open tasks. `None` when Hive does not apply or there
1079/// is nothing to say. Bounded by [`BRIEFING_BUDGET`].
1080pub fn briefing(project_root: &Path) -> Option<String> {
1081    let c = connected(project_root, HiveRight::TasksRead).ok()?;
1082    let mut link = c.link();
1083    link.budget = BRIEFING_BUDGET;
1084    let now = link.now();
1085    let mut lines: Vec<String> = claims::all(link.data_dir)
1086        .into_iter()
1087        .filter(|held| {
1088            held.vault_id == link.vault_id && held.until().is_some_and(|until| until > now)
1089        })
1090        .map(|held| {
1091            format!(
1092                "Hive task #{} is claimed on this machine for agent {} until {}.",
1093                held.number, held.agent, held.until
1094            )
1095        })
1096        .collect();
1097    let open = list_via(
1098        &link,
1099        &ListFilter {
1100            state: Some(lean_ctx_protocol::hive::tasks::TaskState::Open),
1101            ..ListFilter::default()
1102        },
1103    )
1104    .ok()
1105    .filter(|list| !list.tasks.is_empty());
1106    if let Some(open) = open {
1107        lines.push(render_list(&open, 5));
1108    }
1109    (!lines.is_empty()).then(|| lines.join("\n"))
1110}
1111
1112#[cfg(test)]
1113#[path = "tests.rs"]
1114mod tests;