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