1use std::path::PathBuf;
30use std::sync::Mutex;
31use std::time::SystemTime;
32
33use serde::{Deserialize, Serialize};
34use sha2::{Digest as _, Sha256};
35
36use super::AgentRegistry;
37use crate::core::a2a::message::{MessagePriority, PrivacyLevel};
38
39pub const DIRECTIVE_SENDER: &str = "cloud";
41pub const DIRECTIVE_CATEGORY: &str = "directive";
43pub const REFUSE_REASONS: [&str; 5] = [
45 "conflicts_with_decision",
46 "task_finished",
47 "out_of_scope",
48 "unverified_plan",
49 "other",
50];
51const MAX_DIRECTIVES: usize = 500;
53const MAX_REASON_CHARS: usize = 500;
55pub const MAX_GOAL_BYTES: usize = 16_000;
57pub const MAX_BRIEF_BYTES: usize = 32_000;
59
60const ACK_HINT: &str = "Answer with ctx_agent action=ack directive_id={id} verdict=accept, or verdict=refuse reason_code=conflicts_with_decision|task_finished|out_of_scope|unverified_plan|other.";
61
62pub fn ack_hint(directive_id: &str) -> String {
64 ACK_HINT.replace("{id}", directive_id)
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "snake_case")]
70pub enum DirectiveKind {
71 Plan,
72 Decision,
73}
74
75impl DirectiveKind {
76 pub fn as_str(self) -> &'static str {
77 match self {
78 DirectiveKind::Plan => "plan",
79 DirectiveKind::Decision => "decision",
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum DirectiveState {
88 Offered,
91 Pending,
93 Accepted,
94 Refused,
95 Superseded,
97}
98
99impl DirectiveState {
100 pub fn wire(self) -> Option<&'static str> {
103 match self {
104 DirectiveState::Offered | DirectiveState::Superseded => None,
105 DirectiveState::Pending => Some("delivered"),
106 DirectiveState::Accepted => Some("acked"),
107 DirectiveState::Refused => Some("refused"),
108 }
109 }
110
111 pub fn local(self) -> Option<&'static str> {
114 match self {
115 DirectiveState::Offered => Some("offered"),
116 other => other.wire(),
117 }
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct Directive {
124 pub directive_id: String,
126 pub agent_id: String,
127 pub project_root: String,
128 pub kind: DirectiveKind,
129 pub subject: String,
131 pub version: u64,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub slot: Option<String>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub worker_id: Option<String>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub task_id: Option<String>,
139 pub vault_id: String,
141 #[serde(default)]
143 pub digest: String,
144 pub message_id: String,
146 pub state: DirectiveState,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub reason_code: Option<String>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub reason: Option<String>,
152 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub reported: Option<DirectiveState>,
155 #[serde(default, skip_serializing_if = "String::is_empty")]
157 pub text: String,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub release_sha256: Option<String>,
163 #[serde(skip)]
169 pub release_id: Option<String>,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub released_at: Option<String>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub brief_sha256: Option<String>,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub goal_sha256: Option<String>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
190#[serde(deny_unknown_fields)]
191pub struct ReleaseBody {
192 pub version: u64,
193 pub goal: String,
194 #[serde(default)]
195 pub brief: Option<String>,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum ReleaseError {
201 NotReleaseId,
203 Unknown,
206 Superseded,
208 Body(String),
211 Internal(String),
213}
214
215impl ReleaseError {
216 pub fn code(&self) -> &'static str {
218 match self {
219 Self::NotReleaseId | Self::Body(_) => "invalid_argument",
220 Self::Unknown => "not_found",
221 Self::Superseded => "superseded",
222 Self::Internal(_) => "internal",
223 }
224 }
225
226 pub fn message(&self) -> String {
227 match self {
228 Self::NotReleaseId => "not a release id (64 lowercase hex)".to_string(),
229 Self::Unknown => UNKNOWN_RELEASE_ID.to_string(),
230 Self::Superseded => {
231 "superseded: a newer version was offered before this one was released".to_string()
232 }
233 Self::Body(why) | Self::Internal(why) => why.clone(),
234 }
235 }
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct Release {
241 pub released: bool,
244 pub directive_id: String,
245 pub agent_id: String,
246 pub version: u64,
247 pub released_at: Option<String>,
248}
249
250pub const UNKNOWN_RELEASE_ID: &str = "unknown release id";
253
254const RELEASE_ID_BYTES: usize = 32;
256
257fn new_release_id() -> Result<String, String> {
259 let mut bytes = [0u8; RELEASE_ID_BYTES];
260 getrandom::fill(&mut bytes).map_err(|e| format!("release id: entropy source failed: {e}"))?;
261 Ok(hex::encode(bytes))
262}
263
264pub const RELEASE_IDS_FILE: &str = "directive-release-ids.json";
269
270fn release_sha256(rid: &str) -> String {
272 hex::encode(Sha256::digest(rid.as_bytes()))
273}
274
275pub fn is_release_id(rid: &str) -> bool {
278 rid.len() == RELEASE_ID_BYTES * 2 && rid.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct DirectiveIssue {
284 pub directive_id: String,
285 pub kind: DirectiveKind,
286 pub subject: String,
287 pub version: u64,
288 pub slot: Option<String>,
289 pub worker_id: Option<String>,
290 pub task_id: Option<String>,
291 pub vault_id: String,
292 pub digest: String,
293 pub brief_sha256: Option<String>,
296 pub goal_sha256: Option<String>,
298 pub text: String,
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum Verdict {
306 Accept,
307 Refuse,
308}
309
310impl Verdict {
311 pub fn parse(verdict: &str) -> Option<Self> {
312 match verdict {
313 "accept" => Some(Verdict::Accept),
314 "refuse" => Some(Verdict::Refuse),
315 _ => None,
316 }
317 }
318}
319
320#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
322pub struct DirectiveStore {
323 #[serde(default)]
324 pub directives: Vec<Directive>,
325}
326
327fn plain_text(field: &str, text: &str, max: usize) -> Result<String, String> {
333 if text.trim().is_empty() {
334 return Err(format!("{field} is empty"));
335 }
336 if text.len() > max {
337 return Err(format!("{field} is longer than {max} bytes"));
338 }
339 if text
340 .chars()
341 .any(|c| c.is_control() && c != '\n' && c != '\t')
342 {
343 return Err(format!("{field} carries a control character"));
344 }
345 if text.chars().any(lean_ctx_protocol::cloud::invisible) {
346 return Err(format!("{field} carries an invisible or bidi character"));
347 }
348 Ok(text.to_string())
349}
350
351pub fn brief_digest(text: &str) -> String {
353 format!("sha256:{}", hex::encode(Sha256::digest(text.as_bytes())))
354}
355
356pub fn release_text(d: &Directive, body: Option<&ReleaseBody>) -> Result<String, String> {
362 if d.kind == DirectiveKind::Decision {
363 if body.is_some() {
364 return Err("a decision release takes no body".to_string());
365 }
366 return Ok(d.text.clone());
367 }
368 let body = body.ok_or_else(|| {
369 "a plan release needs the confirmed body on stdin ({\"release_id\",\"version\",\"goal\",\"brief\"})"
370 .to_string()
371 })?;
372 if body.version != d.version {
373 return Err(format!(
374 "the body is version {}, the release id names version {}",
375 body.version, d.version
376 ));
377 }
378 if d.goal_sha256
379 .as_ref()
380 .is_some_and(|signed| &brief_digest(&body.goal) != signed)
381 {
382 return Err("goal does not match the verified plan body of this version".to_string());
383 }
384 let goal = plain_text("goal", &body.goal, MAX_GOAL_BYTES)?;
385 let part = match (&d.brief_sha256, &body.brief) {
386 (Some(signed), Some(brief)) => {
387 if &brief_digest(brief) != signed {
388 return Err(
389 "brief does not match the signed brief_sha256 of this agent's part".to_string(),
390 );
391 }
392 let brief = plain_text("brief", brief, MAX_BRIEF_BYTES)?;
393 let slot = d.slot.as_deref().unwrap_or_default();
394 format!("Your part ({slot}):\n{brief}")
395 }
396 (Some(_), None) => {
397 return Err("brief is required: a part of the plan names this agent".to_string());
398 }
399 (None, Some(_)) => {
400 return Err("brief must be null: no part of the plan names this agent".to_string());
401 }
402 (None, None) => {
403 "No part of this plan names you: check that your work still fits its goal.".to_string()
404 }
405 };
406 Ok(format!(
407 "LeanCTX: plan {plan} v{version}, sent by the person from LeanCTX Code.\nGoal:\n{goal}\n{part}\n{hint}",
408 plan = d.subject,
409 version = d.version,
410 hint = ack_hint(&d.directive_id),
411 ))
412}
413
414fn store_path() -> Result<PathBuf, String> {
415 Ok(super::persistence::agents_dir()?.join("directives.json"))
416}
417
418fn release_ids_path() -> Result<PathBuf, String> {
419 Ok(super::persistence::agents_dir()?.join(RELEASE_IDS_FILE))
420}
421
422type ReleaseIds = std::collections::BTreeMap<String, String>;
423
424enum IdFile {
427 Absent,
428 Ids(ReleaseIds),
429 Damaged(String),
430}
431
432fn read_release_ids(path: &std::path::Path) -> Result<IdFile, String> {
433 match std::fs::symlink_metadata(path) {
434 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(IdFile::Absent),
435 Err(error) => return Ok(IdFile::Damaged(error.to_string())),
436 Ok(meta) if meta.file_type().is_symlink() => {
437 return Err(format!(
438 "release ids {}: a symlink, not followed",
439 path.display()
440 ));
441 }
442 Ok(_) => {}
443 }
444 Ok(match std::fs::read_to_string(path) {
445 Ok(text) => match serde_json::from_str(&text) {
446 Ok(ids) => IdFile::Ids(ids),
447 Err(error) => IdFile::Damaged(error.to_string()),
448 },
449 Err(error) => IdFile::Damaged(error.to_string()),
450 })
451}
452
453fn load_release_ids() -> ReleaseIds {
456 let Ok(path) = release_ids_path() else {
457 return ReleaseIds::new();
458 };
459 match read_release_ids(&path) {
460 Ok(IdFile::Ids(ids)) => ids,
461 Ok(IdFile::Absent) => ReleaseIds::new(),
462 Ok(IdFile::Damaged(error)) => {
463 tracing::warn!("release ids {} unreadable: {error}", path.display());
464 ReleaseIds::new()
465 }
466 Err(error) => {
467 tracing::warn!("{error}");
468 ReleaseIds::new()
469 }
470 }
471}
472
473impl DirectiveStore {
474 pub fn load() -> Self {
476 store_path()
477 .ok()
478 .and_then(|path| std::fs::read_to_string(path).ok())
479 .and_then(|text| serde_json::from_str(&text).ok())
480 .unwrap_or_default()
481 }
482
483 pub fn load_for_app() -> Self {
487 let mut store = Self::load();
488 let ids = load_release_ids();
489 for d in &mut store.directives {
490 if d.state == DirectiveState::Offered {
491 d.release_id = d
492 .release_sha256
493 .as_deref()
494 .and_then(|sha| ids.get(sha))
495 .filter(|rid| d.release_sha256.as_deref() == Some(&release_sha256(rid)))
496 .cloned();
497 }
498 }
499 store
500 }
501
502 fn save(&self) -> Result<(), String> {
506 self.save_release_ids()?;
507 let path = store_path()?;
508 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
509 crate::config_io::write_atomic(&path, &json)
510 .map_err(|error| format!("persist directives {}: {error}", path.display()))
511 }
512
513 fn save_release_ids(&self) -> Result<(), String> {
516 let dir = super::persistence::agents_dir()?;
517 let path = dir.join(RELEASE_IDS_FILE);
518 let mut ids = match read_release_ids(&path)? {
519 IdFile::Absent => ReleaseIds::new(),
520 IdFile::Ids(ids) => ids,
521 IdFile::Damaged(error) => {
525 let aside = dir.join(format!("{RELEASE_IDS_FILE}.damaged"));
526 tracing::warn!(
527 "release ids {} damaged ({error}); kept as {} and started anew: \
528 the offered directives it named can no longer be released",
529 path.display(),
530 aside.display()
531 );
532 std::fs::rename(&path, &aside).map_err(|e| {
533 format!("set aside damaged release ids {}: {e}", path.display())
534 })?;
535 ReleaseIds::new()
536 }
537 };
538 for d in &self.directives {
539 if let (Some(sha), Some(rid)) = (&d.release_sha256, &d.release_id) {
540 ids.insert(sha.clone(), rid.clone());
541 }
542 }
543 ids.retain(|sha, _| {
544 self.directives.iter().any(|d| {
545 d.state == DirectiveState::Offered && d.release_sha256.as_deref() == Some(sha)
546 })
547 });
548 if ids.is_empty() {
549 return match std::fs::remove_file(&path) {
550 Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
551 Err(format!("remove release ids {}: {error}", path.display()))
552 }
553 _ => Ok(()),
554 };
555 }
556 let json = serde_json::to_string(&ids).map_err(|e| e.to_string())?;
557 crate::core::pathjail_write::write_below(
560 &dir,
561 std::path::Path::new(RELEASE_IDS_FILE),
562 json.as_bytes(),
563 0o600,
564 )
565 .map(|_| ())
566 .map_err(|error| format!("persist release ids {}: {error}", path.display()))
567 }
568
569 pub fn mutate<T>(
571 f: impl FnOnce(&mut AgentRegistry, &mut DirectiveStore) -> Result<T, String>,
572 ) -> Result<T, String> {
573 let (_, out) = AgentRegistry::mutate_locked(|registry| {
574 let mut store = Self::load();
575 let out = f(registry, &mut store);
579 store.save().and(out)
580 })?;
581 out
582 }
583
584 pub fn mutate_release(
591 release_id: &str,
592 body: Option<&ReleaseBody>,
593 ) -> Result<(Release, Option<String>), ReleaseError> {
594 let dir = super::persistence::agents_dir().map_err(ReleaseError::Internal)?;
595 let (_, out) = AgentRegistry::mutate_locked(|registry| {
596 let mut store = Self::load();
597 let release = store.release_offered(registry, release_id, body)?;
598 if !release.released {
599 return Ok((release, None));
600 }
601 registry.save_locked(&dir).map_err(ReleaseError::Internal)?;
602 Ok((release, store.save().err()))
603 })
604 .map_err(ReleaseError::Internal)?;
605 out
606 }
607
608 pub fn issue(
617 &mut self,
618 root: &str,
619 agent_id: &str,
620 issue: &DirectiveIssue,
621 ) -> Result<bool, String> {
622 if self
623 .directives
624 .iter()
625 .any(|d| d.agent_id == agent_id && d.directive_id == issue.directive_id)
626 {
627 return Ok(false);
628 }
629 let release_id = new_release_id()?;
630 self.supersede_older(
631 agent_id,
632 issue.kind,
633 &issue.subject,
634 issue.version,
635 &issue.directive_id,
636 DirectiveState::Offered,
637 );
638 self.directives.push(Directive {
639 directive_id: issue.directive_id.clone(),
640 agent_id: agent_id.to_string(),
641 project_root: root.to_string(),
642 kind: issue.kind,
643 subject: issue.subject.clone(),
644 version: issue.version,
645 slot: issue.slot.clone(),
646 worker_id: issue.worker_id.clone(),
647 task_id: issue.task_id.clone(),
648 vault_id: issue.vault_id.clone(),
649 digest: issue.digest.clone(),
650 message_id: String::new(),
651 state: DirectiveState::Offered,
652 reason_code: None,
653 reason: None,
654 reported: None,
655 text: match issue.kind {
659 DirectiveKind::Plan => String::new(),
660 DirectiveKind::Decision => issue.text.clone(),
661 },
662 release_sha256: Some(release_sha256(&release_id)),
663 release_id: Some(release_id),
664 released_at: None,
665 brief_sha256: issue.brief_sha256.clone(),
666 goal_sha256: issue.goal_sha256.clone(),
667 });
668 self.prune();
669 Ok(true)
670 }
671
672 pub fn deliver_decision(
681 &mut self,
682 registry: &mut AgentRegistry,
683 root: &str,
684 agent_id: &str,
685 issue: &DirectiveIssue,
686 ) -> Result<bool, String> {
687 if issue.kind != DirectiveKind::Decision {
688 return Err("only a team decision is delivered from its frame".to_string());
689 }
690 self.issue(root, agent_id, issue)?;
691 let Some(held) = self
692 .directives
693 .iter()
694 .find(|d| d.agent_id == agent_id && d.directive_id == issue.directive_id)
695 else {
696 return Err("the issued decision directive is not recorded".to_string());
697 };
698 if held.kind != DirectiveKind::Decision || held.state != DirectiveState::Offered {
700 return Ok(false);
701 }
702 let release_id = held
703 .release_id
704 .clone()
705 .ok_or_else(|| "the issued decision directive has no release id".to_string())?;
706 self.release_offered(registry, &release_id, None)
707 .map(|release| release.released)
708 .map_err(|error| error.message())
709 }
710
711 fn supersede_older(
714 &mut self,
715 agent_id: &str,
716 kind: DirectiveKind,
717 subject: &str,
718 version: u64,
719 directive_id: &str,
720 state: DirectiveState,
721 ) {
722 for older in self.directives.iter_mut().filter(|d| {
723 d.agent_id == agent_id
724 && d.kind == kind
725 && d.subject == subject
726 && d.state == state
727 && d.directive_id != directive_id
728 && (kind == DirectiveKind::Decision || d.version < version)
729 }) {
730 older.state = DirectiveState::Superseded;
731 }
732 }
733
734 pub fn release_offered(
748 &mut self,
749 registry: &mut AgentRegistry,
750 release_id: &str,
751 body: Option<&ReleaseBody>,
752 ) -> Result<Release, ReleaseError> {
753 if !is_release_id(release_id) {
754 return Err(ReleaseError::NotReleaseId);
755 }
756 let index = self
757 .directives
758 .iter()
759 .position(|d| d.release_sha256.as_deref() == Some(&release_sha256(release_id)))
760 .ok_or(ReleaseError::Unknown)?;
761 let found = &self.directives[index];
762 if found.state != DirectiveState::Offered {
763 if found.released_at.is_none() {
764 return Err(ReleaseError::Superseded);
765 }
766 return Ok(Release {
767 released: false,
768 directive_id: found.directive_id.clone(),
769 agent_id: found.agent_id.clone(),
770 version: found.version,
771 released_at: found.released_at.clone(),
772 });
773 }
774 let d = found.clone();
775 let text = release_text(&d, body).map_err(ReleaseError::Body)?;
776 let key = format!(
777 "{}directive:{}",
778 super::CLOUD_INBOUND_KEY_PREFIX,
779 &crate::core::hasher::hash_hex(
780 format!("{}\0{}", d.agent_id, d.directive_id).as_bytes()
781 )[..32]
782 );
783 let message_id = registry
784 .post_message_keyed(
785 Some(&d.project_root),
786 DIRECTIVE_SENDER,
787 Some(&d.agent_id),
788 DIRECTIVE_CATEGORY,
789 &text,
790 PrivacyLevel::Team,
791 MessagePriority::High,
792 None,
793 Some(&key),
794 )
795 .map_err(ReleaseError::Internal)?;
796 if let Some(entry) = registry.scratchpad.iter_mut().find(|e| e.id == message_id) {
797 entry.task_id.clone_from(&d.task_id);
798 let (subject_key, version) = match d.kind {
799 DirectiveKind::Plan => ("plan_id", Some(d.version.to_string())),
800 DirectiveKind::Decision => ("decision_id", None),
801 };
802 entry
803 .metadata
804 .insert(subject_key.to_string(), d.subject.clone());
805 if let Some(version) = version {
806 entry.metadata.insert("plan_version".to_string(), version);
807 }
808 entry
809 .metadata
810 .insert("directive_id".to_string(), d.directive_id.clone());
811 }
812 self.supersede_older(
813 &d.agent_id,
814 d.kind,
815 &d.subject,
816 d.version,
817 &d.directive_id,
818 DirectiveState::Pending,
819 );
820 let released_at = lean_ctx_time::UtcDateTime::now()
821 .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
822 let record = &mut self.directives[index];
823 record.state = DirectiveState::Pending;
824 record.message_id = message_id;
825 record.released_at = Some(released_at.clone());
826 record.text = text;
827 record.release_id = None;
828 Ok(Release {
829 released: true,
830 directive_id: d.directive_id,
831 agent_id: d.agent_id,
832 version: d.version,
833 released_at: Some(released_at),
834 })
835 }
836
837 fn prune(&mut self) {
838 while self.directives.len() > MAX_DIRECTIVES {
839 let index = self
840 .directives
841 .iter()
842 .position(|d| !matches!(d.state, DirectiveState::Pending | DirectiveState::Offered))
843 .unwrap_or(0);
844 self.directives.remove(index);
845 }
846 }
847
848 pub fn ack(
852 &mut self,
853 registry: &mut AgentRegistry,
854 agent_id: &str,
855 directive_id: &str,
856 verdict: Verdict,
857 reason_code: Option<&str>,
858 reason: Option<&str>,
859 ) -> Result<Directive, String> {
860 let directive = self
861 .directives
862 .iter_mut()
863 .find(|d| {
865 d.agent_id == agent_id
866 && d.directive_id == directive_id
867 && d.state != DirectiveState::Offered
868 })
869 .ok_or_else(|| format!("no directive {directive_id} for this agent"))?;
870 if directive.state == DirectiveState::Superseded {
871 return Err(format!(
872 "directive {directive_id} was superseded by a newer version: answer the newer directive"
873 ));
874 }
875 match verdict {
876 Verdict::Accept => {
877 directive.state = DirectiveState::Accepted;
878 directive.reason_code = None;
879 }
880 Verdict::Refuse => {
881 let code = reason_code
882 .filter(|code| REFUSE_REASONS.contains(code))
883 .ok_or_else(|| {
884 format!(
885 "verdict=refuse needs reason_code, one of: {}",
886 REFUSE_REASONS.join(", ")
887 )
888 })?;
889 directive.state = DirectiveState::Refused;
890 directive.reason_code = Some(code.to_string());
891 }
892 }
893 directive.reason = reason
894 .map(str::trim)
895 .filter(|r| !r.is_empty())
896 .map(|r| r.chars().take(MAX_REASON_CHARS).collect());
897 if let Some(entry) = registry
898 .scratchpad
899 .iter_mut()
900 .find(|e| e.id == directive.message_id)
901 && !entry.read_by.iter().any(|reader| reader == agent_id)
902 {
903 entry.read_by.push(agent_id.to_string());
904 }
905 Ok(directive.clone())
906 }
907
908 pub fn pending_for(&self, agent_id: &str) -> Vec<&Directive> {
910 let mut pending: Vec<&Directive> = self
911 .directives
912 .iter()
913 .filter(|d| d.agent_id == agent_id && d.state == DirectiveState::Pending)
914 .collect();
915 pending.sort_by(|a, b| a.directive_id.cmp(&b.directive_id));
916 pending
917 }
918
919 pub fn unreported_plans(&self) -> Vec<&Directive> {
921 self.directives
922 .iter()
923 .filter(|d| {
924 d.kind == DirectiveKind::Plan
925 && d.state.wire().is_some()
926 && d.reported != Some(d.state)
927 })
928 .collect()
929 }
930
931 pub fn mark_reported(&mut self, done: &[(String, String, DirectiveState)]) {
934 for (agent, id, state) in done {
935 if let Some(d) = self
936 .directives
937 .iter_mut()
938 .find(|d| &d.agent_id == agent && &d.directive_id == id && d.state == *state)
939 {
940 d.reported = Some(*state);
941 }
942 }
943 }
944}
945
946pub fn pending_line(directive: &Directive) -> String {
948 match directive.kind {
949 DirectiveKind::Plan => format!(
950 "[directive pending: plan {} v{}, ack with ctx_agent action=ack directive_id={}]",
951 directive.subject, directive.version, directive.directive_id
952 ),
953 DirectiveKind::Decision => format!(
954 "[directive pending: decision {}, ack with ctx_agent action=ack directive_id={}]",
955 directive.subject, directive.directive_id
956 ),
957 }
958}
959
960pub fn pending_lines(store: &DirectiveStore, agent_id: &str) -> Option<String> {
962 let lines: Vec<String> = store
963 .pending_for(agent_id)
964 .into_iter()
965 .map(pending_line)
966 .collect();
967 (!lines.is_empty()).then(|| lines.join("\n"))
968}
969
970pub fn directives_modified() -> Option<SystemTime> {
972 std::fs::metadata(store_path().ok()?)
973 .and_then(|m| m.modified())
974 .ok()
975}
976
977type SuffixCache = Option<(Option<SystemTime>, String, Option<String>)>;
978static SUFFIX_CACHE: Mutex<SuffixCache> = Mutex::new(None);
979
980pub fn pending_suffix_for(agent_id: &str) -> Option<String> {
983 let modified = directives_modified();
984 modified?;
985 let mut cache = SUFFIX_CACHE.lock().ok()?;
986 if let Some((at, agent, lines)) = cache.as_ref()
987 && *at == modified
988 && agent == agent_id
989 {
990 return lines.clone();
991 }
992 let lines = pending_lines(&DirectiveStore::load(), agent_id);
993 *cache = Some((modified, agent_id.to_string(), lines.clone()));
994 lines
995}
996
997#[cfg(test)]
998#[path = "directives_tests.rs"]
999mod tests;