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