Skip to main content

lean_ctx/core/agents/
directives.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Directives (contract §37): a person changed the plan or a team decision
3//! in Code, and Cloud told this engine. Each affected local agent gets a
4//! record here, first **offered**: invisible to the agent (no bus entry, no
5//! pending line, no ack). Only the person's confirmed "Send to agents" in
6//! LeanCTX Code releases it, through the local CLI
7//! `lean-ctx cloud plan release` with the random release id (on stdin,
8//! never in argv) of that one directive and agent ([`DirectiveStore::release_offered`]).
9//! The person's confirmed body goes with the release: for a plan, the
10//! plan's goal and this agent's own brief of exactly the released version
11//! ([`ReleaseBody`]); the goal and the brief are checked against the
12//! digests of the verified plan body (the slot's signed `brief_sha256`). The agent's bus entry carries that
13//! and nothing else (no other part, no other version, no release id).
14//! Then the agent gets one bus entry (category `directive`, priority high)
15//! and the record stays pending until the agent answers with
16//! `ctx_agent action=ack`. Nothing on the agent bus or a Cloud frame can
17//! release a directive: issuing ([`DirectiveStore::issue`]) never touches
18//! the bus, and the release id is shown only to the app's reads.
19//!
20//! The records live in `<agents>/directives.json`, next to `registry.json`
21//! and written under its lock, not inside it: older MCP processes re-write
22//! the registry with their own schema and would drop a field they do not
23//! know (the same reason `ProcessIdentityIndex` has its own file).
24//!
25//! A directive is an instruction, never a control: nothing here pauses,
26//! stops or gates local work. Free-text refusal reasons stay on this
27//! machine; Cloud receives only the state and the reason code.
28
29use 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
39/// The sender every directive entry carries on the local bus.
40pub const DIRECTIVE_SENDER: &str = "cloud";
41/// The bus category of a directive entry.
42pub const DIRECTIVE_CATEGORY: &str = "directive";
43/// Reason codes an agent may refuse a directive with (§37.4).
44pub const REFUSE_REASONS: [&str; 5] = [
45    "conflicts_with_decision",
46    "task_finished",
47    "out_of_scope",
48    "unverified_plan",
49    "other",
50];
51/// Records kept; the oldest answered ones drop first.
52const MAX_DIRECTIVES: usize = 500;
53/// A local refusal reason is kept to this many characters.
54const MAX_REASON_CHARS: usize = 500;
55/// Bytes of a released plan goal (the body's 4000 characters, UTF-8).
56pub const MAX_GOAL_BYTES: usize = 16_000;
57/// Bytes of a released brief (the body's 8000 characters, UTF-8).
58pub 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
62/// How an agent answers `directive_id` (the last line of every directive).
63pub fn ack_hint(directive_id: &str) -> String {
64    ACK_HINT.replace("{id}", directive_id)
65}
66
67/// What changed.
68#[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/// Where the agent stands with one directive.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum DirectiveState {
88    /// Received from Cloud, waiting for the person's release in LeanCTX
89    /// Code. Invisible to the agent: no bus entry, no pending line, no ack.
90    Offered,
91    /// Released and delivered to the agent's inbox, not answered yet.
92    Pending,
93    Accepted,
94    Refused,
95    /// A newer version of the same plan or decision replaced it unanswered.
96    Superseded,
97}
98
99impl DirectiveState {
100    /// The state as the plan ack route names it (§37.5); `None` for one
101    /// Cloud is not told about.
102    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    /// The state as the app's local read shows it: `offered` besides the
112    /// wire states; `None` for a superseded one.
113    pub fn local(self) -> Option<&'static str> {
114        match self {
115            DirectiveState::Offered => Some("offered"),
116            other => other.wire(),
117        }
118    }
119}
120
121/// One directive for one local agent.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct Directive {
124    /// `plan_id:version:slot` for a plan, `decision_id:status` for a decision.
125    pub directive_id: String,
126    pub agent_id: String,
127    pub project_root: String,
128    pub kind: DirectiveKind,
129    /// `plan_id` or `decision_id`.
130    pub subject: String,
131    /// Plan version; 0 for a decision.
132    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    /// The Cloud vault id the change came from.
140    pub vault_id: String,
141    /// The plan's `content_sha256`; empty for a decision.
142    #[serde(default)]
143    pub digest: String,
144    /// The bus entry that carried it; empty while offered.
145    pub message_id: String,
146    pub state: DirectiveState,
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub reason_code: Option<String>,
149    /// The agent's own words; local only, never sent to Cloud.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub reason: Option<String>,
152    /// The last state Cloud recorded for this agent.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub reported: Option<DirectiveState>,
155    /// The bus text the agent reads once the directive is released.
156    #[serde(default, skip_serializing_if = "String::is_empty")]
157    pub text: String,
158    /// SHA-256 (hex) of the release id: what a release is matched
159    /// against. Only this digest is in `directives.json`, which an agent's
160    /// read tools may open.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub release_sha256: Option<String>,
163    /// The release id itself (`rid`, 64 hex of 32 random bytes): the one
164    /// handle that releases this directive for this agent. In memory only:
165    /// kept in [`RELEASE_IDS_FILE`] (a secret path every agent read tool
166    /// refuses) and filled by [`DirectiveStore::load_for_app`] for the
167    /// app's read (`cloud.plan.updates`), while offered.
168    #[serde(skip)]
169    pub release_id: Option<String>,
170    /// When the person released it (RFC 3339 UTC): the local audit of the
171    /// release, shown with the version and agent on the app's read.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub released_at: Option<String>,
174    /// The signed `brief_sha256` of the agent's slot (`sha256:<64 hex>` of
175    /// the brief's UTF-8 bytes); `None` for a plan-wide directive and a
176    /// decision. A released brief must match it.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub brief_sha256: Option<String>,
179    /// `sha256:<64 hex>` of the verified plan body's goal; `None` for a
180    /// decision (and a record from before). A released goal must match it.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub goal_sha256: Option<String>,
183}
184
185/// What the person confirmed in LeanCTX Code for one release of a plan
186/// directive (the JSON `cloud plan release` reads on stdin): the version,
187/// the plan's goal, and the agent's own brief (`null` for an agent no part
188/// of the plan names). Nothing else is accepted.
189#[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/// Why [`DirectiveStore::release_offered`] released nothing.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum ReleaseError {
201    /// Not the shape of a release id (a directive id, a guess).
202    NotReleaseId,
203    /// A release id no directive of this machine carries (unknown, or
204    /// another machine's).
205    Unknown,
206    /// The offer was superseded by a newer version before it was released.
207    Superseded,
208    /// The body does not match the directive (version, brief digest) or is
209    /// not well-formed.
210    Body(String),
211    /// The bus could not take the entry; nothing was released.
212    Internal(String),
213}
214
215impl ReleaseError {
216    /// The error code of the CLI's JSON line.
217    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/// What [`DirectiveStore::release_offered`] did.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct Release {
241    /// False when this id was released before (the same release again):
242    /// nothing changed, the earlier delivery stands.
243    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
250/// The error of [`DirectiveStore::release_offered`] for a well-formed id
251/// no directive carries.
252pub const UNKNOWN_RELEASE_ID: &str = "unknown release id";
253
254/// Bytes of a release id.
255const RELEASE_ID_BYTES: usize = 32;
256
257/// A fresh release id from the OS CSPRNG (256 bit, lowercase hex).
258fn 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
264/// The file next to `directives.json` that holds the release ids of the
265/// offered directives (`{release_sha256: release_id}`, mode 0600). Its name
266/// is a secret path ([`crate::core::io_boundary::is_secret_like`]): no
267/// `ctx_*` read, search or shell tool and no hooked native read opens it.
268pub const RELEASE_IDS_FILE: &str = "directive-release-ids.json";
269
270/// SHA-256 (hex) of a release id.
271fn release_sha256(rid: &str) -> String {
272    hex::encode(Sha256::digest(rid.as_bytes()))
273}
274
275/// Whether `rid` has the shape of a release id (64 lowercase hex). A
276/// directive id (`<plan>:<v>:<slot>`) never has it.
277pub 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/// A directive to issue, as the Cloud relay builds it.
282#[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    /// The slot's signed `brief_sha256`; `None` for a plan-wide directive
294    /// and a decision.
295    pub brief_sha256: Option<String>,
296    /// The digest of the verified body's goal; `None` for a decision.
297    pub goal_sha256: Option<String>,
298    /// The bus text of a decision. A plan's entry is built at release from
299    /// the confirmed [`ReleaseBody`] instead.
300    pub text: String,
301}
302
303/// The agent's answer.
304#[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/// `<agents>/directives.json`.
321#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
322pub struct DirectiveStore {
323    #[serde(default)]
324    pub directives: Vec<Directive>,
325}
326
327/// Text a person typed may carry newlines and tabs, no other control
328/// characters (they could fake a bus line or a terminal sequence) and no
329/// character a Cloud text field refuses (bidi and other format controls,
330/// zero-width characters: [`lean_ctx_protocol::cloud::invisible`]), which
331/// could hide or reorder what the agent reads.
332fn 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
351/// `sha256:<64 hex>` of `text`'s UTF-8 bytes.
352pub fn brief_digest(text: &str) -> String {
353    format!("sha256:{}", hex::encode(Sha256::digest(text.as_bytes())))
354}
355
356/// The one bus entry a released directive becomes. A plan's entry is the
357/// plan id and version, `body`'s goal, this agent's own brief (or, for a
358/// plan-wide directive, that no part names it) and how to answer: no other
359/// part, no other version, no release id. A decision keeps its text and
360/// takes no body.
361pub 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 Cloud: 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
424/// The id file as read: absent, readable, or damaged (unreadable or not
425/// the expected JSON). A symlink in its place is an error, never followed.
426enum 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
453/// The ids for the app's read; a missing, damaged or symlinked file gives
454/// none (fail closed: nothing can be released), with a warning.
455fn 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    /// The records on disk; a missing or damaged file reads as none.
475    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    /// The records with the release id of each offered one: the app's
484    /// read (`cloud.plan.updates`) only. Every other reader uses
485    /// [`Self::load`], which never holds a release id.
486    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    /// The id file first, then the records: a crash in between leaves an
503    /// id whose record is missing (dropped at the next save), never an
504    /// offered record without its release id.
505    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    /// Keep the ids of the offered directives only: a new one is added, a
514    /// released or superseded one is dropped.
515    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            // Never overwritten unseen: the damaged file is kept aside
522            // (`….damaged`, also a secret path) with a warning. Its ids are
523            // lost: their directives can no longer be released (fail closed).
524            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        // Crash-atomic, mode 0600, and no symlink below the agents dir is
558        // followed (the file itself included).
559        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    /// Change the registry and the records under the registry lock.
570    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            // The registry is written even when `f` fails part-way, so the
576            // records of the directives it already posted are written too:
577            // a bus entry never lacks its record (issuing again is a no-op).
578            let out = f(registry, &mut store);
579            store.save().and(out)
580        })?;
581        out
582    }
583
584    /// [`Self::release_offered`] for the CLI, so that its answer matches
585    /// what happened: the bus entry (registry) is written first, then the
586    /// records. A failed registry write delivered nothing (`Err`, the
587    /// directive stays offered). A failed record write after it does not
588    /// undo the delivery: the release is reported with the error as a
589    /// warning (a retry finds the keyed entry and changes nothing).
590    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    /// Record `issue` for `agent_id` in `root` as **offered**: nothing is
609    /// posted on the bus and the agent sees nothing until the person
610    /// releases it ([`Self::release_offered`]). Offering the same directive
611    /// to the same agent again changes nothing (a catch-up after a frame).
612    /// Offered directives of an older version of the same plan, or of the
613    /// same decision, are superseded (their release ids release nothing);
614    /// a released one stays as it is until the newer one is released.
615    /// True when a record was added.
616    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            // An offered plan directive keeps no text: `directives.json` is
656            // readable by agents, and the delivered text is the person's
657            // confirmed body (set on release).
658            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    /// Issue a team decision directive to `agent_id` and post it at once.
673    /// Cloud announces a decision change (`decision.changed`) only after the
674    /// person's confirmed "Send to agents" in LeanCTX Code, so the frame is
675    /// the release; the relay calls this only from that frame. The same
676    /// directive to the same agent again posts nothing (false), unless an
677    /// earlier frame recorded it but could not post it: a decision directive
678    /// still offered is released by the next frame. A plan directive is
679    /// refused: it waits for [`Self::release_offered`].
680    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        // Released, superseded or pruned before: nothing to post again.
699        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    /// Mark `agent_id`'s directives in `state` of an older version of the
712    /// same plan (any other id of the same decision) superseded.
713    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    /// Release the one offered directive `release_id` names, for the agent
735    /// it was offered to: post its bus entry and make it pending. Called
736    /// by the local CLI `lean-ctx cloud plan release` after the person's
737    /// confirmed "Send to agents" in LeanCTX Code, and for a team decision by
738    /// [`Self::deliver_decision`]; no bus or Cloud handler reaches it for a
739    /// plan.
740    ///
741    /// Per agent and version: the id releases nothing else. A plan entry is
742    /// exactly `body`'s goal and this agent's brief ([`release_text`]); the
743    /// body must name the directive's version and its brief must match the
744    /// slot's signed digest. The same id again after its release changes
745    /// nothing (`released: false`); an id superseded before its release, an
746    /// unknown id, or anything that is no release id is an error.
747    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    /// Record `agent_id`'s answer to `directive_id`. A refusal needs one of
849    /// [`REFUSE_REASONS`]; `reason` is kept locally. Answering again
850    /// replaces the earlier answer. The directive's bus entry counts as read.
851    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            // An offered directive does not exist for the agent yet.
864            .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    /// `agent_id`'s unanswered directives, by id.
909    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    /// Plan directives whose state Cloud has not recorded yet.
920    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    /// Note that Cloud recorded `state` for these `(agent, directive)`s; a
932    /// state that moved on since stays unreported.
933    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
946/// The one-line reminder of a pending directive (stable text, #498).
947pub 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
960/// The reminder lines for `agent_id`, sorted; `None` when nothing is pending.
961pub 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
970/// When the records last changed; `None` while there are none.
971pub 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
980/// [`pending_lines`] for `agent_id` from disk, re-read only when the file
981/// changed: the tool pipeline asks on every call.
982pub 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;