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