lean-ctx-cloud 3.12.8

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// SPDX-License-Identifier: Apache-2.0
//! Local tasks (lean-ctx-tasks) for a project that is not linked to a Cloud
//! vault: where its store lives, which projects use it, the bus notices of
//! every transition and how an agent reads them.
//!
//! - A project linked to a vault keeps using Cloud exactly as before
//!   ([`linked`]); every other project keeps its tasks on this machine in
//!   `<data>/tasks/<project hash>/` (keyed like knowledge).
//! - Every transition posts on the local bus (category `status`, sender
//!   [`SENDER`], key `task:<n>:<event>:<seq>:<i>`), so the Queen and Cloud
//!   Desktop react at once. A result to check goes to every agent of the
//!   project except the one that did the work. A notice names the number
//!   only, never task text, so nothing in it reads as an instruction.

use std::path::{Path, PathBuf};

use lean_ctx_time::UtcDateTime;

use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
use lean_ctx::core::agents::AgentRegistry;
use lean_ctx_protocol::cloud::tasks::{EvidenceV1, TaskState, TaskSummaryV1, TaskV1};
use lean_ctx_tasks::{Actor, Board, Change, LocalTask, Store, TaskError, TaskEvent};

use super::EvidenceInput;
use super::render::{origin, state_with};
use crate::bus::task_events::{Notice, TaskAction, TaskVerb, to_checkers};
use crate::state::CloudStore;
use crate::untrusted::{UntrustedKind, wrap};
use crate::vault::VaultMap;

/// Who posts the notices of local tasks on the bus.
pub const SENDER: &str = "local-tasks";

/// Whether `root` is linked to a Cloud vault on this machine (its tasks are
/// Cloud's then). A Cloud state that cannot be read is an error, never
/// "unlinked": a linked project's writes must not go local silently. Only
/// a vault map that does not exist yet means no project is linked.
pub fn linked(root: &Path) -> Result<bool, String> {
    let unavailable = |e: &dyn std::fmt::Display| {
        format!("the LeanCTX Cloud link of this project cannot be read: {e}")
    };
    let store = CloudStore::open().map_err(|e| unavailable(&e))?;
    // Another account's vault map goes first (3.12.8 account scope).
    store.instance().map_err(|e| unavailable(&e))?;
    let path = store
        .data_dir()
        .join(lean_ctx::core::vault_map::VAULTS_FILE);
    let map: VaultMap = match std::fs::read(&path) {
        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(unavailable(&e)),
    };
    Ok(map.for_root(&root.to_string_lossy()).is_some())
}

/// The directory of `root`'s local tasks.
pub fn store_dir(root: &Path) -> Result<PathBuf, TaskError> {
    let hash = lean_ctx::core::project_hash::hash_project_root(&root.to_string_lossy());
    lean_ctx::core::data_dir::lean_ctx_data_dir()
        .map(|dir| dir.join("tasks").join(hash))
        .map_err(TaskError::Store)
}

fn store(root: &Path) -> Result<Store, TaskError> {
    store_dir(root).map(Store::new)
}

/// The board of `root` as of now; claims that ran out are given back first,
/// and every transition the bus has not taken yet is announced.
pub fn board(root: &Path) -> Result<Board, TaskError> {
    let (board, _) =
        store(root)?.read_announced(UtcDateTime::now(), |changes| announce(root, changes))?;
    Ok(board)
}

/// Change `root`'s tasks and announce every transition of the write (and
/// any an earlier failed bus write left behind).
pub fn write<T>(
    root: &Path,
    change: impl FnOnce(&mut Board, lean_ctx_time::UtcDateTime) -> Result<T, TaskError>,
) -> Result<T, TaskError> {
    let now = UtcDateTime::now();
    let (out, _) = store(root)?.write_announced(
        now,
        |board| change(board, now),
        |changes| announce(root, changes),
    )?;
    Ok(out)
}

/// The project's local tasks, by number (LeanCTX · Share brings them into
/// a vault on link).
pub fn list(root: &Path) -> Result<Vec<LocalTask>, String> {
    board(root)
        .map(|board| board.tasks.into_values().collect())
        .map_err(|e| e.to_string())
}

/// Record that local task `number` was brought into `vault` (`ws/vault`)
/// as its task `vault_number`; a second mark is refused (`already_shared`).
pub fn mark_shared(root: &Path, number: u64, vault: &str, vault_number: u64) -> Result<(), String> {
    write(root, |board, now| {
        board.mark_shared(number, &Actor::person("person"), vault, vault_number, now)
    })
    .map(|_| ())
    .map_err(|e| e.to_string())
}

/// Evidence as a caller names it, checked as Cloud checks it (a
/// `file_anchor` is digested in `root` as it is now).
pub fn evidence(root: &Path, inputs: Vec<EvidenceInput>) -> Result<Vec<EvidenceV1>, TaskError> {
    inputs
        .into_iter()
        .map(|input| {
            input
                .into_evidence(root)
                .map_err(|e| TaskError::Invalid(e.to_string()))
        })
        .collect()
}

/// The posts `change` asks for. `local` are the project's active agents.
/// The text is plain language for people; what may be done next travels in
/// the notice's [`TaskAction`] (agents are shown the exact call from it).
pub fn notices(change: &Change, local: &[String]) -> Vec<Notice> {
    let n = change.number;
    let act = |verbs: &[TaskVerb]| Some(TaskAction::new(n, verbs));
    let claimable = act(&[TaskVerb::Show, TaskVerb::Claim]);
    let (text, action) = match change.event {
        TaskEvent::Proposed => (
            format!("Local task #{n} was proposed and waits to be accepted or declined."),
            act(&[TaskVerb::Show, TaskVerb::Accept, TaskVerb::Decline]),
        ),
        TaskEvent::Accepted => (
            format!("Local task #{n} is open and can be claimed."),
            claimable,
        ),
        TaskEvent::Released => (
            format!("Local task #{n} is open again: its claim ended."),
            claimable,
        ),
        TaskEvent::Rejected => (
            format!("Local task #{n} is open again: a check rejected its result."),
            claimable,
        ),
        TaskEvent::Submitted => {
            let notice = Notice::new(
                None,
                format!("Local task #{n} has a result to check."),
                act(&[TaskVerb::Show, TaskVerb::Verify]),
            );
            let worker = change.worker.as_deref().unwrap_or_default();
            return to_checkers(notice, worker, local);
        }
        TaskEvent::Declined => (format!("Local task #{n} was declined."), None),
        TaskEvent::Claimed => (format!("Local task #{n} was claimed."), None),
        TaskEvent::Updated => (format!("Local task #{n} has a progress update."), None),
        TaskEvent::Failed => (format!("Local task #{n} ended as failed."), None),
        TaskEvent::Verified => (
            format!("Local task #{n} is done: its result was accepted."),
            None,
        ),
        TaskEvent::Stopped => (format!("Local task #{n} was stopped."), None),
        TaskEvent::Amended => (
            format!(
                "Local task #{n}: its result was amended or its merge recorded (the history keeps old and new)."
            ),
            act(&[TaskVerb::Show]),
        ),
        TaskEvent::Shared | TaskEvent::Fields => return Vec::new(),
    };
    vec![Notice::new(None, text, action)]
}

/// Post the notices of `changes` on the project's bus; whether the bus
/// write went through. A notice that cannot be posted never undoes the
/// transition (it is journaled already): when the bus write fails (a
/// contended `registry.lock` past its wait, an unreadable registry) the
/// store keeps it due and it is posted on the next access (Cloud task #39;
/// before, it was dropped here with only a warning).
pub fn announce(root: &Path, changes: &[Change]) -> bool {
    if changes
        .iter()
        .all(|c| matches!(c.event, TaskEvent::Shared | TaskEvent::Fields))
    {
        return true;
    }
    let root = root.to_string_lossy().into_owned();
    let posted = AgentRegistry::mutate_locked(|registry| post_notices(registry, &root, changes));
    if let Err(error) = &posted {
        tracing::warn!("local tasks: bus notice not posted yet (next access retries): {error}");
    }
    posted.is_ok()
}

/// [`announce`] into `registry` (no lock of its own).
pub fn post_notices(registry: &mut AgentRegistry, root: &str, changes: &[Change]) {
    let local: Vec<String> = registry
        .list_active(Some(root))
        .into_iter()
        .map(|a| a.agent_id.clone())
        .collect();
    for change in changes {
        let key = format!(
            "task:{}:{}:{}",
            change.number,
            change.event.as_str(),
            change.seq
        );
        for (i, notice) in notices(change, &local).into_iter().enumerate() {
            match registry.post_message_keyed(
                Some(root),
                SENDER,
                notice.to.as_deref(),
                "status",
                &notice.text,
                PrivacyLevel::Team,
                MessagePriority::Normal,
                None,
                Some(&format!("{key}:{i}")),
            ) {
                Ok(id) => {
                    if let Some(action) = &notice.action {
                        action.attach(registry, &id);
                    }
                }
                Err(error) => tracing::warn!("local tasks: notice {key} not posted: {error}"),
            }
        }
    }
}

/// `task` with `mine` set for the reader `agent`.
pub fn for_reader(task: &TaskV1, agent: Option<&str>) -> TaskV1 {
    let mut task = task.clone();
    let mine = |actor: &mut lean_ctx_protocol::cloud::tasks::TaskActorV1| {
        actor.mine = agent.is_some() && actor.agent.as_deref() == agent;
    };
    if let Some(claim) = task.claim.as_mut() {
        mine(&mut claim.holder);
    }
    mine(&mut task.created_by);
    if let Some(result) = task.result.as_mut() {
        mine(&mut result.by);
    }
    task
}

/// A listing row of `task` for the reader `agent` (the newest transition
/// is its update time).
pub fn summary(local: &LocalTask, agent: Option<&str>) -> TaskSummaryV1 {
    let task = &local.task;
    TaskSummaryV1 {
        number: task.number,
        state: task.state,
        lifecycle: task.lifecycle,
        title: task.title.clone(),
        role: task.role.clone(),
        origin: task.origin.kind,
        updated_at: local
            .transitions
            .last()
            .map_or_else(|| task.created_at.clone(), |t| t.at.clone()),
        mine: agent.is_some()
            && task
                .claim
                .as_ref()
                .is_some_and(|c| c.holder.agent.as_deref() == agent),
        priority: task.priority,
        labels: task.labels.clone(),
        fields_version: task.fields_version,
    }
}

/// Which local tasks a listing shows.
#[derive(Debug, Clone, Default)]
pub struct LocalFilter {
    pub state: Option<TaskState>,
    pub role: Option<String>,
    /// Only tasks the reader holds.
    pub mine: bool,
}

/// The tasks `filter` selects, high priority first, then by number, for the
/// reader `agent`.
pub fn select<'a>(
    board: &'a Board,
    filter: &LocalFilter,
    agent: Option<&str>,
) -> Vec<&'a LocalTask> {
    let mut tasks: Vec<&LocalTask> = board
        .tasks
        .values()
        .filter(|local| filter.state.is_none_or(|s| local.task.state == s))
        .filter(|local| {
            filter
                .role
                .as_deref()
                .is_none_or(|r| local.task.role.as_deref() == Some(r))
        })
        .filter(|local| !filter.mine || summary(local, agent).mine)
        .collect();
    // The order of work, as a Cloud listing: high first, then by number.
    tasks.sort_by_key(|local| (super::fields::rank(local.task.priority), local.task.number));
    tasks
}

/// The listing as an agent reads it; task text fenced as foreign data.
pub fn render_list(tasks: &[&LocalTask], agent: Option<&str>, limit: usize) -> String {
    if tasks.is_empty() {
        return "No local tasks match (this project is not linked to a LeanCTX Cloud vault; its tasks stay on this machine).".into();
    }
    let mut body = String::new();
    for local in tasks.iter().take(limit) {
        let row = summary(local, agent);
        body.push_str(&format!(
            "#{} {}{} ({}){}{}{}: {}\n",
            row.number,
            super::render::high(row.priority),
            state_with(row.state, row.lifecycle),
            origin(row.origin),
            row.role
                .as_deref()
                .map(|role| format!(" role={role}"))
                .unwrap_or_default(),
            if row.mine { " mine" } else { "" },
            super::render::labels(&row.labels),
            row.title.as_deref().unwrap_or("(untitled)"),
        ));
    }
    let mut out = format!("Local tasks ({}):\n", tasks.len());
    out.push_str(&wrap(
        UntrustedKind::TaskBody,
        "local tasks",
        body.trim_end(),
    ));
    let more = tasks.len().saturating_sub(limit);
    if more > 0 {
        out.push_str(&format!("\n… {more} more (ctx_tasks action=list state=…)"));
    }
    out
}

/// One local task with its updates, result and transitions.
pub fn render_task(local: &LocalTask, agent: Option<&str>) -> String {
    let task = for_reader(&local.task, agent);
    let mut out = format!(
        "Local task #{} — {} ({})",
        task.number,
        state_with(task.state, task.lifecycle),
        origin(task.origin.kind)
    );
    if let Some(role) = task
        .role
        .as_deref()
        .filter(|role| lean_ctx_protocol::cloud::tasks::validate_role(role).is_ok())
    {
        out.push_str(&format!(" role={role}"));
    }
    if let Some(claim) = &task.claim {
        out.push_str(&format!(
            "\nClaimed until {}{}.",
            claim.until.as_str(),
            if claim.holder.mine { " (by you)" } else { "" }
        ));
    }
    let source = format!("local task #{}", task.number);
    let mut body = String::new();
    if let Some(title) = &task.title {
        body.push_str(&format!("Title: {title}\n"));
    }
    if let Some(goal) = &task.goal {
        body.push_str(&format!("Goal: {goal}\n"));
    }
    if let Some(acceptance) = &task.acceptance {
        body.push_str(&format!("Done when: {acceptance}\n"));
    }
    body.push_str(&format!(
        "Priority: {}\n",
        super::fields::priority_word(task.priority)
    ));
    if !task.labels.is_empty() {
        body.push_str(&format!("Labels: {}\n", task.labels.join(", ")));
    }
    body.push_str(&format!("Created by: {}\n", task.created_by.label));
    out.push('\n');
    out.push_str(&wrap(UntrustedKind::TaskBody, &source, body.trim_end()));
    if !task.updates.is_empty() {
        let mut updates = String::new();
        for update in &task.updates {
            updates.push_str(&format!(
                "{} {}: {}\n",
                update.at.as_str(),
                update.by.label,
                update.summary.as_deref().unwrap_or("(no summary)")
            ));
        }
        out.push_str("\nUpdates:\n");
        out.push_str(&wrap(
            UntrustedKind::TaskUpdate,
            &source,
            updates.trim_end(),
        ));
    }
    if let Some(result) = &task.result {
        out.push_str(&format!(
            "\nResult by {} ({} evidence){}",
            result.by.label,
            result.evidence.len(),
            if result.by.mine {
                ", yours: another agent or a person checks it"
            } else {
                ""
            }
        ));
    }
    if !local.transitions.is_empty() {
        let mut history = String::new();
        for t in &local.transitions {
            history.push_str(&format!(
                "{} {} by {}{}\n",
                t.at.as_str(),
                t.event.as_str(),
                t.by.label,
                t.reason
                    .as_deref()
                    .map(|r| format!(": {r}"))
                    .unwrap_or_default()
            ));
        }
        out.push_str("\nHistory:\n");
        out.push_str(&wrap(
            UntrustedKind::TaskUpdate,
            &source,
            history.trim_end(),
        ));
    }
    out
}

/// The answer of a write, in the words of the Cloud answers.
pub fn render_change(change: &Change) -> String {
    let n = change.number;
    match change.event {
        TaskEvent::Proposed => format!(
            "Local task #{n} proposed; anyone accepts it (action=accept) before an agent claims it."
        ),
        TaskEvent::Accepted => format!("Local task #{n} is open for any agent to claim."),
        TaskEvent::Declined => format!("Local task #{n} declined."),
        TaskEvent::Claimed => format!(
            "Claimed local task #{n}. Report with action=update (renews the claim), finish with action=submit."
        ),
        TaskEvent::Updated => format!("Update recorded on local task #{n}."),
        TaskEvent::Released => format!("Local task #{n} released."),
        TaskEvent::Submitted => format!(
            "Result submitted on local task #{n}; another agent or a person checks it before it is done."
        ),
        TaskEvent::Failed => format!("Local task #{n} ended as failed with this result."),
        TaskEvent::Verified => format!("Local task #{n} is done: the result is accepted."),
        TaskEvent::Rejected => format!("Local task #{n} is open again: the result is rejected."),
        TaskEvent::Stopped => format!("Local task #{n} stopped."),
        TaskEvent::Amended => {
            format!("Result of local task #{n} amended; the history keeps old and new.")
        }
        TaskEvent::Shared => format!("Local task #{n} marked as brought into a vault."),
        TaskEvent::Fields => format!("Local task #{n}: priority and labels set."),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn change(event: TaskEvent, worker: Option<&str>) -> Change {
        Change {
            seq: 3,
            number: 7,
            event,
            state: TaskState::Submitted,
            worker: worker.map(str::to_owned),
        }
    }

    #[test]
    fn an_unreadable_vault_map_is_an_error_not_unlinked() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let root = tempfile::tempdir().expect("project");
        assert_eq!(linked(root.path()), Ok(false), "no vault map yet");
        let store = CloudStore::open().expect("cloud store");
        std::fs::create_dir_all(store.data_dir()).expect("cloud dir");
        std::fs::write(
            store
                .data_dir()
                .join(lean_ctx::core::vault_map::VAULTS_FILE),
            b"{not json",
        )
        .expect("corrupt map");
        assert!(linked(root.path()).is_err());
    }

    #[test]
    fn a_result_to_check_goes_to_everyone_but_its_worker() {
        let local = vec!["queen".to_owned(), "w1".to_owned(), "w2".to_owned()];
        let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("w1")), &local)
            .into_iter()
            .map(|notice| notice.to)
            .collect();
        assert_eq!(to, [Some("queen".to_owned()), Some("w2".to_owned())]);
        // A worker not on this bus: everyone may check it.
        let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("gone")), &local)
            .into_iter()
            .map(|notice| notice.to)
            .collect();
        assert_eq!(to, [None]);
        assert_eq!(notices(&change(TaskEvent::Proposed, None), &local).len(), 1);
        assert!(notices(&change(TaskEvent::Shared, None), &local).is_empty());
    }

    #[test]
    fn notices_read_plainly_and_carry_the_call_for_agents() {
        let local = vec!["w1".to_owned()];
        let only = |event, worker| {
            let mut out = notices(&change(event, worker), &local);
            assert_eq!(out.len(), 1);
            out.remove(0)
        };
        let proposed = only(TaskEvent::Proposed, None);
        assert_eq!(
            proposed.text,
            "Local task #7 was proposed and waits to be accepted or declined."
        );
        assert_eq!(
            proposed.action.unwrap().call(),
            "ctx_tasks action=show number=7, then action=accept number=7 or action=decline number=7"
        );
        let open = only(TaskEvent::Accepted, None);
        assert_eq!(open.text, "Local task #7 is open and can be claimed.");
        assert_eq!(
            open.action.unwrap().call(),
            "ctx_tasks action=show number=7, then action=claim number=7"
        );
        let check = only(TaskEvent::Submitted, Some("gone"));
        assert_eq!(check.text, "Local task #7 has a result to check.");
        assert_eq!(
            check.action.unwrap().actions,
            [TaskVerb::Show, TaskVerb::Verify]
        );
        assert_eq!(only(TaskEvent::Claimed, None).action, None);
        for event in [
            TaskEvent::Proposed,
            TaskEvent::Accepted,
            TaskEvent::Released,
            TaskEvent::Rejected,
            TaskEvent::Submitted,
            TaskEvent::Amended,
        ] {
            for notice in notices(&change(event, Some("gone")), &local) {
                for banned in ["ctx_tasks", "action=", "LeanCTX Cloud"] {
                    assert!(!notice.text.contains(banned), "{}", notice.text);
                }
            }
        }
    }

    #[test]
    fn a_posted_notice_carries_its_action_on_the_bus() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let _policy = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
        let dir = tempfile::tempdir().expect("project");
        let root = dir.path().to_string_lossy().into_owned();
        let mut registry = AgentRegistry::new();
        post_notices(&mut registry, &root, &[change(TaskEvent::Proposed, None)]);
        let entry = registry
            .scratchpad
            .iter()
            .find(|e| e.from_agent == SENDER)
            .expect("posted");
        assert_eq!(
            entry.message,
            "Local task #7 was proposed and waits to be accepted or declined."
        );
        assert_eq!(
            TaskAction::of(entry),
            Some(TaskAction::new(
                7,
                &[TaskVerb::Show, TaskVerb::Accept, TaskVerb::Decline]
            ))
        );
    }
}