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. The owner turns it on again on the web, or the
21//!   person at this computer in LeanCTX Code signing with its own opt-in key
22//!   (rc4-16, `local_read::pickup_part`).
23//!
24//! Cloud 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 lean_ctx_time::UtcDateTime;
32use serde::{Deserialize, Serialize};
33
34use super::CloudError;
35use super::auth::Session;
36use super::state::{CloudStore, write_private};
37use super::transport::CloudClient;
38use lean_ctx_protocol::cloud::optin::{ENGINE_OPTIN_STOP_SCHEMA, EngineOptinStopV1, EngineOptinV1};
39
40/// The engine's own opt-in record (engine auth, own instance only).
41pub const OPTIN_PATH: &str = "/me/optin";
42/// The provider-terms note every worker opt-in shows (plan X1; the web
43/// opt-in form carries the same text). LeanCTX never handles subscription
44/// credentials: the agent is one the person started and signed in to.
45pub const PROVIDER_TERMS_NOTE: &str = "\
46You use your own subscription; follow your provider's terms. LeanCTX never sees,
47stores or routes your provider login: your agent runs in a session you started
48and signed in to yourself. Not allowed by the providers: OpenCode or Pi signed in
49with a Claude Pro or Max login, and third-party tools using a Gemini CLI login
50(OAuth). Use the provider's own agent or an API key instead.";
51
52const STATE_FILE: &str = "worker.json";
53const LOCK_FILE: &str = "worker.lock";
54
55pub use lean_ctx::core::config::cloud::CloudWorkerConfig;
56
57/// What a day has used on this machine.
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(default)]
60pub struct Usage {
61    pub tasks: u64,
62    pub tokens: u64,
63    pub usd_micros: u64,
64}
65
66/// The engine's opt-in (C0 1.9 section 4).
67pub type Optin = EngineOptinV1;
68
69/// The local worker state: pause flag and what this machine used today.
70#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(default)]
72pub struct WorkerState {
73    pub paused: bool,
74    /// The person turned task pickup off (rc4-16). Durable: `cloud worker
75    /// resume` lifts only `paused`, never this; only a turn-on LeanCTX Code
76    /// signed with its opt-in key clears it ([`clear_off`]), and so does an
77    /// opt-in the person turned on on the web ([`reconcile`]).
78    pub explicit_off: bool,
79    /// The opt-in id that was current when this computer turned task pickup
80    /// off; empty when none was active then, `None` when it is not known
81    /// yet. The id rotates on every stop and turn-on, so an active opt-in
82    /// with another id was turned on after this off, on the web.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub stopped_optin_id: Option<String>,
85    /// Set by enrollment only: a first turn-on may be preselected
86    /// (`suggest_on`). A state written again after its file went missing
87    /// lacks it, so deleting the file never brings the suggestion back.
88    pub enrolled_fresh: bool,
89    /// UTC day the counters belong to (`YYYY-MM-DD`).
90    pub day: String,
91    pub used: Usage,
92}
93
94impl WorkerState {
95    fn today(mut self, day: &str) -> Self {
96        if self.day != day {
97            day.clone_into(&mut self.day);
98            self.used = Usage::default();
99        }
100        self
101    }
102}
103
104/// The task a claim or result is for.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct TaskScope {
107    pub task_id: String,
108    /// The Cloud project (repo) id.
109    pub vault_id: String,
110}
111
112/// What a result reports it cost, for today's budget.
113#[derive(Debug, Clone, Default, PartialEq, Eq)]
114pub struct EvidenceSummary {
115    pub usage_tokens: u64,
116    pub usage_usd_micros: u64,
117}
118
119/// What is left of today's budget; `None` is no limit.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct BudgetLeft {
122    pub tasks: Option<u64>,
123    pub tokens: Option<u64>,
124    pub usd_micros: Option<u64>,
125}
126
127/// An admitted claim: the opt-in it works under and what is left after it.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Admission {
130    pub optin_id: Option<String>,
131    pub budget_left: BudgetLeft,
132}
133
134/// The limit a budget refusal hit.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum Limit {
137    Tasks,
138    Tokens,
139    UsdMicros,
140}
141
142/// Why the gate refused; its text never names the task or its content.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum Refusal {
145    /// This engine has no opt-in, or it does not cover the task.
146    NotOptedIn,
147    /// The opt-in was stopped; only the owner turns it on again.
148    Stopped,
149    /// `cloud worker pause` is in effect on this machine.
150    Paused,
151    BudgetExhausted(Limit),
152    /// The opt-in could not be read; nothing is claimed without it.
153    Unavailable(String),
154}
155
156impl fmt::Display for Refusal {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            Self::NotOptedIn => f.write_str(
160                "worker mode is not enabled for this task (opt in for its vault on the web)",
161            ),
162            Self::Stopped => {
163                f.write_str("worker mode was stopped for this computer (the owner turns it on again on the web or in LeanCTX Code)")
164            }
165            Self::Paused => f.write_str(
166                "worker mode is paused on this machine; the person resumes it with `lean-ctx cloud worker resume` in their own terminal",
167            ),
168            Self::BudgetExhausted(limit) => write!(
169                f,
170                "today's worker budget is used up ({})",
171                match limit {
172                    Limit::Tasks => "tasks",
173                    Limit::Tokens => "tokens",
174                    Limit::UsdMicros => "USD",
175                }
176            ),
177            Self::Unavailable(why) => write!(f, "the worker opt-in cannot be read ({why})"),
178        }
179    }
180}
181
182impl std::error::Error for Refusal {}
183
184/// A refusal reaches the caller with its own (content-free) words.
185impl From<Refusal> for CloudError {
186    fn from(refusal: Refusal) -> Self {
187        Self::Refused(refusal.to_string())
188    }
189}
190
191/// Repo ids compare without their wire prefix (`prj_`), dashes and case:
192/// Cloud writes a project id as 32 hex digits and an opt-in repo as a dashed
193/// UUID.
194fn same_id(a: &str, b: &str) -> bool {
195    let norm = |s: &str| {
196        let bare = match s.split_once('_') {
197            Some((prefix, rest))
198                if !prefix.is_empty()
199                    && prefix.len() <= 8
200                    && prefix.bytes().all(|b| b.is_ascii_lowercase()) =>
201            {
202                rest
203            }
204            _ => s,
205        };
206        bare.chars()
207            .filter(|c| *c != '-')
208            .map(|c| c.to_ascii_lowercase())
209            .collect::<String>()
210    };
211    !a.is_empty() && norm(a) == norm(b)
212}
213
214fn left(limit: Option<u64>, local: Option<u64>, used: u64) -> Option<u64> {
215    let limit = match (limit, local) {
216        (Some(a), Some(b)) => Some(a.min(b)),
217        (a, b) => a.or(b),
218    };
219    limit.map(|l| l.saturating_sub(used))
220}
221
222/// The claim decision on a read opt-in and the local state (no I/O).
223pub fn decide_claim(
224    optin: &Optin,
225    local: &CloudWorkerConfig,
226    state: &WorkerState,
227    scope: &TaskScope,
228) -> Result<Admission, Refusal> {
229    if state.paused {
230        return Err(Refusal::Paused);
231    }
232    if state.explicit_off {
233        return Err(Refusal::Stopped);
234    }
235    if optin.optin_id.is_none() {
236        return Err(Refusal::NotOptedIn);
237    }
238    if !optin.active {
239        return Err(Refusal::Stopped);
240    }
241    let budget = optin.daily_budget;
242    if !optin.vaults.iter().any(|r| same_id(r, &scope.vault_id)) {
243        return Err(Refusal::NotOptedIn);
244    }
245    // The server counts the engine, this machine counts itself: the higher
246    // of the two is today's use.
247    let used = Usage {
248        tasks: u64::from(optin.used_today.tasks).max(state.used.tasks),
249        tokens: optin.used_today.tokens.max(state.used.tokens),
250        usd_micros: optin.used_today.usd_micros.max(state.used.usd_micros),
251    };
252    // Cloud task #19: no task limit on the server and none here is none.
253    let tasks = left(
254        budget.tasks.map(u64::from),
255        local.max_tasks_per_day.map(u64::from),
256        used.tasks,
257    );
258    let tokens = left(budget.tokens, local.max_tokens_per_day, used.tokens);
259    let usd_micros = left(
260        budget.usd_micros,
261        local.max_usd_micros_per_day,
262        used.usd_micros,
263    );
264    for (rest, limit) in [
265        (tasks, Limit::Tasks),
266        (tokens, Limit::Tokens),
267        (usd_micros, Limit::UsdMicros),
268    ] {
269        if rest == Some(0) {
270            return Err(Refusal::BudgetExhausted(limit));
271        }
272    }
273    Ok(Admission {
274        optin_id: optin.optin_id.clone(),
275        budget_left: BudgetLeft {
276            // The claim this admits counts one.
277            tasks: tasks.map(|t| t - 1),
278            tokens,
279            usd_micros,
280        },
281    })
282}
283
284fn day() -> String {
285    UtcDateTime::now().format("%Y-%m-%d").to_string()
286}
287
288/// Read-modify-write the worker state under its lock.
289fn with_state<T>(
290    store: &CloudStore,
291    change: impl FnOnce(&mut WorkerState) -> T,
292) -> Result<T, CloudError> {
293    let dir = store.data_dir();
294    std::fs::create_dir_all(dir).map_err(|e| CloudError::Local(format!("worker: {e}")))?;
295    let _lock = lean_ctx::core::agents::FileLock::acquire(&dir.join(LOCK_FILE))
296        .map_err(|e| CloudError::Local(format!("worker lock: {e}")))?;
297    let mut state = read_state(store).today(&day());
298    let out = change(&mut state);
299    let bytes = serde_json::to_vec(&state).map_err(|e| CloudError::Local(e.to_string()))?;
300    write_private(dir, STATE_FILE, &bytes)?;
301    Ok(out)
302}
303
304/// Write the state before the engine enrolls, so that a missing one after
305/// enrollment can only mean it was deleted. A state already there, paused
306/// or not, stays as it is; the web opt-in still gates every claim.
307pub(crate) fn prepare_enrollment(store: &CloudStore) -> Result<(), CloudError> {
308    with_state(store, |state| state.enrolled_fresh = true)
309}
310
311/// The local state as stored (today's counters reset on a new day). Fail
312/// closed: a file that cannot be read or parsed counts as paused, and so
313/// does a missing one on an engine enrolled with Cloud — deleting it never
314/// lifts a pause or resets today's counts. Only enrollment
315/// (`prepare_enrollment`) and `cloud worker resume`, both of which the
316/// person runs (an agent shell refuses them), write it unpaused.
317pub fn read_state(store: &CloudStore) -> WorkerState {
318    let paused = || WorkerState {
319        paused: true,
320        ..WorkerState::default()
321    };
322    // A damaged or unreadable file also counts as an explicit off: only the
323    // app's signed turn-on lifts it. A missing file does not (rc4-16): a
324    // state never written (a fresh or older engine) cannot be told apart
325    // from a deleted one, and an update must not stop a worker the Cloud
326    // has on.
327    let damaged = || WorkerState {
328        explicit_off: true,
329        ..paused()
330    };
331    let state = match std::fs::read(store.data_dir().join(STATE_FILE)) {
332        Ok(bytes) => serde_json::from_slice::<WorkerState>(&bytes).unwrap_or_else(|_| damaged()),
333        Err(e) if e.kind() == std::io::ErrorKind::NotFound => match store.instance() {
334            Ok(None) => WorkerState::default(),
335            Ok(Some(_)) | Err(_) => paused(),
336        },
337        Err(_) => damaged(),
338    };
339    state.today(&day())
340}
341
342/// The server's opt-in for this engine.
343pub fn fetch_optin(session: &Session) -> Result<Optin, CloudError> {
344    parse_optin(session.with_client(|c| c.get(OPTIN_PATH))?)
345}
346
347/// The opt-in through `client` (a bounded client of a tool call).
348pub fn fetch_optin_via(client: &CloudClient) -> Result<Optin, CloudError> {
349    parse_optin(client.get(OPTIN_PATH)?)
350}
351
352/// An opt-in as Cloud answers it, checked.
353pub fn parse_optin(body: serde_json::Value) -> Result<Optin, CloudError> {
354    let optin: Optin =
355        serde_json::from_value(body).map_err(|e| CloudError::Protocol(format!("opt-in: {e}")))?;
356    optin
357        .validate()
358        .map_err(|e| CloudError::Protocol(format!("opt-in: {e}")))?;
359    Ok(optin)
360}
361
362/// Admit a claim: whether this machine may ask Cloud for it. Nothing is
363/// counted yet; [`count_claim`] counts it once Cloud granted it, so a claim
364/// Cloud refuses costs no task of today's budget.
365pub fn admit_claim(
366    session: &Session,
367    local: &CloudWorkerConfig,
368    scope: &TaskScope,
369) -> Result<Admission, Refusal> {
370    let optin = fetch_optin(session).map_err(|e| Refusal::Unavailable(e.to_string()))?;
371    admit_claim_for(&session.store, local, scope, &optin)
372}
373
374/// [`admit_claim`] on an opt-in the caller just read.
375pub fn admit_claim_for(
376    store: &CloudStore,
377    local: &CloudWorkerConfig,
378    scope: &TaskScope,
379    optin: &Optin,
380) -> Result<Admission, Refusal> {
381    with_state(store, |state| {
382        reconcile(state, optin);
383        decide_claim(optin, local, state, scope)
384    })
385    .map_err(|e| Refusal::Unavailable(e.to_string()))?
386}
387
388/// Bring the kept off in line with the Cloud's opt-in (pure; rc4-16 M3):
389/// an active opt-in with another id than the one this computer stopped
390/// was turned on by the person on the web, and lifts the off and the
391/// pause the stop set. The same id keeps the off. An off whose id is not
392/// known yet (the stop did not reach the Cloud, or the file was damaged)
393/// takes the id seen now as the stopped one: it stays off. Returns whether
394/// `state` changed.
395pub fn reconcile(state: &mut WorkerState, optin: &Optin) -> bool {
396    if !state.explicit_off {
397        return false;
398    }
399    let Some(id) = optin.optin_id.as_deref() else {
400        return false;
401    };
402    match state.stopped_optin_id.as_deref() {
403        Some(stopped) if stopped == id => false,
404        Some(_) if optin.active => {
405            state.paused = false;
406            state.explicit_off = false;
407            state.stopped_optin_id = None;
408            true
409        }
410        // Not known yet, or a later stop (on the web): this one stays off.
411        _ => {
412            state.stopped_optin_id = Some(id.to_owned());
413            true
414        }
415    }
416}
417
418/// The local state after [`reconcile`] with `optin` the Cloud just
419/// answered: written only when it changed.
420pub fn observe(store: &CloudStore, optin: &Optin) -> Result<WorkerState, CloudError> {
421    let state = read_state(store);
422    if !reconcile(&mut state.clone(), optin) {
423        return Ok(state);
424    }
425    with_state(store, |state| {
426        reconcile(state, optin);
427        state.clone()
428    })
429}
430
431/// Count a claim Cloud granted (or a verification commit it took) against
432/// today's tasks on this machine. A refused claim is never counted: it
433/// used to be, and refusals then ate the local budget until this machine
434/// refused on its own.
435pub fn count_claim(store: &CloudStore) -> Result<(), CloudError> {
436    with_state(store, |state| state.used.tasks += 1)
437}
438
439/// Add the usage a result reports to today's.
440pub fn admit_submit(store: &CloudStore, evidence: &EvidenceSummary) -> Result<(), Refusal> {
441    with_state(store, |state| {
442        state.used.tokens = state.used.tokens.saturating_add(evidence.usage_tokens);
443        state.used.usd_micros = state
444            .used
445            .usd_micros
446            .saturating_add(evidence.usage_usd_micros);
447    })
448    .map_err(|e| Refusal::Unavailable(e.to_string()))
449}
450
451/// Stop or resume claiming on this machine. Resuming never lifts an
452/// explicit off.
453pub fn set_paused(store: &CloudStore, paused: bool) -> Result<(), CloudError> {
454    with_state(store, |state| state.paused = paused)
455}
456
457/// Lift the pause and the explicit off: only after the Cloud took a turn-on
458/// LeanCTX Code signed with its opt-in key (rc4-16).
459pub fn clear_off(store: &CloudStore) -> Result<(), CloudError> {
460    with_state(store, |state| {
461        state.paused = false;
462        state.explicit_off = false;
463        state.stopped_optin_id = None;
464    })
465}
466
467/// A turn-on the Cloud did not take: its status and answer.
468pub type TurnOnRefused = (u16, serde_json::Value);
469
470/// Send the app-signed turn-on `signed` (the caller checked its
471/// signature) unchanged. Only a 2xx answer carrying a valid opt-in lifts
472/// the off and the pause here ([`clear_off`]); any other answer, or none,
473/// leaves them as they were. A refusal comes back with its status and
474/// answer for the caller's words.
475pub fn send_turn_on(
476    session: &Session,
477    signed: &serde_json::Value,
478) -> Result<Result<Optin, TurnOnRefused>, CloudError> {
479    let (status, answer) = session.with_client(|client| {
480        let (status, answer) = client.send_answer(
481            "PUT",
482            OPTIN_PATH,
483            Some(signed),
484            lean_ctx_protocol::cloud::MAX_BODY_BYTES,
485        )?;
486        if status == 401 {
487            return Err(CloudError::Unauthorized);
488        }
489        Ok((status, answer))
490    })?;
491    if !(200..300).contains(&status) {
492        return Ok(Err((status, answer)));
493    }
494    let optin = parse_optin(answer)?;
495    // The person's signed click lifts the off kept here.
496    clear_off(&session.store)?;
497    Ok(Ok(optin))
498}
499
500/// Stop worker mode for this engine: pause here and switch the opt-in off
501/// on the server, which ends every claim of this engine at once. The off
502/// is kept here first; the stopped opt-in's id is kept with it
503/// ([`reconcile`]). A Cloud without an active opt-in (409
504/// `optin_inactive`) is already off: that is a success, kept with an
505/// empty id, so any opt-in turned on later lifts the off.
506pub fn stop(session: &Session) -> Result<(), CloudError> {
507    with_state(&session.store, |state| {
508        state.paused = true;
509        state.explicit_off = true;
510    })?;
511    let stop = serde_json::to_value(EngineOptinStopV1 {
512        schema: ENGINE_OPTIN_STOP_SCHEMA.into(),
513        active: false,
514    })
515    .map_err(|e| CloudError::Local(e.to_string()))?;
516    let answer = session.with_client(|c| {
517        c.send(
518            "PUT",
519            OPTIN_PATH,
520            Some(&stop),
521            &[],
522            lean_ctx_protocol::cloud::MAX_BODY_BYTES,
523        )
524        .map(|r| r.body)
525    });
526    let stopped_id = match answer {
527        Ok(body) => parse_optin(body)?.optin_id.unwrap_or_default(),
528        Err(CloudError::Task {
529            refusal: crate::TaskRefusal::OptinInactive,
530            ..
531        }) => String::new(),
532        Err(e) => return Err(e),
533    };
534    note_stopped(&session.store, stopped_id)
535}
536
537/// Keep `id` as the opt-in this computer stopped, while the off holds.
538fn note_stopped(store: &CloudStore, id: String) -> Result<(), CloudError> {
539    with_state(store, |state| {
540        if state.explicit_off {
541            state.stopped_optin_id = Some(id);
542        }
543    })
544}
545
546#[cfg(test)]
547mod tests {
548    use super::*;
549    use lean_ctx_protocol::cloud::optin::ENGINE_OPTIN_SCHEMA;
550    use serde_json::Value;
551    use serde_json::json;
552
553    const REPO: &str = "0b7c3c1e5d2a4f7e9a312c4d5e6f7a8b";
554
555    fn optin() -> Optin {
556        parse_optin(json!({
557            "schema": ENGINE_OPTIN_SCHEMA,
558            "optin_id": "opt_1",
559            "active": true,
560            "vaults": [REPO],
561            "networks": [],
562            "topics": [],
563            "daily_budget": {"tasks": 2, "tokens": 1000},
564            "used_today": {"day": "2026-10-22", "tasks": 0, "tokens": 0, "usd_micros": 0},
565            "updated_at": "2026-10-22T10:00:00Z"
566        }))
567        .unwrap()
568    }
569
570    fn org() -> TaskScope {
571        TaskScope {
572            task_id: "7".into(),
573            vault_id: REPO.into(),
574        }
575    }
576
577    #[test]
578    fn a_claim_needs_an_active_opt_in_that_covers_the_task() {
579        let local = CloudWorkerConfig::default();
580        let state = WorkerState::default();
581        let admitted = decide_claim(&optin(), &local, &state, &org()).unwrap();
582        assert_eq!(admitted.optin_id.as_deref(), Some("opt_1"));
583        assert_eq!(admitted.budget_left.tasks, Some(1));
584        assert_eq!(admitted.budget_left.tokens, Some(1000));
585        assert_eq!(admitted.budget_left.usd_micros, None);
586
587        let other = TaskScope {
588            vault_id: "ffffffffffffffffffffffffffffffff".into(),
589            ..org()
590        };
591        assert_eq!(
592            decide_claim(&optin(), &local, &state, &other),
593            Err(Refusal::NotOptedIn)
594        );
595        let none = parse_optin(json!({
596            "schema": ENGINE_OPTIN_SCHEMA, "active": false, "vaults": [], "networks": [], "topics": [],
597            "daily_budget": {"tasks": 5},
598            "used_today": {"day": "2026-10-22", "tasks": 0, "tokens": 0, "usd_micros": 0}
599        }))
600        .unwrap();
601        assert_eq!(
602            decide_claim(&none, &local, &state, &org()),
603            Err(Refusal::NotOptedIn)
604        );
605        let stopped = Optin {
606            active: false,
607            ..optin()
608        };
609        assert_eq!(
610            decide_claim(&stopped, &local, &state, &org()),
611            Err(Refusal::Stopped)
612        );
613        let paused = WorkerState {
614            paused: true,
615            ..WorkerState::default()
616        };
617        assert_eq!(
618            decide_claim(&optin(), &local, &paused, &org()),
619            Err(Refusal::Paused)
620        );
621    }
622
623    /// Cloud task #19: an opt-in without a task limit (C0 §4 erratum) admits
624    /// on count however many tasks the day has seen; a local cap still
625    /// applies.
626    #[test]
627    fn no_task_limit_admits_on_count_and_a_local_cap_still_holds() {
628        let mut free = optin();
629        free.daily_budget.tasks = None;
630        free.daily_budget.tokens = None;
631        free.used_today.tasks = 140;
632        let state = WorkerState::default();
633        let admitted = decide_claim(&free, &CloudWorkerConfig::default(), &state, &org()).unwrap();
634        assert_eq!(admitted.budget_left.tasks, None, "no limit stays no limit");
635        let capped = CloudWorkerConfig {
636            max_tasks_per_day: Some(150),
637            ..CloudWorkerConfig::default()
638        };
639        assert_eq!(
640            decide_claim(&free, &capped, &state, &org())
641                .unwrap()
642                .budget_left
643                .tasks,
644            Some(9)
645        );
646        free.used_today.tasks = 150;
647        assert_eq!(
648            decide_claim(&free, &capped, &state, &org()),
649            Err(Refusal::BudgetExhausted(Limit::Tasks))
650        );
651        // As Cloud sends it: no `tasks` field at all.
652        let wire = parse_optin(json!({
653            "schema": ENGINE_OPTIN_SCHEMA, "optin_id": "opt_2", "active": true,
654            "vaults": [REPO], "networks": [], "topics": [], "daily_budget": {},
655            "used_today": {"day": "2026-10-22", "tasks": 140, "tokens": 0, "usd_micros": 0}
656        }))
657        .unwrap();
658        assert!(decide_claim(&wire, &CloudWorkerConfig::default(), &state, &org()).is_ok());
659    }
660
661    #[test]
662    fn the_first_limit_reached_stops_and_local_caps_only_tighten() {
663        let state = WorkerState::default();
664        let mut spent = optin();
665        spent.used_today.tasks = 2;
666        assert_eq!(
667            decide_claim(&spent, &CloudWorkerConfig::default(), &state, &org()),
668            Err(Refusal::BudgetExhausted(Limit::Tasks))
669        );
670        let mut tokens = optin();
671        tokens.used_today.tokens = 1200;
672        assert_eq!(
673            decide_claim(&tokens, &CloudWorkerConfig::default(), &state, &org()),
674            Err(Refusal::BudgetExhausted(Limit::Tokens))
675        );
676
677        // A wider local cap does not widen the server's budget.
678        let wide = CloudWorkerConfig {
679            max_tasks_per_day: Some(50),
680            max_tokens_per_day: Some(1_000_000),
681            max_usd_micros_per_day: None,
682        };
683        assert_eq!(
684            decide_claim(&spent, &wide, &state, &org()),
685            Err(Refusal::BudgetExhausted(Limit::Tasks))
686        );
687        // A tighter one applies, also to a limit the server leaves open.
688        let tight = CloudWorkerConfig {
689            max_tasks_per_day: Some(1),
690            max_tokens_per_day: None,
691            max_usd_micros_per_day: Some(500),
692        };
693        let one_done = WorkerState {
694            used: Usage {
695                tasks: 1,
696                ..Usage::default()
697            },
698            ..WorkerState::default()
699        };
700        assert_eq!(
701            decide_claim(&optin(), &tight, &one_done, &org()),
702            Err(Refusal::BudgetExhausted(Limit::Tasks)),
703            "the machine's own count holds when the server's is behind"
704        );
705        let admitted = decide_claim(&optin(), &tight, &state, &org()).unwrap();
706        assert_eq!(admitted.budget_left.usd_micros, Some(500));
707        let usd_spent = WorkerState {
708            used: Usage {
709                usd_micros: 500,
710                ..Usage::default()
711            },
712            ..WorkerState::default()
713        };
714        assert_eq!(
715            decide_claim(&optin(), &tight, &usd_spent, &org()),
716            Err(Refusal::BudgetExhausted(Limit::UsdMicros))
717        );
718    }
719
720    #[test]
721    fn opt_ins_follow_the_section_4_contract() {
722        let fixture: serde_json::Value = serde_json::from_str(include_str!(
723            "../../../crates/lean-ctx-protocol/tests/fixtures/cloud/instance_optin.response.json"
724        ))
725        .unwrap();
726        let optin = parse_optin(fixture.clone()).unwrap();
727        assert!(optin.active && optin.optin_id.is_some());
728
729        let mut wrong = fixture.clone();
730        wrong["schema"] = json!("leanctx.cloud.instance-optin/v2");
731        assert!(matches!(parse_optin(wrong), Err(CloudError::Protocol(_))));
732        // Active without an opt-in id breaks the contract: fail closed.
733        let mut broken = fixture;
734        broken.as_object_mut().unwrap().remove("optin_id");
735        assert!(matches!(parse_optin(broken), Err(CloudError::Protocol(_))));
736
737        let stop = serde_json::to_value(EngineOptinStopV1 {
738            schema: ENGINE_OPTIN_STOP_SCHEMA.into(),
739            active: false,
740        })
741        .unwrap();
742        assert_eq!(
743            stop,
744            serde_json::from_str::<serde_json::Value>(include_str!(
745                "../../../crates/lean-ctx-protocol/tests/fixtures/cloud/instance_optin_stop.request.json"
746            ))
747            .unwrap()
748        );
749    }
750
751    #[test]
752    fn refusals_name_no_task_and_reach_the_caller_in_their_own_words() {
753        for refusal in [
754            Refusal::NotOptedIn,
755            Refusal::Stopped,
756            Refusal::Paused,
757            Refusal::BudgetExhausted(Limit::Tokens),
758        ] {
759            let text = refusal.to_string();
760            assert!(!text.contains(REPO), "{text}");
761            assert_eq!(CloudError::from(refusal).to_string(), text);
762        }
763    }
764
765    #[test]
766    fn ids_match_across_wire_prefix_dashes_and_case() {
767        let uuid = "558f6ef0-1c2d-4e5f-8a9b-0c1d2e3f4a5b";
768        assert!(same_id(uuid, "558f6ef01c2d4e5f8a9b0c1d2e3f4a5b"));
769        assert!(same_id("prj_558F6EF01C2D4E5F8A9B0C1D2E3F4A5B", uuid));
770        assert!(!same_id(uuid, "prj_658f6ef01c2d4e5f8a9b0c1d2e3f4a5b"));
771        assert!(!same_id("", ""));
772    }
773
774    /// c9's finding: the gate counted a claim before Cloud answered, so
775    /// refused claims ate today's budget until this machine refused on its
776    /// own. Now only a granted claim counts.
777    #[test]
778    fn only_a_granted_claim_counts_against_the_local_budget() {
779        let dir = tempfile::tempdir().unwrap();
780        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
781        prepare_enrollment(&store).unwrap();
782        let cap = CloudWorkerConfig {
783            max_tasks_per_day: Some(2),
784            ..CloudWorkerConfig::default()
785        };
786        // Cloud refuses every one of these (say `task_claimed`): the gate
787        // admitted them, nothing was granted, nothing counts.
788        for _ in 0..5 {
789            assert!(admit_claim_for(&store, &cap, &org(), &optin()).is_ok());
790        }
791        assert_eq!(read_state(&store).used.tasks, 0);
792        // Two granted claims use the local cap of two.
793        count_claim(&store).unwrap();
794        count_claim(&store).unwrap();
795        assert_eq!(read_state(&store).used.tasks, 2);
796        assert_eq!(
797            admit_claim_for(&store, &cap, &org(), &optin()),
798            Err(Refusal::BudgetExhausted(Limit::Tasks))
799        );
800    }
801
802    #[test]
803    fn an_agent_deleting_the_state_file_leaves_the_worker_paused() {
804        let dir = tempfile::tempdir().unwrap();
805        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
806        // Enrollment writes the state first: a fresh engine is not paused.
807        prepare_enrollment(&store).unwrap();
808        enroll(&store);
809        assert!(!read_state(&store).paused, "a fresh enrollment runs");
810        set_paused(&store, true).unwrap();
811        prepare_enrollment(&store).unwrap();
812        assert!(read_state(&store).paused, "enrolling again keeps the pause");
813
814        let dir = tempfile::tempdir().unwrap();
815        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
816        enroll(&store);
817        assert!(
818            read_state(&store).paused,
819            "an enrolled engine without its state counts as paused"
820        );
821        set_paused(&store, false).unwrap();
822        assert!(!read_state(&store).paused, "the person resumed it");
823        set_paused(&store, true).unwrap();
824        std::fs::remove_file(store.data_dir().join(STATE_FILE)).unwrap();
825        assert!(
826            read_state(&store).paused,
827            "a deleted file never lifts the pause"
828        );
829    }
830
831    fn enroll(store: &CloudStore) {
832        store
833            .write_config(
834                super::super::state::INSTANCE_FILE,
835                &super::super::state::InstanceRecord {
836                    instance_id: "inst_1".into(),
837                    org_id: "org_1".into(),
838                    org_name: "Acme".into(),
839                    label: "laptop".into(),
840                    url: "https://cloud.example.com".into(),
841                    org_salt_id: "salt_1".into(),
842                    enrolled_at: "2026-10-22T12:00:00Z".into(),
843                    web_url: None,
844                    org_kind: None,
845                    company_name: None,
846                },
847            )
848            .unwrap();
849    }
850
851    #[test]
852    fn pickup_resume_never_lifts_an_explicit_off() {
853        let dir = tempfile::tempdir().unwrap();
854        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
855        prepare_enrollment(&store).unwrap();
856        enroll(&store);
857        // The person turned task pickup off (what `stop` writes first).
858        with_state(&store, |state| {
859            state.paused = true;
860            state.explicit_off = true;
861        })
862        .unwrap();
863        // `cloud worker resume` (an agent can run it) lifts only the pause.
864        set_paused(&store, false).unwrap();
865        let state = read_state(&store);
866        assert!(!state.paused && state.explicit_off, "the off stays");
867        assert_eq!(
868            decide_claim(&optin(), &CloudWorkerConfig::default(), &state, &org()),
869            Err(Refusal::Stopped)
870        );
871        // A damaged file fails closed on the off too.
872        write_private(store.data_dir(), STATE_FILE, b"{not json").unwrap();
873        set_paused(&store, false).unwrap();
874        assert!(read_state(&store).explicit_off);
875        // Only the app's signed turn-on lifts it.
876        clear_off(&store).unwrap();
877        let state = read_state(&store);
878        assert!(!state.paused && !state.explicit_off);
879    }
880
881    #[test]
882    fn pickup_an_update_without_a_state_file_keeps_an_active_worker_on() {
883        let local = CloudWorkerConfig::default();
884        // An engine that never wrote the state (fresh, or older than it):
885        // with an active opt-in on the Cloud it claims as before.
886        let dir = tempfile::tempdir().unwrap();
887        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
888        let state = read_state(&store);
889        assert!(!state.explicit_off);
890        assert!(decide_claim(&optin(), &local, &state, &org()).is_ok());
891        // A state written before `explicit_off` existed reads as not off.
892        write_private(
893            store.data_dir(),
894            STATE_FILE,
895            br#"{"paused":false,"day":"2000-01-01","used":{}}"#,
896        )
897        .unwrap();
898        let state = read_state(&store);
899        assert!(!state.paused && !state.explicit_off);
900        assert!(decide_claim(&optin(), &local, &state, &org()).is_ok());
901        // A missing file never adds an explicit off on an enrolled engine.
902        std::fs::remove_file(store.data_dir().join(STATE_FILE)).unwrap();
903        enroll(&store);
904        assert!(!read_state(&store).explicit_off);
905    }
906
907    #[test]
908    fn a_damaged_state_file_counts_as_paused() {
909        let dir = tempfile::tempdir().unwrap();
910        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
911        assert!(!read_state(&store).paused, "no file yet: never paused");
912        write_private(store.data_dir(), STATE_FILE, b"{not json").unwrap();
913        assert!(read_state(&store).paused, "a broken file fails closed");
914        // Lifting it takes an explicit resume, which writes a sound file.
915        set_paused(&store, false).unwrap();
916        assert!(!read_state(&store).paused);
917    }
918
919    #[test]
920    fn usage_counts_per_day_and_pause_survives_it() {
921        let dir = tempfile::tempdir().unwrap();
922        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
923        admit_submit(
924            &store,
925            &EvidenceSummary {
926                usage_tokens: 300,
927                usage_usd_micros: 40,
928            },
929        )
930        .unwrap();
931        set_paused(&store, true).unwrap();
932        let state = read_state(&store);
933        assert!(state.paused);
934        assert_eq!(state.used.tokens, 300);
935        assert_eq!(state.used.usd_micros, 40);
936
937        // A new day starts with empty counters; the pause stays.
938        let mut stale = state.clone();
939        stale.day = "2000-01-01".into();
940        write_private(
941            store.data_dir(),
942            STATE_FILE,
943            &serde_json::to_vec(&stale).unwrap(),
944        )
945        .unwrap();
946        let state = read_state(&store);
947        assert!(state.paused);
948        assert_eq!(state.used, Usage::default());
949        set_paused(&store, false).unwrap();
950        assert!(!read_state(&store).paused);
951    }
952
953    fn optin_as(id: Option<&str>, active: bool) -> Optin {
954        let mut optin = optin();
955        optin.optin_id = id.map(str::to_owned);
956        optin.active = active;
957        optin
958    }
959
960    fn kept_off(stopped: Option<&str>) -> WorkerState {
961        WorkerState {
962            paused: true,
963            explicit_off: true,
964            stopped_optin_id: stopped.map(str::to_owned),
965            ..WorkerState::default()
966        }
967    }
968
969    #[test]
970    fn pickup_a_turn_on_on_the_web_lifts_the_kept_off_and_the_same_id_keeps_it() {
971        // The same id as the stopped one keeps the off, active or not.
972        for active in [false, true] {
973            let mut state = kept_off(Some("opt_2"));
974            assert!(!reconcile(&mut state, &optin_as(Some("opt_2"), active)));
975            assert_eq!(state, kept_off(Some("opt_2")));
976        }
977        // A new active id: the person turned it on on the web.
978        let mut state = kept_off(Some("opt_2"));
979        assert!(reconcile(&mut state, &optin_as(Some("opt_3"), true)));
980        assert!(!state.paused && !state.explicit_off && state.stopped_optin_id.is_none());
981        let scope = org();
982        assert!(decide_claim(&optin(), &CloudWorkerConfig::default(), &state, &scope).is_ok());
983        // Stopped without an active opt-in (empty id): any later one is new.
984        let mut state = kept_off(Some(""));
985        assert!(reconcile(&mut state, &optin_as(Some("opt_1"), true)));
986        assert!(!state.explicit_off);
987        // A new stopped id (stopped on the web too) is kept, still off.
988        let mut state = kept_off(Some("opt_2"));
989        assert!(reconcile(&mut state, &optin_as(Some("opt_4"), false)));
990        assert_eq!(state, kept_off(Some("opt_4")));
991        // Not known yet (the stop did not reach the Cloud, or a damaged
992        // state): the id read now counts as the stopped one.
993        let mut state = kept_off(None);
994        assert!(reconcile(&mut state, &optin_as(Some("opt_1"), true)));
995        assert_eq!(state, kept_off(Some("opt_1")));
996        assert!(!reconcile(&mut state, &optin_as(Some("opt_1"), true)));
997        // No opt-in row, or no off: nothing changes.
998        let mut state = kept_off(Some("opt_2"));
999        assert!(!reconcile(&mut state, &optin_as(None, false)));
1000        let mut on = WorkerState::default();
1001        assert!(!reconcile(&mut on, &optin_as(Some("opt_9"), true)));
1002        assert_eq!(on, WorkerState::default());
1003    }
1004
1005    #[test]
1006    fn pickup_only_enrollment_marks_a_state_that_may_suggest_on() {
1007        let dir = tempfile::tempdir().unwrap();
1008        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1009        prepare_enrollment(&store).unwrap();
1010        enroll(&store);
1011        assert!(read_state(&store).enrolled_fresh);
1012        // Deleted, then `cloud worker resume`: written again without it.
1013        std::fs::remove_file(store.data_dir().join(STATE_FILE)).unwrap();
1014        set_paused(&store, false).unwrap();
1015        let state = read_state(&store);
1016        assert!(!state.paused && !state.explicit_off && !state.enrolled_fresh);
1017    }
1018
1019    type Script = std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<(u16, Value)>>>;
1020    type Seen = std::sync::Arc<std::sync::Mutex<Vec<(String, Value)>>>;
1021
1022    /// A Cloud on 127.0.0.1 that mints tokens and answers every other
1023    /// request with the next of `answers`; those requests are recorded as
1024    /// method and path, with their body.
1025    fn cloud(answers: Vec<(u16, Value)>) -> (String, Seen) {
1026        use std::io::{BufRead as _, Read as _, Write as _};
1027        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1028        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
1029        let script: Script = std::sync::Arc::new(std::sync::Mutex::new(answers.into()));
1030        let seen = Seen::default();
1031        let recorded = std::sync::Arc::clone(&seen);
1032        std::thread::spawn(move || {
1033            for stream in listener.incoming().flatten() {
1034                let (script, recorded) = (
1035                    std::sync::Arc::clone(&script),
1036                    std::sync::Arc::clone(&recorded),
1037                );
1038                std::thread::spawn(move || {
1039                    let mut writer = stream.try_clone().unwrap();
1040                    let mut reader = std::io::BufReader::new(stream);
1041                    loop {
1042                        let mut line = String::new();
1043                        if reader.read_line(&mut line).unwrap_or(0) == 0 {
1044                            return;
1045                        }
1046                        let mut words = line.split_whitespace();
1047                        let method = words.next().unwrap_or_default().to_owned();
1048                        let path = words.next().unwrap_or_default().to_owned();
1049                        let mut length = 0usize;
1050                        loop {
1051                            let mut header = String::new();
1052                            reader.read_line(&mut header).unwrap();
1053                            let header = header.trim_end();
1054                            if header.is_empty() {
1055                                break;
1056                            }
1057                            if let Some((name, value)) = header.split_once(':')
1058                                && name.eq_ignore_ascii_case("content-length")
1059                            {
1060                                length = value.trim().parse().unwrap();
1061                            }
1062                        }
1063                        let mut body = vec![0; length];
1064                        reader.read_exact(&mut body).unwrap();
1065                        let (code, reply) = if path.ends_with("/token") {
1066                            let token = json!({"schema": "leanctx.cloud.access-token/v1",
1067                                "access_token": "test-access", "expires_in": 3600});
1068                            (200, token)
1069                        } else {
1070                            let body = serde_json::from_slice(&body).unwrap_or(Value::Null);
1071                            recorded
1072                                .lock()
1073                                .unwrap()
1074                                .push((format!("{method} {path}"), body));
1075                            script.lock().unwrap().pop_front().unwrap_or((
1076                                500,
1077                                json!({"error": {"code": "internal", "message": "x"}}),
1078                            ))
1079                        };
1080                        let text = reply.to_string();
1081                        let _ = write!(
1082                            writer,
1083                            "HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{text}",
1084                            text.len()
1085                        );
1086                    }
1087                });
1088            }
1089        });
1090        (origin, seen)
1091    }
1092
1093    fn optin_json(id: &str, active: bool) -> Value {
1094        let mut optin = serde_json::to_value(optin()).unwrap();
1095        optin["optin_id"] = json!(id);
1096        optin["active"] = json!(active);
1097        // The Cloud sets `stopped_at` exactly while an opt-in is inactive.
1098        optin["stopped_at"] = if active {
1099            Value::Null
1100        } else {
1101            json!("2026-10-20T12:00:00Z")
1102        };
1103        optin
1104    }
1105
1106    fn refusal(reason: &str) -> Value {
1107        json!({"error": {"code": "invalid_state", "message": "x", "reason": reason}})
1108    }
1109
1110    /// rc4-16 S2: turn off, failed turn-ons, the signed turn-on, a stop
1111    /// without an opt-in, then a turn-on on the web, against a Cloud.
1112    #[test]
1113    fn pickup_turn_on_and_off_against_a_cloud_lift_the_off_only_after_a_2xx() {
1114        let signed = json!({"schema": "leanctx.cloud.instance-optin-on/v1", "active": true,
1115            "prev_optin_id": "opt_2", "vaults": [REPO], "daily_budget": {"tasks": 2},
1116            "presence_signature": "sig"});
1117        let (origin, seen) = cloud(vec![
1118            (200, optin_json("opt_2", false)), // stop
1119            (409, refusal("optin_changed")),   // turn-on refused
1120            (
1121                403,
1122                json!({"error": {"code": "forbidden", "message": "x",
1123                "reason": "person_unproven"}}),
1124            ), // turn-on refused
1125            (200, json!({"not": "an opt-in"})), // 2xx without an opt-in
1126            (200, optin_json("opt_3", true)),  // the signed turn-on
1127            (409, refusal("optin_inactive")),  // stop, nothing active
1128        ]);
1129        let (_dir, session) = crate::auth::fixture_session_at(&origin);
1130        crate::instance_key::InstanceKeys::load_or_create(&session.store).unwrap();
1131        let store = &session.store;
1132        prepare_enrollment(store).unwrap();
1133        let off = |state: &WorkerState| state.paused && state.explicit_off;
1134
1135        stop(&session).unwrap();
1136        let state = read_state(store);
1137        assert!(off(&state));
1138        assert_eq!(state.stopped_optin_id.as_deref(), Some("opt_2"));
1139        // The stopped opt-in read again keeps the off.
1140        assert!(off(
1141            &observe(store, &optin_as(Some("opt_2"), false)).unwrap()
1142        ));
1143
1144        // Refused and broken answers never lift it.
1145        for status in [409, 403] {
1146            let refused = send_turn_on(&session, &signed).unwrap().unwrap_err();
1147            assert_eq!(refused.0, status);
1148            assert!(off(&read_state(store)), "{status} keeps the off");
1149        }
1150        assert!(send_turn_on(&session, &signed).is_err());
1151        assert!(off(&read_state(store)), "a 2xx without an opt-in keeps it");
1152
1153        // The signed turn-on the Cloud took lifts it.
1154        let on = send_turn_on(&session, &signed).unwrap().unwrap();
1155        assert_eq!(on.optin_id.as_deref(), Some("opt_3"));
1156        let state = read_state(store);
1157        assert!(!state.paused && !state.explicit_off && state.stopped_optin_id.is_none());
1158
1159        // A stop the Cloud answers `optin_inactive` is a success, kept off
1160        // with an empty id; a later turn-on on the web lifts it.
1161        stop(&session).unwrap();
1162        let state = read_state(store);
1163        assert!(off(&state));
1164        assert_eq!(state.stopped_optin_id.as_deref(), Some(""));
1165        let state = observe(store, &optin_as(Some("opt_5"), true)).unwrap();
1166        assert!(!state.paused && !state.explicit_off);
1167        assert_eq!(read_state(store), state);
1168
1169        let seen = seen.lock().unwrap().clone();
1170        let lines: Vec<&str> = seen.iter().map(|(line, _)| line.as_str()).collect();
1171        let put = format!("PUT /v1{OPTIN_PATH}");
1172        assert_eq!(lines, [put.as_str(); 6]);
1173        assert_eq!(seen[0].1["active"], false);
1174        assert_eq!(seen[1].1, signed);
1175    }
1176}