Skip to main content

lean_ctx/core/
agent_registry.rs

1//! First-class agent identities: registry + lifecycle (GL #433, H3 Epic D).
2//!
3//! An agent stops being an anonymous process with a role config and
4//! becomes a registered identity: stable `agent_id`, mandatory human
5//! `owner` (accountability principle — orphaned agents are the security
6//! hole of the agent era), lifecycle state, best-effort attestation and a
7//! SPIFFE-compatible identity string for workload-IAM integration.
8//!
9//! Storage: `<data_dir>/agents/identity-registry.json`, advisory-file-locked like
10//! the audit trail (multiple concurrent agent processes are LeanCTX's
11//! normal operating mode). Every lifecycle transition writes a
12//! tamper-evident audit entry (OCP Part 4, additive event types).
13
14use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16use std::path::PathBuf;
17
18use super::audit_trail::{self, AuditEntryData, AuditEventType};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum AgentStatus {
23    Active,
24    Suspended,
25    Decommissioned,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Attestation {
30    /// SHA-256 of the running binary at registration/heartbeat time.
31    pub binary_sha256: String,
32    /// SHA-256 of the active role file (empty when the role is built-in).
33    pub config_sha256: String,
34    pub attested_at: String,
35    /// Set when this attestation *replaced* a different one, i.e. drift was
36    /// observed and audited at `attested_at`. Sticky: heartbeat persists the
37    /// freshly observed state, so every later heartbeat is clean by
38    /// construction and auto-clearing would make `block_on_drift` expire
39    /// after a single beat. Cleared ONLY by
40    /// `lean-ctx agent ack-drift <agent-id> --evidence <evidence>`, which
41    /// binds the acknowledgement to the exact evidence the operator
42    /// reviewed. Resuming a suspended identity deliberately does not clear
43    /// it: un-suspending an identity after an unrelated incident must never
44    /// silently sign off attestation drift nobody looked at.
45    ///
46    /// `default` on purpose: a pre-Phase-18 registry has no `drift` key and
47    /// must keep round-tripping as "no unacknowledged drift".
48    #[serde(skip_serializing_if = "Option::is_none", default)]
49    pub drift: Option<DriftMark>,
50}
51
52/// Bounded, non-secret evidence of one observed drift, persisted next to
53/// the attestation and mirrored verbatim into the `AgentDriftDetected`
54/// audit entry.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct DriftMark {
57    pub detected_at: String,
58    /// The running binary changed.
59    pub binary: bool,
60    /// The active role file changed (independent of `binary`).
61    pub config: bool,
62    pub evidence: String,
63}
64
65/// Result of one heartbeat.
66///
67/// `drift` is the identity's *state* after the beat (sticky until
68/// acknowledged), `newly_observed` is the *transition*. Keeping them apart is
69/// the whole point: the monitoring signal must stay red on every beat while
70/// the drift is unacknowledged, but only the beat that first observed it may
71/// append an `AgentDriftDetected` entry — otherwise a one-minute heartbeat
72/// would write one audit entry per minute forever.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct HeartbeatOutcome {
75    pub drift: Option<DriftMark>,
76    pub newly_observed: bool,
77}
78
79#[cfg(test)]
80impl HeartbeatOutcome {
81    /// Evidence of the unacknowledged drift, if any.
82    pub(crate) fn evidence(&self) -> Option<&str> {
83        self.drift.as_ref().map(|mark| mark.evidence.as_str())
84    }
85
86    /// Compatibility view for existing callers: `None` means this beat did
87    /// not observe a new transition, while [`Self::drift`] remains sticky.
88    pub(crate) fn is_none(&self) -> bool {
89        !self.newly_observed
90    }
91
92    /// Compatibility view for existing tests that extracted the newly
93    /// observed evidence from the old `Result<Option<String>, String>` shape.
94    pub(crate) fn expect(self, message: &str) -> String {
95        self.drift
96            .map(|mark| mark.evidence)
97            .unwrap_or_else(|| panic!("{message}"))
98    }
99}
100
101/// A completed, audited drift acknowledgement.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct DriftAcknowledgement {
104    pub agent_id: String,
105    /// The evidence that was cleared — verbatim, as the operator saw it.
106    pub evidence: String,
107    pub detected_at: String,
108    pub acknowledged_at: String,
109}
110
111/// Which attestation dimensions changed. Two independent booleans on
112/// purpose: the previous `if / else if` chain reported binary drift and
113/// silently dropped a simultaneous role-config change.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub(crate) struct DriftDimensions {
116    pub binary: bool,
117    pub config: bool,
118}
119
120impl DriftDimensions {
121    fn any(self) -> bool {
122        self.binary || self.config
123    }
124
125    /// Stable, bounded label — the only place the two dimensions are joined.
126    fn label(self) -> &'static str {
127        match (self.binary, self.config) {
128            (true, true) => "binary+config",
129            (true, false) => "binary",
130            (false, true) => "config",
131            (false, false) => "none",
132        }
133    }
134}
135
136/// Whether unacknowledged attestation drift denies a `check`.
137///
138/// COMPATIBILITY DEFAULT: `block_on_drift = false`. Before this slice drift
139/// was advisory only (the heartbeat printed it, nothing acted on it), so the
140/// default keeps every existing caller's allow/deny bit identical and only
141/// enriches `detail`. Operators opt in with
142/// `LEAN_CTX_AGENT_BLOCK_ON_DRIFT=1|true|yes`.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
144pub(crate) struct DriftPolicy {
145    pub block_on_drift: bool,
146}
147
148impl DriftPolicy {
149    pub(crate) fn from_env() -> Self {
150        Self {
151            block_on_drift: std::env::var("LEAN_CTX_AGENT_BLOCK_ON_DRIFT")
152                .is_ok_and(|value| matches!(value.trim(), "1" | "true" | "yes")),
153        }
154    }
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct AgentRecord {
159    /// Stable identity (key of the registry).
160    pub agent_id: String,
161    /// Role name under `roles/*.toml` / built-ins.
162    pub role: String,
163    /// Human accountable for this agent — mandatory, never empty.
164    pub owner: String,
165    pub status: AgentStatus,
166    pub created_at: String,
167    /// Ed25519 public key (hex) bound to this identity.
168    pub public_key: String,
169    #[serde(skip_serializing_if = "Option::is_none", default)]
170    pub attestation: Option<Attestation>,
171    #[serde(skip_serializing_if = "Option::is_none", default)]
172    pub last_heartbeat: Option<String>,
173    #[serde(skip_serializing_if = "Option::is_none", default)]
174    pub suspended_reason: Option<String>,
175    #[serde(skip_serializing_if = "Option::is_none", default)]
176    pub decommissioned_at: Option<String>,
177}
178
179/// Outcome of an identity check on a call path (team server middleware,
180/// enforce mode).
181#[derive(Debug, Clone, Serialize)]
182pub struct IdentityCheck {
183    pub agent_id: String,
184    pub registered: bool,
185    /// Active = may act. Suspended/decommissioned/unregistered = may not.
186    pub allowed: bool,
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub status: Option<AgentStatus>,
189    /// Unacknowledged attestation drift is recorded on the identity. Whether
190    /// it also flips `allowed` is the caller's `DriftPolicy` decision.
191    pub drifted: bool,
192    pub detail: String,
193}
194
195fn registry_path() -> Result<PathBuf, String> {
196    let dir = crate::core::data_dir::lean_ctx_data_dir()
197        .map_err(|e| format!("data dir: {e}"))?
198        .join("agents");
199    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
200    Ok(dir.join("identity-registry.json"))
201}
202
203fn legacy_registry_path() -> Result<PathBuf, String> {
204    registry_path().map(|path| path.with_file_name("registry.json"))
205}
206
207fn load_unlocked(path: &PathBuf) -> Result<BTreeMap<String, AgentRecord>, String> {
208    let contents = match std::fs::read_to_string(path) {
209        Ok(contents) => contents,
210        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
211            return Ok(BTreeMap::new());
212        }
213        Err(error) => return Err(format!("read registry {}: {error}", path.display())),
214    };
215    serde_json::from_str(&contents)
216        .map_err(|error| format!("parse registry {}: {error}", path.display()))
217}
218
219fn load_registry(path: &PathBuf) -> Result<BTreeMap<String, AgentRecord>, String> {
220    if path.exists() {
221        return load_unlocked(path);
222    }
223    let legacy = legacy_registry_path()?;
224    match load_unlocked(&legacy) {
225        Ok(registry) => Ok(registry),
226        Err(identity_error) => {
227            // `agents/registry.json` is also the MCP presence registry. Its
228            // versioned top-level `agents` array was never an identity map and
229            // must be left untouched rather than treated as corrupt legacy
230            // identity state.
231            let is_presence_registry = std::fs::read_to_string(&legacy)
232                .ok()
233                .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
234                .and_then(|value| value.get("agents").cloned())
235                .is_some_and(|agents| agents.is_array());
236            if is_presence_registry {
237                Ok(BTreeMap::new())
238            } else {
239                Err(identity_error)
240            }
241        }
242    }
243}
244
245/// Read durable identities without interpreting malformed state as an empty
246/// registry. The legacy path is migration input only, never presence state.
247fn load_registry_strict() -> Result<BTreeMap<String, AgentRecord>, String> {
248    let path = registry_path()?;
249    let path = if path.exists() {
250        path
251    } else {
252        legacy_registry_path()?
253    };
254    if !path.exists() {
255        return Ok(BTreeMap::new());
256    }
257    let contents = std::fs::read_to_string(&path)
258        .map_err(|error| format!("read durable identity registry: {error}"))?;
259    serde_json::from_str(&contents)
260        .map_err(|error| format!("durable identity registry is corrupt: {error}"))
261}
262
263/// Run `f` over the registry under an exclusive cross-process lock and
264/// persist the result.
265fn with_registry<T>(
266    f: impl FnOnce(&mut BTreeMap<String, AgentRecord>) -> Result<T, String>,
267) -> Result<T, String> {
268    use fs2::FileExt;
269    use std::time::{Duration, Instant};
270
271    const LOCK_TIMEOUT: Duration = Duration::from_millis(750);
272    const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(25);
273    let path = registry_path()?;
274    let lock_path = path.with_extension("lock");
275    let lock = std::fs::OpenOptions::new()
276        .create(true)
277        .truncate(false)
278        .write(true)
279        .open(&lock_path)
280        .map_err(|e| format!("registry lock: {e}"))?;
281    let deadline = Instant::now() + LOCK_TIMEOUT;
282    let _lock = loop {
283        match lock.try_lock_exclusive() {
284            Ok(()) => break super::file_lock::FlockGuard::from_locked(lock),
285            Err(error) if super::file_lock::is_contended(&error) && Instant::now() < deadline => {
286                std::thread::sleep(LOCK_RETRY_INTERVAL);
287            }
288            Err(error) if super::file_lock::is_contended(&error) => {
289                return Err(format!(
290                    "registry lock timed out after {}ms; another agent operation is still active",
291                    LOCK_TIMEOUT.as_millis()
292                ));
293            }
294            Err(error) => return Err(format!("registry lock: {error}")),
295        }
296    };
297
298    let mut registry = load_registry(&path)?;
299    let result = f(&mut registry);
300    if result.is_ok() {
301        persist_registry(&path, &registry)?;
302    }
303    result
304}
305
306/// Atomic replace: write a sibling temp file, fsync it, rename it over the
307/// registry. An interrupted in-place write left a truncated
308/// `identity-registry.json` behind, and a truncated registry parses as an
309/// *empty* one — silently resurrecting decommissioned identities. A failed
310/// write now leaves the previous snapshot byte-identical and drops the temp.
311fn persist_registry(
312    path: &PathBuf,
313    registry: &BTreeMap<String, AgentRecord>,
314) -> Result<(), String> {
315    use std::io::Write;
316
317    let json = serde_json::to_string_pretty(registry).map_err(|e| format!("serialize: {e}"))?;
318    let tmp = path.with_extension("json.tmp");
319    let written = (|| -> std::io::Result<()> {
320        let mut file = std::fs::File::create(&tmp)?;
321        file.write_all(json.as_bytes())?;
322        file.sync_all()
323    })();
324    if let Err(error) = written {
325        let _ = std::fs::remove_file(&tmp);
326        return Err(format!("persist registry: {error}"));
327    }
328    std::fs::rename(&tmp, path).map_err(|error| {
329        let _ = std::fs::remove_file(&tmp);
330        format!("persist registry: {error}")
331    })
332}
333
334/// Read-only registry snapshot.
335#[cfg(test)]
336pub fn list() -> Vec<AgentRecord> {
337    try_list().unwrap_or_default()
338}
339
340pub fn try_list() -> Result<Vec<AgentRecord>, String> {
341    let path = registry_path()?;
342    Ok(load_registry(&path)?.into_values().collect())
343}
344
345/// Active identities are the peer view. Lifecycle history remains available
346/// through `list()` for audit and operator use.
347#[cfg(test)]
348pub(crate) fn list_active() -> Vec<AgentRecord> {
349    list()
350        .into_iter()
351        .filter(|record| record.status == AgentStatus::Active)
352        .collect()
353}
354
355pub fn try_list_active() -> Result<Vec<AgentRecord>, String> {
356    Ok(try_list()?
357        .into_iter()
358        .filter(|record| record.status == AgentStatus::Active)
359        .collect())
360}
361
362#[cfg(test)]
363pub(crate) fn get(agent_id: &str) -> Option<AgentRecord> {
364    try_get(agent_id).ok().flatten()
365}
366
367pub fn try_get(agent_id: &str) -> Result<Option<AgentRecord>, String> {
368    let path = registry_path()?;
369    Ok(load_registry(&path)?.remove(agent_id))
370}
371
372/// Fail closed unless the explicitly bound durable identity currently exists
373/// and remains active.
374pub(crate) fn require_active(agent_id: &str) -> Result<(), String> {
375    if agent_id.trim().is_empty() {
376        return Err("durable identity id must not be empty".to_string());
377    }
378    let registry = load_registry_strict()?;
379    let Some(record) = registry.get(agent_id) else {
380        return Err(format!("durable identity '{agent_id}' is not registered"));
381    };
382    match record.status {
383        AgentStatus::Active => Ok(()),
384        AgentStatus::Suspended => Err(format!("durable identity '{agent_id}' is suspended")),
385        AgentStatus::Decommissioned => {
386            Err(format!("durable identity '{agent_id}' is decommissioned"))
387        }
388    }
389}
390
391fn audit(event_type: AuditEventType, agent_id: &str, role: &str, detail: Option<String>) {
392    audit_trail::record(AuditEntryData {
393        agent_id: agent_id.to_string(),
394        tool: "agent_registry".to_string(),
395        action: detail,
396        input_hash: audit_trail::hash_input(&serde_json::Map::new()),
397        output_tokens: 0,
398        role: role.to_string(),
399        event_type,
400    });
401}
402
403/// SHA-256 of the running binary, cached by (len, mtime) — heartbeats may
404/// fire every minute and the binary is large; re-hashing is only needed
405/// when the file on disk actually changed (which is exactly the drift
406/// signal we care about, and it changes the mtime).
407///
408/// KNOWN LIMIT: the cache key is metadata, not content. Inside a long-lived
409/// process (the MCP server), a swap that preserves both length and mtime
410/// (`touch -r`) is not re-hashed and evades the binary dimension until the
411/// process restarts. Attestation is a drift detector, not a defence against
412/// an attacker who already controls the host.
413fn binary_sha256() -> String {
414    use std::sync::{Mutex, OnceLock};
415    /// (binary len, binary mtime secs) → hex digest.
416    type HashCache = Mutex<Option<((u64, u64), String)>>;
417    static CACHE: OnceLock<HashCache> = OnceLock::new();
418
419    let Ok(exe) = std::env::current_exe() else {
420        return String::new();
421    };
422    let Ok(meta) = std::fs::metadata(&exe) else {
423        return String::new();
424    };
425    let mtime = meta
426        .modified()
427        .ok()
428        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
429        .map_or(0, |d| d.as_secs());
430    let key = (meta.len(), mtime);
431
432    let cache = CACHE.get_or_init(|| Mutex::new(None));
433    let mut slot = cache
434        .lock()
435        .unwrap_or_else(std::sync::PoisonError::into_inner);
436    if let Some((cached_key, hash)) = slot.as_ref()
437        && *cached_key == key
438    {
439        return hash.clone();
440    }
441    let hash = std::fs::read(&exe)
442        .map(|bytes| sha256_hex(&bytes))
443        .unwrap_or_default();
444    *slot = Some((key, hash.clone()));
445    hash
446}
447
448/// Best-effort attestation: hash the running binary and the role file.
449/// Detects drift; does NOT stop a determined attacker who controls the
450/// host (documented in docs/enterprise/agent-identity.md).
451pub(crate) fn attest(role: &str) -> Attestation {
452    let binary_sha256 = binary_sha256();
453    let config_sha256 = role_file_path(role)
454        .and_then(|p| std::fs::read(p).ok())
455        .map(|bytes| sha256_hex(&bytes))
456        .unwrap_or_default();
457    Attestation {
458        binary_sha256,
459        config_sha256,
460        attested_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
461        drift: None,
462    }
463}
464
465/// Compare two attestations per dimension. Both dimensions are evaluated
466/// unconditionally, so simultaneous binary+config drift reports *both*.
467fn diff_attestation(previous: &Attestation, fresh: &Attestation) -> DriftDimensions {
468    DriftDimensions {
469        binary: previous.binary_sha256 != fresh.binary_sha256,
470        config: previous.config_sha256 != fresh.config_sha256,
471    }
472}
473
474/// Hex characters of each digest kept in the evidence. 48 bits is more than
475/// enough to tell two attestations apart in an audit review and keeps the
476/// evidence string bounded; the digests are public hashes, not secrets.
477const EVIDENCE_DIGEST_PREFIX: usize = 12;
478
479/// Bounded, deterministic, injection-proof rendering of one digest.
480/// Non-hex bytes from a hand-edited registry become `?`, so evidence can
481/// never smuggle a newline or a quote into the JSONL audit line.
482fn digest_prefix(digest: &str) -> String {
483    if digest.is_empty() {
484        return "none".to_string();
485    }
486    digest
487        .chars()
488        .take(EVIDENCE_DIGEST_PREFIX)
489        .map(|c| if c.is_ascii_hexdigit() { c } else { '?' })
490        .collect()
491}
492
493/// Deterministic drift evidence for the audit entry: the changed-dimension
494/// label plus, per changed dimension, the previous and freshly observed
495/// digest prefixes. No paths, no file contents, no owner data — and at most
496/// 110 characters regardless of what the registry holds.
497fn drift_evidence(
498    previous: &Attestation,
499    fresh: &Attestation,
500    dimensions: DriftDimensions,
501) -> String {
502    use std::fmt::Write as _;
503
504    let mut evidence = format!("attestation drift dimensions={}", dimensions.label());
505    if dimensions.binary {
506        let _ = write!(
507            evidence,
508            " binary={}->{}",
509            digest_prefix(&previous.binary_sha256),
510            digest_prefix(&fresh.binary_sha256)
511        );
512    }
513    if dimensions.config {
514        let _ = write!(
515            evidence,
516            " config={}->{}",
517            digest_prefix(&previous.config_sha256),
518            digest_prefix(&fresh.config_sha256)
519        );
520    }
521    evidence
522}
523
524/// Upper bound on any evidence string that reaches an audit line. Matches
525/// what [`drift_evidence`] can produce; applied again on the way *out* of the
526/// registry because that file is operator-writable.
527const EVIDENCE_MAX_CHARS: usize = 256;
528
529/// Re-clamp evidence read back from the registry before it enters a JSONL
530/// audit line: control characters and quoting characters are dropped and the
531/// length is bounded, exactly as for freshly generated evidence.
532fn bounded_evidence(evidence: &str) -> String {
533    evidence
534        .chars()
535        .filter(|c| !c.is_control() && *c != '"' && *c != '\\')
536        .take(EVIDENCE_MAX_CHARS)
537        .collect()
538}
539
540fn validate_drift_mark(mark: DriftMark) -> Result<DriftMark, String> {
541    let validated = bounded_evidence(&mark.evidence);
542    if validated.is_empty() || validated != mark.evidence {
543        return Err("stored drift evidence is invalid or oversized".to_string());
544    }
545    Ok(mark)
546}
547
548/// Append the typed drift event. Fallible on purpose: the caller must not
549/// commit the fresh attestation when the evidence could not be persisted.
550fn audit_drift(agent_id: &str, role: &str, evidence: &str) -> Result<String, String> {
551    audit_trail::try_record(AuditEntryData {
552        agent_id: agent_id.to_string(),
553        tool: "agent_registry".to_string(),
554        action: Some(evidence.to_string()),
555        input_hash: audit_trail::hash_input(&serde_json::Map::new()),
556        output_tokens: 0,
557        role: role.to_string(),
558        event_type: AuditEventType::AgentDriftDetected,
559    })
560    .map(|entry| entry.entry_hash)
561    .map_err(|error| format!("drift audit failed, attestation not updated: {error}"))
562}
563
564/// Append the typed acknowledgement event, naming the exact evidence being
565/// cleared. Fallible for the same reason as [`audit_drift`], in the opposite
566/// direction: an acknowledgement that cannot be recorded must not clear the
567/// mark, or the identity would be allowed again with nothing in the trail
568/// saying anyone signed it off.
569fn audit_drift_ack(agent_id: &str, role: &str, mark: &DriftMark) -> Result<(), String> {
570    let chain = audit_trail::verify_chain();
571    if !chain.source_present {
572        return Err("acknowledgement audit failed, audit trail unavailable".to_string());
573    }
574    if !chain.valid {
575        return Err(format!(
576            "acknowledgement audit failed, audit chain invalid at entry {}",
577            chain.first_invalid_at.unwrap_or(chain.total_entries)
578        ));
579    }
580    let evidence = bounded_evidence(&mark.evidence);
581    if evidence.is_empty() || evidence != mark.evidence {
582        return Err("acknowledgement evidence on record is invalid or oversized".to_string());
583    }
584    audit_trail::try_record(AuditEntryData {
585        agent_id: agent_id.to_string(),
586        tool: "agent_registry".to_string(),
587        action: Some(evidence),
588        input_hash: audit_trail::hash_input(&serde_json::Map::new()),
589        output_tokens: 0,
590        role: role.to_string(),
591        event_type: AuditEventType::AgentDriftAcknowledged,
592    })
593    .map(|_| ())
594    .map_err(|error| format!("acknowledgement audit failed, drift not cleared: {error}"))
595}
596
597fn drift_from_audit(agent_id: &str) -> Result<Option<DriftMark>, String> {
598    let Some((detected_at, evidence)) = audit_trail::latest_unacknowledged_drift(agent_id)? else {
599        return Ok(None);
600    };
601    let validated = bounded_evidence(&evidence);
602    if validated.is_empty() || validated != evidence {
603        return Err("audit drift evidence is invalid or oversized".to_string());
604    }
605    let dimensions = evidence
606        .split_whitespace()
607        .find_map(|part| part.strip_prefix("dimensions="))
608        .unwrap_or("none");
609    Ok(Some(DriftMark {
610        detected_at,
611        binary: matches!(dimensions, "binary" | "binary+config"),
612        config: matches!(dimensions, "config" | "binary+config"),
613        evidence,
614    }))
615}
616
617fn role_file_path(role: &str) -> Option<PathBuf> {
618    let dir = crate::core::data_dir::lean_ctx_data_dir()
619        .ok()?
620        .join("roles");
621    let path = dir.join(format!("{role}.toml"));
622    path.exists().then_some(path)
623}
624
625fn sha256_hex(bytes: &[u8]) -> String {
626    use sha2::{Digest, Sha256};
627    let mut hasher = Sha256::new();
628    hasher.update(bytes);
629    crate::core::agent_identity::hex_encode(&hasher.finalize())
630}
631
632/// Register a new agent identity. The role must exist; the owner is
633/// mandatory (accountability). Creating an identity also provisions its
634/// Ed25519 keypair.
635pub fn register(agent_id: &str, role: &str, owner: &str) -> Result<AgentRecord, String> {
636    if agent_id.trim().is_empty()
637        || !agent_id
638            .chars()
639            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
640    {
641        return Err("agent_id must be non-empty [A-Za-z0-9_-]".to_string());
642    }
643    if owner.trim().is_empty() {
644        return Err(
645            "owner is mandatory — every agent identity has a human accountable for it".to_string(),
646        );
647    }
648    if crate::core::roles::load_role(role).is_none() {
649        return Err(format!(
650            "role '{role}' does not exist (see `lean-ctx roles list`)"
651        ));
652    }
653
654    let public_key = crate::core::agent_identity::get_public_key(agent_id)
655        .map(|k| crate::core::agent_identity::hex_encode(k.as_bytes()))
656        .map_err(|e| format!("keypair: {e}"))?;
657
658    let record = AgentRecord {
659        agent_id: agent_id.to_string(),
660        role: role.to_string(),
661        owner: owner.trim().to_string(),
662        status: AgentStatus::Active,
663        created_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
664        public_key,
665        attestation: Some(attest(role)),
666        last_heartbeat: None,
667        suspended_reason: None,
668        decommissioned_at: None,
669    };
670
671    with_registry(|reg| {
672        if reg.contains_key(agent_id) {
673            return Err(format!("agent '{agent_id}' is already registered"));
674        }
675        reg.insert(agent_id.to_string(), record.clone());
676        Ok(())
677    })?;
678    audit(
679        AuditEventType::AgentRegistered,
680        agent_id,
681        role,
682        Some(format!("owner={}", record.owner)),
683    );
684    Ok(record)
685}
686
687/// Heartbeat: liveness + re-attestation.
688///
689/// Returns the identity's unacknowledged-drift STATE plus whether this beat
690/// is the one that observed it. Every beat reports sticky drift, so a monitor
691/// wired to this call cannot flip back to green one minute after the incident
692/// while `check` still denies; only the observing beat appends evidence.
693///
694/// The freshly observed attestation *replaces* the stored one, so the next
695/// heartbeat compares against reality instead of against registration time
696/// (drift used to be re-reported forever, and a rolled-back binary was
697/// indistinguishable from a fixed one).
698///
699/// Ordering is deliberate and is the fail-safe: the `AgentDriftDetected`
700/// entry is appended BEFORE the registry write, and `with_registry` persists
701/// only when this closure returns `Ok`. A failing audit sink therefore
702/// leaves the stored attestation and `last_heartbeat` untouched and the very
703/// same drift is re-detected on the next beat — never a silent state update
704/// that loses the evidence. The opposite failure (evidence durable, registry
705/// write fails) is safe by the same argument: the registry keeps its
706/// previous snapshot atomically and the next beat re-emits the same
707/// deterministic evidence.
708///
709/// Evidence and registry state are two separate files with no cross-file
710/// atomicity, so the guarantee is AT-LEAST-ONCE, never exactly-once: a crash
711/// between the fsynced append and the registry rename can duplicate an
712/// observation on the next beat. Losing one is what the ordering rules out.
713pub fn heartbeat(agent_id: &str) -> Result<HeartbeatOutcome, String> {
714    with_registry(|reg| {
715        let record = reg
716            .get_mut(agent_id)
717            .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
718        if record.status == AgentStatus::Decommissioned {
719            return Err(format!("agent '{agent_id}' is decommissioned"));
720        }
721        let stored_drift = record
722            .attestation
723            .as_ref()
724            .and_then(|attestation| attestation.drift.clone())
725            .map(validate_drift_mark)
726            .transpose()?;
727        // The append-only audit trail is canonical and is verified on every
728        // heartbeat for an attested identity, even when the registry already
729        // carries a sticky mark. A genuinely pre-attestation legacy record has
730        // no drift state to recover or mask, so its first heartbeat may create
731        // the initial attestation before an audit trail exists.
732        let recovered_drift = match drift_from_audit(agent_id) {
733            Ok(drift) => drift,
734            Err(error)
735                if record.attestation.is_none()
736                    && record.last_heartbeat.is_none()
737                    && error == "audit trail unavailable" =>
738            {
739                None
740            }
741            Err(error) => return Err(error),
742        };
743        let mut fresh = attest(&record.role);
744        let observed = record.attestation.as_ref().and_then(|previous| {
745            let dimensions = diff_attestation(previous, &fresh);
746            dimensions
747                .any()
748                .then(|| (dimensions, drift_evidence(previous, &fresh, dimensions)))
749        });
750
751        match &observed {
752            Some((dimensions, evidence)) => {
753                let observation_id = audit_drift(agent_id, &record.role, evidence)?;
754                fresh.drift = Some(DriftMark {
755                    detected_at: fresh.attested_at.clone(),
756                    binary: dimensions.binary,
757                    config: dimensions.config,
758                    evidence: format!("{evidence} observation={observation_id}"),
759                });
760            }
761            // Carry an unacknowledged mark forward — see `Attestation::drift`.
762            None => {
763                fresh.drift = recovered_drift.or(stored_drift);
764            }
765        }
766
767        record.last_heartbeat = Some(fresh.attested_at.clone());
768        let outcome = HeartbeatOutcome {
769            drift: fresh.drift.clone(),
770            newly_observed: observed.is_some(),
771        };
772        record.attestation = Some(fresh);
773        Ok(outcome)
774    })
775}
776
777pub fn suspend(agent_id: &str, reason: &str) -> Result<(), String> {
778    let role = transition(agent_id, AgentStatus::Suspended, Some(reason.to_string()))?;
779    audit(
780        AuditEventType::AgentSuspended,
781        agent_id,
782        &role,
783        Some(reason.to_string()),
784    );
785    Ok(())
786}
787
788/// Resume is a lifecycle transition ONLY: suspended → active. It deliberately
789/// does not touch the sticky [`DriftMark`] — un-suspending an identity after
790/// an unrelated incident must not silently sign off attestation drift the
791/// operator never saw, and a beat landing between review and resume must not
792/// get acknowledged along the way. Drift is cleared exclusively by
793/// [`acknowledge_drift`], which names the evidence.
794pub fn resume(agent_id: &str) -> Result<(), String> {
795    let role = transition(agent_id, AgentStatus::Active, None)?;
796    audit(AuditEventType::AgentResumed, agent_id, &role, None);
797    Ok(())
798}
799
800/// Explicit operator acknowledgement of ONE observed attestation drift.
801///
802/// `observed_evidence` must equal the evidence currently on the identity, so
803/// an acknowledgement can only ever clear the drift the operator actually
804/// reviewed: if a heartbeat observed a newer change in the meantime, the
805/// stored evidence differs and this fails with both strings, leaving the mark
806/// intact. The typed `AgentDriftAcknowledged` entry is appended BEFORE the
807/// registry mutation and inside the same registry lock, so a failing audit
808/// sink aborts the whole acknowledgement (`with_registry` persists only on
809/// `Ok`) rather than clearing the mark with nothing in the trail.
810///
811/// The `AgentDriftDetected` evidence stays in the trail — acknowledging never
812/// erases history.
813///
814/// The audit trail and registry snapshot are separate files: durability is
815/// AT-LEAST-ONCE, not exactly-once. A crash after the audit fsync but before
816/// the registry rename may require the operator to retry the same evidence;
817/// it can never turn an unrecorded acknowledgement into a cleared mark.
818pub fn acknowledge_drift(
819    agent_id: &str,
820    observed_evidence: &str,
821) -> Result<DriftAcknowledgement, String> {
822    let observed = observed_evidence.to_string();
823    with_registry(|reg| {
824        let record = reg
825            .get_mut(agent_id)
826            .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
827        if record.status == AgentStatus::Decommissioned {
828            return Err(format!(
829                "agent '{agent_id}' is decommissioned — identities are never reactivated"
830            ));
831        }
832        let role = record.role.clone();
833        let mark = drift_from_audit(agent_id)?.ok_or_else(|| {
834            format!("agent '{agent_id}' has no audited unacknowledged attestation drift")
835        })?;
836        if mark.evidence != observed {
837            return Err(format!(
838                "acknowledgement does not match the drift on record — \
839                 you acknowledged: {observed} — current: {} (detected at {}). \
840                 Re-review and acknowledge the current evidence.",
841                mark.evidence, mark.detected_at
842            ));
843        }
844
845        audit_drift_ack(agent_id, &role, &mark)?;
846        if let Some(attestation) = record.attestation.as_mut() {
847            attestation.drift = None;
848        }
849        Ok(DriftAcknowledgement {
850            agent_id: agent_id.to_string(),
851            evidence: mark.evidence,
852            detected_at: mark.detected_at,
853            acknowledged_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
854        })
855    })
856}
857
858/// Decommission closes the identity with a final audit entry; the record
859/// stays in the registry (auditability) but can never act again.
860pub fn decommission(agent_id: &str) -> Result<(), String> {
861    let role = with_registry(|reg| {
862        let record = reg
863            .get_mut(agent_id)
864            .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
865        record.status = AgentStatus::Decommissioned;
866        record.decommissioned_at = Some(lean_ctx_time::UtcDateTime::now().to_rfc3339());
867        Ok(record.role.clone())
868    })?;
869    audit(
870        AuditEventType::AgentDecommissioned,
871        agent_id,
872        &role,
873        Some("audit-closing entry".to_string()),
874    );
875    Ok(())
876}
877
878fn transition(agent_id: &str, to: AgentStatus, reason: Option<String>) -> Result<String, String> {
879    with_registry(|reg| {
880        let record = reg
881            .get_mut(agent_id)
882            .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
883        if record.status == AgentStatus::Decommissioned {
884            return Err(format!(
885                "agent '{agent_id}' is decommissioned — identities are never reactivated"
886            ));
887        }
888        record.status = to;
889        record.suspended_reason = reason;
890        Ok(record.role.clone())
891    })
892}
893
894/// Owner offboarding (SCIM `active=false` hook, GL #399): suspend every
895/// active agent owned by `owner`. Returns the suspended agent ids.
896pub fn suspend_agents_for_owner(owner: &str, reason: &str) -> Result<Vec<String>, String> {
897    let suspended = with_registry(|reg| {
898        let mut hit = Vec::new();
899        for record in reg.values_mut() {
900            if record.owner == owner && record.status == AgentStatus::Active {
901                record.status = AgentStatus::Suspended;
902                record.suspended_reason = Some(reason.to_string());
903                hit.push((record.agent_id.clone(), record.role.clone()));
904            }
905        }
906        Ok(hit)
907    })?;
908    for (agent_id, role) in &suspended {
909        audit(
910            AuditEventType::AgentSuspended,
911            agent_id,
912            role,
913            Some(format!("owner offboarded: {reason}")),
914        );
915    }
916    Ok(suspended.into_iter().map(|(id, _)| id).collect())
917}
918
919/// Identity check for enforce paths (team-server middleware): registered
920/// AND active. Unregistered agents are reported (monitor mode logs,
921/// enforce mode rejects — the caller decides).
922///
923/// Drift policy comes from the environment; see `DriftPolicy` for the
924/// documented compatibility default (drift is reported, never blocking).
925pub fn check(agent_id: &str) -> IdentityCheck {
926    check_with_policy(agent_id, DriftPolicy::from_env())
927}
928
929/// [`check`] with an explicit drift decision — the deterministic entry point
930/// for callers that carry their own policy instead of reading the process
931/// environment.
932pub(crate) fn check_with_policy(agent_id: &str, policy: DriftPolicy) -> IdentityCheck {
933    let record = match try_get(agent_id) {
934        Ok(record) => record,
935        Err(error) => {
936            return IdentityCheck {
937                agent_id: agent_id.to_string(),
938                registered: false,
939                allowed: false,
940                status: None,
941                drifted: false,
942                detail: format!("denied, registry unavailable: {error}"),
943            };
944        }
945    };
946    match record {
947        None => IdentityCheck {
948            agent_id: agent_id.to_string(),
949            registered: false,
950            allowed: false,
951            status: None,
952            drifted: false,
953            detail: "not registered — register with `lean-ctx agent register`".to_string(),
954        },
955        Some(record) => {
956            let stored_drift = record
957                .attestation
958                .as_ref()
959                .and_then(|attestation| attestation.drift.clone())
960                .map(validate_drift_mark)
961                .transpose();
962            let (drift, audit_error) = match drift_from_audit(agent_id) {
963                Ok(audit_drift) => match stored_drift {
964                    Ok(stored) => (audit_drift.or(stored), None),
965                    Err(error) => (audit_drift, Some(error)),
966                },
967                Err(error) => (stored_drift.unwrap_or(None), Some(error)),
968            };
969            let blocked_by_drift = policy.block_on_drift && drift.is_some();
970            let allowed =
971                record.status == AgentStatus::Active && !blocked_by_drift && audit_error.is_none();
972            IdentityCheck {
973                agent_id: agent_id.to_string(),
974                registered: true,
975                allowed,
976                status: Some(record.status),
977                // Evidence loss is an unknown/red state, never a green signal.
978                drifted: drift.is_some() || audit_error.is_some(),
979                detail: match record.status {
980                    AgentStatus::Active => match (drift.as_ref(), audit_error.as_ref()) {
981                        (_, Some(error)) => {
982                            format!("denied, audit state unavailable: {error}")
983                        }
984                        (Some(mark), _) if policy.block_on_drift => {
985                            format!("denied, unacknowledged {}", mark.evidence)
986                        }
987                        (Some(mark), _) => format!(
988                            "active, owner {} (advisory: unacknowledged {})",
989                            record.owner, mark.evidence
990                        ),
991                        (None, None) => format!("active, owner {}", record.owner),
992                    },
993                    AgentStatus::Suspended => format!(
994                        "suspended: {}",
995                        record.suspended_reason.as_deref().unwrap_or("no reason")
996                    ),
997                    AgentStatus::Decommissioned => "decommissioned".to_string(),
998                },
999            }
1000        }
1001    }
1002}
1003
1004/// SPIFFE-compatible workload identity:
1005/// `spiffe://<trust_domain>/agent/<role>/<agent_id>`.
1006pub fn spiffe_id(record: &AgentRecord, trust_domain: &str) -> String {
1007    format!(
1008        "spiffe://{}/agent/{}/{}",
1009        trust_domain.trim_matches('/'),
1010        record.role,
1011        record.agent_id
1012    )
1013}
1014
1015#[cfg(test)]
1016#[path = "agent_registry_tests.rs"]
1017mod tests;
1018
1019/// Adversarial attestation-drift coverage (Phase 18 S3), with access to private helpers.
1020#[cfg(test)]
1021#[path = "agent_registry_drift_tests.rs"]
1022mod drift_tests;