lean-ctx-engine 3.12.13

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
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,
};

/// One trail entry. The v2 fields (see `audit_trail/v2.rs`) are absent on
/// entries an older writer appended.
#[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,
    /// Ed25519 signature over `entry_hash`, proving provenance from the local
    /// lean-ctx identity. `None` only when the keypair is unavailable (early boot).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub signature: Option<String>,
    /// Entry version: absent on v1 entries, [`ENTRY_VERSION`] on entries this
    /// build writes.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub v: Option<u64>,
    /// The session whose call this entry records.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub session_id: Option<String>,
    /// Position of the entry in its session, from 1, in chain order.
    #[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>,
    /// The [`AuditDecision`] label, kept as text so a reader older than the
    /// writer still parses a decision it does not know.
    #[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>,
    /// Chained hash over the v2 fields (`audit_trail/v2.rs`).
    #[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,
    // Agent identity lifecycle (GL #433) — additive OCP Part 4 evolution.
    AgentRegistered,
    AgentSuspended,
    AgentResumed,
    AgentDecommissioned,
    /// Attestation drift observed on heartbeat: the running binary and/or
    /// the active role file no longer match the attestation the registry
    /// holds for this identity (GL #433 / Phase 18 S3).
    AgentDriftDetected,
    /// An operator explicitly acknowledged one specific observed drift,
    /// naming its evidence. Only this event clears the sticky drift mark —
    /// resuming a suspended identity does not (GL #433 / Phase 18 S3).
    AgentDriftAcknowledged,
    /// An unbound session adopted the project of its first absolute path.
    /// Not a refusal: never counted as a block or cross-project access.
    /// Written in the `x-` extension namespace, so older readers keep
    /// parsing the trail (as an additive unknown event).
    ProjectAdopted,
    /// Forward-compatible additive event emitted by a newer writer. Keep the
    /// exact wire label so reports never silently discard security evidence.
    Unknown(String),
}

/// Wire label of [`AuditEventType::ProjectAdopted`]: an `x-` extension label,
/// so a reader that predates it parses it as an additive unknown event.
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>,
    /// Whether the audit trail file existed and was readable. A missing trail
    /// is a valid empty history for a fresh install, but callers that already
    /// hold audited state must treat `false` as evidence loss.
    pub source_present: bool,
    /// Entries whose `event_type` or entry version (`v` above
    /// [`ENTRY_VERSION`]) this build does not know, but whose hash links
    /// verify. Forward compatibility, NOT corruption: a reader older
    /// than the writer must report those separately instead of raising a
    /// false tamper alarm (OCP Part 4 additive-event rule). Actual hash or
    /// structure damage still sets `valid = false`.
    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"))
}

/// Read the chain tail from the file itself. Called under the exclusive
/// file lock — the file is the ONLY source of truth for `prev_hash`. (A
/// per-process cache forked the chain whenever two processes appended
/// concurrently — found by `leanctx-verify` on a real trail, GL #425.)
///
/// Every I/O failure is propagated instead of being folded into `"genesis"`:
/// a seek/read error on a NON-empty trail is indistinguishable from an empty
/// one at that point, so the old fallback silently forked the chain and still
/// returned `Ok` to a caller (attestation drift) that commits state on it.
fn read_tail(file: &fs::File) -> Result<Tail, String> {
    Ok(Tail::after(read_tail_entry(file)?.as_ref()))
}

/// Where the next entry links in: the `entry_hash` of the last entry (its
/// `prev_hash`) and the v2 chain head after it.
#[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 }
    }
}

/// The last entry of `file` as raw JSON; `None` for an empty file. A
/// non-empty file without a readable entry in its tail is an error.
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}"))?;
    // Concurrent-append history may hold multiple objects per line; a
    // stream parse of the last non-empty line yields the true tail entry.
    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);
        }
    }
    // Non-empty file with no parseable entry_hash in the tail window: the
    // trail exists but has no usable head, so a fresh chain would fork it.
    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())
}

/// Fire-and-forget append. The hot tool path must never fail a tool call
/// because the audit sink is momentarily unavailable, so every error is
/// swallowed here. Callers whose own state update is only sound *with* the
/// evidence on disk (agent attestation drift) use [`try_record`] instead.
pub fn record(data: AuditEntryData) {
    let _ = try_record(data);
}

/// How long an append waits for the cross-process trail lock before giving
/// up. Bounded on purpose: the drift path takes this lock while it holds the
/// (also deadline-bounded) identity-registry lock, so an unbounded blocking
/// `flock` would let one stalled process freeze every registry operation.
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);

/// Acquire the exclusive trail lock, bounded by [`LOCK_TIMEOUT`].
fn lock_trail(file: &fs::File) -> Result<(), String> {
    lock_trail_with(file, fs2::FileExt::try_lock_exclusive)
}

/// Acquire a shared trail lock for a reader, bounded by [`LOCK_TIMEOUT`].
/// Windows file locks are mandatory: a reader without one that ran into an
/// append's exclusive lock failed mid-file, and the verifier reported that
/// I/O error as a corrupt chain ("audit chain invalid at entry 0"), e.g. a
/// heartbeat racing a resume. The shared lock waits for the append and gives
/// the verifier a consistent snapshot on every platform.
fn lock_trail_shared(file: &fs::File) -> Result<(), String> {
    lock_trail_with(file, fs2::FileExt::try_lock_shared)
}

/// End a reader's shared lock once it has taken the trail's length. Appends
/// hold the exclusive lock and only ever extend the file (a failed append
/// truncates back to its own start), so `file[..len]` stays exactly as it was
/// and the reader goes on without the lock: a pass over a large trail no
/// longer makes every append in every process time out behind it. Windows
/// locks are mandatory, so a reader there keeps its lock to the end.
///
/// This rests on the trail being append-only in place. Anything that
/// rewrites, repairs or rotates `trail.jsonl` must write a new file and
/// rename it over the old one (an open reader keeps its own inode), never
/// truncate or edit it in place; a verifier that finds its file shorter
/// than the length it took reports the trail unavailable
/// ([`still_holds_prefix`]).
fn release_read_lock(file: &fs::File) {
    #[cfg(not(windows))]
    let _ = fs2::FileExt::unlock(file);
    #[cfg(windows)]
    let _ = file;
}

/// Whether `file` still holds the `len` bytes a reader took (see
/// [`release_read_lock`]): false only if something truncated it in place.
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}")),
        }
    }
}

/// Fallible append. Returns the persisted entry, so a caller can commit its
/// own state only once the evidence is durable. On `Err` nothing was
/// appended — a short write is rolled back to the pre-append length — which
/// makes a retry safe and leaves the hash chain intact.
///
/// Durability is AT-LEAST-ONCE, not exactly-once: the line is `fsync`ed, but
/// the caller's own state file is a separate object with no cross-file
/// atomicity, so a crash between the two can leave the entry on disk without
/// the state update. The direction is deliberate — a duplicate observation on
/// the next attempt, never a lost one.
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)
}

/// Append one entry to the trail at an explicit `path` (used by callers that
/// keep their own chained trail, e.g. value proofs). Errors are swallowed like
/// [`record`].
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(),
    )
}

/// Fire-and-forget append of a call of a session (see [`record`]).
pub fn record_v2(data: AuditEntryData, facts: SessionFacts) {
    let _ = try_record_v2(data, facts);
}

/// Append an entry that binds `facts` to the call: the session id, its next
/// `seq`, the instance, policy digest, decision and output digest, hashed
/// with the timestamp into the entry's `v2_hash`.
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)
}

/// [`try_record_v2`] to the trail at an explicit `path`.
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())
}

/// One entry to append: the v1 data and, for a call of a session, its facts.
struct Record {
    data: AuditEntryData,
    facts: Option<SessionFacts>,
}

/// [`try_record_at`] with the clock that decides whether a day has passed.
fn try_record_at_time(
    path: &Path,
    record: Record,
    now: lean_ctx_time::UtcDateTime,
) -> Result<AuditEntry, String> {
    // At most one seal per append: after it the next file is fresh.
    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())
}

/// What [`append_or_seal`] did with the entry.
enum Appended {
    Done(AuditEntry),
    /// The file was sealed and moved: append the entry to the new one.
    Moved(Record),
}

/// Open the active trail and take the exclusive lock. Advisory lock
/// serializes appends ACROSS processes; prev_hash is read from the file
/// under the same lock, so the chain cannot fork. A writer that waited on a
/// file another writer sealed and renamed meanwhile opens the new one.
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())
}

/// Whether `file` is still the file at `path`.
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,
        }
    }
    // lean-ctx: std has no stable file id on Windows; a renamed file is
    // caught there by its tail (a seal) on the next append instead.
    #[cfg(not(unix))]
    {
        let _ = (path, file);
        true
    }
}

/// Append `data` to the locked active trail, sealing it first when it is
/// due.
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 {
        // A fresh active file continues the chain of the newest segment.
        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 {
        // Sealed before, but the rename did not happen.
        Some(seq) if seq == next_seq => seq,
        // Already moved to its segment (a handle that outlived the rename).
        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) => {
            // The seal stays in the active file and the chain runs on; this
            // process tries again after a back-off.
            tracing::warn!("audit trail not sealed: {error}");
            segments::back_off();
            let tail = read_tail(file)?;
            append_locked(file, record, tail).map(Appended::Done)
        }
    }
}

/// Never seal a trail this build has not verified: only a trail with a
/// valid checkpoint (from a successful pass) is sealed. Trails outside the
/// data dir have no checkpoint and are never sealed.
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()),
    }
}

/// Whether an entry is the seal that closes a trail segment: chain
/// bookkeeping, not an agent action.
pub fn is_seal(event_type: &AuditEventType) -> bool {
    matches!(event_type, AuditEventType::Unknown(label) if label == segments::SEAL_EVENT)
}

/// Build and append one v2 entry after `tail`. Caller holds the exclusive
/// lock, so a session's `seq` follows chain order.
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');
    // A short write would leave a truncated JSON line and invalidate the
    // chain from that point onwards; roll the file back to its pre-append
    // length so a failed append is a no-op instead of corruption.
    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)
}

/// Path of the local audit trail (`<data_dir>/audit/trail.jsonl`).
pub fn default_trail_path() -> Option<PathBuf> {
    trail_path()
}

/// The last `limit` entries of the default trail.
pub fn load_recent(limit: usize) -> Vec<AuditEntry> {
    let Some(path) = trail_path() else {
        return Vec::new();
    };
    load_recent_at(&path, limit)
}

/// Bytes read per step when [`load_recent_at`] walks back from the end.
const TAIL_BLOCK: u64 = 256 * 1024;

/// The last `limit` entries of the trail at `path`, read back from its end
/// in blocks until enough whole lines are in, never the whole trail; a
/// short active trail is topped up from the newest sealed segments.
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();
    // Unless the walk reached the start, the first line may be cut.
    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()
}

/// Every parseable entry of the trail at `path`, its sealed segments first.
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
}

/// Visit the parseable entries of the trail at `path` in chain order, one at
/// a time, like [`load_all_at`] without holding the trail in memory.
///
/// * `since` leaves out the sealed segments sealed before it (see
///   [`trail_files_since`]).
/// * `needle` leaves out, unparsed, every line that does not contain it.
///
/// Returns the number of entries visited.
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(_) => {}
            }
            // Like `BufRead::lines` in `load_all_at`: a file stops at its
            // first line that is not UTF-8.
            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
}

/// The files of the trail at `trail` in chain order: its sealed segments,
/// oldest first, then the active trail if it exists. With `since`, a sealed
/// segment whose last entry (its seal) is older than `since` is left out;
/// that takes one tail read per segment. Lines keep the trail's format and
/// run in time order across the files.
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
}

/// The text of [`trail_files_since`] joined in order; `None` when the trail
/// has no file at all. A seal that lands while the files are read moves the
/// active trail away, so the read is repeated until the segment list held
/// still across it.
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",
    ))
}

/// How often a reader retries when a seal moved the active trail under it.
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(),
    )
}

/// Open the trail at `path` for a listing, with its length taken under the
/// shared lock (see [`release_read_lock`]).
fn open_for_listing(path: &Path) -> Option<(fs::File, u64)> {
    let file = fs::File::open(path).ok()?;
    // Best effort: without the shared lock a Windows read can stop at an
    // in-progress append (see `lock_trail_shared`); the listing then ends early.
    let locked = lock_trail_shared(&file);
    if let Err(error) = &locked {
        tracing::debug!("audit listing reads unlocked and may end early: {error}");
    }
    // Release before the `?`: a failed metadata read must not leave the lock
    // to the file's close, which a child forked meanwhile would delay.
    let len = file.metadata().map(|meta| meta.len());
    if locked.is_ok() {
        release_read_lock(&file);
    }
    Some((file, len.ok()?))
}

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
}

/// Reconstruct the latest unacknowledged drift from the append-only trail.
/// This is the downgrade-safe source of truth: an older binary may rewrite an
/// `Attestation` without its newer `drift` field, but it cannot synthesize the
/// explicit acknowledgement event required to clear this history.
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 {
        // An existing zero-byte trail is evidence loss for any identity that
        // has already reached an attested state. Keep the generic verifier's
        // fresh-install view (`valid=true`, `source_present=true`) compatible,
        // but do not let a caller that reconstructs durable identity state
        // interpret an emptied trail as a clean history.
        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;