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
11use std::path::Path;
12
13use lean_ctx_time::UtcDateTime;
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16
17use super::screened;
18use crate::CloudError;
19use crate::auth::Session;
20use crate::outbox::{CHANNEL_TASKS, Outbox};
21use crate::vault::VaultMap;
22use lean_ctx_protocol::cloud::lease::CloudRight;
23use lean_ctx_protocol::cloud::tasks::{
24    TASK_PROPOSE_SCHEMA, TaskOriginKind, TaskOriginV1, TaskProposeRequestV1,
25};
26
27/// What a proposal is.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ProposalKind {
31    Agent,
32    Contradiction,
33}
34
35/// One queued proposal (the outbox payload).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct QueuedProposal {
38    pub kind: ProposalKind,
39    /// `stable_identity` of the project (as knowledge drafts name it).
40    pub stable_identity: String,
41    pub root: String,
42    /// The two contradicting facts; empty for an agent task.
43    #[serde(default)]
44    pub facts: Vec<String>,
45    pub title: String,
46    #[serde(default)]
47    pub goal: Option<String>,
48    pub acceptance: String,
49    #[serde(default)]
50    pub role: Option<String>,
51    /// Opaque session reference. [`propose_agent_task`] keys it under the
52    /// local receipts key (`session_ref::uploaded_ses_ref`) for a session id
53    /// and for the fixed labels callers pass in its place alike (such as
54    /// `emspace-import`), and queues nothing when that key is unavailable.
55    /// Only constant labels that name no session stay unsalted: the
56    /// `cloud-link` ref of a brought local task and, when absent, the
57    /// `cloud-task-proposals` ref of a contradiction proposal.
58    #[serde(default)]
59    pub session_ref: Option<String>,
60    /// The local task this proposal brings into the vault on link
61    /// (`cloud link --bring-local`); part of the key, so two local tasks
62    /// with the same title stay two vault tasks.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub local_number: Option<u64>,
65    /// `session_ref` is keyed already. Absent on a proposal queued before
66    /// refs were keyed: its stored ref (an unsalted digest; the queue never
67    /// kept the session id) is re-keyed before it is sent.
68    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
69    pub ref_keyed: bool,
70}
71
72impl QueuedProposal {
73    fn origin(&self) -> TaskOriginV1 {
74        let mut facts = self.facts.clone();
75        facts.sort();
76        TaskOriginV1 {
77            kind: match self.kind {
78                ProposalKind::Agent => TaskOriginKind::Agent,
79                ProposalKind::Contradiction => TaskOriginKind::Contradiction,
80            },
81            facts,
82            message: None,
83        }
84    }
85
86    /// Key a stored ref of a proposal queued before refs were keyed, so no
87    /// guessable digest is sent; an error (no local key) keeps it queued.
88    pub(crate) fn rekey_legacy_ref(&mut self, cloud_data: &Path) -> Result<(), CloudError> {
89        if self.ref_keyed {
90            return Ok(());
91        }
92        if let Some(stored) = &self.session_ref {
93            self.session_ref = Some(crate::session_ref::rekeyed_legacy_ref(cloud_data, stored)?);
94        }
95        self.ref_keyed = true;
96        Ok(())
97    }
98
99    fn session_ref(&self) -> String {
100        self.session_ref
101            .clone()
102            .unwrap_or_else(|| crate::knowledge::draft::session_ref("cloud-task-proposals"))
103    }
104
105    /// The request in the clear (validated before it is queued and sent).
106    fn plain_request(&self) -> TaskProposeRequestV1 {
107        TaskProposeRequestV1 {
108            schema: TASK_PROPOSE_SCHEMA.into(),
109            title: Some(self.title.clone()),
110            goal: self.goal.clone(),
111            acceptance: Some(self.acceptance.clone()),
112            role: self.role.clone(),
113            origin: self.origin(),
114            session_ref: self.session_ref(),
115        }
116    }
117
118    /// One proposal is one task, however often it is resent or requeued:
119    /// the key covers the project, the kind, the facts, (for an agent task)
120    /// the title and, for a brought local task, its local number.
121    #[must_use]
122    pub fn idempotency_key(&self) -> String {
123        let origin = self.origin();
124        let title = match self.kind {
125            ProposalKind::Agent => self.title.trim(),
126            ProposalKind::Contradiction => "",
127        };
128        let mut text = format!(
129            "leanctx.cloud.task-proposal.v1\n{}\n{:?}\n{}\n{title}",
130            self.stable_identity,
131            self.kind,
132            origin.facts.join(",")
133        );
134        // Absent for every other proposal: their keys stay as they were.
135        if let Some(number) = self.local_number {
136            text.push_str(&format!("\nlocal:{number}"));
137        }
138        let digest = Sha256::digest(text.as_bytes());
139        hex::encode(&digest[..16])
140    }
141}
142
143/// Secrets screened out, the request valid: before a proposal is queued
144/// or sent.
145fn checked(proposal: &QueuedProposal) -> Result<(), CloudError> {
146    screened(&[
147        ("title", Some(&proposal.title)),
148        ("goal", proposal.goal.as_deref()),
149        ("acceptance", Some(&proposal.acceptance)),
150    ])?;
151    proposal
152        .plain_request()
153        .validate()
154        .map_err(|e| CloudError::Refused(format!("invalid task proposal: {e}")))?;
155    Ok(())
156}
157
158/// Screen, validate and queue `proposal`; returns the outbox item id.
159pub fn enqueue(data_dir: &Path, proposal: &QueuedProposal) -> Result<String, CloudError> {
160    checked(proposal)?;
161    let payload = serde_json::to_value(proposal).map_err(|e| CloudError::Local(e.to_string()))?;
162    Outbox::at(data_dir).enqueue(CHANNEL_TASKS, payload, UtcDateTime::now())
163}
164
165/// Screen, validate and send `proposal` to `vault_id` now, without the
166/// outbox: for a caller that needs the task number at once (bringing local
167/// tasks into a vault on link). The idempotency key is the queued one, so
168/// a repeat after an interrupted run gets the same task back.
169pub fn propose_now(
170    session: &Session,
171    vault_id: &str,
172    proposal: &QueuedProposal,
173) -> Result<(u64, lean_ctx_protocol::cloud::tasks::TaskState), CloudError> {
174    checked(proposal)?;
175    send(session, vault_id, proposal)
176}
177
178/// An agent task for the project at `project_root`.
179pub fn propose_agent_task(
180    data_dir: &Path,
181    project_root: &Path,
182    title: &str,
183    goal: Option<&str>,
184    acceptance: &str,
185    role: Option<&str>,
186    session_id: &str,
187) -> Result<String, CloudError> {
188    let identity = crate::vault::project_identity(project_root).ok_or_else(|| {
189        CloudError::Config(
190            "this repository has no identity LeanCTX Cloud can link to a vault (no git remote)"
191                .into(),
192        )
193    })?;
194    enqueue(
195        data_dir,
196        &QueuedProposal {
197            kind: ProposalKind::Agent,
198            stable_identity: lean_ctx_protocol::cloud::vault::stable_identity(&identity),
199            root: project_root.to_string_lossy().into_owned(),
200            facts: Vec::new(),
201            title: title.trim().to_owned(),
202            goal: goal
203                .map(str::trim)
204                .filter(|g| !g.is_empty())
205                .map(str::to_owned),
206            acceptance: acceptance.trim().to_owned(),
207            role: role.map(str::to_owned),
208            // Keyed for a label too; without the local key nothing is queued.
209            session_ref: Some(crate::session_ref::uploaded_ses_ref(data_dir, session_id)?),
210            local_number: None,
211            ref_keyed: true,
212        },
213    )
214}
215
216/// What one drain pass did.
217#[derive(Debug, Clone, Default, PartialEq, Eq)]
218pub struct DrainReport {
219    /// The tasks Cloud created, with the state it gave each.
220    pub sent: Vec<(u64, lean_ctx_protocol::cloud::tasks::TaskState)>,
221    pub pending: usize,
222    pub failed: usize,
223    pub problems: Vec<String>,
224}
225
226/// What became of one queued proposal.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum Delivery {
229    /// Cloud created the task.
230    Sent(u64, lean_ctx_protocol::cloud::tasks::TaskState),
231    /// Kept in the outbox for a later pass (offline, 429, not linked yet).
232    Waiting(String),
233    /// Moved to the failed outbox; never sent.
234    Failed(String),
235}
236
237const NO_PROPOSE_RIGHT: &str = "the LeanCTX Cloud lease does not allow task proposals";
238
239fn deliver(
240    session: &Session,
241    outbox: &Outbox,
242    map: &VaultMap,
243    mut item: crate::outbox::OutboxItem,
244    now: lean_ctx_time::UtcDateTime,
245) -> Delivery {
246    let Ok(mut proposal) = serde_json::from_value::<QueuedProposal>(item.payload.clone()) else {
247        let _ = outbox.fail(&mut item, "damaged task proposal");
248        return Delivery::Failed("damaged task proposal".into());
249    };
250    // Queued before refs were keyed: keyed now, or kept queued while the
251    // local key is unavailable.
252    if let Err(error) = proposal.rekey_legacy_ref(session.store.data_dir()) {
253        let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
254        return Delivery::Waiting(error.to_string());
255    }
256    // The checkout's current vault first: a proposal queued under an
257    // identity the checkout left goes where the checkout syncs now.
258    let Some(record) = map
259        .for_root(&proposal.root)
260        .or_else(|| map.vaults.get(&proposal.stable_identity))
261    else {
262        let reason = "this repository is not linked to a vault yet";
263        let _ = outbox.retry_later(&mut item, reason, None, now);
264        return Delivery::Waiting(reason.into());
265    };
266    match send(session, &record.vault_id, &proposal) {
267        Ok((number, state)) => {
268            let _ = outbox.remove(&item);
269            Delivery::Sent(number, state)
270        }
271        Err(error) if error.is_transient() => {
272            // 429: Retry-After / retry_after_s, or a quota's reset_at.
273            let retry_after = error.retry_after_at(lean_ctx_time::UtcDateTime::now());
274            let _ = outbox.retry_later(&mut item, &error.to_string(), retry_after, now);
275            Delivery::Waiting(error.to_string())
276        }
277        Err(error @ CloudError::Refused(_)) => {
278            // Refused for now: try again later.
279            let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
280            Delivery::Waiting(error.to_string())
281        }
282        Err(error) => {
283            let _ = outbox.fail(&mut item, &error.to_string());
284            Delivery::Failed(error.to_string())
285        }
286    }
287}
288
289/// Send the due proposals (scheduler, `lean-ctx cloud sync`; never inside
290/// a tool call).
291pub fn drain(session: &Session) -> DrainReport {
292    let data = session.store.data_dir().to_path_buf();
293    let outbox = Outbox::at(&data);
294    let mut report = DrainReport::default();
295    let items = outbox.list(CHANNEL_TASKS);
296    if !items.is_empty() && !session.lease.lease.grants(CloudRight::TasksPropose) {
297        report.pending = items.len();
298        report.problems.push(NO_PROPOSE_RIGHT.into());
299        return report;
300    }
301    // Never into a vault a checkout's link file or identity left.
302    let map = match crate::resolution::load_current(&data) {
303        Ok((map, _)) => map,
304        Err(error) => {
305            report.problems.push(error.to_string());
306            VaultMap::default()
307        }
308    };
309    let now = UtcDateTime::now();
310    for item in items {
311        if !item.due(now) {
312            continue;
313        }
314        match deliver(session, &outbox, &map, item, now) {
315            Delivery::Sent(number, state) => report.sent.push((number, state)),
316            Delivery::Waiting(_) => {}
317            Delivery::Failed(problem) => report.problems.push(problem),
318        }
319    }
320    let depth = outbox.depth(CHANNEL_TASKS);
321    report.pending = depth.pending;
322    report.failed = depth.failed;
323    report
324}
325
326/// Send the queued proposal `id` now instead of with the next scheduler
327/// pass (`ctx_tasks propose` runs this off the tool call, as claims and
328/// results go out). A proposal that cannot go out now stays queued and the
329/// scheduler sends it later. `None`: the scheduler sent it meanwhile (Cloud's
330/// idempotency key keeps a resend of one proposal one task).
331#[must_use]
332pub fn send_now(session: &Session, id: &str) -> Option<Delivery> {
333    let data = session.store.data_dir().to_path_buf();
334    let outbox = Outbox::at(&data);
335    let item = outbox
336        .list(CHANNEL_TASKS)
337        .into_iter()
338        .find(|item| item.id == id)?;
339    if !session.lease.lease.grants(CloudRight::TasksPropose) {
340        return Some(Delivery::Waiting(NO_PROPOSE_RIGHT.into()));
341    }
342    // Never into a vault a checkout's link file or identity left.
343    let map = match crate::resolution::load_current(&data) {
344        Ok((map, _)) => map,
345        Err(error) => return Some(Delivery::Waiting(error.to_string())),
346    };
347    Some(deliver(session, &outbox, &map, item, UtcDateTime::now()))
348}
349
350/// The caller's line for what [`send_now`] did.
351#[must_use]
352pub fn delivery_line(delivery: Option<&Delivery>) -> String {
353    match delivery {
354        Some(Delivery::Sent(number, state)) => created_line(*number, *state),
355        Some(Delivery::Waiting(reason)) => format!(
356            "Task proposal not sent yet ({reason}); it stays queued and the next LeanCTX Cloud sync sends it."
357        ),
358        Some(Delivery::Failed(problem)) => format!("Task proposal not sent: {problem}."),
359        None => "Task proposal went out with the last LeanCTX Cloud sync.".into(),
360    }
361}
362
363fn send(
364    session: &Session,
365    vault_id: &str,
366    proposal: &QueuedProposal,
367) -> Result<(u64, lean_ctx_protocol::cloud::tasks::TaskState), CloudError> {
368    let request = proposal.plain_request();
369    let key = proposal.idempotency_key();
370    let sent = session
371        .with_client(|client| super::client::TasksApi { client, vault_id }.propose(&request, &key))
372        .map(|ack| (ack.number, ack.state));
373    super::reads::outdate(session.store.data_dir(), vault_id);
374    sent
375}
376
377/// What `lean-ctx cloud sync` prints for a task Cloud created from a
378/// proposal: its real state, so an agent knows whether it can claim it.
379#[must_use]
380pub fn created_line(number: u64, state: lean_ctx_protocol::cloud::tasks::TaskState) -> String {
381    use lean_ctx_protocol::cloud::tasks::TaskState;
382    match state {
383        TaskState::Open => format!("Created task #{number}, open now (any agent may claim it)."),
384        other => format!(
385            "Created task #{number} ({}).",
386            format!("{other:?}").to_lowercase()
387        ),
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    /// !406 follow-up: `deliver()` of a proposal queued before refs were
396    /// keyed (no `ref_keyed`, the unsalted digest) while the local key is
397    /// unavailable. It waits in the outbox with its stored ref and is never
398    /// moved to the failed outbox; with the key back the key gate lets it
399    /// through to the next step.
400    #[test]
401    fn a_legacy_proposal_without_a_key_waits_and_keeps_its_ref() {
402        let (_dir, session) = crate::auth::fixture_session();
403        let data = session.store.data_dir().to_path_buf();
404        let unsalted = crate::knowledge::draft::session_ref("20261116-091500u123456p4242s0");
405        let legacy = serde_json::json!({
406            "kind": "agent",
407            "stable_identity": "a".repeat(64),
408            "root": "/tmp/p",
409            "title": "Import the emspace pages",
410            "acceptance": "Every page is a fact",
411            "session_ref": unsalted,
412        });
413        let parsed: QueuedProposal = serde_json::from_value(legacy.clone()).unwrap();
414        assert!(!parsed.ref_keyed, "a pre-!406 payload");
415        let outbox = Outbox::at(&data);
416        let id = outbox
417            .enqueue(CHANNEL_TASKS, legacy.clone(), UtcDateTime::now())
418            .unwrap();
419        // No vault is mapped: had the key gate let it pass, the answer
420        // would be "not linked" and nothing would be sent either.
421        let map = VaultMap::default();
422
423        let keyless = data.join("receipts.hmac-key");
424        crate::session_ref::make_keyless(&data);
425        let item = outbox.list(CHANNEL_TASKS).remove(0);
426        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
427        let Delivery::Waiting(reason) = &delivery else {
428            panic!("{delivery:?}");
429        };
430        assert!(reason.contains("receipts.hmac-key"), "{reason}");
431        let items = outbox.list(CHANNEL_TASKS);
432        assert_eq!(items.len(), 1, "still queued");
433        assert_eq!(items[0].id, id);
434        assert_eq!(items[0].attempts, 1);
435        assert!(items[0].next_attempt_at.is_some(), "waits with a backoff");
436        assert_eq!(
437            items[0].payload, legacy,
438            "the stored ref is kept, never marked keyed"
439        );
440        assert_eq!(outbox.depth(CHANNEL_TASKS).failed, 0, "never failed");
441
442        // The key is readable again: the key gate passes, and the proposal
443        // waits for its vault, its payload still the stored one (it is keyed
444        // again, the same way, when it is sent).
445        std::fs::remove_dir(&keyless).unwrap();
446        let mut item = outbox.list(CHANNEL_TASKS).remove(0);
447        item.next_attempt_at = None;
448        let delivery = deliver(&session, &outbox, &map, item, UtcDateTime::now());
449        let Delivery::Waiting(reason) = &delivery else {
450            panic!("{delivery:?}");
451        };
452        assert!(reason.contains("not linked"), "{reason}");
453        assert!(!reason.contains("receipts.hmac-key"), "{reason}");
454        assert_eq!(outbox.list(CHANNEL_TASKS)[0].attempts, 2);
455    }
456}