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;
pub const SENDER: &str = "local-tasks";
pub fn linked(root: &Path) -> Result<bool, String> {
let unavailable =
|e: &dyn std::fmt::Display| format!("the Cloud link of this project cannot be read: {e}");
let store = CloudStore::open().map_err(|e| unavailable(&e))?;
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())
}
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)
}
pub fn board(root: &Path) -> Result<Board, TaskError> {
let (board, _) =
store(root)?.read_announced(UtcDateTime::now(), |changes| announce(root, changes))?;
Ok(board)
}
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)
}
pub fn list(root: &Path) -> Result<Vec<LocalTask>, String> {
board(root)
.map(|board| board.tasks.into_values().collect())
.map_err(|e| e.to_string())
}
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())
}
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()
}
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)]
}
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()
}
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",
¬ice.text,
PrivacyLevel::Team,
MessagePriority::Normal,
None,
Some(&format!("{key}:{i}")),
) {
Ok(id) => {
if let Some(action) = ¬ice.action {
action.attach(registry, &id);
}
}
Err(error) => tracing::warn!("local tasks: notice {key} not posted: {error}"),
}
}
}
}
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
}
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,
}
}
#[derive(Debug, Clone, Default)]
pub struct LocalFilter {
pub state: Option<TaskState>,
pub role: Option<String>,
pub mine: bool,
}
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();
tasks.sort_by_key(|local| (super::fields::rank(local.task.priority), local.task.number));
tasks
}
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 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
}
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
}
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())]);
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]
))
);
}
}