lean-ctx 3.10.3

Local context engine, CLI, MCP server, and proxy for AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! `lean-ctx agent` — first-class agent identities (GL #433).
//!
//! Subcommands: register, list, show, heartbeat, suspend, resume,
//! decommission, offboard-owner, check.

use crate::core::agent_registry::{self, AgentStatus};

pub(crate) fn cmd_agent(args: &[String]) {
    let flag = |name: &str| -> Option<String> {
        args.iter()
            .position(|a| a == name)
            .and_then(|pos| args.get(pos + 1).cloned())
    };
    let positional = |idx: usize| -> Option<String> {
        args.iter()
            .skip(1)
            .filter(|a| !a.starts_with("--"))
            .nth(idx)
            .cloned()
    };
    let as_json = args.iter().any(|a| a == "--json");

    match args.first().map(String::as_str) {
        Some("register") => {
            let (Some(agent_id), Some(role), Some(owner)) =
                (flag("--id"), flag("--role"), flag("--owner"))
            else {
                exit_usage("agent register --id <agent-id> --role <role> --owner <user@org>");
            };
            match agent_registry::register(&agent_id, &role, &owner) {
                Ok(record) => {
                    println!(
                        "registered: {} (role {}, owner {})",
                        record.agent_id, record.role, record.owner
                    );
                    println!("public key: {}", record.public_key);
                    if let Some(att) = &record.attestation {
                        println!(
                            "attested: binary {}…, config {}",
                            &att.binary_sha256[..16.min(att.binary_sha256.len())],
                            if att.config_sha256.is_empty() {
                                "(built-in role)"
                            } else {
                                &att.config_sha256[..16]
                            }
                        );
                    }
                    if let Some(domain) = flag("--trust-domain") {
                        println!("spiffe id: {}", agent_registry::spiffe_id(&record, &domain));
                    }
                }
                Err(e) => exit_err(&e),
            }
        }
        Some("list") => {
            let records = if args.iter().any(|arg| arg == "--all") {
                agent_registry::list()
            } else {
                agent_registry::list_active()
            };
            if as_json {
                print_json_or_exit(&records);
                return;
            }
            if records.is_empty() {
                println!(
                    "no registered agents — start with:\n  lean-ctx agent register --id <agent-id> --role developer --owner you@org"
                );
                return;
            }
            println!(
                "{:<24} {:<12} {:<22} {:<14} heartbeat",
                "AGENT", "ROLE", "OWNER", "STATUS"
            );
            for r in records {
                let status = match r.status {
                    AgentStatus::Active => "active".to_string(),
                    AgentStatus::Suspended => "SUSPENDED".to_string(),
                    AgentStatus::Decommissioned => "decommissioned".to_string(),
                };
                println!(
                    "{:<24} {:<12} {:<22} {:<14} {}",
                    r.agent_id,
                    r.role,
                    r.owner,
                    status,
                    r.last_heartbeat.as_deref().unwrap_or("-")
                );
            }
        }
        Some("presence") => print_local_presence(as_json, args.iter().any(|arg| arg == "--all")),
        Some("show") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent show <agent-id> [--trust-domain org.example]");
            };
            match agent_registry::get(&agent_id) {
                Some(record) => {
                    if as_json {
                        print_json_or_exit(&record);
                    } else {
                        print_json_or_exit(&record);
                        if let Some(domain) = flag("--trust-domain") {
                            println!("spiffe id: {}", agent_registry::spiffe_id(&record, &domain));
                        }
                    }
                }
                None => exit_err(&format!("agent '{agent_id}' is not registered")),
            }
        }
        Some("heartbeat") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent heartbeat <agent-id>");
            };
            match agent_registry::heartbeat(&agent_id) {
                Ok(None) => println!("heartbeat recorded, attestation unchanged"),
                Ok(Some(drift)) => {
                    println!("heartbeat recorded — ATTESTATION DRIFT: {drift}");
                    std::process::exit(3);
                }
                Err(e) => exit_err(&e),
            }
        }
        Some("suspend") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent suspend <agent-id> [--reason <text>]");
            };
            let reason = flag("--reason").unwrap_or_else(|| "manual suspend".to_string());
            match agent_registry::suspend(&agent_id, &reason) {
                Ok(()) => println!("suspended: {agent_id} ({reason})"),
                Err(e) => exit_err(&e),
            }
        }
        Some("resume") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent resume <agent-id>");
            };
            match agent_registry::resume(&agent_id) {
                Ok(()) => println!("resumed: {agent_id}"),
                Err(e) => exit_err(&e),
            }
        }
        Some("decommission") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent decommission <agent-id>");
            };
            match agent_registry::decommission(&agent_id) {
                Ok(()) => println!("decommissioned: {agent_id} (final, audit-closed)"),
                Err(e) => exit_err(&e),
            }
        }
        Some("offboard-owner") => {
            let Some(owner) = positional(0) else {
                exit_usage("agent offboard-owner <user@org> [--reason <text>]");
            };
            let reason = flag("--reason").unwrap_or_else(|| "owner offboarded".to_string());
            match agent_registry::suspend_agents_for_owner(&owner, &reason) {
                Ok(ids) if ids.is_empty() => println!("no active agents owned by {owner}"),
                Ok(ids) => println!("suspended {} agent(s): {}", ids.len(), ids.join(", ")),
                Err(e) => exit_err(&e),
            }
        }
        Some("check") => {
            let Some(agent_id) = positional(0) else {
                exit_usage("agent check <agent-id>");
            };
            let result = agent_registry::check(&agent_id);
            if as_json {
                print_json_or_exit(&result);
            } else {
                println!(
                    "{}: {} — {}",
                    result.agent_id,
                    if result.allowed { "ALLOWED" } else { "DENIED" },
                    result.detail
                );
            }
            if !result.allowed {
                std::process::exit(1);
            }
        }
        _ => {
            println!(
                "lean-ctx agent — first-class agent identities (registered, attested, revocable)\n\n\
USAGE:\n\
  lean-ctx agent register --id <agent-id> --role <role> --owner <user@org>\n\
  lean-ctx agent list [--json] [--all]      list active identities (--all: lifecycle history)\n\
  lean-ctx agent presence [--json] [--all]  inspect local MCP agent liveness\n\
  lean-ctx agent show <agent-id> [--trust-domain org.example]\n\
  lean-ctx agent heartbeat <agent-id>        liveness + attestation drift check\n\
  lean-ctx agent suspend <agent-id> [--reason <text>]\n\
  lean-ctx agent resume <agent-id>\n\
  lean-ctx agent decommission <agent-id>     final — writes the audit-closing entry\n\
  lean-ctx agent offboard-owner <user@org>   suspend all agents of an owner (SCIM hook)\n\
  lean-ctx agent check <agent-id>            enforce-path identity check (exit 1 = deny)\n\n\
Every identity has a mandatory human owner. Lifecycle transitions write\n\
tamper-evident audit entries. Docs: docs/enterprise/agent-identity.md"
            );
        }
    }
}

/// Runtime presence is intentionally separate from `agent list`: the latter
/// is an identity/authorization registry, while this view answers the
/// operational question "which local agents are actually connected and doing
/// work?". A live but quiet MCP process is `idle`, not falsely `active`.
#[derive(serde::Serialize)]
struct LocalPresenceRow {
    id: String,
    agent_type: String,
    role: Option<String>,
    state: &'static str,
    alive: bool,
    last_active: chrono::DateTime<chrono::Utc>,
    age_seconds: i64,
    pid: u32,
    project_root: String,
    status_message: Option<String>,
}

fn local_presence_snapshot(
    registry: &crate::core::agents::AgentRegistry,
    now: chrono::DateTime<chrono::Utc>,
    include_finished: bool,
    compatibility_identities: &crate::core::agents::ProcessIdentityIndex,
) -> Vec<LocalPresenceRow> {
    const ACTIVE_WINDOW_SECONDS: i64 = 60;

    let mut rows: Vec<_> = registry
        .agents
        .iter()
        .filter_map(|agent| {
            let alive = agent
                .process_identity
                .as_ref()
                .or_else(|| compatibility_identities.get(&agent.agent_id))
                .is_some_and(|identity| crate::ipc::process::matches_identity(agent.pid, identity));
            let age_seconds = (now - agent.last_active).num_seconds().max(0);
            let state = if !alive || agent.status == crate::core::agents::AgentStatus::Finished {
                "finished"
            } else if age_seconds <= ACTIVE_WINDOW_SECONDS {
                "active"
            } else {
                "idle"
            };
            (include_finished || state != "finished").then(|| LocalPresenceRow {
                id: agent.agent_id.clone(),
                agent_type: agent.agent_type.clone(),
                role: agent.role.clone(),
                state,
                alive,
                last_active: agent.last_active,
                age_seconds,
                pid: agent.pid,
                project_root: agent.project_root.clone(),
                status_message: agent.status_message.clone(),
            })
        })
        .collect();
    rows.sort_by(|left, right| {
        left.age_seconds
            .cmp(&right.age_seconds)
            .then_with(|| left.id.cmp(&right.id))
    });
    rows
}

fn print_local_presence(as_json: bool, include_finished: bool) {
    const ACTIVE_WINDOW_SECONDS: i64 = 60;

    let registry = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
        registry.cleanup_stale(
            crate::core::config::Config::load()
                .agents
                .presence_ttl_hours,
        );
    })
    .map(|(registry, ())| registry)
    .unwrap_or_else(|_| crate::core::agents::AgentRegistry::load_or_create());
    let compatibility_identities = crate::core::agents::ProcessIdentityIndex::load();
    let rows = local_presence_snapshot(
        &registry,
        chrono::Utc::now(),
        include_finished,
        &compatibility_identities,
    );

    if as_json {
        print_json_or_exit(&serde_json::json!({
            "active_window_seconds": ACTIVE_WINDOW_SECONDS,
            "presence": rows,
        }));
        return;
    }

    if rows.is_empty() {
        println!("no local MCP agent presence detected");
        return;
    }

    println!(
        "{:<24} {:<14} {:<16} {:<10} {:>8}  PROJECT",
        "AGENT", "TYPE", "ROLE", "STATE", "AGE"
    );
    for row in rows {
        println!(
            "{:<24} {:<14} {:<16} {:<10} {:>7}s  {}",
            row.id,
            row.agent_type,
            row.role.as_deref().unwrap_or("-"),
            row.state,
            row.age_seconds,
            row.project_root,
        );
    }
}

fn exit_usage(usage: &str) -> ! {
    eprintln!("usage: lean-ctx {usage}");
    std::process::exit(2);
}

fn print_json_or_exit<T: serde::Serialize>(value: &T) {
    match serde_json::to_string_pretty(value) {
        Ok(json) => println!("{json}"),
        Err(error) => exit_err(&format!("cannot serialize JSON output: {error}")),
    }
}

fn exit_err(message: &str) -> ! {
    eprintln!("agent: {message}");
    std::process::exit(1);
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, Utc};

    use super::local_presence_snapshot;
    use crate::core::agents::{AgentEntry, AgentRegistry, AgentStatus};

    #[test]
    fn presence_snapshot_classifies_and_hides_finished_agents() {
        let now = Utc::now();
        let pid = std::process::id();
        let process_identity = crate::ipc::process::identity(pid)
            .expect("current process must have immutable identity");
        let registry = AgentRegistry {
            agents: vec![
                AgentEntry {
                    agent_id: "active".to_string(),
                    agent_type: "mcp".to_string(),
                    role: Some("coder".to_string()),
                    project_root: "/project".to_string(),
                    started_at: now,
                    last_active: now,
                    pid,
                    process_identity: Some(process_identity.clone()),
                    status: AgentStatus::Active,
                    status_message: None,
                },
                AgentEntry {
                    agent_id: "idle".to_string(),
                    agent_type: "mcp".to_string(),
                    role: None,
                    project_root: "/project".to_string(),
                    started_at: now,
                    last_active: now - Duration::seconds(61),
                    pid,
                    process_identity: Some(process_identity.clone()),
                    status: AgentStatus::Active,
                    status_message: None,
                },
                AgentEntry {
                    agent_id: "finished".to_string(),
                    agent_type: "mcp".to_string(),
                    role: None,
                    project_root: "/project".to_string(),
                    started_at: now,
                    last_active: now,
                    pid,
                    process_identity: Some(process_identity),
                    status: AgentStatus::Finished,
                    status_message: None,
                },
            ],
            scratchpad: vec![],
            logical_sessions: vec![],
            logical_session_telemetry_seen: false,
            updated_at: now,
        };

        let visible = local_presence_snapshot(
            &registry,
            now,
            false,
            &crate::core::agents::ProcessIdentityIndex::default(),
        );
        assert_eq!(visible.len(), 2);
        assert_eq!(visible[0].id, "active");
        assert_eq!(visible[0].state, "active");
        assert_eq!(visible[1].id, "idle");
        assert_eq!(visible[1].state, "idle");

        let all = local_presence_snapshot(
            &registry,
            now,
            true,
            &crate::core::agents::ProcessIdentityIndex::default(),
        );
        assert_eq!(all.len(), 3);
        assert!(all.iter().any(|row| row.state == "finished"));
    }
}