Skip to main content

lean_ctx_server/tools/
ctx_agent.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
3use lean_ctx::core::a2a::task::TaskStore;
4use lean_ctx::core::agents::{
5    AgentDiary, AgentRegistry, AgentStatus, DiaryEntryType, ScratchpadEntry,
6};
7use lean_ctx::core::ocla::capsule::global_capsule_store;
8use lean_ctx::core::ocla::registry::OclaRegistry;
9use lean_ctx::core::ocla::types::{
10    AGENT_ENVELOPE_SCHEMA_VERSION, AgentEnvelope, AgentMessageRequest, OclaRequestContext,
11};
12
13#[path = "ctx_agent_claims.rs"]
14pub(crate) mod claims;
15#[path = "ctx_agent_control.rs"]
16mod control;
17#[path = "ctx_agent_lease.rs"]
18mod lease;
19use control::{control_status, lease_resource};
20#[cfg(test)]
21use lease::LeaseSettle;
22
23fn presence_ttl_hours() -> u64 {
24    lean_ctx::core::config::Config::load()
25        .agents
26        .presence_ttl_hours
27}
28
29fn scratchpad_default_ttl_hours() -> u64 {
30    lean_ctx::core::config::Config::load()
31        .agents
32        .scratchpad_default_ttl_hours
33}
34
35/// Every action [`handle`] dispatches, one entry each. The MCP schema's
36/// `action` enum and the unknown-action reply are both built from this list.
37pub(crate) const ACTIONS: &[&str] = &[
38    "register",
39    "list",
40    "post",
41    "read",
42    "wait",
43    "status",
44    "info",
45    "handoff",
46    "sync",
47    "claim",
48    "release",
49    "claims",
50    "brief",
51    "return",
52    "export",
53    "diary",
54    "recall_diary",
55    "diaries",
56    "share_knowledge",
57    "receive_knowledge",
58    "poll_events",
59    "control_status",
60    "lease_acquire",
61    "lease_renew",
62    "lease_release",
63    "plan_claims",
64    "send",
65    "reply",
66    "inbox",
67    "ack",
68];
69
70/// `ack`: answer a Cloud directive (a plan update or a changed team
71/// decision, contract §37). `accept`, or `refuse` with one of
72/// [`lean_ctx::core::agents::REFUSE_REASONS`]; `reason` stays on this
73/// machine, Cloud sees the state and the code only.
74pub fn handle_ack(
75    current_agent_id: Option<&str>,
76    directive_id: Option<&str>,
77    verdict: Option<&str>,
78    reason_code: Option<&str>,
79    reason: Option<&str>,
80) -> Result<String, String> {
81    use lean_ctx::core::agents::{DirectiveStore, Verdict};
82    let Some(agent_id) = current_agent_id else {
83        return Err("Error: agent must be registered first (use action=register)".to_string());
84    };
85    let Some(directive_id) = directive_id.map(str::trim).filter(|id| !id.is_empty()) else {
86        return Err("Error: ack needs directive_id".to_string());
87    };
88    let Some(verdict) = verdict.and_then(Verdict::parse) else {
89        return Err("Error: ack needs verdict=accept or verdict=refuse".to_string());
90    };
91    let answered = DirectiveStore::mutate(|registry, store| {
92        store.ack(
93            registry,
94            agent_id,
95            directive_id,
96            verdict,
97            reason_code,
98            reason,
99        )
100    })
101    .map_err(|error| format!("Error: {error}"))?;
102    Ok(match answered.reason_code {
103        Some(code) => format!(
104            "Directive {directive_id}: refused ({code}). Cloud is told on the next relay pass."
105        ),
106        None => {
107            format!("Directive {directive_id}: accepted. Cloud is told on the next relay pass.")
108        }
109    })
110}
111
112/// Arguments of the Cloud message actions (`send`, `reply`, `inbox`).
113#[derive(Debug, Clone, Default)]
114pub struct MessageArgs {
115    pub message_type: Option<String>,
116    pub text: Option<String>,
117    pub to: Option<String>,
118    pub reply_to: Option<String>,
119    pub references: Vec<String>,
120    /// reply to a handoff: take it (`true`) or decline it.
121    pub accept: Option<bool>,
122}
123
124impl MessageArgs {
125    fn untyped(text: Option<&str>, category: Option<&str>, to: Option<&str>) -> Self {
126        Self {
127            message_type: category.map(str::to_string),
128            text: text.map(str::to_string),
129            to: to.map(str::to_string),
130            ..Self::default()
131        }
132    }
133}
134
135/// `send`: a typed message to the vault bus of the checkout. `reply`:
136/// answers a received message in its thread (type defaults to `answer`).
137/// `inbox`: the unread messages, Cloud deliveries fenced as foreign data
138/// ([`lean_ctx_cloud::bus::messages_v2`]).
139pub fn handle_message(
140    action: &str,
141    args: &MessageArgs,
142    project_root: &str,
143    current_agent_id: Option<&str>,
144) -> String {
145    use lean_ctx_cloud::bus::messages_v2::{Extras, send};
146    let Some(agent) = current_agent_id else {
147        return "Error: agent must be registered first (use action=register)".to_string();
148    };
149    if action == "inbox" {
150        return match read_messages_as(agent, project_root, true) {
151            Ok(text) | Err(text) => text,
152        };
153    }
154    let Some(text) = args.text.as_deref() else {
155        return format!("Error: message is required for {action}");
156    };
157    let reply_to = args.reply_to.as_deref();
158    if action == "reply" && reply_to.is_none() {
159        return "Error: reply_to (the msg_… id of the message answered) is required".to_string();
160    }
161    let message_type = args
162        .message_type
163        .as_deref()
164        .or((action == "reply").then_some("answer"));
165    let extras = Extras {
166        to_worker: args.to.as_deref(),
167        reply_to,
168        accept: args.accept,
169        resource: args.references.first().map(String::as_str),
170        refs: &args.references,
171    };
172    match send(project_root, agent, message_type, text, extras) {
173        Ok(id) => format!(
174            "Queued [{}] {id}; the LeanCTX Cloud relay sends it to the vault's agents",
175            message_type.unwrap_or("?")
176        ),
177        Err(error) => format!("Error: {error}"),
178    }
179}
180
181/// `action=read` with a typed outcome: `Ok` is the reply, `Err` is the text
182/// of a failed read — the same text [`handle`] answers. `read` is the one
183/// action of this tool that declares every source
184/// (`CtxAgentTool::publishes_every_source`), so its failure must reach the
185/// registered tool as a failure and never as a reply that could be recorded
186/// as a delivery of the sources captured before it failed.
187pub fn handle_read(
188    message: Option<&str>,
189    current_agent_id: Option<&str>,
190    project_root: &str,
191) -> Result<String, String> {
192    // Same admission as `handle`: unadmitted caller text refuses the call.
193    if let Some(text) = message
194        && let Err(withheld) = lean_ctx::core::context_admission::carrier::admit_for_store(text)
195    {
196        return Err(format!("Error: {}", withheld.message("agent message")));
197    }
198    read_messages(current_agent_id, project_root)
199}
200
201/// The unread messages of `current_agent_id` in `project_root`.
202fn read_messages(current_agent_id: Option<&str>, project_root: &str) -> Result<String, String> {
203    let Some(agent_id) = current_agent_id else {
204        return Err("Error: agent must be registered first (use action=register)".to_string());
205    };
206    let mut text = read_messages_as(agent_id, project_root, true)?;
207    // What other agents declared in the linked emspace space, beside the bus.
208    if let Some(sessions) =
209        lean_ctx::core::providers::emspace::admitted_sessions_block(project_root)
210    {
211        text.push_str(&sessions);
212    }
213    Ok(text)
214}
215
216/// The line `read`/`wait` print once after an expired registration was renewed.
217fn renewed_line(agent_id: &str) -> String {
218    format!(
219        "Note: the registration of {agent_id} had expired and was renewed; retry a claim refused meanwhile.\n"
220    )
221}
222
223/// One `read` answers at most this much message text (at least one
224/// message); the rest stays unread and the answer says how many. Hosts
225/// archive or cut longer tool answers, and the cut messages were lost.
226pub(crate) const READ_PAGE_BYTES: usize = 6_000;
227
228/// One unread message as `read` shows it.
229fn render_message(m: &ScratchpadEntry, project_root: &str) -> String {
230    let age = (lean_ctx_time::UtcDateTime::now() - m.timestamp).num_minutes();
231    // A new delivery: re-authorized under the current policy. One from
232    // another instance carries its sender and kind inside the fence.
233    if lean_ctx_cloud::bus::relay_v2::is_inbound(m) {
234        // Text from another Instance: untrusted by origin (pz21 §1.1).
235        lean_ctx::core::context_admission::capture::note_origin(
236            &lean_ctx::core::context_admission::origin::SourceClass::External(
237                lean_ctx::core::context_admission::origin::InputOrigin::new(
238                    lean_ctx::core::context_admission::origin::InputKind::BusMessage,
239                    format!("cloud:{}", m.id),
240                ),
241            ),
242        );
243        return format!(
244            "  [cloud] ({age}m ago):\n{}\n",
245            m.served_message(Some(project_root))
246        );
247    }
248    format!(
249        "  [{}] from {} ({}m ago): {}\n",
250        m.category,
251        m.from_agent,
252        age,
253        m.served_message(Some(project_root))
254    )
255}
256
257/// The unread messages of `agent_id`, oldest first and at most
258/// `READ_PAGE_BYTES` per call; only the ones shown are marked read.
259/// `own_process`: the call comes from the agent's own session, which renews
260/// its lease (and revives an expired one); `lean-ctx agent wait` reads for
261/// it from another process.
262pub fn read_messages_as(
263    agent_id: &str,
264    project_root: &str,
265    own_process: bool,
266) -> Result<String, String> {
267    let (shown, left) = match AgentRegistry::mutate_locked(|registry| {
268        if own_process {
269            registry.renew_worker(agent_id)?;
270        }
271        registry.read_unread_page(agent_id, project_root, READ_PAGE_BYTES, |m| {
272            render_message(m, project_root)
273        })
274    }) {
275        Ok((_, Ok(page))) => page,
276        Ok((_, Err(error))) => {
277            tracing::warn!("lean-ctx: message read rejected: {error}");
278            return Err(format!("Error: {error}"));
279        }
280        Err(e) => {
281            tracing::warn!(
282                "lean-ctx: failed to persist agent registry (messages may reappear): {e}"
283            );
284            return Err("Error: failed to read messages".to_string());
285        }
286    };
287
288    let mut renewed = if lean_ctx::core::agents::take_renewed(agent_id) {
289        renewed_line(agent_id)
290    } else {
291        String::new()
292    };
293    // An MCP server older than the installed binary misses its fixes.
294    if own_process && let Some(note) = lean_ctx::core::binary_identity::replaced_note() {
295        renewed.insert_str(0, &note);
296    }
297    // Unanswered directives stay on top until acked, read or not (§37).
298    if let Some(lines) = lean_ctx::core::agents::pending_lines(
299        &lean_ctx::core::agents::DirectiveStore::load(),
300        agent_id,
301    ) {
302        renewed.push_str(&lines);
303        renewed.push('\n');
304    }
305    if shown.is_empty() {
306        return Ok(format!("{renewed}No new messages."));
307    }
308
309    let mut out = format!("{renewed}New messages ({}):\n", shown.len());
310    for line in &shown {
311        out.push_str(line);
312    }
313    if left > 0 {
314        out.push_str(&format!(
315            "{left} more unread (still unread): read again for the next ones.\n"
316        ));
317    }
318    Ok(out)
319}
320
321/// `wait` without `timeout_secs`, and its ceiling.
322pub const WAIT_DEFAULT_SECS: u64 = 600;
323pub const WAIT_MAX_SECS: u64 = 1800;
324
325/// The stable reply of a `wait` that saw no message.
326pub fn wait_timeout_line(secs: u64) -> String {
327    format!("No new messages within {secs}s.")
328}
329
330/// `action=wait`: block until a message for `agent_id` (to it or broadcast,
331/// not its own) is waiting in `project_root`, then answer exactly like
332/// `read`; `Ok(None)` after `timeout_secs` (default 600, at most 1800).
333/// `own_process` as in [`read_messages_as`]: the agent's own session keeps
334/// its lease alive while it waits.
335pub fn wait_messages(
336    agent_id: &str,
337    project_root: &str,
338    timeout_secs: Option<u64>,
339    own_process: bool,
340) -> Result<Option<String>, String> {
341    let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
342    if own_process {
343        // Fail fast on an unknown or finished agent instead of waiting.
344        AgentRegistry::renew_worker_persistent(agent_id).map_err(|e| format!("Error: {e}"))?;
345    }
346    let arrived = AgentRegistry::wait_for_unread(
347        agent_id,
348        project_root,
349        std::time::Duration::from_secs(secs),
350        || {
351            if own_process && let Err(e) = AgentRegistry::renew_worker_persistent(agent_id) {
352                tracing::debug!("lean-ctx: wait keepalive for {agent_id}: {e}");
353            }
354        },
355    );
356    if arrived {
357        return read_messages_as(agent_id, project_root, own_process).map(Some);
358    }
359    lean_ctx::core::agents::friction::record_for(
360        lean_ctx::core::agents::friction::WAIT_TIMEOUT,
361        Some(agent_id),
362        Some(project_root),
363    );
364    Ok(None)
365}
366
367/// The text of `wait` for the MCP tool: the messages, or the timeout line
368/// (after the renewal note, when there is one).
369pub fn handle_wait(
370    current_agent_id: Option<&str>,
371    project_root: &str,
372    timeout_secs: Option<u64>,
373) -> Result<String, String> {
374    let Some(agent_id) = current_agent_id else {
375        return Err("Error: agent must be registered first (use action=register)".to_string());
376    };
377    let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
378    Ok(
379        match wait_messages(agent_id, project_root, timeout_secs, true)? {
380            Some(text) => text,
381            None if lean_ctx::core::agents::take_renewed(agent_id) => {
382                format!("{}{}", renewed_line(agent_id), wait_timeout_line(secs))
383            }
384            None => wait_timeout_line(secs),
385        },
386    )
387}
388
389/// What `register` stores from the caller's `role` and `name`: `role` is a
390/// role id ([`lean_ctx::core::agents::role_id`]), `name` the display name
391/// (a bounded single line). Free text given as `role` is never stored as a
392/// role; it becomes the display name when no `name` is given. The warnings
393/// say what was not taken as asked.
394pub fn role_and_name(
395    role: Option<&str>,
396    name: Option<&str>,
397) -> (Option<String>, Option<String>, Vec<String>) {
398    let mut warnings = Vec::new();
399    let mut display = None;
400    if let Some(raw) = name {
401        display = lean_ctx::core::activity::session_name(raw);
402        if display.is_none() {
403            warnings.push("warning: name ignored (1-128 characters, one line)".to_owned());
404        }
405    }
406    let role_id = role.and_then(lean_ctx::core::agents::role_id);
407    if let (Some(raw), None) = (role, &role_id) {
408        warnings.push(format!(
409            "warning: unknown_role: {:?} is not a role id (coder, reviewer, tester, …); \
410             pass a display name as name=",
411            raw.chars().take(64).collect::<String>()
412        ));
413        if display.is_none() {
414            display = lean_ctx::core::activity::session_name(raw);
415        }
416    }
417    (role_id, display, warnings)
418}
419
420/// `register`: register (or refresh) this process's presence with `role`
421/// and `name` and answer exactly what was stored. A re-register on the same
422/// presence takes over the new role and name.
423pub fn register(
424    agent_type: Option<&str>,
425    role: Option<&str>,
426    name: Option<&str>,
427    durable_identity_id: Option<&str>,
428    project_root: &str,
429) -> String {
430    let atype = agent_type.unwrap_or("unknown");
431    let (role, name, warnings) = role_and_name(role, name);
432    let stored = AgentRegistry::mutate_locked(|registry| {
433        registry.cleanup_stale(presence_ttl_hours());
434        let agent_id =
435            registry.register(atype, role.as_deref(), project_root, durable_identity_id)?;
436        if let Some(name) = &name {
437            registry.set_display_name(&agent_id, name);
438        }
439        let entry = registry.agents.iter().find(|a| a.agent_id == agent_id);
440        Ok((
441            agent_id.clone(),
442            entry.and_then(|a| a.role.clone()),
443            entry.and_then(|a| a.display_name.clone()),
444        ))
445    })
446    .and_then(|(_, stored)| stored);
447    match stored {
448        Ok((agent_id, role, name)) => {
449            // The relay announces the agent (and its role) now, not on its
450            // next tick: a claim right after register finds it.
451            lean_ctx_cloud::bus::presence::request_announce();
452            // Callers take the id from the text after the first ':'; the
453            // warnings and the note come after the stored values.
454            let mut text = format!(
455                "Agent registered: {agent_id} (type: {atype}, role: {}, name: {})",
456                role.as_deref().unwrap_or("none"),
457                name.as_deref().unwrap_or("none"),
458            );
459            for warning in warnings {
460                text.push('\n');
461                text.push_str(&warning);
462            }
463            if let Some(note) = lean_ctx::core::binary_identity::replaced_note() {
464                text.push('\n');
465                text.push_str(note.trim_end());
466            }
467            text
468        }
469        Err(e) => format!("Registration failed: {e}"),
470    }
471}
472
473/// The Queen-network fields of a `post` (QN0): its kind (one of the
474/// fourteen Queen kinds, posted only by the registered Queen), the task it
475/// belongs to and its conversation.
476#[derive(Debug, Clone, Copy, Default)]
477pub struct PostFields<'a> {
478    pub kind: Option<&'a str>,
479    pub task_id: Option<&'a str>,
480    pub thread: Option<&'a str>,
481}
482
483/// A `ctx_agent` call. What Cloud answered to this agent's earlier lease
484/// requests (asked off the tool call) comes in front of the answer, except
485/// for `read`, whose answer is a delivery of its sources only.
486#[allow(clippy::too_many_arguments)]
487pub fn handle(
488    action: &str,
489    agent_type: Option<&str>,
490    role: Option<&str>,
491    durable_identity_id: Option<&str>,
492    project_root: &str,
493    current_agent_id: Option<&str>,
494    message: Option<&str>,
495    category: Option<&str>,
496    to_agent: Option<&str>,
497    status: Option<&str>,
498    privacy: Option<&str>,
499    priority: Option<&str>,
500    ttl_hours: Option<u64>,
501    format: Option<&str>,
502    write: bool,
503    filename: Option<&str>,
504    request_id: Option<&str>,
505) -> String {
506    handle_with(
507        action,
508        agent_type,
509        role,
510        durable_identity_id,
511        project_root,
512        current_agent_id,
513        message,
514        category,
515        to_agent,
516        status,
517        privacy,
518        priority,
519        ttl_hours,
520        format,
521        write,
522        filename,
523        request_id,
524        PostFields::default(),
525    )
526}
527
528/// A post's Queen-network fields as the bus stores them: the task id and
529/// the entry metadata (kind, thread). Refused: an unknown kind (with the
530/// list), priority high or critical with a kind other than conflict,
531/// escalate or stop, a malformed task id or thread, and a kind from a sender
532/// that is no registered Queen (`not_queen`) or over its minute's budget
533/// (`rate_limited`), and any kind while the team policy for `project_root`
534/// turns the Orchestrator network off (`orchestrator_network_off`, QN2; the
535/// same refusal as the CLI bus).
536fn checked_post_fields(
537    registry: &AgentRegistry,
538    sender: &str,
539    project_root: &str,
540    post: PostFields<'_>,
541    priority: &MessagePriority,
542) -> Result<(Option<String>, std::collections::BTreeMap<String, String>), String> {
543    use lean_ctx_cloud::bus::queen_kinds::{self, QueenKind, SenderRefusal};
544    let kind = QueenKind::from_input(post.kind)?;
545    if let Some(task_id) = post.task_id {
546        queen_kinds::check_task_id(task_id)?;
547    }
548    if let Some(thread) = post.thread {
549        queen_kinds::check_thread(thread)?;
550    }
551    if let Some(kind) = kind
552        && matches!(priority, MessagePriority::High | MessagePriority::Critical)
553        && !kind.allows_high()
554    {
555        return Err(format!(
556            "priority high is only for kinds conflict, escalate and stop, not {}",
557            kind.as_str()
558        ));
559    }
560    // Every post counts against its sender's budget, as on the CLI; a
561    // kind also needs the registered Queen.
562    let now = lean_ctx_time::UtcDateTime::now().timestamp_millis();
563    queen_kinds::check_sender(registry, sender, kind, now).map_err(|refused| match refused {
564        SenderRefusal::NotQueen(why) | SenderRefusal::RateLimited(why) => why,
565    })?;
566    if kind.is_some()
567        && let Some(why) = lean_ctx::core::policy::cloud_orchestrator::network_refusal(Some(
568            std::path::Path::new(project_root),
569        ))
570    {
571        return Err(why);
572    }
573    let mut metadata = std::collections::BTreeMap::new();
574    if let Some(kind) = kind {
575        metadata.insert(queen_kinds::KIND_KEY.to_owned(), kind.as_str().to_owned());
576    }
577    if let Some(thread) = post.thread {
578        metadata.insert(queen_kinds::THREAD_KEY.to_owned(), thread.to_owned());
579    }
580    Ok((post.task_id.map(str::to_owned), metadata))
581}
582
583/// [`handle`] with a post's Queen-network fields.
584#[allow(clippy::too_many_arguments)]
585pub fn handle_with(
586    action: &str,
587    agent_type: Option<&str>,
588    role: Option<&str>,
589    durable_identity_id: Option<&str>,
590    project_root: &str,
591    current_agent_id: Option<&str>,
592    message: Option<&str>,
593    category: Option<&str>,
594    to_agent: Option<&str>,
595    status: Option<&str>,
596    privacy: Option<&str>,
597    priority: Option<&str>,
598    ttl_hours: Option<u64>,
599    format: Option<&str>,
600    write: bool,
601    filename: Option<&str>,
602    request_id: Option<&str>,
603    post: PostFields<'_>,
604) -> String {
605    let earlier = current_agent_id.filter(|_| action != "read").map(|agent| {
606        lean_ctx_cloud::background::earlier(&lean_ctx_cloud::bus::leases::caller(agent))
607    });
608    let answer = handle_action(
609        action,
610        agent_type,
611        role,
612        durable_identity_id,
613        project_root,
614        current_agent_id,
615        message,
616        category,
617        to_agent,
618        status,
619        privacy,
620        priority,
621        ttl_hours,
622        format,
623        write,
624        filename,
625        request_id,
626        post,
627    );
628    match earlier {
629        Some(earlier) => earlier.present(answer),
630        None => answer,
631    }
632}
633
634#[allow(clippy::too_many_arguments)]
635fn handle_action(
636    action: &str,
637    agent_type: Option<&str>,
638    role: Option<&str>,
639    durable_identity_id: Option<&str>,
640    project_root: &str,
641    current_agent_id: Option<&str>,
642    message: Option<&str>,
643    category: Option<&str>,
644    to_agent: Option<&str>,
645    status: Option<&str>,
646    privacy: Option<&str>,
647    priority: Option<&str>,
648    _ttl_hours: Option<u64>,
649    format: Option<&str>,
650    write: bool,
651    filename: Option<&str>,
652    request_id: Option<&str>,
653    post: PostFields<'_>,
654) -> String {
655    // The caller's text is admitted once, before any action stores, routes,
656    // derives from or echoes it (post, handoff, status, diary, knowledge,
657    // brief). Unadmitted input is never echoed back: a refusal names the typed
658    // reason only. Allowed text is unchanged byte for byte.
659    let admitted_message = match message
660        .map(lean_ctx::core::context_admission::carrier::admit_for_store)
661        .transpose()
662    {
663        Ok(admitted) => admitted,
664        Err(withheld) => return format!("Error: {}", withheld.message("agent message")),
665    };
666    let message = admitted_message.as_deref();
667    match action {
668        "register" => register(agent_type, role, None, durable_identity_id, project_root),
669
670        "list" => {
671            let registry = match AgentRegistry::mutate_locked(|registry| {
672                registry.cleanup_stale(presence_ttl_hours());
673            }) {
674                Ok((registry, ())) => registry,
675                Err(e) => {
676                    tracing::warn!("lean-ctx: failed to persist agent registry: {e}");
677                    AgentRegistry::load_or_create()
678                }
679            };
680
681            let agents = registry.list_active(Some(project_root));
682            let sessions =
683                lean_ctx::core::providers::emspace::admitted_sessions_block(project_root)
684                    .unwrap_or_default();
685            if agents.is_empty() {
686                return format!("No active agents for this project.{sessions}");
687            }
688
689            // V5.3: sessions are listed under the durable worker they attach
690            // to; without an enrolled instance workers have no `wkr_` id.
691            let store = lean_ctx_cloud::CloudStore::open().ok();
692            let instance = store
693                .as_ref()
694                .and_then(|s| s.instance().ok().flatten())
695                .map(|record| record.instance_id);
696            let book = match (&store, &instance) {
697                (Some(store), Some(id)) => {
698                    lean_ctx_cloud::workers::attach::list(store, id).unwrap_or_default()
699                }
700                _ => Vec::new(),
701            };
702            let mut roster = lean_ctx_cloud::workers::roster::render(
703                &agents,
704                instance.as_deref().map(|id| (id, book.as_slice())),
705                lean_ctx_time::UtcDateTime::now(),
706            );
707            if let Some(store) = &store {
708                roster.push_str(&lean_ctx_cloud::bus::presence::render_remote(
709                    store.data_dir(),
710                    lean_ctx_time::UtcDateTime::now(),
711                ));
712            }
713            roster.push_str(&sessions);
714            roster
715        }
716
717        "post" => {
718            let Some(msg) = message else {
719                return "Error: message is required for post".to_string();
720            };
721            let cat = category.unwrap_or("status");
722            let from = current_agent_id.unwrap_or("anonymous");
723            let msg_privacy = privacy.map_or(PrivacyLevel::Team, PrivacyLevel::parse_str);
724            let msg_priority = priority.map_or(MessagePriority::Normal, MessagePriority::parse_str);
725            let ttl_hours = _ttl_hours.or(Some(scratchpad_default_ttl_hours()));
726            if msg_privacy == PrivacyLevel::Private && to_agent.is_none() {
727                return "Error: private messages require to_agent".to_string();
728            }
729            let registry = AgentRegistry::load_or_create();
730            // `queen` reaches the registered Queen (QN0), never an agent that
731            // only took the role name.
732            let to_agent = match to_agent
733                .map(|t| lean_ctx_cloud::bus::queen_kinds::resolve_to(&registry, t))
734                .transpose()
735            {
736                Ok(to) => to,
737                Err(refused) => return format!("Error: not posted: {refused}"),
738            };
739            let to_agent = to_agent.as_deref();
740            let (task_id, metadata) =
741                match checked_post_fields(&registry, from, project_root, post, &msg_priority) {
742                    Ok(fields) => fields,
743                    Err(refused) => return format!("Error: not posted: {refused}"),
744                };
745            // No approval in a person's name (refused), and only the
746            // registered Queen appears as the Queen (process v1 §7): another
747            // sender is refused (`enforce`) or marked for its receivers (`warn`).
748            let msg = {
749                // The sender among the active presences; a question, offer or
750                // handoff that passes on a refused action is refused too.
751                match lean_ctx_cloud::bus::person_rules::check_local_post(
752                    &registry,
753                    current_agent_id,
754                    cat,
755                    to_agent,
756                    msg,
757                ) {
758                    Ok(text) => text,
759                    Err(refused) => return format!("Error: not posted: {refused}"),
760                }
761            };
762            let msg = msg.as_str();
763            let request = AgentMessageRequest {
764                project_root: project_root.to_string(),
765                from_agent_id: from.to_string(),
766                to_agent_id: to_agent.map(str::to_string),
767                category: cat.to_string(),
768                message: msg.to_string(),
769                privacy: msg_privacy,
770                priority: msg_priority,
771                ttl_hours,
772                request_id: request_id.map(str::to_string),
773                task_id,
774                metadata,
775            };
776            match OclaRegistry::global().agent_gateway.route_message(&request) {
777                Ok(msg_id) => {
778                    let target = to_agent.unwrap_or("all agents (broadcast)");
779                    format!("Posted [{cat}] to {target}: {msg} (id: {msg_id})")
780                }
781                Err(e) => format!("Post failed: {e}"),
782            }
783        }
784
785        // The text of either outcome, for callers of this untyped entry
786        // point; the registered tool takes the typed one (`handle_read`).
787        "read" => match read_messages(current_agent_id, project_root) {
788            Ok(text) | Err(text) => text,
789        },
790
791        // This entry point has no `timeout_secs`: the default applies; the
792        // registered tool passes it (`handle_wait`).
793        "wait" => match handle_wait(current_agent_id, project_root, None) {
794            Ok(text) | Err(text) => text,
795        },
796
797        // Cloud agent messages (I1). This entry point has no `type`/`reply_to`
798        // arguments: `category` carries the type; the registered tool passes all.
799        "send" => handle_message(
800            "send",
801            &MessageArgs::untyped(message, category, to_agent),
802            project_root,
803            current_agent_id,
804        ),
805        "reply" => handle_message(
806            "reply",
807            &MessageArgs::untyped(message, category, to_agent),
808            project_root,
809            current_agent_id,
810        ),
811        "inbox" => handle_message(
812            "inbox",
813            &MessageArgs::untyped(message, category, to_agent),
814            project_root,
815            current_agent_id,
816        ),
817
818        "status" => {
819            let Some(agent_id) = current_agent_id else {
820                return "Error: agent must be registered first".to_string();
821            };
822            let new_status = match status {
823                Some("active") => AgentStatus::Active,
824                Some("idle") => AgentStatus::Idle,
825                Some("finished") => AgentStatus::Finished,
826                Some(other) => {
827                    return format!("Unknown status: {other}. Use: active, idle, finished");
828                }
829                None => return "Error: status value is required".to_string(),
830            };
831            let status_msg = message;
832
833            match AgentRegistry::mutate_locked(|registry| {
834                registry.set_status_by_agent(agent_id, new_status.clone(), status_msg)
835            })
836            .and_then(|(_, result)| result)
837            {
838                Ok(()) => {
839                    // A finished agent edits no more: its unit claims go.
840                    let released = if matches!(new_status, AgentStatus::Finished) {
841                        lean_ctx::core::unit_claims::release_agent(agent_id)
842                    } else {
843                        0
844                    };
845                    format!(
846                        "Status updated: {} → {}{}{}",
847                        agent_id,
848                        new_status,
849                        status_msg.map(|m| format!(" ({m})")).unwrap_or_default(),
850                        if released > 0 {
851                            format!("; released {released} unit claim(s)")
852                        } else {
853                            String::new()
854                        }
855                    )
856                }
857                Err(e) => format!("Status update rejected: {e}"),
858            }
859        }
860
861        // Every unit claim of the repository (edit-made, `claim units=[…]`,
862        // path leases) and the overlaps between agents.
863        "claims" => claims::handle_claims(project_root, current_agent_id),
864
865        "plan_claims" => {
866            let holder = current_agent_id
867                .map(str::to_string)
868                .unwrap_or_else(crate::tools::claims_gate::process_agent);
869            claims::plan(project_root, &holder, message)
870        }
871
872        "info" => {
873            let registry = AgentRegistry::mutate_locked(|registry| {
874                registry.cleanup_stale(presence_ttl_hours());
875            })
876            .map(|(registry, ())| registry)
877            .unwrap_or_else(|_| AgentRegistry::load_or_create());
878            let total = registry.agents.len();
879            let active = registry.list_active(None).len();
880            let messages = registry.scratchpad.len();
881            format!(
882                "Agent Registry: {total} total, {active} active, {messages} scratchpad entries\nLast updated: {}",
883                registry.updated_at.format("%Y-%m-%d %H:%M UTC")
884            )
885        }
886
887        "handoff" => {
888            let Some(from) = current_agent_id else {
889                return "Error: agent must be registered first".to_string();
890            };
891            let Some(target) = to_agent else {
892                return "Error: to_agent is required for handoff".to_string();
893            };
894            let summary = message.unwrap_or("(no summary provided)");
895            let scratchpad_ttl = scratchpad_default_ttl_hours();
896            // A worker of another machine (`wkr_…`, as `ctx_agent list`
897            // shows it): the handoff is a typed message through Cloud, which
898            // that worker answers (accept or decline). Any other target is
899            // an agent on this machine.
900            if target.starts_with("wkr_") {
901                use lean_ctx_cloud::bus::messages_v2::{Extras, send};
902                let extras = Extras {
903                    to_worker: Some(target),
904                    ..Extras::default()
905                };
906                return match send(project_root, from, Some("handoff"), summary, extras) {
907                    Ok(id) => {
908                        let waiting = format!("handoff to {target} offered through LeanCTX Cloud");
909                        let _ = AgentRegistry::mutate_locked(|registry| {
910                            registry.set_status(from, AgentStatus::Idle, Some(&waiting))
911                        });
912                        format!(
913                            "Handoff offered (cloud): {from} → {target} message={id}; \
914                             {target} answers it (accept or decline)\nSummary: {summary}"
915                        )
916                    }
917                    Err(error) => format!("Handoff rejected: {error}"),
918                };
919            }
920
921            if let Err(error) = AgentRegistry::mutate_locked(|registry| {
922                // The handoff message must be persisted before the sender is
923                // marked Finished. A bound presence that finishes first can no
924                // longer post, so the delivery would be silently dropped.
925                registry.post_message_scoped(
926                    Some(project_root),
927                    from,
928                    Some(target),
929                    "handoff",
930                    &format!("HANDOFF from {from}: {summary}"),
931                    PrivacyLevel::Team,
932                    MessagePriority::Normal,
933                    Some(scratchpad_ttl),
934                )?;
935                registry.set_status(from, AgentStatus::Finished, Some("handed off"))
936            })
937            .and_then(|(_, result)| result)
938            {
939                return format!("Handoff rejected: {error}");
940            }
941
942            // Route through OCLA AgentGateway for cross-process visibility.
943            let handoff_message = format!("HANDOFF: {summary}");
944            let capsule_ref = global_capsule_store().register(handoff_message.as_bytes());
945            let mut envelope = AgentEnvelope {
946                schema_version: AGENT_ENVELOPE_SCHEMA_VERSION,
947                relay_id: String::new(),
948                context: OclaRequestContext::new(
949                    format!("handoff:{capsule_ref}"),
950                    project_root.to_string(),
951                    from.to_string(),
952                    capsule_ref.clone(),
953                    None,
954                    Some(format!("handoff:{from}:{target}")),
955                ),
956                from_agent_id: from.to_string(),
957                to_agent_id: target.to_string(),
958                capsule_ref,
959                budget_tokens: handoff_message.len().max(1) as u64,
960            };
961            if let Err(error) = envelope.assign_relay_id() {
962                tracing::debug!("OCLA relay setup failed (non-fatal): {error}");
963            } else if let Err(error) = OclaRegistry::global().agent_gateway.relay_agent(envelope) {
964                tracing::debug!("OCLA relay failed (non-fatal): {error}");
965            }
966
967            // Stigmergy (#540): mark the handed-off work as Done in the field
968            // so other agents see it arithmetically, without reading messages.
969            lean_ctx::core::scent_field::deposit_for(
970                project_root,
971                from,
972                lean_ctx::core::scent_field::ScentKind::Done,
973                summary,
974                1.0,
975            );
976
977            format!("Handoff complete: {from} → {target}\nSummary: {summary}")
978        }
979
980        // Stigmergic claim (#540): atomically claim a target (file, task,
981        // deploy unit) in the shared scent field. Fails fast when another
982        // agent's claim is still active — prevents duplicate work for ~0 tokens.
983        "claim" => {
984            let Some(target) = message else {
985                return "Error: message (the claim target, e.g. a file path or task label) is required for claim".to_string();
986            };
987            let agent = current_agent_id.map_or_else(
988                || lean_ctx::core::scent_field::scent_agent_id().to_string(),
989                str::to_string,
990            );
991            let normalized = lean_ctx::core::pathutil::normalize_tool_path(target);
992            match lean_ctx::core::scent_field::claim(project_root, &agent, &normalized) {
993                Ok(()) => {
994                    format!("Claimed: {normalized} (by {agent}, decays in ~10m unless re-claimed)")
995                }
996                Err(e) => format!("Claim REJECTED: {normalized} — {e}"),
997            }
998        }
999
1000        // Release a stigmergic claim early (done or abandoned).
1001        "release" => {
1002            let Some(target) = message else {
1003                return "Error: message (the claim target) is required for release".to_string();
1004            };
1005            let agent = current_agent_id.map_or_else(
1006                || lean_ctx::core::scent_field::scent_agent_id().to_string(),
1007                str::to_string,
1008            );
1009            let normalized = lean_ctx::core::pathutil::normalize_tool_path(target);
1010            lean_ctx::core::scent_field::release(project_root, &agent, &normalized);
1011            format!("Released: {normalized}")
1012        }
1013
1014        // Sub-agent context contract (GL#450): deterministic briefing pack.
1015        // `message` is the task; `priority` doubles as the token budget when
1016        // numeric (default 2000). Same knowledge + task ⇒ byte-identical pack.
1017        "brief" => {
1018            let Some(task) = message else {
1019                return "Error: message (the sub-agent task) is required for brief".to_string();
1020            };
1021            let budget = priority
1022                .and_then(|p| p.parse::<usize>().ok())
1023                .unwrap_or(2000);
1024            let Some(knowledge) = lean_ctx::core::knowledge::ProjectKnowledge::load(project_root)
1025            else {
1026                return "No knowledge stored for this project yet — a briefing pack needs facts. Use ctx_knowledge(action=\"remember\") first.".to_string();
1027            };
1028            // The pack builder leaves out facts that may not be delivered now.
1029            let pack =
1030                lean_ctx::core::subagent_contract::build_briefing_pack(&knowledge, task, budget);
1031            match lean_ctx::core::subagent_contract::serialize_pack(&pack) {
1032                Ok(json) => json,
1033                Err(e) => format!("Error: {e}"),
1034            }
1035        }
1036
1037        // Return synthesis (GL#450): distill a sub-agent's report into
1038        // recallable parent knowledge. Expects contract-formatted lines
1039        // ('category/key: value'); rejects are listed, never silently dropped.
1040        "return" => {
1041            let Some(report) = message else {
1042                return "Error: message (the sub-agent report) is required for return".to_string();
1043            };
1044            let (facts, rejected) = lean_ctx::core::subagent_contract::parse_return_lines(report);
1045            if facts.is_empty() {
1046                return format!(
1047                    "No contract-formatted lines found ({} rejected). Expected 'category/key: value' per line.",
1048                    rejected.len()
1049                );
1050            }
1051
1052            let session_label = current_agent_id.unwrap_or("subagent");
1053            let policy = match crate::tools::knowledge_shared::load_policy_or_error() {
1054                Ok(p) => p,
1055                Err(e) => return e,
1056            };
1057            let count = facts.len();
1058            let res = lean_ctx::core::knowledge::ProjectKnowledge::mutate_locked(
1059                project_root,
1060                |knowledge| {
1061                    for f in &facts {
1062                        knowledge.remember(
1063                            &f.category,
1064                            &f.key,
1065                            &f.value,
1066                            session_label,
1067                            0.8,
1068                            &policy,
1069                        );
1070                    }
1071                },
1072            );
1073            match res {
1074                Ok(_) => {
1075                    let mut out = format!(
1076                        "Return synthesis: {count} fact(s) distilled into parent knowledge"
1077                    );
1078                    if !rejected.is_empty() {
1079                        out.push_str(&format!(
1080                            "\n{} line(s) rejected (not 'category/key: value'):",
1081                            rejected.len()
1082                        ));
1083                        for r in rejected.iter().take(5) {
1084                            out.push_str(&format!("\n  ✗ {r}"));
1085                        }
1086                    }
1087                    out
1088                }
1089                Err(e) => format!("Error: knowledge store update failed: {e}"),
1090            }
1091        }
1092
1093        "sync" => {
1094            let registry = AgentRegistry::mutate_locked(|registry| {
1095                registry.cleanup_stale(presence_ttl_hours());
1096            })
1097            .map(|(registry, ())| registry)
1098            .unwrap_or_else(|_| AgentRegistry::load_or_create());
1099            let pending_count = current_agent_id.map_or(0, |id| {
1100                registry
1101                    .scratchpad
1102                    .iter()
1103                    .filter(|e| {
1104                        !e.read_by.contains(&id.to_string())
1105                            && e.from_agent != id
1106                            && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(id))
1107                            && e.project_root.as_deref().is_some_and(|own| {
1108                                lean_ctx::core::pathutil::same_project(own, project_root)
1109                            })
1110                    })
1111                    .count()
1112            });
1113            let agents = registry.list_active(Some(project_root));
1114
1115            if agents.is_empty() {
1116                return "No active agents to sync with.".to_string();
1117            }
1118
1119            // Only this project's shares (`ctx_share` partitions by project).
1120            let shared_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
1121                .unwrap_or_default()
1122                .join("agents")
1123                .join("shared")
1124                .join(lean_ctx::core::project_hash::hash_project_root(
1125                    project_root,
1126                ));
1127
1128            let shared_count = if shared_dir.exists() {
1129                std::fs::read_dir(&shared_dir).map_or(0, std::iter::Iterator::count)
1130            } else {
1131                0
1132            };
1133
1134            let mut out = "Multi-Agent Sync Status:\n".to_string();
1135            out.push_str(&format!("  Active agents: {}\n", agents.len()));
1136            for a in &agents {
1137                let role = a.role.as_deref().unwrap_or("-");
1138                let age = (lean_ctx_time::UtcDateTime::now() - a.last_active).num_minutes();
1139                out.push_str(&format!(
1140                    "    {} [{}] role={} ({}m ago)\n",
1141                    a.agent_id, a.agent_type, role, age
1142                ));
1143            }
1144            out.push_str(&format!("  Pending messages: {pending_count}\n"));
1145            out.push_str(&format!("  Shared contexts: {shared_count}\n"));
1146
1147            // Stigmergy (#540): arithmetic field view — claims, stuck markers,
1148            // hot files across this project's agents, no scratchpad reads needed.
1149            let scents = lean_ctx::core::scent_field::sync_block(project_root);
1150            if !scents.is_empty() {
1151                out.push_str(&scents);
1152            }
1153            out
1154        }
1155
1156        // Premium control-plane snapshot: one bounded, read-only view of
1157        // presence, messages and persisted Work Graph execution state.
1158        // This keeps agents from guessing whether they should retry, wait or
1159        // integrate, and gives the operator a stable next action.
1160        "control_status" => control_status(project_root, current_agent_id),
1161
1162        "export" => {
1163            let Some(agent_id) = current_agent_id else {
1164                return "Error: agent must be registered first (use action=register)".to_string();
1165            };
1166
1167            fn privacy_label(p: &PrivacyLevel) -> &'static str {
1168                match p {
1169                    PrivacyLevel::Public => "public",
1170                    PrivacyLevel::Team => "team",
1171                    PrivacyLevel::Private => "private",
1172                }
1173            }
1174
1175            fn priority_label(p: &MessagePriority) -> &'static str {
1176                match p {
1177                    MessagePriority::Low => "low",
1178                    MessagePriority::Normal => "normal",
1179                    MessagePriority::High => "high",
1180                    MessagePriority::Critical => "critical",
1181                }
1182            }
1183
1184            fn maybe_redact(s: &str, should_redact: bool) -> String {
1185                if should_redact {
1186                    lean_ctx::core::redaction::redact_text(s)
1187                } else {
1188                    s.to_string()
1189                }
1190            }
1191
1192            #[derive(serde::Serialize)]
1193            struct ExportAgentV1 {
1194                agent_id: String,
1195                agent_type: String,
1196                role: Option<String>,
1197                status: String,
1198                status_message: Option<String>,
1199                started_at: String,
1200                last_active: String,
1201                pid: u32,
1202            }
1203
1204            #[derive(serde::Serialize)]
1205            struct ExportMessageV1 {
1206                id: String,
1207                from_agent: String,
1208                to_agent: Option<String>,
1209                category: String,
1210                privacy: String,
1211                priority: String,
1212                message: String,
1213                metadata: std::collections::BTreeMap<String, String>,
1214                timestamp: String,
1215                expires_at: Option<String>,
1216                read_by_count: usize,
1217            }
1218
1219            #[derive(serde::Serialize)]
1220            struct ExportTaskV1 {
1221                id: String,
1222                from_agent: String,
1223                to_agent: String,
1224                state: String,
1225                description: String,
1226                created_at: String,
1227                updated_at: String,
1228                messages: usize,
1229                artifacts: usize,
1230                transitions: usize,
1231            }
1232
1233            #[derive(serde::Serialize)]
1234            struct ExportDiaryEntryV1 {
1235                entry_type: String,
1236                content: String,
1237                context: Option<String>,
1238                timestamp: String,
1239            }
1240
1241            #[derive(serde::Serialize)]
1242            struct ExportDiaryV1 {
1243                agent_id: String,
1244                agent_type: String,
1245                project_root: String,
1246                updated_at: String,
1247                entries: Vec<ExportDiaryEntryV1>,
1248            }
1249
1250            #[derive(serde::Serialize)]
1251            struct A2ASnapshotV1 {
1252                schema_version: u32,
1253                created_at: String,
1254                project_root: String,
1255                agent_id: String,
1256                agents: Vec<ExportAgentV1>,
1257                messages: Vec<ExportMessageV1>,
1258                tasks: Vec<ExportTaskV1>,
1259                diary: Option<ExportDiaryV1>,
1260            }
1261
1262            let privacy_mode = privacy.unwrap_or("redacted");
1263            let allow_full = privacy_mode == "full"
1264                && !lean_ctx::core::redaction::redaction_enabled_for_active_role();
1265            let should_redact = !allow_full;
1266
1267            let now = lean_ctx_time::UtcDateTime::now();
1268            let mut registry = AgentRegistry::load_or_create();
1269            registry.cleanup_stale(presence_ttl_hours());
1270
1271            let mut agents: Vec<ExportAgentV1> = registry
1272                .list_active(Some(project_root))
1273                .into_iter()
1274                .map(|a| ExportAgentV1 {
1275                    agent_id: a.agent_id.clone(),
1276                    agent_type: a.agent_type.clone(),
1277                    role: a.role.clone(),
1278                    status: a.status.to_string(),
1279                    status_message: a.status_message.clone(),
1280                    started_at: a.started_at.to_rfc3339(),
1281                    last_active: a.last_active.to_rfc3339(),
1282                    pid: a.pid,
1283                })
1284                .collect();
1285            agents.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
1286
1287            let mut messages: Vec<ExportMessageV1> = registry
1288                .scratchpad
1289                .iter()
1290                .filter(|e| {
1291                    e.project_root.as_deref().is_some_and(|own| {
1292                        lean_ctx::core::pathutil::same_project(own, project_root)
1293                    }) && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
1294                })
1295                .take(200)
1296                .map(|m| ExportMessageV1 {
1297                    id: m.id.clone(),
1298                    from_agent: m.from_agent.clone(),
1299                    to_agent: m.to_agent.clone(),
1300                    category: m.category.clone(),
1301                    privacy: privacy_label(&m.privacy).to_string(),
1302                    priority: priority_label(&m.priority).to_string(),
1303                    message: maybe_redact(&m.served_message(Some(project_root)), should_redact),
1304                    // The admission binding is store-internal provenance.
1305                    metadata: m
1306                        .metadata
1307                        .iter()
1308                        .filter(|(k, _)| k.as_str() != lean_ctx::core::agents::BINDING_METADATA_KEY)
1309                        .map(|(k, v)| (k.clone(), maybe_redact(v, should_redact)))
1310                        .collect(),
1311                    timestamp: m.timestamp.to_rfc3339(),
1312                    expires_at: m.expires_at.map(lean_ctx_time::UtcDateTime::to_rfc3339),
1313                    read_by_count: m.read_by.len(),
1314                })
1315                .collect();
1316            messages.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
1317
1318            // Prune and read under the store lock: a concurrent task mutation
1319            // is either fully before or fully after this one, never lost.
1320            // Export runs once per request, so it waits for a busy store
1321            // instead of failing after the default lock timeout.
1322            const EXPORT_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
1323            let tasks = TaskStore::default_path().and_then(|path| {
1324                TaskStore::mutate_locked_within(&path, EXPORT_LOCK_WAIT, |task_store| {
1325                    task_store.cleanup_old(72);
1326                    Ok::<_, std::io::Error>(
1327                        task_store
1328                            .tasks_for_agent(agent_id)
1329                            .into_iter()
1330                            .take(200)
1331                            .map(|t| ExportTaskV1 {
1332                                id: t.id.clone(),
1333                                from_agent: t.from_agent.clone(),
1334                                to_agent: t.to_agent.clone(),
1335                                state: t.state.to_string(),
1336                                description: maybe_redact(&t.served_description(), should_redact),
1337                                created_at: t.created_at.to_rfc3339(),
1338                                updated_at: t.updated_at.to_rfc3339(),
1339                                messages: t.messages.len(),
1340                                artifacts: t.artifacts.len(),
1341                                transitions: t.history.len(),
1342                            })
1343                            .collect::<Vec<ExportTaskV1>>(),
1344                    )
1345                })
1346            });
1347            let mut tasks = match tasks {
1348                Ok(tasks) => tasks,
1349                Err(error) => {
1350                    tracing::warn!("lean-ctx: failed to read task store: {error}");
1351                    return "Error: task storage unavailable".to_string();
1352                }
1353            };
1354            tasks.sort_by(|a, b| {
1355                b.updated_at
1356                    .cmp(&a.updated_at)
1357                    .then_with(|| a.id.cmp(&b.id))
1358            });
1359
1360            let diary =
1361                AgentDiary::load_for_project(agent_id, project_root).map(|d| ExportDiaryV1 {
1362                    agent_id: d.agent_id,
1363                    agent_type: d.agent_type,
1364                    project_root: d.project_root,
1365                    updated_at: d.updated_at.to_rfc3339(),
1366                    entries: d
1367                        .entries
1368                        .iter()
1369                        .rev()
1370                        .take(25)
1371                        .rev()
1372                        .map(|e| ExportDiaryEntryV1 {
1373                            entry_type: e.entry_type.to_string(),
1374                            content: maybe_redact(&e.content, should_redact),
1375                            context: e.context.as_deref().map(|c| maybe_redact(c, should_redact)),
1376                            timestamp: e.timestamp.to_rfc3339(),
1377                        })
1378                        .collect(),
1379                });
1380
1381            let payload = A2ASnapshotV1 {
1382                schema_version: lean_ctx::core::contracts::A2A_SNAPSHOT_V1_SCHEMA_VERSION,
1383                created_at: now.to_rfc3339(),
1384                project_root: project_root.to_string(),
1385                agent_id: agent_id.to_string(),
1386                agents,
1387                messages,
1388                tasks,
1389                diary,
1390            };
1391
1392            let json = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_string());
1393
1394            if write {
1395                let name = filename.map_or_else(
1396                    || format!("a2a-snapshot-v1_{}.json", now.format("%Y%m%d_%H%M%S")),
1397                    str::to_string,
1398                );
1399                let out_path =
1400                    match write_a2a_snapshot(std::path::Path::new(project_root), &name, &json) {
1401                        Ok(path) => path,
1402                        Err(e) => return format!("Error: write snapshot: {e}"),
1403                    };
1404
1405                return format!(
1406                    "A2A snapshot exported: {}\n  agents: {}\n  messages: {}\n  tasks: {}",
1407                    out_path.display(),
1408                    payload.agents.len(),
1409                    payload.messages.len(),
1410                    payload.tasks.len()
1411                );
1412            }
1413
1414            match format.unwrap_or("json") {
1415                "text" => format!(
1416                    "A2A snapshot (v1)\n  agents: {}\n  messages: {}\n  tasks: {}",
1417                    payload.agents.len(),
1418                    payload.messages.len(),
1419                    payload.tasks.len()
1420                ),
1421                _ => json,
1422            }
1423        }
1424
1425        "diary" => {
1426            let Some(agent_id) = current_agent_id else {
1427                return "Error: agent must be registered first".to_string();
1428            };
1429            let Some(content) = message else {
1430                return "Error: message is required for diary entry".to_string();
1431            };
1432            let entry_type = match category.unwrap_or("progress") {
1433                "discovery" | "found" => DiaryEntryType::Discovery,
1434                "decision" | "decided" => DiaryEntryType::Decision,
1435                "blocker" | "blocked" => DiaryEntryType::Blocker,
1436                "progress" | "done" => DiaryEntryType::Progress,
1437                "insight" => DiaryEntryType::Insight,
1438                other => {
1439                    return format!(
1440                        "Unknown diary type: {other}. Use: discovery, decision, blocker, progress, insight"
1441                    );
1442                }
1443            };
1444            let atype = agent_type.unwrap_or("unknown");
1445            let mut diary = AgentDiary::load_or_create(agent_id, atype, project_root);
1446            let context_str = to_agent;
1447            diary.add_entry(entry_type.clone(), content, context_str);
1448            match diary.save() {
1449                Ok(()) => format!("Diary entry [{entry_type}] added: {content}"),
1450                Err(e) => format!("Diary entry added but save failed: {e}"),
1451            }
1452        }
1453
1454        "recall_diary" | "diary_recall" => {
1455            let Some(agent_id) = current_agent_id else {
1456                let diaries = AgentDiary::list_for_project(project_root);
1457                if diaries.is_empty() {
1458                    return "No agent diaries found.".to_string();
1459                }
1460                let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1461                for (id, count, updated) in &diaries {
1462                    let age = (lean_ctx_time::UtcDateTime::now() - *updated).num_minutes();
1463                    out.push_str(&format!("  {id}: {count} entries ({age}m ago)\n"));
1464                }
1465                return out;
1466            };
1467            match AgentDiary::load_for_project(agent_id, project_root) {
1468                Some(diary) => diary.format_summary(),
1469                None => format!("No diary found for agent '{agent_id}'."),
1470            }
1471        }
1472
1473        "diaries" => {
1474            let diaries = AgentDiary::list_for_project(project_root);
1475            if diaries.is_empty() {
1476                return "No agent diaries found.".to_string();
1477            }
1478            let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1479            for (id, count, updated) in &diaries {
1480                let age = (lean_ctx_time::UtcDateTime::now() - *updated).num_minutes();
1481                out.push_str(&format!("  {id}: {count} entries ({age}m ago)\n"));
1482            }
1483            out
1484        }
1485
1486        "share_knowledge" => {
1487            let cat = category.unwrap_or("general");
1488            let Some(msg_text) = message else {
1489                return "Error: message required (format: key1=value1;key2=value2)".to_string();
1490            };
1491            let facts: Vec<(String, String)> = msg_text
1492                .split(';')
1493                .filter_map(|kv| {
1494                    let (k, v) = kv.split_once('=')?;
1495                    Some((k.trim().to_string(), v.trim().to_string()))
1496                })
1497                .collect();
1498            if facts.is_empty() {
1499                return "Error: no valid key=value pairs found".to_string();
1500            }
1501            let Some(from) = current_agent_id else {
1502                return "Error: agent must be registered first".to_string();
1503            };
1504            // Shared knowledge reaches only the agents of this project.
1505            match AgentRegistry::mutate_locked(|registry| {
1506                registry.require_active_for_presence(from, "sharing knowledge")?;
1507                registry.share_knowledge(project_root, from, cat, &facts)
1508            })
1509            .and_then(|(_, shared)| shared)
1510            {
1511                Ok(count) => format!("Shared {count} facts in category '{cat}' with this project"),
1512                Err(e) => format!("Share failed: {e}"),
1513            }
1514        }
1515
1516        "receive_knowledge" => {
1517            let Some(agent_id) = current_agent_id else {
1518                return "Error: agent must be registered first".to_string();
1519            };
1520            let facts = match AgentRegistry::mutate_locked(|registry| {
1521                registry.require_active_for_presence(agent_id, "receiving knowledge")?;
1522                registry.receive_shared_knowledge(project_root, agent_id)
1523            })
1524            .and_then(|(_, facts)| facts)
1525            {
1526                Ok(facts) => facts,
1527                Err(e) => return format!("Receive failed: {e}"),
1528            };
1529            if facts.is_empty() {
1530                return "No new shared knowledge.".to_string();
1531            }
1532            let mut out = format!("Received {} facts:\n", facts.len());
1533            for f in &facts {
1534                let age = (lean_ctx_time::UtcDateTime::now() - f.timestamp).num_minutes();
1535                out.push_str(&format!(
1536                    "  [{}] {} (from {}, {}m ago)\n",
1537                    f.category, f.text, f.from_agent, age
1538                ));
1539            }
1540            out
1541        }
1542
1543        "poll_events" => {
1544            let Some(agent_id) = current_agent_id else {
1545                return "Error: agent must be registered first".to_string();
1546            };
1547            let workspace_id = to_agent.unwrap_or(project_root);
1548            let channel_id = category.unwrap_or("default");
1549            let since_id: i64 = message.and_then(|s| s.parse().ok()).unwrap_or(0);
1550            let limit: usize = _ttl_hours.unwrap_or(50) as usize;
1551
1552            let rt = lean_ctx::core::context_os::runtime();
1553            let events = rt.bus.read(workspace_id, channel_id, since_id, limit);
1554
1555            let filter = lean_ctx::core::context_os::TopicFilter {
1556                agent_id: Some(agent_id.to_string()),
1557                kinds: privacy.and_then(|s| {
1558                    let kinds: Vec<_> = s
1559                        .split(',')
1560                        .map(|k| lean_ctx::core::context_os::ContextEventKindV1::parse(k.trim()))
1561                        .collect();
1562                    if kinds.is_empty() { None } else { Some(kinds) }
1563                }),
1564                ..Default::default()
1565            };
1566
1567            let filtered: Vec<_> = events.into_iter().filter(|e| filter.matches(e)).collect();
1568            if filtered.is_empty() {
1569                return format!("No new events since id={since_id} for {agent_id}.");
1570            }
1571
1572            let mut out = format!("Events ({}, since={since_id}):\n", filtered.len());
1573            for ev in &filtered {
1574                let actor = ev.actor.as_deref().unwrap_or("-");
1575                out.push_str(&format!(
1576                    "  #{} [{}] actor={} cl={} ({})\n",
1577                    ev.id,
1578                    ev.kind,
1579                    actor,
1580                    ev.consistency_level,
1581                    ev.timestamp.format("%H:%M:%S")
1582                ));
1583            }
1584            if let Some(last) = filtered.last() {
1585                out.push_str(&format!("cursor={}", last.id));
1586            }
1587            out
1588        }
1589
1590        // P11: path/symbol leases for mutation planning (see `lease`).
1591        "lease_acquire" => lease::acquire(project_root, current_agent_id, message, _ttl_hours),
1592        "lease_release" => lease::release(project_root, current_agent_id, message, category),
1593        "lease_renew" => lease::renew(
1594            project_root,
1595            current_agent_id,
1596            message,
1597            category,
1598            _ttl_hours,
1599        ),
1600
1601        // This entry point has no `directive_id`/`verdict`/`reason_code`:
1602        // `message` carries the directive id, `category` the verdict and
1603        // `status` the reason code; the registered tool passes all.
1604        "ack" => match handle_ack(current_agent_id, message, category, status, None) {
1605            Ok(text) | Err(text) => text,
1606        },
1607
1608        _ => format!("Unknown action: {action}. Use: {}", ACTIONS.join(", ")),
1609    }
1610}
1611
1612/// Write an exported A2A snapshot to `<project>/.lean-ctx/proofs/<name>` through
1613/// the shared proof destination: a plain file name only, and no symlinked
1614/// `.lean-ctx`, `proofs` or target file.
1615fn write_a2a_snapshot(
1616    project_root: &std::path::Path,
1617    name: &str,
1618    json: &str,
1619) -> Result<std::path::PathBuf, String> {
1620    lean_ctx::core::context_proof::proof_destination(project_root, name)?.write(json)
1621}
1622
1623#[cfg(test)]
1624#[path = "ctx_agent_tests.rs"]
1625mod tests;
1626// SPDX-License-Identifier: Apache-2.0