Skip to main content

lean_ctx/core/hive/
worker.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Worker mode (Hive plan v3 L1, owner decision O1): the person's own agent
3//! pulls tasks through MCP; the engine never starts an agent by itself.
4//!
5//! Every claim and every result passes this gate first:
6//!
7//! - The engine's opt-in lives on the server (`GET /v1/me/optin`): which
8//!   repos and swarms its agents may work on, whether it is
9//!   active, and the daily budget. It is read fresh for every claim; when
10//!   it cannot be read, nothing is claimed (fail closed).
11//! - The daily budget has three limits and the first one reached stops the
12//!   work: tasks per day (checked before a claim), and optionally tokens and
13//!   USD per day (counted from the usage each result reports; the result
14//!   that crosses a limit still goes through, the next claim does not).
15//! - `[hive.worker]` may only tighten these limits on this machine, never
16//!   widen them.
17//! - `hive worker pause` stops claiming here until `resume`, and held
18//!   claims are no longer renewed (they end at their expiry); `hive worker
19//!   stop` also switches the opt-in off on the server, which ends every claim
20//!   of this engine at once. Only the owner turns it on again, on the web.
21//! - A swarm task carries only the swarm's material: a result that
22//!   cites files of the engine's own projects is refused before it leaves.
23//!
24//! Hive enforces the same rules (C0 1.9 section 4: 403 `optin_scope` /
25//! `vetoed`, 409 `optin_inactive` / `optin_changed`, 429 `daily_budget`);
26//! this gate makes a refusal local and content-free instead of a request
27//! that would leak which task was attempted.
28
29use std::fmt;
30
31use chrono::Utc;
32use serde::{Deserialize, Serialize};
33
34use super::HiveError;
35use super::auth::Session;
36use super::state::{HiveStore, write_private};
37use super::transport::HiveClient;
38use lean_ctx_protocol::hive::messages::NetworkV1;
39use lean_ctx_protocol::hive::optin::{ENGINE_OPTIN_STOP_SCHEMA, EngineOptinStopV1, EngineOptinV1};
40
41/// The engine's own opt-in record (engine auth, own instance only).
42pub const OPTIN_PATH: &str = "/me/optin";
43/// The provider-terms note every worker opt-in shows (plan X1; the web
44/// opt-in form carries the same text). LeanCTX never handles subscription
45/// credentials: the agent is one the person started and signed in to.
46pub const PROVIDER_TERMS_NOTE: &str = "\
47You use your own subscription; follow your provider's terms. LeanCTX never sees,
48stores or routes your provider login: your agent runs in a session you started
49and signed in to yourself. Not allowed by the providers: OpenCode or Pi signed in
50with a Claude Pro or Max login, and third-party tools using a Gemini CLI login
51(OAuth). Use the provider's own agent or an API key instead. Swarm work on a
52personal subscription is allowed; your provider's terms still apply.";
53
54const STATE_FILE: &str = "worker.json";
55const LOCK_FILE: &str = "worker.lock";
56
57/// `[hive.worker]`: stricter local caps on top of the server's budget.
58#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(default)]
60pub struct HiveWorkerConfig {
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub max_tasks_per_day: Option<u32>,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub max_tokens_per_day: Option<u64>,
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub max_usd_micros_per_day: Option<u64>,
67}
68
69/// What a day has used on this machine.
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(default)]
72pub struct Usage {
73    pub tasks: u64,
74    pub tokens: u64,
75    pub usd_micros: u64,
76}
77
78/// The engine's opt-in (C0 1.9 section 4).
79pub type Optin = EngineOptinV1;
80
81/// The swarms `optin` names.
82pub fn optin_swarms(optin: &Optin) -> impl Iterator<Item = &str> {
83    optin.networks.iter().filter_map(|n| match n {
84        NetworkV1::Swarm { swarm_id } => Some(swarm_id.as_str()),
85        NetworkV1::Org { .. } => None,
86    })
87}
88
89/// The local worker state: pause flag and what this machine used today.
90#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(default)]
92pub struct WorkerState {
93    pub paused: bool,
94    /// UTC day the counters belong to (`YYYY-MM-DD`).
95    pub day: String,
96    pub used: Usage,
97}
98
99impl WorkerState {
100    fn today(mut self, day: &str) -> Self {
101        if self.day != day {
102            day.clone_into(&mut self.day);
103            self.used = Usage::default();
104        }
105        self
106    }
107}
108
109/// Where a task comes from.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum TaskKind {
112    /// A task of one of the organization's repos.
113    Org,
114    /// A subtask of a swarm; the opt-in covers it by its
115    /// network (the swarm) or by one of its topics.
116    Swarm {
117        swarm_id: String,
118        topics: Vec<String>,
119    },
120}
121
122/// The task a claim or result is for.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct TaskScope {
125    pub task_id: String,
126    /// The Hive project (repo) id.
127    pub vault_id: String,
128    pub kind: TaskKind,
129}
130
131/// What a result reports it cost, for today's budget.
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct EvidenceSummary {
134    pub usage_tokens: u64,
135    pub usage_usd_micros: u64,
136}
137
138/// What is left of today's budget; `None` is no limit.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct BudgetLeft {
141    pub tasks: Option<u64>,
142    pub tokens: Option<u64>,
143    pub usd_micros: Option<u64>,
144}
145
146/// An admitted claim: the opt-in it works under and what is left after it.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Admission {
149    pub optin_id: Option<String>,
150    pub budget_left: BudgetLeft,
151}
152
153/// The limit a budget refusal hit.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum Limit {
156    Tasks,
157    Tokens,
158    UsdMicros,
159}
160
161/// Why the gate refused; its text never names the task or its content.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum Refusal {
164    /// This engine has no opt-in, or it does not cover the task.
165    NotOptedIn,
166    /// The opt-in was stopped; only the owner turns it on again.
167    Stopped,
168    /// `hive worker pause` is in effect on this machine.
169    Paused,
170    BudgetExhausted(Limit),
171    /// The opt-in could not be read; nothing is claimed without it.
172    Unavailable(String),
173}
174
175impl fmt::Display for Refusal {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            Self::NotOptedIn => f.write_str(
179                "worker mode is not enabled for this task (opt in for its vault or swarm on the web)",
180            ),
181            Self::Stopped => {
182                f.write_str("worker mode was stopped for this engine (the owner resumes it on the web)")
183            }
184            Self::Paused => f.write_str(
185                "worker mode is paused on this machine; the person resumes it with `lean-ctx hive worker resume` in their own terminal",
186            ),
187            Self::BudgetExhausted(limit) => write!(
188                f,
189                "today's worker budget is used up ({})",
190                match limit {
191                    Limit::Tasks => "tasks",
192                    Limit::Tokens => "tokens",
193                    Limit::UsdMicros => "USD",
194                }
195            ),
196            Self::Unavailable(why) => write!(f, "the worker opt-in cannot be read ({why})"),
197        }
198    }
199}
200
201impl std::error::Error for Refusal {}
202
203/// A refusal reaches the caller with its own (content-free) words.
204impl From<Refusal> for HiveError {
205    fn from(refusal: Refusal) -> Self {
206        Self::Refused(refusal.to_string())
207    }
208}
209
210/// Repo and swarm ids compare without their wire prefix (`sw_`, `prj_`),
211/// dashes and case: Hive writes a project id as 32 hex digits, an opt-in
212/// repo or swarm as a dashed UUID, and swarm routes as `sw_<hex>`.
213fn same_id(a: &str, b: &str) -> bool {
214    let norm = |s: &str| {
215        let bare = match s.split_once('_') {
216            Some((prefix, rest))
217                if !prefix.is_empty()
218                    && prefix.len() <= 8
219                    && prefix.bytes().all(|b| b.is_ascii_lowercase()) =>
220            {
221                rest
222            }
223            _ => s,
224        };
225        bare.chars()
226            .filter(|c| *c != '-')
227            .map(|c| c.to_ascii_lowercase())
228            .collect::<String>()
229    };
230    !a.is_empty() && norm(a) == norm(b)
231}
232
233fn left(limit: Option<u64>, local: Option<u64>, used: u64) -> Option<u64> {
234    let limit = match (limit, local) {
235        (Some(a), Some(b)) => Some(a.min(b)),
236        (a, b) => a.or(b),
237    };
238    limit.map(|l| l.saturating_sub(used))
239}
240
241/// The claim decision on a read opt-in and the local state (no I/O).
242pub fn decide_claim(
243    optin: &Optin,
244    local: &HiveWorkerConfig,
245    state: &WorkerState,
246    scope: &TaskScope,
247) -> Result<Admission, Refusal> {
248    if state.paused {
249        return Err(Refusal::Paused);
250    }
251    if optin.optin_id.is_none() {
252        return Err(Refusal::NotOptedIn);
253    }
254    if !optin.active {
255        return Err(Refusal::Stopped);
256    }
257    let budget = optin.daily_budget;
258    let in_scope = match &scope.kind {
259        TaskKind::Org => optin.vaults.iter().any(|r| same_id(r, &scope.vault_id)),
260        TaskKind::Swarm { swarm_id, topics } => {
261            optin_swarms(optin).any(|q| same_id(q, swarm_id))
262                || topics.iter().any(|t| optin.topics.contains(t))
263        }
264    };
265    if !in_scope {
266        return Err(Refusal::NotOptedIn);
267    }
268    // The server counts the engine, this machine counts itself: the higher
269    // of the two is today's use.
270    let used = Usage {
271        tasks: u64::from(optin.used_today.tasks).max(state.used.tasks),
272        tokens: optin.used_today.tokens.max(state.used.tokens),
273        usd_micros: optin.used_today.usd_micros.max(state.used.usd_micros),
274    };
275    // Hive task #19: no task limit on the server and none here is none.
276    let tasks = left(
277        budget.tasks.map(u64::from),
278        local.max_tasks_per_day.map(u64::from),
279        used.tasks,
280    );
281    let tokens = left(budget.tokens, local.max_tokens_per_day, used.tokens);
282    let usd_micros = left(
283        budget.usd_micros,
284        local.max_usd_micros_per_day,
285        used.usd_micros,
286    );
287    for (rest, limit) in [
288        (tasks, Limit::Tasks),
289        (tokens, Limit::Tokens),
290        (usd_micros, Limit::UsdMicros),
291    ] {
292        if rest == Some(0) {
293            return Err(Refusal::BudgetExhausted(limit));
294        }
295    }
296    Ok(Admission {
297        optin_id: optin.optin_id.clone(),
298        budget_left: BudgetLeft {
299            // The claim this admits counts one.
300            tasks: tasks.map(|t| t - 1),
301            tokens,
302            usd_micros,
303        },
304    })
305}
306
307fn day() -> String {
308    Utc::now().format("%Y-%m-%d").to_string()
309}
310
311/// Read-modify-write the worker state under its lock.
312fn with_state<T>(
313    store: &HiveStore,
314    change: impl FnOnce(&mut WorkerState) -> T,
315) -> Result<T, HiveError> {
316    let dir = store.data_dir();
317    std::fs::create_dir_all(dir).map_err(|e| HiveError::Local(format!("worker: {e}")))?;
318    let _lock = crate::core::agents::FileLock::acquire(&dir.join(LOCK_FILE))
319        .map_err(|e| HiveError::Local(format!("worker lock: {e}")))?;
320    let mut state = read_state(store).today(&day());
321    let out = change(&mut state);
322    let bytes = serde_json::to_vec(&state).map_err(|e| HiveError::Local(e.to_string()))?;
323    write_private(dir, STATE_FILE, &bytes)?;
324    Ok(out)
325}
326
327/// Write the state before the engine enrolls, so that a missing one after
328/// enrollment can only mean it was deleted. A state already there, paused
329/// or not, stays as it is; the web opt-in still gates every claim.
330pub(crate) fn prepare_enrollment(store: &HiveStore) -> Result<(), HiveError> {
331    with_state(store, |_| ())
332}
333
334/// The local state as stored (today's counters reset on a new day). Fail
335/// closed: a file that cannot be read or parsed counts as paused, and so
336/// does a missing one on an engine enrolled with Hive — deleting it never
337/// lifts a pause or resets today's counts. Only enrollment
338/// (`prepare_enrollment`) and `hive worker resume`, both of which the
339/// person runs (an agent shell refuses them), write it unpaused.
340pub fn read_state(store: &HiveStore) -> WorkerState {
341    let paused = || WorkerState {
342        paused: true,
343        ..WorkerState::default()
344    };
345    let state = match std::fs::read(store.data_dir().join(STATE_FILE)) {
346        Ok(bytes) => serde_json::from_slice::<WorkerState>(&bytes).unwrap_or_else(|_| paused()),
347        Err(e) if e.kind() == std::io::ErrorKind::NotFound => match store.instance() {
348            Ok(None) => WorkerState::default(),
349            Ok(Some(_)) | Err(_) => paused(),
350        },
351        Err(_) => paused(),
352    };
353    state.today(&day())
354}
355
356/// The server's opt-in for this engine.
357pub fn fetch_optin(session: &Session) -> Result<Optin, HiveError> {
358    parse_optin(session.with_client(|c| c.get(OPTIN_PATH))?)
359}
360
361/// The opt-in through `client` (a bounded client of a tool call).
362pub fn fetch_optin_via(client: &HiveClient) -> Result<Optin, HiveError> {
363    parse_optin(client.get(OPTIN_PATH)?)
364}
365
366fn parse_optin(body: serde_json::Value) -> Result<Optin, HiveError> {
367    let optin: Optin =
368        serde_json::from_value(body).map_err(|e| HiveError::Protocol(format!("opt-in: {e}")))?;
369    optin
370        .validate()
371        .map_err(|e| HiveError::Protocol(format!("opt-in: {e}")))?;
372    Ok(optin)
373}
374
375/// Admit a claim: whether this machine may ask Hive for it. Nothing is
376/// counted yet; [`count_claim`] counts it once Hive granted it, so a claim
377/// Hive refuses costs no task of today's budget.
378pub fn admit_claim(
379    session: &Session,
380    local: &HiveWorkerConfig,
381    scope: &TaskScope,
382) -> Result<Admission, Refusal> {
383    let optin = fetch_optin(session).map_err(|e| Refusal::Unavailable(e.to_string()))?;
384    admit_claim_for(&session.store, local, scope, &optin)
385}
386
387/// [`admit_claim`] on an opt-in the caller just read.
388pub fn admit_claim_for(
389    store: &HiveStore,
390    local: &HiveWorkerConfig,
391    scope: &TaskScope,
392    optin: &Optin,
393) -> Result<Admission, Refusal> {
394    with_state(store, |state| decide_claim(optin, local, state, scope))
395        .map_err(|e| Refusal::Unavailable(e.to_string()))?
396}
397
398/// Count a claim Hive granted (or a verification commit it took) against
399/// today's tasks on this machine. A refused claim is never counted: it
400/// used to be, and refusals then ate the local budget until this machine
401/// refused on its own.
402pub fn count_claim(store: &HiveStore) -> Result<(), HiveError> {
403    with_state(store, |state| state.used.tasks += 1)
404}
405
406/// Add the usage a result reports to today's.
407pub fn admit_submit(store: &HiveStore, evidence: &EvidenceSummary) -> Result<(), Refusal> {
408    with_state(store, |state| {
409        state.used.tokens = state.used.tokens.saturating_add(evidence.usage_tokens);
410        state.used.usd_micros = state
411            .used
412            .usd_micros
413            .saturating_add(evidence.usage_usd_micros);
414    })
415    .map_err(|e| Refusal::Unavailable(e.to_string()))
416}
417
418/// Stop or resume claiming on this machine.
419pub fn set_paused(store: &HiveStore, paused: bool) -> Result<(), HiveError> {
420    with_state(store, |state| state.paused = paused)
421}
422
423/// Stop worker mode for this engine: pause here and switch the opt-in off
424/// on the server, which ends every claim of this engine at once.
425pub fn stop(session: &Session) -> Result<Optin, HiveError> {
426    set_paused(&session.store, true)?;
427    let stop = serde_json::to_value(EngineOptinStopV1 {
428        schema: ENGINE_OPTIN_STOP_SCHEMA.into(),
429        active: false,
430    })
431    .map_err(|e| HiveError::Local(e.to_string()))?;
432    let body = session.with_client(|c| {
433        c.send(
434            "PUT",
435            OPTIN_PATH,
436            Some(&stop),
437            &[],
438            lean_ctx_protocol::hive::MAX_BODY_BYTES,
439        )
440        .map(|r| r.body)
441    })?;
442    parse_optin(body)
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use lean_ctx_protocol::hive::optin::ENGINE_OPTIN_SCHEMA;
449    use serde_json::json;
450
451    const REPO: &str = "0b7c3c1e5d2a4f7e9a312c4d5e6f7a8b";
452    const SWARM: &str = "sw_01jbretry";
453
454    fn optin() -> Optin {
455        parse_optin(json!({
456            "schema": ENGINE_OPTIN_SCHEMA,
457            "optin_id": "opt_1",
458            "active": true,
459            "vaults": [REPO],
460            "networks": [{"kind": "swarm", "swarm_id": SWARM}],
461            "topics": ["rust"],
462            "daily_budget": {"tasks": 2, "tokens": 1000},
463            "used_today": {"day": "2026-10-22", "tasks": 0, "tokens": 0, "usd_micros": 0},
464            "updated_at": "2026-10-22T10:00:00Z"
465        }))
466        .unwrap()
467    }
468
469    fn org() -> TaskScope {
470        TaskScope {
471            task_id: "7".into(),
472            vault_id: REPO.into(),
473            kind: TaskKind::Org,
474        }
475    }
476
477    fn swarm() -> TaskScope {
478        TaskScope {
479            task_id: "3".into(),
480            vault_id: String::new(),
481            kind: TaskKind::Swarm {
482                swarm_id: SWARM.into(),
483                topics: Vec::new(),
484            },
485        }
486    }
487
488    #[test]
489    fn a_claim_needs_an_active_opt_in_that_covers_the_task() {
490        let local = HiveWorkerConfig::default();
491        let state = WorkerState::default();
492        let admitted = decide_claim(&optin(), &local, &state, &org()).unwrap();
493        assert_eq!(admitted.optin_id.as_deref(), Some("opt_1"));
494        assert_eq!(admitted.budget_left.tasks, Some(1));
495        assert_eq!(admitted.budget_left.tokens, Some(1000));
496        assert_eq!(admitted.budget_left.usd_micros, None);
497        assert!(decide_claim(&optin(), &local, &state, &swarm()).is_ok());
498
499        let other = TaskScope {
500            vault_id: "ffffffffffffffffffffffffffffffff".into(),
501            ..org()
502        };
503        assert_eq!(
504            decide_claim(&optin(), &local, &state, &other),
505            Err(Refusal::NotOptedIn)
506        );
507        let none = parse_optin(json!({
508            "schema": ENGINE_OPTIN_SCHEMA, "active": false, "vaults": [], "networks": [], "topics": [],
509            "daily_budget": {"tasks": 5},
510            "used_today": {"day": "2026-10-22", "tasks": 0, "tokens": 0, "usd_micros": 0}
511        }))
512        .unwrap();
513        assert_eq!(
514            decide_claim(&none, &local, &state, &org()),
515            Err(Refusal::NotOptedIn)
516        );
517        let stopped = Optin {
518            active: false,
519            ..optin()
520        };
521        assert_eq!(
522            decide_claim(&stopped, &local, &state, &org()),
523            Err(Refusal::Stopped)
524        );
525        // Swarms are covered by their network or a topic.
526        let by_topic = |topics: &[&str]| TaskScope {
527            kind: TaskKind::Swarm {
528                swarm_id: "sw_other".into(),
529                topics: topics.iter().map(|t| (*t).to_string()).collect(),
530            },
531            ..swarm()
532        };
533        assert!(decide_claim(&optin(), &local, &state, &by_topic(&["go", "rust"])).is_ok());
534        assert_eq!(
535            decide_claim(&optin(), &local, &state, &by_topic(&["go"])),
536            Err(Refusal::NotOptedIn)
537        );
538        let paused = WorkerState {
539            paused: true,
540            ..WorkerState::default()
541        };
542        assert_eq!(
543            decide_claim(&optin(), &local, &paused, &org()),
544            Err(Refusal::Paused)
545        );
546    }
547
548    /// Hive task #19: an opt-in without a task limit (C0 §4 erratum) admits
549    /// on count however many tasks the day has seen; a local cap still
550    /// applies.
551    #[test]
552    fn no_task_limit_admits_on_count_and_a_local_cap_still_holds() {
553        let mut free = optin();
554        free.daily_budget.tasks = None;
555        free.daily_budget.tokens = None;
556        free.used_today.tasks = 140;
557        let state = WorkerState::default();
558        let admitted = decide_claim(&free, &HiveWorkerConfig::default(), &state, &org()).unwrap();
559        assert_eq!(admitted.budget_left.tasks, None, "no limit stays no limit");
560        let capped = HiveWorkerConfig {
561            max_tasks_per_day: Some(150),
562            ..HiveWorkerConfig::default()
563        };
564        assert_eq!(
565            decide_claim(&free, &capped, &state, &org())
566                .unwrap()
567                .budget_left
568                .tasks,
569            Some(9)
570        );
571        free.used_today.tasks = 150;
572        assert_eq!(
573            decide_claim(&free, &capped, &state, &org()),
574            Err(Refusal::BudgetExhausted(Limit::Tasks))
575        );
576        // As Hive sends it: no `tasks` field at all.
577        let wire = parse_optin(json!({
578            "schema": ENGINE_OPTIN_SCHEMA, "optin_id": "opt_2", "active": true,
579            "vaults": [REPO], "networks": [], "topics": [], "daily_budget": {},
580            "used_today": {"day": "2026-10-22", "tasks": 140, "tokens": 0, "usd_micros": 0}
581        }))
582        .unwrap();
583        assert!(decide_claim(&wire, &HiveWorkerConfig::default(), &state, &org()).is_ok());
584    }
585
586    #[test]
587    fn the_first_limit_reached_stops_and_local_caps_only_tighten() {
588        let state = WorkerState::default();
589        let mut spent = optin();
590        spent.used_today.tasks = 2;
591        assert_eq!(
592            decide_claim(&spent, &HiveWorkerConfig::default(), &state, &org()),
593            Err(Refusal::BudgetExhausted(Limit::Tasks))
594        );
595        let mut tokens = optin();
596        tokens.used_today.tokens = 1200;
597        assert_eq!(
598            decide_claim(&tokens, &HiveWorkerConfig::default(), &state, &org()),
599            Err(Refusal::BudgetExhausted(Limit::Tokens))
600        );
601
602        // A wider local cap does not widen the server's budget.
603        let wide = HiveWorkerConfig {
604            max_tasks_per_day: Some(50),
605            max_tokens_per_day: Some(1_000_000),
606            max_usd_micros_per_day: None,
607        };
608        assert_eq!(
609            decide_claim(&spent, &wide, &state, &org()),
610            Err(Refusal::BudgetExhausted(Limit::Tasks))
611        );
612        // A tighter one applies, also to a limit the server leaves open.
613        let tight = HiveWorkerConfig {
614            max_tasks_per_day: Some(1),
615            max_tokens_per_day: None,
616            max_usd_micros_per_day: Some(500),
617        };
618        let one_done = WorkerState {
619            used: Usage {
620                tasks: 1,
621                ..Usage::default()
622            },
623            ..WorkerState::default()
624        };
625        assert_eq!(
626            decide_claim(&optin(), &tight, &one_done, &org()),
627            Err(Refusal::BudgetExhausted(Limit::Tasks)),
628            "the machine's own count holds when the server's is behind"
629        );
630        let admitted = decide_claim(&optin(), &tight, &state, &org()).unwrap();
631        assert_eq!(admitted.budget_left.usd_micros, Some(500));
632        let usd_spent = WorkerState {
633            used: Usage {
634                usd_micros: 500,
635                ..Usage::default()
636            },
637            ..WorkerState::default()
638        };
639        assert_eq!(
640            decide_claim(&optin(), &tight, &usd_spent, &org()),
641            Err(Refusal::BudgetExhausted(Limit::UsdMicros))
642        );
643    }
644
645    #[test]
646    fn opt_ins_follow_the_section_4_contract() {
647        let fixture: serde_json::Value = serde_json::from_str(include_str!(
648            "../../../crates/lean-ctx-protocol/tests/fixtures/hive/engine_optin.response.json"
649        ))
650        .unwrap();
651        let optin = parse_optin(fixture.clone()).unwrap();
652        assert!(optin.active && optin.optin_id.is_some());
653        assert!(optin_swarms(&optin).count() >= 1);
654
655        let mut wrong = fixture.clone();
656        wrong["schema"] = json!("leanctx.hive.engine-optin/v2");
657        assert!(matches!(parse_optin(wrong), Err(HiveError::Protocol(_))));
658        // Active without an opt-in id breaks the contract: fail closed.
659        let mut broken = fixture;
660        broken.as_object_mut().unwrap().remove("optin_id");
661        assert!(matches!(parse_optin(broken), Err(HiveError::Protocol(_))));
662
663        let stop = serde_json::to_value(EngineOptinStopV1 {
664            schema: ENGINE_OPTIN_STOP_SCHEMA.into(),
665            active: false,
666        })
667        .unwrap();
668        assert_eq!(
669            stop,
670            serde_json::from_str::<serde_json::Value>(include_str!(
671                "../../../crates/lean-ctx-protocol/tests/fixtures/hive/engine_optin_stop.request.json"
672            ))
673            .unwrap()
674        );
675    }
676
677    #[test]
678    fn refusals_name_no_task_and_reach_the_caller_in_their_own_words() {
679        for refusal in [
680            Refusal::NotOptedIn,
681            Refusal::Stopped,
682            Refusal::Paused,
683            Refusal::BudgetExhausted(Limit::Tokens),
684        ] {
685            let text = refusal.to_string();
686            assert!(!text.contains(REPO) && !text.contains(SWARM), "{text}");
687            assert_eq!(HiveError::from(refusal).to_string(), text);
688        }
689    }
690
691    #[test]
692    fn ids_match_across_wire_prefix_dashes_and_case() {
693        let uuid = "558f6ef0-1c2d-4e5f-8a9b-0c1d2e3f4a5b";
694        assert!(same_id(uuid, "sw_558f6ef01c2d4e5f8a9b0c1d2e3f4a5b"));
695        assert!(same_id("prj_558F6EF01C2D4E5F8A9B0C1D2E3F4A5B", uuid));
696        assert!(same_id("sw_01jbretry", "sw_01jbretry"));
697        assert!(!same_id(uuid, "sw_658f6ef01c2d4e5f8a9b0c1d2e3f4a5b"));
698        assert!(!same_id("", ""));
699    }
700
701    /// c9's finding: the gate counted a claim before Hive answered, so
702    /// refused claims ate today's budget until this machine refused on its
703    /// own. Now only a granted claim counts.
704    #[test]
705    fn only_a_granted_claim_counts_against_the_local_budget() {
706        let dir = tempfile::tempdir().unwrap();
707        let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
708        prepare_enrollment(&store).unwrap();
709        let cap = HiveWorkerConfig {
710            max_tasks_per_day: Some(2),
711            ..HiveWorkerConfig::default()
712        };
713        // Hive refuses every one of these (say `task_claimed`): the gate
714        // admitted them, nothing was granted, nothing counts.
715        for _ in 0..5 {
716            assert!(admit_claim_for(&store, &cap, &org(), &optin()).is_ok());
717        }
718        assert_eq!(read_state(&store).used.tasks, 0);
719        // Two granted claims use the local cap of two.
720        count_claim(&store).unwrap();
721        count_claim(&store).unwrap();
722        assert_eq!(read_state(&store).used.tasks, 2);
723        assert_eq!(
724            admit_claim_for(&store, &cap, &org(), &optin()),
725            Err(Refusal::BudgetExhausted(Limit::Tasks))
726        );
727    }
728
729    #[test]
730    fn an_agent_deleting_the_state_file_leaves_the_worker_paused() {
731        let dir = tempfile::tempdir().unwrap();
732        let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
733        // Enrollment writes the state first: a fresh engine is not paused.
734        prepare_enrollment(&store).unwrap();
735        enroll(&store);
736        assert!(!read_state(&store).paused, "a fresh enrollment runs");
737        set_paused(&store, true).unwrap();
738        prepare_enrollment(&store).unwrap();
739        assert!(read_state(&store).paused, "enrolling again keeps the pause");
740
741        let dir = tempfile::tempdir().unwrap();
742        let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
743        enroll(&store);
744        assert!(
745            read_state(&store).paused,
746            "an enrolled engine without its state counts as paused"
747        );
748        set_paused(&store, false).unwrap();
749        assert!(!read_state(&store).paused, "the person resumed it");
750        set_paused(&store, true).unwrap();
751        std::fs::remove_file(store.data_dir().join(STATE_FILE)).unwrap();
752        assert!(
753            read_state(&store).paused,
754            "a deleted file never lifts the pause"
755        );
756    }
757
758    fn enroll(store: &HiveStore) {
759        store
760            .write_config(
761                super::super::state::INSTANCE_FILE,
762                &super::super::state::InstanceRecord {
763                    instance_id: "inst_1".into(),
764                    org_id: "org_1".into(),
765                    org_name: "Acme".into(),
766                    label: "laptop".into(),
767                    url: "https://hive.example.com".into(),
768                    org_salt_id: "salt_1".into(),
769                    enrolled_at: "2026-10-22T12:00:00Z".into(),
770                    web_url: None,
771                    org_kind: None,
772                    company_name: None,
773                },
774            )
775            .unwrap();
776    }
777
778    #[test]
779    fn a_damaged_state_file_counts_as_paused() {
780        let dir = tempfile::tempdir().unwrap();
781        let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
782        assert!(!read_state(&store).paused, "no file yet: never paused");
783        write_private(store.data_dir(), STATE_FILE, b"{not json").unwrap();
784        assert!(read_state(&store).paused, "a broken file fails closed");
785        // Lifting it takes an explicit resume, which writes a sound file.
786        set_paused(&store, false).unwrap();
787        assert!(!read_state(&store).paused);
788    }
789
790    #[test]
791    fn usage_counts_per_day_and_pause_survives_it() {
792        let dir = tempfile::tempdir().unwrap();
793        let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
794        admit_submit(
795            &store,
796            &EvidenceSummary {
797                usage_tokens: 300,
798                usage_usd_micros: 40,
799            },
800        )
801        .unwrap();
802        set_paused(&store, true).unwrap();
803        let state = read_state(&store);
804        assert!(state.paused);
805        assert_eq!(state.used.tokens, 300);
806        assert_eq!(state.used.usd_micros, 40);
807
808        // A new day starts with empty counters; the pause stays.
809        let mut stale = state.clone();
810        stale.day = "2000-01-01".into();
811        write_private(
812            store.data_dir(),
813            STATE_FILE,
814            &serde_json::to_vec(&stale).unwrap(),
815        )
816        .unwrap();
817        let state = read_state(&store);
818        assert!(state.paused);
819        assert_eq!(state.used, Usage::default());
820        set_paused(&store, false).unwrap();
821        assert!(!read_state(&store).paused);
822    }
823}