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 the Cloud can link to a vault (no git remote)".into(),
413        )
414    })?;
415    Ok(QueuedProposal {
416        kind,
417        stable_identity: lean_ctx_protocol::cloud::vault::stable_identity(&identity),
418        root: project_root.to_string_lossy().into_owned(),
419        facts: Vec::new(),
420        title: title.trim().to_owned(),
421        goal: goal
422            .map(str::trim)
423            .filter(|g| !g.is_empty())
424            .map(str::to_owned),
425        acceptance: acceptance.trim().to_owned(),
426        role: role.map(str::to_owned),
427        // Keyed for a label too; without the local key nothing is queued.
428        session_ref: Some(crate::session_ref::uploaded_ses_ref(data_dir, session_id)?),
429        local_number: None,
430        ref_keyed: true,
431        signed: None,
432    })
433}
434
435/// What one drain pass did.
436#[derive(Debug, Clone, Default, PartialEq, Eq)]
437pub struct DrainReport {
438    /// The tasks Cloud created, with the state it gave each.
439    pub sent: Vec<(u64, lean_ctx_protocol::cloud::tasks::TaskState)>,
440    pub pending: usize,
441    pub failed: usize,
442    pub problems: Vec<String>,
443}
444
445/// What became of one queued proposal.
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub enum Delivery {
448    /// Cloud created the task.
449    Sent(u64, lean_ctx_protocol::cloud::tasks::TaskState),
450    /// Kept in the outbox for a later pass (offline, 429, not linked yet).
451    Waiting(String),
452    /// Moved to the failed outbox; never sent.
453    Failed(String),
454}
455
456const NO_PROPOSE_RIGHT: &str = "your Cloud plan does not allow task proposals";
457
458fn deliver(
459    session: &Session,
460    outbox: &Outbox,
461    map: &VaultMap,
462    mut item: crate::outbox::OutboxItem,
463    now: lean_ctx_time::UtcDateTime,
464) -> Delivery {
465    let Ok(mut proposal) = serde_json::from_value::<QueuedProposal>(item.payload.clone()) else {
466        let _ = outbox.fail(&mut item, "damaged task proposal");
467        return Delivery::Failed("damaged task proposal".into());
468    };
469    // Queued before refs were keyed: keyed now, or kept queued while the
470    // local key is unavailable.
471    if let Err(error) = proposal.rekey_legacy_ref(session.store.data_dir()) {
472        let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
473        return Delivery::Waiting(error.to_string());
474    }
475    // A folder the person stopped sharing sends nothing, not even through
476    // the record of another checkout; kept for a later `cloud link` (rc4-6).
477    if crate::unlinked::contains(session.store.data_dir(), Path::new(&proposal.root)) {
478        let reason = crate::unlinked::refusal(session.store.data_dir());
479        let _ = outbox.retry_later(&mut item, &reason, None, now);
480        return Delivery::Waiting(reason);
481    }
482    // The checkout's current vault first: a proposal queued under an
483    // identity the checkout left goes where the checkout syncs now.
484    let Some(record) = map
485        .for_root(&proposal.root)
486        .or_else(|| map.vaults.get(&proposal.stable_identity))
487    else {
488        let reason = "this repository is not linked to a vault yet";
489        let _ = outbox.retry_later(&mut item, reason, None, now);
490        return Delivery::Waiting(reason.into());
491    };
492    // A signature names its vault and machine: never sent elsewhere.
493    if let Some(signed) = &proposal.signed {
494        let now_ids = crate::consent::task_key::canonical_person_ids(
495            &session.instance.instance_id,
496            &record.vault_id,
497        );
498        let signed_ids = (signed.instance_id.clone(), signed.vault_id.clone());
499        if now_ids.as_ref() != Some(&signed_ids) {
500            let problem = "the project now syncs elsewhere; propose the task again in the app";
501            let _ = outbox.fail(&mut item, problem);
502            return Delivery::Failed(problem.into());
503        }
504    }
505    match send(session, &record.vault_id, &proposal) {
506        Ok((number, state)) => {
507            let _ = outbox.remove(&item);
508            Delivery::Sent(number, state)
509        }
510        Err(error) if error.is_transient() => {
511            // 429: Retry-After / retry_after_s, or a quota's reset_at.
512            let retry_after = error.retry_after_at(lean_ctx_time::UtcDateTime::now());
513            let _ = outbox.retry_later(&mut item, &error.to_string(), retry_after, now);
514            Delivery::Waiting(error.to_string())
515        }
516        Err(error @ CloudError::Refused(_)) => {
517            // Refused for now: try again later.
518            let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
519            Delivery::Waiting(error.to_string())
520        }
521        Err(error) => {
522            let _ = outbox.fail(&mut item, &error.to_string());
523            Delivery::Failed(error.to_string())
524        }
525    }
526}
527
528/// Send the due proposals (scheduler, `lean-ctx cloud sync`; never inside
529/// a tool call).
530pub fn drain(session: &Session) -> DrainReport {
531    let data = session.store.data_dir().to_path_buf();
532    let outbox = Outbox::at(&data);
533    let mut report = DrainReport::default();
534    let items = outbox.list(CHANNEL_TASKS);
535    if !items.is_empty() && !session.lease.lease.grants(CloudRight::TasksPropose) {
536        report.pending = items.len();
537        report.problems.push(NO_PROPOSE_RIGHT.into());
538        return report;
539    }
540    // Never into a vault a checkout's link file or identity left, nor one
541    // of another Cloud or account (rc3-81).
542    let scope = session.instance.vault_scope();
543    let map = match crate::resolution::load_current(&data, Some(&scope)) {
544        Ok((map, _)) => map,
545        Err(error) => {
546            report.problems.push(error.to_string());
547            VaultMap::default()
548        }
549    };
550    let now = UtcDateTime::now();
551    for item in items {
552        if !item.due(now) {
553            continue;
554        }
555        match deliver(session, &outbox, &map, item, now) {
556            Delivery::Sent(number, state) => report.sent.push((number, state)),
557            Delivery::Waiting(_) => {}
558            Delivery::Failed(problem) => report.problems.push(problem),
559        }
560    }
561    let depth = outbox.depth(CHANNEL_TASKS);
562    report.pending = depth.pending;
563    report.failed = depth.failed;
564    report
565}
566
567/// Send the queued proposal `id` now instead of with the next scheduler
568/// pass (`ctx_tasks propose` runs this off the tool call, as claims and
569/// results go out). A proposal that cannot go out now stays queued and the
570/// scheduler sends it later. `None`: the scheduler sent it meanwhile (Cloud's
571/// idempotency key keeps a resend of one proposal one task).
572#[must_use]
573pub fn send_now(session: &Session, id: &str) -> Option<Delivery> {
574    let data = session.store.data_dir().to_path_buf();
575    let outbox = Outbox::at(&data);
576    let item = outbox
577        .list(CHANNEL_TASKS)
578        .into_iter()
579        .find(|item| item.id == id)?;
580    if !session.lease.lease.grants(CloudRight::TasksPropose) {
581        return Some(Delivery::Waiting(NO_PROPOSE_RIGHT.into()));
582    }
583    // Never into a vault a checkout's link file or identity left, nor one
584    // of another Cloud or account (rc3-81).
585    let scope = session.instance.vault_scope();
586    let map = match crate::resolution::load_current(&data, Some(&scope)) {
587        Ok((map, _)) => map,
588        Err(error) => return Some(Delivery::Waiting(error.to_string())),
589    };
590    Some(deliver(session, &outbox, &map, item, UtcDateTime::now()))
591}
592
593/// [`send_now`] for a person's proposal (rc4-67): asks the Cloud first what
594/// it accepts (a failure keeps the last answer), so the answer says whether
595/// the Cloud records the task as the person's (`true`) or, an older Cloud,
596/// as an agent's.
597#[must_use]
598pub fn send_person_now(session: &Session, id: &str) -> (Option<Delivery>, bool) {
599    let person = person_origin_offered(session);
600    (send_now(session, id), person)
601}
602
603/// Whether the Cloud takes a person's origin: asked now (a failure keeps
604/// the last answer).
605#[must_use]
606pub fn person_origin_offered(session: &Session) -> bool {
607    let _ = session.with_client(|client| {
608        crate::session_ref::refresh(&session.store, &session.instance.url, client)
609    });
610    crate::session_ref::announced(&session.store, FEATURE_TASK_PERSON_ORIGIN)
611}
612
613/// The caller's line for what [`send_now`] did.
614#[must_use]
615pub fn delivery_line(delivery: Option<&Delivery>) -> String {
616    match delivery {
617        Some(Delivery::Sent(number, state)) => created_line(*number, *state),
618        Some(Delivery::Waiting(reason)) => format!(
619            "Task proposal not sent yet ({reason}); it stays queued and the next Cloud sync sends it."
620        ),
621        Some(Delivery::Failed(problem)) => format!("Task proposal not sent: {problem}."),
622        None => "Task proposal went out with the last Cloud sync.".into(),
623    }
624}
625
626fn send(
627    session: &Session,
628    vault_id: &str,
629    proposal: &QueuedProposal,
630) -> Result<(u64, lean_ctx_protocol::cloud::tasks::TaskState), CloudError> {
631    let person_origin = crate::session_ref::announced(&session.store, FEATURE_TASK_PERSON_ORIGIN);
632    let request = proposal.request_for(person_origin);
633    let key = proposal.idempotency_key();
634    let sent = session
635        .with_client(|client| super::client::TasksApi { client, vault_id }.propose(&request, &key))
636        .map(|ack| (ack.number, ack.state));
637    super::reads::outdate(session.store.data_dir(), vault_id);
638    sent
639}
640
641/// What `lean-ctx cloud sync` prints for a task Cloud created from a
642/// proposal: its real state, so an agent knows whether it can claim it.
643#[must_use]
644pub fn created_line(number: u64, state: lean_ctx_protocol::cloud::tasks::TaskState) -> String {
645    use lean_ctx_protocol::cloud::tasks::TaskState;
646    match state {
647        TaskState::Open => format!("Created task #{number}, open now (any agent may claim it)."),
648        other => format!(
649            "Created task #{number} ({}).",
650            format!("{other:?}").to_lowercase()
651        ),
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    /// !406 follow-up: `deliver()` of a proposal queued before refs were
660    /// keyed (no `ref_keyed`, the unsalted digest) while the local key is
661    /// unavailable. It waits in the outbox with its stored ref and is never
662    /// moved to the failed outbox; with the key back the key gate lets it
663    /// through to the next step.
664    #[test]
665    fn a_legacy_proposal_without_a_key_waits_and_keeps_its_ref() {
666        let (_dir, session) = crate::auth::fixture_session();
667        let data = session.store.data_dir().to_path_buf();
668        let unsalted = crate::knowledge::draft::session_ref("20261116-091500u123456p4242s0");
669        let legacy = serde_json::json!({
670            "kind": "agent",
671            "stable_identity": "a".repeat(64),
672            "root": "/tmp/p",
673            "title": "Import the emspace pages",
674            "acceptance": "Every page is a fact",
675            "session_ref": unsalted,
676        });
677        let parsed: QueuedProposal = serde_json::from_value(legacy.clone()).unwrap();
678        assert!(!parsed.ref_keyed, "a pre-!406 payload");
679        let outbox = Outbox::at(&data);
680        let id = outbox
681            .enqueue(CHANNEL_TASKS, legacy.clone(), UtcDateTime::now())
682            .unwrap();
683        // No vault is mapped: had the key gate let it pass, the answer
684        // would be "not linked" and nothing would be sent either.
685        let map = VaultMap::default();
686
687        let keyless = data.join("receipts.hmac-key");
688        crate::session_ref::make_keyless(&data);
689        let item = outbox.list(CHANNEL_TASKS).remove(0);
690        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
691        let Delivery::Waiting(reason) = &delivery else {
692            panic!("{delivery:?}");
693        };
694        assert!(reason.contains("receipts.hmac-key"), "{reason}");
695        let items = outbox.list(CHANNEL_TASKS);
696        assert_eq!(items.len(), 1, "still queued");
697        assert_eq!(items[0].id, id);
698        assert_eq!(items[0].attempts, 1);
699        assert!(items[0].next_attempt_at.is_some(), "waits with a backoff");
700        assert_eq!(
701            items[0].payload, legacy,
702            "the stored ref is kept, never marked keyed"
703        );
704        assert_eq!(outbox.depth(CHANNEL_TASKS).failed, 0, "never failed");
705
706        // The key is readable again: the key gate passes, and the proposal
707        // waits for its vault, its payload still the stored one (it is keyed
708        // again, the same way, when it is sent).
709        std::fs::remove_dir(&keyless).unwrap();
710        let mut item = outbox.list(CHANNEL_TASKS).remove(0);
711        item.next_attempt_at = None;
712        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
713        let Delivery::Waiting(reason) = &delivery else {
714            panic!("{delivery:?}");
715        };
716        assert!(reason.contains("not linked"), "{reason}");
717        assert!(!reason.contains("receipts.hmac-key"), "{reason}");
718        assert_eq!(outbox.list(CHANNEL_TASKS)[0].attempts, 2);
719    }
720
721    const INSTANCE: &str = "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09";
722    const VAULT: &str = "9d2e4f6a1b3c4d5e8f7a6b5c4d3e2f1a";
723
724    /// A signed person's proposal for `vault`/`instance`, queued; the map
725    /// syncs its identity to `now_vault`.
726    fn queued_signed(
727        session: &Session,
728        vault: &str,
729        instance: &str,
730        now_vault: &str,
731    ) -> (Outbox, VaultMap) {
732        let proposal = QueuedProposal {
733            kind: ProposalKind::Person,
734            stable_identity: "b".repeat(64),
735            root: "/tmp/rc467-p".into(),
736            facts: Vec::new(),
737            title: "Show the retry budget in settings".into(),
738            goal: None,
739            acceptance: "The settings page names it".into(),
740            role: None,
741            session_ref: Some(PERSON_SESSION_LABEL.into()),
742            local_number: None,
743            ref_keyed: true,
744            signed: Some(SignedPerson {
745                signed_at: "2026-11-24T09:30:00Z".into(),
746                vault_id: vault.into(),
747                instance_id: instance.into(),
748                task_signature: "A".repeat(86),
749            }),
750        };
751        let outbox = Outbox::at(session.store.data_dir());
752        outbox
753            .enqueue(
754                CHANNEL_TASKS,
755                serde_json::to_value(&proposal).unwrap(),
756                UtcDateTime::now(),
757            )
758            .unwrap();
759        let mut map = VaultMap::default();
760        map.vaults.insert(
761            "b".repeat(64),
762            crate::vault::VaultRecord {
763                vault_id: now_vault.into(),
764                ns: "acme".into(),
765                name: "payments".into(),
766                sealed: false,
767                roots: Vec::new(),
768            },
769        );
770        (outbox, map)
771    }
772
773    /// rc4-67 (bd S3): a signature names its vault and machine. When the
774    /// project now syncs to another vault, or the machine is another one,
775    /// the proposal fails for good (never retried, never sent elsewhere),
776    /// before any request.
777    #[test]
778    fn a_signed_proposal_is_never_sent_to_another_vault_or_from_another_machine() {
779        let (_dir, mut session) = crate::auth::fixture_session();
780        // INSTANCE in upper case: the same machine.
781        session.instance.instance_id = INSTANCE.to_ascii_uppercase();
782        let other_vault = "0123456789abcdef0123456789abcdef";
783        let other_instance = "0a80ace1-52f1-49c2-85f7-6991bada0099";
784        for (vault, instance, now_vault) in [
785            (VAULT, INSTANCE, other_vault),
786            (VAULT, other_instance, VAULT),
787        ] {
788            let (outbox, map) = queued_signed(&session, vault, instance, now_vault);
789            let failed_before = outbox.failed(CHANNEL_TASKS).len();
790            let item = outbox.list(CHANNEL_TASKS).remove(0);
791            let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
792            let Delivery::Failed(problem) = &delivery else {
793                panic!("{delivery:?}");
794            };
795            assert!(problem.contains("syncs elsewhere"), "{problem}");
796            assert!(outbox.list(CHANNEL_TASKS).is_empty(), "not retried");
797            assert_eq!(outbox.failed(CHANNEL_TASKS).len(), failed_before + 1);
798        }
799    }
800
801    /// rc4-67 (bd S1): the ids are signed as the Cloud checks them.
802    #[test]
803    fn person_ids_are_signed_in_the_clouds_spelling() {
804        use crate::consent::task_key::canonical_person_ids;
805        let canonical = Some((INSTANCE.to_owned(), VAULT.to_owned()));
806        for instance in [INSTANCE, "3F1C2B6A-8D4E-4A7B-9C10-5E2F6A7B8C09"] {
807            assert_eq!(
808                canonical_person_ids(instance, VAULT),
809                canonical,
810                "{instance}"
811            );
812        }
813        assert_eq!(
814            canonical_person_ids(INSTANCE, &VAULT.to_ascii_uppercase()),
815            canonical
816        );
817        for (instance, vault) in [
818            ("inst-1", VAULT),
819            ("inst_01jb8z3k4m5n6p7q8r9s0t1v2w", VAULT),
820            ("inst_3f1c2b6a8d4e4a7b9c105e2f6a7b8c09", VAULT),
821            ("3f1c2b6a8d4e4a7b9c105e2f6a7b8c09", VAULT),
822            (INSTANCE, "p-1"),
823            (INSTANCE, "9d2e4f6a-1b3c-4d5e-8f7a-6b5c4d3e2f1a"),
824            (INSTANCE, ""),
825        ] {
826            assert_eq!(
827                canonical_person_ids(instance, vault),
828                None,
829                "{instance} {vault}"
830            );
831        }
832        // prepare refuses what it cannot sign so.
833        let (_dir, session) = crate::auth::fixture_session();
834        let fields = Fields {
835            title: "Show the retry budget in settings",
836            goal: None,
837            acceptance: "The settings page names it",
838            role: None,
839        };
840        let refused = prepare_person_task(
841            session.store.data_dir(),
842            Path::new("/tmp/rc467-p"),
843            &fields,
844            "inst-1",
845            VAULT,
846            UtcDateTime::now(),
847        );
848        assert!(refused.is_err());
849    }
850
851    /// rc4-67 (bd S3): the Cloud refusing a person's signature
852    /// (`person_unproven`, `signature_expired`) is final: neither transient
853    /// nor `Refused`, so `deliver()` fails it instead of retrying.
854    #[test]
855    fn an_unproven_or_expired_person_signature_is_never_retried() {
856        use crate::error::TaskRefusal;
857        for (reason, refusal) in [
858            ("person_unproven", TaskRefusal::PersonUnproven),
859            ("signature_expired", TaskRefusal::SignatureExpired),
860        ] {
861            let body = serde_json::json!({"error": {"code": "forbidden_right", "message": "x", "reason": reason}});
862            let error = CloudError::from_response(403, &body);
863            assert!(
864                matches!(&error, CloudError::Task { refusal: r, .. } if *r == refusal),
865                "{error:?}"
866            );
867            assert!(!error.is_transient(), "{reason}");
868            assert!(!matches!(error, CloudError::Refused(_)), "{reason}");
869        }
870    }
871
872    /// bd 39657 S-a: a proposal from a folder the person unlinked is not
873    /// sent through the record of its identity; it waits for a link.
874    #[test]
875    fn a_proposal_after_unlink_waits_and_is_not_sent() {
876        let (_dir, session) = crate::auth::fixture_session();
877        let data = session.store.data_dir().to_path_buf();
878        let root = tempfile::tempdir().unwrap();
879        let root_text = root.path().to_string_lossy().into_owned();
880        let stable = "a".repeat(64);
881        let outbox = Outbox::at(&data);
882        outbox
883            .enqueue(
884                CHANNEL_TASKS,
885                serde_json::json!({
886                    "kind": "agent",
887                    "stable_identity": stable,
888                    "root": root_text,
889                    "title": "Import the emspace pages",
890                    "acceptance": "Every page is a fact",
891                }),
892                UtcDateTime::now(),
893            )
894            .unwrap();
895        let mut map = VaultMap::default();
896        map.vaults.insert(
897            stable,
898            crate::vault::VaultRecord {
899                vault_id: "vlt_1".into(),
900                ns: "acme".into(),
901                name: "payments".into(),
902                sealed: false,
903                roots: vec!["/elsewhere/checkout".into()],
904            },
905        );
906        crate::unlinked::add(&data, root.path()).unwrap();
907
908        let item = outbox.list(CHANNEL_TASKS).remove(0);
909        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
910        assert_eq!(delivery, Delivery::Waiting(crate::unlinked::REFUSAL.into()));
911        assert_eq!(outbox.list(CHANNEL_TASKS).len(), 1, "still queued");
912        assert_eq!(outbox.depth(CHANNEL_TASKS).failed, 0);
913    }
914}