use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::{self, OpenOptions};
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
mod checkpoint;
mod segments;
mod v2;
mod verify;
#[cfg(test)]
use verify::verify_chain_mode_at;
use verify::{ChainState, verify_chain_with_drift};
pub use verify::{
SignedTallyEvidence, verified_security_at, verified_signed_tally_at, verify_chain,
verify_chain_at, verify_chain_full,
};
pub use v2::{
AuditDecision, ENTRY_VERSION, HMAC_PREFIX, SessionFacts, hmac_hex, keyed_digest,
keyed_input_digest, load_or_create_hmac_key,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
pub timestamp: String,
pub agent_id: String,
pub tool: String,
pub action: Option<String>,
pub input_hash: String,
pub output_tokens: u32,
pub role: String,
pub event_type: AuditEventType,
pub prev_hash: String,
pub entry_hash: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub signature: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub v: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub seq: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub instance_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub policy_digest: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub decision: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub output_digest: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub v2_hash: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuditEventType {
ToolCall,
ToolDenied,
PathJailViolation,
BudgetExceeded,
CrossProjectAccess,
RateLimited,
SecurityViolation,
RoleChanged,
SecretDetected,
AgentRegistered,
AgentSuspended,
AgentResumed,
AgentDecommissioned,
AgentDriftDetected,
AgentDriftAcknowledged,
ProjectAdopted,
Unknown(String),
}
pub const PROJECT_ADOPTED_EVENT: &str = "x-project_adopted";
impl AuditEventType {
fn wire_label(&self) -> &str {
match self {
Self::ToolCall => "tool_call",
Self::ToolDenied => "tool_denied",
Self::PathJailViolation => "path_jail_violation",
Self::BudgetExceeded => "budget_exceeded",
Self::CrossProjectAccess => "cross_project_access",
Self::RateLimited => "rate_limited",
Self::SecurityViolation => "security_violation",
Self::RoleChanged => "role_changed",
Self::SecretDetected => "secret_detected",
Self::AgentRegistered => "agent_registered",
Self::AgentSuspended => "agent_suspended",
Self::AgentResumed => "agent_resumed",
Self::AgentDecommissioned => "agent_decommissioned",
Self::AgentDriftDetected => "agent_drift_detected",
Self::AgentDriftAcknowledged => "agent_drift_acknowledged",
Self::ProjectAdopted => PROJECT_ADOPTED_EVENT,
Self::Unknown(label) => label,
}
}
}
impl Serialize for AuditEventType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if let Self::Unknown(label) = self {
if !valid_unknown_event_label_for_write(label) {
return Err(serde::ser::Error::custom(format!(
"unknown event_type is not a safe additive label: {label}"
)));
}
}
serializer.serialize_str(self.wire_label())
}
}
impl<'de> Deserialize<'de> for AuditEventType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let label = String::deserialize(deserializer)?;
let event_type = match label.as_str() {
"tool_call" => Self::ToolCall,
"tool_denied" => Self::ToolDenied,
"path_jail_violation" => Self::PathJailViolation,
"budget_exceeded" => Self::BudgetExceeded,
"cross_project_access" => Self::CrossProjectAccess,
"rate_limited" => Self::RateLimited,
"security_violation" => Self::SecurityViolation,
"role_changed" => Self::RoleChanged,
"secret_detected" => Self::SecretDetected,
"agent_registered" => Self::AgentRegistered,
"agent_suspended" => Self::AgentSuspended,
"agent_resumed" => Self::AgentResumed,
"agent_decommissioned" => Self::AgentDecommissioned,
"agent_drift_detected" => Self::AgentDriftDetected,
"agent_drift_acknowledged" => Self::AgentDriftAcknowledged,
PROJECT_ADOPTED_EVENT => Self::ProjectAdopted,
_ if valid_extension_event_label(&label) => Self::Unknown(label),
_ => {
return Err(serde::de::Error::custom(
"unknown event_type must use the x- extension namespace",
));
}
};
Ok(event_type)
}
}
fn valid_extension_event_label(label: &str) -> bool {
const MAX_EVENT_LABEL_BYTES: usize = 64;
if label.len() > MAX_EVENT_LABEL_BYTES {
return false;
}
let Some(rest) = label.strip_prefix("x-") else {
return false;
};
let mut chars = rest.chars();
chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
fn valid_unknown_event_label_for_write(label: &str) -> bool {
valid_extension_event_label(label)
}
pub struct AuditEntryData {
pub agent_id: String,
pub tool: String,
pub action: Option<String>,
pub input_hash: String,
pub output_tokens: u32,
pub role: String,
pub event_type: AuditEventType,
}
pub struct ChainVerifyResult {
pub total_entries: usize,
pub valid: bool,
pub first_invalid_at: Option<usize>,
pub source_present: bool,
pub unknown_event_types: usize,
}
fn trail_path() -> Option<PathBuf> {
let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
let audit_dir = dir.join("audit");
fs::create_dir_all(&audit_dir).ok()?;
Some(audit_dir.join("trail.jsonl"))
}
fn read_tail(file: &fs::File) -> Result<Tail, String> {
Ok(Tail::after(read_tail_entry(file)?.as_ref()))
}
#[derive(Clone)]
struct Tail {
prev_hash: String,
head: String,
}
impl Tail {
fn after(entry: Option<&serde_json::Value>) -> Self {
let prev_hash = entry
.and_then(|entry| entry.get("entry_hash")?.as_str())
.unwrap_or("genesis")
.to_string();
let head = entry
.and_then(|entry| v2::head_of(entry, v2::version_of(entry)?))
.unwrap_or_else(|| prev_hash.clone());
Self { prev_hash, head }
}
}
fn read_tail_entry(file: &fs::File) -> Result<Option<serde_json::Value>, String> {
use std::io::{Read, Seek, SeekFrom};
const TAIL: i64 = 64 * 1024;
let mut f = file;
let len = f
.seek(SeekFrom::End(0))
.map_err(|e| format!("audit tail seek: {e}"))?;
if len == 0 {
return Ok(None);
}
let start = if (len as i64) > TAIL {
-TAIL
} else {
-(len as i64)
};
f.seek(SeekFrom::End(start))
.map_err(|e| format!("audit tail seek: {e}"))?;
let mut buf = String::new();
f.read_to_string(&mut buf)
.map_err(|e| format!("audit tail read: {e}"))?;
for line in buf.lines().rev() {
if line.trim().is_empty() {
continue;
}
let mut last: Option<serde_json::Value> = None;
for parsed in serde_json::Deserializer::from_str(line).into_iter::<serde_json::Value>() {
let v = parsed.map_err(|e| format!("audit tail parse: {e}"))?;
if v.get("entry_hash").and_then(|h| h.as_str()).is_some() {
last = Some(v);
}
}
if last.is_some() {
return Ok(last);
}
}
Err("audit tail: no readable chain head".to_string())
}
fn compute_entry_hash(prev_hash: &str, data_json: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(prev_hash.as_bytes());
hasher.update(data_json.as_bytes());
crate::core::agent_identity::hex_encode(&hasher.finalize())
}
pub fn record(data: AuditEntryData) {
let _ = try_record(data);
}
const LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(750);
const LOCK_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);
fn lock_trail(file: &fs::File) -> Result<(), String> {
lock_trail_with(file, fs2::FileExt::try_lock_exclusive)
}
fn lock_trail_shared(file: &fs::File) -> Result<(), String> {
lock_trail_with(file, fs2::FileExt::try_lock_shared)
}
fn release_read_lock(file: &fs::File) {
#[cfg(not(windows))]
let _ = fs2::FileExt::unlock(file);
#[cfg(windows)]
let _ = file;
}
fn still_holds_prefix(file: &fs::File, len: u64) -> bool {
file.metadata().is_ok_and(|meta| meta.len() >= len)
}
fn lock_trail_with(
file: &fs::File,
try_lock: fn(&fs::File) -> std::io::Result<()>,
) -> Result<(), String> {
use std::time::Instant;
let deadline = Instant::now() + LOCK_TIMEOUT;
loop {
match try_lock(file) {
Ok(()) => return Ok(()),
Err(error) if super::file_lock::is_contended(&error) => {
if Instant::now() >= deadline {
return Err(format!(
"audit trail lock timed out after {}ms; another append is still active",
LOCK_TIMEOUT.as_millis()
));
}
std::thread::sleep(LOCK_RETRY_INTERVAL);
}
Err(error) => return Err(format!("audit trail lock: {error}")),
}
}
}
pub fn try_record(data: AuditEntryData) -> Result<AuditEntry, String> {
let path = trail_path().ok_or_else(|| "audit trail unavailable".to_string())?;
try_record_at(&path, data)
}
pub fn record_at(path: &Path, data: AuditEntryData) {
let _ = try_record_at(path, data);
}
fn try_record_at(path: &Path, data: AuditEntryData) -> Result<AuditEntry, String> {
try_record_at_time(
path,
Record { data, facts: None },
lean_ctx_time::UtcDateTime::now(),
)
}
pub fn record_v2(data: AuditEntryData, facts: SessionFacts) {
let _ = try_record_v2(data, facts);
}
pub fn try_record_v2(data: AuditEntryData, facts: SessionFacts) -> Result<AuditEntry, String> {
let path = trail_path().ok_or_else(|| "audit trail unavailable".to_string())?;
try_record_v2_at(&path, data, facts)
}
pub fn try_record_v2_at(
path: &Path,
data: AuditEntryData,
facts: SessionFacts,
) -> Result<AuditEntry, String> {
if facts.session_id.is_empty() {
return Err("audit v2: empty session id".to_string());
}
let record = Record {
data,
facts: Some(facts),
};
try_record_at_time(path, record, lean_ctx_time::UtcDateTime::now())
}
struct Record {
data: AuditEntryData,
facts: Option<SessionFacts>,
}
fn try_record_at_time(
path: &Path,
record: Record,
now: lean_ctx_time::UtcDateTime,
) -> Result<AuditEntry, String> {
let mut record = record;
for _ in 0..SNAPSHOT_ATTEMPTS {
let mut file = open_active_locked(path)?;
let appended = append_or_seal(path, &mut file, record, now);
let _ = fs2::FileExt::unlock(&file);
match appended? {
Appended::Done(entry) => return Ok(entry),
Appended::Moved(back) => record = back,
}
}
Err("audit trail: the active file kept moving".to_string())
}
enum Appended {
Done(AuditEntry),
Moved(Record),
}
fn open_active_locked(path: &Path) -> Result<fs::File, String> {
for _ in 0..SNAPSHOT_ATTEMPTS {
let file = OpenOptions::new()
.create(true)
.append(true)
.read(true)
.open(path)
.map_err(|e| format!("audit trail open: {e}"))?;
lock_trail(&file)?;
if is_current(path, &file) {
return Ok(file);
}
let _ = fs2::FileExt::unlock(&file);
}
Err("audit trail: the active file kept moving".to_string())
}
fn is_current(path: &Path, file: &fs::File) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
match (fs::metadata(path), file.metadata()) {
(Ok(named), Ok(open)) => (named.dev(), named.ino()) == (open.dev(), open.ino()),
_ => false,
}
}
#[cfg(not(unix))]
{
let _ = (path, file);
true
}
}
fn append_or_seal(
path: &Path,
file: &mut fs::File,
record: Record,
now: lean_ctx_time::UtcDateTime,
) -> Result<Appended, String> {
let Some(last) = read_tail_entry(file)? else {
let tail = match segments::sealed(path).last() {
Some((_, segment)) => fs::File::open(segment)
.map_err(|e| format!("audit segment open: {e}"))
.and_then(|segment| read_tail(&segment))?,
None => Tail::after(None),
};
return append_locked(file, record, tail).map(Appended::Done);
};
let last_tail = Tail::after(Some(&last));
let next_seq = segments::sealed(path).last().map_or(0, |(seq, _)| seq + 1);
let sealed_seq = if last.get("event_type").and_then(serde_json::Value::as_str)
== Some(segments::SEAL_EVENT)
{
segments::sealed_seq(last.get("action").and_then(serde_json::Value::as_str))
} else {
None
};
let len = file
.metadata()
.map_err(|e| format!("audit stat: {e}"))?
.len();
let last_at = last.get("timestamp").and_then(serde_json::Value::as_str);
let seq = match sealed_seq {
Some(seq) if seq == next_seq => seq,
Some(seq) if seq < next_seq => return Ok(Appended::Moved(record)),
_ if segments::due(len, last_at, now)
&& !segments::backing_off()
&& verified_once(path, file) =>
{
let seal = Record {
data: seal_data(next_seq),
facts: None,
};
append_locked(file, seal, last_tail)?;
next_seq
}
_ => return append_locked(file, record, last_tail).map(Appended::Done),
};
match segments::retire(path, seq) {
Ok(()) => Ok(Appended::Moved(record)),
Err(error) => {
tracing::warn!("audit trail not sealed: {error}");
segments::back_off();
let tail = read_tail(file)?;
append_locked(file, record, tail).map(Appended::Done)
}
}
}
fn verified_once(path: &Path, file: &fs::File) -> bool {
let Some(store) = checkpoint::Store::for_trail(path) else {
return false;
};
checkpoint::FileStamp::of(file).is_some_and(|stamp| store.holds_prefix_of(file, &stamp))
}
fn seal_data(seq: u64) -> AuditEntryData {
AuditEntryData {
agent_id: "lean-ctx".to_string(),
tool: "audit_trail".to_string(),
action: Some(segments::seal_action(seq)),
input_hash: String::new(),
output_tokens: 0,
role: "system".to_string(),
event_type: AuditEventType::Unknown(segments::SEAL_EVENT.to_string()),
}
}
pub fn is_seal(event_type: &AuditEventType) -> bool {
matches!(event_type, AuditEventType::Unknown(label) if label == segments::SEAL_EVENT)
}
fn append_locked(file: &mut fs::File, record: Record, tail: Tail) -> Result<AuditEntry, String> {
use std::io::{Seek, SeekFrom};
let Record { data, facts } = record;
let Tail { prev_hash, head } = tail;
let authenticated_drift = matches!(
&data.event_type,
AuditEventType::AgentDriftDetected | AuditEventType::AgentDriftAcknowledged
) || is_seal(&data.event_type);
let partial = serde_json::json!({
"agent_id": data.agent_id,
"tool": data.tool,
"action": data.action,
"input_hash": data.input_hash,
"output_tokens": data.output_tokens,
"role": data.role,
"event_type": data.event_type,
});
let data_json = serde_json::to_string(&partial).map_err(|e| format!("audit serialize: {e}"))?;
let entry_hash = compute_entry_hash(&prev_hash, &data_json);
let signature_result =
crate::core::agent_identity::sign_bytes("lean-ctx", entry_hash.as_bytes())
.map(|sig| crate::core::agent_identity::hex_encode(&sig));
let signature = if authenticated_drift {
Some(signature_result.map_err(|e| format!("audit signature: {e}"))?)
} else {
signature_result.ok()
};
let facts = facts.map(|facts| {
let seq = v2::next_seq(&facts.session_id);
(facts, seq)
});
let (session_id, seq, instance_id, policy_digest, decision, output_digest) = match facts {
Some((facts, seq)) => (
Some(facts.session_id),
Some(seq),
facts.instance_id,
facts.policy_digest,
Some(facts.decision.as_str().to_string()),
facts.output_digest,
),
None => (None, None, None, None, None, None),
};
let mut entry = AuditEntry {
timestamp: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
agent_id: data.agent_id,
tool: data.tool,
action: data.action,
input_hash: data.input_hash,
output_tokens: data.output_tokens,
role: data.role,
event_type: data.event_type,
prev_hash,
entry_hash,
signature,
v: Some(ENTRY_VERSION),
session_id,
seq,
instance_id,
policy_digest,
decision,
output_digest,
v2_hash: None,
};
let raw = serde_json::to_value(&entry).map_err(|e| format!("audit serialize: {e}"))?;
let fields = v2::v2_fields(&raw).ok_or_else(|| "audit v2: malformed facts".to_string())?;
entry.v2_hash = Some(v2::compute_v2_hash(&head, &fields));
let mut line = serde_json::to_string(&entry).map_err(|e| format!("audit serialize: {e}"))?;
line.push('\n');
let rollback_len = file
.seek(SeekFrom::End(0))
.map_err(|e| format!("audit seek: {e}"))?;
if let Err(e) = file
.write_all(line.as_bytes())
.and_then(|()| file.flush())
.and_then(|()| file.sync_data())
{
let _ = file.set_len(rollback_len);
return Err(format!("audit append: {e}"));
}
Ok(entry)
}
pub fn default_trail_path() -> Option<PathBuf> {
trail_path()
}
pub fn load_recent(limit: usize) -> Vec<AuditEntry> {
let Some(path) = trail_path() else {
return Vec::new();
};
load_recent_at(&path, limit)
}
const TAIL_BLOCK: u64 = 256 * 1024;
pub fn load_recent_at(path: &Path, limit: usize) -> Vec<AuditEntry> {
let mut entries: Vec<AuditEntry> = Vec::new();
for file in segments::chain(path).iter().rev() {
if entries.len() >= limit {
break;
}
let mut older = load_recent_in(file, limit - entries.len());
older.append(&mut entries);
entries = older;
}
entries
}
fn load_recent_in(path: &Path, limit: usize) -> Vec<AuditEntry> {
use std::io::{Seek, SeekFrom};
if limit == 0 {
return Vec::new();
}
let Some((file, len)) = open_for_listing(path) else {
return Vec::new();
};
let mut start = len;
let mut blocks: Vec<Vec<u8>> = Vec::new();
let mut newlines = 0usize;
while start > 0 && newlines <= limit {
let from = start.saturating_sub(TAIL_BLOCK);
let mut block = Vec::new();
let read = (&file)
.seek(SeekFrom::Start(from))
.and_then(|_| (&file).take(start - from).read_to_end(&mut block));
if read.is_err() {
break;
}
newlines += bytecount::count(&block, b'\n');
blocks.push(block);
start = from;
}
let mut tail: Vec<u8> = blocks.into_iter().rev().flatten().collect();
if start > 0 {
let cut = tail
.iter()
.position(|&byte| byte == b'\n')
.map_or(tail.len(), |at| at + 1);
tail.drain(..cut);
}
let entries = parse_entries(std::io::BufReader::new(tail.as_slice()));
let skip = entries.len().saturating_sub(limit);
entries.into_iter().skip(skip).collect()
}
pub fn load_all_at(path: &Path) -> Vec<AuditEntry> {
let mut entries = Vec::new();
for file in segments::chain(path) {
if let Some((file, len)) = open_for_listing(&file) {
entries.extend(parse_entries(std::io::BufReader::new(file.take(len))));
}
}
entries
}
pub fn for_each_entry_at(
path: &Path,
since: Option<lean_ctx_time::UtcDateTime>,
needle: Option<&str>,
mut visit: impl FnMut(&AuditEntry),
) -> usize {
let mut visited = 0;
let mut line = Vec::new();
for file in trail_files_since(path, since) {
let Some((file, len)) = open_for_listing(&file) else {
continue;
};
let mut reader = std::io::BufReader::new(file.take(len));
loop {
line.clear();
match reader.read_until(b'\n', &mut line) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
let Ok(text) = std::str::from_utf8(&line) else {
break;
};
if needle.is_some_and(|needle| !text.contains(needle)) {
continue;
}
for entry in serde_json::Deserializer::from_str(text)
.into_iter::<AuditEntry>()
.map_while(Result::ok)
{
visited += 1;
visit(&entry);
}
}
}
visited
}
pub fn trail_files_since(trail: &Path, since: Option<lean_ctx_time::UtcDateTime>) -> Vec<PathBuf> {
let mut files: Vec<PathBuf> = segments::sealed(trail)
.into_iter()
.map(|(_, path)| path)
.filter(|path| {
since.is_none_or(|since| {
fs::File::open(path)
.ok()
.and_then(|file| read_tail_entry(&file).ok().flatten())
.and_then(|last| entry_time(&last))
.is_none_or(|sealed_at| sealed_at >= since)
})
})
.collect();
if trail.exists() {
files.push(trail.to_path_buf());
}
files
}
pub fn read_trail_since(
trail: &Path,
since: Option<lean_ctx_time::UtcDateTime>,
) -> std::io::Result<Option<String>> {
for _ in 0..SNAPSHOT_ATTEMPTS {
let before = segments::sealed(trail);
let files = trail_files_since(trail, since);
if files.is_empty() {
return Ok(None);
}
let mut text = String::new();
for file in files {
match fs::read_to_string(&file) {
Ok(part) => {
text.push_str(&part);
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
if segments::sealed(trail) == before {
return Ok(Some(text));
}
}
Err(std::io::Error::other(
"the audit trail kept being sealed while it was read",
))
}
const SNAPSHOT_ATTEMPTS: usize = 3;
fn entry_time(entry: &serde_json::Value) -> Option<lean_ctx_time::UtcDateTime> {
let stamp = entry.get("timestamp")?.as_str()?;
Some(
lean_ctx_time::OffsetDateTime::parse_from_rfc3339(stamp)
.ok()?
.to_utc(),
)
}
fn open_for_listing(path: &Path) -> Option<(fs::File, u64)> {
let file = fs::File::open(path).ok()?;
let locked = lock_trail_shared(&file);
if let Err(error) = &locked {
tracing::debug!("audit listing reads unlocked and may end early: {error}");
}
let len = file.metadata().ok()?.len();
if locked.is_ok() {
release_read_lock(&file);
}
Some((file, len))
}
fn parse_entries(reader: impl BufRead) -> Vec<AuditEntry> {
let mut entries = Vec::new();
for line in reader.lines().map_while(Result::ok) {
entries.extend(
serde_json::Deserializer::from_str(&line)
.into_iter::<AuditEntry>()
.map_while(Result::ok),
);
}
entries
}
pub fn latest_unacknowledged_drift(agent_id: &str) -> Result<Option<(String, String)>, String> {
let (chain, pending) = verify_chain_with_drift(Some(agent_id));
if !chain.source_present {
return Err("audit trail unavailable".to_string());
}
if !chain.valid {
return Err(format!(
"audit chain invalid at entry {}",
chain.first_invalid_at.unwrap_or(chain.total_entries)
));
}
if chain.total_entries == 0 {
return Err("audit trail unavailable".to_string());
}
Ok(pending)
}
pub fn hash_input(args: &serde_json::Map<String, serde_json::Value>) -> String {
let serialized = serde_json::to_string(args).unwrap_or_default();
let mut hasher = Sha256::new();
hasher.update(serialized.as_bytes());
crate::core::agent_identity::hex_encode(&hasher.finalize())
}
#[cfg(test)]
#[path = "audit_trail_tests.rs"]
mod tests;