Skip to main content

lean_ctx_cloud/tasks/
local.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local tasks (lean-ctx-tasks) for a project that is not linked to a Cloud
3//! vault: where its store lives, which projects use it, the bus notices of
4//! every transition and how an agent reads them.
5//!
6//! - A project linked to a vault keeps using Cloud exactly as before
7//!   ([`linked`]); every other project keeps its tasks on this machine in
8//!   `<data>/tasks/<project hash>/` (keyed like knowledge).
9//! - Every transition posts on the local bus (category `status`, sender
10//!   [`SENDER`], key `task:<n>:<event>:<seq>:<i>`), so the Queen and Cloud
11//!   Desktop react at once. A result to check goes to every agent of the
12//!   project except the one that did the work. A notice names the number
13//!   only, never task text, so nothing in it reads as an instruction.
14
15use std::path::{Path, PathBuf};
16
17use lean_ctx_time::UtcDateTime;
18
19use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
20use lean_ctx::core::agents::AgentRegistry;
21use lean_ctx_protocol::cloud::tasks::{EvidenceV1, TaskState, TaskSummaryV1, TaskV1};
22use lean_ctx_tasks::{Actor, Board, Change, LocalTask, Store, TaskError, TaskEvent};
23
24use super::EvidenceInput;
25use super::render::{origin, state_with};
26use crate::bus::task_events::{Notice, TaskAction, TaskVerb, to_checkers};
27use crate::state::CloudStore;
28use crate::untrusted::{UntrustedKind, wrap};
29use crate::vault::VaultMap;
30
31/// Who posts the notices of local tasks on the bus.
32pub const SENDER: &str = "local-tasks";
33
34/// Whether `root` is linked to a Cloud vault on this machine (its tasks are
35/// Cloud's then). A Cloud state that cannot be read is an error, never
36/// "unlinked": a linked project's writes must not go local silently. Only
37/// a vault map that does not exist yet means no project is linked.
38pub fn linked(root: &Path) -> Result<bool, String> {
39    let unavailable = |e: &dyn std::fmt::Display| {
40        format!("the LeanCTX Cloud link of this project cannot be read: {e}")
41    };
42    let store = CloudStore::open().map_err(|e| unavailable(&e))?;
43    // Another account's vault map goes first (3.12.8 account scope).
44    store.instance().map_err(|e| unavailable(&e))?;
45    let path = store
46        .data_dir()
47        .join(lean_ctx::core::vault_map::VAULTS_FILE);
48    let map: VaultMap = match std::fs::read(&path) {
49        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
50        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
51        Err(e) => return Err(unavailable(&e)),
52    };
53    Ok(map.for_root(&root.to_string_lossy()).is_some())
54}
55
56/// The directory of `root`'s local tasks.
57pub fn store_dir(root: &Path) -> Result<PathBuf, TaskError> {
58    let hash = lean_ctx::core::project_hash::hash_project_root(&root.to_string_lossy());
59    lean_ctx::core::data_dir::lean_ctx_data_dir()
60        .map(|dir| dir.join("tasks").join(hash))
61        .map_err(TaskError::Store)
62}
63
64fn store(root: &Path) -> Result<Store, TaskError> {
65    store_dir(root).map(Store::new)
66}
67
68/// The board of `root` as of now; claims that ran out are given back first,
69/// and every transition the bus has not taken yet is announced.
70pub fn board(root: &Path) -> Result<Board, TaskError> {
71    let (board, _) =
72        store(root)?.read_announced(UtcDateTime::now(), |changes| announce(root, changes))?;
73    Ok(board)
74}
75
76/// Change `root`'s tasks and announce every transition of the write (and
77/// any an earlier failed bus write left behind).
78pub fn write<T>(
79    root: &Path,
80    change: impl FnOnce(&mut Board, lean_ctx_time::UtcDateTime) -> Result<T, TaskError>,
81) -> Result<T, TaskError> {
82    let now = UtcDateTime::now();
83    let (out, _) = store(root)?.write_announced(
84        now,
85        |board| change(board, now),
86        |changes| announce(root, changes),
87    )?;
88    Ok(out)
89}
90
91/// The project's local tasks, by number (LeanCTX · Share brings them into
92/// a vault on link).
93pub fn list(root: &Path) -> Result<Vec<LocalTask>, String> {
94    board(root)
95        .map(|board| board.tasks.into_values().collect())
96        .map_err(|e| e.to_string())
97}
98
99/// Record that local task `number` was brought into `vault` (`ws/vault`)
100/// as its task `vault_number`; a second mark is refused (`already_shared`).
101pub fn mark_shared(root: &Path, number: u64, vault: &str, vault_number: u64) -> Result<(), String> {
102    write(root, |board, now| {
103        board.mark_shared(number, &Actor::person("person"), vault, vault_number, now)
104    })
105    .map(|_| ())
106    .map_err(|e| e.to_string())
107}
108
109/// Evidence as a caller names it, checked as Cloud checks it (a
110/// `file_anchor` is digested in `root` as it is now).
111pub fn evidence(root: &Path, inputs: Vec<EvidenceInput>) -> Result<Vec<EvidenceV1>, TaskError> {
112    inputs
113        .into_iter()
114        .map(|input| {
115            input
116                .into_evidence(root)
117                .map_err(|e| TaskError::Invalid(e.to_string()))
118        })
119        .collect()
120}
121
122/// The posts `change` asks for. `local` are the project's active agents.
123/// The text is plain language for people; what may be done next travels in
124/// the notice's [`TaskAction`] (agents are shown the exact call from it).
125pub fn notices(change: &Change, local: &[String]) -> Vec<Notice> {
126    let n = change.number;
127    let act = |verbs: &[TaskVerb]| Some(TaskAction::new(n, verbs));
128    let claimable = act(&[TaskVerb::Show, TaskVerb::Claim]);
129    let (text, action) = match change.event {
130        TaskEvent::Proposed => (
131            format!("Local task #{n} was proposed and waits to be accepted or declined."),
132            act(&[TaskVerb::Show, TaskVerb::Accept, TaskVerb::Decline]),
133        ),
134        TaskEvent::Accepted => (
135            format!("Local task #{n} is open and can be claimed."),
136            claimable,
137        ),
138        TaskEvent::Released => (
139            format!("Local task #{n} is open again: its claim ended."),
140            claimable,
141        ),
142        TaskEvent::Rejected => (
143            format!("Local task #{n} is open again: a check rejected its result."),
144            claimable,
145        ),
146        TaskEvent::Submitted => {
147            let notice = Notice::new(
148                None,
149                format!("Local task #{n} has a result to check."),
150                act(&[TaskVerb::Show, TaskVerb::Verify]),
151            );
152            let worker = change.worker.as_deref().unwrap_or_default();
153            return to_checkers(notice, worker, local);
154        }
155        TaskEvent::Declined => (format!("Local task #{n} was declined."), None),
156        TaskEvent::Claimed => (format!("Local task #{n} was claimed."), None),
157        TaskEvent::Updated => (format!("Local task #{n} has a progress update."), None),
158        TaskEvent::Failed => (format!("Local task #{n} ended as failed."), None),
159        TaskEvent::Verified => (
160            format!("Local task #{n} is done: its result was accepted."),
161            None,
162        ),
163        TaskEvent::Stopped => (format!("Local task #{n} was stopped."), None),
164        TaskEvent::Amended => (
165            format!(
166                "Local task #{n}: its result was amended or its merge recorded (the history keeps old and new)."
167            ),
168            act(&[TaskVerb::Show]),
169        ),
170        TaskEvent::Shared | TaskEvent::Fields => return Vec::new(),
171    };
172    vec![Notice::new(None, text, action)]
173}
174
175/// Post the notices of `changes` on the project's bus; whether the bus
176/// write went through. A notice that cannot be posted never undoes the
177/// transition (it is journaled already): when the bus write fails (a
178/// contended `registry.lock` past its wait, an unreadable registry) the
179/// store keeps it due and it is posted on the next access (Cloud task #39;
180/// before, it was dropped here with only a warning).
181pub fn announce(root: &Path, changes: &[Change]) -> bool {
182    if changes
183        .iter()
184        .all(|c| matches!(c.event, TaskEvent::Shared | TaskEvent::Fields))
185    {
186        return true;
187    }
188    let root = root.to_string_lossy().into_owned();
189    let posted = AgentRegistry::mutate_locked(|registry| post_notices(registry, &root, changes));
190    if let Err(error) = &posted {
191        tracing::warn!("local tasks: bus notice not posted yet (next access retries): {error}");
192    }
193    posted.is_ok()
194}
195
196/// [`announce`] into `registry` (no lock of its own).
197pub fn post_notices(registry: &mut AgentRegistry, root: &str, changes: &[Change]) {
198    let local: Vec<String> = registry
199        .list_active(Some(root))
200        .into_iter()
201        .map(|a| a.agent_id.clone())
202        .collect();
203    for change in changes {
204        let key = format!(
205            "task:{}:{}:{}",
206            change.number,
207            change.event.as_str(),
208            change.seq
209        );
210        for (i, notice) in notices(change, &local).into_iter().enumerate() {
211            match registry.post_message_keyed(
212                Some(root),
213                SENDER,
214                notice.to.as_deref(),
215                "status",
216                &notice.text,
217                PrivacyLevel::Team,
218                MessagePriority::Normal,
219                None,
220                Some(&format!("{key}:{i}")),
221            ) {
222                Ok(id) => {
223                    if let Some(action) = &notice.action {
224                        action.attach(registry, &id);
225                    }
226                }
227                Err(error) => tracing::warn!("local tasks: notice {key} not posted: {error}"),
228            }
229        }
230    }
231}
232
233/// `task` with `mine` set for the reader `agent`.
234pub fn for_reader(task: &TaskV1, agent: Option<&str>) -> TaskV1 {
235    let mut task = task.clone();
236    let mine = |actor: &mut lean_ctx_protocol::cloud::tasks::TaskActorV1| {
237        actor.mine = agent.is_some() && actor.agent.as_deref() == agent;
238    };
239    if let Some(claim) = task.claim.as_mut() {
240        mine(&mut claim.holder);
241    }
242    mine(&mut task.created_by);
243    if let Some(result) = task.result.as_mut() {
244        mine(&mut result.by);
245    }
246    task
247}
248
249/// A listing row of `task` for the reader `agent` (the newest transition
250/// is its update time).
251pub fn summary(local: &LocalTask, agent: Option<&str>) -> TaskSummaryV1 {
252    let task = &local.task;
253    TaskSummaryV1 {
254        number: task.number,
255        state: task.state,
256        lifecycle: task.lifecycle,
257        title: task.title.clone(),
258        role: task.role.clone(),
259        origin: task.origin.kind,
260        updated_at: local
261            .transitions
262            .last()
263            .map_or_else(|| task.created_at.clone(), |t| t.at.clone()),
264        mine: agent.is_some()
265            && task
266                .claim
267                .as_ref()
268                .is_some_and(|c| c.holder.agent.as_deref() == agent),
269        priority: task.priority,
270        labels: task.labels.clone(),
271        fields_version: task.fields_version,
272    }
273}
274
275/// Which local tasks a listing shows.
276#[derive(Debug, Clone, Default)]
277pub struct LocalFilter {
278    pub state: Option<TaskState>,
279    pub role: Option<String>,
280    /// Only tasks the reader holds.
281    pub mine: bool,
282}
283
284/// The tasks `filter` selects, high priority first, then by number, for the
285/// reader `agent`.
286pub fn select<'a>(
287    board: &'a Board,
288    filter: &LocalFilter,
289    agent: Option<&str>,
290) -> Vec<&'a LocalTask> {
291    let mut tasks: Vec<&LocalTask> = board
292        .tasks
293        .values()
294        .filter(|local| filter.state.is_none_or(|s| local.task.state == s))
295        .filter(|local| {
296            filter
297                .role
298                .as_deref()
299                .is_none_or(|r| local.task.role.as_deref() == Some(r))
300        })
301        .filter(|local| !filter.mine || summary(local, agent).mine)
302        .collect();
303    // The order of work, as a Cloud listing: high first, then by number.
304    tasks.sort_by_key(|local| (super::fields::rank(local.task.priority), local.task.number));
305    tasks
306}
307
308/// The listing as an agent reads it; task text fenced as foreign data.
309pub fn render_list(tasks: &[&LocalTask], agent: Option<&str>, limit: usize) -> String {
310    if tasks.is_empty() {
311        return "No local tasks match (this project is not linked to a LeanCTX Cloud vault; its tasks stay on this machine).".into();
312    }
313    let mut body = String::new();
314    for local in tasks.iter().take(limit) {
315        let row = summary(local, agent);
316        body.push_str(&format!(
317            "#{} {}{} ({}){}{}{}: {}\n",
318            row.number,
319            super::render::high(row.priority),
320            state_with(row.state, row.lifecycle),
321            origin(row.origin),
322            row.role
323                .as_deref()
324                .map(|role| format!(" role={role}"))
325                .unwrap_or_default(),
326            if row.mine { " mine" } else { "" },
327            super::render::labels(&row.labels),
328            row.title.as_deref().unwrap_or("(untitled)"),
329        ));
330    }
331    let mut out = format!("Local tasks ({}):\n", tasks.len());
332    out.push_str(&wrap(
333        UntrustedKind::TaskBody,
334        "local tasks",
335        body.trim_end(),
336    ));
337    let more = tasks.len().saturating_sub(limit);
338    if more > 0 {
339        out.push_str(&format!("\n… {more} more (ctx_tasks action=list state=…)"));
340    }
341    out
342}
343
344/// One local task with its updates, result and transitions.
345pub fn render_task(local: &LocalTask, agent: Option<&str>) -> String {
346    let task = for_reader(&local.task, agent);
347    let mut out = format!(
348        "Local task #{} — {} ({})",
349        task.number,
350        state_with(task.state, task.lifecycle),
351        origin(task.origin.kind)
352    );
353    if let Some(role) = task
354        .role
355        .as_deref()
356        .filter(|role| lean_ctx_protocol::cloud::tasks::validate_role(role).is_ok())
357    {
358        out.push_str(&format!(" role={role}"));
359    }
360    if let Some(claim) = &task.claim {
361        out.push_str(&format!(
362            "\nClaimed until {}{}.",
363            claim.until.as_str(),
364            if claim.holder.mine { " (by you)" } else { "" }
365        ));
366    }
367    let source = format!("local task #{}", task.number);
368    let mut body = String::new();
369    if let Some(title) = &task.title {
370        body.push_str(&format!("Title: {title}\n"));
371    }
372    if let Some(goal) = &task.goal {
373        body.push_str(&format!("Goal: {goal}\n"));
374    }
375    if let Some(acceptance) = &task.acceptance {
376        body.push_str(&format!("Done when: {acceptance}\n"));
377    }
378    body.push_str(&format!(
379        "Priority: {}\n",
380        super::fields::priority_word(task.priority)
381    ));
382    if !task.labels.is_empty() {
383        body.push_str(&format!("Labels: {}\n", task.labels.join(", ")));
384    }
385    body.push_str(&format!("Created by: {}\n", task.created_by.label));
386    out.push('\n');
387    out.push_str(&wrap(UntrustedKind::TaskBody, &source, body.trim_end()));
388    if !task.updates.is_empty() {
389        let mut updates = String::new();
390        for update in &task.updates {
391            updates.push_str(&format!(
392                "{} {}: {}\n",
393                update.at.as_str(),
394                update.by.label,
395                update.summary.as_deref().unwrap_or("(no summary)")
396            ));
397        }
398        out.push_str("\nUpdates:\n");
399        out.push_str(&wrap(
400            UntrustedKind::TaskUpdate,
401            &source,
402            updates.trim_end(),
403        ));
404    }
405    if let Some(result) = &task.result {
406        out.push_str(&format!(
407            "\nResult by {} ({} evidence){}",
408            result.by.label,
409            result.evidence.len(),
410            if result.by.mine {
411                ", yours: another agent or a person checks it"
412            } else {
413                ""
414            }
415        ));
416    }
417    if !local.transitions.is_empty() {
418        let mut history = String::new();
419        for t in &local.transitions {
420            history.push_str(&format!(
421                "{} {} by {}{}\n",
422                t.at.as_str(),
423                t.event.as_str(),
424                t.by.label,
425                t.reason
426                    .as_deref()
427                    .map(|r| format!(": {r}"))
428                    .unwrap_or_default()
429            ));
430        }
431        out.push_str("\nHistory:\n");
432        out.push_str(&wrap(
433            UntrustedKind::TaskUpdate,
434            &source,
435            history.trim_end(),
436        ));
437    }
438    out
439}
440
441/// The answer of a write, in the words of the Cloud answers.
442pub fn render_change(change: &Change) -> String {
443    let n = change.number;
444    match change.event {
445        TaskEvent::Proposed => format!(
446            "Local task #{n} proposed; anyone accepts it (action=accept) before an agent claims it."
447        ),
448        TaskEvent::Accepted => format!("Local task #{n} is open for any agent to claim."),
449        TaskEvent::Declined => format!("Local task #{n} declined."),
450        TaskEvent::Claimed => format!(
451            "Claimed local task #{n}. Report with action=update (renews the claim), finish with action=submit."
452        ),
453        TaskEvent::Updated => format!("Update recorded on local task #{n}."),
454        TaskEvent::Released => format!("Local task #{n} released."),
455        TaskEvent::Submitted => format!(
456            "Result submitted on local task #{n}; another agent or a person checks it before it is done."
457        ),
458        TaskEvent::Failed => format!("Local task #{n} ended as failed with this result."),
459        TaskEvent::Verified => format!("Local task #{n} is done: the result is accepted."),
460        TaskEvent::Rejected => format!("Local task #{n} is open again: the result is rejected."),
461        TaskEvent::Stopped => format!("Local task #{n} stopped."),
462        TaskEvent::Amended => {
463            format!("Result of local task #{n} amended; the history keeps old and new.")
464        }
465        TaskEvent::Shared => format!("Local task #{n} marked as brought into a vault."),
466        TaskEvent::Fields => format!("Local task #{n}: priority and labels set."),
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    fn change(event: TaskEvent, worker: Option<&str>) -> Change {
475        Change {
476            seq: 3,
477            number: 7,
478            event,
479            state: TaskState::Submitted,
480            worker: worker.map(str::to_owned),
481        }
482    }
483
484    #[test]
485    fn an_unreadable_vault_map_is_an_error_not_unlinked() {
486        let _data = lean_ctx::core::data_dir::isolated_data_dir();
487        let root = tempfile::tempdir().expect("project");
488        assert_eq!(linked(root.path()), Ok(false), "no vault map yet");
489        let store = CloudStore::open().expect("cloud store");
490        std::fs::create_dir_all(store.data_dir()).expect("cloud dir");
491        std::fs::write(
492            store
493                .data_dir()
494                .join(lean_ctx::core::vault_map::VAULTS_FILE),
495            b"{not json",
496        )
497        .expect("corrupt map");
498        assert!(linked(root.path()).is_err());
499    }
500
501    #[test]
502    fn a_result_to_check_goes_to_everyone_but_its_worker() {
503        let local = vec!["queen".to_owned(), "w1".to_owned(), "w2".to_owned()];
504        let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("w1")), &local)
505            .into_iter()
506            .map(|notice| notice.to)
507            .collect();
508        assert_eq!(to, [Some("queen".to_owned()), Some("w2".to_owned())]);
509        // A worker not on this bus: everyone may check it.
510        let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("gone")), &local)
511            .into_iter()
512            .map(|notice| notice.to)
513            .collect();
514        assert_eq!(to, [None]);
515        assert_eq!(notices(&change(TaskEvent::Proposed, None), &local).len(), 1);
516        assert!(notices(&change(TaskEvent::Shared, None), &local).is_empty());
517    }
518
519    #[test]
520    fn notices_read_plainly_and_carry_the_call_for_agents() {
521        let local = vec!["w1".to_owned()];
522        let only = |event, worker| {
523            let mut out = notices(&change(event, worker), &local);
524            assert_eq!(out.len(), 1);
525            out.remove(0)
526        };
527        let proposed = only(TaskEvent::Proposed, None);
528        assert_eq!(
529            proposed.text,
530            "Local task #7 was proposed and waits to be accepted or declined."
531        );
532        assert_eq!(
533            proposed.action.unwrap().call(),
534            "ctx_tasks action=show number=7, then action=accept number=7 or action=decline number=7"
535        );
536        let open = only(TaskEvent::Accepted, None);
537        assert_eq!(open.text, "Local task #7 is open and can be claimed.");
538        assert_eq!(
539            open.action.unwrap().call(),
540            "ctx_tasks action=show number=7, then action=claim number=7"
541        );
542        let check = only(TaskEvent::Submitted, Some("gone"));
543        assert_eq!(check.text, "Local task #7 has a result to check.");
544        assert_eq!(
545            check.action.unwrap().actions,
546            [TaskVerb::Show, TaskVerb::Verify]
547        );
548        assert_eq!(only(TaskEvent::Claimed, None).action, None);
549        for event in [
550            TaskEvent::Proposed,
551            TaskEvent::Accepted,
552            TaskEvent::Released,
553            TaskEvent::Rejected,
554            TaskEvent::Submitted,
555            TaskEvent::Amended,
556        ] {
557            for notice in notices(&change(event, Some("gone")), &local) {
558                for banned in ["ctx_tasks", "action=", "LeanCTX Cloud"] {
559                    assert!(!notice.text.contains(banned), "{}", notice.text);
560                }
561            }
562        }
563    }
564
565    #[test]
566    fn a_posted_notice_carries_its_action_on_the_bus() {
567        let _data = lean_ctx::core::data_dir::isolated_data_dir();
568        let _policy = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
569        let dir = tempfile::tempdir().expect("project");
570        let root = dir.path().to_string_lossy().into_owned();
571        let mut registry = AgentRegistry::new();
572        post_notices(&mut registry, &root, &[change(TaskEvent::Proposed, None)]);
573        let entry = registry
574            .scratchpad
575            .iter()
576            .find(|e| e.from_agent == SENDER)
577            .expect("posted");
578        assert_eq!(
579            entry.message,
580            "Local task #7 was proposed and waits to be accepted or declined."
581        );
582        assert_eq!(
583            TaskAction::of(entry),
584            Some(TaskAction::new(
585                7,
586                &[TaskVerb::Show, TaskVerb::Accept, TaskVerb::Decline]
587            ))
588        );
589    }
590}