Skip to main content

lean_ctx/core/execution_ledger/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Append-only, task-aware execution ledger.
3//!
4//! The execution ledger is an additive projection beside the Savings Ledger.  It
5//! shares the Savings Ledger's SHA-256 chain primitive, but stores execution
6//! identity and lifecycle observations keyed by task and trace IDs.
7
8pub mod canonical_receipt;
9pub mod event;
10pub(crate) mod host;
11pub mod migration;
12pub mod producer;
13pub mod projection;
14pub mod store;
15pub mod verify;
16
17pub use canonical_receipt::{PublishedCanonicalReceipt, publish_canonical_receipt};
18pub use event::{ContextBalance, ContextBalanceV1, ExecutionEvent, TriState};
19pub use migration::{migrate_from_savings_ledger, migrate_from_savings_ledger_at};
20pub use producer::{
21    CanonicalReceiptRecordV1, ReceiptSignerAdmissionV1, record_canonical_engine_receipt,
22};
23pub use projection::{
24    CanonicalReceiptProjectionV1, ExecutionProjection, LegacyReceiptProjectionV1, TaskCostSummary,
25    canonical_receipt_for_task_from_store, canonical_receipt_for_task_verified_from_store,
26    legacy_receipt_for_task, legacy_receipt_for_task_from_store, task_cost_summary,
27    task_cost_summary_from_store,
28};
29pub use store::{ExecutionLedgerStore, default_path};
30pub use verify::{GENESIS, hash_event, verify_events};
31
32use std::io;
33
34use serde::{Deserialize, Serialize};
35
36/// Errors returned while reading, serializing, or validating the execution ledger.
37#[derive(Debug, thiserror::Error)]
38pub enum ExecutionLedgerError {
39    #[error("execution ledger I/O failed: {0}")]
40    Io(#[from] io::Error),
41    #[error("execution ledger serialization failed: {0}")]
42    Serialization(#[from] serde_json::Error),
43    #[error("execution ledger chain is invalid: {0}")]
44    InvalidChain(String),
45    #[error("execution ledger record is invalid: {0}")]
46    InvalidRecord(String),
47}
48
49/// Result type shared by execution-ledger operations.
50pub type Result<T> = std::result::Result<T, ExecutionLedgerError>;
51
52/// Compatibility view consumed by the existing `ledger execution` CLI.
53///
54/// The event store remains the source of truth; this view groups the current
55/// task projection without introducing a second writable ledger format. Legacy
56/// receipt evidence and its estimates remain explicitly named and never occupy
57/// canonical receipt or accepted-cost fields.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct ExecutionLedgerEntryV1 {
60    pub task_id: String,
61    #[serde(alias = "receipt")]
62    pub legacy_receipt: Option<LegacyReceiptProjectionV1>,
63    #[serde(alias = "actual_cost_micros")]
64    pub legacy_estimated_actual_cost_micros: Option<u64>,
65    #[serde(alias = "baseline_cost_micros")]
66    pub legacy_estimated_baseline_cost_micros: Option<u64>,
67    pub predicted_cost_micros: Option<u64>,
68    pub actual_etpao: Option<crate::core::etpao::EtpaoResult>,
69    pub baseline_etpao: Option<crate::core::etpao::EtpaoResult>,
70    pub predicted_etpao: Option<crate::core::etpao::EtpaoResult>,
71}
72
73/// Compatibility aggregate for the existing execution-ledger CLI commands.
74#[derive(Debug, Clone, Default, Serialize, Deserialize)]
75pub struct ExecutionLedger {
76    pub entries: Vec<ExecutionLedgerEntryV1>,
77}
78
79#[derive(Debug, Clone, Default)]
80pub struct ExecutionLedgerVerifyResult {
81    pub valid: bool,
82    pub total_entries: usize,
83    pub first_invalid_at: Option<usize>,
84    pub error: Option<String>,
85}
86
87impl ExecutionLedger {
88    /// Loads the compatibility projection from the default event store.
89    pub fn load() -> Result<Self> {
90        let store = ExecutionLedgerStore::from_default()?;
91        let events = store.load_verified()?;
92        let mut task_ids = Vec::new();
93        for event in events {
94            if !task_ids.iter().any(|known| known == event.task_id()) {
95                task_ids.push(event.task_id().to_owned());
96            }
97        }
98
99        let entries = task_ids
100            .into_iter()
101            .map(|task_id| {
102                let legacy_receipt = legacy_receipt_for_task_from_store(&store, &task_id);
103                ExecutionLedgerEntryV1 {
104                    task_id,
105                    legacy_estimated_actual_cost_micros: legacy_receipt
106                        .as_ref()
107                        .map(|value| value.legacy_receipt().actual_cost_micros),
108                    legacy_estimated_baseline_cost_micros: legacy_receipt
109                        .as_ref()
110                        .map(|value| value.legacy_receipt().baseline_cost_micros),
111                    predicted_cost_micros: None,
112                    actual_etpao: None,
113                    baseline_etpao: None,
114                    predicted_etpao: None,
115                    legacy_receipt,
116                }
117            })
118            .collect();
119        Ok(Self { entries })
120    }
121
122    /// Finds the first projection for a task.
123    #[must_use]
124    pub fn find_task(&self, task_id: &str) -> Option<&ExecutionLedgerEntryV1> {
125        self.entries.iter().find(|entry| entry.task_id == task_id)
126    }
127
128    /// Verifies the source event chain and reports CLI-friendly details.
129    #[must_use]
130    pub fn verify(&self) -> ExecutionLedgerVerifyResult {
131        match ExecutionLedgerStore::from_default().and_then(|store| store.verify_chain()) {
132            Ok(valid) => ExecutionLedgerVerifyResult {
133                valid,
134                total_entries: self.entries.len(),
135                first_invalid_at: (!valid).then_some(0),
136                error: (!valid).then(|| "hash or sequence link mismatch".to_owned()),
137            },
138            Err(error) => ExecutionLedgerVerifyResult {
139                valid: false,
140                total_entries: self.entries.len(),
141                first_invalid_at: Some(0),
142                error: Some(error.to_string()),
143            },
144        }
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use lean_ctx_protocol::AcceptanceState;
152    use tempfile::tempdir;
153
154    fn task_started(task_id: &str, trace_id: &str) -> ExecutionEvent {
155        ExecutionEvent::TaskStarted {
156            task_id: task_id.to_owned(),
157            trace_id: trace_id.to_owned(),
158            envelope_ref: "envelope:task".to_owned(),
159            timestamp: "2026-08-09T12:00:00Z".to_owned(),
160            sequence_number: 0,
161            prev_hash: String::new(),
162        }
163    }
164
165    fn model_invoked(task_id: &str, trace_id: &str) -> ExecutionEvent {
166        model_invoked_with(task_id, trace_id, "invocation-1", "model-1", 20, 10)
167    }
168
169    fn model_invoked_with(
170        task_id: &str,
171        trace_id: &str,
172        invocation_id: &str,
173        model: &str,
174        tokens_in: u64,
175        tokens_out: u64,
176    ) -> ExecutionEvent {
177        ExecutionEvent::ModelInvoked {
178            task_id: task_id.to_owned(),
179            trace_id: trace_id.to_owned(),
180            plan_id: "plan-1".to_owned(),
181            invocation_id: invocation_id.to_owned(),
182            invocation_ref: format!("sha256:{invocation_id}"),
183            model: model.to_owned(),
184            provider: "provider-1".to_owned(),
185            tokens_in,
186            tokens_out,
187            latency_ms: 25,
188            timestamp: "2026-08-09T12:00:01Z".to_owned(),
189            sequence_number: 0,
190            prev_hash: String::new(),
191        }
192    }
193
194    fn context_delivered(task_id: &str, trace_id: &str) -> ExecutionEvent {
195        ExecutionEvent::ContextDelivered {
196            task_id: task_id.to_owned(),
197            trace_id: trace_id.to_owned(),
198            context_balance: ContextBalanceV1 {
199                original_tokens: 100,
200                materialized_tokens: 80,
201                delivered_tokens: 60,
202                provider_billed_tokens: 60,
203            },
204            timestamp: "2026-08-09T12:00:00Z".to_owned(),
205            sequence_number: 0,
206            prev_hash: String::new(),
207        }
208    }
209
210    fn engine_invoked(task_id: &str, trace_id: &str) -> ExecutionEvent {
211        ExecutionEvent::EngineInvoked {
212            task_id: task_id.to_owned(),
213            trace_id: trace_id.to_owned(),
214            plan_id: "plan-1".to_owned(),
215            invocation_id: "invocation-engine-1".to_owned(),
216            invocation_ref: "sha256:engine-invocation-1".to_owned(),
217            capability_id: "capability://leanctx/context".to_owned(),
218            capability_version: "1.0.0".to_owned(),
219            timestamp: "2026-08-09T12:00:01Z".to_owned(),
220            sequence_number: 0,
221            prev_hash: String::new(),
222        }
223    }
224
225    fn canonical_record(
226        task_id: &str,
227        trace_id: &str,
228        invocation_id: &str,
229        digit: char,
230    ) -> ExecutionEvent {
231        ExecutionEvent::CanonicalReceiptRecorded {
232            task_id: task_id.to_owned(),
233            trace_id: trace_id.to_owned(),
234            invocation_id: invocation_id.to_owned(),
235            receipt_id: format!("sha256:{}", digit.to_string().repeat(64)),
236            receipt_ref: format!("id:sha256:{}", digit.to_string().repeat(64)),
237            receipt_digest: format!("sha256:{}", digit.to_string().repeat(64)),
238            receipt_chain_id: "shared-chain".to_owned(),
239            receipt_sequence_number: 1,
240            previous_receipt_id: None,
241            previous_signature_digest: None,
242            timestamp: "2026-08-23T12:00:00Z".to_owned(),
243            sequence_number: 0,
244            prev_hash: String::new(),
245            entry_hash: String::new(),
246        }
247    }
248
249    #[test]
250    fn append_assigns_sequence_and_verifies_chain() {
251        let directory = tempdir().expect("temporary directory");
252        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
253        store.append(task_started("task-1", "trace-1")).unwrap();
254        store
255            .append(ExecutionEvent::PlanCreated {
256                task_id: "task-1".to_owned(),
257                trace_id: "trace-1".to_owned(),
258                plan_id: "plan-1".to_owned(),
259                plan_ref: "plan:1".to_owned(),
260                timestamp: "2026-08-09T12:00:00Z".to_owned(),
261                sequence_number: 0,
262                prev_hash: String::new(),
263            })
264            .unwrap();
265        store
266            .append(context_delivered("task-1", "trace-1"))
267            .unwrap();
268        store.append(model_invoked("task-1", "trace-1")).unwrap();
269
270        assert_eq!(store.last_sequence(), 4);
271        assert!(store.verify_chain().unwrap());
272    }
273
274    #[test]
275    fn engine_invocation_is_auditable_without_fabricated_model_usage() {
276        let directory = tempdir().expect("temporary directory");
277        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
278        store.append(task_started("task-1", "trace-1")).unwrap();
279        store
280            .append(ExecutionEvent::PlanCreated {
281                task_id: "task-1".to_owned(),
282                trace_id: "trace-1".to_owned(),
283                plan_id: "plan-1".to_owned(),
284                plan_ref: "sha256:plan-1".to_owned(),
285                timestamp: "2026-08-09T12:00:00Z".to_owned(),
286                sequence_number: 0,
287                prev_hash: String::new(),
288            })
289            .unwrap();
290        store
291            .append(context_delivered("task-1", "trace-1"))
292            .unwrap();
293        store.append(engine_invoked("task-1", "trace-1")).unwrap();
294
295        assert!(store.verify_chain().unwrap());
296        let summary = store.task_cost_summary("task-1");
297        assert_eq!(summary.model_calls, 0);
298        assert_eq!(
299            summary.cost_classification(),
300            lean_ctx_protocol::ReceiptValueClassificationV1::Unavailable
301        );
302        assert_eq!(
303            summary.baseline_cost_classification(),
304            lean_ctx_protocol::ReceiptValueClassificationV1::Unavailable
305        );
306        assert!(store.legacy_receipt_for_task("task-1").is_none());
307    }
308
309    #[test]
310    fn canonical_receipt_self_hash_detects_last_event_tampering() {
311        let directory = tempdir().expect("temporary directory");
312        let path = directory.path().join("ledger.jsonl");
313        let store = ExecutionLedgerStore::new(&path);
314        store.append(task_started("task-1", "trace-1")).unwrap();
315        store
316            .append(ExecutionEvent::PlanCreated {
317                task_id: "task-1".to_owned(),
318                trace_id: "trace-1".to_owned(),
319                plan_id: "plan-1".to_owned(),
320                plan_ref: "plan:1".to_owned(),
321                timestamp: "2026-08-23T11:59:58Z".to_owned(),
322                sequence_number: 0,
323                prev_hash: String::new(),
324            })
325            .unwrap();
326        store
327            .append(ExecutionEvent::ContextDelivered {
328                task_id: "task-1".to_owned(),
329                trace_id: "trace-1".to_owned(),
330                context_balance: ContextBalanceV1 {
331                    original_tokens: 1,
332                    materialized_tokens: 1,
333                    delivered_tokens: 1,
334                    provider_billed_tokens: 1,
335                },
336                timestamp: "2026-08-23T11:59:58Z".to_owned(),
337                sequence_number: 0,
338                prev_hash: String::new(),
339            })
340            .unwrap();
341        store.append(model_invoked("task-1", "trace-1")).unwrap();
342        store
343            .append(ExecutionEvent::CanonicalReceiptRecorded {
344                task_id: "task-1".to_owned(),
345                trace_id: "trace-1".to_owned(),
346                invocation_id: "invocation-1".to_owned(),
347                receipt_id: format!("sha256:{}", "1".repeat(64)),
348                receipt_ref: format!("id:sha256:{}", "2".repeat(64)),
349                receipt_digest: format!("sha256:{}", "2".repeat(64)),
350                receipt_chain_id: "chain-1".to_owned(),
351                receipt_sequence_number: 1,
352                previous_receipt_id: None,
353                previous_signature_digest: None,
354                timestamp: "2026-08-23T12:00:00Z".to_owned(),
355                sequence_number: 0,
356                prev_hash: String::new(),
357                entry_hash: String::new(),
358            })
359            .unwrap();
360        assert!(store.verify_chain().unwrap());
361        let projected = store
362            .canonical_receipt_for_task_verified("task-1")
363            .unwrap()
364            .unwrap();
365        assert_eq!(projected.invocation_id, "invocation-1");
366        assert_eq!(projected.chain_id, "chain-1");
367        assert_eq!(projected.sequence_number, 1);
368
369        let content = std::fs::read_to_string(&path).unwrap();
370        std::fs::write(&path, content.replace(&"1".repeat(64), &"3".repeat(64))).unwrap();
371
372        assert!(!store.verify_chain().unwrap());
373    }
374
375    #[test]
376    fn verify_chain_rejects_modified_event() {
377        let directory = tempdir().expect("temporary directory");
378        let path = directory.path().join("ledger.jsonl");
379        let store = ExecutionLedgerStore::new(&path);
380        store.append(task_started("task-1", "trace-1")).unwrap();
381        store
382            .append(ExecutionEvent::PlanCreated {
383                task_id: "task-1".to_owned(),
384                trace_id: "trace-1".to_owned(),
385                plan_id: "plan-1".to_owned(),
386                plan_ref: "plan:1".to_owned(),
387                timestamp: "2026-08-09T12:00:00Z".to_owned(),
388                sequence_number: 0,
389                prev_hash: String::new(),
390            })
391            .unwrap();
392        store
393            .append(context_delivered("task-1", "trace-1"))
394            .unwrap();
395        store.append(model_invoked("task-1", "trace-1")).unwrap();
396        let mut line = std::fs::read_to_string(&path).unwrap();
397        line = line.replace("envelope:task", "envelope:changed");
398        std::fs::write(&path, line).unwrap();
399
400        assert!(!store.verify_chain().unwrap());
401    }
402
403    #[test]
404    fn record_digest_detects_single_tail_event_tampering() {
405        let directory = tempdir().expect("temporary directory");
406        let path = directory.path().join("ledger.jsonl");
407        let store = ExecutionLedgerStore::new(&path);
408        store.append(task_started("task-1", "trace-1")).unwrap();
409        let content = std::fs::read_to_string(&path).unwrap();
410        std::fs::write(&path, content.replace("trace-1", "trace-x")).unwrap();
411
412        assert!(!store.verify_chain().unwrap());
413    }
414
415    #[test]
416    fn append_rejects_cross_trace_and_out_of_order_events() {
417        let directory = tempdir().expect("temporary directory");
418        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
419        store.append(task_started("task-1", "trace-1")).unwrap();
420
421        assert!(matches!(
422            store.append(model_invoked("task-1", "trace-1")),
423            Err(ExecutionLedgerError::InvalidChain(_))
424        ));
425        assert!(matches!(
426            store.append(ExecutionEvent::PlanCreated {
427                task_id: "task-1".to_owned(),
428                trace_id: "trace-x".to_owned(),
429                plan_id: "plan-1".to_owned(),
430                plan_ref: "plan:1".to_owned(),
431                timestamp: "2026-08-09T12:00:00Z".to_owned(),
432                sequence_number: 0,
433                prev_hash: String::new(),
434            }),
435            Err(ExecutionLedgerError::InvalidChain(_))
436        ));
437        assert_eq!(store.last_sequence(), 1);
438    }
439
440    #[test]
441    fn canonical_receipt_chain_rejects_cross_task_forks_and_unlinked_outcomes() {
442        let directory = tempdir().expect("temporary directory");
443        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
444        for (task_id, trace_id) in [("task-1", "trace-1"), ("task-2", "trace-2")] {
445            store.append(task_started(task_id, trace_id)).unwrap();
446            store
447                .append(ExecutionEvent::PlanCreated {
448                    task_id: task_id.to_owned(),
449                    trace_id: trace_id.to_owned(),
450                    plan_id: "plan-1".to_owned(),
451                    plan_ref: "plan:1".to_owned(),
452                    timestamp: "2026-08-23T11:59:00Z".to_owned(),
453                    sequence_number: 0,
454                    prev_hash: String::new(),
455                })
456                .unwrap();
457            store.append(context_delivered(task_id, trace_id)).unwrap();
458            store.append(engine_invoked(task_id, trace_id)).unwrap();
459        }
460        assert!(matches!(
461            store.append(ExecutionEvent::OutcomeRecorded {
462                task_id: "task-1".to_owned(),
463                trace_id: "trace-1".to_owned(),
464                outcome_id: "outcome-1".to_owned(),
465                receipt_id: format!("sha256:{}", "1".repeat(64)),
466                accepted: AcceptanceState::Accepted,
467                timestamp: "2026-08-23T12:00:00Z".to_owned(),
468                sequence_number: 0,
469                prev_hash: String::new(),
470            }),
471            Err(ExecutionLedgerError::InvalidChain(_))
472        ));
473        store
474            .append(canonical_record(
475                "task-1",
476                "trace-1",
477                "invocation-engine-1",
478                '1',
479            ))
480            .unwrap();
481        assert!(matches!(
482            store.append(canonical_record(
483                "task-2",
484                "trace-2",
485                "invocation-engine-1",
486                '2',
487            )),
488            Err(ExecutionLedgerError::InvalidChain(_))
489        ));
490
491        let mut duplicate_id = canonical_record("task-2", "trace-2", "invocation-engine-1", '1');
492        if let ExecutionEvent::CanonicalReceiptRecorded {
493            receipt_ref,
494            receipt_digest,
495            receipt_chain_id,
496            ..
497        } = &mut duplicate_id
498        {
499            *receipt_digest = format!("sha256:{}", "3".repeat(64));
500            *receipt_ref = format!("id:{receipt_digest}");
501            *receipt_chain_id = "independent-chain".to_owned();
502        }
503        assert!(matches!(
504            store.append(duplicate_id),
505            Err(ExecutionLedgerError::InvalidChain(_))
506        ));
507    }
508
509    #[test]
510    fn legacy_receipts_never_authorize_or_downgrade_canonical_outcomes() {
511        let directory = tempdir().expect("temporary directory");
512        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
513        store.append(task_started("task-1", "trace-1")).unwrap();
514        store
515            .append(ExecutionEvent::PlanCreated {
516                task_id: "task-1".to_owned(),
517                trace_id: "trace-1".to_owned(),
518                plan_id: "plan-1".to_owned(),
519                plan_ref: "plan:1".to_owned(),
520                timestamp: "2026-08-23T11:59:00Z".to_owned(),
521                sequence_number: 0,
522                prev_hash: String::new(),
523            })
524            .unwrap();
525        store
526            .append(context_delivered("task-1", "trace-1"))
527            .unwrap();
528        store.append(model_invoked("task-1", "trace-1")).unwrap();
529        let canonical_id = format!("sha256:{}", "1".repeat(64));
530        store
531            .append(ExecutionEvent::ReceiptSigned {
532                task_id: "task-1".to_owned(),
533                trace_id: "trace-1".to_owned(),
534                receipt_id: canonical_id.clone(),
535                receipt_hash: "arbitrary-nonempty-hash".to_owned(),
536                signature: "arbitrary-nonempty-signature".to_owned(),
537                timestamp: "2026-08-23T12:00:00Z".to_owned(),
538                sequence_number: 0,
539                prev_hash: String::new(),
540            })
541            .unwrap();
542        let legacy_outcome = |receipt_id: &str, outcome_id: &str| ExecutionEvent::OutcomeRecorded {
543            task_id: "task-1".to_owned(),
544            trace_id: "trace-1".to_owned(),
545            outcome_id: outcome_id.to_owned(),
546            receipt_id: receipt_id.to_owned(),
547            accepted: AcceptanceState::Accepted,
548            timestamp: "2026-08-23T12:00:01Z".to_owned(),
549            sequence_number: 0,
550            prev_hash: String::new(),
551        };
552
553        assert!(
554            store
555                .append(legacy_outcome(&canonical_id, "legacy-only"))
556                .is_err()
557        );
558        store
559            .append(canonical_record("task-1", "trace-1", "invocation-1", '1'))
560            .unwrap();
561        store
562            .append(ExecutionEvent::ReceiptSigned {
563                task_id: "task-1".to_owned(),
564                trace_id: "trace-1".to_owned(),
565                receipt_id: "legacy-downgrade".to_owned(),
566                receipt_hash: "still-arbitrary".to_owned(),
567                signature: "still-arbitrary".to_owned(),
568                timestamp: "2026-08-23T12:00:02Z".to_owned(),
569                sequence_number: 0,
570                prev_hash: String::new(),
571            })
572            .unwrap();
573        assert!(
574            store
575                .append(legacy_outcome("legacy-downgrade", "downgrade"))
576                .is_err()
577        );
578        store
579            .append(legacy_outcome(&canonical_id, "canonical-outcome"))
580            .unwrap();
581        assert!(
582            store
583                .append(ExecutionEvent::OutcomeRecorded {
584                    task_id: "task-1".to_owned(),
585                    trace_id: "trace-1".to_owned(),
586                    outcome_id: "contradictory-canonical-outcome".to_owned(),
587                    receipt_id: canonical_id.clone(),
588                    accepted: AcceptanceState::Rejected,
589                    timestamp: "2026-08-23T12:00:02Z".to_owned(),
590                    sequence_number: 0,
591                    prev_hash: String::new(),
592                })
593                .is_err()
594        );
595        assert!(
596            store
597                .append(ExecutionEvent::ReceiptSigned {
598                    task_id: "task-1".to_owned(),
599                    trace_id: "trace-1".to_owned(),
600                    receipt_id: "legacy-downgrade".to_owned(),
601                    receipt_hash: "different".to_owned(),
602                    signature: "different".to_owned(),
603                    timestamp: "2026-08-23T12:00:03Z".to_owned(),
604                    sequence_number: 0,
605                    prev_hash: String::new(),
606                })
607                .is_err()
608        );
609
610        let canonical = store
611            .canonical_receipt_for_task_verified("task-1")
612            .unwrap()
613            .unwrap();
614        assert_eq!(canonical.receipt_id, canonical_id);
615        assert!(store.legacy_receipt_for_task("task-1").is_none());
616    }
617
618    #[test]
619    fn load_rejects_duplicate_json_keys() {
620        let directory = tempdir().expect("temporary directory");
621        let path = directory.path().join("ledger.jsonl");
622        let store = ExecutionLedgerStore::new(&path);
623        store.append(task_started("task-1", "trace-1")).unwrap();
624        let content = std::fs::read_to_string(&path).unwrap();
625        let duplicated = content.replacen(
626            "\"task_id\":\"task-1\",",
627            "\"task_id\":\"task-1\",\"task_id\":\"task-1\",",
628            1,
629        );
630        std::fs::write(&path, duplicated).unwrap();
631
632        assert!(matches!(
633            store.load(),
634            Err(ExecutionLedgerError::Serialization(_))
635        ));
636    }
637
638    #[test]
639    fn load_rejects_noncanonical_json_whitespace() {
640        let directory = tempdir().expect("temporary directory");
641        let path = directory.path().join("ledger.jsonl");
642        let store = ExecutionLedgerStore::new(&path);
643        store.append(task_started("task-1", "trace-1")).unwrap();
644        let content = std::fs::read_to_string(&path).unwrap();
645        std::fs::write(&path, format!(" {content}")).unwrap();
646
647        assert!(matches!(
648            store.load(),
649            Err(ExecutionLedgerError::InvalidRecord(message))
650                if message == "execution ledger record is not canonical JSON"
651        ));
652    }
653
654    #[test]
655    fn by_task_filters_events_without_losing_order() {
656        let directory = tempdir().expect("temporary directory");
657        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
658        store.append(task_started("task-1", "trace-1")).unwrap();
659        store
660            .append(ExecutionEvent::PlanCreated {
661                task_id: "task-1".to_owned(),
662                trace_id: "trace-1".to_owned(),
663                plan_id: "plan-1".to_owned(),
664                plan_ref: "plan:1".to_owned(),
665                timestamp: "2026-08-09T12:00:00Z".to_owned(),
666                sequence_number: 0,
667                prev_hash: String::new(),
668            })
669            .unwrap();
670        store.append(task_started("task-2", "trace-2")).unwrap();
671        store
672            .append(context_delivered("task-1", "trace-1"))
673            .unwrap();
674        store.append(model_invoked("task-1", "trace-1")).unwrap();
675
676        let events = store.by_task("task-1");
677        assert_eq!(events.len(), 4);
678        assert_eq!(events[0].sequence_number(), 1);
679        assert_eq!(events[1].sequence_number(), 2);
680        assert_eq!(events[2].sequence_number(), 4);
681        assert_eq!(events[3].sequence_number(), 5);
682    }
683
684    #[test]
685    fn migration_reads_source_without_mutating_it() {
686        let directory = tempdir().expect("temporary directory");
687        let savings_path = directory.path().join("savings.jsonl");
688        let execution_path = directory.path().join("execution.jsonl");
689        let savings_event = crate::core::savings_ledger::event::SavingsEvent {
690            ts: "2026-08-09T12:00:00Z".to_owned(),
691            tool: "ctx_read".to_owned(),
692            mechanism: "compression".to_owned(),
693            model_id: "model-1".to_owned(),
694            tokenizer: "o200k_base".to_owned(),
695            baseline_tokens: 100,
696            actual_tokens: 60,
697            saved_tokens: 40,
698            bounce_adjustment: 0,
699            unit_price_per_m_usd: 1.0,
700            saved_usd: 0.00004,
701            repo_hash: "repo".to_owned(),
702            agent_id: "agent".to_owned(),
703            prev_hash: String::new(),
704            entry_hash: String::new(),
705            version: "test".to_owned(),
706            intent_tag: None,
707            outcome: None,
708            model_original: None,
709            model_routed: None,
710            routing_savings: None,
711            response_original_tokens: None,
712            response_delivered_tokens: None,
713            agent_chain_id: None,
714            chain_depth: None,
715            measurement_method: None,
716            evidence_class: None,
717            confidence: None,
718            request_id: None,
719            session_id: None,
720            trace_id: None,
721            solution_decision: None,
722            loc_added: None,
723            loc_removed: None,
724            path: None,
725            lines_added: None,
726            lines_removed: None,
727            net: None,
728            quality_signal: None,
729            attribution_group: None,
730            attribution_id: None,
731            baseline_ref: None,
732            price_version: None,
733            customer_approval: None,
734            settlement_status: None,
735            is_first_inject: None,
736            cache_read_per_m_usd: None,
737            cache_write_per_m_usd: None,
738        };
739        let mut second_savings_event = savings_event.clone();
740        second_savings_event.ts = "2026-08-09T12:00:01Z".to_owned();
741        second_savings_event.model_id = "model-2".to_owned();
742        crate::core::savings_ledger::store::append(&savings_path, savings_event).unwrap();
743        crate::core::savings_ledger::store::append(&savings_path, second_savings_event).unwrap();
744        let before = std::fs::read(&savings_path).unwrap();
745        let source_hashes: Vec<String> = crate::core::savings_ledger::store::load(&savings_path)
746            .into_iter()
747            .map(|event| event.entry_hash)
748            .collect();
749
750        let destination = ExecutionLedgerStore::new(execution_path);
751        assert_eq!(
752            migrate_from_savings_ledger_at(
753                &savings_path,
754                &destination,
755                "task-legacy",
756                "trace-legacy"
757            )
758            .unwrap(),
759            2
760        );
761        assert_eq!(before, std::fs::read(&savings_path).unwrap());
762        assert_eq!(
763            migrate_from_savings_ledger_at(
764                &savings_path,
765                &destination,
766                "task-legacy",
767                "trace-legacy"
768            )
769            .unwrap(),
770            0
771        );
772        let migrated_events = destination.by_task("task-legacy");
773        assert_eq!(migrated_events.len(), 4);
774        assert_eq!(
775            migrated_events
776                .iter()
777                .filter(|event| matches!(event, ExecutionEvent::PlanCreated { .. }))
778                .count(),
779            1
780        );
781        for source_hash in source_hashes {
782            assert!(migrated_events.iter().any(|event| {
783                matches!(event, ExecutionEvent::ModelInvoked { invocation_ref, .. } if invocation_ref.contains(&source_hash))
784            }));
785        }
786    }
787
788    #[test]
789    fn projections_summarize_cost_and_build_receipt() {
790        let directory = tempdir().expect("temporary directory");
791        let store = ExecutionLedgerStore::new(directory.path().join("ledger.jsonl"));
792        store.append(task_started("task-1", "trace-1")).unwrap();
793        store
794            .append(ExecutionEvent::PlanCreated {
795                task_id: "task-1".to_owned(),
796                trace_id: "trace-1".to_owned(),
797                plan_id: "plan-1".to_owned(),
798                plan_ref: "plan:1".to_owned(),
799                timestamp: "2026-08-09T12:00:00Z".to_owned(),
800                sequence_number: 0,
801                prev_hash: String::new(),
802            })
803            .unwrap();
804        store
805            .append(ExecutionEvent::ContextDelivered {
806                task_id: "task-1".to_owned(),
807                trace_id: "trace-1".to_owned(),
808                context_balance: ContextBalanceV1 {
809                    original_tokens: 100,
810                    materialized_tokens: 80,
811                    delivered_tokens: 60,
812                    provider_billed_tokens: 60,
813                },
814                timestamp: "2026-08-09T12:00:00Z".to_owned(),
815                sequence_number: 0,
816                prev_hash: String::new(),
817            })
818            .unwrap();
819        store
820            .append(context_delivered("task-1", "trace-1"))
821            .unwrap();
822        store
823            .append(model_invoked_with(
824                "task-1",
825                "trace-1",
826                "invocation-1",
827                "gpt-4o",
828                20,
829                10,
830            ))
831            .unwrap();
832        store
833            .append(model_invoked_with(
834                "task-1",
835                "trace-1",
836                "invocation-2",
837                "claude-sonnet-4.5",
838                30,
839                15,
840            ))
841            .unwrap();
842        store
843            .append(ExecutionEvent::ReceiptSigned {
844                task_id: "task-1".to_owned(),
845                trace_id: "trace-1".to_owned(),
846                receipt_id: "receipt-1".to_owned(),
847                receipt_hash: "sha256:receipt".to_owned(),
848                signature: "signature".to_owned(),
849                timestamp: "2026-08-09T12:00:02Z".to_owned(),
850                sequence_number: 0,
851                prev_hash: String::new(),
852            })
853            .unwrap();
854        assert!(matches!(
855            store.append(ExecutionEvent::OutcomeRecorded {
856                task_id: "task-1".to_owned(),
857                trace_id: "trace-1".to_owned(),
858                outcome_id: "outcome-1".to_owned(),
859                receipt_id: "receipt-1".to_owned(),
860                accepted: AcceptanceState::Accepted,
861                timestamp: "2026-08-09T12:00:03Z".to_owned(),
862                sequence_number: 0,
863                prev_hash: String::new(),
864            }),
865            Err(ExecutionLedgerError::InvalidChain(_))
866        ));
867
868        let summary = task_cost_summary_from_store(&store, "task-1");
869        assert_eq!(summary.total_tokens, 75);
870        assert_eq!(summary.model_calls, 2);
871        assert_eq!(
872            summary.cost_classification(),
873            lean_ctx_protocol::ReceiptValueClassificationV1::Estimated
874        );
875        assert_eq!(
876            summary.baseline_cost_classification(),
877            lean_ctx_protocol::ReceiptValueClassificationV1::Unavailable
878        );
879        let last_model_quote =
880            crate::core::gain::model_pricing::ModelPricing::load().quote(Some("claude-sonnet-4.5"));
881        let repriced_at_last_model = (last_model_quote.cost.estimate_usd(
882            summary.total_tokens_in,
883            summary.total_tokens_out,
884            0,
885            0,
886        ) * 1_000_000.0)
887            .round() as u64;
888        assert_ne!(summary.cost_micros, repriced_at_last_model);
889        let legacy_receipt = legacy_receipt_for_task_from_store(&store, "task-1").unwrap();
890        assert_eq!(
891            legacy_receipt.cost_classification(),
892            lean_ctx_protocol::ReceiptValueClassificationV1::Estimated
893        );
894        assert_eq!(
895            legacy_receipt.baseline_cost_classification(),
896            lean_ctx_protocol::ReceiptValueClassificationV1::Unavailable
897        );
898        assert_eq!(
899            legacy_receipt.legacy_receipt().actual_cost_micros,
900            summary.cost_micros
901        );
902        assert_eq!(
903            legacy_receipt.legacy_receipt().baseline_cost_micros,
904            legacy_receipt.legacy_receipt().actual_cost_micros
905        );
906        let entry = ExecutionLedgerEntryV1 {
907            task_id: "task-1".to_owned(),
908            legacy_estimated_actual_cost_micros: Some(
909                legacy_receipt.legacy_receipt().actual_cost_micros,
910            ),
911            legacy_estimated_baseline_cost_micros: Some(
912                legacy_receipt.legacy_receipt().baseline_cost_micros,
913            ),
914            legacy_receipt: Some(legacy_receipt.clone()),
915            predicted_cost_micros: None,
916            actual_etpao: None,
917            baseline_etpao: None,
918            predicted_etpao: None,
919        };
920        let serialized = serde_json::to_value(entry).unwrap();
921        assert!(serialized.get("legacy_receipt").is_some());
922        assert!(
923            serialized
924                .get("legacy_estimated_actual_cost_micros")
925                .is_some()
926        );
927        assert!(
928            serialized
929                .get("legacy_estimated_baseline_cost_micros")
930                .is_some()
931        );
932        assert!(serialized.get("receipt").is_none());
933        assert!(serialized.get("actual_cost_micros").is_none());
934        assert!(serialized.get("baseline_cost_micros").is_none());
935        let mut invalid = serialized.clone();
936        invalid["legacy_receipt"]["schema_version"] = serde_json::json!(2);
937        assert!(serde_json::from_value::<ExecutionLedgerEntryV1>(invalid).is_err());
938        let mut outcome_authority = serialized.clone();
939        outcome_authority["legacy_receipt"]["outcome_ref"] = serde_json::json!("outcome-1");
940        assert!(serde_json::from_value::<ExecutionLedgerEntryV1>(outcome_authority).is_err());
941        let mut signature_authority = serialized;
942        signature_authority["legacy_receipt"]["evidence_refs"][0]["signature_status"] =
943            serde_json::json!("Verified");
944        assert!(serde_json::from_value::<ExecutionLedgerEntryV1>(signature_authority).is_err());
945
946        let receipt = legacy_receipt.into_legacy_receipt();
947        assert_eq!(receipt.model_calls, 2);
948        assert_eq!(receipt.output_tokens, 25);
949        assert!(receipt.outcome_ref.is_none());
950    }
951}