Skip to main content

lean_ctx_cloud/bus/
plan_view.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The plan versions this instance applied, with what its agents answered,
3//! for a local reader (kind `cloud.plan.updates`, contract §37.6).
4//!
5//! Built from the verified plan documents the relay kept
6//! (`<cloud data>/plans/<plan_id>.json`) and the agents' directives
7//! (`<agents>/directives.json`). Nothing is sent to Cloud. The text
8//! (`title`, `goal`, a part's `role`, `brief` and `folder`, and the same
9//! per agent) comes from the verified plan body only.
10//!
11//! This is the app's read: it is the only place that shows an offered
12//! directive's release id (`release_id`) and the plan text, which LeanCTX
13//! Code shows the person and passes to `lean-ctx cloud plan release` after
14//! the person confirmed "Send to agents". Every other reader (the local
15//! socket) gets the same document with the text and release ids `null`. No
16//! agent-facing tool or bus path renders this view.
17
18use 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
28/// The most plan documents read from disk.
29const MAX_PLANS: usize = 256;
30/// The largest plan document read from disk.
31const MAX_PLAN_BYTES: u64 = 1024 * 1024;
32
33/// One applied plan version.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
35pub struct PlanUpdate {
36    pub id: String,
37    /// The vault address `#<workspace>/<vault>` when this instance follows
38    /// the vault, else the document's vault id (32 hex).
39    pub vault: String,
40    pub version: u64,
41    /// The body's `content_sha256`.
42    pub digest: String,
43    /// Who published the version (Cloud's `issued_by`, covered by its
44    /// signature).
45    pub issued_by: String,
46    /// Whether the kept body still hashes to `digest`. A document is kept
47    /// only after its digest and Cloud signature checked out (37.5); `false`
48    /// when the stored copy no longer matches (it is then not opened).
49    pub verified: bool,
50    pub published_at: Option<String>,
51    /// The verified body's title; `null` for a reader without text.
52    pub title: Option<String>,
53    pub goal: Option<String>,
54    pub parts: Vec<PlanPart>,
55    pub agents: Vec<PlanAgent>,
56    /// The whole verified `leanctx.plan-body/v1` (title, goal, sessions,
57    /// decisions), for the app's read; `null` for a reader without text or
58    /// when the body does not open.
59    pub body: Option<PlanBody>,
60    /// Why the body does not open (`invalid`, `digest_mismatch`); `null`
61    /// when it opened or the reader gets no text.
62    pub body_error: Option<&'static str>,
63    /// The local audit of every release of this plan (any version still
64    /// on record): which version reached which agent, and when.
65    pub releases: Vec<PlanRelease>,
66}
67
68/// One release of a plan version to one local agent.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70pub struct PlanRelease {
71    pub version: u64,
72    pub agent_id: String,
73    pub directive_id: String,
74    /// RFC 3339 UTC, when `lean-ctx cloud plan release` delivered it.
75    pub released_at: String,
76}
77
78/// One session of the plan.
79#[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/// One local agent's directive for the plan version.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct PlanAgent {
94    pub agent_id: String,
95    pub plan_id: String,
96    /// The plan version this entry answers (the `<version>` of
97    /// `directive_id`); it never counts for another version.
98    pub version: u64,
99    pub directive_id: String,
100    /// The session's slot, or `all` for an agent no session names.
101    pub slot: String,
102    /// `offered` (waiting for "Send to agents"), `delivered`, `acked` or
103    /// `refused`.
104    pub state: &'static str,
105    /// The release id, only while `offered`: the one argument of
106    /// `lean-ctx cloud plan release` (as `release_id` on stdin).
107    pub release_id: Option<String>,
108    /// When the person released it; `null` while offered.
109    pub released_at: Option<String>,
110    pub reason_code: Option<String>,
111    /// The agent's own words (local only, never sent to Cloud).
112    pub reason: Option<String>,
113    /// What this agent gets on release, from the verified body: the plan's
114    /// title and goal, its part's role, brief and folder (`null` for slot
115    /// `all`, which no part names). `null` for a reader without text.
116    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    /// Whether the version changed this agent's part (its session's
122    /// `changed`; `false` for slot `all`).
123    pub changed: bool,
124}
125
126/// One offered directive waiting for "Send to agents": what LeanCTX Code
127/// shows, confirms and passes to `lean-ctx cloud plan release` (§37.6
128/// `offers`). Text and `release_id` are `null` for a reader without them.
129#[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
144/// The offered directives of `plans`, in the plans' order (plan id, then
145/// agent id): one entry per agent and offered version.
146pub 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
167/// The plan documents kept under `data_dir`, sorted by plan id; a file
168/// that does not parse is left out.
169pub 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    // Sorted before the cap: the same files are kept whatever order the
174    // directory lists them in.
175    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
226/// The view of `docs` with the directives of `store`, limited to the
227/// enrolled vault `only` (a vault id) when given. `addresses` names each
228/// followed vault by its id (any case, with or without `-`). `with_text`
229/// fills the plan text from each verified body (the app's read only).
230/// Byte-stable: plans by id, agents by id.
231pub 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;