Skip to main content

lean_ctx_cloud/
worker.rs

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