use std::collections::BTreeMap;
use std::path::Path;
use serde::Serialize;
use serde_json::Value;
use super::plan_body::PlanBody;
use super::plan_events::{ALL_SLOT, PlanDoc, vault_key};
use lean_ctx::core::agents::{Directive, DirectiveKind, DirectiveState, DirectiveStore};
const MAX_PLANS: usize = 256;
const MAX_PLAN_BYTES: u64 = 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlanUpdate {
pub id: String,
pub vault: String,
pub version: u64,
pub digest: String,
pub issued_by: String,
pub verified: bool,
pub published_at: Option<String>,
pub title: Option<String>,
pub goal: Option<String>,
pub parts: Vec<PlanPart>,
pub agents: Vec<PlanAgent>,
pub body: Option<PlanBody>,
pub body_error: Option<&'static str>,
pub releases: Vec<PlanRelease>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlanRelease {
pub version: u64,
pub agent_id: String,
pub directive_id: String,
pub released_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlanPart {
pub slot: String,
pub role: Option<String>,
pub task_id: Option<String>,
pub worker_id: Option<String>,
pub brief: Option<String>,
pub folder: Option<String>,
pub brief_sha256: String,
pub changed: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlanAgent {
pub agent_id: String,
pub plan_id: String,
pub version: u64,
pub directive_id: String,
pub slot: String,
pub state: &'static str,
pub release_id: Option<String>,
pub released_at: Option<String>,
pub reason_code: Option<String>,
pub reason: Option<String>,
pub title: Option<String>,
pub goal: Option<String>,
pub role: Option<String>,
pub brief: Option<String>,
pub folder: Option<String>,
pub changed: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Offer {
pub release_id: Option<String>,
pub plan_id: String,
pub version: u64,
pub slot: String,
pub agent_id: String,
pub title: Option<String>,
pub goal: Option<String>,
pub role: Option<String>,
pub brief: Option<String>,
pub folder: Option<String>,
pub changed: bool,
}
pub fn offers(plans: &[PlanUpdate]) -> Vec<Offer> {
plans
.iter()
.flat_map(|plan| plan.agents.iter())
.filter(|a| a.state == "offered")
.map(|a| Offer {
release_id: a.release_id.clone(),
plan_id: a.plan_id.clone(),
version: a.version,
slot: a.slot.clone(),
agent_id: a.agent_id.clone(),
title: a.title.clone(),
goal: a.goal.clone(),
role: a.role.clone(),
brief: a.brief.clone(),
folder: a.folder.clone(),
changed: a.changed,
})
.collect()
}
pub fn kept_plans(data_dir: &Path) -> Vec<PlanDoc> {
let Ok(entries) = std::fs::read_dir(data_dir.join("plans")) else {
return Vec::new();
};
let mut files: Vec<std::path::PathBuf> = entries
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "json"))
.filter(|e| {
e.metadata()
.is_ok_and(|m| m.is_file() && m.len() <= MAX_PLAN_BYTES)
})
.map(|e| e.path())
.collect();
files.sort();
let mut docs: Vec<PlanDoc> = files
.into_iter()
.take(MAX_PLANS)
.filter_map(|path| std::fs::read_to_string(path).ok())
.filter_map(|text| serde_json::from_str::<Value>(&text).ok())
.filter_map(|raw| serde_json::from_value::<PlanDoc>(raw).ok())
.collect();
docs.sort_by(|a, b| a.plan_id.cmp(&b.plan_id));
docs
}
fn agent_of(d: &Directive, doc: &PlanDoc, body: Option<&PlanBody>) -> Option<PlanAgent> {
let slot = d.slot.clone().unwrap_or_else(|| ALL_SLOT.to_string());
let part = body.and_then(|b| b.session(&slot));
Some(PlanAgent {
agent_id: d.agent_id.clone(),
plan_id: d.subject.clone(),
version: d.version,
directive_id: d.directive_id.clone(),
state: d.state.local()?,
release_id: if d.state == DirectiveState::Offered {
d.release_id.clone()
} else {
None
},
released_at: d.released_at.clone(),
reason_code: d.reason_code.clone(),
reason: d.reason.clone(),
title: body.map(|b| b.title.clone()),
goal: body.map(|b| b.goal.clone()),
role: part.map(|p| p.role.clone()),
brief: part.map(|p| p.brief.clone()),
folder: part.and_then(|p| p.folder.clone()),
changed: doc
.sessions
.iter()
.any(|s| s.slot == slot && s.slot != ALL_SLOT && s.changed),
slot,
})
}
pub fn updates(
docs: &[PlanDoc],
store: &DirectiveStore,
addresses: &BTreeMap<String, String>,
only: Option<&str>,
with_text: bool,
) -> Vec<PlanUpdate> {
let addresses: BTreeMap<String, &String> =
addresses.iter().map(|(id, a)| (vault_key(id), a)).collect();
let only = only.map(vault_key);
let mut out = Vec::new();
for doc in docs {
let key = vault_key(&doc.vault);
if only.as_ref().is_some_and(|o| *o != key) {
continue;
}
let (body, body_error) = if with_text {
match doc.open() {
Ok(body) => (Some(body), None),
Err(code) => (None, Some(code)),
}
} else {
(None, None)
};
let mut agents: Vec<PlanAgent> = store
.directives
.iter()
.filter(|d| {
d.kind == DirectiveKind::Plan
&& d.subject == doc.plan_id
&& d.version == doc.version
&& d.digest == doc.content_sha256
})
.filter_map(|d| agent_of(d, doc, body.as_ref()))
.collect();
agents.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
let mut releases: Vec<PlanRelease> = store
.directives
.iter()
.filter(|d| d.kind == DirectiveKind::Plan && d.subject == doc.plan_id)
.filter_map(|d| {
Some(PlanRelease {
version: d.version,
agent_id: d.agent_id.clone(),
directive_id: d.directive_id.clone(),
released_at: d.released_at.clone()?,
})
})
.collect();
releases.sort_by(|a, b| {
(&a.released_at, a.version, &a.agent_id).cmp(&(&b.released_at, b.version, &b.agent_id))
});
out.push(PlanUpdate {
id: doc.plan_id.clone(),
vault: addresses
.get(&key)
.map_or_else(|| doc.vault.clone(), |a| (*a).clone()),
version: doc.version,
digest: doc.content_sha256.clone(),
issued_by: doc.issued_by.clone(),
verified: super::plan_body::decode_body(&doc.body)
.is_ok_and(|bytes| super::plan_body::sha256_of(&bytes) == doc.content_sha256),
published_at: doc.published_at.clone(),
title: body.as_ref().map(|b| b.title.clone()),
goal: body.as_ref().map(|b| b.goal.clone()),
parts: doc
.sessions
.iter()
.map(|s| {
let part = body.as_ref().and_then(|b| b.session(&s.slot));
PlanPart {
slot: s.slot.clone(),
role: part.map(|p| p.role.clone()),
task_id: s.task_id.clone(),
worker_id: s.worker_id.clone(),
brief: part.map(|p| p.brief.clone()),
folder: part.and_then(|p| p.folder.clone()),
brief_sha256: s.brief_sha256.clone(),
changed: s.changed,
}
})
.collect(),
agents,
body,
body_error,
releases,
});
}
out
}
#[cfg(test)]
#[path = "plan_view_tests.rs"]
mod tests;