Skip to main content

lean_ctx_cloud/tasks/
propose.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Task proposals through the outbox (`tasks` channel): an agent task the
3//! agent asks for, or a contradiction between two facts (lean-ctx-ae
4//! queues those). A proposal is screened when it is queued; `ctx_tasks
5//! propose` sends it at once off the tool call ([`send_now`]), and the
6//! scheduler and `lean-ctx cloud sync` send what is still queued. Cloud
7//! answers with the task's state: a member agent's task is open at once
8//! (owners and maintainers may close it afterwards); a Cloud that still
9//! asks for approval answers `proposed`, and that is what is reported.
10//!
11//! A person's proposal from LeanCTX Code (rc4-67) goes the same way with
12//! origin `person`; only the app-only local routes queue one, never
13//! `ctx_tasks` or `lean-ctx cloud tasks propose`. Origin `person` is sent
14//! only signed by the app's task-propose key ([`prepare_person_task`] makes
15//! the exact bytes, the app signs them, [`enqueue_signed_person`] queues the
16//! request with that signature; this process never signs) and only to a
17//! Cloud that announces [`FEATURE_TASK_PERSON_ORIGIN`]. Any other person's
18//! proposal ([`propose_person_task`], an older Cloud) goes as an agent's, as
19//! before.
20
21use std::path::Path;
22
23use lean_ctx_time::UtcDateTime;
24use serde::{Deserialize, Serialize};
25use sha2::{Digest, Sha256};
26
27use super::screened;
28use crate::CloudError;
29use crate::auth::Session;
30use crate::outbox::{CHANNEL_TASKS, Outbox};
31use crate::vault::VaultMap;
32use lean_ctx_protocol::cloud::lease::CloudRight;
33use lean_ctx_protocol::cloud::tasks::{
34    TASK_PROPOSE_SCHEMA, TaskOriginKind, TaskOriginV1, TaskProposeRequestV1,
35};
36
37/// What a proposal is.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum ProposalKind {
41    Agent,
42    Contradiction,
43    /// The person this machine is linked to, from LeanCTX Code (rc4-67).
44    Person,
45}
46
47/// The `GET /v1/capabilities` feature of a Cloud that records an engine's
48/// proposal with origin `person` as the linked person's.
49pub const FEATURE_TASK_PERSON_ORIGIN: &str = "task_person_origin";
50
51/// The session label of a person's proposal: no agent session asked for it.
52const PERSON_SESSION_LABEL: &str = "leanctx-code";
53
54/// One queued proposal (the outbox payload).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct QueuedProposal {
57    pub kind: ProposalKind,
58    /// `stable_identity` of the project (as knowledge drafts name it).
59    pub stable_identity: String,
60    pub root: String,
61    /// The two contradicting facts; empty for an agent task.
62    #[serde(default)]
63    pub facts: Vec<String>,
64    pub title: String,
65    #[serde(default)]
66    pub goal: Option<String>,
67    pub acceptance: String,
68    #[serde(default)]
69    pub role: Option<String>,
70    /// Opaque session reference. [`propose_agent_task`] keys it under the
71    /// local receipts key (`session_ref::uploaded_ses_ref`) for a session id
72    /// and for the fixed labels callers pass in its place alike (such as
73    /// `emspace-import`), and queues nothing when that key is unavailable.
74    /// Only constant labels that name no session stay unsalted: the
75    /// `cloud-link` ref of a brought local task and, when absent, the
76    /// `cloud-task-proposals` ref of a contradiction proposal.
77    #[serde(default)]
78    pub session_ref: Option<String>,
79    /// The local task this proposal brings into the vault on link
80    /// (`cloud link --bring-local`); part of the key, so two local tasks
81    /// with the same title stay two vault tasks.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub local_number: Option<u64>,
84    /// `session_ref` is keyed already. Absent on a proposal queued before
85    /// refs were keyed: its stored ref (an unsalted digest; the queue never
86    /// kept the session id) is re-keyed before it is sent.
87    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
88    pub ref_keyed: bool,
89    /// A person's proposal signed by LeanCTX Code's task-propose key
90    /// (rc4-67): sent with origin `person` only with this.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub signed: Option<SignedPerson>,
93}
94
95/// What the app's signature on a person's proposal covers besides the body,
96/// and the signature itself (public: it proves nothing without the bound key
97/// the Cloud holds).
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct SignedPerson {
100    /// RFC 3339, whole seconds, `Z`: part of the signed body.
101    pub signed_at: String,
102    /// The vault the signature names (the path's id); a proposal whose
103    /// checkout now syncs elsewhere is never sent there.
104    pub vault_id: String,
105    /// The machine the signature names.
106    pub instance_id: String,
107    /// base64url Ed25519 over the signing input; empty while prepared.
108    #[serde(default, skip_serializing_if = "String::is_empty")]
109    pub task_signature: String,
110}
111
112impl QueuedProposal {
113    fn origin(&self) -> TaskOriginV1 {
114        let mut facts = self.facts.clone();
115        facts.sort();
116        TaskOriginV1 {
117            kind: match self.kind {
118                ProposalKind::Agent => TaskOriginKind::Agent,
119                ProposalKind::Contradiction => TaskOriginKind::Contradiction,
120                ProposalKind::Person => TaskOriginKind::Person,
121            },
122            facts,
123            message: None,
124        }
125    }
126
127    /// Key a stored ref of a proposal queued before refs were keyed, so no
128    /// guessable digest is sent; an error (no local key) keeps it queued.
129    pub(crate) fn rekey_legacy_ref(&mut self, cloud_data: &Path) -> Result<(), CloudError> {
130        if self.ref_keyed {
131            return Ok(());
132        }
133        if let Some(stored) = &self.session_ref {
134            self.session_ref = Some(crate::session_ref::rekeyed_legacy_ref(cloud_data, stored)?);
135        }
136        self.ref_keyed = true;
137        Ok(())
138    }
139
140    fn session_ref(&self) -> String {
141        self.session_ref
142            .clone()
143            .unwrap_or_else(|| crate::knowledge::draft::session_ref("cloud-task-proposals"))
144    }
145
146    /// The request in the clear (validated before it is queued and sent): a
147    /// signed person's proposal with its `signed_at` and `task_signature`,
148    /// an unsigned one as an agent's.
149    fn plain_request(&self) -> TaskProposeRequestV1 {
150        self.request_for(true)
151    }
152
153    /// The request without `task_signature`: the body the app's signature
154    /// covers (with `instance_id` and `vault_id`).
155    fn unsigned_body(&self) -> TaskProposeRequestV1 {
156        let mut request = self.request_for(true);
157        request.task_signature = None;
158        request
159    }
160
161    /// The request as sent: a person's origin only signed and only to a
162    /// Cloud that announced [`FEATURE_TASK_PERSON_ORIGIN`]; otherwise the
163    /// agent's origin it took before, without a signature (an older Cloud
164    /// refuses `person`, a newer one an unsigned `person`).
165    pub(crate) fn request_for(&self, person_origin: bool) -> TaskProposeRequestV1 {
166        let mut request = TaskProposeRequestV1 {
167            schema: TASK_PROPOSE_SCHEMA.into(),
168            title: Some(self.title.clone()),
169            goal: self.goal.clone(),
170            acceptance: Some(self.acceptance.clone()),
171            role: self.role.clone(),
172            origin: self.origin(),
173            session_ref: self.session_ref(),
174            signed_at: None,
175            task_signature: None,
176        };
177        if request.origin.kind == TaskOriginKind::Person {
178            match (&self.signed, person_origin) {
179                (Some(signed), true) => {
180                    request.signed_at = Some(signed.signed_at.clone());
181                    request.task_signature =
182                        Some(signed.task_signature.clone()).filter(|s| !s.is_empty());
183                }
184                _ => request.origin.kind = TaskOriginKind::Agent,
185            }
186        }
187        request
188    }
189
190    /// One proposal is one task, however often it is resent or requeued:
191    /// the key covers the project, the kind, the facts, (for an agent task)
192    /// the title and, for a brought local task, its local number.
193    #[must_use]
194    pub fn idempotency_key(&self) -> String {
195        let origin = self.origin();
196        let title = match self.kind {
197            ProposalKind::Agent | ProposalKind::Person => self.title.trim(),
198            ProposalKind::Contradiction => "",
199        };
200        let mut text = format!(
201            "leanctx.cloud.task-proposal.v1\n{}\n{:?}\n{}\n{title}",
202            self.stable_identity,
203            self.kind,
204            origin.facts.join(",")
205        );
206        // Absent for every other proposal: their keys stay as they were.
207        if let Some(number) = self.local_number {
208            text.push_str(&format!("\nlocal:{number}"));
209        }
210        let digest = Sha256::digest(text.as_bytes());
211        hex::encode(&digest[..16])
212    }
213}
214
215/// Secrets screened out, the request valid: before a proposal is queued
216/// or sent.
217fn checked(proposal: &QueuedProposal) -> Result<(), CloudError> {
218    screened(&[
219        ("title", Some(&proposal.title)),
220        ("goal", proposal.goal.as_deref()),
221        ("acceptance", Some(&proposal.acceptance)),
222    ])?;
223    proposal
224        .plain_request()
225        .validate()
226        .map_err(|e| CloudError::Refused(format!("invalid task proposal: {e}")))?;
227    Ok(())
228}
229
230/// A person's proposal ready for the app to sign (rc4-67): the proposal as
231/// it will be queued, the exact body sent (without `task_signature`) and the
232/// bytes the app signs. Nothing is queued or signed here.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct PreparedPerson {
235    pub proposal: QueuedProposal,
236    pub body: serde_json::Value,
237    pub signing_input: Vec<u8>,
238}
239
240/// Prepare the person's proposal for `project_root` in `vault_id` through
241/// `instance_id`, signed at `signed_at` (see [`PreparedPerson`]). Screened
242/// and validated as one that is sent.
243pub fn prepare_person_task(
244    data_dir: &Path,
245    project_root: &Path,
246    fields: &Fields<'_>,
247    instance_id: &str,
248    vault_id: &str,
249    signed_at: UtcDateTime,
250) -> Result<PreparedPerson, CloudError> {
251    let Some((instance_id, vault_id)) =
252        crate::consent::task_key::canonical_person_ids(instance_id, vault_id)
253    else {
254        return Err(CloudError::Local(
255            "this computer's or this project's Cloud id has an unexpected form".into(),
256        ));
257    };
258    let (instance_id, vault_id) = (instance_id.as_str(), vault_id.as_str());
259    let mut proposal = proposal_of(
260        data_dir,
261        project_root,
262        ProposalKind::Person,
263        fields,
264        PERSON_SESSION_LABEL,
265    )?;
266    proposal.signed = Some(SignedPerson {
267        signed_at: signed_at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
268        vault_id: vault_id.to_owned(),
269        instance_id: instance_id.to_owned(),
270        task_signature: String::new(),
271    });
272    screened(&[
273        ("title", Some(&proposal.title)),
274        ("goal", proposal.goal.as_deref()),
275        ("acceptance", Some(&proposal.acceptance)),
276    ])?;
277    let request = proposal.unsigned_body();
278    let signing_input =
279        crate::consent::task_key::person_task_signing_input(&request, instance_id, vault_id)
280            .map_err(CloudError::Local)?;
281    let body = serde_json::to_value(&request).map_err(|e| CloudError::Local(e.to_string()))?;
282    Ok(PreparedPerson {
283        proposal,
284        body,
285        signing_input,
286    })
287}
288
289/// Queue a prepared person's proposal with the app's `task_signature`
290/// (checked against the bound key by the caller); returns the outbox id.
291pub fn enqueue_signed_person(
292    data_dir: &Path,
293    prepared: &PreparedPerson,
294    task_signature: &str,
295) -> Result<String, CloudError> {
296    let mut proposal = prepared.proposal.clone();
297    let Some(signed) = proposal.signed.as_mut() else {
298        return Err(CloudError::Local("not a prepared person's proposal".into()));
299    };
300    task_signature.clone_into(&mut signed.task_signature);
301    enqueue(data_dir, &proposal)
302}
303
304/// Screen, validate and queue `proposal`; returns the outbox item id.
305pub fn enqueue(data_dir: &Path, proposal: &QueuedProposal) -> Result<String, CloudError> {
306    checked(proposal)?;
307    let payload = serde_json::to_value(proposal).map_err(|e| CloudError::Local(e.to_string()))?;
308    Outbox::at(data_dir).enqueue(CHANNEL_TASKS, payload, UtcDateTime::now())
309}
310
311/// Screen, validate and send `proposal` to `vault_id` now, without the
312/// outbox: for a caller that needs the task number at once (bringing local
313/// tasks into a vault on link). The idempotency key is the queued one, so
314/// a repeat after an interrupted run gets the same task back.
315pub fn propose_now(
316    session: &Session,
317    vault_id: &str,
318    proposal: &QueuedProposal,
319) -> Result<(u64, lean_ctx_protocol::cloud::tasks::TaskState), CloudError> {
320    checked(proposal)?;
321    send(session, vault_id, proposal)
322}
323
324/// An agent task for the project at `project_root`: `ctx_tasks propose`,
325/// `lean-ctx cloud tasks propose` and imports. Always origin `agent`.
326pub fn propose_agent_task(
327    data_dir: &Path,
328    project_root: &Path,
329    title: &str,
330    goal: Option<&str>,
331    acceptance: &str,
332    role: Option<&str>,
333    session_id: &str,
334) -> Result<String, CloudError> {
335    let fields = Fields {
336        title,
337        goal,
338        acceptance,
339        role,
340    };
341    queue_task(
342        data_dir,
343        project_root,
344        ProposalKind::Agent,
345        &fields,
346        session_id,
347    )
348}
349
350/// A task the person this machine is linked to proposed in LeanCTX Code
351/// (rc4-67): origin `person`. Only the app-only local route calls it; the
352/// Cloud names the person from the machine's link, never from the request.
353pub fn propose_person_task(
354    data_dir: &Path,
355    project_root: &Path,
356    title: &str,
357    goal: Option<&str>,
358    acceptance: &str,
359    role: Option<&str>,
360) -> Result<String, CloudError> {
361    let fields = Fields {
362        title,
363        goal,
364        acceptance,
365        role,
366    };
367    queue_task(
368        data_dir,
369        project_root,
370        ProposalKind::Person,
371        &fields,
372        PERSON_SESSION_LABEL,
373    )
374}
375
376/// A proposal's words.
377pub struct Fields<'a> {
378    pub title: &'a str,
379    pub goal: Option<&'a str>,
380    pub acceptance: &'a str,
381    pub role: Option<&'a str>,
382}
383
384fn queue_task(
385    data_dir: &Path,
386    project_root: &Path,
387    kind: ProposalKind,
388    fields: &Fields<'_>,
389    session_id: &str,
390) -> Result<String, CloudError> {
391    enqueue(
392        data_dir,
393        &proposal_of(data_dir, project_root, kind, fields, session_id)?,
394    )
395}
396
397fn proposal_of(
398    data_dir: &Path,
399    project_root: &Path,
400    kind: ProposalKind,
401    fields: &Fields<'_>,
402    session_id: &str,
403) -> Result<QueuedProposal, CloudError> {
404    let Fields {
405        title,
406        goal,
407        acceptance,
408        role,
409    } = *fields;
410    let identity = crate::vault::project_identity(project_root).ok_or_else(|| {
411        CloudError::Config(
412            "this repository has no identity LeanCTX Cloud can link to a vault (no git remote)"
413                .into(),
414        )
415    })?;
416    Ok(QueuedProposal {
417        kind,
418        stable_identity: lean_ctx_protocol::cloud::vault::stable_identity(&identity),
419        root: project_root.to_string_lossy().into_owned(),
420        facts: Vec::new(),
421        title: title.trim().to_owned(),
422        goal: goal
423            .map(str::trim)
424            .filter(|g| !g.is_empty())
425            .map(str::to_owned),
426        acceptance: acceptance.trim().to_owned(),
427        role: role.map(str::to_owned),
428        // Keyed for a label too; without the local key nothing is queued.
429        session_ref: Some(crate::session_ref::uploaded_ses_ref(data_dir, session_id)?),
430        local_number: None,
431        ref_keyed: true,
432        signed: None,
433    })
434}
435
436/// What one drain pass did.
437#[derive(Debug, Clone, Default, PartialEq, Eq)]
438pub struct DrainReport {
439    /// The tasks Cloud created, with the state it gave each.
440    pub sent: Vec<(u64, lean_ctx_protocol::cloud::tasks::TaskState)>,
441    pub pending: usize,
442    pub failed: usize,
443    pub problems: Vec<String>,
444}
445
446/// What became of one queued proposal.
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub enum Delivery {
449    /// Cloud created the task.
450    Sent(u64, lean_ctx_protocol::cloud::tasks::TaskState),
451    /// Kept in the outbox for a later pass (offline, 429, not linked yet).
452    Waiting(String),
453    /// Moved to the failed outbox; never sent.
454    Failed(String),
455}
456
457const NO_PROPOSE_RIGHT: &str = "your LeanCTX Cloud plan does not allow task proposals";
458
459fn deliver(
460    session: &Session,
461    outbox: &Outbox,
462    map: &VaultMap,
463    mut item: crate::outbox::OutboxItem,
464    now: lean_ctx_time::UtcDateTime,
465) -> Delivery {
466    let Ok(mut proposal) = serde_json::from_value::<QueuedProposal>(item.payload.clone()) else {
467        let _ = outbox.fail(&mut item, "damaged task proposal");
468        return Delivery::Failed("damaged task proposal".into());
469    };
470    // Queued before refs were keyed: keyed now, or kept queued while the
471    // local key is unavailable.
472    if let Err(error) = proposal.rekey_legacy_ref(session.store.data_dir()) {
473        let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
474        return Delivery::Waiting(error.to_string());
475    }
476    // A folder the person stopped sharing sends nothing, not even through
477    // the record of another checkout; kept for a later `cloud link` (rc4-6).
478    if crate::unlinked::contains(session.store.data_dir(), Path::new(&proposal.root)) {
479        let reason = crate::unlinked::refusal(session.store.data_dir());
480        let _ = outbox.retry_later(&mut item, &reason, None, now);
481        return Delivery::Waiting(reason);
482    }
483    // The checkout's current vault first: a proposal queued under an
484    // identity the checkout left goes where the checkout syncs now.
485    let Some(record) = map
486        .for_root(&proposal.root)
487        .or_else(|| map.vaults.get(&proposal.stable_identity))
488    else {
489        let reason = "this repository is not linked to a vault yet";
490        let _ = outbox.retry_later(&mut item, reason, None, now);
491        return Delivery::Waiting(reason.into());
492    };
493    // A signature names its vault and machine: never sent elsewhere.
494    if let Some(signed) = &proposal.signed {
495        let now_ids = crate::consent::task_key::canonical_person_ids(
496            &session.instance.instance_id,
497            &record.vault_id,
498        );
499        let signed_ids = (signed.instance_id.clone(), signed.vault_id.clone());
500        if now_ids.as_ref() != Some(&signed_ids) {
501            let problem = "the project now syncs elsewhere; propose the task again in the app";
502            let _ = outbox.fail(&mut item, problem);
503            return Delivery::Failed(problem.into());
504        }
505    }
506    match send(session, &record.vault_id, &proposal) {
507        Ok((number, state)) => {
508            let _ = outbox.remove(&item);
509            Delivery::Sent(number, state)
510        }
511        Err(error) if error.is_transient() => {
512            // 429: Retry-After / retry_after_s, or a quota's reset_at.
513            let retry_after = error.retry_after_at(lean_ctx_time::UtcDateTime::now());
514            let _ = outbox.retry_later(&mut item, &error.to_string(), retry_after, now);
515            Delivery::Waiting(error.to_string())
516        }
517        Err(error @ CloudError::Refused(_)) => {
518            // Refused for now: try again later.
519            let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
520            Delivery::Waiting(error.to_string())
521        }
522        Err(error) => {
523            let _ = outbox.fail(&mut item, &error.to_string());
524            Delivery::Failed(error.to_string())
525        }
526    }
527}
528
529/// Send the due proposals (scheduler, `lean-ctx cloud sync`; never inside
530/// a tool call).
531pub fn drain(session: &Session) -> DrainReport {
532    let data = session.store.data_dir().to_path_buf();
533    let outbox = Outbox::at(&data);
534    let mut report = DrainReport::default();
535    let items = outbox.list(CHANNEL_TASKS);
536    if !items.is_empty() && !session.lease.lease.grants(CloudRight::TasksPropose) {
537        report.pending = items.len();
538        report.problems.push(NO_PROPOSE_RIGHT.into());
539        return report;
540    }
541    // Never into a vault a checkout's link file or identity left.
542    let map = match crate::resolution::load_current(&data) {
543        Ok((map, _)) => map,
544        Err(error) => {
545            report.problems.push(error.to_string());
546            VaultMap::default()
547        }
548    };
549    let now = UtcDateTime::now();
550    for item in items {
551        if !item.due(now) {
552            continue;
553        }
554        match deliver(session, &outbox, &map, item, now) {
555            Delivery::Sent(number, state) => report.sent.push((number, state)),
556            Delivery::Waiting(_) => {}
557            Delivery::Failed(problem) => report.problems.push(problem),
558        }
559    }
560    let depth = outbox.depth(CHANNEL_TASKS);
561    report.pending = depth.pending;
562    report.failed = depth.failed;
563    report
564}
565
566/// Send the queued proposal `id` now instead of with the next scheduler
567/// pass (`ctx_tasks propose` runs this off the tool call, as claims and
568/// results go out). A proposal that cannot go out now stays queued and the
569/// scheduler sends it later. `None`: the scheduler sent it meanwhile (Cloud's
570/// idempotency key keeps a resend of one proposal one task).
571#[must_use]
572pub fn send_now(session: &Session, id: &str) -> Option<Delivery> {
573    let data = session.store.data_dir().to_path_buf();
574    let outbox = Outbox::at(&data);
575    let item = outbox
576        .list(CHANNEL_TASKS)
577        .into_iter()
578        .find(|item| item.id == id)?;
579    if !session.lease.lease.grants(CloudRight::TasksPropose) {
580        return Some(Delivery::Waiting(NO_PROPOSE_RIGHT.into()));
581    }
582    // Never into a vault a checkout's link file or identity left.
583    let map = match crate::resolution::load_current(&data) {
584        Ok((map, _)) => map,
585        Err(error) => return Some(Delivery::Waiting(error.to_string())),
586    };
587    Some(deliver(session, &outbox, &map, item, UtcDateTime::now()))
588}
589
590/// [`send_now`] for a person's proposal (rc4-67): asks the Cloud first what
591/// it accepts (a failure keeps the last answer), so the answer says whether
592/// the Cloud records the task as the person's (`true`) or, an older Cloud,
593/// as an agent's.
594#[must_use]
595pub fn send_person_now(session: &Session, id: &str) -> (Option<Delivery>, bool) {
596    let person = person_origin_offered(session);
597    (send_now(session, id), person)
598}
599
600/// Whether the Cloud takes a person's origin: asked now (a failure keeps
601/// the last answer).
602#[must_use]
603pub fn person_origin_offered(session: &Session) -> bool {
604    let _ = session.with_client(|client| {
605        crate::session_ref::refresh(&session.store, &session.instance.url, client)
606    });
607    crate::session_ref::announced(&session.store, FEATURE_TASK_PERSON_ORIGIN)
608}
609
610/// The caller's line for what [`send_now`] did.
611#[must_use]
612pub fn delivery_line(delivery: Option<&Delivery>) -> String {
613    match delivery {
614        Some(Delivery::Sent(number, state)) => created_line(*number, *state),
615        Some(Delivery::Waiting(reason)) => format!(
616            "Task proposal not sent yet ({reason}); it stays queued and the next LeanCTX Cloud sync sends it."
617        ),
618        Some(Delivery::Failed(problem)) => format!("Task proposal not sent: {problem}."),
619        None => "Task proposal went out with the last LeanCTX Cloud sync.".into(),
620    }
621}
622
623fn send(
624    session: &Session,
625    vault_id: &str,
626    proposal: &QueuedProposal,
627) -> Result<(u64, lean_ctx_protocol::cloud::tasks::TaskState), CloudError> {
628    let person_origin = crate::session_ref::announced(&session.store, FEATURE_TASK_PERSON_ORIGIN);
629    let request = proposal.request_for(person_origin);
630    let key = proposal.idempotency_key();
631    let sent = session
632        .with_client(|client| super::client::TasksApi { client, vault_id }.propose(&request, &key))
633        .map(|ack| (ack.number, ack.state));
634    super::reads::outdate(session.store.data_dir(), vault_id);
635    sent
636}
637
638/// What `lean-ctx cloud sync` prints for a task Cloud created from a
639/// proposal: its real state, so an agent knows whether it can claim it.
640#[must_use]
641pub fn created_line(number: u64, state: lean_ctx_protocol::cloud::tasks::TaskState) -> String {
642    use lean_ctx_protocol::cloud::tasks::TaskState;
643    match state {
644        TaskState::Open => format!("Created task #{number}, open now (any agent may claim it)."),
645        other => format!(
646            "Created task #{number} ({}).",
647            format!("{other:?}").to_lowercase()
648        ),
649    }
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    /// !406 follow-up: `deliver()` of a proposal queued before refs were
657    /// keyed (no `ref_keyed`, the unsalted digest) while the local key is
658    /// unavailable. It waits in the outbox with its stored ref and is never
659    /// moved to the failed outbox; with the key back the key gate lets it
660    /// through to the next step.
661    #[test]
662    fn a_legacy_proposal_without_a_key_waits_and_keeps_its_ref() {
663        let (_dir, session) = crate::auth::fixture_session();
664        let data = session.store.data_dir().to_path_buf();
665        let unsalted = crate::knowledge::draft::session_ref("20261116-091500u123456p4242s0");
666        let legacy = serde_json::json!({
667            "kind": "agent",
668            "stable_identity": "a".repeat(64),
669            "root": "/tmp/p",
670            "title": "Import the emspace pages",
671            "acceptance": "Every page is a fact",
672            "session_ref": unsalted,
673        });
674        let parsed: QueuedProposal = serde_json::from_value(legacy.clone()).unwrap();
675        assert!(!parsed.ref_keyed, "a pre-!406 payload");
676        let outbox = Outbox::at(&data);
677        let id = outbox
678            .enqueue(CHANNEL_TASKS, legacy.clone(), UtcDateTime::now())
679            .unwrap();
680        // No vault is mapped: had the key gate let it pass, the answer
681        // would be "not linked" and nothing would be sent either.
682        let map = VaultMap::default();
683
684        let keyless = data.join("receipts.hmac-key");
685        crate::session_ref::make_keyless(&data);
686        let item = outbox.list(CHANNEL_TASKS).remove(0);
687        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
688        let Delivery::Waiting(reason) = &delivery else {
689            panic!("{delivery:?}");
690        };
691        assert!(reason.contains("receipts.hmac-key"), "{reason}");
692        let items = outbox.list(CHANNEL_TASKS);
693        assert_eq!(items.len(), 1, "still queued");
694        assert_eq!(items[0].id, id);
695        assert_eq!(items[0].attempts, 1);
696        assert!(items[0].next_attempt_at.is_some(), "waits with a backoff");
697        assert_eq!(
698            items[0].payload, legacy,
699            "the stored ref is kept, never marked keyed"
700        );
701        assert_eq!(outbox.depth(CHANNEL_TASKS).failed, 0, "never failed");
702
703        // The key is readable again: the key gate passes, and the proposal
704        // waits for its vault, its payload still the stored one (it is keyed
705        // again, the same way, when it is sent).
706        std::fs::remove_dir(&keyless).unwrap();
707        let mut item = outbox.list(CHANNEL_TASKS).remove(0);
708        item.next_attempt_at = None;
709        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
710        let Delivery::Waiting(reason) = &delivery else {
711            panic!("{delivery:?}");
712        };
713        assert!(reason.contains("not linked"), "{reason}");
714        assert!(!reason.contains("receipts.hmac-key"), "{reason}");
715        assert_eq!(outbox.list(CHANNEL_TASKS)[0].attempts, 2);
716    }
717
718    /// bd 39657 S-a: a proposal from a folder the person unlinked is not
719    /// sent through the record of its identity; it waits for a link.
720    #[test]
721    fn a_proposal_after_unlink_waits_and_is_not_sent() {
722        let (_dir, session) = crate::auth::fixture_session();
723        let data = session.store.data_dir().to_path_buf();
724        let root = tempfile::tempdir().unwrap();
725        let root_text = root.path().to_string_lossy().into_owned();
726        let stable = "a".repeat(64);
727        let outbox = Outbox::at(&data);
728        outbox
729            .enqueue(
730                CHANNEL_TASKS,
731                serde_json::json!({
732                    "kind": "agent",
733                    "stable_identity": stable,
734                    "root": root_text,
735                    "title": "Import the emspace pages",
736                    "acceptance": "Every page is a fact",
737                }),
738                UtcDateTime::now(),
739            )
740            .unwrap();
741        let mut map = VaultMap::default();
742        map.vaults.insert(
743            stable,
744            crate::vault::VaultRecord {
745                vault_id: "vlt_1".into(),
746                ns: "acme".into(),
747                name: "payments".into(),
748                sealed: false,
749                roots: vec!["/elsewhere/checkout".into()],
750            },
751        );
752        crate::unlinked::add(&data, root.path()).unwrap();
753
754        let item = outbox.list(CHANNEL_TASKS).remove(0);
755        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
756        assert_eq!(delivery, Delivery::Waiting(crate::unlinked::REFUSAL.into()));
757        assert_eq!(outbox.list(CHANNEL_TASKS).len(), 1, "still queued");
758        assert_eq!(outbox.depth(CHANNEL_TASKS).failed, 0);
759    }
760
761    const INSTANCE: &str = "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09";
762    const VAULT: &str = "9d2e4f6a1b3c4d5e8f7a6b5c4d3e2f1a";
763
764    /// A signed person's proposal for `vault`/`instance`, queued; the map
765    /// syncs its identity to `now_vault`.
766    fn queued_signed(
767        session: &Session,
768        vault: &str,
769        instance: &str,
770        now_vault: &str,
771    ) -> (Outbox, VaultMap) {
772        let proposal = QueuedProposal {
773            kind: ProposalKind::Person,
774            stable_identity: "b".repeat(64),
775            root: "/tmp/rc467-p".into(),
776            facts: Vec::new(),
777            title: "Show the retry budget in settings".into(),
778            goal: None,
779            acceptance: "The settings page names it".into(),
780            role: None,
781            session_ref: Some(PERSON_SESSION_LABEL.into()),
782            local_number: None,
783            ref_keyed: true,
784            signed: Some(SignedPerson {
785                signed_at: "2026-11-24T09:30:00Z".into(),
786                vault_id: vault.into(),
787                instance_id: instance.into(),
788                task_signature: "A".repeat(86),
789            }),
790        };
791        let outbox = Outbox::at(session.store.data_dir());
792        outbox
793            .enqueue(
794                CHANNEL_TASKS,
795                serde_json::to_value(&proposal).unwrap(),
796                UtcDateTime::now(),
797            )
798            .unwrap();
799        let mut map = VaultMap::default();
800        map.vaults.insert(
801            "b".repeat(64),
802            crate::vault::VaultRecord {
803                vault_id: now_vault.into(),
804                ns: "acme".into(),
805                name: "payments".into(),
806                sealed: false,
807                roots: Vec::new(),
808            },
809        );
810        (outbox, map)
811    }
812
813    /// rc4-67 (bd S3): a signature names its vault and machine. When the
814    /// project now syncs to another vault, or the machine is another one,
815    /// the proposal fails for good (never retried, never sent elsewhere),
816    /// before any request.
817    #[test]
818    fn a_signed_proposal_is_never_sent_to_another_vault_or_from_another_machine() {
819        let (_dir, mut session) = crate::auth::fixture_session();
820        // INSTANCE in upper case: the same machine.
821        session.instance.instance_id = INSTANCE.to_ascii_uppercase();
822        let other_vault = "0123456789abcdef0123456789abcdef";
823        let other_instance = "0a80ace1-52f1-49c2-85f7-6991bada0099";
824        for (vault, instance, now_vault) in [
825            (VAULT, INSTANCE, other_vault),
826            (VAULT, other_instance, VAULT),
827        ] {
828            let (outbox, map) = queued_signed(&session, vault, instance, now_vault);
829            let failed_before = outbox.failed(CHANNEL_TASKS).len();
830            let item = outbox.list(CHANNEL_TASKS).remove(0);
831            let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
832            let Delivery::Failed(problem) = &delivery else {
833                panic!("{delivery:?}");
834            };
835            assert!(problem.contains("syncs elsewhere"), "{problem}");
836            assert!(outbox.list(CHANNEL_TASKS).is_empty(), "not retried");
837            assert_eq!(outbox.failed(CHANNEL_TASKS).len(), failed_before + 1);
838        }
839    }
840
841    /// rc4-67 (bd S1): the ids are signed as the Cloud checks them.
842    #[test]
843    fn person_ids_are_signed_in_the_clouds_spelling() {
844        use crate::consent::task_key::canonical_person_ids;
845        let canonical = Some((INSTANCE.to_owned(), VAULT.to_owned()));
846        for instance in [INSTANCE, "3F1C2B6A-8D4E-4A7B-9C10-5E2F6A7B8C09"] {
847            assert_eq!(
848                canonical_person_ids(instance, VAULT),
849                canonical,
850                "{instance}"
851            );
852        }
853        assert_eq!(
854            canonical_person_ids(INSTANCE, &VAULT.to_ascii_uppercase()),
855            canonical
856        );
857        for (instance, vault) in [
858            ("inst-1", VAULT),
859            ("inst_01jb8z3k4m5n6p7q8r9s0t1v2w", VAULT),
860            ("inst_3f1c2b6a8d4e4a7b9c105e2f6a7b8c09", VAULT),
861            ("3f1c2b6a8d4e4a7b9c105e2f6a7b8c09", VAULT),
862            (INSTANCE, "p-1"),
863            (INSTANCE, "9d2e4f6a-1b3c-4d5e-8f7a-6b5c4d3e2f1a"),
864            (INSTANCE, ""),
865        ] {
866            assert_eq!(
867                canonical_person_ids(instance, vault),
868                None,
869                "{instance} {vault}"
870            );
871        }
872        // prepare refuses what it cannot sign so.
873        let (_dir, session) = crate::auth::fixture_session();
874        let fields = Fields {
875            title: "Show the retry budget in settings",
876            goal: None,
877            acceptance: "The settings page names it",
878            role: None,
879        };
880        let refused = prepare_person_task(
881            session.store.data_dir(),
882            Path::new("/tmp/rc467-p"),
883            &fields,
884            "inst-1",
885            VAULT,
886            UtcDateTime::now(),
887        );
888        assert!(refused.is_err());
889    }
890
891    /// rc4-67 (bd S3): the Cloud refusing a person's signature
892    /// (`person_unproven`, `signature_expired`) is final: neither transient
893    /// nor `Refused`, so `deliver()` fails it instead of retrying.
894    #[test]
895    fn an_unproven_or_expired_person_signature_is_never_retried() {
896        use crate::error::TaskRefusal;
897        for (reason, refusal) in [
898            ("person_unproven", TaskRefusal::PersonUnproven),
899            ("signature_expired", TaskRefusal::SignatureExpired),
900        ] {
901            let body = serde_json::json!({"error": {"code": "forbidden_right", "message": "x", "reason": reason}});
902            let error = CloudError::from_response(403, &body);
903            assert!(
904                matches!(&error, CloudError::Task { refusal: r, .. } if *r == refusal),
905                "{error:?}"
906            );
907            assert!(!error.is_transient(), "{reason}");
908            assert!(!matches!(error, CloudError::Refused(_)), "{reason}");
909        }
910    }
911}