Skip to main content

lean_ctx_cloud/tasks/
render.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Tasks as an agent reads them. Every text people or other agents wrote
3//! (titles, goals, criteria, summaries, labels) is fenced as foreign data
4//! ([`crate::untrusted::wrap`], X5); only the numbers, states
5//! and the engine's own words stand outside the fence.
6//! Deterministic for the same answer (#498).
7
8use super::TaskView;
9use crate::untrusted::{UntrustedKind, wrap};
10use lean_ctx_protocol::cloud::tasks::{
11    TaskAckV1, TaskLifecycle, TaskListV1, TaskOriginKind, TaskPriority, TaskResultV1, TaskState,
12};
13
14fn state(state: TaskState) -> &'static str {
15    match state {
16        TaskState::Proposed => "proposed",
17        TaskState::Open => "open",
18        TaskState::Claimed => "claimed",
19        TaskState::Submitted => "submitted",
20        TaskState::Done => "done",
21        TaskState::Rejected => "rejected",
22        TaskState::Cancelled => "cancelled",
23        TaskState::Failed => "failed",
24        TaskState::Unknown => "unknown",
25    }
26}
27
28/// The state word, plus ` running` when a Cloud v5 lifecycle says the
29/// holder reported progress (the one thing `state` does not show). A 1.x
30/// Cloud sends no lifecycle: the state alone, as before.
31pub(super) fn state_with(task_state: TaskState, lifecycle: Option<TaskLifecycle>) -> String {
32    let word = state(task_state);
33    if task_state == TaskState::Claimed && lifecycle == Some(TaskLifecycle::Running) {
34        format!("{word} running")
35    } else {
36        word.to_owned()
37    }
38}
39
40/// What carries a result: a 1.x proposal, or (Cloud v5, proposal 0) the
41/// log seq of its knowledge, or the task alone.
42fn result_line(result: &TaskResultV1) -> String {
43    let carrier = match (result.proposal, result.seq) {
44        (0, Some(seq)) => format!("knowledge at log seq {seq}"),
45        (0, None) => "recorded on the task".to_owned(),
46        (proposal, _) => format!("proposal #{proposal}"),
47    };
48    format!("\nResult: {carrier} ({} evidence)", result.evidence.len())
49}
50
51/// What a result did, from Cloud's answer: `submitted` waits for a second
52/// agent's check, `done` or `failed` ends the task.
53#[must_use]
54pub fn render_result_ack(ack: &TaskAckV1) -> String {
55    let n = ack.number;
56    match ack.state {
57        TaskState::Submitted => {
58            format!("Result submitted on task #{n}; another agent checks it before it is done.")
59        }
60        TaskState::Done => format!("Task #{n} completed with this result."),
61        TaskState::Failed => format!("Task #{n} ended as failed with this result."),
62        other => format!("Result recorded on task #{n} (now {}).", state(other)),
63    }
64}
65
66/// What a verdict did (C0 2.2 E48): `done`, or `open` again.
67#[must_use]
68pub fn render_verify_ack(ack: &TaskAckV1) -> String {
69    let n = ack.number;
70    match ack.state {
71        TaskState::Done => format!("Task #{n} is done: the result is accepted."),
72        TaskState::Open => format!("Task #{n} is open again: the result is rejected."),
73        other => format!("Verdict recorded on task #{n} (now {}).", state(other)),
74    }
75}
76
77pub(super) fn origin(origin: TaskOriginKind) -> &'static str {
78    match origin {
79        TaskOriginKind::Person => "person",
80        TaskOriginKind::Agent => "agent",
81        TaskOriginKind::Contradiction => "contradiction",
82        TaskOriginKind::Question => "question",
83        TaskOriginKind::Unknown => "unknown",
84    }
85}
86
87/// `"high "` before the state of a high-priority task, nothing for normal.
88pub(super) fn high(priority: Option<TaskPriority>) -> &'static str {
89    if priority == Some(TaskPriority::High) {
90        "high "
91    } else {
92        ""
93    }
94}
95
96/// ` [a, b]` for a task's labels, nothing without any.
97pub(super) fn labels(labels: &[String]) -> String {
98    if labels.is_empty() {
99        String::new()
100    } else {
101        format!(" [{}]", labels.join(", "))
102    }
103}
104
105/// The first `limit` tasks of `list`, one line each.
106#[must_use]
107pub fn render_list(list: &TaskListV1, limit: usize) -> String {
108    if list.tasks.is_empty() {
109        return "No LeanCTX Cloud tasks match.".into();
110    }
111    let mut body = String::new();
112    for task in list.tasks.iter().take(limit) {
113        body.push_str(&format!(
114            "#{} {}{} ({}){}{}{}: {}\n",
115            task.number,
116            high(task.priority),
117            state_with(task.state, task.lifecycle),
118            origin(task.origin),
119            task.role
120                .as_deref()
121                .map(|role| format!(" role={role}"))
122                .unwrap_or_default(),
123            if task.mine { " mine" } else { "" },
124            labels(&task.labels),
125            task.title.as_deref().unwrap_or("(untitled)"),
126        ));
127    }
128    let more = list.tasks.len().saturating_sub(limit);
129    let mut out = format!("LeanCTX Cloud tasks ({}):\n", list.tasks.len());
130    out.push_str(&wrap(
131        UntrustedKind::TaskBody,
132        "cloud tasks",
133        body.trim_end(),
134    ));
135    if more > 0 {
136        out.push_str(&format!("\n… {more} more (ctx_tasks action=list)"));
137    }
138    out
139}
140
141/// The line under a partial listing.
142pub const PARTIAL_NOTE: &str = "(partial: LeanCTX Cloud sends at most 100 tasks per answer, so older tasks may be missing; narrow the list with state or role)";
143
144/// [`render_list`] of a listing; a partial one says so under the tasks.
145#[must_use]
146pub fn render_listing(listing: &super::TaskListing, limit: usize) -> String {
147    let out = render_list(&listing.list, limit);
148    if listing.partial {
149        format!("{out}\n{PARTIAL_NOTE}")
150    } else {
151        out
152    }
153}
154
155/// One task with its updates and result.
156#[must_use]
157pub fn render_task(view: &TaskView) -> String {
158    let task = &view.task;
159    let mut out = format!(
160        "LeanCTX Cloud task #{} — {} ({})",
161        task.number,
162        state_with(task.state, task.lifecycle),
163        origin(task.origin.kind)
164    );
165    // Outside the fence only a validated role slug: anything else Cloud
166    // sends there is someone's text and never reaches the header (X5).
167    if let Some(role) = task
168        .role
169        .as_deref()
170        .filter(|role| lean_ctx_protocol::cloud::tasks::validate_role(role).is_ok())
171    {
172        out.push_str(&format!(" role={role}"));
173    }
174    match (&view.held_until, &task.claim) {
175        (Some(until), _) => out.push_str(&format!("\nThis machine holds the claim until {until}.")),
176        (None, Some(claim)) => out.push_str(&format!(
177            "\nClaimed until {}{}.",
178            claim.until.as_str(),
179            if claim.holder.mine {
180                " (by you, elsewhere)"
181            } else {
182                ""
183            }
184        )),
185        (None, None) => {}
186    }
187    let (title, goal, acceptance) = (
188        task.title.as_deref(),
189        task.goal.as_deref(),
190        task.acceptance.as_deref(),
191    );
192    let mut body = String::new();
193    if let Some(title) = title {
194        body.push_str(&format!("Title: {title}\n"));
195    }
196    if let Some(goal) = goal {
197        body.push_str(&format!("Goal: {goal}\n"));
198    }
199    if let Some(acceptance) = acceptance {
200        body.push_str(&format!("Done when: {acceptance}\n"));
201    }
202    body.push_str(&format!(
203        "Priority: {}\n",
204        super::fields::priority_word(task.priority)
205    ));
206    if !task.labels.is_empty() {
207        body.push_str(&format!("Labels: {}\n", task.labels.join(", ")));
208    }
209    body.push_str(&format!("Created by: {}\n", task.created_by.label));
210    let source = format!("cloud task #{}", task.number);
211    out.push('\n');
212    out.push_str(&wrap(UntrustedKind::TaskBody, &source, body.trim_end()));
213    if !task.updates.is_empty() {
214        let mut updates = String::new();
215        for update in &task.updates {
216            updates.push_str(&format!(
217                "{} {}: {}\n",
218                update.at.as_str(),
219                update.by.label,
220                update.summary.as_deref().unwrap_or("(no summary)")
221            ));
222        }
223        out.push_str("\nUpdates:\n");
224        out.push_str(&wrap(
225            UntrustedKind::TaskUpdate,
226            &source,
227            updates.trim_end(),
228        ));
229    }
230    if let Some(result) = &task.result {
231        out.push_str(&result_line(result));
232    }
233    out
234}