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#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
42 pub signature: Option<String>,
43 #[serde(skip_serializing_if = "Option::is_none", default)]
46 pub v: Option<u64>,
47 #[serde(skip_serializing_if = "Option::is_none", default)]
49 pub session_id: Option<String>,
50 #[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 #[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 #[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 AgentRegistered,
81 AgentSuspended,
82 AgentResumed,
83 AgentDecommissioned,
84 AgentDriftDetected,
88 AgentDriftAcknowledged,
92 ProjectAdopted,
97 Unknown(String),
100}
101
102pub 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 pub source_present: bool,
215 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
231fn read_tail(file: &fs::File) -> Result<Tail, String> {
241 Ok(Tail::after(read_tail_entry(file)?.as_ref()))
242}
243
244#[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
265fn 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 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 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
317pub fn record(data: AuditEntryData) {
322 let _ = try_record(data);
323}
324
325const 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
332fn lock_trail(file: &fs::File) -> Result<(), String> {
334 lock_trail_with(file, fs2::FileExt::try_lock_exclusive)
335}
336
337fn lock_trail_shared(file: &fs::File) -> Result<(), String> {
344 lock_trail_with(file, fs2::FileExt::try_lock_shared)
345}
346
347fn release_read_lock(file: &fs::File) {
361 #[cfg(not(windows))]
362 let _ = fs2::FileExt::unlock(file);
363 #[cfg(windows)]
364 let _ = file;
365}
366
367fn 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
397pub 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
412pub 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
427pub fn record_v2(data: AuditEntryData, facts: SessionFacts) {
429 let _ = try_record_v2(data, facts);
430}
431
432pub 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
440pub 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
456struct Record {
458 data: AuditEntryData,
459 facts: Option<SessionFacts>,
460}
461
462fn try_record_at_time(
464 path: &Path,
465 record: Record,
466 now: lean_ctx_time::UtcDateTime,
467) -> Result<AuditEntry, String> {
468 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
482enum Appended {
484 Done(AuditEntry),
485 Moved(Record),
487}
488
489fn 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
510fn 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 #[cfg(not(unix))]
523 {
524 let _ = (path, file);
525 true
526 }
527}
528
529fn 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 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 Some(seq) if seq == next_seq => seq,
564 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 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
592fn 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
614pub fn is_seal(event_type: &AuditEventType) -> bool {
617 matches!(event_type, AuditEventType::Unknown(label) if label == segments::SEAL_EVENT)
618}
619
620fn 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 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
713pub fn default_trail_path() -> Option<PathBuf> {
715 trail_path()
716}
717
718pub 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
726const TAIL_BLOCK: u64 = 256 * 1024;
728
729pub 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 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
784pub 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
795pub 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 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
842pub 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
867pub 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
903const 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
915fn open_for_listing(path: &Path) -> Option<(fs::File, u64)> {
918 let file = fs::File::open(path).ok()?;
919 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
944pub 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 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;