Skip to main content

lean_ctx/core/
audit_trail.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::fs::{self, OpenOptions};
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct AuditEntry {
9    pub timestamp: String,
10    pub agent_id: String,
11    pub tool: String,
12    pub action: Option<String>,
13    pub input_hash: String,
14    pub output_tokens: u32,
15    pub role: String,
16    pub event_type: AuditEventType,
17    pub prev_hash: String,
18    pub entry_hash: String,
19    /// Ed25519 signature over `entry_hash`, proving provenance from the local
20    /// lean-ctx identity. `None` only when the keypair is unavailable (early boot).
21    #[serde(skip_serializing_if = "Option::is_none", default)]
22    pub signature: Option<String>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum AuditEventType {
27    ToolCall,
28    ToolDenied,
29    PathJailViolation,
30    BudgetExceeded,
31    CrossProjectAccess,
32    RateLimited,
33    SecurityViolation,
34    RoleChanged,
35    SecretDetected,
36    // Agent identity lifecycle (GL #433) — additive OCP Part 4 evolution.
37    AgentRegistered,
38    AgentSuspended,
39    AgentResumed,
40    AgentDecommissioned,
41    /// Attestation drift observed on heartbeat: the running binary and/or
42    /// the active role file no longer match the attestation the registry
43    /// holds for this identity (GL #433 / Phase 18 S3).
44    AgentDriftDetected,
45    /// An operator explicitly acknowledged one specific observed drift,
46    /// naming its evidence. Only this event clears the sticky drift mark —
47    /// resuming a suspended identity does not (GL #433 / Phase 18 S3).
48    AgentDriftAcknowledged,
49    /// Forward-compatible additive event emitted by a newer writer. Keep the
50    /// exact wire label so reports never silently discard security evidence.
51    Unknown(String),
52}
53
54impl AuditEventType {
55    fn wire_label(&self) -> &str {
56        match self {
57            Self::ToolCall => "tool_call",
58            Self::ToolDenied => "tool_denied",
59            Self::PathJailViolation => "path_jail_violation",
60            Self::BudgetExceeded => "budget_exceeded",
61            Self::CrossProjectAccess => "cross_project_access",
62            Self::RateLimited => "rate_limited",
63            Self::SecurityViolation => "security_violation",
64            Self::RoleChanged => "role_changed",
65            Self::SecretDetected => "secret_detected",
66            Self::AgentRegistered => "agent_registered",
67            Self::AgentSuspended => "agent_suspended",
68            Self::AgentResumed => "agent_resumed",
69            Self::AgentDecommissioned => "agent_decommissioned",
70            Self::AgentDriftDetected => "agent_drift_detected",
71            Self::AgentDriftAcknowledged => "agent_drift_acknowledged",
72            Self::Unknown(label) => label,
73        }
74    }
75}
76
77impl Serialize for AuditEventType {
78    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
79    where
80        S: serde::Serializer,
81    {
82        if let Self::Unknown(label) = self {
83            if !valid_unknown_event_label_for_write(label) {
84                return Err(serde::ser::Error::custom(format!(
85                    "unknown event_type is not a safe additive label: {label}"
86                )));
87            }
88        }
89        serializer.serialize_str(self.wire_label())
90    }
91}
92
93impl<'de> Deserialize<'de> for AuditEventType {
94    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
95    where
96        D: serde::Deserializer<'de>,
97    {
98        let label = String::deserialize(deserializer)?;
99        let event_type = match label.as_str() {
100            "tool_call" => Self::ToolCall,
101            "tool_denied" => Self::ToolDenied,
102            "path_jail_violation" => Self::PathJailViolation,
103            "budget_exceeded" => Self::BudgetExceeded,
104            "cross_project_access" => Self::CrossProjectAccess,
105            "rate_limited" => Self::RateLimited,
106            "security_violation" => Self::SecurityViolation,
107            "role_changed" => Self::RoleChanged,
108            "secret_detected" => Self::SecretDetected,
109            "agent_registered" => Self::AgentRegistered,
110            "agent_suspended" => Self::AgentSuspended,
111            "agent_resumed" => Self::AgentResumed,
112            "agent_decommissioned" => Self::AgentDecommissioned,
113            "agent_drift_detected" => Self::AgentDriftDetected,
114            "agent_drift_acknowledged" => Self::AgentDriftAcknowledged,
115            _ if valid_extension_event_label(&label) => Self::Unknown(label),
116            _ => {
117                return Err(serde::de::Error::custom(
118                    "unknown event_type must use the x- extension namespace",
119                ));
120            }
121        };
122        Ok(event_type)
123    }
124}
125
126fn valid_extension_event_label(label: &str) -> bool {
127    const MAX_EVENT_LABEL_BYTES: usize = 64;
128    if label.len() > MAX_EVENT_LABEL_BYTES {
129        return false;
130    }
131    let Some(rest) = label.strip_prefix("x-") else {
132        return false;
133    };
134    let mut chars = rest.chars();
135    chars.next().is_some_and(|c| c.is_ascii_lowercase())
136        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
137}
138
139fn valid_unknown_event_label_for_write(label: &str) -> bool {
140    valid_extension_event_label(label)
141}
142
143pub struct AuditEntryData {
144    pub agent_id: String,
145    pub tool: String,
146    pub action: Option<String>,
147    pub input_hash: String,
148    pub output_tokens: u32,
149    pub role: String,
150    pub event_type: AuditEventType,
151}
152
153pub struct ChainVerifyResult {
154    pub total_entries: usize,
155    pub valid: bool,
156    pub first_invalid_at: Option<usize>,
157    /// Whether the audit trail file existed and was readable. A missing trail
158    /// is a valid empty history for a fresh install, but callers that already
159    /// hold audited state must treat `false` as evidence loss.
160    pub source_present: bool,
161    /// Entries whose `event_type` this build does not know, but whose hash
162    /// links verify. Forward compatibility, NOT corruption: a reader older
163    /// than the writer must report those separately instead of raising a
164    /// false tamper alarm (OCP Part 4 additive-event rule). Actual hash or
165    /// structure damage still sets `valid = false`.
166    pub unknown_event_types: usize,
167}
168
169fn trail_path() -> Option<PathBuf> {
170    let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
171    let audit_dir = dir.join("audit");
172    fs::create_dir_all(&audit_dir).ok()?;
173    Some(audit_dir.join("trail.jsonl"))
174}
175
176/// Read the chain tail from the file itself. Called under the exclusive
177/// file lock — the file is the ONLY source of truth for `prev_hash`. (A
178/// per-process cache forked the chain whenever two processes appended
179/// concurrently — found by `leanctx-verify` on a real trail, GL #425.)
180///
181/// Every I/O failure is propagated instead of being folded into `"genesis"`:
182/// a seek/read error on a NON-empty trail is indistinguishable from an empty
183/// one at that point, so the old fallback silently forked the chain and still
184/// returned `Ok` to a caller (attestation drift) that commits state on it.
185fn read_last_hash_tail(file: &fs::File) -> Result<String, String> {
186    use std::io::{Read, Seek, SeekFrom};
187    const TAIL: i64 = 64 * 1024;
188
189    let mut f = file;
190    let len = f
191        .seek(SeekFrom::End(0))
192        .map_err(|e| format!("audit tail seek: {e}"))?;
193    if len == 0 {
194        return Ok("genesis".to_string());
195    }
196    let start = if (len as i64) > TAIL {
197        -TAIL
198    } else {
199        -(len as i64)
200    };
201    f.seek(SeekFrom::End(start))
202        .map_err(|e| format!("audit tail seek: {e}"))?;
203    let mut buf = String::new();
204    f.read_to_string(&mut buf)
205        .map_err(|e| format!("audit tail read: {e}"))?;
206    // Concurrent-append history may hold multiple objects per line; a
207    // stream parse of the last non-empty line yields the true tail entry.
208    for line in buf.lines().rev() {
209        if line.trim().is_empty() {
210            continue;
211        }
212        let mut last: Option<String> = None;
213        for parsed in serde_json::Deserializer::from_str(line).into_iter::<serde_json::Value>() {
214            let v = parsed.map_err(|e| format!("audit tail parse: {e}"))?;
215            if let Some(h) = v.get("entry_hash").and_then(|h| h.as_str()) {
216                last = Some(h.to_string());
217            }
218        }
219        if let Some(h) = last {
220            return Ok(h);
221        }
222    }
223    // Non-empty file with no parseable entry_hash in the tail window: the
224    // trail exists but has no usable head, so a fresh chain would fork it.
225    Err("audit tail: no readable chain head".to_string())
226}
227
228fn compute_entry_hash(prev_hash: &str, data_json: &str) -> String {
229    let mut hasher = Sha256::new();
230    hasher.update(prev_hash.as_bytes());
231    hasher.update(data_json.as_bytes());
232    crate::core::agent_identity::hex_encode(&hasher.finalize())
233}
234
235/// Fire-and-forget append. The hot tool path must never fail a tool call
236/// because the audit sink is momentarily unavailable, so every error is
237/// swallowed here. Callers whose own state update is only sound *with* the
238/// evidence on disk (agent attestation drift) use [`try_record`] instead.
239pub fn record(data: AuditEntryData) {
240    let _ = try_record(data);
241}
242
243/// How long an append waits for the cross-process trail lock before giving
244/// up. Bounded on purpose: the drift path takes this lock while it holds the
245/// (also deadline-bounded) identity-registry lock, so an unbounded blocking
246/// `flock` would let one stalled process freeze every registry operation.
247const LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(750);
248const LOCK_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);
249
250/// Acquire the exclusive trail lock, bounded by [`LOCK_TIMEOUT`].
251fn lock_trail(file: &fs::File) -> Result<(), String> {
252    lock_trail_with(file, fs2::FileExt::try_lock_exclusive)
253}
254
255/// Acquire a shared trail lock for a reader, bounded by [`LOCK_TIMEOUT`].
256/// Windows file locks are mandatory: a reader without one that ran into an
257/// append's exclusive lock failed mid-file, and the verifier reported that
258/// I/O error as a corrupt chain ("audit chain invalid at entry 0"), e.g. a
259/// heartbeat racing a resume. The shared lock waits for the append and gives
260/// the verifier a consistent snapshot on every platform.
261fn lock_trail_shared(file: &fs::File) -> Result<(), String> {
262    lock_trail_with(file, fs2::FileExt::try_lock_shared)
263}
264
265fn lock_trail_with(
266    file: &fs::File,
267    try_lock: fn(&fs::File) -> std::io::Result<()>,
268) -> Result<(), String> {
269    use std::time::Instant;
270
271    let deadline = Instant::now() + LOCK_TIMEOUT;
272    loop {
273        match try_lock(file) {
274            Ok(()) => return Ok(()),
275            Err(error) if super::file_lock::is_contended(&error) => {
276                if Instant::now() >= deadline {
277                    return Err(format!(
278                        "audit trail lock timed out after {}ms; another append is still active",
279                        LOCK_TIMEOUT.as_millis()
280                    ));
281                }
282                std::thread::sleep(LOCK_RETRY_INTERVAL);
283            }
284            Err(error) => return Err(format!("audit trail lock: {error}")),
285        }
286    }
287}
288
289/// Fallible append. Returns the persisted entry, so a caller can commit its
290/// own state only once the evidence is durable. On `Err` nothing was
291/// appended — a short write is rolled back to the pre-append length — which
292/// makes a retry safe and leaves the hash chain intact.
293///
294/// Durability is AT-LEAST-ONCE, not exactly-once: the line is `fsync`ed, but
295/// the caller's own state file is a separate object with no cross-file
296/// atomicity, so a crash between the two can leave the entry on disk without
297/// the state update. The direction is deliberate — a duplicate observation on
298/// the next attempt, never a lost one.
299pub fn try_record(data: AuditEntryData) -> Result<AuditEntry, String> {
300    let path = trail_path().ok_or_else(|| "audit trail unavailable".to_string())?;
301    try_record_at(&path, data)
302}
303
304/// Append one entry to the trail at an explicit `path` (used by callers that
305/// keep their own chained trail, e.g. value proofs). Errors are swallowed like
306/// [`record`].
307pub fn record_at(path: &Path, data: AuditEntryData) {
308    let _ = try_record_at(path, data);
309}
310
311fn try_record_at(path: &Path, data: AuditEntryData) -> Result<AuditEntry, String> {
312    use fs2::FileExt;
313
314    let mut file = OpenOptions::new()
315        .create(true)
316        .append(true)
317        .read(true)
318        .open(path)
319        .map_err(|e| format!("audit trail open: {e}"))?;
320    // Advisory lock serializes appends ACROSS processes; prev_hash is read
321    // from the file under the same lock, so the chain cannot fork.
322    lock_trail(&file)?;
323    let appended = append_locked(&mut file, data);
324    let _ = FileExt::unlock(&file);
325    appended
326}
327
328/// Build and append one entry. Caller holds the exclusive lock.
329fn append_locked(file: &mut fs::File, data: AuditEntryData) -> Result<AuditEntry, String> {
330    use std::io::{Seek, SeekFrom};
331
332    let prev_hash = read_last_hash_tail(file)?;
333    let authenticated_drift = matches!(
334        &data.event_type,
335        AuditEventType::AgentDriftDetected | AuditEventType::AgentDriftAcknowledged
336    );
337
338    let partial = serde_json::json!({
339        "agent_id": data.agent_id,
340        "tool": data.tool,
341        "action": data.action,
342        "input_hash": data.input_hash,
343        "output_tokens": data.output_tokens,
344        "role": data.role,
345        "event_type": data.event_type,
346    });
347    let data_json = serde_json::to_string(&partial).map_err(|e| format!("audit serialize: {e}"))?;
348    let entry_hash = compute_entry_hash(&prev_hash, &data_json);
349
350    let signature_result =
351        crate::core::agent_identity::sign_bytes("lean-ctx", entry_hash.as_bytes())
352            .map(|sig| crate::core::agent_identity::hex_encode(&sig));
353    let signature = if authenticated_drift {
354        Some(signature_result.map_err(|e| format!("audit signature: {e}"))?)
355    } else {
356        signature_result.ok()
357    };
358
359    let entry = AuditEntry {
360        timestamp: chrono::Utc::now().to_rfc3339(),
361        agent_id: data.agent_id,
362        tool: data.tool,
363        action: data.action,
364        input_hash: data.input_hash,
365        output_tokens: data.output_tokens,
366        role: data.role,
367        event_type: data.event_type,
368        prev_hash,
369        entry_hash,
370        signature,
371    };
372
373    let mut line = serde_json::to_string(&entry).map_err(|e| format!("audit serialize: {e}"))?;
374    line.push('\n');
375    // A short write would leave a truncated JSON line and invalidate the
376    // chain from that point onwards; roll the file back to its pre-append
377    // length so a failed append is a no-op instead of corruption.
378    let rollback_len = file
379        .seek(SeekFrom::End(0))
380        .map_err(|e| format!("audit seek: {e}"))?;
381    if let Err(e) = file
382        .write_all(line.as_bytes())
383        .and_then(|()| file.flush())
384        .and_then(|()| file.sync_data())
385    {
386        let _ = file.set_len(rollback_len);
387        return Err(format!("audit append: {e}"));
388    }
389    Ok(entry)
390}
391
392/// Path of the local audit trail (`<data_dir>/audit/trail.jsonl`).
393pub fn default_trail_path() -> Option<PathBuf> {
394    trail_path()
395}
396
397pub fn load_recent(limit: usize) -> Vec<AuditEntry> {
398    let Some(path) = trail_path() else {
399        return Vec::new();
400    };
401    let entries = load_all_at(&path);
402    let skip = entries.len().saturating_sub(limit);
403    entries.into_iter().skip(skip).collect()
404}
405
406/// Every parseable entry of the trail at `path`.
407pub fn load_all_at(path: &Path) -> Vec<AuditEntry> {
408    let Ok(file) = fs::File::open(path) else {
409        return Vec::new();
410    };
411    // Best effort: without the shared lock a Windows read can stop at an
412    // in-progress append (see `lock_trail_shared`); the listing then ends early.
413    if let Err(error) = lock_trail_shared(&file) {
414        tracing::debug!("audit listing reads unlocked and may end early: {error}");
415    }
416    let reader = std::io::BufReader::new(file);
417    let mut entries = Vec::new();
418    for line in reader.lines().map_while(Result::ok) {
419        entries.extend(
420            serde_json::Deserializer::from_str(&line)
421                .into_iter::<AuditEntry>()
422                .map_while(Result::ok),
423        );
424    }
425    entries
426}
427
428/// Reconstruct the latest unacknowledged drift from the append-only trail.
429/// This is the downgrade-safe source of truth: an older binary may rewrite an
430/// `Attestation` without its newer `drift` field, but it cannot synthesize the
431/// explicit acknowledgement event required to clear this history.
432pub fn latest_unacknowledged_drift(agent_id: &str) -> Result<Option<(String, String)>, String> {
433    let (chain, pending) = verify_chain_with_drift(Some(agent_id));
434    if !chain.source_present {
435        return Err("audit trail unavailable".to_string());
436    }
437    if !chain.valid {
438        return Err(format!(
439            "audit chain invalid at entry {}",
440            chain.first_invalid_at.unwrap_or(chain.total_entries)
441        ));
442    }
443    if chain.total_entries == 0 {
444        // An existing zero-byte trail is evidence loss for any identity that
445        // has already reached an attested state. Keep the generic verifier's
446        // fresh-install view (`valid=true`, `source_present=true`) compatible,
447        // but do not let a caller that reconstructs durable identity state
448        // interpret an emptied trail as a clean history.
449        return Err("audit trail unavailable".to_string());
450    }
451
452    Ok(pending)
453}
454
455/// The hashed field set of an entry, kept as raw JSON values.
456///
457/// The chain hash covers exactly these fields in exactly this order, so a
458/// reader can re-derive it WITHOUT understanding `event_type` — that is what
459/// makes an additive event type verifiable by an older reader (OCP Part 4).
460/// A missing field is a structural defect and yields `None`.
461fn hashed_fields(value: &serde_json::Value) -> Option<serde_json::Value> {
462    let get = |key: &str| value.get(key).cloned();
463    Some(serde_json::json!({
464        "agent_id": get("agent_id")?,
465        "tool": get("tool")?,
466        "action": value.get("action").cloned().unwrap_or(serde_json::Value::Null),
467        "input_hash": get("input_hash")?,
468        "output_tokens": get("output_tokens")?,
469        "role": get("role")?,
470        "event_type": get("event_type")?,
471    }))
472}
473
474fn invalid_at(total: usize, unknown: usize) -> ChainVerifyResult {
475    ChainVerifyResult {
476        total_entries: total,
477        valid: false,
478        first_invalid_at: Some(total),
479        source_present: true,
480        unknown_event_types: unknown,
481    }
482}
483
484fn unavailable() -> ChainVerifyResult {
485    ChainVerifyResult {
486        total_entries: 0,
487        valid: false,
488        first_invalid_at: Some(0),
489        source_present: false,
490        unknown_event_types: 0,
491    }
492}
493
494/// Verify the hash chain over the whole trail.
495///
496/// A namespaced extension entry whose `event_type` this build does not know is counted in
497/// `unknown_event_types` and its links are still verified from the raw
498/// fields — a reader older than the writer must not report a forward-
499/// compatible `x-` event as tampering. Anything else (unparseable line,
500/// missing hashed field, broken `prev_hash` link, wrong `entry_hash`) is
501/// still reported as invalid at its index; corruption is never hidden.
502fn verify_chain_with_drift(
503    agent_id: Option<&str>,
504) -> (ChainVerifyResult, Option<(String, String)>) {
505    let Some(path) = trail_path() else {
506        return (unavailable(), None);
507    };
508    verify_chain_with_drift_at(&path, agent_id)
509}
510
511fn verify_chain_with_drift_at(
512    path: &Path,
513    agent_id: Option<&str>,
514) -> (ChainVerifyResult, Option<(String, String)>) {
515    let empty = ChainVerifyResult {
516        total_entries: 0,
517        valid: true,
518        first_invalid_at: None,
519        source_present: false,
520        unknown_event_types: 0,
521    };
522    let file = match fs::File::open(path) {
523        Ok(file) => file,
524        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return (empty, None),
525        Err(_) => return (unavailable(), None),
526    };
527    // Contention is not corruption: a reader that cannot get the lock in time
528    // reports the trail unavailable (fail-closed), never invalid. The lock is
529    // released when `file` closes at the end of the read.
530    if lock_trail_shared(&file).is_err() {
531        return (unavailable(), None);
532    }
533    let reader = std::io::BufReader::new(file);
534    let mut prev_hash = "genesis".to_string();
535    let mut total = 0usize;
536    let mut unknown = 0usize;
537    let mut pending = None;
538
539    for line_result in reader.lines() {
540        let Ok(line) = line_result else {
541            return (invalid_at(total, unknown), None);
542        };
543        let mut saw_value = false;
544        for parsed in serde_json::Deserializer::from_str(&line).into_iter::<serde_json::Value>() {
545            saw_value = true;
546            let Ok(value) = parsed else {
547                return (invalid_at(total, unknown), None);
548            };
549            let (Some(entry_prev), Some(entry_hash)) = (
550                value.get("prev_hash").and_then(serde_json::Value::as_str),
551                value.get("entry_hash").and_then(serde_json::Value::as_str),
552            ) else {
553                return (invalid_at(total, unknown), None);
554            };
555            let Some(partial) = hashed_fields(&value) else {
556                return (invalid_at(total, unknown), None);
557            };
558            if entry_prev != prev_hash {
559                return (invalid_at(total, unknown), None);
560            }
561            let data_json = serde_json::to_string(&partial).unwrap_or_default();
562            if entry_hash != compute_entry_hash(&prev_hash, &data_json) {
563                return (invalid_at(total, unknown), None);
564            }
565            let entry_hash = entry_hash.to_string();
566            let Ok(entry) = serde_json::from_value::<AuditEntry>(value) else {
567                return (invalid_at(total, unknown), None);
568            };
569            if matches!(&entry.event_type, AuditEventType::Unknown(_)) {
570                unknown += 1;
571            }
572            if matches!(
573                &entry.event_type,
574                AuditEventType::AgentDriftDetected | AuditEventType::AgentDriftAcknowledged
575            ) {
576                let Some(signature) = entry.signature.as_deref() else {
577                    return (invalid_at(total, unknown), None);
578                };
579                let Ok(signature) = crate::core::agent_identity::hex_decode(signature) else {
580                    return (invalid_at(total, unknown), None);
581                };
582                let Ok(public_key) = crate::core::agent_identity::load_public_key("lean-ctx")
583                else {
584                    return (invalid_at(total, unknown), None);
585                };
586                if !crate::core::agent_identity::verify_signature(
587                    public_key.as_bytes(),
588                    entry.entry_hash.as_bytes(),
589                    &signature,
590                ) {
591                    return (invalid_at(total, unknown), None);
592                }
593            }
594            if agent_id == Some(entry.agent_id.as_str()) {
595                match entry.event_type {
596                    AuditEventType::AgentDriftDetected => {
597                        if let Some(evidence) = entry.action {
598                            pending = Some((
599                                entry.timestamp,
600                                format!("{evidence} observation={}", entry.entry_hash),
601                            ));
602                        }
603                    }
604                    AuditEventType::AgentDriftAcknowledged
605                        if pending.as_ref().is_some_and(|(_, evidence)| {
606                            entry.action.as_ref() == Some(evidence)
607                        }) =>
608                    {
609                        pending = None;
610                    }
611                    _ => {}
612                }
613            }
614            prev_hash = entry_hash;
615            total += 1;
616        }
617        if !saw_value {
618            return (invalid_at(total, unknown), None);
619        }
620    }
621
622    (
623        ChainVerifyResult {
624            total_entries: total,
625            valid: true,
626            first_invalid_at: None,
627            source_present: true,
628            unknown_event_types: unknown,
629        },
630        pending,
631    )
632}
633
634pub fn verify_chain() -> ChainVerifyResult {
635    verify_chain_with_drift(None).0
636}
637
638/// Verify the hash chain of the trail at an explicit `path`.
639pub fn verify_chain_at(path: &Path) -> ChainVerifyResult {
640    verify_chain_with_drift_at(path, None).0
641}
642
643pub fn hash_input(args: &serde_json::Map<String, serde_json::Value>) -> String {
644    let serialized = serde_json::to_string(args).unwrap_or_default();
645    let mut hasher = Sha256::new();
646    hasher.update(serialized.as_bytes());
647    crate::core::agent_identity::hex_encode(&hasher.finalize())
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653
654    fn drift_data() -> AuditEntryData {
655        AuditEntryData {
656            agent_id: "drift-agent".to_string(),
657            tool: "agent_registry".to_string(),
658            action: Some("attestation drift dimensions=binary+config".to_string()),
659            input_hash: hash_input(&serde_json::Map::new()),
660            output_tokens: 0,
661            role: "coder".to_string(),
662            event_type: AuditEventType::AgentDriftDetected,
663        }
664    }
665
666    /// The drift event must be a first-class, on-disk-stable event type:
667    /// the OCP Part 4 contract enumerates the snake_case label, so a rename
668    /// would silently invalidate every consumer's schema check.
669    #[test]
670    fn drift_event_type_has_a_stable_wire_label() {
671        let json = serde_json::to_string(&AuditEventType::AgentDriftDetected).expect("serialize");
672        assert_eq!(json, "\"agent_drift_detected\"");
673        let parsed: AuditEventType =
674            serde_json::from_str("\"agent_drift_detected\"").expect("deserialize");
675        assert!(matches!(parsed, AuditEventType::AgentDriftDetected));
676    }
677
678    #[test]
679    fn try_record_appends_a_chained_drift_entry() {
680        let _iso = crate::core::data_dir::isolated_data_dir();
681        let first = try_record(drift_data()).expect("first append");
682        assert_eq!(first.prev_hash, "genesis");
683        let second = try_record(drift_data()).expect("second append");
684        assert_eq!(second.prev_hash, first.entry_hash);
685
686        let entries = load_recent(10);
687        assert_eq!(entries.len(), 2);
688        assert!(
689            entries
690                .iter()
691                .all(|e| matches!(e.event_type, AuditEventType::AgentDriftDetected))
692        );
693        let chain = verify_chain();
694        assert!(
695            chain.valid,
696            "chain must verify: {:?}",
697            chain.first_invalid_at
698        );
699        assert_eq!(chain.total_entries, 2);
700    }
701
702    #[test]
703    fn drift_entries_require_a_valid_local_signature() {
704        let iso = crate::core::data_dir::isolated_data_dir();
705        let entry = try_record(drift_data()).expect("append signed drift");
706        assert!(
707            entry.signature.is_some(),
708            "drift writes must fail without a signature"
709        );
710
711        let path = iso.path().join("audit").join("trail.jsonl");
712        let mut value: serde_json::Value =
713            serde_json::from_str(std::fs::read_to_string(&path).expect("trail").trim_end())
714                .expect("entry JSON");
715        value["signature"] = serde_json::Value::String("00".repeat(64));
716        std::fs::write(
717            &path,
718            format!("{}\n", serde_json::to_string(&value).expect("JSON")),
719        )
720        .expect("forge signature");
721
722        let chain = verify_chain();
723        assert!(
724            !chain.valid,
725            "a hash-linked forged drift entry must fail authentication"
726        );
727        assert_eq!(chain.first_invalid_at, Some(0));
728    }
729
730    /// A blocked sink must surface as an error rather than being swallowed —
731    /// that is the whole reason `try_record` exists. `record` keeps the
732    /// historical fire-and-forget contract on the same failure.
733    #[test]
734    fn try_record_surfaces_sink_failure_that_record_swallows() {
735        let iso = crate::core::data_dir::isolated_data_dir();
736        // A regular file where the audit directory belongs makes
737        // `create_dir_all` fail, so no trail path can be resolved.
738        std::fs::write(iso.path().join("audit"), b"not a directory").expect("block audit dir");
739
740        let error = try_record(drift_data()).expect_err("blocked sink must fail");
741        assert!(error.contains("audit trail unavailable"), "{error}");
742        record(drift_data());
743        assert!(load_recent(10).is_empty(), "nothing may be persisted");
744    }
745
746    #[test]
747    fn unknown_additive_event_verifies_as_forward_compatible_not_tampered() {
748        let _iso = crate::core::data_dir::isolated_data_dir();
749        let path = trail_path().expect("trail path");
750        let event_type = "x-agent_future_observed";
751        let partial = serde_json::json!({
752            "agent_id": "forward-agent",
753            "tool": "agent_registry",
754            "action": null,
755            "input_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
756            "output_tokens": 0,
757            "role": "coder",
758            "event_type": event_type,
759        });
760        let data_json = serde_json::to_string(&partial).expect("partial serializes");
761        let entry_hash = compute_entry_hash("genesis", &data_json);
762        let mut entry = serde_json::json!({
763            "timestamp": "2026-09-06T20:00:00Z",
764            "agent_id": "forward-agent",
765            "tool": "agent_registry",
766            "action": null,
767            "input_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
768            "output_tokens": 0,
769            "role": "coder",
770            "event_type": event_type,
771            "prev_hash": "genesis",
772            "entry_hash": entry_hash,
773        });
774        std::fs::write(
775            &path,
776            format!(
777                "{}\n",
778                serde_json::to_string(&entry).expect("entry serializes")
779            ),
780        )
781        .expect("write forward entry");
782
783        let forward = verify_chain();
784        assert!(forward.valid, "unknown additive event is not tampering");
785        assert_eq!(forward.total_entries, 1);
786        assert_eq!(forward.unknown_event_types, 1);
787        assert_eq!(forward.first_invalid_at, None);
788        let recent = load_recent(1);
789        assert!(matches!(
790            recent.as_slice(),
791            [AuditEntry {
792                event_type: AuditEventType::Unknown(label),
793                ..
794            }] if label == event_type
795        ));
796
797        try_record(drift_data()).expect("append after unknown event");
798        let continued = verify_chain();
799        assert!(continued.valid);
800        assert_eq!(continued.total_entries, 2);
801        assert_eq!(continued.unknown_event_types, 1);
802
803        entry["entry_hash"] = serde_json::json!("0".repeat(64));
804        std::fs::write(
805            &path,
806            format!(
807                "{}\n",
808                serde_json::to_string(&entry).expect("tampered serializes")
809            ),
810        )
811        .expect("write tampered entry");
812        let tampered = verify_chain();
813        assert!(
814            !tampered.valid,
815            "actual hash corruption must remain invalid"
816        );
817        assert_eq!(tampered.first_invalid_at, Some(0));
818    }
819
820    #[test]
821    fn unnamespaced_unknown_event_is_rejected_even_when_hash_linked() {
822        let _iso = crate::core::data_dir::isolated_data_dir();
823        let path = trail_path().expect("trail path");
824        let event_type = "agent_future_observed";
825        let partial = serde_json::json!({
826            "agent_id": "forward-agent",
827            "tool": "agent_registry",
828            "action": null,
829            "input_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
830            "output_tokens": 0,
831            "role": "coder",
832            "event_type": event_type,
833        });
834        let data_json = serde_json::to_string(&partial).expect("partial serializes");
835        let entry_hash = compute_entry_hash("genesis", &data_json);
836        let entry = serde_json::json!({
837            "timestamp": "2026-09-06T20:00:00Z",
838            "agent_id": "forward-agent",
839            "tool": "agent_registry",
840            "action": null,
841            "input_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
842            "output_tokens": 0,
843            "role": "coder",
844            "event_type": event_type,
845            "prev_hash": "genesis",
846            "entry_hash": entry_hash,
847        });
848        std::fs::write(
849            &path,
850            format!("{}\n", serde_json::to_string(&entry).unwrap()),
851        )
852        .expect("write future entry");
853
854        let result = verify_chain();
855        assert!(!result.valid);
856        assert_eq!(result.first_invalid_at, Some(0));
857        assert!(load_recent(1).is_empty());
858    }
859
860    #[test]
861    fn writers_reject_unsafe_unknown_event_labels() {
862        let unsafe_event = AuditEventType::Unknown("future\nlabel".to_string());
863        assert!(serde_json::to_string(&unsafe_event).is_err());
864        assert!(
865            serde_json::to_string(&AuditEventType::Unknown(
866                "agent_future_observed".to_string()
867            ))
868            .is_err()
869        );
870        assert!(
871            serde_json::to_string(&AuditEventType::Unknown(
872                "x-agent_future_observed".to_string()
873            ))
874            .is_ok()
875        );
876        assert!(
877            serde_json::to_string(&AuditEventType::Unknown(format!("x-a{}", "b".repeat(64))))
878                .is_err(),
879            "extension labels must stay report-bounded"
880        );
881    }
882
883    #[test]
884    fn verifier_accepts_legacy_multiple_objects_on_one_line() {
885        let _iso = crate::core::data_dir::isolated_data_dir();
886        try_record(drift_data()).expect("first append");
887        try_record(drift_data()).expect("second append");
888        let path = trail_path().expect("trail path");
889        let joined = std::fs::read_to_string(&path)
890            .expect("audit trail")
891            .lines()
892            .collect::<String>();
893        std::fs::write(&path, format!("{joined}\n")).expect("legacy joined line");
894
895        let chain = verify_chain();
896        assert!(chain.valid, "legacy stream must remain verifiable");
897        assert_eq!(chain.total_entries, 2);
898        assert_eq!(load_recent(2).len(), 2);
899    }
900
901    #[test]
902    fn audited_state_fails_closed_when_trail_disappears() {
903        let _iso = crate::core::data_dir::isolated_data_dir();
904        try_record(drift_data()).expect("append drift");
905        let path = trail_path().expect("trail path");
906        std::fs::remove_file(path).expect("remove audit trail");
907
908        let chain = verify_chain();
909        assert!(chain.valid, "missing file is an empty history generically");
910        assert!(!chain.source_present);
911        let error = latest_unacknowledged_drift("drift-agent").expect_err("evidence loss");
912        assert!(error.contains("unavailable"), "{error}");
913    }
914
915    #[cfg(unix)]
916    #[test]
917    fn audit_lock_contention_is_bounded() {
918        use fs2::FileExt;
919        use std::time::{Duration, Instant};
920
921        let _iso = crate::core::data_dir::isolated_data_dir();
922        let path = trail_path().expect("trail path");
923        let held = OpenOptions::new()
924            .create(true)
925            .truncate(false)
926            .read(true)
927            .write(true)
928            .open(path)
929            .expect("trail lock file");
930        held.lock_exclusive().expect("hold trail lock");
931
932        let started = Instant::now();
933        let error = try_record(drift_data()).expect_err("contention must fail closed");
934        assert!(error.contains("timed out"), "unexpected error: {error}");
935        assert!(
936            started.elapsed() < Duration::from_secs(2),
937            "bounded audit lock exceeded two seconds"
938        );
939    }
940
941    /// A verifier that meets an in-progress append waits for it under a
942    /// shared lock; if the append outlasts the bound, contention reads as an
943    /// unavailable trail, never as corruption ("invalid at entry 0" on
944    /// Windows, where the writer's lock is mandatory).
945    #[test]
946    fn verifier_reports_contention_as_unavailable_not_invalid() {
947        use fs2::FileExt;
948
949        let _iso = crate::core::data_dir::isolated_data_dir();
950        try_record(drift_data()).expect("append drift");
951        let path = trail_path().expect("trail path");
952        let held = OpenOptions::new()
953            .read(true)
954            .write(true)
955            .open(&path)
956            .expect("trail lock file");
957        held.lock_exclusive()
958            .expect("hold trail lock like an append");
959
960        let contended = verify_chain();
961        assert!(
962            !contended.source_present,
963            "contention is not a present-but-invalid trail"
964        );
965        let error = latest_unacknowledged_drift("drift-agent").expect_err("fail closed");
966        assert!(error.contains("unavailable"), "{error}");
967
968        FileExt::unlock(&held).expect("release");
969        let released = verify_chain();
970        assert!(released.valid && released.source_present);
971        assert_eq!(released.total_entries, 1);
972    }
973}