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