1use std::collections::BTreeMap;
19use std::path::Path;
20
21use serde::Serialize;
22use serde_json::Value;
23
24use super::plan_body::PlanBody;
25use super::plan_events::{ALL_SLOT, PlanDoc, vault_key};
26use lean_ctx::core::agents::{Directive, DirectiveKind, DirectiveState, DirectiveStore};
27
28const MAX_PLANS: usize = 256;
30const MAX_PLAN_BYTES: u64 = 1024 * 1024;
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
35pub struct PlanUpdate {
36 pub id: String,
37 pub vault: String,
40 pub version: u64,
41 pub digest: String,
43 pub issued_by: String,
46 pub verified: bool,
50 pub published_at: Option<String>,
51 pub title: Option<String>,
53 pub goal: Option<String>,
54 pub parts: Vec<PlanPart>,
55 pub agents: Vec<PlanAgent>,
56 pub body: Option<PlanBody>,
60 pub body_error: Option<&'static str>,
63 pub releases: Vec<PlanRelease>,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70pub struct PlanRelease {
71 pub version: u64,
72 pub agent_id: String,
73 pub directive_id: String,
74 pub released_at: String,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
80pub struct PlanPart {
81 pub slot: String,
82 pub role: Option<String>,
83 pub task_id: Option<String>,
84 pub worker_id: Option<String>,
85 pub brief: Option<String>,
86 pub folder: Option<String>,
87 pub brief_sha256: String,
88 pub changed: bool,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct PlanAgent {
94 pub agent_id: String,
95 pub plan_id: String,
96 pub version: u64,
99 pub directive_id: String,
100 pub slot: String,
102 pub state: &'static str,
105 pub release_id: Option<String>,
108 pub released_at: Option<String>,
110 pub reason_code: Option<String>,
111 pub reason: Option<String>,
113 pub title: Option<String>,
117 pub goal: Option<String>,
118 pub role: Option<String>,
119 pub brief: Option<String>,
120 pub folder: Option<String>,
121 pub changed: bool,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
130pub struct Offer {
131 pub release_id: Option<String>,
132 pub plan_id: String,
133 pub version: u64,
134 pub slot: String,
135 pub agent_id: String,
136 pub title: Option<String>,
137 pub goal: Option<String>,
138 pub role: Option<String>,
139 pub brief: Option<String>,
140 pub folder: Option<String>,
141 pub changed: bool,
142}
143
144pub fn offers(plans: &[PlanUpdate]) -> Vec<Offer> {
147 plans
148 .iter()
149 .flat_map(|plan| plan.agents.iter())
150 .filter(|a| a.state == "offered")
151 .map(|a| Offer {
152 release_id: a.release_id.clone(),
153 plan_id: a.plan_id.clone(),
154 version: a.version,
155 slot: a.slot.clone(),
156 agent_id: a.agent_id.clone(),
157 title: a.title.clone(),
158 goal: a.goal.clone(),
159 role: a.role.clone(),
160 brief: a.brief.clone(),
161 folder: a.folder.clone(),
162 changed: a.changed,
163 })
164 .collect()
165}
166
167pub fn kept_plans(data_dir: &Path) -> Vec<PlanDoc> {
170 let Ok(entries) = std::fs::read_dir(data_dir.join("plans")) else {
171 return Vec::new();
172 };
173 let mut files: Vec<std::path::PathBuf> = entries
176 .flatten()
177 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
178 .filter(|e| {
179 e.metadata()
180 .is_ok_and(|m| m.is_file() && m.len() <= MAX_PLAN_BYTES)
181 })
182 .map(|e| e.path())
183 .collect();
184 files.sort();
185 let mut docs: Vec<PlanDoc> = files
186 .into_iter()
187 .take(MAX_PLANS)
188 .filter_map(|path| std::fs::read_to_string(path).ok())
189 .filter_map(|text| serde_json::from_str::<Value>(&text).ok())
190 .filter_map(|raw| serde_json::from_value::<PlanDoc>(raw).ok())
191 .collect();
192 docs.sort_by(|a, b| a.plan_id.cmp(&b.plan_id));
193 docs
194}
195
196fn agent_of(d: &Directive, doc: &PlanDoc, body: Option<&PlanBody>) -> Option<PlanAgent> {
197 let slot = d.slot.clone().unwrap_or_else(|| ALL_SLOT.to_string());
198 let part = body.and_then(|b| b.session(&slot));
199 Some(PlanAgent {
200 agent_id: d.agent_id.clone(),
201 plan_id: d.subject.clone(),
202 version: d.version,
203 directive_id: d.directive_id.clone(),
204 state: d.state.local()?,
205 release_id: if d.state == DirectiveState::Offered {
206 d.release_id.clone()
207 } else {
208 None
209 },
210 released_at: d.released_at.clone(),
211 reason_code: d.reason_code.clone(),
212 reason: d.reason.clone(),
213 title: body.map(|b| b.title.clone()),
214 goal: body.map(|b| b.goal.clone()),
215 role: part.map(|p| p.role.clone()),
216 brief: part.map(|p| p.brief.clone()),
217 folder: part.and_then(|p| p.folder.clone()),
218 changed: doc
219 .sessions
220 .iter()
221 .any(|s| s.slot == slot && s.slot != ALL_SLOT && s.changed),
222 slot,
223 })
224}
225
226pub fn updates(
232 docs: &[PlanDoc],
233 store: &DirectiveStore,
234 addresses: &BTreeMap<String, String>,
235 only: Option<&str>,
236 with_text: bool,
237) -> Vec<PlanUpdate> {
238 let addresses: BTreeMap<String, &String> =
239 addresses.iter().map(|(id, a)| (vault_key(id), a)).collect();
240 let only = only.map(vault_key);
241 let mut out = Vec::new();
242 for doc in docs {
243 let key = vault_key(&doc.vault);
244 if only.as_ref().is_some_and(|o| *o != key) {
245 continue;
246 }
247 let (body, body_error) = if with_text {
248 match doc.open() {
249 Ok(body) => (Some(body), None),
250 Err(code) => (None, Some(code)),
251 }
252 } else {
253 (None, None)
254 };
255 let mut agents: Vec<PlanAgent> = store
256 .directives
257 .iter()
258 .filter(|d| {
259 d.kind == DirectiveKind::Plan
260 && d.subject == doc.plan_id
261 && d.version == doc.version
262 && d.digest == doc.content_sha256
263 })
264 .filter_map(|d| agent_of(d, doc, body.as_ref()))
265 .collect();
266 agents.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
267 let mut releases: Vec<PlanRelease> = store
268 .directives
269 .iter()
270 .filter(|d| d.kind == DirectiveKind::Plan && d.subject == doc.plan_id)
271 .filter_map(|d| {
272 Some(PlanRelease {
273 version: d.version,
274 agent_id: d.agent_id.clone(),
275 directive_id: d.directive_id.clone(),
276 released_at: d.released_at.clone()?,
277 })
278 })
279 .collect();
280 releases.sort_by(|a, b| {
281 (&a.released_at, a.version, &a.agent_id).cmp(&(&b.released_at, b.version, &b.agent_id))
282 });
283 out.push(PlanUpdate {
284 id: doc.plan_id.clone(),
285 vault: addresses
286 .get(&key)
287 .map_or_else(|| doc.vault.clone(), |a| (*a).clone()),
288 version: doc.version,
289 digest: doc.content_sha256.clone(),
290 issued_by: doc.issued_by.clone(),
291 verified: super::plan_body::decode_body(&doc.body)
292 .is_ok_and(|bytes| super::plan_body::sha256_of(&bytes) == doc.content_sha256),
293 published_at: doc.published_at.clone(),
294 title: body.as_ref().map(|b| b.title.clone()),
295 goal: body.as_ref().map(|b| b.goal.clone()),
296 parts: doc
297 .sessions
298 .iter()
299 .map(|s| {
300 let part = body.as_ref().and_then(|b| b.session(&s.slot));
301 PlanPart {
302 slot: s.slot.clone(),
303 role: part.map(|p| p.role.clone()),
304 task_id: s.task_id.clone(),
305 worker_id: s.worker_id.clone(),
306 brief: part.map(|p| p.brief.clone()),
307 folder: part.and_then(|p| p.folder.clone()),
308 brief_sha256: s.brief_sha256.clone(),
309 changed: s.changed,
310 }
311 })
312 .collect(),
313 agents,
314 body,
315 body_error,
316 releases,
317 });
318 }
319 out
320}
321
322#[cfg(test)]
323#[path = "plan_view_tests.rs"]
324mod tests;