Skip to main content

lean_ctx_protocol/cloud/
tasks.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Tasks, claims and results (C0 1.9, section 1).
4//!
5//! A task is a question or a piece of work in one Cloud vault with an
6//! acceptance criterion. People create tasks on the web. An engine may only
7//! *propose* one, for its agent or for a contradiction it found, and a person
8//! approves it before anyone can claim it.
9//!
10//! The rules:
11//! - A task has at most one claim at a time. The claim is a bus lease
12//!   (`kind task`, section 2), so Hold, Veto and Stop end it like any lease.
13//! - The holder reports short summaries (never prompts) and submits one
14//!   result with evidence. Every write carries the claim's fencing token, so
15//!   a stale holder is refused.
16//! - A result is a proposal (`origin task`), with its knowledge change if it
17//!   brings one.
18//! - The claiming instance never decides on it, not through its instance
19//!   token either. A person decides (the instance's owner included), or an
20//!   auto-merge threshold. A threshold counts independent confirmations: in
21//!   Team people and agents of other owners (one by
22//!   default, configurable per vault), and in Personal sessions on the owner's
23//!   other instances (one by default): never the claiming instance, in any
24//!   of its sessions (D1 per instance).
25//! - A signal (message, offer) never changes a task's state.
26//!
27//! ```text
28//! proposed --approve--> open --claim--> claimed --result--> submitted --accept--> done
29//!    |                   ^  ^              |                     |
30//!    +--reject--> rejected  +--release / expiry / veto / stop ---+   +--decline--> open
31//! proposed/open/claimed --cancel (people)--> cancelled
32//! ```
33//!
34//! Cloud v5 (additive): a result ends the task at once, `done`, or `failed`
35//! when the request says `outcome: failed`; no person decides on it. Task
36//! views carry a [`TaskLifecycle`] next to `state` (`queued → claimed →
37//! running → completed | failed | cancelled`), and a result references the
38//! log `seq` of its knowledge instead of a proposal (`proposal` 0). A 1.x
39//! Cloud answers `submitted` and sends no `lifecycle`; an engine sends
40//! `outcome` only to a Cloud whose task views carry `lifecycle`.
41//!
42//! Engine routes, all under `/v1/vaults/{vault_id}/tasks`:
43//!
44//! | Route | Body | Answer | Lease right |
45//! |---|---|---|---|
46//! | `GET` (`?state=…&role=…&mine=true&priority=…`) | | [`TaskListV1`] | `tasks.read` |
47//! | `GET /{number}` | | [`TaskV1`] | `tasks.read` |
48//! | `POST` | [`TaskProposeRequestV1`] | [`TaskAckV1`] (`proposed`) | `tasks.propose` |
49//! | `POST /{number}/claim` | [`TaskClaimRequestV1`] | [`TaskClaimAckV1`] | `tasks.work` |
50//! | `POST /{number}/claim/renew` | [`TaskClaimRenewRequestV1`] | [`TaskClaimAckV1`] | `tasks.work` |
51//! | `POST /{number}/release` | [`TaskReleaseRequestV1`] | [`TaskAckV1`] (`open`) | `tasks.work` |
52//! | `POST /{number}/updates` | [`TaskUpdateRequestV1`] | [`TaskAckV1`] | `tasks.work` |
53//! | `POST /{number}/result` | [`TaskResultRequestV1`] | [`TaskAckV1`] (`submitted`; v5 `done` or `failed`) | `tasks.work` |
54//! | `POST /{number}/verify` | [`TaskVerifyRequestV1`] | [`TaskAckV1`] (`done` or `open`; C0 2.2) | `tasks.work` |
55//! | `PATCH /{number}` | [`TaskFieldsRequestV1`] | [`TaskAckV1`] (C0 2.2) | `tasks.propose` |
56//!
57//! C0 2.2: a result leaves the task `submitted` (`failed` with `outcome:
58//! failed`) until another agent verifies it (E48): `accept` → `done`,
59//! `reject` → `open`. The verifier is never the result's worker (`403
60//! forbidden_right`, `reason` `self_verify`), and only a submitted task
61//! takes a verdict (`409 invalid_state`, `reason` `not_submitted`).
62//!
63//! Errors carry `number` (`CloudErrorDetailV1::number`):
64//! - `409 invalid_state`, `reason`:
65//!   - `task_claimed`: another claim holds the task;
66//!   - `task_not_open`: claim on a task that is not `open`;
67//!   - `stale_claim`: the lease id or fencing token is not the current claim's;
68//!   - `task_closed`: any write to a `done`, `rejected` or `cancelled` task;
69//!   - `reviewer_not_independent`: a confirmation that a threshold may not count.
70//! - `403 forbidden_right`, `reason`:
71//!   - `not_permitted`: the task's role or the owner's worker consent does
72//!     not allow this agent;
73//!   - `vetoed`: a veto or stop holds this agent;
74//!   - `optin_scope`: the engine's opt-in does not cover this vault
75//!     (section 4).
76//! - `409 invalid_state`, `reason` `optin_changed` or `optin_inactive`
77//!   (section 4).
78//! - `429 rate_limited`, `reason` `daily_budget`: the opt-in's daily
79//!   budget is used up (`retry_after_s` until it resets).
80//!
81//! A proposed task, an update and a result carry their text in the clear.
82
83use serde::{Deserialize, Serialize};
84
85use super::anchor::CodeAnchorV1;
86use super::knowledge::DraftProposalV1;
87use super::{require_schema, validate_hex64, validate_id, validate_text};
88use crate::{UtcTimestamp, ValidationError};
89
90pub const TASK_SCHEMA: &str = "leanctx.cloud.task/v1";
91pub const TASK_LIST_SCHEMA: &str = "leanctx.cloud.task-list/v1";
92pub const TASK_ACK_SCHEMA: &str = "leanctx.cloud.task-ack/v1";
93pub const TASK_PROPOSE_SCHEMA: &str = "leanctx.cloud.task-propose/v1";
94pub const TASK_CLAIM_REQUEST_SCHEMA: &str = "leanctx.cloud.task-claim-request/v1";
95pub const TASK_CLAIM_RENEW_SCHEMA: &str = "leanctx.cloud.task-claim-renew/v1";
96pub const TASK_CLAIM_ACK_SCHEMA: &str = "leanctx.cloud.task-claim/v1";
97pub const TASK_RELEASE_SCHEMA: &str = "leanctx.cloud.task-release/v1";
98pub const TASK_UPDATE_SCHEMA: &str = "leanctx.cloud.task-update/v1";
99pub const TASK_RESULT_SCHEMA: &str = "leanctx.cloud.task-result/v1";
100/// C0 2.2 E48: another agent's verdict on a submitted result.
101pub const TASK_VERIFY_SCHEMA: &str = "leanctx.cloud.task-verify/v1";
102/// 3.12.3: the submitter corrects its submitted result (summary, evidence).
103pub const TASK_AMEND_SCHEMA: &str = "leanctx.cloud.task-amend/v1";
104/// C0 2.2 E47 `PATCH`: a task's priority and labels.
105pub const TASK_FIELDS_SCHEMA: &str = "leanctx.cloud.task-fields/v1";
106
107pub const MIN_TITLE_CHARS: usize = 5;
108pub const MAX_TITLE_CHARS: usize = 180;
109pub const MAX_GOAL_CHARS: usize = 2000;
110pub const MAX_ACCEPTANCE_CHARS: usize = 2000;
111/// Updates and result summaries are summaries, not prompts: one line.
112pub const MAX_SUMMARY_CHARS: usize = 500;
113pub const MAX_REASON_CHARS: usize = 280;
114/// A verifier's reason (C0 2.2 E48), required on `reject`.
115pub const MAX_VERIFY_REASON_CHARS: usize = 2000;
116pub const MAX_TASK_LABELS: usize = 16;
117pub const MAX_EVIDENCE: usize = 20;
118pub const MAX_EVIDENCE_REF_CHARS: usize = 512;
119/// Updates a task view carries, newest last.
120pub const MAX_VIEW_UPDATES: usize = 20;
121pub const MAX_TASKS_PAGE: usize = 100;
122/// A claim is a bus lease: 5 to 15 minutes ([`super::bus::MAX_BUS_LEASE_MS`]),
123/// renewed while work goes on, so a silent agent frees the task quickly.
124pub const MIN_CLAIM_MINUTES: u32 = 5;
125pub const MAX_CLAIM_MINUTES: u32 = 15;
126
127/// Lifecycle of a task.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
129#[serde(rename_all = "snake_case")]
130pub enum TaskState {
131    /// Proposed by an engine or the system; a person must approve it.
132    Proposed,
133    Open,
134    Claimed,
135    /// A result waits for its decision.
136    Submitted,
137    Done,
138    /// A proposed task a person declined.
139    Rejected,
140    Cancelled,
141    /// Cloud v5: the holder ended its claim with a failure (terminal).
142    Failed,
143    #[serde(other)]
144    Unknown,
145}
146
147/// Cloud v5 lifecycle of a task, sent next to `state` (additive):
148/// `queued → claimed → running → completed | failed | cancelled`.
149/// `running` = claimed, and the holder reported progress under this claim.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
151#[serde(rename_all = "snake_case")]
152pub enum TaskLifecycle {
153    Queued,
154    Claimed,
155    Running,
156    /// C0 2.2: a result waits for a second agent's check.
157    Submitted,
158    Completed,
159    Failed,
160    Cancelled,
161    #[serde(other)]
162    Unknown,
163}
164
165/// How the holder ends its claim with a result (Cloud v5); absent on the
166/// wire means `completed`.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
168#[serde(rename_all = "snake_case")]
169pub enum TaskOutcome {
170    #[default]
171    Completed,
172    Failed,
173}
174
175/// Who created a task, and why.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178pub enum TaskOriginKind {
179    /// A person: on the web, or in LeanCTX Code, whose engine relays the
180    /// person's own proposal (the Cloud names the person the engine is
181    /// linked to, never one from the request).
182    Person,
183    /// An engine, for its agent.
184    Agent,
185    /// An engine that found two facts contradicting each other.
186    Contradiction,
187    /// A question no agent answered (section 2).
188    Question,
189    /// Any other origin.
190    #[serde(other)]
191    Unknown,
192}
193
194/// Origin of a task. `facts` names exactly two distinct fact ids for a
195/// contradiction; `message` names the question's message id for a
196/// question.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(deny_unknown_fields)]
199pub struct TaskOriginV1 {
200    pub kind: TaskOriginKind,
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub facts: Vec<String>,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub message: Option<String>,
205}
206
207impl TaskOriginV1 {
208    /// What an engine may send: `agent`, `person` (a person's proposal
209    /// from LeanCTX Code, only to a Cloud that announces
210    /// `task_person_origin`), or `contradiction` with two facts.
211    pub fn validate_from_engine(&self) -> Result<(), ValidationError> {
212        if self.message.is_some() {
213            return Err(ValidationError::new("engines do not create question tasks"));
214        }
215        match self.kind {
216            TaskOriginKind::Agent | TaskOriginKind::Person if self.facts.is_empty() => Ok(()),
217            TaskOriginKind::Agent => Err(ValidationError::new("an agent task names no facts")),
218            TaskOriginKind::Person => Err(ValidationError::new("a person's task names no facts")),
219            TaskOriginKind::Contradiction => {
220                if self.facts.len() != 2 || self.facts[0] == self.facts[1] {
221                    return Err(ValidationError::new(
222                        "a contradiction names exactly two distinct facts",
223                    ));
224                }
225                self.facts
226                    .iter()
227                    .try_for_each(|id| validate_id(id, "facts"))
228            }
229            _ => Err(ValidationError::new(
230                "a proposal is an agent, person or contradiction task only",
231            )),
232        }
233    }
234}
235
236/// An actor as an engine sees it: never a user id or an email.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct TaskActorV1 {
239    pub kind: TaskActorKind,
240    /// A person's display name, or an instance label.
241    pub label: String,
242    /// The agent on that instance (bus agent id), for instances.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub agent: Option<String>,
245    /// The person who owns that instance (display name), for instances.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub owner: Option<String>,
248    /// The model the agent reported for itself; unverified.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub model: Option<String>,
251    /// Whether this is the instance asking.
252    pub mine: bool,
253    /// 1.9 (section 5): the agent's profile, for instances.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub profile_id: Option<String>,
256    /// rc4-79/rc4-67: whether this actor is the person the asking instance
257    /// is linked to (the Cloud compares person ids, which it never sends).
258    /// Absent from a Cloud that does not say: not known.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub own: Option<bool>,
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(rename_all = "snake_case")]
265pub enum TaskActorKind {
266    Person,
267    Instance,
268    #[serde(other)]
269    Unknown,
270}
271
272/// One piece of evidence. `reference` is what the kind names:
273/// - `receipt`: a receipt digest (64 lowercase hex), checked by Cloud;
274/// - `commit`: a commit id (7-64 hex);
275/// - `ci_run`: a CI run reference (an `https` URL or a provider id);
276/// - `file_anchor`: absent, the anchor is in `anchor`;
277/// - `url`: an `https` URL, which Cloud never fetches;
278/// - `fact`: a fact id of the vault.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281pub struct EvidenceV1 {
282    pub kind: EvidenceKind,
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub reference: Option<String>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub anchor: Option<CodeAnchorV1>,
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
290#[serde(rename_all = "snake_case")]
291pub enum EvidenceKind {
292    Receipt,
293    Commit,
294    CiRun,
295    FileAnchor,
296    Url,
297    Fact,
298    #[serde(other)]
299    Unknown,
300}
301
302impl EvidenceV1 {
303    pub fn validate(&self) -> Result<(), ValidationError> {
304        let refuse = || ValidationError::new(format!("evidence does not fit kind {:?}", self.kind));
305        if self.kind == EvidenceKind::FileAnchor {
306            return match (&self.reference, &self.anchor) {
307                (None, Some(anchor)) => anchor.validate(),
308                _ => Err(refuse()),
309            };
310        }
311        if self.anchor.is_some() {
312            return Err(refuse());
313        }
314        let reference = self.reference.as_deref().ok_or_else(refuse)?;
315        validate_text(
316            reference,
317            MAX_EVIDENCE_REF_CHARS,
318            "evidence.reference",
319            false,
320        )?;
321        let https = |r: &str| r.starts_with("https://") && !r.contains(char::is_whitespace);
322        let ok = match self.kind {
323            EvidenceKind::Receipt => validate_hex64(reference, "evidence.reference").is_ok(),
324            EvidenceKind::Commit => {
325                (7..=64).contains(&reference.len())
326                    && reference
327                        .bytes()
328                        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
329            }
330            EvidenceKind::CiRun => https(reference) || validate_id(reference, "ci_run").is_ok(),
331            EvidenceKind::Url => https(reference),
332            EvidenceKind::Fact => validate_id(reference, "fact").is_ok(),
333            EvidenceKind::FileAnchor | EvidenceKind::Unknown => false,
334        };
335        if ok { Ok(()) } else { Err(refuse()) }
336    }
337}
338
339fn validate_evidence(evidence: &[EvidenceV1]) -> Result<(), ValidationError> {
340    if evidence.is_empty() || evidence.len() > MAX_EVIDENCE {
341        return Err(ValidationError::new(format!(
342            "a result carries 1-{MAX_EVIDENCE} pieces of evidence"
343        )));
344    }
345    for (i, item) in evidence.iter().enumerate() {
346        item.validate()?;
347        if evidence[..i].contains(item) {
348            return Err(ValidationError::new("evidence repeats"));
349        }
350    }
351    Ok(())
352}
353
354fn validate_title(title: &str) -> Result<(), ValidationError> {
355    validate_text(title, MAX_TITLE_CHARS, "title", false)?;
356    if title.trim().chars().count() < MIN_TITLE_CHARS {
357        return Err(ValidationError::new(format!(
358            "title must have at least {MIN_TITLE_CHARS} characters"
359        )));
360    }
361    Ok(())
362}
363
364/// An agent role slug (section 5): 1-64 of `[a-z0-9-]`, starting with a letter.
365pub fn validate_role(role: &str) -> Result<(), ValidationError> {
366    let bytes = role.as_bytes();
367    if !bytes.is_empty()
368        && bytes.len() <= 64
369        && bytes[0].is_ascii_lowercase()
370        && bytes
371            .iter()
372            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
373    {
374        Ok(())
375    } else {
376        Err(ValidationError::new(
377            "role must be 1-64 characters of [a-z0-9-] starting with a letter",
378        ))
379    }
380}
381
382/// A task write carries its text (`plain`).
383fn text_required(plain: bool) -> Result<(), ValidationError> {
384    if plain {
385        Ok(())
386    } else {
387        Err(ValidationError::new("text is required"))
388    }
389}
390
391/// The claim a write acts under: the lease id and its fencing token.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(deny_unknown_fields)]
394pub struct ClaimRefV1 {
395    pub lease_id: String,
396    pub fencing_token: u64,
397}
398
399impl ClaimRefV1 {
400    pub fn validate(&self) -> Result<(), ValidationError> {
401        validate_id(&self.lease_id, "lease_id")?;
402        if self.fencing_token == 0 {
403            return Err(ValidationError::new("fencing tokens start at 1"));
404        }
405        Ok(())
406    }
407}
408
409fn validate_minutes(minutes: u32) -> Result<(), ValidationError> {
410    if (MIN_CLAIM_MINUTES..=MAX_CLAIM_MINUTES).contains(&minutes) {
411        Ok(())
412    } else {
413        Err(ValidationError::new(format!(
414            "minutes must be {MIN_CLAIM_MINUTES}-{MAX_CLAIM_MINUTES}"
415        )))
416    }
417}
418
419/// `POST /v1/vaults/{vault_id}/tasks`: an engine proposes a task.
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
421#[serde(deny_unknown_fields)]
422pub struct TaskProposeRequestV1 {
423    pub schema: String,
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub title: Option<String>,
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub goal: Option<String>,
428    /// When the task is done; required in the clear.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub acceptance: Option<String>,
431    /// The agent role it is for (section 5); any role when absent.
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub role: Option<String>,
434    pub origin: TaskOriginV1,
435    /// Opaque, per-session id (no host or user data).
436    pub session_ref: String,
437    /// rc4-67: when the person signed their own proposal in the app
438    /// (RFC 3339, second precision `Z`); only with origin `person`.
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub signed_at: Option<String>,
441    /// rc4-67: the app's task-propose key over
442    /// `leanctx.cloud.task_propose_person.v1\n` + canonical JSON of this
443    /// body without the signature, plus `instance_id` and `vault_id`.
444    /// Base64url, no padding; only with origin `person`.
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub task_signature: Option<String>,
447}
448
449/// The longest base64url text an Ed25519 signature takes (86 characters).
450const TASK_SIGNATURE_CHARS: usize = 86;
451
452impl TaskProposeRequestV1 {
453    pub fn validate(&self) -> Result<(), ValidationError> {
454        require_schema(&self.schema, TASK_PROPOSE_SCHEMA)?;
455        self.origin.validate_from_engine()?;
456        self.validate_signed()?;
457        validate_id(&self.session_ref, "session_ref")?;
458        if let Some(role) = &self.role {
459            validate_role(role)?;
460        }
461        let plain = self.title.is_some() || self.goal.is_some() || self.acceptance.is_some();
462        text_required(plain)?;
463        if plain {
464            validate_title(self.title.as_deref().unwrap_or_default())?;
465            if let Some(goal) = &self.goal {
466                validate_text(goal, MAX_GOAL_CHARS, "goal", true)?;
467            }
468            validate_text(
469                self.acceptance.as_deref().unwrap_or_default(),
470                MAX_ACCEPTANCE_CHARS,
471                "acceptance",
472                true,
473            )?;
474        }
475        Ok(())
476    }
477
478    /// A person's proposal carries the app's signature and its time; any
479    /// other origin carries neither (the Cloud refuses both mismatches).
480    fn validate_signed(&self) -> Result<(), ValidationError> {
481        let person = self.origin.kind == TaskOriginKind::Person;
482        match (&self.signed_at, &self.task_signature) {
483            (None, None) if !person => Ok(()),
484            (Some(at), Some(signature)) if person => {
485                let at_ok = at.len() == 20
486                    && at.ends_with('Z')
487                    && at.bytes().enumerate().all(|(i, b)| match i {
488                        4 | 7 => b == b'-',
489                        10 => b == b'T',
490                        13 | 16 => b == b':',
491                        19 => b == b'Z',
492                        _ => b.is_ascii_digit(),
493                    });
494                if !at_ok {
495                    return Err(ValidationError::new("signed_at is not a UTC time"));
496                }
497                let sig_ok = signature.len() == TASK_SIGNATURE_CHARS
498                    && signature
499                        .bytes()
500                        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
501                if sig_ok {
502                    Ok(())
503                } else {
504                    Err(ValidationError::new("task_signature is not a signature"))
505                }
506            }
507            _ if person => Err(ValidationError::new(
508                "a person's proposal carries signed_at and task_signature",
509            )),
510            _ => Err(ValidationError::new(
511                "only a person's proposal carries signed_at and task_signature",
512            )),
513        }
514    }
515}
516
517/// `POST …/{number}/claim`.
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct TaskClaimRequestV1 {
521    pub schema: String,
522    /// The bus agent id the claim is for.
523    pub agent: String,
524    pub session_ref: String,
525    pub minutes: u32,
526    /// The engine opt-in the claim works under (section 4), whose budget
527    /// it draws on: the `optin_id` the engine last read. Cloud requires it
528    /// and refuses a stale one (`optin_changed`).
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub optin_id: Option<String>,
531}
532
533impl TaskClaimRequestV1 {
534    pub fn validate(&self) -> Result<(), ValidationError> {
535        require_schema(&self.schema, TASK_CLAIM_REQUEST_SCHEMA)?;
536        validate_id(&self.agent, "agent")?;
537        validate_id(&self.session_ref, "session_ref")?;
538        if let Some(optin) = &self.optin_id {
539            validate_id(optin, "optin_id")?;
540        }
541        validate_minutes(self.minutes)
542    }
543}
544
545/// `POST …/{number}/claim/renew`. 1.9 erratum: the renewed claim keeps its
546/// lease id and fencing token (the bus lease rule).
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
548#[serde(deny_unknown_fields)]
549pub struct TaskClaimRenewRequestV1 {
550    pub schema: String,
551    pub claim: ClaimRefV1,
552    pub minutes: u32,
553}
554
555impl TaskClaimRenewRequestV1 {
556    pub fn validate(&self) -> Result<(), ValidationError> {
557        require_schema(&self.schema, TASK_CLAIM_RENEW_SCHEMA)?;
558        self.claim.validate()?;
559        validate_minutes(self.minutes)
560    }
561}
562
563/// The one claim on a task, as a task view shows it.
564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565pub struct TaskClaimV1 {
566    pub holder: TaskActorV1,
567    pub since: UtcTimestamp,
568    pub until: UtcTimestamp,
569}
570
571/// Answer of claim and renew: the lease the holder writes under.
572#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
573pub struct TaskClaimAckV1 {
574    pub schema: String,
575    pub number: u64,
576    pub claim: ClaimRefV1,
577    pub until: UtcTimestamp,
578}
579
580/// `POST …/{number}/release`: give the task back (blocked, out of scope).
581#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
582#[serde(deny_unknown_fields)]
583pub struct TaskReleaseRequestV1 {
584    pub schema: String,
585    pub claim: ClaimRefV1,
586    /// Why, in one line.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub reason: Option<String>,
589}
590
591impl TaskReleaseRequestV1 {
592    pub fn validate(&self) -> Result<(), ValidationError> {
593        require_schema(&self.schema, TASK_RELEASE_SCHEMA)?;
594        self.claim.validate()?;
595        if let Some(reason) = &self.reason {
596            validate_text(reason, MAX_REASON_CHARS, "reason", false)?;
597        }
598        Ok(())
599    }
600}
601
602/// What the work cost the agent's owner so far (self-reported): model
603/// tokens and, if known, US dollars in millionths (integers only, as
604/// everything under a signature).
605#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
606#[serde(deny_unknown_fields)]
607pub struct UsageV1 {
608    /// Negative amounts read as 0 ([`super::usage::non_negative`]).
609    #[serde(deserialize_with = "super::usage::non_negative")]
610    pub tokens: u64,
611    #[serde(
612        default,
613        skip_serializing_if = "Option::is_none",
614        deserialize_with = "super::usage::non_negative_opt"
615    )]
616    pub usd_micros: Option<u64>,
617}
618
619/// `POST …/{number}/updates`: one short summary from the holder.
620#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
621#[serde(deny_unknown_fields)]
622pub struct TaskUpdateRequestV1 {
623    pub schema: String,
624    pub claim: ClaimRefV1,
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub summary: Option<String>,
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub usage: Option<UsageV1>,
629}
630
631impl TaskUpdateRequestV1 {
632    pub fn validate(&self) -> Result<(), ValidationError> {
633        require_schema(&self.schema, TASK_UPDATE_SCHEMA)?;
634        self.claim.validate()?;
635        text_required(self.summary.is_some())?;
636        if let Some(summary) = &self.summary {
637            validate_text(summary, MAX_SUMMARY_CHARS, "summary", false)?;
638        }
639        Ok(())
640    }
641}
642
643/// `POST …/{number}/result`: the holder's result. It ends the claim; a 1.x
644/// Cloud turns it into a proposal (`origin task`), Cloud v5 ends the task
645/// (`done`, or `failed` with `outcome: failed`). `draft` is its knowledge
646/// change, if it brings one, exactly as a regular draft; a failed result
647/// brings none.
648#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
649#[serde(deny_unknown_fields)]
650pub struct TaskResultRequestV1 {
651    pub schema: String,
652    pub claim: ClaimRefV1,
653    #[serde(default, skip_serializing_if = "Option::is_none")]
654    pub summary: Option<String>,
655    #[serde(default, skip_serializing_if = "Vec::is_empty")]
656    pub evidence: Vec<EvidenceV1>,
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub draft: Option<DraftProposalV1>,
659    #[serde(default, skip_serializing_if = "Option::is_none")]
660    pub usage: Option<UsageV1>,
661    /// Cloud v5; absent = `completed`. A 1.x Cloud refuses the field
662    /// (unknown fields are denied), so it is sent only to a v5 Cloud.
663    #[serde(default, skip_serializing_if = "Option::is_none")]
664    pub outcome: Option<TaskOutcome>,
665    /// Process v1 G6: the Instance's part of the record for the judged
666    /// commit (clean locked paths, a green rerun; blocked on the CI pipeline
667    /// Cloud reads). Sent only for a process task (a task view with
668    /// `process`), so a Cloud without process tasks never sees the field.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub gate_record: Option<super::gate::G6RecordV1>,
671}
672
673impl TaskResultRequestV1 {
674    pub fn validate(&self) -> Result<(), ValidationError> {
675        require_schema(&self.schema, TASK_RESULT_SCHEMA)?;
676        self.claim.validate()?;
677        let plain = self.summary.is_some() || !self.evidence.is_empty();
678        text_required(plain)?;
679        if plain {
680            validate_text(
681                self.summary.as_deref().unwrap_or_default(),
682                MAX_SUMMARY_CHARS,
683                "summary",
684                false,
685            )?;
686            validate_evidence(&self.evidence)?;
687        }
688        if let Some(draft) = &self.draft {
689            if self.outcome == Some(TaskOutcome::Failed) {
690                return Err(ValidationError::new("a failed result brings no draft"));
691            }
692            draft.validate()?;
693        }
694        if let Some(record) = &self.gate_record {
695            record.validate()?;
696            if !record.ready_for_cloud() || self.outcome == Some(TaskOutcome::Failed) {
697                return Err(ValidationError::new(
698                    "a result carries only a G6 record whose Instance checks hold, on a completed result",
699                ));
700            }
701        }
702        Ok(())
703    }
704}
705
706/// Answer of every task write: the number and the state afterwards.
707#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
708pub struct TaskAckV1 {
709    pub schema: String,
710    pub number: u64,
711    pub state: TaskState,
712}
713
714/// A verifier's verdict on a submitted result (C0 2.2): `accept` makes the
715/// task `done`, `reject` opens it again.
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
717#[serde(rename_all = "snake_case")]
718pub enum TaskVerdict {
719    Accept,
720    Reject,
721    #[serde(other)]
722    Unknown,
723}
724
725/// `POST …/{number}/verify` (C0 2.2 E48, `tasks.work`): another agent's
726/// verdict. `worker_id` is the verifying agent, never the result's
727/// (`403 self_verify`); `reason` is required on `reject`.
728#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
729#[serde(deny_unknown_fields)]
730pub struct TaskVerifyRequestV1 {
731    pub schema: String,
732    pub worker_id: String,
733    pub verdict: TaskVerdict,
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub reason: Option<String>,
736}
737
738fn validate_worker_id(worker_id: &str) -> Result<(), ValidationError> {
739    let worker_ok = (1..=128).contains(&worker_id.len())
740        && worker_id
741            .bytes()
742            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'));
743    if worker_ok {
744        Ok(())
745    } else {
746        Err(ValidationError::new(
747            "worker_id is 1-128 of [A-Za-z0-9._:-]",
748        ))
749    }
750}
751
752impl TaskVerifyRequestV1 {
753    pub fn validate(&self) -> Result<(), ValidationError> {
754        require_schema(&self.schema, TASK_VERIFY_SCHEMA)?;
755        validate_worker_id(&self.worker_id)?;
756        match (self.verdict, &self.reason) {
757            (TaskVerdict::Unknown, _) => Err(ValidationError::new("verdict is accept or reject")),
758            (TaskVerdict::Reject, None) => Err(ValidationError::new("a reject names its reason")),
759            (_, Some(reason)) => validate_text(reason, MAX_VERIFY_REASON_CHARS, "reason", false),
760            (TaskVerdict::Accept, None) => Ok(()),
761        }
762    }
763}
764
765/// The last verdict on a task's result, as a task view shows it (C0 2.2).
766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
767pub struct TaskVerificationV1 {
768    pub verdict: TaskVerdict,
769    pub by: TaskActorV1,
770    pub at: UtcTimestamp,
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub reason: Option<String>,
773}
774
775/// `POST …/{number}/amend` (3.12.3, `tasks.work`): a result is corrected
776/// without a claim (a submit ends the claim). Two shapes, by state
777/// ([`amend_rule`]):
778/// - `submitted`: the agent that submitted it (`worker_id`) replaces
779///   `evidence` (the whole new list) and optionally `summary`;
780/// - `done`: the submitter, a person or a registered Queen session records
781///   the merge once (`merge_commit`, the merge commit's SHA); nothing else
782///   changes. Never the reviewer (`verified_by`): `403 not_merger`.
783///
784/// Anyone else is `403 not_submitter` ([`may_amend`]). Cloud appends a `kind: amendment`
785/// update with `amended_from` (the evidence before) and `amended_to` (the
786/// evidence after, or the merge commit), so the history keeps old → new.
787#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
788#[serde(deny_unknown_fields)]
789pub struct TaskAmendRequestV1 {
790    pub schema: String,
791    pub worker_id: String,
792    #[serde(default, skip_serializing_if = "Option::is_none")]
793    pub summary: Option<String>,
794    #[serde(default, skip_serializing_if = "Vec::is_empty")]
795    pub evidence: Vec<EvidenceV1>,
796    /// The merge commit's SHA (7-64 lowercase hex), on a `done` task only.
797    #[serde(default, skip_serializing_if = "Option::is_none")]
798    pub merge_commit: Option<String>,
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub reason: Option<String>,
801}
802
803impl TaskAmendRequestV1 {
804    pub fn validate(&self) -> Result<(), ValidationError> {
805        require_schema(&self.schema, TASK_AMEND_SCHEMA)?;
806        validate_worker_id(&self.worker_id)?;
807        if let Some(reason) = &self.reason {
808            validate_text(reason, MAX_REASON_CHARS, "reason", false)?;
809        }
810        match &self.merge_commit {
811            Some(commit) => {
812                if !self.evidence.is_empty() || self.summary.is_some() {
813                    return Err(ValidationError::new(
814                        "a merge record carries only merge_commit (no evidence, no summary)",
815                    ));
816                }
817                merge_evidence(commit).validate()
818            }
819            None => {
820                if let Some(summary) = &self.summary {
821                    validate_text(summary, MAX_SUMMARY_CHARS, "summary", false)?;
822                }
823                validate_evidence(&self.evidence)
824            }
825        }
826    }
827}
828
829/// The merge commit as a piece of evidence (how history shows it).
830pub fn merge_evidence(commit: &str) -> EvidenceV1 {
831    EvidenceV1 {
832        kind: EvidenceKind::Commit,
833        reference: Some(commit.to_owned()),
834        anchor: None,
835    }
836}
837
838/// Why a result cannot be amended (the Cloud reason code in brackets).
839#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840pub enum AmendRefusal {
841    /// Only a `submitted` or `done` task carries a result to amend
842    /// (`not_amendable`).
843    NotAmendable,
844    /// A `done` task takes only a merge record (`record_merge_only`).
845    RecordMergeOnly,
846    /// A merge record is for a `done` task; a `submitted` one is not merged
847    /// yet (`not_merged_yet`).
848    NotMergedYet,
849    /// The task's merge is already recorded; it is never replaced
850    /// (`merge_recorded`).
851    MergeRecorded,
852}
853
854impl AmendRefusal {
855    pub fn code(self) -> &'static str {
856        match self {
857            Self::NotAmendable => "not_amendable",
858            Self::RecordMergeOnly => "record_merge_only",
859            Self::NotMergedYet => "not_merged_yet",
860            Self::MergeRecorded => "merge_recorded",
861        }
862    }
863}
864
865/// What a task's state allows an amendment of its result: `submitted`
866/// replaces summary and evidence; `done` records the merge once and
867/// changes nothing else; any other state refuses. The one rule for Cloud and
868/// the client (the client checks first, Cloud enforces); who may amend is
869/// [`may_amend`].
870pub fn amend_rule(task: &TaskV1, request: &TaskAmendRequestV1) -> Result<(), AmendRefusal> {
871    let result = task.result.as_ref().ok_or(AmendRefusal::NotAmendable)?;
872    match (task.state, &request.merge_commit) {
873        (TaskState::Submitted, None) => Ok(()),
874        (TaskState::Submitted, Some(_)) => Err(AmendRefusal::NotMergedYet),
875        (TaskState::Done, Some(_)) if result.merge.is_some() => Err(AmendRefusal::MergeRecorded),
876        (TaskState::Done, Some(_)) => Ok(()),
877        (TaskState::Done, None) => Err(AmendRefusal::RecordMergeOnly),
878        _ => Err(AmendRefusal::NotAmendable),
879    }
880}
881
882/// Who is amending, as the caller established it: the result's submitter,
883/// the reviewer (the actor whose verdict made the task `done`), a person,
884/// or a Queen session the app registered.
885#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
886pub struct AmendCaller {
887    pub submitter: bool,
888    pub reviewer: bool,
889    pub person: bool,
890    pub queen: bool,
891}
892
893/// Why this caller may not amend (`403` with the code).
894#[derive(Debug, Clone, Copy, PartialEq, Eq)]
895pub enum AmendForbidden {
896    /// Only the submitter corrects a result (`not_submitter`).
897    NotSubmitter,
898    /// The reviewer never records the merge: checker and merger stay
899    /// separate (`not_merger`).
900    NotMerger,
901}
902
903impl AmendForbidden {
904    pub fn code(self) -> &'static str {
905        match self {
906            Self::NotSubmitter => "not_submitter",
907            Self::NotMerger => "not_merger",
908        }
909    }
910}
911
912/// Who may amend: the submitter always (a correction, or its merge
913/// record); a merge record also a person or a registered Queen session;
914/// never the reviewer (`not_merger`), anyone else `not_submitter`.
915pub fn may_amend(request: &TaskAmendRequestV1, caller: AmendCaller) -> Result<(), AmendForbidden> {
916    if caller.submitter {
917        return Ok(());
918    }
919    if request.merge_commit.is_none() {
920        return Err(AmendForbidden::NotSubmitter);
921    }
922    if caller.reviewer {
923        return Err(AmendForbidden::NotMerger);
924    }
925    if caller.person || caller.queen {
926        Ok(())
927    } else {
928        Err(AmendForbidden::NotSubmitter)
929    }
930}
931
932/// 3.12.3: a `done` task's merge record (`amend` with `merge_commit`).
933#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
934pub struct TaskMergeV1 {
935    pub commit: String,
936    pub by: TaskActorV1,
937    pub at: UtcTimestamp,
938}
939
940/// What a task update is (C0 2.2): the holder's progress, or a verifier's
941/// verdict.
942#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
943#[serde(rename_all = "snake_case")]
944pub enum TaskUpdateKind {
945    Progress,
946    Verification,
947    /// 3.12.3: the submitter amended its result (`amended_from` holds the
948    /// evidence before).
949    Amendment,
950    #[serde(other)]
951    Unknown,
952}
953
954/// A task's priority (C0 2.2); absent means `normal`.
955#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
956#[serde(rename_all = "snake_case")]
957pub enum TaskPriority {
958    High,
959    #[default]
960    Normal,
961}
962
963/// `PATCH …/{number}` (C0 2.2 E47, `tasks.propose`): an agent sets a
964/// task's priority and labels. `base_version` is the task's
965/// `fields_version`; a mismatch answers `409 stale_base`.
966#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
967#[serde(deny_unknown_fields)]
968pub struct TaskFieldsRequestV1 {
969    pub schema: String,
970    pub base_version: u32,
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub priority: Option<TaskPriority>,
973    #[serde(default, skip_serializing_if = "Option::is_none")]
974    pub labels: Option<Vec<String>>,
975}
976
977impl TaskFieldsRequestV1 {
978    pub fn validate(&self) -> Result<(), ValidationError> {
979        require_schema(&self.schema, TASK_FIELDS_SCHEMA)?;
980        if self.priority.is_none() && self.labels.is_none() {
981            return Err(ValidationError::new("set priority, labels or both"));
982        }
983        if let Some(labels) = &self.labels {
984            validate_labels(labels)?;
985        }
986        Ok(())
987    }
988}
989
990/// At most [`MAX_TASK_LABELS`] unique labels of `^[a-z0-9-]{1,32}$`.
991pub fn validate_labels(labels: &[String]) -> Result<(), ValidationError> {
992    if labels.len() > MAX_TASK_LABELS {
993        return Err(ValidationError::new("at most 16 labels"));
994    }
995    let mut seen = std::collections::BTreeSet::new();
996    for label in labels {
997        let ok = (1..=32).contains(&label.len())
998            && label
999                .bytes()
1000                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
1001        if !ok {
1002            return Err(ValidationError::new("a label is 1-32 of [a-z0-9-]"));
1003        }
1004        if !seen.insert(label) {
1005            return Err(ValidationError::new("labels are unique"));
1006        }
1007    }
1008    Ok(())
1009}
1010
1011/// One update as a task view shows it.
1012#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1013pub struct TaskUpdateV1 {
1014    pub by: TaskActorV1,
1015    pub at: UtcTimestamp,
1016    #[serde(default, skip_serializing_if = "Option::is_none")]
1017    pub summary: Option<String>,
1018    #[serde(default, skip_serializing_if = "Option::is_none")]
1019    pub usage: Option<UsageV1>,
1020    /// C0 2.2; absent from older Clouds (progress).
1021    #[serde(default, skip_serializing_if = "Option::is_none")]
1022    pub kind: Option<TaskUpdateKind>,
1023    /// C0 2.2: a verifier's verdict, on `kind: verification`.
1024    #[serde(default, skip_serializing_if = "Option::is_none")]
1025    pub verdict: Option<TaskVerdict>,
1026    /// 3.12.3, on `kind: amendment`: the result's evidence before the
1027    /// amendment, so the history keeps every earlier reference.
1028    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1029    pub amended_from: Vec<EvidenceViewV1>,
1030    /// 3.12.3, on `kind: amendment`: the evidence after it (old → new), or
1031    /// the merge commit of a merge record.
1032    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1033    pub amended_to: Vec<EvidenceViewV1>,
1034}
1035
1036/// Evidence as Cloud shows it: `verified` is set by Cloud (a `receipt`
1037/// whose digest and signature it checked), never by a client.
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1039pub struct EvidenceViewV1 {
1040    pub kind: EvidenceKind,
1041    #[serde(default, skip_serializing_if = "Option::is_none")]
1042    pub reference: Option<String>,
1043    #[serde(default, skip_serializing_if = "Option::is_none")]
1044    pub anchor: Option<CodeAnchorV1>,
1045    pub verified: bool,
1046}
1047
1048/// The submitted result, as a task view shows it.
1049#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1050pub struct TaskResultV1 {
1051    pub by: TaskActorV1,
1052    pub at: UtcTimestamp,
1053    /// The proposal that carries it; 0 when there is none (Cloud v5: the
1054    /// result completed the task directly).
1055    pub proposal: u64,
1056    /// Cloud v5: the log seq of the result's appended knowledge.
1057    #[serde(default, skip_serializing_if = "Option::is_none")]
1058    pub seq: Option<u64>,
1059    #[serde(default, skip_serializing_if = "Option::is_none")]
1060    pub summary: Option<String>,
1061    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1062    pub evidence: Vec<EvidenceViewV1>,
1063    #[serde(default, skip_serializing_if = "Option::is_none")]
1064    pub usage: Option<UsageV1>,
1065    /// 3.12.3: the merge, once recorded on a `done` task.
1066    #[serde(default, skip_serializing_if = "Option::is_none")]
1067    pub merge: Option<TaskMergeV1>,
1068}
1069
1070/// Who decided on a result: a person, or the auto-merge threshold (Personal).
1071#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1072#[serde(tag = "kind", rename_all = "snake_case")]
1073pub enum DecidedByV1 {
1074    Person {
1075        label: String,
1076    },
1077    Threshold,
1078    #[serde(other)]
1079    Unknown,
1080}
1081
1082#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1083#[serde(rename_all = "snake_case")]
1084pub enum TaskDecisionOutcome {
1085    Accepted,
1086    Declined,
1087    #[serde(other)]
1088    Unknown,
1089}
1090
1091/// The decision on a result.
1092#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1093pub struct TaskDecisionV1 {
1094    pub outcome: TaskDecisionOutcome,
1095    pub decided_by: DecidedByV1,
1096    pub at: UtcTimestamp,
1097    #[serde(default, skip_serializing_if = "Option::is_none")]
1098    pub reason: Option<String>,
1099}
1100
1101/// `GET /v1/vaults/{vault_id}/tasks/{number}`.
1102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1103pub struct TaskV1 {
1104    pub schema: String,
1105    pub vault_id: String,
1106    pub number: u64,
1107    pub state: TaskState,
1108    /// Cloud v5 lifecycle; absent when Cloud sends none.
1109    #[serde(default, skip_serializing_if = "Option::is_none")]
1110    pub lifecycle: Option<TaskLifecycle>,
1111    /// The task's title; absent when Cloud sends none (shown as untitled).
1112    #[serde(default, skip_serializing_if = "Option::is_none")]
1113    pub title: Option<String>,
1114    #[serde(default, skip_serializing_if = "Option::is_none")]
1115    pub goal: Option<String>,
1116    #[serde(default, skip_serializing_if = "Option::is_none")]
1117    pub acceptance: Option<String>,
1118    #[serde(default, skip_serializing_if = "Option::is_none")]
1119    pub role: Option<String>,
1120    pub origin: TaskOriginV1,
1121    pub created_by: TaskActorV1,
1122    pub created_at: UtcTimestamp,
1123    /// The person who approved a proposed task.
1124    #[serde(default, skip_serializing_if = "Option::is_none")]
1125    pub approved_by: Option<TaskActorV1>,
1126    #[serde(default, skip_serializing_if = "Option::is_none")]
1127    pub claim: Option<TaskClaimV1>,
1128    /// Newest last, at most [`MAX_VIEW_UPDATES`].
1129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1130    pub updates: Vec<TaskUpdateV1>,
1131    #[serde(default, skip_serializing_if = "Option::is_none")]
1132    pub result: Option<TaskResultV1>,
1133    #[serde(default, skip_serializing_if = "Option::is_none")]
1134    pub decision: Option<TaskDecisionV1>,
1135    /// C0 2.2: the agent whose `accept` made the task `done`.
1136    #[serde(default, skip_serializing_if = "Option::is_none")]
1137    pub verified_by: Option<TaskActorV1>,
1138    #[serde(default, skip_serializing_if = "Option::is_none")]
1139    pub verified_at: Option<UtcTimestamp>,
1140    /// C0 2.2: the last verdict (accept or reject).
1141    #[serde(default, skip_serializing_if = "Option::is_none")]
1142    pub verification: Option<TaskVerificationV1>,
1143    /// C0 2.2; absent means `normal`.
1144    #[serde(default, skip_serializing_if = "Option::is_none")]
1145    pub priority: Option<TaskPriority>,
1146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1147    pub labels: Vec<String>,
1148    /// C0 2.2: +1 whenever priority or labels change (the `base_version`
1149    /// of [`TaskFieldsRequestV1`]).
1150    #[serde(default, skip_serializing_if = "Option::is_none")]
1151    pub fields_version: Option<u32>,
1152    /// Process v1: the task's process fields (`task-process.schema.json`).
1153    /// Absent on a task that is not a process task.
1154    #[serde(default, skip_serializing_if = "Option::is_none")]
1155    pub process: Option<super::gate::TaskProcessV1>,
1156    /// What G6 needs beyond the process fields, and Cloud's G6 record
1157    /// (model v1 `task.process_gate`).
1158    #[serde(default, skip_serializing_if = "Option::is_none")]
1159    pub process_gate: Option<super::gate::TaskProcessGateV1>,
1160}
1161
1162impl TaskV1 {
1163    pub fn validate(&self) -> Result<(), ValidationError> {
1164        require_schema(&self.schema, TASK_SCHEMA)?;
1165        super::validate_vault_id(&self.vault_id)?;
1166        if self.number == 0 {
1167            return Err(ValidationError::new("task numbers start at 1"));
1168        }
1169        if (self.state == TaskState::Claimed) != self.claim.is_some() {
1170            return Err(ValidationError::new(
1171                "a task carries a claim exactly while it is claimed",
1172            ));
1173        }
1174        if self.updates.len() > MAX_VIEW_UPDATES {
1175            return Err(ValidationError::new("too many updates in a task view"));
1176        }
1177        if let Some(approver) = &self.approved_by
1178            && approver.kind != TaskActorKind::Person
1179        {
1180            return Err(ValidationError::new("only a person approves a task"));
1181        }
1182        if matches!(self.state, TaskState::Submitted | TaskState::Done) && self.result.is_none() {
1183            return Err(ValidationError::new(
1184                "a submitted or done task carries its result",
1185            ));
1186        }
1187        if let Some(process) = &self.process {
1188            process.validate()?;
1189        }
1190        Ok(())
1191    }
1192}
1193
1194/// One task in a listing.
1195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1196pub struct TaskSummaryV1 {
1197    pub number: u64,
1198    pub state: TaskState,
1199    /// Cloud v5 lifecycle (additive; absent from a 1.x Cloud).
1200    #[serde(default, skip_serializing_if = "Option::is_none")]
1201    pub lifecycle: Option<TaskLifecycle>,
1202    #[serde(default, skip_serializing_if = "Option::is_none")]
1203    pub title: Option<String>,
1204    #[serde(default, skip_serializing_if = "Option::is_none")]
1205    pub role: Option<String>,
1206    pub origin: TaskOriginKind,
1207    pub updated_at: UtcTimestamp,
1208    /// Whether this instance holds its claim.
1209    pub mine: bool,
1210    /// C0 2.2; absent means `normal`.
1211    #[serde(default, skip_serializing_if = "Option::is_none")]
1212    pub priority: Option<TaskPriority>,
1213    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1214    pub labels: Vec<String>,
1215    #[serde(default, skip_serializing_if = "Option::is_none")]
1216    pub fields_version: Option<u32>,
1217}
1218
1219/// `GET /v1/vaults/{vault_id}/tasks`.
1220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1221pub struct TaskListV1 {
1222    pub schema: String,
1223    pub vault_id: String,
1224    pub tasks: Vec<TaskSummaryV1>,
1225}
1226
1227impl TaskListV1 {
1228    pub fn validate(&self) -> Result<(), ValidationError> {
1229        require_schema(&self.schema, TASK_LIST_SCHEMA)?;
1230        super::validate_vault_id(&self.vault_id)?;
1231        if self.tasks.len() > MAX_TASKS_PAGE {
1232            return Err(ValidationError::new("too many tasks in one page"));
1233        }
1234        Ok(())
1235    }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240    use super::*;
1241
1242    fn propose() -> TaskProposeRequestV1 {
1243        TaskProposeRequestV1 {
1244            schema: TASK_PROPOSE_SCHEMA.into(),
1245            title: Some("Explain the retry budget".into()),
1246            goal: None,
1247            acceptance: Some("A fact with an anchor on retry.rs".into()),
1248            role: None,
1249            origin: TaskOriginV1 {
1250                kind: TaskOriginKind::Agent,
1251                facts: Vec::new(),
1252                message: None,
1253            },
1254            session_ref: "s-1".into(),
1255            signed_at: None,
1256            task_signature: None,
1257        }
1258    }
1259
1260    /// rc4-67: a person's proposal needs the app's signature and its
1261    /// time; an agent's may carry neither.
1262    #[test]
1263    fn only_a_signed_person_proposal_carries_a_task_signature() {
1264        let signature = "OGzdIhUg_HO7JT0XJssV-pqSkN2WBu6SL6dGN2fuXzs5fZxT-fF0X865cAoJIWCz_9bzCsJpyeewB4hiiDpqAg";
1265        let mut person = propose();
1266        person.origin.kind = TaskOriginKind::Person;
1267        assert!(person.validate().is_err(), "unsigned person proposal");
1268        person.signed_at = Some("2026-11-24T09:30:00Z".into());
1269        person.task_signature = Some(signature.into());
1270        person.validate().unwrap();
1271        person.signed_at = Some("2026-11-24 09:30:00".into());
1272        assert!(person.validate().is_err(), "bad time");
1273        let mut agent = propose();
1274        agent.validate().unwrap();
1275        agent.signed_at = Some("2026-11-24T09:30:00Z".into());
1276        agent.task_signature = Some(signature.into());
1277        assert!(agent.validate().is_err(), "agent with signature");
1278    }
1279
1280    fn claim() -> ClaimRefV1 {
1281        ClaimRefV1 {
1282            lease_id: "lease-1".into(),
1283            fencing_token: 3,
1284        }
1285    }
1286
1287    #[test]
1288    fn an_unknown_task_origin_parses_as_unknown() {
1289        let origin: TaskOriginV1 = serde_json::from_value(serde_json::json!({
1290            "kind": "quarantine_timeout", "facts": ["f-1"],
1291        }))
1292        .unwrap();
1293        assert_eq!(origin.kind, TaskOriginKind::Unknown);
1294    }
1295
1296    /// rc4-67: a person's origin is the bare kind on the wire, the same
1297    /// shape an agent's has, so an older reader parses it unchanged.
1298    #[test]
1299    fn a_person_origin_is_the_bare_kind_on_the_wire() {
1300        let person = TaskOriginV1 {
1301            kind: TaskOriginKind::Person,
1302            facts: Vec::new(),
1303            message: None,
1304        };
1305        let wire = serde_json::to_value(&person).unwrap();
1306        assert_eq!(wire, serde_json::json!({"kind": "person"}));
1307        let back: TaskOriginV1 = serde_json::from_value(wire).unwrap();
1308        assert_eq!(back, person);
1309        assert!(person.validate_from_engine().is_ok());
1310    }
1311
1312    /// rc4-79/rc4-67: `created_by.own` is the Cloud's word that the creator
1313    /// is the asking machine's person; absent (an older Cloud) is unknown.
1314    #[test]
1315    fn an_actor_says_own_only_when_the_cloud_does() {
1316        let said: TaskActorV1 = serde_json::from_value(serde_json::json!({
1317            "kind": "person", "label": "Yves", "mine": false, "own": true,
1318        }))
1319        .unwrap();
1320        assert_eq!(said.own, Some(true));
1321        let older: TaskActorV1 = serde_json::from_value(serde_json::json!({
1322            "kind": "person", "label": "Yves", "mine": false,
1323        }))
1324        .unwrap();
1325        assert_eq!(older.own, None);
1326        assert!(serde_json::to_value(&older).unwrap().get("own").is_none());
1327    }
1328
1329    #[test]
1330    fn engines_propose_only_agent_person_or_contradiction_tasks() {
1331        assert!(propose().validate().is_ok());
1332        let mut person = propose();
1333        person.origin.kind = TaskOriginKind::Person;
1334        assert!(person.validate().is_err(), "a person's proposal is signed");
1335        person.signed_at = Some("2026-11-24T09:30:00Z".into());
1336        person.task_signature = Some("A".repeat(86));
1337        assert!(
1338            person.validate().is_ok(),
1339            "a person's proposal via LeanCTX Code"
1340        );
1341        person.origin.facts = vec!["f-1".into()];
1342        assert!(person.validate().is_err(), "a person's task names no facts");
1343        let mut question = propose();
1344        question.origin.kind = TaskOriginKind::Question;
1345        assert!(question.validate().is_err());
1346        let mut contradiction = propose();
1347        contradiction.origin = TaskOriginV1 {
1348            kind: TaskOriginKind::Contradiction,
1349            facts: vec!["f-1".into(), "f-1".into()],
1350            message: None,
1351        };
1352        assert!(contradiction.validate().is_err());
1353        contradiction.origin.facts[1] = "f-2".into();
1354        assert!(contradiction.validate().is_ok());
1355    }
1356
1357    #[test]
1358    fn a_result_needs_evidence_that_fits_its_kind() {
1359        let mut result = TaskResultRequestV1 {
1360            schema: TASK_RESULT_SCHEMA.into(),
1361            claim: claim(),
1362            summary: Some("Done".into()),
1363            evidence: Vec::new(),
1364            draft: None,
1365            usage: None,
1366            outcome: None,
1367            gate_record: None,
1368        };
1369        assert!(result.validate().is_err(), "no evidence");
1370        let r = |kind, reference: &str| EvidenceV1 {
1371            kind,
1372            reference: Some(reference.into()),
1373            anchor: None,
1374        };
1375        for (evidence, ok) in [
1376            (r(EvidenceKind::Commit, "9f01cf32a3"), true),
1377            (r(EvidenceKind::Commit, "main"), false),
1378            (r(EvidenceKind::Url, "http://example.com"), false),
1379            (r(EvidenceKind::Receipt, &"a".repeat(64)), true),
1380            (r(EvidenceKind::FileAnchor, "src/retry.rs"), false),
1381        ] {
1382            result.evidence = vec![evidence.clone()];
1383            assert_eq!(result.validate().is_ok(), ok, "{evidence:?}");
1384        }
1385        result.claim.fencing_token = 0;
1386        result.evidence = vec![r(EvidenceKind::Commit, "9f01cf32a3")];
1387        assert!(result.validate().is_err(), "fencing tokens start at 1");
1388    }
1389
1390    #[test]
1391    fn summaries_are_one_line() {
1392        let update = |summary: &str| TaskUpdateRequestV1 {
1393            schema: TASK_UPDATE_SCHEMA.into(),
1394            claim: claim(),
1395            summary: Some(summary.into()),
1396            usage: None,
1397        };
1398        assert!(update("Reproduced the timeout").validate().is_ok());
1399        assert!(update("line one\nline two").validate().is_err());
1400        assert!(
1401            update(&"x".repeat(MAX_SUMMARY_CHARS + 1))
1402                .validate()
1403                .is_err()
1404        );
1405    }
1406
1407    #[test]
1408    fn decided_by_is_a_person_or_the_threshold() {
1409        let person: DecidedByV1 =
1410            serde_json::from_value(serde_json::json!({"kind": "person", "label": "Ada"})).unwrap();
1411        assert_eq!(
1412            person,
1413            DecidedByV1::Person {
1414                label: "Ada".into()
1415            }
1416        );
1417        let threshold: DecidedByV1 =
1418            serde_json::from_value(serde_json::json!({"kind": "threshold"})).unwrap();
1419        assert_eq!(threshold, DecidedByV1::Threshold);
1420    }
1421
1422    fn fixture(name: &str) -> serde_json::Value {
1423        let path = format!("{}/tests/fixtures/cloud/{name}", env!("CARGO_MANIFEST_DIR"));
1424        serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
1425    }
1426
1427    /// Cloud v5: `outcome` is sent only when set (a 1.x Cloud denies the
1428    /// field), and a failed result brings no draft.
1429    #[test]
1430    fn a_failed_result_names_its_outcome_and_brings_no_draft() {
1431        let mut result: TaskResultRequestV1 =
1432            serde_json::from_value(fixture("task_result.request.json")).unwrap();
1433        assert_eq!(result.outcome, None);
1434        assert!(
1435            serde_json::to_value(&result)
1436                .unwrap()
1437                .get("outcome")
1438                .is_none(),
1439            "a completed result sends no outcome"
1440        );
1441        result.outcome = Some(TaskOutcome::Failed);
1442        assert!(result.validate().is_ok());
1443        assert_eq!(serde_json::to_value(&result).unwrap()["outcome"], "failed");
1444        result.draft =
1445            Some(serde_json::from_value(fixture("proposal.import.request.json")).unwrap());
1446        assert_eq!(
1447            result.validate().unwrap_err().to_string(),
1448            "a failed result brings no draft"
1449        );
1450        result.outcome = Some(TaskOutcome::Completed);
1451        assert!(
1452            result.validate().is_ok(),
1453            "a completed result may bring one"
1454        );
1455    }
1456
1457    /// A 1.x view (`submitted`, no `lifecycle`, a proposal) and a v5 view
1458    /// (`failed`, `lifecycle`, `seq` with proposal 0) both parse; unknown
1459    /// lifecycle words stay tolerated.
1460    #[test]
1461    fn task_views_of_both_lines_parse() {
1462        let old: TaskV1 = serde_json::from_value(fixture("task.done.response.json")).unwrap();
1463        assert_eq!(old.lifecycle, None);
1464        assert_eq!(old.result.as_ref().unwrap().seq, None);
1465        assert!(
1466            serde_json::to_value(&old)
1467                .unwrap()
1468                .get("lifecycle")
1469                .is_none()
1470        );
1471
1472        let mut v5 = fixture("task.done.response.json");
1473        v5["state"] = "failed".into();
1474        v5["lifecycle"] = "failed".into();
1475        v5["result"]["proposal"] = 0.into();
1476        v5["result"]["seq"] = 42.into();
1477        let v5: TaskV1 = serde_json::from_value(v5).unwrap();
1478        assert_eq!(v5.state, TaskState::Failed);
1479        assert_eq!(v5.lifecycle, Some(TaskLifecycle::Failed));
1480        let result = v5.result.as_ref().unwrap();
1481        assert_eq!((result.proposal, result.seq), (0, Some(42)));
1482        assert!(v5.validate().is_ok());
1483
1484        let mut list = fixture("task_list.response.json");
1485        list["tasks"][0]["lifecycle"] = "paused_someday".into();
1486        let list: TaskListV1 = serde_json::from_value(list).unwrap();
1487        assert_eq!(list.tasks[0].lifecycle, Some(TaskLifecycle::Unknown));
1488        let state: TaskState = serde_json::from_value("someday".into()).unwrap();
1489        assert_eq!(state, TaskState::Unknown);
1490    }
1491
1492    fn v2_route(name: &str) -> serde_json::Value {
1493        let path = format!(
1494            "{}/tests/fixtures/cloud-v2/routes/{name}.json",
1495            env!("CARGO_MANIFEST_DIR")
1496        );
1497        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1498    }
1499
1500    /// C0 2.2 (E48, E47 fields): the contract's requests validate, its
1501    /// answers parse, and a reject without reason or an empty field change
1502    /// is refused before it is sent.
1503    #[test]
1504    fn the_c0_2_2_task_shapes_hold() {
1505        for name in ["task_verify.request", "task_verify.reject.request"] {
1506            let request: TaskVerifyRequestV1 = serde_json::from_value(v2_route(name)).unwrap();
1507            request.validate().unwrap_or_else(|e| panic!("{name}: {e}"));
1508            assert_eq!(serde_json::to_value(&request).unwrap(), v2_route(name));
1509        }
1510        let mut reject: TaskVerifyRequestV1 =
1511            serde_json::from_value(v2_route("task_verify.reject.request")).unwrap();
1512        reject.reason = None;
1513        assert_eq!(
1514            reject.validate().unwrap_err().to_string(),
1515            "a reject names its reason"
1516        );
1517        for (name, state) in [
1518            ("task_verify.response", TaskState::Done),
1519            ("task_verify.reject.response", TaskState::Open),
1520            ("task_result.submitted.response", TaskState::Submitted),
1521        ] {
1522            let ack: TaskAckV1 = serde_json::from_value(v2_route(name)).unwrap();
1523            assert_eq!(ack.state, state, "{name}");
1524        }
1525        let fields: TaskFieldsRequestV1 =
1526            serde_json::from_value(v2_route("task_fields.request")).unwrap();
1527        fields.validate().unwrap();
1528        assert_eq!(fields.priority, Some(TaskPriority::High));
1529        let empty = TaskFieldsRequestV1 {
1530            labels: None,
1531            priority: None,
1532            ..fields.clone()
1533        };
1534        assert!(empty.validate().is_err());
1535        let bad = TaskFieldsRequestV1 {
1536            labels: Some(vec!["Docs".into()]),
1537            ..fields
1538        };
1539        assert!(bad.validate().is_err());
1540    }
1541}