use std::path::PathBuf;
use std::sync::Mutex;
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use super::AgentRegistry;
use crate::core::a2a::message::{MessagePriority, PrivacyLevel};
pub const DIRECTIVE_SENDER: &str = "cloud";
pub const DIRECTIVE_CATEGORY: &str = "directive";
pub const REFUSE_REASONS: [&str; 5] = [
"conflicts_with_decision",
"task_finished",
"out_of_scope",
"unverified_plan",
"other",
];
const MAX_DIRECTIVES: usize = 500;
const MAX_REASON_CHARS: usize = 500;
pub const MAX_GOAL_BYTES: usize = 16_000;
pub const MAX_BRIEF_BYTES: usize = 32_000;
const 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.";
pub fn ack_hint(directive_id: &str) -> String {
ACK_HINT.replace("{id}", directive_id)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DirectiveKind {
Plan,
Decision,
}
impl DirectiveKind {
pub fn as_str(self) -> &'static str {
match self {
DirectiveKind::Plan => "plan",
DirectiveKind::Decision => "decision",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DirectiveState {
Offered,
Pending,
Accepted,
Refused,
Superseded,
}
impl DirectiveState {
pub fn wire(self) -> Option<&'static str> {
match self {
DirectiveState::Offered | DirectiveState::Superseded => None,
DirectiveState::Pending => Some("delivered"),
DirectiveState::Accepted => Some("acked"),
DirectiveState::Refused => Some("refused"),
}
}
pub fn local(self) -> Option<&'static str> {
match self {
DirectiveState::Offered => Some("offered"),
other => other.wire(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Directive {
pub directive_id: String,
pub agent_id: String,
pub project_root: String,
pub kind: DirectiveKind,
pub subject: String,
pub version: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slot: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub worker_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task_id: Option<String>,
pub vault_id: String,
#[serde(default)]
pub digest: String,
pub message_id: String,
pub state: DirectiveState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason_code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reported: Option<DirectiveState>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub release_sha256: Option<String>,
#[serde(skip)]
pub release_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub released_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub brief_sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goal_sha256: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReleaseBody {
pub version: u64,
pub goal: String,
#[serde(default)]
pub brief: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReleaseError {
NotReleaseId,
Unknown,
Superseded,
Body(String),
Internal(String),
}
impl ReleaseError {
pub fn code(&self) -> &'static str {
match self {
Self::NotReleaseId | Self::Body(_) => "invalid_argument",
Self::Unknown => "not_found",
Self::Superseded => "superseded",
Self::Internal(_) => "internal",
}
}
pub fn message(&self) -> String {
match self {
Self::NotReleaseId => "not a release id (64 lowercase hex)".to_string(),
Self::Unknown => UNKNOWN_RELEASE_ID.to_string(),
Self::Superseded => {
"superseded: a newer version was offered before this one was released".to_string()
}
Self::Body(why) | Self::Internal(why) => why.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Release {
pub released: bool,
pub directive_id: String,
pub agent_id: String,
pub version: u64,
pub released_at: Option<String>,
}
pub const UNKNOWN_RELEASE_ID: &str = "unknown release id";
const RELEASE_ID_BYTES: usize = 32;
fn new_release_id() -> Result<String, String> {
let mut bytes = [0u8; RELEASE_ID_BYTES];
getrandom::fill(&mut bytes).map_err(|e| format!("release id: entropy source failed: {e}"))?;
Ok(hex::encode(bytes))
}
pub const RELEASE_IDS_FILE: &str = "directive-release-ids.json";
fn release_sha256(rid: &str) -> String {
hex::encode(Sha256::digest(rid.as_bytes()))
}
pub fn is_release_id(rid: &str) -> bool {
rid.len() == RELEASE_ID_BYTES * 2 && rid.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectiveIssue {
pub directive_id: String,
pub kind: DirectiveKind,
pub subject: String,
pub version: u64,
pub slot: Option<String>,
pub worker_id: Option<String>,
pub task_id: Option<String>,
pub vault_id: String,
pub digest: String,
pub brief_sha256: Option<String>,
pub goal_sha256: Option<String>,
pub text: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
Accept,
Refuse,
}
impl Verdict {
pub fn parse(verdict: &str) -> Option<Self> {
match verdict {
"accept" => Some(Verdict::Accept),
"refuse" => Some(Verdict::Refuse),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectiveStore {
#[serde(default)]
pub directives: Vec<Directive>,
}
fn plain_text(field: &str, text: &str, max: usize) -> Result<String, String> {
if text.trim().is_empty() {
return Err(format!("{field} is empty"));
}
if text.len() > max {
return Err(format!("{field} is longer than {max} bytes"));
}
if text
.chars()
.any(|c| c.is_control() && c != '\n' && c != '\t')
{
return Err(format!("{field} carries a control character"));
}
if text.chars().any(lean_ctx_protocol::cloud::invisible) {
return Err(format!("{field} carries an invisible or bidi character"));
}
Ok(text.to_string())
}
pub fn brief_digest(text: &str) -> String {
format!("sha256:{}", hex::encode(Sha256::digest(text.as_bytes())))
}
pub fn release_text(d: &Directive, body: Option<&ReleaseBody>) -> Result<String, String> {
if d.kind == DirectiveKind::Decision {
if body.is_some() {
return Err("a decision release takes no body".to_string());
}
return Ok(d.text.clone());
}
let body = body.ok_or_else(|| {
"a plan release needs the confirmed body on stdin ({\"release_id\",\"version\",\"goal\",\"brief\"})"
.to_string()
})?;
if body.version != d.version {
return Err(format!(
"the body is version {}, the release id names version {}",
body.version, d.version
));
}
if d.goal_sha256
.as_ref()
.is_some_and(|signed| &brief_digest(&body.goal) != signed)
{
return Err("goal does not match the verified plan body of this version".to_string());
}
let goal = plain_text("goal", &body.goal, MAX_GOAL_BYTES)?;
let part = match (&d.brief_sha256, &body.brief) {
(Some(signed), Some(brief)) => {
if &brief_digest(brief) != signed {
return Err(
"brief does not match the signed brief_sha256 of this agent's part".to_string(),
);
}
let brief = plain_text("brief", brief, MAX_BRIEF_BYTES)?;
let slot = d.slot.as_deref().unwrap_or_default();
format!("Your part ({slot}):\n{brief}")
}
(Some(_), None) => {
return Err("brief is required: a part of the plan names this agent".to_string());
}
(None, Some(_)) => {
return Err("brief must be null: no part of the plan names this agent".to_string());
}
(None, None) => {
"No part of this plan names you: check that your work still fits its goal.".to_string()
}
};
Ok(format!(
"LeanCTX: plan {plan} v{version}, sent by the person from LeanCTX Code.\nGoal:\n{goal}\n{part}\n{hint}",
plan = d.subject,
version = d.version,
hint = ack_hint(&d.directive_id),
))
}
fn store_path() -> Result<PathBuf, String> {
Ok(super::persistence::agents_dir()?.join("directives.json"))
}
fn release_ids_path() -> Result<PathBuf, String> {
Ok(super::persistence::agents_dir()?.join(RELEASE_IDS_FILE))
}
type ReleaseIds = std::collections::BTreeMap<String, String>;
enum IdFile {
Absent,
Ids(ReleaseIds),
Damaged(String),
}
fn read_release_ids(path: &std::path::Path) -> Result<IdFile, String> {
match std::fs::symlink_metadata(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(IdFile::Absent),
Err(error) => return Ok(IdFile::Damaged(error.to_string())),
Ok(meta) if meta.file_type().is_symlink() => {
return Err(format!(
"release ids {}: a symlink, not followed",
path.display()
));
}
Ok(_) => {}
}
Ok(match std::fs::read_to_string(path) {
Ok(text) => match serde_json::from_str(&text) {
Ok(ids) => IdFile::Ids(ids),
Err(error) => IdFile::Damaged(error.to_string()),
},
Err(error) => IdFile::Damaged(error.to_string()),
})
}
fn load_release_ids() -> ReleaseIds {
let Ok(path) = release_ids_path() else {
return ReleaseIds::new();
};
match read_release_ids(&path) {
Ok(IdFile::Ids(ids)) => ids,
Ok(IdFile::Absent) => ReleaseIds::new(),
Ok(IdFile::Damaged(error)) => {
tracing::warn!("release ids {} unreadable: {error}", path.display());
ReleaseIds::new()
}
Err(error) => {
tracing::warn!("{error}");
ReleaseIds::new()
}
}
}
impl DirectiveStore {
pub fn load() -> Self {
store_path()
.ok()
.and_then(|path| std::fs::read_to_string(path).ok())
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
pub fn load_for_app() -> Self {
let mut store = Self::load();
let ids = load_release_ids();
for d in &mut store.directives {
if d.state == DirectiveState::Offered {
d.release_id = d
.release_sha256
.as_deref()
.and_then(|sha| ids.get(sha))
.filter(|rid| d.release_sha256.as_deref() == Some(&release_sha256(rid)))
.cloned();
}
}
store
}
fn save(&self) -> Result<(), String> {
self.save_release_ids()?;
let path = store_path()?;
let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
crate::config_io::write_atomic(&path, &json)
.map_err(|error| format!("persist directives {}: {error}", path.display()))
}
fn save_release_ids(&self) -> Result<(), String> {
let dir = super::persistence::agents_dir()?;
let path = dir.join(RELEASE_IDS_FILE);
let mut ids = match read_release_ids(&path)? {
IdFile::Absent => ReleaseIds::new(),
IdFile::Ids(ids) => ids,
IdFile::Damaged(error) => {
let aside = dir.join(format!("{RELEASE_IDS_FILE}.damaged"));
tracing::warn!(
"release ids {} damaged ({error}); kept as {} and started anew: \
the offered directives it named can no longer be released",
path.display(),
aside.display()
);
std::fs::rename(&path, &aside).map_err(|e| {
format!("set aside damaged release ids {}: {e}", path.display())
})?;
ReleaseIds::new()
}
};
for d in &self.directives {
if let (Some(sha), Some(rid)) = (&d.release_sha256, &d.release_id) {
ids.insert(sha.clone(), rid.clone());
}
}
ids.retain(|sha, _| {
self.directives.iter().any(|d| {
d.state == DirectiveState::Offered && d.release_sha256.as_deref() == Some(sha)
})
});
if ids.is_empty() {
return match std::fs::remove_file(&path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
Err(format!("remove release ids {}: {error}", path.display()))
}
_ => Ok(()),
};
}
let json = serde_json::to_string(&ids).map_err(|e| e.to_string())?;
crate::core::pathjail_write::write_below(
&dir,
std::path::Path::new(RELEASE_IDS_FILE),
json.as_bytes(),
0o600,
)
.map(|_| ())
.map_err(|error| format!("persist release ids {}: {error}", path.display()))
}
pub fn mutate<T>(
f: impl FnOnce(&mut AgentRegistry, &mut DirectiveStore) -> Result<T, String>,
) -> Result<T, String> {
let (_, out) = AgentRegistry::mutate_locked(|registry| {
let mut store = Self::load();
let out = f(registry, &mut store);
store.save().and(out)
})?;
out
}
pub fn mutate_release(
release_id: &str,
body: Option<&ReleaseBody>,
) -> Result<(Release, Option<String>), ReleaseError> {
let dir = super::persistence::agents_dir().map_err(ReleaseError::Internal)?;
let (_, out) = AgentRegistry::mutate_locked(|registry| {
let mut store = Self::load();
let release = store.release_offered(registry, release_id, body)?;
if !release.released {
return Ok((release, None));
}
registry.save_locked(&dir).map_err(ReleaseError::Internal)?;
Ok((release, store.save().err()))
})
.map_err(ReleaseError::Internal)?;
out
}
pub fn issue(
&mut self,
root: &str,
agent_id: &str,
issue: &DirectiveIssue,
) -> Result<bool, String> {
if self
.directives
.iter()
.any(|d| d.agent_id == agent_id && d.directive_id == issue.directive_id)
{
return Ok(false);
}
let release_id = new_release_id()?;
self.supersede_older(
agent_id,
issue.kind,
&issue.subject,
issue.version,
&issue.directive_id,
DirectiveState::Offered,
);
self.directives.push(Directive {
directive_id: issue.directive_id.clone(),
agent_id: agent_id.to_string(),
project_root: root.to_string(),
kind: issue.kind,
subject: issue.subject.clone(),
version: issue.version,
slot: issue.slot.clone(),
worker_id: issue.worker_id.clone(),
task_id: issue.task_id.clone(),
vault_id: issue.vault_id.clone(),
digest: issue.digest.clone(),
message_id: String::new(),
state: DirectiveState::Offered,
reason_code: None,
reason: None,
reported: None,
text: match issue.kind {
DirectiveKind::Plan => String::new(),
DirectiveKind::Decision => issue.text.clone(),
},
release_sha256: Some(release_sha256(&release_id)),
release_id: Some(release_id),
released_at: None,
brief_sha256: issue.brief_sha256.clone(),
goal_sha256: issue.goal_sha256.clone(),
});
self.prune();
Ok(true)
}
pub fn deliver_decision(
&mut self,
registry: &mut AgentRegistry,
root: &str,
agent_id: &str,
issue: &DirectiveIssue,
) -> Result<bool, String> {
if issue.kind != DirectiveKind::Decision {
return Err("only a team decision is delivered from its frame".to_string());
}
self.issue(root, agent_id, issue)?;
let Some(held) = self
.directives
.iter()
.find(|d| d.agent_id == agent_id && d.directive_id == issue.directive_id)
else {
return Err("the issued decision directive is not recorded".to_string());
};
if held.kind != DirectiveKind::Decision || held.state != DirectiveState::Offered {
return Ok(false);
}
let release_id = held
.release_id
.clone()
.ok_or_else(|| "the issued decision directive has no release id".to_string())?;
self.release_offered(registry, &release_id, None)
.map(|release| release.released)
.map_err(|error| error.message())
}
fn supersede_older(
&mut self,
agent_id: &str,
kind: DirectiveKind,
subject: &str,
version: u64,
directive_id: &str,
state: DirectiveState,
) {
for older in self.directives.iter_mut().filter(|d| {
d.agent_id == agent_id
&& d.kind == kind
&& d.subject == subject
&& d.state == state
&& d.directive_id != directive_id
&& (kind == DirectiveKind::Decision || d.version < version)
}) {
older.state = DirectiveState::Superseded;
}
}
pub fn release_offered(
&mut self,
registry: &mut AgentRegistry,
release_id: &str,
body: Option<&ReleaseBody>,
) -> Result<Release, ReleaseError> {
if !is_release_id(release_id) {
return Err(ReleaseError::NotReleaseId);
}
let index = self
.directives
.iter()
.position(|d| d.release_sha256.as_deref() == Some(&release_sha256(release_id)))
.ok_or(ReleaseError::Unknown)?;
let found = &self.directives[index];
if found.state != DirectiveState::Offered {
if found.released_at.is_none() {
return Err(ReleaseError::Superseded);
}
return Ok(Release {
released: false,
directive_id: found.directive_id.clone(),
agent_id: found.agent_id.clone(),
version: found.version,
released_at: found.released_at.clone(),
});
}
let d = found.clone();
let text = release_text(&d, body).map_err(ReleaseError::Body)?;
let key = format!(
"{}directive:{}",
super::CLOUD_INBOUND_KEY_PREFIX,
&crate::core::hasher::hash_hex(
format!("{}\0{}", d.agent_id, d.directive_id).as_bytes()
)[..32]
);
let message_id = registry
.post_message_keyed(
Some(&d.project_root),
DIRECTIVE_SENDER,
Some(&d.agent_id),
DIRECTIVE_CATEGORY,
&text,
PrivacyLevel::Team,
MessagePriority::High,
None,
Some(&key),
)
.map_err(ReleaseError::Internal)?;
if let Some(entry) = registry.scratchpad.iter_mut().find(|e| e.id == message_id) {
entry.task_id.clone_from(&d.task_id);
let (subject_key, version) = match d.kind {
DirectiveKind::Plan => ("plan_id", Some(d.version.to_string())),
DirectiveKind::Decision => ("decision_id", None),
};
entry
.metadata
.insert(subject_key.to_string(), d.subject.clone());
if let Some(version) = version {
entry.metadata.insert("plan_version".to_string(), version);
}
entry
.metadata
.insert("directive_id".to_string(), d.directive_id.clone());
}
self.supersede_older(
&d.agent_id,
d.kind,
&d.subject,
d.version,
&d.directive_id,
DirectiveState::Pending,
);
let released_at = lean_ctx_time::UtcDateTime::now()
.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
let record = &mut self.directives[index];
record.state = DirectiveState::Pending;
record.message_id = message_id;
record.released_at = Some(released_at.clone());
record.text = text;
record.release_id = None;
Ok(Release {
released: true,
directive_id: d.directive_id,
agent_id: d.agent_id,
version: d.version,
released_at: Some(released_at),
})
}
fn prune(&mut self) {
while self.directives.len() > MAX_DIRECTIVES {
let index = self
.directives
.iter()
.position(|d| !matches!(d.state, DirectiveState::Pending | DirectiveState::Offered))
.unwrap_or(0);
self.directives.remove(index);
}
}
pub fn ack(
&mut self,
registry: &mut AgentRegistry,
agent_id: &str,
directive_id: &str,
verdict: Verdict,
reason_code: Option<&str>,
reason: Option<&str>,
) -> Result<Directive, String> {
let directive = self
.directives
.iter_mut()
.find(|d| {
d.agent_id == agent_id
&& d.directive_id == directive_id
&& d.state != DirectiveState::Offered
})
.ok_or_else(|| format!("no directive {directive_id} for this agent"))?;
if directive.state == DirectiveState::Superseded {
return Err(format!(
"directive {directive_id} was superseded by a newer version: answer the newer directive"
));
}
match verdict {
Verdict::Accept => {
directive.state = DirectiveState::Accepted;
directive.reason_code = None;
}
Verdict::Refuse => {
let code = reason_code
.filter(|code| REFUSE_REASONS.contains(code))
.ok_or_else(|| {
format!(
"verdict=refuse needs reason_code, one of: {}",
REFUSE_REASONS.join(", ")
)
})?;
directive.state = DirectiveState::Refused;
directive.reason_code = Some(code.to_string());
}
}
directive.reason = reason
.map(str::trim)
.filter(|r| !r.is_empty())
.map(|r| r.chars().take(MAX_REASON_CHARS).collect());
if let Some(entry) = registry
.scratchpad
.iter_mut()
.find(|e| e.id == directive.message_id)
&& !entry.read_by.iter().any(|reader| reader == agent_id)
{
entry.read_by.push(agent_id.to_string());
}
Ok(directive.clone())
}
pub fn pending_for(&self, agent_id: &str) -> Vec<&Directive> {
let mut pending: Vec<&Directive> = self
.directives
.iter()
.filter(|d| d.agent_id == agent_id && d.state == DirectiveState::Pending)
.collect();
pending.sort_by(|a, b| a.directive_id.cmp(&b.directive_id));
pending
}
pub fn unreported_plans(&self) -> Vec<&Directive> {
self.directives
.iter()
.filter(|d| {
d.kind == DirectiveKind::Plan
&& d.state.wire().is_some()
&& d.reported != Some(d.state)
})
.collect()
}
pub fn mark_reported(&mut self, done: &[(String, String, DirectiveState)]) {
for (agent, id, state) in done {
if let Some(d) = self
.directives
.iter_mut()
.find(|d| &d.agent_id == agent && &d.directive_id == id && d.state == *state)
{
d.reported = Some(*state);
}
}
}
}
pub fn pending_line(directive: &Directive) -> String {
match directive.kind {
DirectiveKind::Plan => format!(
"[directive pending: plan {} v{}, ack with ctx_agent action=ack directive_id={}]",
directive.subject, directive.version, directive.directive_id
),
DirectiveKind::Decision => format!(
"[directive pending: decision {}, ack with ctx_agent action=ack directive_id={}]",
directive.subject, directive.directive_id
),
}
}
pub fn pending_lines(store: &DirectiveStore, agent_id: &str) -> Option<String> {
let lines: Vec<String> = store
.pending_for(agent_id)
.into_iter()
.map(pending_line)
.collect();
(!lines.is_empty()).then(|| lines.join("\n"))
}
pub fn directives_modified() -> Option<SystemTime> {
std::fs::metadata(store_path().ok()?)
.and_then(|m| m.modified())
.ok()
}
type SuffixCache = Option<(Option<SystemTime>, String, Option<String>)>;
static SUFFIX_CACHE: Mutex<SuffixCache> = Mutex::new(None);
pub fn pending_suffix_for(agent_id: &str) -> Option<String> {
let modified = directives_modified();
modified?;
let mut cache = SUFFIX_CACHE.lock().ok()?;
if let Some((at, agent, lines)) = cache.as_ref()
&& *at == modified
&& agent == agent_id
{
return lines.clone();
}
let lines = pending_lines(&DirectiveStore::load(), agent_id);
*cache = Some((modified, agent_id.to_string(), lines.clone()));
lines
}
#[cfg(test)]
#[path = "directives_tests.rs"]
mod tests;