1use std::collections::BTreeMap;
51#[cfg(feature = "http-server")]
52use std::path::Path;
53
54use ed25519_dalek::Signature;
55use serde::{Deserialize, Serialize};
56use serde_json::{Value, json};
57use sha2::{Digest as _, Sha256};
58
59use super::plan_body::PlanBody;
60use super::v2::ControlKeys;
61#[cfg(feature = "http-server")]
62use lean_ctx::core::agents::{AgentEntry, AgentRegistry, DirectiveStore};
63use lean_ctx::core::agents::{Directive, DirectiveIssue, DirectiveKind, DirectiveState};
64
65#[cfg(feature = "http-server")]
66use super::address::Address;
67#[cfg(feature = "http-server")]
68use crate::vault::{VaultMap, VaultRecord};
69
70pub const PLAN_UPDATES: &str = "plan_updates";
72pub const PLAN_DOMAIN: &str = "leanctx.cloud.plan.v1\n";
75pub const PLAN_SCHEMA: &str = "leanctx.cloud.plan/v1";
76pub const PLAN_STATEMENT_SCHEMA: &str = "leanctx.cloud.plan-statement/v1";
78const MAX_ACK_AGENTS: usize = 64;
80const MAX_SESSIONS: usize = 32;
82#[cfg(any(test, feature = "http-server"))]
84const MAX_PLANS: usize = 200;
85
86fn chars_ok(text: &str, min: usize, max: usize, ok: impl Fn(char) -> bool) -> bool {
87 (min..=max).contains(&text.chars().count()) && text.chars().all(ok)
88}
89
90pub(crate) fn plan_id_ok(id: &str) -> bool {
91 id.strip_prefix("plan_")
92 .is_some_and(|rest| chars_ok(rest, 8, 40, |c| c.is_ascii_alphanumeric()))
93}
94
95pub fn decision_id_ok(id: &str) -> bool {
99 id.len() <= 80
100 && id.strip_prefix("dec-").is_some_and(|rest| {
101 rest.split('-').all(|segment| {
102 !segment.is_empty()
103 && segment
104 .chars()
105 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
106 })
107 })
108}
109
110pub(crate) fn slot_ok(slot: &str) -> bool {
111 slot != ALL_SLOT
112 && chars_ok(slot, 1, 32, |c| {
113 c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'
114 })
115}
116
117pub(crate) fn task_id_ok(id: &str) -> bool {
118 chars_ok(id, 1, 128, |c| {
119 c.is_ascii_alphanumeric() || "._:-".contains(c)
120 })
121}
122
123fn sha_ok(digest: &str) -> bool {
124 digest.strip_prefix("sha256:").is_some_and(|hex| {
125 hex.len() == 64
126 && hex
127 .chars()
128 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
129 })
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct PlanAdvanced {
136 #[serde(default)]
137 t: Option<String>,
138 pub vault: String,
139 pub plan_id: String,
140 pub version: u64,
141}
142
143impl PlanAdvanced {
144 pub fn new(vault: &str, plan_id: &str, version: u64) -> Self {
145 Self {
146 t: None,
147 vault: vault.to_string(),
148 plan_id: plan_id.to_string(),
149 version,
150 }
151 }
152
153 pub fn parse(frame: &Value) -> Option<Self> {
154 serde_json::from_value(frame.clone())
155 .ok()
156 .filter(|e: &Self| e.version >= 1 && plan_id_ok(&e.plan_id))
157 .map(|e| Self { t: None, ..e })
158 }
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
162#[serde(rename_all = "snake_case")]
163pub enum DecisionStatus {
164 Active,
165 Superseded,
166 Revoked,
167}
168
169impl DecisionStatus {
170 pub fn as_str(self) -> &'static str {
171 match self {
172 DecisionStatus::Active => "active",
173 DecisionStatus::Superseded => "superseded",
174 DecisionStatus::Revoked => "revoked",
175 }
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct DecisionChanged {
183 #[serde(default)]
184 t: Option<String>,
185 pub vault: String,
186 pub decision_id: String,
187 pub status: DecisionStatus,
188 #[serde(default)]
189 pub superseded_by: Option<String>,
190}
191
192impl DecisionChanged {
193 pub fn parse(frame: &Value) -> Option<Self> {
194 serde_json::from_value(frame.clone())
195 .ok()
196 .filter(|e: &Self| {
197 decision_id_ok(&e.decision_id)
198 && e.superseded_by.as_deref().is_none_or(decision_id_ok)
199 })
200 .map(|e| Self { t: None, ..e })
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct PlanSignature {
208 pub key_id: String,
209 pub sig: String,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PlanSession {
214 pub slot: String,
215 pub task_id: Option<String>,
216 #[serde(default)]
217 pub worker_id: Option<String>,
218 pub brief_sha256: String,
219 #[serde(default)]
220 pub changed: bool,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225pub struct PlanDoc {
226 pub schema: String,
227 pub plan_id: String,
228 pub vault: String,
229 pub version: u64,
230 #[serde(default)]
231 pub supersedes_version: Option<u64>,
232 pub content_sha256: String,
233 pub issued_by: String,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub published_at: Option<String>,
237 #[serde(default)]
238 pub signature: Option<PlanSignature>,
239 pub body: String,
242 pub sessions: Vec<PlanSession>,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum PlanRefusal {
248 DigestMismatch,
249 SignatureInvalid,
250 OlderThanApplied,
251 DecryptFailed,
254}
255
256impl PlanRefusal {
257 pub fn code(self) -> &'static str {
258 match self {
259 PlanRefusal::DigestMismatch => "digest_mismatch",
260 PlanRefusal::SignatureInvalid => "signature_invalid",
261 PlanRefusal::OlderThanApplied => "older_than_applied",
262 PlanRefusal::DecryptFailed => "decrypt_failed",
263 }
264 }
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
269pub enum Rejected {
270 Refuse {
272 refusal: PlanRefusal,
273 content_sha256: String,
274 },
275 Invalid(String),
277}
278
279fn invalid(what: &str) -> Rejected {
280 Rejected::Invalid(format!("plan document: {what}"))
281}
282
283pub fn vault_key(id: &str) -> String {
285 id.chars()
286 .filter(|c| *c != '-')
287 .map(|c| c.to_ascii_lowercase())
288 .collect()
289}
290
291pub fn verify(
297 raw: &Value,
298 expect: &PlanAdvanced,
299 vault_id: &str,
300 keys: &ControlKeys,
301) -> Result<PlanDoc, Rejected> {
302 let doc: PlanDoc =
303 serde_json::from_value(raw.clone()).map_err(|e| invalid(&format!("shape: {e}")))?;
304 if doc.schema != PLAN_SCHEMA {
305 return Err(invalid("schema"));
306 }
307 if doc.plan_id != expect.plan_id || doc.version != expect.version {
308 return Err(invalid("not the announced plan version"));
309 }
310 let enrolled = vault_key(vault_id);
311 let is_id = enrolled.len() == 32
312 && enrolled
313 .chars()
314 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c));
315 if !is_id || vault_key(&doc.vault) != enrolled {
316 return Err(invalid("not the enrolled vault"));
317 }
318 let shape_ok = plan_id_ok(&doc.plan_id)
319 && doc.version >= 1
320 && sha_ok(&doc.content_sha256)
321 && !doc.issued_by.trim().is_empty()
322 && doc.sessions.len() <= MAX_SESSIONS
323 && doc.sessions.iter().all(|s| {
324 (s.slot == ALL_SLOT || slot_ok(&s.slot))
325 && sha_ok(&s.brief_sha256)
326 && s.worker_id.as_deref().is_none_or(task_id_ok)
327 && s.task_id.as_deref().is_none_or(task_id_ok)
328 });
329 if !shape_ok {
330 return Err(invalid("fields"));
331 }
332 let refuse = |refusal| Rejected::Refuse {
333 refusal,
334 content_sha256: doc.content_sha256.clone(),
335 };
336 let body = super::plan_body::decode_body(&doc.body).map_err(|e| invalid(&e))?;
337 if super::plan_body::sha256_of(&body) != doc.content_sha256 {
338 return Err(refuse(PlanRefusal::DigestMismatch));
339 }
340 let signature = doc
341 .signature
342 .as_ref()
343 .ok_or_else(|| refuse(PlanRefusal::SignatureInvalid))?;
344 let key = keys
345 .get(&signature.key_id)
346 .ok_or_else(|| refuse(PlanRefusal::SignatureInvalid))?;
347 let mut sig = [0u8; 64];
348 hex::decode_to_slice(&signature.sig, &mut sig)
349 .map_err(|_| refuse(PlanRefusal::SignatureInvalid))?;
350 let input = lean_ctx_protocol::cloud::signing_input_without_signature(
351 PLAN_DOMAIN,
352 &plan_statement(&doc, &signature.key_id),
353 )
354 .map_err(|_| invalid("not signable"))?;
355 key.verify_strict(&input, &Signature::from_bytes(&sig))
356 .map_err(|_| refuse(PlanRefusal::SignatureInvalid))?;
357 let opened = PlanBody::parse(&body).map_err(|e| invalid(&e))?;
360 let routed_ok = doc.sessions.iter().all(|s| {
364 s.slot == ALL_SLOT
365 || opened
366 .session(&s.slot)
367 .is_some_and(|b| super::plan_body::sha256_of(b.brief.as_bytes()) == s.brief_sha256)
368 });
369 if !routed_ok {
370 return Err(refuse(PlanRefusal::DigestMismatch));
371 }
372 Ok(doc)
373}
374
375impl PlanDoc {
376 pub fn opened(&self) -> Option<PlanBody> {
379 self.open().ok()
380 }
381
382 pub fn open(&self) -> Result<PlanBody, &'static str> {
387 let bytes = super::plan_body::decode_body(&self.body).map_err(|_| "invalid")?;
388 if super::plan_body::sha256_of(&bytes) != self.content_sha256 {
389 return Err(PlanRefusal::DigestMismatch.code());
390 }
391 PlanBody::parse(&bytes).map_err(|_| "invalid")
392 }
393}
394
395pub fn plan_statement(doc: &PlanDoc, key_id: &str) -> Value {
400 json!({
401 "schema": PLAN_STATEMENT_SCHEMA,
402 "vault": doc.vault,
403 "plan_id": doc.plan_id,
404 "version": doc.version,
405 "content_sha256": doc.content_sha256,
406 "issued_by": doc.issued_by,
407 "key_id": key_id,
408 })
409}
410
411pub type PlansSeen = BTreeMap<String, BTreeMap<String, u64>>;
413
414pub fn applied(seen: &PlansSeen, vault: &str, plan_id: &str) -> Option<u64> {
416 seen.get(vault)
417 .and_then(|plans| plans.get(plan_id))
418 .copied()
419}
420
421#[cfg(any(test, feature = "http-server"))]
423fn admit(seen: &mut PlansSeen, vault: &str, plan_id: &str, version: u64) -> bool {
424 let plans = seen.entry(vault.to_string()).or_default();
425 if plans.get(plan_id).is_some_and(|known| *known >= version) {
426 return false;
427 }
428 plans.insert(plan_id.to_string(), version);
429 while plans.len() > MAX_PLANS {
430 let Some(first) = plans.keys().next().cloned() else {
431 break;
432 };
433 plans.remove(&first);
434 }
435 true
436}
437
438fn ack_hint(directive_id: &str) -> String {
439 lean_ctx::core::agents::ack_hint(directive_id)
440}
441
442pub const ALL_SLOT: &str = "all";
446
447pub fn plan_directives(
454 doc: &PlanDoc,
455 vault_id: &str,
456 local: &[(String, Option<String>)],
457) -> Vec<(String, DirectiveIssue)> {
458 let mut out = Vec::new();
459 let Some(body) = doc.opened() else {
460 return out;
461 };
462 let goal_sha256 = super::plan_body::sha256_of(body.goal.as_bytes());
463 for (agent, worker) in local {
464 let session = worker.as_deref().and_then(|w| {
465 doc.sessions
466 .iter()
467 .find(|s| s.worker_id.as_deref() == Some(w))
468 });
469 let brief_sha256 = session
470 .filter(|s| s.slot != ALL_SLOT)
471 .map(|s| s.brief_sha256.clone());
472 let (slot, task_id) = match session {
473 Some(session) => (session.slot.clone(), session.task_id.clone()),
474 None => (ALL_SLOT.to_string(), None),
475 };
476 let directive_id = format!("{}:{}:{slot}", doc.plan_id, doc.version);
477 out.push((
478 agent.clone(),
479 DirectiveIssue {
480 directive_id,
481 kind: DirectiveKind::Plan,
482 subject: doc.plan_id.clone(),
483 version: doc.version,
484 slot: Some(slot),
485 worker_id: session.and_then(|s| s.worker_id.clone()),
486 task_id,
487 vault_id: vault_id.to_string(),
488 digest: doc.content_sha256.clone(),
489 brief_sha256,
490 goal_sha256: Some(goal_sha256.clone()),
491 text: String::new(),
493 },
494 ));
495 }
496 out
497}
498
499pub fn decision_directive_id(known: &[Directive], event: &DecisionChanged) -> String {
506 let prefix = format!("{}:", event.decision_id);
507 let last = known
508 .iter()
509 .filter(|d| d.kind == DirectiveKind::Decision && d.subject == event.decision_id)
510 .filter_map(|d| {
511 let (status, n) = d.directive_id.strip_prefix(&prefix)?.split_once(':')?;
512 Some((n.parse::<u64>().ok()?, status.to_string(), d.digest.clone()))
513 })
514 .max();
515 match last {
516 Some((n, status, successor))
517 if status == event.status.as_str() && successor == decision_successor(event) =>
518 {
519 format!("{prefix}{status}:{n}")
520 }
521 Some((n, _, _)) => format!("{prefix}{}:{}", event.status.as_str(), n + 1),
522 None => format!("{prefix}{}:1", event.status.as_str()),
523 }
524}
525
526fn decision_successor(event: &DecisionChanged) -> String {
529 event.superseded_by.clone().unwrap_or_default()
530}
531
532pub fn decision_directive(
535 event: &DecisionChanged,
536 vault_id: &str,
537 known: &[Directive],
538) -> DirectiveIssue {
539 let directive_id = decision_directive_id(known, event);
540 let id = &event.decision_id;
541 let what = match (event.status, event.superseded_by.as_deref()) {
542 (DecisionStatus::Superseded, Some(by)) => {
543 format!("was superseded by {by}; work that relies on {id} may no longer apply")
544 }
545 (DecisionStatus::Superseded, None) => {
546 format!("was superseded; work that relies on {id} may no longer apply")
547 }
548 (DecisionStatus::Revoked, _) => {
549 format!("was revoked; work that relies on {id} may no longer apply")
550 }
551 (DecisionStatus::Active, _) => format!("is now active; follow {id} from here on"),
552 };
553 let text = format!(
554 "Cloud: team decision {id} {what}. Re-read the project's decisions before you go on. {hint}",
555 hint = ack_hint(&directive_id),
556 );
557 DirectiveIssue {
558 directive_id,
559 kind: DirectiveKind::Decision,
560 subject: event.decision_id.clone(),
561 version: 0,
562 slot: None,
563 worker_id: None,
564 task_id: None,
565 vault_id: vault_id.to_string(),
566 digest: decision_successor(event),
567 brief_sha256: None,
568 goal_sha256: None,
569 text,
570 }
571}
572
573#[cfg(feature = "http-server")]
580pub(crate) fn deliver_decision(
581 registry: &mut AgentRegistry,
582 store: &mut DirectiveStore,
583 map: &VaultMap,
584 event: &DecisionChanged,
585) -> Result<usize, String> {
586 let Some((record, root)) = record_of(map, &event.vault) else {
587 return Ok(0);
588 };
589 let issue = decision_directive(event, &record.vault_id, &store.directives);
590 let agents: Vec<String> = registry
591 .list_active(Some(root))
592 .into_iter()
593 .map(|agent| agent.agent_id.clone())
594 .collect();
595 let mut delivered = 0;
596 let mut errors = Vec::new();
597 for agent in agents {
598 match store.deliver_decision(registry, root, &agent, &issue) {
599 Ok(true) => delivered += 1,
600 Ok(false) => {}
601 Err(error) => errors.push(format!("agent {agent}: {error}")),
602 }
603 }
604 if errors.is_empty() {
605 Ok(delivered)
606 } else {
607 Err(format!(
608 "decision {} reached {delivered} agent(s); {}",
609 event.decision_id,
610 errors.join("; ")
611 ))
612 }
613}
614
615pub fn agent_type(local: &str) -> &'static str {
617 let local = local.to_ascii_lowercase();
618 if local.contains("claude") {
619 "claude"
620 } else if local.contains("codex") {
621 "codex"
622 } else if local.contains("cursor") {
623 "cursor"
624 } else {
625 "other"
626 }
627}
628
629#[derive(Debug, Clone, PartialEq)]
631pub struct AckRequest {
632 pub vault_id: String,
633 pub plan_id: String,
634 pub body: Value,
635 pub key: String,
637 pub covers: Vec<(String, String, DirectiveState)>,
638}
639
640pub fn ack_requests(
644 due: &[&Directive],
645 agent_ref: &dyn Fn(&str) -> String,
646 agent_type_of: &dyn Fn(&str) -> &'static str,
647) -> Vec<AckRequest> {
648 let mut groups: BTreeMap<(&str, &str, u64, &str), Vec<&Directive>> = BTreeMap::new();
649 for d in due.iter().filter(|d| d.kind == DirectiveKind::Plan) {
650 groups
651 .entry((&d.vault_id, &d.subject, d.version, &d.digest))
652 .or_default()
653 .push(d);
654 }
655 let mut out = Vec::new();
656 for ((vault_id, plan_id, version, digest), mut members) in groups {
657 members.sort_by(|a, b| (&a.agent_id, &a.directive_id).cmp(&(&b.agent_id, &b.directive_id)));
658 for chunk in members.chunks(MAX_ACK_AGENTS) {
659 let agents: Vec<Value> = chunk
660 .iter()
661 .filter_map(|d| {
662 Some(json!({
663 "agent_ref": agent_ref(&d.agent_id),
664 "worker_id": d.worker_id,
665 "slot": d.slot,
666 "agent_type": agent_type_of(&d.agent_id),
667 "state": d.state.wire()?,
668 "reason_code": d.reason_code,
669 }))
670 })
671 .collect();
672 let body = json!({
673 "version": version,
674 "content_sha256": digest,
675 "agents": agents,
676 "refused": null,
677 });
678 out.push(AckRequest {
679 vault_id: vault_id.to_string(),
680 plan_id: plan_id.to_string(),
681 key: ack_key(plan_id, version, &body),
682 body,
683 covers: chunk
684 .iter()
685 .map(|d| (d.agent_id.clone(), d.directive_id.clone(), d.state))
686 .collect(),
687 });
688 }
689 }
690 out
691}
692
693pub fn refusal_request(
695 vault_id: &str,
696 plan_id: &str,
697 version: u64,
698 content_sha256: &str,
699 refusal: PlanRefusal,
700 applied_version: Option<u64>,
701) -> AckRequest {
702 let body = json!({
703 "version": version,
704 "content_sha256": content_sha256,
705 "agents": [],
706 "refused": {"reason_code": refusal.code(), "applied_version": applied_version},
707 });
708 AckRequest {
709 vault_id: vault_id.to_string(),
710 plan_id: plan_id.to_string(),
711 key: ack_key(plan_id, version, &body),
712 body,
713 covers: Vec::new(),
714 }
715}
716
717fn ack_key(plan_id: &str, version: u64, body: &Value) -> String {
718 let digest = hex::encode(Sha256::digest(body.to_string().as_bytes()));
719 format!("plan-ack:{plan_id}:{version}:{}", &digest[..32])
720}
721
722pub const PLANS_NOT_READY: &str = "plan updates not available (the Cloud has no signing key yet)";
728
729pub fn frames_taken(ack: &Value) -> bool {
732 super::relay_v2::acks_feature(ack, PLAN_UPDATES)
733}
734
735pub fn plans_not_ready(error: &crate::CloudError) -> bool {
737 matches!(error, crate::CloudError::Server { status: 409, code } if code == crate::error::NOT_READY)
738}
739
740#[cfg(feature = "http-server")]
742#[derive(Debug)]
743pub(crate) enum PlanOutcome {
744 Verified {
746 vault: String,
747 vault_id: String,
748 root: String,
749 doc: Box<PlanDoc>,
750 },
751 Note(String),
753}
754
755#[cfg(feature = "http-server")]
756fn record_of<'a>(map: &'a VaultMap, address: &str) -> Option<(&'a VaultRecord, &'a str)> {
757 let Ok(Address::Vault { workspace, vault }) = Address::parse(Some(address)) else {
758 return None;
759 };
760 let record = map
761 .vaults
762 .values()
763 .find(|r| r.ns == workspace && r.name == vault)?;
764 let root = record.roots.iter().find(|root| Path::new(root).is_dir())?;
765 Some((record, root.as_str()))
766}
767
768#[cfg(feature = "http-server")]
769fn post_ack(root: &str, request: &AckRequest) -> Result<(), String> {
770 let conn = super::leases::connected(Path::new(root))?;
771 let path = format!("/vaults/{}/plans/{}/ack", conn.vault_id, request.plan_id);
772 match conn
773 .session
774 .with_client(|c| c.post_idempotent(&path, &request.body, &request.key))
775 {
776 Ok(_)
779 | Err(crate::CloudError::Conflict { .. } | crate::CloudError::Server { status: 409, .. }) => {
780 Ok(())
781 }
782 Err(error) => Err(format!("plan ack {}: {error}", request.plan_id)),
783 }
784}
785
786#[cfg(feature = "http-server")]
791pub(crate) fn fetch(
792 map: &VaultMap,
793 data_dir: &Path,
794 seen: &PlansSeen,
795 keys: &ControlKeys,
796 events: &[PlanAdvanced],
797) -> Vec<PlanOutcome> {
798 let mut out = Vec::new();
799 for event in events {
800 let applied_version = applied(seen, &event.vault, &event.plan_id);
801 if applied_version == Some(event.version) {
804 continue;
805 }
806 let older = applied_version.is_some_and(|v| v > event.version);
807 let Some((record, root)) = record_of(map, &event.vault) else {
808 continue;
809 };
810 let note = |what: String| {
811 PlanOutcome::Note(format!("{} v{}: {what}", event.plan_id, event.version))
812 };
813 let conn = match super::leases::connected(Path::new(root)) {
814 Ok(conn) => conn,
815 Err(error) => {
816 out.push(note(error));
817 continue;
818 }
819 };
820 let path = format!(
821 "/vaults/{}/plans/{}?version={}",
822 conn.vault_id, event.plan_id, event.version
823 );
824 let raw = match conn.session.with_client(|c| c.get(&path)) {
825 Ok(raw) => raw,
826 Err(error) if plans_not_ready(&error) => {
827 out.push(note(PLANS_NOT_READY.to_string()));
828 continue;
829 }
830 Err(error) => {
831 out.push(note(error.to_string()));
832 continue;
833 }
834 };
835 match verify(&raw, event, &conn.vault_id, keys) {
836 Ok(doc) if older => {
837 let request = refusal_request(
838 &record.vault_id,
839 &event.plan_id,
840 event.version,
841 &doc.content_sha256,
842 PlanRefusal::OlderThanApplied,
843 applied_version,
844 );
845 let sent = post_ack(root, &request).err().map(|e| format!("; {e}"));
846 out.push(note(format!(
847 "refused ({}){}",
848 PlanRefusal::OlderThanApplied.code(),
849 sent.unwrap_or_default()
850 )));
851 }
852 Ok(doc) => {
853 let dir = data_dir.join("plans");
854 let saved = std::fs::create_dir_all(&dir)
855 .map_err(|e| e.to_string())
856 .and_then(|()| {
857 lean_ctx::config_io::write_atomic(
858 &dir.join(format!("{}.json", doc.plan_id)),
859 &raw.to_string(),
860 )
861 });
862 if let Err(error) = saved {
863 out.push(note(format!("keep: {error}")));
864 }
865 out.push(PlanOutcome::Verified {
866 vault: event.vault.clone(),
867 vault_id: record.vault_id.clone(),
868 root: root.to_string(),
869 doc: Box::new(doc),
870 });
871 }
872 Err(Rejected::Refuse {
873 refusal,
874 content_sha256,
875 }) => {
876 let request = refusal_request(
877 &record.vault_id,
878 &event.plan_id,
879 event.version,
880 &content_sha256,
881 refusal,
882 applied_version,
883 );
884 let sent = post_ack(root, &request).err().map(|e| format!("; {e}"));
885 out.push(note(format!(
886 "refused ({}){}",
887 refusal.code(),
888 sent.unwrap_or_default()
889 )));
890 }
891 Err(Rejected::Invalid(why)) => out.push(note(why)),
892 }
893 }
894 out
895}
896
897#[cfg(feature = "http-server")]
900pub(crate) fn catch_up(
901 map: &VaultMap,
902 subscribed: &[String],
903 seen: &PlansSeen,
904) -> (Vec<PlanAdvanced>, Vec<String>) {
905 let (mut events, mut errors) = (Vec::new(), Vec::new());
906 for record in map.vaults.values() {
907 let vault = super::relay_v2::address_of(record);
908 if !subscribed.contains(&vault) {
909 continue;
910 }
911 let Some(root) = record.roots.iter().find(|root| Path::new(root).is_dir()) else {
912 continue;
913 };
914 let listed = super::leases::connected(Path::new(root)).and_then(|conn| {
915 let path = format!("/vaults/{}/plans?state=active", conn.vault_id);
916 conn.session.with_client(|c| c.get(&path)).map_err(|e| {
917 if plans_not_ready(&e) {
918 PLANS_NOT_READY.to_string()
919 } else {
920 e.to_string()
921 }
922 })
923 });
924 let listed = match listed {
925 Ok(listed) => listed,
926 Err(error) => {
927 errors.push(format!("{vault}: {error}"));
928 continue;
929 }
930 };
931 events.extend(active_newer(&listed, &vault, seen));
932 }
933 (events, errors)
934}
935
936pub fn active_newer(listed: &Value, vault: &str, seen: &PlansSeen) -> Vec<PlanAdvanced> {
939 let mut events: Vec<PlanAdvanced> = listed["items"]
941 .as_array()
942 .or_else(|| listed["plans"].as_array())
943 .into_iter()
944 .flatten()
945 .filter_map(|plan| {
946 let plan_id = plan["plan_id"].as_str()?;
947 let version = plan["version"].as_u64()?;
948 (plan_id_ok(plan_id)
949 && version >= 1
950 && applied(seen, vault, plan_id).is_none_or(|v| v < version))
951 .then(|| PlanAdvanced::new(vault, plan_id, version))
952 })
953 .collect();
954 events.sort_by(|a, b| a.plan_id.cmp(&b.plan_id));
955 events
956}
957
958#[cfg(feature = "http-server")]
963pub(crate) fn apply(
964 registry: &AgentRegistry,
965 store: &mut DirectiveStore,
966 seen: &mut PlansSeen,
967 outcome: (&str, &str, &str, &PlanDoc),
968 worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
969) -> Result<bool, String> {
970 let (vault, vault_id, root, doc) = outcome;
971 if !admit(seen, vault, &doc.plan_id, doc.version) {
972 return Ok(false);
973 }
974 let local: Vec<(String, Option<String>)> = registry
975 .list_active(Some(root))
976 .into_iter()
977 .map(|agent| (agent.agent_id.clone(), worker_of(agent)))
978 .collect();
979 for (agent, issue) in plan_directives(doc, vault_id, &local) {
980 store.issue(root, &agent, &issue)?;
981 }
982 Ok(true)
983}
984
985#[cfg(feature = "http-server")]
989pub(crate) fn report(map: &VaultMap, data_dir: &Path) -> Vec<String> {
990 let store = DirectiveStore::load();
991 let due = store.unreported_plans();
992 if due.is_empty() {
993 return Vec::new();
994 }
995 let Some(key) = crate::receipts::ReceiptKey::load_or_create(data_dir) else {
996 return vec!["plan ack: no local HMAC key".to_string()];
997 };
998 let registry = AgentRegistry::load_or_create();
999 let agent_ref =
1000 |agent: &str| format!("ag-{}", &key.mac_hex("leanctx.plan-ack.agent", agent)[..32]);
1001 let agent_type_of = |agent: &str| {
1002 registry
1003 .agents
1004 .iter()
1005 .find(|a| a.agent_id == agent)
1006 .map_or("other", |a| agent_type(&a.agent_type))
1007 };
1008 let mut errors = Vec::new();
1009 let mut done = Vec::new();
1010 for request in ack_requests(&due, &agent_ref, &agent_type_of) {
1011 let Some(root) = map
1012 .vaults
1013 .values()
1014 .find(|r| r.vault_id == request.vault_id)
1015 .and_then(|r| r.roots.iter().find(|root| Path::new(root).is_dir()))
1016 else {
1017 continue;
1018 };
1019 match post_ack(root, &request) {
1020 Ok(()) => done.extend(request.covers),
1021 Err(error) => errors.push(error),
1022 }
1023 }
1024 if !done.is_empty()
1025 && let Err(error) = DirectiveStore::mutate(|_, store| {
1026 store.mark_reported(&done);
1027 Ok(())
1028 })
1029 {
1030 errors.push(format!("plan ack record: {error}"));
1031 }
1032 errors
1033}
1034
1035#[cfg(test)]
1036#[path = "plan_events_tests.rs"]
1037mod tests;