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::state::CloudStore;
27use crate::untrusted::{UntrustedKind, wrap};
28use crate::vault::VaultMap;
29
30pub const SENDER: &str = "local-tasks";
32
33pub fn linked(root: &Path) -> Result<bool, String> {
38 let unavailable = |e: &dyn std::fmt::Display| {
39 format!("the LeanCTX Cloud link of this project cannot be read: {e}")
40 };
41 let store = CloudStore::open().map_err(|e| unavailable(&e))?;
42 let path = store
43 .data_dir()
44 .join(lean_ctx::core::vault_map::VAULTS_FILE);
45 let map: VaultMap = match std::fs::read(&path) {
46 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
47 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
48 Err(e) => return Err(unavailable(&e)),
49 };
50 Ok(map.for_root(&root.to_string_lossy()).is_some())
51}
52
53pub fn store_dir(root: &Path) -> Result<PathBuf, TaskError> {
55 let hash = lean_ctx::core::project_hash::hash_project_root(&root.to_string_lossy());
56 lean_ctx::core::data_dir::lean_ctx_data_dir()
57 .map(|dir| dir.join("tasks").join(hash))
58 .map_err(TaskError::Store)
59}
60
61fn store(root: &Path) -> Result<Store, TaskError> {
62 store_dir(root).map(Store::new)
63}
64
65pub fn board(root: &Path) -> Result<Board, TaskError> {
68 let (board, _) =
69 store(root)?.read_announced(UtcDateTime::now(), |changes| announce(root, changes))?;
70 Ok(board)
71}
72
73pub fn write<T>(
76 root: &Path,
77 change: impl FnOnce(&mut Board, lean_ctx_time::UtcDateTime) -> Result<T, TaskError>,
78) -> Result<T, TaskError> {
79 let now = UtcDateTime::now();
80 let (out, _) = store(root)?.write_announced(
81 now,
82 |board| change(board, now),
83 |changes| announce(root, changes),
84 )?;
85 Ok(out)
86}
87
88pub fn list(root: &Path) -> Result<Vec<LocalTask>, String> {
91 board(root)
92 .map(|board| board.tasks.into_values().collect())
93 .map_err(|e| e.to_string())
94}
95
96pub fn mark_shared(root: &Path, number: u64, vault: &str, vault_number: u64) -> Result<(), String> {
99 write(root, |board, now| {
100 board.mark_shared(number, &Actor::person("person"), vault, vault_number, now)
101 })
102 .map(|_| ())
103 .map_err(|e| e.to_string())
104}
105
106pub fn evidence(root: &Path, inputs: Vec<EvidenceInput>) -> Result<Vec<EvidenceV1>, TaskError> {
109 inputs
110 .into_iter()
111 .map(|input| {
112 input
113 .into_evidence(root)
114 .map_err(|e| TaskError::Invalid(e.to_string()))
115 })
116 .collect()
117}
118
119pub fn notices(change: &Change, local: &[String]) -> Vec<(Option<String>, String)> {
122 let n = change.number;
123 let show = format!("ctx_tasks action=show number={n}");
124 let text = match change.event {
125 TaskEvent::Proposed => format!(
126 "Local task #{n} was proposed: read it with {show}, then action=accept or action=decline."
127 ),
128 TaskEvent::Accepted => {
129 format!("Local task #{n} is open: read it with {show}, claim it with action=claim.")
130 }
131 TaskEvent::Released => format!(
132 "Local task #{n} is open again (its claim ended): read it with {show}, claim it with action=claim."
133 ),
134 TaskEvent::Rejected => format!(
135 "Local task #{n} is open again (a check rejected its result): read it with {show}, claim it with action=claim."
136 ),
137 TaskEvent::Submitted => {
138 let text = format!(
139 "Local task #{n} has a result to check: read it with {show}, then action=verify verdict=accept|reject (another agent than the one that did the work)."
140 );
141 let worker = change.worker.as_deref().unwrap_or_default();
142 if !local.iter().any(|agent| agent == worker) {
143 return vec![(None, text)];
144 }
145 return local
146 .iter()
147 .filter(|agent| agent.as_str() != worker)
148 .map(|agent| (Some(agent.clone()), text.clone()))
149 .collect();
150 }
151 TaskEvent::Declined => format!("Local task #{n} was declined."),
152 TaskEvent::Claimed => format!("Local task #{n} was claimed."),
153 TaskEvent::Updated => format!("Local task #{n} has a progress update."),
154 TaskEvent::Failed => format!("Local task #{n} ended as failed."),
155 TaskEvent::Verified => format!("Local task #{n} is done: its result was accepted."),
156 TaskEvent::Stopped => format!("Local task #{n} was stopped."),
157 TaskEvent::Amended => format!(
158 "Local task #{n}: its result was amended or its merge recorded (the history keeps old and new): read it with {show}."
159 ),
160 TaskEvent::Shared | TaskEvent::Fields => return Vec::new(),
161 };
162 vec![(None, text)]
163}
164
165pub fn announce(root: &Path, changes: &[Change]) -> bool {
172 if changes
173 .iter()
174 .all(|c| matches!(c.event, TaskEvent::Shared | TaskEvent::Fields))
175 {
176 return true;
177 }
178 let root = root.to_string_lossy().into_owned();
179 let posted = AgentRegistry::mutate_locked(|registry| post_notices(registry, &root, changes));
180 if let Err(error) = &posted {
181 tracing::warn!("local tasks: bus notice not posted yet (next access retries): {error}");
182 }
183 posted.is_ok()
184}
185
186pub fn post_notices(registry: &mut AgentRegistry, root: &str, changes: &[Change]) {
188 let local: Vec<String> = registry
189 .list_active(Some(root))
190 .into_iter()
191 .map(|a| a.agent_id.clone())
192 .collect();
193 for change in changes {
194 let key = format!(
195 "task:{}:{}:{}",
196 change.number,
197 change.event.as_str(),
198 change.seq
199 );
200 for (i, (to, text)) in notices(change, &local).into_iter().enumerate() {
201 if let Err(error) = registry.post_message_keyed(
202 Some(root),
203 SENDER,
204 to.as_deref(),
205 "status",
206 &text,
207 PrivacyLevel::Team,
208 MessagePriority::Normal,
209 None,
210 Some(&format!("{key}:{i}")),
211 ) {
212 tracing::warn!("local tasks: notice {key} not posted: {error}");
213 }
214 }
215 }
216}
217
218pub fn for_reader(task: &TaskV1, agent: Option<&str>) -> TaskV1 {
220 let mut task = task.clone();
221 let mine = |actor: &mut lean_ctx_protocol::cloud::tasks::TaskActorV1| {
222 actor.mine = agent.is_some() && actor.agent.as_deref() == agent;
223 };
224 if let Some(claim) = task.claim.as_mut() {
225 mine(&mut claim.holder);
226 }
227 mine(&mut task.created_by);
228 if let Some(result) = task.result.as_mut() {
229 mine(&mut result.by);
230 }
231 task
232}
233
234pub fn summary(local: &LocalTask, agent: Option<&str>) -> TaskSummaryV1 {
237 let task = &local.task;
238 TaskSummaryV1 {
239 number: task.number,
240 state: task.state,
241 lifecycle: task.lifecycle,
242 title: task.title.clone(),
243 role: task.role.clone(),
244 origin: task.origin.kind,
245 updated_at: local
246 .transitions
247 .last()
248 .map_or_else(|| task.created_at.clone(), |t| t.at.clone()),
249 mine: agent.is_some()
250 && task
251 .claim
252 .as_ref()
253 .is_some_and(|c| c.holder.agent.as_deref() == agent),
254 priority: task.priority,
255 labels: task.labels.clone(),
256 fields_version: task.fields_version,
257 }
258}
259
260#[derive(Debug, Clone, Default)]
262pub struct LocalFilter {
263 pub state: Option<TaskState>,
264 pub role: Option<String>,
265 pub mine: bool,
267}
268
269pub fn select<'a>(
272 board: &'a Board,
273 filter: &LocalFilter,
274 agent: Option<&str>,
275) -> Vec<&'a LocalTask> {
276 let mut tasks: Vec<&LocalTask> = board
277 .tasks
278 .values()
279 .filter(|local| filter.state.is_none_or(|s| local.task.state == s))
280 .filter(|local| {
281 filter
282 .role
283 .as_deref()
284 .is_none_or(|r| local.task.role.as_deref() == Some(r))
285 })
286 .filter(|local| !filter.mine || summary(local, agent).mine)
287 .collect();
288 tasks.sort_by_key(|local| (super::fields::rank(local.task.priority), local.task.number));
290 tasks
291}
292
293pub fn render_list(tasks: &[&LocalTask], agent: Option<&str>, limit: usize) -> String {
295 if tasks.is_empty() {
296 return "No local tasks match (this project is not linked to a LeanCTX Cloud vault; its tasks stay on this machine).".into();
297 }
298 let mut body = String::new();
299 for local in tasks.iter().take(limit) {
300 let row = summary(local, agent);
301 body.push_str(&format!(
302 "#{} {}{} ({}){}{}{}: {}\n",
303 row.number,
304 super::render::high(row.priority),
305 state_with(row.state, row.lifecycle),
306 origin(row.origin),
307 row.role
308 .as_deref()
309 .map(|role| format!(" role={role}"))
310 .unwrap_or_default(),
311 if row.mine { " mine" } else { "" },
312 super::render::labels(&row.labels),
313 row.title.as_deref().unwrap_or("(untitled)"),
314 ));
315 }
316 let mut out = format!("Local tasks ({}):\n", tasks.len());
317 out.push_str(&wrap(
318 UntrustedKind::TaskBody,
319 "local tasks",
320 body.trim_end(),
321 ));
322 let more = tasks.len().saturating_sub(limit);
323 if more > 0 {
324 out.push_str(&format!("\n… {more} more (ctx_tasks action=list state=…)"));
325 }
326 out
327}
328
329pub fn render_task(local: &LocalTask, agent: Option<&str>) -> String {
331 let task = for_reader(&local.task, agent);
332 let mut out = format!(
333 "Local task #{} — {} ({})",
334 task.number,
335 state_with(task.state, task.lifecycle),
336 origin(task.origin.kind)
337 );
338 if let Some(role) = task
339 .role
340 .as_deref()
341 .filter(|role| lean_ctx_protocol::cloud::tasks::validate_role(role).is_ok())
342 {
343 out.push_str(&format!(" role={role}"));
344 }
345 if let Some(claim) = &task.claim {
346 out.push_str(&format!(
347 "\nClaimed until {}{}.",
348 claim.until.as_str(),
349 if claim.holder.mine { " (by you)" } else { "" }
350 ));
351 }
352 let source = format!("local task #{}", task.number);
353 let mut body = String::new();
354 if let Some(title) = &task.title {
355 body.push_str(&format!("Title: {title}\n"));
356 }
357 if let Some(goal) = &task.goal {
358 body.push_str(&format!("Goal: {goal}\n"));
359 }
360 if let Some(acceptance) = &task.acceptance {
361 body.push_str(&format!("Done when: {acceptance}\n"));
362 }
363 body.push_str(&format!(
364 "Priority: {}\n",
365 super::fields::priority_word(task.priority)
366 ));
367 if !task.labels.is_empty() {
368 body.push_str(&format!("Labels: {}\n", task.labels.join(", ")));
369 }
370 body.push_str(&format!("Created by: {}\n", task.created_by.label));
371 out.push('\n');
372 out.push_str(&wrap(UntrustedKind::TaskBody, &source, body.trim_end()));
373 if !task.updates.is_empty() {
374 let mut updates = String::new();
375 for update in &task.updates {
376 updates.push_str(&format!(
377 "{} {}: {}\n",
378 update.at.as_str(),
379 update.by.label,
380 update.summary.as_deref().unwrap_or("(no summary)")
381 ));
382 }
383 out.push_str("\nUpdates:\n");
384 out.push_str(&wrap(
385 UntrustedKind::TaskUpdate,
386 &source,
387 updates.trim_end(),
388 ));
389 }
390 if let Some(result) = &task.result {
391 out.push_str(&format!(
392 "\nResult by {} ({} evidence){}",
393 result.by.label,
394 result.evidence.len(),
395 if result.by.mine {
396 ", yours: another agent or a person checks it"
397 } else {
398 ""
399 }
400 ));
401 }
402 if !local.transitions.is_empty() {
403 let mut history = String::new();
404 for t in &local.transitions {
405 history.push_str(&format!(
406 "{} {} by {}{}\n",
407 t.at.as_str(),
408 t.event.as_str(),
409 t.by.label,
410 t.reason
411 .as_deref()
412 .map(|r| format!(": {r}"))
413 .unwrap_or_default()
414 ));
415 }
416 out.push_str("\nHistory:\n");
417 out.push_str(&wrap(
418 UntrustedKind::TaskUpdate,
419 &source,
420 history.trim_end(),
421 ));
422 }
423 out
424}
425
426pub fn render_change(change: &Change) -> String {
428 let n = change.number;
429 match change.event {
430 TaskEvent::Proposed => format!(
431 "Local task #{n} proposed; anyone accepts it (action=accept) before an agent claims it."
432 ),
433 TaskEvent::Accepted => format!("Local task #{n} is open for any agent to claim."),
434 TaskEvent::Declined => format!("Local task #{n} declined."),
435 TaskEvent::Claimed => format!(
436 "Claimed local task #{n}. Report with action=update (renews the claim), finish with action=submit."
437 ),
438 TaskEvent::Updated => format!("Update recorded on local task #{n}."),
439 TaskEvent::Released => format!("Local task #{n} released."),
440 TaskEvent::Submitted => format!(
441 "Result submitted on local task #{n}; another agent or a person checks it before it is done."
442 ),
443 TaskEvent::Failed => format!("Local task #{n} ended as failed with this result."),
444 TaskEvent::Verified => format!("Local task #{n} is done: the result is accepted."),
445 TaskEvent::Rejected => format!("Local task #{n} is open again: the result is rejected."),
446 TaskEvent::Stopped => format!("Local task #{n} stopped."),
447 TaskEvent::Amended => {
448 format!("Result of local task #{n} amended; the history keeps old and new.")
449 }
450 TaskEvent::Shared => format!("Local task #{n} marked as brought into a vault."),
451 TaskEvent::Fields => format!("Local task #{n}: priority and labels set."),
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 fn change(event: TaskEvent, worker: Option<&str>) -> Change {
460 Change {
461 seq: 3,
462 number: 7,
463 event,
464 state: TaskState::Submitted,
465 worker: worker.map(str::to_owned),
466 }
467 }
468
469 #[test]
470 fn an_unreadable_vault_map_is_an_error_not_unlinked() {
471 let _data = lean_ctx::core::data_dir::isolated_data_dir();
472 let root = tempfile::tempdir().expect("project");
473 assert_eq!(linked(root.path()), Ok(false), "no vault map yet");
474 let store = CloudStore::open().expect("cloud store");
475 std::fs::create_dir_all(store.data_dir()).expect("cloud dir");
476 std::fs::write(
477 store
478 .data_dir()
479 .join(lean_ctx::core::vault_map::VAULTS_FILE),
480 b"{not json",
481 )
482 .expect("corrupt map");
483 assert!(linked(root.path()).is_err());
484 }
485
486 #[test]
487 fn a_result_to_check_goes_to_everyone_but_its_worker() {
488 let local = vec!["queen".to_owned(), "w1".to_owned(), "w2".to_owned()];
489 let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("w1")), &local)
490 .into_iter()
491 .map(|(to, _)| to)
492 .collect();
493 assert_eq!(to, [Some("queen".to_owned()), Some("w2".to_owned())]);
494 let to: Vec<_> = notices(&change(TaskEvent::Submitted, Some("gone")), &local)
496 .into_iter()
497 .map(|(to, _)| to)
498 .collect();
499 assert_eq!(to, [None]);
500 assert_eq!(notices(&change(TaskEvent::Proposed, None), &local).len(), 1);
501 assert!(notices(&change(TaskEvent::Shared, None), &local).is_empty());
502 }
503}