crtx 0.1.0

CLI for the Cortex supervisory memory substrate.
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
//! `cortex ingest` — append session events to the JSONL ledger.
//!
//! The session file is a JSON document containing one or more
//! [`cortex_core::Event`] rows in the canonical wire shape (BUILD_SPEC §9.1).
//! Two top-level shapes are accepted:
//!
//! 1. `{"events": [Event, ...]}` — explicit envelope.
//! 2. A bare JSON array `[Event, ...]` — convenience for hand-rolled fixtures.
//! 3. A bare JSON object — interpreted as a single [`cortex_core::Event`].
//!
//! ## Idempotency
//!
//! Re-ingesting the same `session.json` is a **no-op**. The dedup key is
//! `Event::id`: any event whose id already appears in the on-disk JSONL log
//! is skipped, the chain head is unchanged, and the command exits
//! [`Exit::Ok`]. This is the lane 1.C anti-criterion — a second `cortex
//! ingest <same_file>` MUST NOT grow the ledger.
//!
//! ## User-source attestation (Lane 3.D.5, ADR 0010)
//!
//! `EventSource::User` events carry the strongest authorship claim in the
//! cortex ledger ("the operator did X"). To stop a forged session.json from
//! laundering attacker-authored events through ingest (THREATS T-EV-1) the
//! command refuses User-source events from file input UNLESS the operator
//! also passes [`IngestArgs::user_attestation`], which:
//!
//! 1. Reads exactly **32 raw bytes** from `<KEY_PATH>` (Ed25519 seed).
//! 2. Builds an in-process [`cortex_core::InMemoryAttestor`] from the seed.
//! 3. For each User event, constructs a canonical
//!    [`cortex_core::AttestationPreimage`] (ADR 0010 §1b) and signs it.
//! 4. Writes a corresponding `audit_records` row with operation
//!    `ingest_user_attested` to `<data_dir>/audit_records.jsonl`.
//!
//! The signature itself is **not** added to the on-disk Schema v1 event
//! (that's Lane S2.9 / ADR 0014's job). Schema v1 stays unchanged; the
//! attestation lives in the audit-records mirror.
//!
//! ### Why an in-memory key file in v0
//!
//! ADR 0010 §3 specifies an OS keychain (`KeychainAttestor`) backed by
//! macOS Keychain / Linux Secret Service / Windows DPAPI. Those backends
//! are scaffolded in `cortex-core::attestor` but the bodies are
//! `unimplemented!()` until lane 3.D.0+. v0 of this command therefore
//! takes a **path to a 32-byte raw private-key file** so operators can
//! exercise the end-to-end attestation flow today; the file is read once
//! and never written back to.
//
// TODO(T-3.D.0+): swap [`InMemoryAttestor`] for the real
// [`cortex_core::attestor::KeychainAttestor`] once the OS keychain
// backends ship and gate the file-key path behind an explicit
// `--unsafe-key-file` opt-in.

use std::collections::HashSet;
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Component, Path, PathBuf};

use chrono::Utc;
use clap::Args;
use cortex_core::{
    attest, compose_policy_outcomes, AttestationPreimage, Attestor, AuditRecord, Event, EventId,
    EventSource, InMemoryAttestor, LineageBinding, Outcome, PolicyContribution, PolicyDecision,
    PolicyOutcome, SourceIdentity, TrustTier, SCHEMA_VERSION_ATTESTATION,
};
use cortex_ledger::{
    JsonlLog, APPEND_ATTESTATION_REQUIRED_RULE_ID, APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
    APPEND_RUNTIME_MODE_RULE_ID,
};

use crate::exit::Exit;
use crate::output::{self, Envelope};
use crate::paths::DataLayout;

/// Required contributor rule id: an `EventSource::User` event was supplied
/// with the operator attestation envelope (ADR 0010 §1b, ADR 0026 §4).
pub const INGEST_USER_ATTESTATION_RULE_ID: &str = "ingest.user_attestation";
/// Required contributor rule id: the event-source trust tier meets the
/// ingest-default floor (ADR 0019 §3 canonical gate matrix).
pub const INGEST_EVENT_SOURCE_TIER_GATE_RULE_ID: &str = "ingest.event_source_tier_gate";
/// Required contributor rule id: the session input path lives under the
/// resolved root and contains no symlink or parent-traversal escape.
pub const INGEST_SYMLINK_ROOT_VALIDATION_RULE_ID: &str = "ingest.symlink_root_validation";

/// Minimum trust tier that an `EventSource` must satisfy to be ingested
/// through the default unsigned path. Per ADR 0019 §3 the audit-visible floor
/// is `Observed`; anything below that has no auditable identity and MUST be
/// refused.
pub const INGEST_MINIMUM_TRUST_TIER: TrustTier = TrustTier::Observed;

/// Filename of the `audit_records` JSONL mirror written alongside
/// `events.jsonl` in the data directory. One JSON object per line.
const AUDIT_RECORDS_FILENAME: &str = "audit_records.jsonl";

/// Stable `operation` string for audit rows produced by attested ingest.
/// Documented in ADR 0010 §4 (operations table).
pub const OPERATION_INGEST_USER_ATTESTED: &str = "ingest_user_attested";

/// `cortex ingest` flags.
#[derive(Debug, Args)]
pub struct IngestArgs {
    /// Path to the session JSON file.
    #[arg(value_name = "SESSION")]
    pub session: PathBuf,

    /// Override the JSONL event-log path. Defaults to the layout-resolved
    /// path (same default as `cortex init`).
    #[arg(long = "event-log", value_name = "PATH")]
    pub event_log: Option<PathBuf>,

    /// Override the SQLite DB path. Carried through so the layout resolves
    /// the same data dir as `cortex init` even though ingest does not yet
    /// touch SQL.
    #[arg(long, value_name = "PATH")]
    pub db: Option<PathBuf>,

    /// Path to a **32-byte raw Ed25519 signing-key file** (ADR 0010 §3).
    ///
    /// When supplied, every `EventSource::User` event in the session file
    /// is signed with this key and an `audit_records` row of operation
    /// `ingest_user_attested` is written for each. When omitted, ingest
    /// REFUSES to append any `EventSource::User` event and exits
    /// `Exit::PreconditionUnmet` (`7`) — see lane 3.D.5 / THREATS T-EV-1.
    ///
    /// **File format:** exactly 32 raw bytes (no PEM, no base64, no header).
    /// Anything else exits `Exit::PreconditionUnmet` with a clear message.
    /// **Not for production:** the OS keychain backend
    /// (`KeychainAttestor`) is the production path; this flag exists so v0
    /// of cortex can exercise the end-to-end attestation flow before the
    /// keychain backends land in lane 3.D.0+.
    #[arg(long = "user-attestation", value_name = "KEY_PATH")]
    pub user_attestation: Option<PathBuf>,
}

/// A parse or precondition error that carries both an [`Exit`] code and a
/// human-readable explanation. Used so `run()` can include the explanation in
/// the JSON envelope (BUG-6) while still printing it to stderr in text mode
/// (BUG-3).
#[derive(Debug)]
pub(crate) struct IngestError {
    pub(crate) exit: Exit,
    pub(crate) detail: String,
}

impl IngestError {
    fn new(exit: Exit, detail: impl Into<String>) -> Self {
        Self {
            exit,
            detail: detail.into(),
        }
    }
}

/// Outcome of a single ingest call.
#[derive(Debug, Clone)]
pub struct IngestOutcome {
    /// Event IDs that were appended this invocation (in append order).
    pub appended: Vec<EventId>,
    /// Event IDs that were skipped because they already appeared in the log.
    pub skipped: Vec<EventId>,
    /// New chain head after this call (None if log is empty).
    pub head: Option<String>,
    /// Event IDs of `EventSource::User` events that were attested this
    /// invocation (in append order). Empty when `--user-attestation` was
    /// not supplied (in which case the ingest refuses to start at all if
    /// any User event is present).
    pub attested_user_events: Vec<EventId>,
}

/// Run the ingest command.
pub fn run(args: IngestArgs) -> Exit {
    match run_inner(args) {
        Ok(outcome) => {
            if output::json_enabled() {
                let payload = serde_json::json!({
                    "appended": outcome.appended.iter().map(EventId::to_string).collect::<Vec<_>>(),
                    "skipped": outcome.skipped.iter().map(EventId::to_string).collect::<Vec<_>>(),
                    "attested_user_events": outcome
                        .attested_user_events
                        .iter()
                        .map(EventId::to_string)
                        .collect::<Vec<_>>(),
                    "appended_count": outcome.appended.len(),
                    "skipped_count": outcome.skipped.len(),
                    "attested_user_count": outcome.attested_user_events.len(),
                    "chain_head": outcome.head,
                });
                let envelope = Envelope::new("cortex.ingest", Exit::Ok, payload);
                output::emit(&envelope, Exit::Ok)
            } else {
                print_summary(&outcome);
                Exit::Ok
            }
        }
        Err(e) => {
            if output::json_enabled() {
                let payload = serde_json::json!({
                    "appended": Vec::<String>::new(),
                    "skipped": Vec::<String>::new(),
                    "appended_count": 0,
                    "skipped_count": 0,
                    "status": "error",
                    "detail": e.detail,
                });
                let envelope = Envelope::new("cortex.ingest", e.exit, payload);
                output::emit(&envelope, e.exit)
            } else {
                e.exit
            }
        }
    }
}

/// Programmatic entry point for tests.
pub fn run_inner(args: IngestArgs) -> Result<IngestOutcome, IngestError> {
    let layout = DataLayout::resolve(args.db, args.event_log)
        .map_err(|e| IngestError::new(e, "failed to resolve data layout"))?;

    // ADR 0026: symlink_root_validation registers as a policy contributor.
    // The check still fails closed before the policy composer when the path
    // is invalid so the operator gets the existing diagnostic that names
    // the offending root.
    validate_session_input_path(&args.session)
        .map_err(|e| IngestError::new(e, format!("invalid session path `{}`", args.session.display())))?;
    let raw = fs::read(&args.session).map_err(|io_err| {
        let detail = format!(
            "cannot read session file `{}`: {io_err}",
            args.session.display()
        );
        eprintln!("ingest: {detail}");
        IngestError::new(Exit::PreconditionUnmet, detail)
    })?;
    let events = parse_events(&raw)?;

    let user_event_ids: Vec<EventId> = events
        .iter()
        .filter(|e| matches!(e.source, EventSource::User))
        .map(|e| e.id)
        .collect();

    // Compose the ADR 0026 ingest policy decision over the parsed input.
    // Three contributors register here:
    // - `ingest.symlink_root_validation` (Allow at this point — the
    //   path-traversal guard above already returned PreconditionUnmet on
    //   failure; the contributor is surfaced so the lattice can replay the
    //   decision explainably).
    // - `ingest.user_attestation` (Allow when an attestor is supplied OR no
    //   User events appear; Reject otherwise).
    // - `ingest.event_source_tier_gate` (Allow when every parsed event meets
    //   `INGEST_MINIMUM_TRUST_TIER`; Reject otherwise, naming the first
    //   offending event id).
    let decision =
        ingest_policy_decision(&events, &user_event_ids, args.user_attestation.is_some());
    if matches!(
        decision.final_outcome,
        PolicyOutcome::Reject | PolicyOutcome::Quarantine
    ) {
        emit_ingest_policy_refusal(&decision, &user_event_ids);
        return Err(IngestError::new(
            Exit::PreconditionUnmet,
            "ingest refused by ADR 0026 policy; see stderr for contributor details",
        ));
    }

    let attestor = match args.user_attestation.as_deref() {
        Some(key_path) => Some(
            load_attestor_from_key_file(key_path)
                .map_err(|e| IngestError::new(e, "failed to load --user-attestation key"))?,
        ),
        None => None,
    };

    // Open log + collect existing ids for dedup.
    let mut log = JsonlLog::open(&layout.event_log_path)
        .map_err(|e| IngestError::new(map_jsonl_err(e), "failed to open event log"))?;
    let existing_ids = collect_existing_ids(&log)
        .map_err(|e| IngestError::new(e, "failed to read existing event ids from log"))?;

    // Pre-existing chain length — used as the base for `ChainPosition`
    // bindings in attestation preimages so a captured signature can't be
    // re-played at a different chain index (ADR 0010 §2 Option B).
    let chain_base: u64 = existing_ids.len() as u64;

    let ledger_id = derive_ledger_id(&layout.event_log_path);
    let audit_records_path = layout.data_dir.join(AUDIT_RECORDS_FILENAME);

    let mut appended = Vec::new();
    let mut skipped = Vec::new();
    let mut attested_user_events = Vec::new();
    let mut audit_rows: Vec<AuditRecord> = Vec::new();

    for event in events {
        if existing_ids.contains(&event.id) {
            skipped.push(event.id);
            continue;
        }

        // If this is a User event AND we have an attestor, build + sign the
        // canonical preimage and queue an audit row. We do this BEFORE
        // appending the event so the chain_position binding matches the
        // index the row will land at.
        let is_user = matches!(event.source, EventSource::User);
        if is_user {
            let attestor = attestor
                .as_ref()
                .expect("user events refused above when no attestor present");
            let chain_position = chain_base + appended.len() as u64;
            let preimage = build_user_preimage(&event, &ledger_id, chain_position, attestor);
            let attestation = attest(&preimage, attestor);
            let actor_json = serde_json::json!({
                "kind": "user",
                "event_id": event.id.to_string(),
                "key_id": attestation.key_id,
                "signature_hex": hex_lower(&attestation.signature),
                "signed_at": attestation.signed_at,
            });
            let row = AuditRecord::new(
                actor_json,
                OPERATION_INGEST_USER_ATTESTED.to_string(),
                event.id.to_string(),
                attestation.signed_at,
                Outcome::Success,
            );
            audit_rows.push(row);
            attested_user_events.push(event.id);
        }

        let id = event.id;
        // Compose the ADR 0026 ledger.append policy decision for this
        // row. `EventSource::User` rows reach this point only after the
        // upstream attestor preflight (which read `--user-attestation`
        // and signed an audit row), so the attestation contributor is
        // `Allow`. All other sources are `Allow` because ingest does not
        // mint user-authority rows for them.
        let policy = ingest_append_policy(&event.source, is_user);
        log.append(event, &policy)
            .map_err(|e| IngestError::new(map_jsonl_err(e), format!("failed to append event {id}")))?;
        appended.push(id);
    }

    if !audit_rows.is_empty() {
        append_audit_rows(&audit_records_path, &audit_rows)
            .map_err(|e| IngestError::new(e, "failed to write audit records"))?;
    }

    Ok(IngestOutcome {
        appended,
        skipped,
        head: log.head().map(str::to_owned),
        attested_user_events,
    })
}

/// Compose the ADR 0026 policy decision for a parsed ingest batch.
///
/// The decision combines three contributors:
///
/// - `ingest.symlink_root_validation` (Allow on entry — the path traversal
///   guard above already failed closed for symlink/parent escapes).
/// - `ingest.user_attestation` (Allow when an attestor was supplied OR no
///   `EventSource::User` events appear in the input; Reject otherwise).
/// - `ingest.event_source_tier_gate` (Allow when every event meets
///   `INGEST_MINIMUM_TRUST_TIER`; Reject otherwise, naming the offending
///   event id and its computed tier).
///
/// The composed `final_outcome` is the strongest of the three per ADR 0026
/// §2 total order. Callers MUST refuse to append on `Reject`/`Quarantine`.
#[must_use]
pub fn ingest_policy_decision(
    events: &[Event],
    user_event_ids: &[EventId],
    attestor_present: bool,
) -> PolicyDecision {
    let symlink_contribution = PolicyContribution::new(
        INGEST_SYMLINK_ROOT_VALIDATION_RULE_ID,
        PolicyOutcome::Allow,
        "session input path resolved under a permitted root with no symlink or parent-traversal escape",
    )
    .expect("static policy contribution is valid");

    let user_attestation_contribution = if user_event_ids.is_empty() {
        PolicyContribution::new(
            INGEST_USER_ATTESTATION_RULE_ID,
            PolicyOutcome::Allow,
            "input contains no EventSource::User events; operator attestation is not required",
        )
        .expect("static policy contribution is valid")
    } else if attestor_present {
        PolicyContribution::new(
            INGEST_USER_ATTESTATION_RULE_ID,
            PolicyOutcome::Allow,
            format!(
                "operator attestation envelope supplied for {} EventSource::User event(s)",
                user_event_ids.len()
            ),
        )
        .expect("static policy contribution is valid")
    } else {
        let ids: Vec<String> = user_event_ids.iter().map(EventId::to_string).collect();
        PolicyContribution::new(
            INGEST_USER_ATTESTATION_RULE_ID,
            PolicyOutcome::Reject,
            format!(
                "policy.ingest.user_attestation.missing: {} EventSource::User event(s) supplied without --user-attestation; offending ids=[{}]",
                ids.len(),
                ids.join(", ")
            ),
        )
        .expect("static policy contribution is valid")
    };

    let tier_contribution = match first_event_below_minimum_tier(events, attestor_present) {
        Some((event_id, tier)) => PolicyContribution::new(
            INGEST_EVENT_SOURCE_TIER_GATE_RULE_ID,
            PolicyOutcome::Reject,
            format!(
                "policy.ingest.event_source_tier_gate.below_minimum: event {event_id} has tier {tier:?} which is below required {INGEST_MINIMUM_TRUST_TIER:?} (ADR 0019 §3)"
            ),
        )
        .expect("static policy contribution is valid"),
        None => PolicyContribution::new(
            INGEST_EVENT_SOURCE_TIER_GATE_RULE_ID,
            PolicyOutcome::Allow,
            format!(
                "every event meets the ingest trust tier floor of {INGEST_MINIMUM_TRUST_TIER:?} (ADR 0019 §3)"
            ),
        )
        .expect("static policy contribution is valid"),
    };

    compose_policy_outcomes(
        vec![
            symlink_contribution,
            user_attestation_contribution,
            tier_contribution,
        ],
        None,
    )
}

/// Classify the trust tier of an [`EventSource`] for ingest purposes per
/// ADR 0019 §3. `User` events depend on whether an operator attestor is
/// present in this invocation: with an attestor, `User` reaches `Operator`
/// tier; without, it stays `Untrusted`.
#[must_use]
pub fn event_source_trust_tier(source: &EventSource, attestor_present: bool) -> TrustTier {
    match source {
        EventSource::User => {
            if attestor_present {
                TrustTier::Operator
            } else {
                TrustTier::Untrusted
            }
        }
        EventSource::ManualCorrection => {
            if attestor_present {
                TrustTier::Operator
            } else {
                TrustTier::Untrusted
            }
        }
        EventSource::ChildAgent { model } => {
            if model.trim().is_empty() {
                TrustTier::Untrusted
            } else {
                TrustTier::Observed
            }
        }
        EventSource::Tool { name } => {
            if name.trim().is_empty() {
                TrustTier::Untrusted
            } else {
                TrustTier::Observed
            }
        }
        EventSource::Runtime | EventSource::ExternalOutcome => TrustTier::Observed,
    }
}

fn first_event_below_minimum_tier(
    events: &[Event],
    attestor_present: bool,
) -> Option<(EventId, TrustTier)> {
    for event in events {
        let tier = event_source_trust_tier(&event.source, attestor_present);
        if tier < INGEST_MINIMUM_TRUST_TIER {
            return Some((event.id, tier));
        }
    }
    None
}

fn emit_ingest_policy_refusal(decision: &PolicyDecision, user_event_ids: &[EventId]) {
    let contributing: Vec<&str> = decision
        .contributing
        .iter()
        .map(|contribution| contribution.rule_id.as_str())
        .collect();
    eprintln!(
        "ingest: refused by ADR 0026 policy outcome {:?}; contributing rules: [{}]; no state was changed",
        decision.final_outcome,
        contributing.join(", ")
    );
    for contribution in decision
        .contributing
        .iter()
        .chain(decision.discarded.iter())
    {
        eprintln!(
            "  - {}: {}",
            contribution.rule_id.as_str(),
            contribution.reason
        );
    }
    if !user_event_ids.is_empty() {
        let ids: Vec<String> = user_event_ids.iter().map(EventId::to_string).collect();
        eprintln!(
            "  EventSource::User event id(s) in input: [{}]",
            ids.join(", ")
        );
    }
}

fn validate_session_input_path(path: &Path) -> Result<(), Exit> {
    if path
        .components()
        .any(|component| matches!(component, Component::ParentDir))
    {
        eprintln!(
            "ingest: refusing session path `{}`: parent-directory traversal is not accepted; no state was changed.",
            path.display(),
        );
        return Err(Exit::PreconditionUnmet);
    }

    let root = session_input_root(path)?;
    let canonical_root = fs::canonicalize(&root).map_err(|e| {
        eprintln!(
            "ingest: cannot inspect session root `{}`: {e}; no state was changed.",
            root.display(),
        );
        Exit::PreconditionUnmet
    })?;
    let canonical_session = fs::canonicalize(path).map_err(|e| {
        eprintln!(
            "ingest: cannot inspect session path `{}`: {e}; no state was changed.",
            path.display(),
        );
        Exit::PreconditionUnmet
    })?;

    if !canonical_session.starts_with(&canonical_root) {
        eprintln!(
            "ingest: refusing session path `{}`: symlink resolves outside root `{}`; no state was changed.",
            path.display(),
            canonical_root.display(),
        );
        return Err(Exit::PreconditionUnmet);
    }

    Ok(())
}

fn session_input_root(path: &Path) -> Result<PathBuf, Exit> {
    let cwd = env::current_dir().map_err(|e| {
        eprintln!("ingest: cannot inspect current directory: {e}; no state was changed.");
        Exit::PreconditionUnmet
    })?;

    if path.is_absolute() {
        if path.starts_with(&cwd) {
            return Ok(cwd);
        }
        return path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .map(Path::to_path_buf)
            .ok_or(Exit::PreconditionUnmet);
    }

    Ok(cwd)
}

fn collect_existing_ids(log: &JsonlLog) -> Result<HashSet<EventId>, Exit> {
    let mut ids = HashSet::new();
    for item in log.iter().map_err(map_jsonl_err)? {
        let e = item.map_err(map_jsonl_err)?;
        ids.insert(e.id);
    }
    Ok(ids)
}

/// Build the ADR 0026 ledger.append policy decision for the row currently
/// being ingested.
///
/// - `EventSource::User` rows reach this helper only after the upstream
///   `--user-attestation` gate proved an attestor was supplied and the
///   per-event preimage was signed. That makes the attestation
///   contributor `Allow`; otherwise the run would have already exited at
///   line ~172 of `run_inner`.
/// - Non-user rows do not need a user attestation and the contributor is
///   trivially `Allow`.
/// - The runtime-mode contributor is `Warn` because ingest writes into
///   the local-development ledger (ADR 0037 §2 `DevOnly`); downstream
///   consumers must not pass ingested rows off as authority-grade.
fn ingest_append_policy(source: &EventSource, is_attested_user: bool) -> PolicyDecision {
    let attestation_reason = if matches!(source, EventSource::User) {
        debug_assert!(
            is_attested_user,
            "ingest: User event reached append without prior attestation gate"
        );
        "ingest: user-source event attested by --user-attestation preimage"
    } else {
        "ingest: non-user event does not require user attestation"
    };
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "ingest: event source tier gate satisfied (user events attested upstream)",
            )
            .expect("static policy contribution is valid"),
            PolicyContribution::new(
                APPEND_ATTESTATION_REQUIRED_RULE_ID,
                PolicyOutcome::Allow,
                attestation_reason,
            )
            .expect("static policy contribution is valid"),
            PolicyContribution::new(
                APPEND_RUNTIME_MODE_RULE_ID,
                PolicyOutcome::Warn,
                "ingest: unsigned local-development ledger row (ADR 0037 §2 DevOnly)",
            )
            .expect("static policy contribution is valid"),
        ],
        None,
    )
}

/// Permissive parse: accept envelope `{events: [..]}`, bare array, or bare
/// single Event. Any other shape returns an [`IngestError`] with a
/// descriptive message explaining what was wrong. The error is also printed
/// to stderr so that non-`--json` callers see an explanation (BUG-3).
fn parse_events(raw: &[u8]) -> Result<Vec<Event>, IngestError> {
    let make_err = |detail: String| -> IngestError {
        eprintln!("ingest: {detail}");
        IngestError::new(Exit::Usage, detail)
    };

    let value: serde_json::Value = serde_json::from_slice(raw).map_err(|parse_err| {
        make_err(format!(
            "failed to parse session JSON: {parse_err}; \
             expected an object with an \"events\" array, a bare array of events, \
             or a single event object"
        ))
    })?;
    match value {
        serde_json::Value::Object(mut map) => {
            if let Some(events_val) = map.remove("events") {
                let events: Vec<Event> =
                    serde_json::from_value(events_val).map_err(|e| {
                        make_err(format!(
                            "failed to parse session JSON: \"events\" array contains \
                             invalid event objects: {e}"
                        ))
                    })?;
                Ok(events)
            } else {
                // Treat the whole object as a single Event.
                let event: Event =
                    serde_json::from_value(serde_json::Value::Object(map)).map_err(|e| {
                        make_err(format!(
                            "failed to parse session JSON: top-level object is not a \
                             valid event and has no \"events\" key: {e}"
                        ))
                    })?;
                Ok(vec![event])
            }
        }
        serde_json::Value::Array(_) => {
            let events: Vec<Event> = serde_json::from_value(value).map_err(|e| {
                make_err(format!(
                    "failed to parse session JSON: top-level array contains \
                     invalid event objects (expected array of event objects, \
                     e.g. [{{\"id\": ...}}], not primitives): {e}"
                ))
            })?;
            Ok(events)
        }
        _ => Err(make_err(
            "failed to parse session JSON: wrong shape — expected object with \
             \"events\" array or array of events, got a primitive (string, number, \
             boolean, or null)"
                .to_string(),
        )),
    }
}

/// Read a 32-byte raw Ed25519 seed from `path` and wrap it in an
/// [`InMemoryAttestor`]. Anything other than exactly 32 bytes is rejected
/// with [`Exit::PreconditionUnmet`] and a clear stderr message.
fn load_attestor_from_key_file(path: &Path) -> Result<InMemoryAttestor, Exit> {
    let bytes = fs::read(path).map_err(|e| {
        eprintln!(
            "ingest: cannot read --user-attestation key file `{}`: {e}",
            path.display(),
        );
        Exit::PreconditionUnmet
    })?;
    if bytes.len() != 32 {
        eprintln!(
            "ingest: --user-attestation key file `{}` must be exactly 32 raw bytes \
             (Ed25519 seed); got {} bytes",
            path.display(),
            bytes.len(),
        );
        return Err(Exit::PreconditionUnmet);
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&bytes);
    Ok(InMemoryAttestor::from_seed(&seed))
}

/// Build the canonical [`AttestationPreimage`] for a `EventSource::User`
/// event being ingested at chain index `chain_position`.
///
/// `ledger_id` is derived from the event-log path stem so a captured
/// signature for `events.jsonl` cannot be replayed under a different
/// ledger; `chain_position` ties the signature to its position in the
/// chain (ADR 0010 §2 Option B).
///
/// The preimage's `payload_hash` is **recomputed** from `event.payload`
/// via [`cortex_ledger::payload_hash`] so that it matches whatever
/// [`cortex_ledger::JsonlLog::append`] will write after `seal()`. Trusting
/// the caller-supplied `event.payload_hash` would let a forged session.json
/// claim arbitrary hashes for its payloads and still pass verification.
pub fn build_user_preimage(
    event: &Event,
    ledger_id: &str,
    chain_position: u64,
    attestor: &InMemoryAttestor,
) -> AttestationPreimage {
    AttestationPreimage {
        schema_version: SCHEMA_VERSION_ATTESTATION,
        source: SourceIdentity::User,
        event_id: event.id.to_string(),
        payload_hash: cortex_ledger::payload_hash(&event.payload),
        session_id: event.session_id.clone().unwrap_or_default(),
        ledger_id: ledger_id.to_string(),
        lineage: LineageBinding::ChainPosition(chain_position),
        signed_at: Utc::now(),
        key_id: attestor.key_id().to_string(),
    }
}

/// Stable identifier for the ledger this attestation binds to. Derived
/// from the event-log file stem so the audit row + signature both refer
/// to "this jsonl file" without leaking absolute paths.
pub fn derive_ledger_id(event_log_path: &Path) -> String {
    event_log_path
        .file_stem()
        .and_then(|s| s.to_str())
        .map_or_else(|| "events".to_string(), str::to_owned)
}

/// Append serialized audit rows to `<data_dir>/audit_records.jsonl`. One
/// JSON object per line; the file is created on first write.
fn append_audit_rows(path: &Path, rows: &[AuditRecord]) -> Result<(), Exit> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() && !parent.exists() {
            fs::create_dir_all(parent).map_err(|_| Exit::PreconditionUnmet)?;
        }
    }
    let mut f = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(|_| Exit::PreconditionUnmet)?;
    for row in rows {
        let line = serde_json::to_string(row).map_err(|_| Exit::Internal)?;
        writeln!(f, "{line}").map_err(|_| Exit::Internal)?;
    }
    f.sync_all().map_err(|_| Exit::Internal)?;
    Ok(())
}

/// Lowercase hex (no separators) — local helper so we don't add a `hex`
/// crate just for one signature field.
fn hex_lower(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

fn map_jsonl_err(e: cortex_ledger::JsonlError) -> Exit {
    use cortex_ledger::JsonlError as J;
    match e {
        J::Decode { .. } | J::ChainBroken(_) => Exit::ChainCorruption,
        J::Validation(_) => Exit::PreconditionUnmet,
        J::Encode(_) | J::Io { .. } => Exit::Internal,
    }
}

fn print_summary(out: &IngestOutcome) {
    for id in &out.appended {
        println!("appended {id}");
    }
    for id in &out.skipped {
        println!("skipped  {id} (already in log)");
    }
    println!("appended_count = {}", out.appended.len());
    println!("skipped_count  = {}", out.skipped.len());
    if !out.attested_user_events.is_empty() {
        println!("attested_user_count = {}", out.attested_user_events.len());
    }
    match &out.head {
        Some(h) => println!("chain_head     = {h}"),
        None => println!("chain_head     = <empty>"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use cortex_core::{canonical, verify, Attestation, EventSource, EventType, SCHEMA_VERSION};
    use std::io::{Read, Write};
    use std::path::PathBuf;
    use tempfile::tempdir;

    fn write_session(path: &std::path::Path, events: &[Event]) {
        let envelope = serde_json::json!({"events": events});
        let mut f = std::fs::File::create(path).unwrap();
        f.write_all(serde_json::to_string_pretty(&envelope).unwrap().as_bytes())
            .unwrap();
    }

    fn make_event() -> Event {
        // A child_agent event so it doesn't trip the User-source attestation
        // gate. Lane-3.D.5 tests below build their own User events explicitly.
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc::now(),
            recorded_at: Utc::now(),
            source: EventSource::ChildAgent {
                model: "test-model".into(),
            },
            event_type: EventType::AgentResponse,
            trace_id: None,
            session_id: Some("test".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"text": "hello"}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    #[test]
    fn ingest_then_reingest_is_noop() {
        let tmp = tempdir().unwrap();
        let session_path = tmp.path().join("session.json");
        let event = make_event();
        write_session(&session_path, &[event]);

        let args = IngestArgs {
            session: session_path.clone(),
            event_log: Some(tmp.path().join("events.jsonl")),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let first = run_inner(args).unwrap();
        assert_eq!(first.appended.len(), 1);
        assert_eq!(first.skipped.len(), 0);
        let head_after_first = first.head.clone();
        assert!(head_after_first.is_some());

        let args2 = IngestArgs {
            session: session_path,
            event_log: Some(tmp.path().join("events.jsonl")),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let second = run_inner(args2).unwrap();
        assert_eq!(second.appended.len(), 0, "re-ingest must append nothing");
        assert_eq!(second.skipped.len(), 1);
        assert_eq!(
            second.head, head_after_first,
            "chain head must be unchanged across idempotent re-ingest"
        );
    }

    #[test]
    fn parse_envelope_array_or_single() {
        let e = make_event();
        let envelope = serde_json::to_vec(&serde_json::json!({"events": [e.clone()]})).unwrap();
        assert_eq!(parse_events(&envelope).unwrap().len(), 1);

        let array = serde_json::to_vec(&serde_json::json!([e.clone(), e.clone()])).unwrap();
        assert_eq!(parse_events(&array).unwrap().len(), 2);

        let single = serde_json::to_vec(&e).unwrap();
        assert_eq!(parse_events(&single).unwrap().len(), 1);

        assert_eq!(parse_events(b"not json").unwrap_err().exit, Exit::Usage);
    }

    // -- Lane 3.D.5 ------------------------------------------------------

    /// Path to the checked-in `forged-user-event.json` fixture.
    fn forged_user_fixture() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("forged-user-event.json")
    }

    /// Path to the deterministic 32-byte test key file.
    fn attested_key_fixture() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("attested-user-event-key.bin")
    }

    /// Acceptance #1: `forged-user-event.json` ingested without the
    /// `--user-attestation` flag MUST exit `Exit::PreconditionUnmet` (7)
    /// and append nothing to the log.
    #[test]
    fn ingest_rejects_user_source_without_attestation() {
        let tmp = tempdir().unwrap();
        let log = tmp.path().join("events.jsonl");
        let args = IngestArgs {
            session: forged_user_fixture(),
            event_log: Some(log.clone()),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let err = run_inner(args).expect_err("must refuse User events without flag");
        assert_eq!(err.exit, Exit::PreconditionUnmet);
        // The log file MUST NOT exist or MUST be empty — the gate is
        // checked BEFORE JsonlLog::open, so the file should not be created.
        if log.exists() {
            assert_eq!(
                std::fs::metadata(&log).unwrap().len(),
                0,
                "no event should have been appended"
            );
        }
    }

    #[test]
    fn ingest_rejects_parent_traversal_session_path_without_mutation() {
        let tmp = tempdir().unwrap();
        let session_path = tmp.path().join("session.json");
        let traversal_path = tmp.path().join("inputs").join("..").join("session.json");
        let log = tmp.path().join("events.jsonl");
        let event = make_event();
        write_session(&session_path, &[event]);

        let args = IngestArgs {
            session: traversal_path,
            event_log: Some(log.clone()),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let err = run_inner(args).expect_err("parent traversal must be rejected");
        assert_eq!(err.exit, Exit::PreconditionUnmet);
        assert!(
            !log.exists(),
            "parent traversal rejection must happen before opening the event log"
        );
    }

    #[cfg(unix)]
    #[test]
    fn ingest_rejects_root_escaping_session_symlink_without_mutation() {
        use std::os::unix::fs::symlink;

        let tmp = tempdir().unwrap();
        let outside = tempdir().unwrap();
        let outside_session = outside.path().join("session.json");
        let symlink_session = tmp.path().join("session-link.json");
        let log = tmp.path().join("events.jsonl");
        let event = make_event();
        write_session(&outside_session, &[event]);
        symlink(&outside_session, &symlink_session).unwrap();

        let args = IngestArgs {
            session: symlink_session,
            event_log: Some(log.clone()),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let err = run_inner(args).expect_err("root-escaping symlink must be rejected");
        assert_eq!(err.exit, Exit::PreconditionUnmet);
        assert!(
            !log.exists(),
            "symlink rejection must happen before opening the event log"
        );
    }

    /// Acceptance #2: same fixture WITH a valid attestation key exits
    /// `Exit::Ok` and produces an `audit_records.jsonl` row whose
    /// `operation` is `ingest_user_attested`.
    #[test]
    fn ingest_accepts_user_source_with_valid_attestation() {
        let tmp = tempdir().unwrap();
        let log = tmp.path().join("events.jsonl");
        let db = tmp.path().join("cortex.db");
        let args = IngestArgs {
            session: forged_user_fixture(),
            event_log: Some(log.clone()),
            db: Some(db),
            user_attestation: Some(attested_key_fixture()),
        };
        let out = run_inner(args).expect("must accept with valid attestation");
        assert_eq!(out.appended.len(), 1);
        assert_eq!(out.attested_user_events.len(), 1);
        // Audit-records mirror sits next to events.jsonl in the data dir.
        let audit_path = tmp.path().join(AUDIT_RECORDS_FILENAME);
        assert!(
            audit_path.exists(),
            "audit_records.jsonl must be written when an attested User event is ingested"
        );
        let raw = std::fs::read_to_string(&audit_path).unwrap();
        let row: AuditRecord = serde_json::from_str(raw.lines().next().unwrap()).unwrap();
        assert_eq!(row.operation, OPERATION_INGEST_USER_ATTESTED);
        assert_eq!(row.target_ref, out.attested_user_events[0].to_string());
        assert!(matches!(row.outcome, Outcome::Success));
    }

    /// Acceptance #3: the audit row's `actor_json` carries the attestation
    /// triple — `key_id`, `signature_hex`, and `signed_at` — plus the
    /// event id (so the row can be linked back to the event).
    #[test]
    fn ingest_audit_row_has_signature_field() {
        let tmp = tempdir().unwrap();
        let log = tmp.path().join("events.jsonl");
        let args = IngestArgs {
            session: forged_user_fixture(),
            event_log: Some(log),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: Some(attested_key_fixture()),
        };
        let _ = run_inner(args).expect("attested ingest");

        let audit_path = tmp.path().join(AUDIT_RECORDS_FILENAME);
        let mut s = String::new();
        std::fs::File::open(&audit_path)
            .unwrap()
            .read_to_string(&mut s)
            .unwrap();
        let row: AuditRecord = serde_json::from_str(s.lines().next().unwrap()).unwrap();
        let actor = &row.actor_json;
        assert_eq!(actor["kind"], "user");
        assert!(actor["event_id"].is_string(), "event_id must be present");
        assert!(actor["key_id"].is_string(), "key_id must be present");
        let sig_hex = actor["signature_hex"]
            .as_str()
            .expect("signature_hex must be a string");
        assert_eq!(
            sig_hex.len(),
            128,
            "Ed25519 signature is 64 bytes -> 128 hex chars"
        );
        assert!(sig_hex.chars().all(|c| c.is_ascii_hexdigit()));
        assert!(actor["signed_at"].is_string(), "signed_at must be present");
    }

    /// Acceptance #4: the produced signature, when re-verified via
    /// `cortex_core::verify` against a freshly-rebuilt canonical preimage,
    /// passes — i.e. the audit row really is a valid attestation, not a
    /// random blob.
    #[test]
    fn ingest_signature_verifies_against_canonical_preimage() {
        let tmp = tempdir().unwrap();
        let log = tmp.path().join("events.jsonl");
        let args = IngestArgs {
            session: forged_user_fixture(),
            event_log: Some(log.clone()),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: Some(attested_key_fixture()),
        };
        let out = run_inner(args).expect("attested ingest");

        // Read the persisted event back so we can recover its payload_hash
        // and session_id (the attestor saw whatever was on disk in the
        // fixture, not a recomputed value).
        let raw_events = std::fs::read_to_string(&log).unwrap();
        let event: Event =
            serde_json::from_str(raw_events.lines().next().expect("one event line")).unwrap();
        assert_eq!(event.id, out.appended[0]);

        // Recover the audit row for this event.
        let audit_path = tmp.path().join(AUDIT_RECORDS_FILENAME);
        let raw_audit = std::fs::read_to_string(&audit_path).unwrap();
        let row: AuditRecord =
            serde_json::from_str(raw_audit.lines().next().expect("one audit line")).unwrap();
        let actor = &row.actor_json;
        let key_id = actor["key_id"].as_str().unwrap().to_string();
        let sig_hex = actor["signature_hex"].as_str().unwrap();
        let signed_at: chrono::DateTime<chrono::Utc> =
            serde_json::from_value(actor["signed_at"].clone()).unwrap();

        // Reconstruct the canonical preimage byte-for-byte. ledger_id is
        // derived from the event-log file stem; chain_position is 0
        // because the fixture has a single event ingested into an empty
        // log (chain_base=0 + appended.len()=0 at sign time).
        let preimage = AttestationPreimage {
            schema_version: SCHEMA_VERSION_ATTESTATION,
            source: SourceIdentity::User,
            event_id: event.id.to_string(),
            payload_hash: event.payload_hash.clone(),
            session_id: event.session_id.clone().unwrap_or_default(),
            ledger_id: derive_ledger_id(&log),
            lineage: LineageBinding::ChainPosition(0),
            signed_at,
            key_id: key_id.clone(),
        };

        // Rebuild the attestation from the persisted hex signature.
        let mut sig_bytes = [0u8; 64];
        for (i, byte_out) in sig_bytes.iter_mut().enumerate() {
            let hi = (sig_hex.as_bytes()[i * 2] as char).to_digit(16).unwrap();
            let lo = (sig_hex.as_bytes()[i * 2 + 1] as char)
                .to_digit(16)
                .unwrap();
            *byte_out = ((hi << 4) | lo) as u8;
        }
        let attestation = Attestation {
            key_id: key_id.clone(),
            signature: sig_bytes,
            signed_at,
        };

        // Recover the verifying key from the test seed (32 bytes of 0x07).
        let key_bytes = std::fs::read(attested_key_fixture()).unwrap();
        let mut seed = [0u8; 32];
        seed.copy_from_slice(&key_bytes);
        let attestor = InMemoryAttestor::from_seed(&seed);

        // Sanity: derived key_id from the seed matches the persisted one.
        assert_eq!(
            attestor.key_id(),
            key_id,
            "derived key_id must match audit row's key_id"
        );

        verify(&preimage, &attestation, &attestor.verifying_key(), &key_id)
            .expect("persisted attestation must verify against canonical preimage");

        // Belt-and-braces: the canonical bytes the verifier sees match the
        // bytes the encoder emits today.
        let _ = canonical::canonical_signing_input(&preimage);
    }

    /// Negative: a short / wrong-size key file is rejected with
    /// PreconditionUnmet (no panic, no partial signing).
    #[test]
    fn ingest_rejects_wrong_size_key_file() {
        let tmp = tempdir().unwrap();
        let bad_key = tmp.path().join("short.bin");
        std::fs::write(&bad_key, b"too-short").unwrap();
        let args = IngestArgs {
            session: forged_user_fixture(),
            event_log: Some(tmp.path().join("events.jsonl")),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: Some(bad_key),
        };
        let err = run_inner(args).expect_err("short key file must be rejected");
        assert_eq!(err.exit, Exit::PreconditionUnmet);
    }

    // -- ADR 0026 ingest policy composition ------------------------------

    fn user_event() -> Event {
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc::now(),
            recorded_at: Utc::now(),
            source: EventSource::User,
            event_type: EventType::UserMessage,
            trace_id: None,
            session_id: Some("test".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"text": "operator message"}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    fn unnamed_tool_event() -> Event {
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc::now(),
            recorded_at: Utc::now(),
            source: EventSource::Tool { name: "".into() },
            event_type: EventType::ToolResult,
            trace_id: None,
            session_id: Some("test".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"result": "ok"}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    fn manual_correction_event() -> Event {
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc::now(),
            recorded_at: Utc::now(),
            source: EventSource::ManualCorrection,
            event_type: EventType::UserMessage,
            trace_id: None,
            session_id: Some("test".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"text": "operator correction"}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    #[test]
    fn policy_user_without_attestation_rejects_with_user_attestation_missing_rule() {
        let event = user_event();
        let decision = ingest_policy_decision(&[event.clone()], &[event.id], false);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
        let user_rule = decision
            .contributing
            .iter()
            .chain(decision.discarded.iter())
            .find(|c| c.rule_id.as_str() == INGEST_USER_ATTESTATION_RULE_ID)
            .expect("user attestation contributor is present");
        assert_eq!(user_rule.outcome, PolicyOutcome::Reject);
        assert!(user_rule
            .reason
            .contains("policy.ingest.user_attestation.missing"));
    }

    #[test]
    fn policy_tool_below_minimum_rejects_with_event_source_tier_gate_rule() {
        let event = unnamed_tool_event();
        let decision = ingest_policy_decision(&[event.clone()], &[], false);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
        let tier_rule = decision
            .contributing
            .iter()
            .chain(decision.discarded.iter())
            .find(|c| c.rule_id.as_str() == INGEST_EVENT_SOURCE_TIER_GATE_RULE_ID)
            .expect("tier gate contributor is present");
        assert_eq!(tier_rule.outcome, PolicyOutcome::Reject);
        assert!(tier_rule
            .reason
            .contains("policy.ingest.event_source_tier_gate.below_minimum"));
        assert!(tier_rule.reason.contains(&event.id.to_string()));
    }

    #[test]
    fn policy_manual_correction_without_attestor_is_below_tier() {
        let event = manual_correction_event();
        // ManualCorrection alone does not produce a User-event id so the
        // attestation rule alone would Allow; the tier gate must catch it.
        let decision = ingest_policy_decision(&[event], &[], false);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn policy_well_formed_child_agent_event_allows() {
        let event = make_event();
        let decision = ingest_policy_decision(&[event], &[], false);
        assert_eq!(decision.final_outcome, PolicyOutcome::Allow);
        assert_eq!(decision.contributing.len(), 3);
    }

    #[test]
    fn policy_attested_user_event_allows() {
        let event = user_event();
        let decision = ingest_policy_decision(&[event.clone()], &[event.id], true);
        assert_eq!(decision.final_outcome, PolicyOutcome::Allow);
    }

    #[test]
    fn event_source_trust_tier_mapping_matches_adr_0019() {
        assert_eq!(
            event_source_trust_tier(&EventSource::User, false),
            TrustTier::Untrusted
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::User, true),
            TrustTier::Operator
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::ManualCorrection, false),
            TrustTier::Untrusted
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::ManualCorrection, true),
            TrustTier::Operator
        );
        assert_eq!(
            event_source_trust_tier(
                &EventSource::ChildAgent {
                    model: "replay".into()
                },
                false
            ),
            TrustTier::Observed
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::ChildAgent { model: "".into() }, false),
            TrustTier::Untrusted
        );
        assert_eq!(
            event_source_trust_tier(
                &EventSource::Tool {
                    name: "auditor".into()
                },
                false
            ),
            TrustTier::Observed
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::Runtime, false),
            TrustTier::Observed
        );
        assert_eq!(
            event_source_trust_tier(&EventSource::ExternalOutcome, false),
            TrustTier::Observed
        );
    }

    /// A reject-tier Tool event ingested through `run_inner` MUST refuse with
    /// `Exit::PreconditionUnmet` and MUST NOT append anything to the log.
    #[test]
    fn run_inner_refuses_tool_event_below_tier_without_mutation() {
        let tmp = tempdir().unwrap();
        let session_path = tmp.path().join("session.json");
        let event = unnamed_tool_event();
        write_session(&session_path, &[event]);

        let log = tmp.path().join("events.jsonl");
        let args = IngestArgs {
            session: session_path,
            event_log: Some(log.clone()),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let err = run_inner(args).expect_err("below-tier tool must be refused");
        assert_eq!(err.exit, Exit::PreconditionUnmet);
        if log.exists() {
            assert_eq!(
                std::fs::metadata(&log).unwrap().len(),
                0,
                "below-tier tool ingest must not append to the JSONL log"
            );
        }
    }

    /// An ingest payload that survives the policy composer must still go
    /// through the existing append path and dedup.
    #[test]
    fn run_inner_allows_named_child_agent_event_through_policy() {
        let tmp = tempdir().unwrap();
        let session_path = tmp.path().join("session.json");
        let event = make_event();
        write_session(&session_path, &[event]);

        let args = IngestArgs {
            session: session_path,
            event_log: Some(tmp.path().join("events.jsonl")),
            db: Some(tmp.path().join("cortex.db")),
            user_attestation: None,
        };
        let outcome = run_inner(args).expect("policy allow path must succeed");
        assert_eq!(outcome.appended.len(), 1);
        assert_eq!(outcome.skipped.len(), 0);
    }
}