crtx 0.1.1

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
//! `cortex run` — Phase 2 runtime command surface.
//!
//! `run` builds an auditable context pack and executes an offline adapter.
//!
//! ## Default unsigned persistence (ADR 0026)
//!
//! Even on the default (non-`--trusted-history`) path, persistence of the
//! agent-response event composes an ADR 0026 [`PolicyDecision`] before any
//! mirror append. Three contributors register:
//!
//! 1. [`RUN_PERSIST_CONTEXT_POLICY_OUTCOME_RULE_ID`] — the run pack's own
//!    composed policy outcome (proof closure, redaction, conflict posture).
//! 2. [`RUN_PERSIST_RUNTIME_MODE_GATE_RULE_ID`] — ADR 0037 weakest-link
//!    ceiling for the runtime mode that drove this run.
//! 3. [`RUN_PERSIST_DEVELOPMENT_LEDGER_AUTHORITY_RULE_ID`] — ADR 0026 §3
//!    floor: a development-ledger run cannot promote into trusted run-history
//!    without a scoped break-glass.
//!
//! Final outcome `Reject` / `Quarantine` fails closed: no mirror append, no
//! JSONL row, no SQLite parity, and stdout contains nothing. The operator may
//! opt in to a [`BreakGlassReasonCode::DiagnosticOnly`] envelope through
//! `--break-glass <JSON>`. A break-glassed reject persists with
//! `forbidden_uses` populated; it MUST NOT be treated as trusted run-history.

use crate::config::LlmBackend;
use async_trait::async_trait;
use clap::Args;
use cortex_core::{
    compose_policy_outcomes, Attestor, AuthorityClass, BreakGlassAuthorization,
    BreakGlassReasonCode, ClaimCeiling, ClaimProofState, InMemoryAttestor, PolicyContribution,
    PolicyDecision, PolicyOutcome, RuntimeMode, TrustTier,
};
use cortex_ledger::{
    verify_signed_chain, JsonlLog, APPEND_ATTESTATION_REQUIRED_RULE_ID,
    APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID, APPEND_RUNTIME_MODE_RULE_ID,
    APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID, APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID,
};
use cortex_llm::{
    blake3_hex, validate_ollama_model_ref, LlmAdapter, LlmError, LlmMessage, LlmRequest,
    LlmResponse, LlmRole, MaxSensitivity, OllamaHttpAdapter, OpenAiCompatAdapter,
    SensitivityGateResult,
};
use cortex_runtime::{compile_runtime_claim, run_configured, Run, RuntimeClaimKind};
use cortex_store::mirror::{self, MIRROR_APPEND_PARITY_INVARIANT_RULE_ID};
use cortex_store::repo::memories::MemoryRepo;
use cortex_store::Pool;
use std::fs;
use std::path::{Path, PathBuf};

use crate::cmd::context::BuildArgs;
use crate::cmd::open_default_store;
use crate::cmd::temporal::{revalidate_operator_temporal_authority, revalidation_failed_invariant};
use crate::exit::Exit;
use crate::output::{self, Envelope};
use crate::paths::DataLayout;

/// Required contributor rule id: the run pack's composed policy outcome
/// participates in the persistence decision (ADR 0026 §2 composition).
pub const RUN_PERSIST_CONTEXT_POLICY_OUTCOME_RULE_ID: &str = "run.persist.context_policy_outcome";
/// Required contributor rule id: the runtime mode ceiling participates in the
/// persistence decision (ADR 0037 weakest-link).
pub const RUN_PERSIST_RUNTIME_MODE_GATE_RULE_ID: &str = "run.persist.runtime_mode_gate";
/// Required contributor rule id: development-ledger authority floor (ADR 0026
/// §3) — `Reject` / `Quarantine` MUST NOT silently promote into trusted
/// run-history. Marked break-glass-overridable so an operator can opt in to a
/// diagnostic envelope.
pub const RUN_PERSIST_DEVELOPMENT_LEDGER_AUTHORITY_RULE_ID: &str =
    "run.persist.development_ledger_authority";

/// `cortex run` arguments.
#[derive(Debug, Args)]
pub struct RunArgs {
    /// Task to run with Cortex context.
    #[arg(long)]
    pub task: String,

    /// Adapter/model selector. Replay is expected for offline verification.
    #[arg(long, default_value = "replay")]
    pub model: String,

    /// Request signed-local trusted run-history output.
    #[arg(long = "trusted-history")]
    pub trusted_history: bool,

    /// 32-byte Ed25519 seed used for the signed-local trusted-history path.
    #[arg(long, value_name = "KEY_PATH")]
    pub attestation: Option<PathBuf>,

    /// JSON-encoded [`BreakGlassAuthorization`] envelope opting in to
    /// diagnostic-only persistence of an otherwise rejected or quarantined
    /// run pack (ADR 0026 §4). The persisted event will carry
    /// `forbidden_uses` and MUST NOT be treated as trusted run-history.
    #[arg(long = "break-glass", value_name = "JSON")]
    pub break_glass: Option<String>,

    /// Stream tokens to stdout incrementally as they arrive (ADR 0049).
    /// The full assembled response is still written to the ledger unchanged.
    /// OfflineAdapter and ReplayAdapter use the default single-chunk impl.
    #[arg(long)]
    pub stream: bool,
}

/// Run `cortex run`.
pub fn run(args: RunArgs) -> Exit {
    if args.task.trim().is_empty() {
        eprintln!("cortex run: --task must not be empty");
        return run_failure_envelope(Exit::Usage, "--task must not be empty");
    }
    if args.model.trim().is_empty() {
        eprintln!("cortex run: --model must not be empty");
        return run_failure_envelope(Exit::Usage, "--model must not be empty");
    }
    if let Some(model) = args.model.trim().strip_prefix("ollama:") {
        if let Err(err) = validate_ollama_model_ref(model) {
            eprintln!("cortex run: {err}; no state was changed");
            return run_failure_envelope(
                Exit::PreconditionUnmet,
                &format!("invalid ollama model ref: {err}"),
            );
        }
    }

    let break_glass = match parse_break_glass_flag(args.break_glass.as_deref()) {
        Ok(authorization) => authorization,
        Err(exit) => return run_failure_envelope(exit, "invalid --break-glass envelope"),
    };

    let pack = match crate::cmd::context::build_pack(BuildArgs {
        task: args.task.clone(),
        max_tokens: 4096,
        axiom_constraints: false,
        tag: Vec::new(),
        fuzzy: false,
        include_doctrine: false,
    }) {
        Ok(pack) => {
            if let Err(err) = pack.require_default_use_allowed() {
                eprintln!("cortex run: {err}");
                return run_failure_envelope(Exit::PreconditionUnmet, &err.to_string());
            }
            pack
        }
        Err(exit) => return run_failure_envelope(exit, "context pack build failed"),
    };

    let mut run = match Run::new(args.task, pack) {
        Ok(run) => run,
        Err(err) => {
            eprintln!("cortex run: {err}");
            return run_failure_envelope(Exit::PreconditionUnmet, &err.to_string());
        }
    };
    run.model = args.model;

    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(err) => {
            eprintln!("cortex run: failed to create runtime: {err}");
            return run_failure_envelope(
                Exit::Internal,
                &format!("failed to create runtime: {err}"),
            );
        }
    };

    // Resolve LLM backend: CLI --model ollama:<ref> > env > cortex.toml > offline default.
    let backend = if let Some(model) = run.model.strip_prefix("ollama:") {
        // CLI flag: --model ollama:<digest-pinned-ref>
        let endpoint = std::env::var("CORTEX_LLM_ENDPOINT")
            .unwrap_or_else(|_| "http://localhost:11434".to_string());
        LlmBackend::Ollama {
            endpoint,
            model: model.to_string(),
            timeout_ms: 30_000,
        }
    } else {
        LlmBackend::resolve()
    };

    let offline_adapter_storage;
    let ollama_adapter_storage;
    let claude_adapter_storage;
    let openai_compat_adapter_storage;
    let adapter: &dyn LlmAdapter = match &backend {
        LlmBackend::Offline => {
            offline_adapter_storage = OfflineAdapter;
            &offline_adapter_storage
        }
        LlmBackend::Claude {
            model,
            max_sensitivity,
            ..
        } => {
            // ADR 0048: RemoteUnsigned ceiling. Key from CORTEX_CLAUDE_API_KEY env var.
            let sensitivity = max_sensitivity
                .parse::<MaxSensitivity>()
                .unwrap_or(MaxSensitivity::Medium);
            match cortex_llm::ClaudeHttpAdapter::new(model.clone(), Some(sensitivity)) {
                Ok(a) => {
                    claude_adapter_storage = a;
                    &claude_adapter_storage
                }
                Err(err) => {
                    eprintln!(
                        "cortex run: ClaudeHttpAdapter init failed: {err}; no state was changed"
                    );
                    return run_failure_envelope(Exit::PreconditionUnmet, &err.to_string());
                }
            }
        }
        LlmBackend::Ollama {
            endpoint,
            model,
            timeout_ms: _timeout_ms,
        } => {
            use cortex_llm::OllamaConfig;
            let config = OllamaConfig {
                endpoint_url: endpoint.clone(),
                model: model.clone(),
            };
            match OllamaHttpAdapter::new(config) {
                Ok(a) => {
                    ollama_adapter_storage = a;
                    &ollama_adapter_storage
                }
                Err(err) => {
                    eprintln!("cortex run: invalid ollama config: {err}; falling back to offline");
                    offline_adapter_storage = OfflineAdapter;
                    &offline_adapter_storage
                }
            }
        }
        LlmBackend::OpenAiCompat {
            base_url,
            model,
            api_key,
            timeout_ms,
            max_sensitivity,
        } => {
            let parsed_sensitivity = max_sensitivity
                .parse::<MaxSensitivity>()
                .unwrap_or(MaxSensitivity::Medium);
            match OpenAiCompatAdapter::new(
                base_url.clone(),
                model.clone(),
                api_key.clone(),
                *timeout_ms,
                Some(parsed_sensitivity),
            ) {
                Ok(a) => {
                    openai_compat_adapter_storage = a;
                    &openai_compat_adapter_storage
                }
                Err(err) => {
                    eprintln!(
                        "cortex run: invalid openai-compat config: {err}; no state was changed"
                    );
                    return run_failure_envelope(Exit::PreconditionUnmet, &err.to_string());
                }
            }
        }
    };

    // ADR 0048 §3 domain-tag sensitivity gate: query active memories before any
    // bytes leave the machine. This replaces the text-scan heuristic with a real
    // per-memory store query (T-0048.2 follow-on).
    if let LlmBackend::Claude {
        max_sensitivity, ..
    } = &backend
    {
        let configured_max = max_sensitivity
            .parse::<MaxSensitivity>()
            .unwrap_or(MaxSensitivity::Medium);
        match open_default_store("run") {
            Ok(pool) => {
                let repo = MemoryRepo::new(&pool);
                match repo.max_sensitivity_for_active_memories() {
                    Ok(memory_max_str) => {
                        let gate = SensitivityGateResult::evaluate(&memory_max_str, configured_max);
                        tracing::info!(
                            max_memory_sensitivity = %gate.max_memory_sensitivity,
                            configured_max = ?gate.configured_max,
                            allowed = gate.allowed,
                            "remote prompt domain-tag sensitivity gate"
                        );
                        if !gate.allowed {
                            let msg = format!(
                                "sensitivity_exceeds_remote_threshold: memories at {} exceed configured max_sensitivity {}; remote dispatch refused",
                                gate.max_memory_sensitivity,
                                max_sensitivity,
                            );
                            eprintln!("cortex run: {msg}");
                            return run_failure_envelope(Exit::PreconditionUnmet, &msg);
                        }
                    }
                    Err(err) => {
                        eprintln!(
                            "cortex run: domain-tag sensitivity gate: store query failed: {err}; refusing remote dispatch"
                        );
                        return run_failure_envelope(
                            Exit::Internal,
                            &format!("sensitivity gate store query failed: {err}"),
                        );
                    }
                }
            }
            Err(exit) => return run_failure_envelope(exit, "sensitivity gate: store open failed"),
        }
    }

    // Streaming display path (ADR 0049 T-0049.4): print deltas as they arrive,
    // then fall through to run_configured for the auditable ledger write.
    // Two adapter calls are intentional — the streaming display is visual only;
    // the ledger hash is anchored to the complete() response for integrity.
    if args.stream {
        let stream_request = LlmRequest {
            model: run.model.clone(),
            system: run.system.clone(),
            messages: vec![LlmMessage {
                role: LlmRole::User,
                content: serde_json::json!({
                    "task": run.task,
                    "context_pack_id": run.pack.context_pack_id,
                    "context_pack": run.pack,
                })
                .to_string(),
            }],
            temperature: run.temperature,
            max_tokens: run.max_tokens,
            json_schema: None,
            timeout_ms: run.timeout_ms,
        };

        let stream_result = runtime.block_on(async {
            use futures::StreamExt as _;
            let stream = adapter.stream_boxed(stream_request);
            futures::pin_mut!(stream);
            while let Some(chunk_result) = stream.next().await {
                match chunk_result {
                    Ok(chunk) => {
                        use std::io::Write as _;
                        print!("{}", chunk.delta);
                        let _ = std::io::stdout().flush();
                    }
                    Err(e) => return Err(e),
                }
            }
            Ok(())
        });

        match stream_result {
            Ok(()) => {
                // Newline after the streamed tokens before the JSON report.
                println!();
            }
            Err(e) => {
                eprintln!("cortex run --stream: stream error: {e}");
                return run_failure_envelope(Exit::PreconditionUnmet, &e.to_string());
            }
        }
    }

    match runtime.block_on(run_configured(run, adapter)) {
        Ok(mut report) => {
            let persist_result = if args.trusted_history {
                match args.attestation.as_ref() {
                    Some(path) => match load_attestor_from_key_file(path) {
                        Ok(attestor) => persist_signed_agent_response_event(&mut report, &attestor),
                        Err(exit) => Err(exit),
                    },
                    None => {
                        eprintln!(
                            "cortex run: --trusted-history requires --attestation <KEY_PATH>; no state was changed"
                        );
                        Err(Exit::PreconditionUnmet)
                    }
                }
            } else if args.attestation.is_some() {
                eprintln!(
                    "cortex run: --attestation is only valid with --trusted-history; no state was changed"
                );
                Err(Exit::Usage)
            } else {
                persist_agent_response_event(&mut report, break_glass.as_ref())
            };

            match persist_result {
                Ok(sealed_event) => {
                    report.agent_response_event = sealed_event;
                    if output::json_enabled() {
                        let payload = match serde_json::to_value(&report) {
                            Ok(value) => value,
                            Err(err) => {
                                eprintln!("cortex run: failed to serialize run report: {err}");
                                return Exit::Internal;
                            }
                        };
                        let envelope = Envelope::new("cortex.run", Exit::Ok, payload);
                        return output::emit(&envelope, Exit::Ok);
                    }
                    match serde_json::to_string_pretty(&report) {
                        Ok(serialized) => {
                            println!("{serialized}");
                            Exit::Ok
                        }
                        Err(err) => {
                            eprintln!("cortex run: failed to serialize run report: {err}");
                            Exit::Internal
                        }
                    }
                }
                Err(exit) => run_failure_envelope(exit, "persistence failed"),
            }
        }
        Err(err) => {
            eprintln!("cortex run: {err}");
            run_failure_envelope(Exit::PreconditionUnmet, &err.to_string())
        }
    }
}

fn run_failure_envelope(exit: Exit, detail: &str) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = serde_json::json!({
        "status": "error",
        "detail": detail,
    });
    let envelope = Envelope::new("cortex.run", exit, payload);
    output::emit(&envelope, exit)
}

/// Required contributor rule id: the operator's diagnostic-only break-glass
/// vote. Present only when `--break-glass` was supplied with a valid
/// [`BreakGlassReasonCode::DiagnosticOnly`] envelope.
pub const RUN_PERSIST_OPERATOR_DIAGNOSTIC_OVERRIDE_RULE_ID: &str =
    "run.persist.operator_diagnostic_override";

/// Compose the ADR 0026 policy decision for the default unsigned persistence
/// path.
///
/// Returns a decision whose `final_outcome` is `Allow`/`Warn`/`BreakGlass` on
/// the happy path. Callers MUST refuse to persist on any other outcome unless
/// the supplied [`BreakGlassAuthorization`] elevates a reject/quarantine into
/// a diagnostic-only `BreakGlass`.
#[must_use]
pub fn run_persist_policy_decision(
    context_policy_outcome: PolicyOutcome,
    runtime_mode: RuntimeMode,
    break_glass: Option<&BreakGlassAuthorization>,
) -> PolicyDecision {
    let context_contribution = PolicyContribution::new(
        RUN_PERSIST_CONTEXT_POLICY_OUTCOME_RULE_ID,
        context_policy_outcome,
        format!(
            "context pack composed policy outcome {context_policy_outcome:?} replays into persistence"
        ),
    )
    .expect("static policy contribution is valid")
    .allow_break_glass_override();

    let (runtime_outcome, runtime_reason) = runtime_mode_persist_outcome(runtime_mode);
    let runtime_contribution = PolicyContribution::new(
        RUN_PERSIST_RUNTIME_MODE_GATE_RULE_ID,
        runtime_outcome,
        runtime_reason,
    )
    .expect("static policy contribution is valid")
    .allow_break_glass_override();

    let development_contribution = PolicyContribution::new(
        RUN_PERSIST_DEVELOPMENT_LEDGER_AUTHORITY_RULE_ID,
        PolicyOutcome::Allow,
        "development ledger floor allows unsigned append; trusted-history requires the signed path",
    )
    .expect("static policy contribution is valid")
    .allow_break_glass_override();

    let mut contributions = vec![
        context_contribution,
        runtime_contribution,
        development_contribution,
    ];

    // ADR 0026 §4: break-glass requires both a `BreakGlass` outcome
    // contribution AND a valid authorization envelope before composition will
    // elevate a reject/quarantine. The operator override contributor encodes
    // the "operator explicitly opted in" vote; the envelope encodes scope,
    // attestation, and reason code.
    if let Some(authorization) = break_glass {
        if authorization.is_valid() {
            contributions.push(
                PolicyContribution::new(
                    RUN_PERSIST_OPERATOR_DIAGNOSTIC_OVERRIDE_RULE_ID,
                    PolicyOutcome::BreakGlass,
                    "operator opted in to diagnostic-only persistence via --break-glass",
                )
                .expect("static policy contribution is valid"),
            );
        }
    }

    compose_policy_outcomes(contributions, break_glass.cloned())
}

/// ADR 0037 weakest-link ceiling for the runtime mode driving an unsigned
/// persistence attempt. `Unknown` and `Dev` are non-persistable by default;
/// `LocalUnsigned` is the supported default mode; everything stronger should
/// have already routed through the signed path.
fn runtime_mode_persist_outcome(runtime_mode: RuntimeMode) -> (PolicyOutcome, String) {
    match runtime_mode {
        RuntimeMode::Unknown => (
            PolicyOutcome::Reject,
            "runtime mode unknown; ADR 0037 forbids treating absent runtime mode as durable authority".into(),
        ),
        RuntimeMode::Dev => (
            PolicyOutcome::Quarantine,
            "runtime mode dev produces diagnostic-only artifacts and must not promote to trusted run-history".into(),
        ),
        RuntimeMode::RemoteUnsigned => (
            PolicyOutcome::Quarantine,
            "runtime mode remote_unsigned: remote API response is unsigned and cannot be locally verified; must not persist as trusted local evidence without operator opt-in".into(),
        ),
        RuntimeMode::LocalUnsigned => (
            PolicyOutcome::Allow,
            "runtime mode local_unsigned permits default unsigned persistence".into(),
        ),
        RuntimeMode::SignedLocalLedger
        | RuntimeMode::ExternallyAnchored
        | RuntimeMode::AuthorityGrade => (
            PolicyOutcome::Warn,
            format!(
                "runtime mode {runtime_mode:?} expected the signed persistence path; the unsigned mirror is being used regardless"
            ),
        ),
    }
}

fn parse_break_glass_flag(raw: Option<&str>) -> Result<Option<BreakGlassAuthorization>, Exit> {
    let Some(value) = raw else {
        return Ok(None);
    };
    let trimmed = value.trim();
    if trimmed.is_empty() {
        eprintln!("cortex run: --break-glass JSON must not be empty; no state was changed");
        return Err(Exit::Usage);
    }
    let parsed: BreakGlassAuthorization = serde_json::from_str(trimmed).map_err(|err| {
        eprintln!(
            "cortex run: --break-glass JSON does not parse as BreakGlassAuthorization: {err}; no state was changed"
        );
        Exit::Usage
    })?;
    if parsed.reason_code != BreakGlassReasonCode::DiagnosticOnly {
        eprintln!(
            "cortex run: --break-glass reason_code must be diagnostic_only for run persistence; got {:?}; no state was changed",
            parsed.reason_code
        );
        return Err(Exit::Usage);
    }
    if !parsed.is_valid() {
        eprintln!(
            "cortex run: --break-glass authorization is not bound (operation_type, artifact_refs, attested, permitted required); no state was changed"
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(Some(parsed))
}

fn persist_agent_response_event(
    report: &mut cortex_runtime::RunReport,
    break_glass: Option<&BreakGlassAuthorization>,
) -> Result<cortex_core::Event, Exit> {
    let decision = run_persist_policy_decision(
        report.context_policy_outcome,
        report.runtime_mode,
        break_glass,
    );

    match decision.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn => {}
        PolicyOutcome::BreakGlass => {
            mark_event_as_diagnostic_only(&mut report.agent_response_event, &decision);
        }
        PolicyOutcome::Reject | PolicyOutcome::Quarantine => {
            emit_persist_policy_refusal(&decision);
            return Err(Exit::PreconditionUnmet);
        }
    }

    let layout = DataLayout::resolve(None, None)?;
    let mut pool = open_default_store("run")?;
    let mut log = JsonlLog::open(&layout.event_log_path).map_err(|err| {
        eprintln!(
            "cortex run: failed to open event log {}: {err}",
            layout.event_log_path.display()
        );
        Exit::Internal
    })?;

    // Default `cortex run` writes the agent-response row into a
    // local-development ledger. The agent response is `EventSource::Runtime`
    // / `ChildAgent`, not `EventSource::User`, so the attestation
    // contributor is `Allow` by construction. The runtime-mode contributor
    // emits `Warn` because the unsigned local ledger is `DevOnly` per
    // ADR 0037 §2 — the row is durable, but its claim ceiling is bounded
    // at the row level by `agent_response_event`'s own provenance.
    let ledger_policy = local_development_ledger_policy();
    let mirror_policy = mirror_parity_satisfied_policy();
    mirror::append_event(
        &mut log,
        &mut pool,
        report.agent_response_event.clone(),
        &ledger_policy,
        &mirror_policy,
    )
    .map_err(|err| {
        eprintln!("cortex run: failed to persist agent response event: {err}");
        Exit::Internal
    })
}

fn persist_signed_agent_response_event(
    report: &mut cortex_runtime::RunReport,
    attestor: &InMemoryAttestor,
) -> Result<cortex_core::Event, Exit> {
    let layout = DataLayout::resolve(None, None)?;
    let mut pool = open_default_store("run")?;
    let mut log = JsonlLog::open(&layout.event_log_path).map_err(|err| {
        eprintln!(
            "cortex run: failed to open event log {}: {err}",
            layout.event_log_path.display()
        );
        Exit::Internal
    })?;

    let preflight = verify_signed_chain(
        &layout.event_log_path,
        &attestor.verifying_key(),
        attestor.key_id(),
    )
    .map_err(|err| {
        eprintln!(
            "cortex run: trusted run history denied: signed ledger verification failed before append: {err}"
        );
        Exit::PreconditionUnmet
    })?;
    if !preflight.report.ok() {
        eprintln!(
            "cortex run: trusted run history denied: existing ledger is not a clean signed chain; no state was changed"
        );
        return Err(Exit::PreconditionUnmet);
    }

    let claim = compile_runtime_claim(
        "trusted run history",
        RuntimeClaimKind::TrustedHistory,
        RuntimeMode::SignedLocalLedger,
        AuthorityClass::Verified,
        ClaimProofState::FullChainVerified,
        ClaimCeiling::SignedLocalLedger,
    );
    if !claim.allowed {
        eprintln!(
            "cortex run: trusted run history denied: {}; no state was changed",
            claim
                .reasons
                .last()
                .cloned()
                .unwrap_or_else(|| "claim preflight failed".to_string())
        );
        return Err(Exit::PreconditionUnmet);
    }

    report.runtime_mode = claim.runtime_mode;
    report.proof_state = claim.proof_state;
    report.claim_ceiling = claim.effective_ceiling;
    report.trusted_run_history = true;
    report.downgrade_reasons = claim.reasons;
    mark_event_as_signed_local(&mut report.agent_response_event);
    report.refresh_observability();

    // Phase 2.6 closure: `verify_signed_chain` is purely Ed25519 — it
    // does NOT consult `authority_key_timeline` and does NOT enforce
    // ADR 0023 current-use / ADR 0019 trust-tier semantics. The
    // contributors at the trusted-history append surface MUST be
    // derived from `AuthorityRepo::revalidate` against the durable
    // timeline rows for the supplied attestor key. A revoked /
    // retired / sub-`Verified` key votes `Reject` here and the
    // signed append fails closed via `JsonlLog::append_signed`'s
    // structural contributor gate (`require_append_signed_key_state_not_break_glassed`).
    let _ = preflight;
    let signed_ledger_policy = build_signed_local_ledger_policy(&pool, attestor)?;
    let mirror_policy = mirror_parity_satisfied_policy();
    let sealed = mirror::append_signed_event(
        &mut log,
        &mut pool,
        report.agent_response_event.clone(),
        attestor,
        &signed_ledger_policy,
        &mirror_policy,
    )
    .map_err(|err| {
        eprintln!("cortex run: failed to persist signed agent response event: {err}");
        Exit::Internal
    })?;

    let postflight = verify_signed_chain(
        &layout.event_log_path,
        &attestor.verifying_key(),
        attestor.key_id(),
    )
    .map_err(|err| {
        eprintln!(
            "cortex run: trusted run history denied: signed ledger verification failed after append: {err}"
        );
        Exit::PreconditionUnmet
    })?;
    if !postflight.report.ok() {
        eprintln!("cortex run: trusted run history denied: signed ledger verification reported failures after append");
        return Err(Exit::PreconditionUnmet);
    }

    Ok(sealed)
}

fn mark_event_as_signed_local(event: &mut cortex_core::Event) {
    if let Some(payload) = event.payload.as_object_mut() {
        payload.insert(
            "ledger_authority".to_string(),
            serde_json::json!("signed_local"),
        );
        payload.insert(
            "signed_ledger_authority".to_string(),
            serde_json::json!(true),
        );
        payload.insert("trusted_run_history".to_string(), serde_json::json!(true));
        payload.insert(
            "forbidden_uses".to_string(),
            serde_json::json!([
                "audit_export",
                "compliance_evidence",
                "cross_system_trust_decision",
                "external_reporting"
            ]),
        );
    }
}

/// Mark a diagnostic-only break-glass persisted event with the ADR 0026 §4
/// forbidden-use set so downstream surfaces cannot promote it.
fn mark_event_as_diagnostic_only(event: &mut cortex_core::Event, decision: &PolicyDecision) {
    if let Some(payload) = event.payload.as_object_mut() {
        payload.insert(
            "ledger_authority".to_string(),
            serde_json::json!("development_diagnostic_only"),
        );
        payload.insert(
            "policy_outcome".to_string(),
            serde_json::json!(decision.final_outcome),
        );
        payload.insert(
            "policy_break_glass".to_string(),
            serde_json::to_value(&decision.break_glass).unwrap_or(serde_json::Value::Null),
        );
        payload.insert(
            "forbidden_uses".to_string(),
            serde_json::json!([
                "trusted_run_history",
                "audit_export",
                "compliance_evidence",
                "cross_system_trust_decision",
                "external_reporting"
            ]),
        );
    }
}

fn emit_persist_policy_refusal(decision: &PolicyDecision) {
    let contributing_rules: Vec<&str> = decision
        .contributing
        .iter()
        .map(|contribution| contribution.rule_id.as_str())
        .collect();
    eprintln!(
        "cortex run: persistence refused by ADR 0026 policy outcome {:?}; contributing rules: [{}]; no state was changed",
        decision.final_outcome,
        contributing_rules.join(", ")
    );
    match serde_json::to_string(decision) {
        Ok(serialized) => eprintln!("{serialized}"),
        Err(err) => {
            eprintln!("cortex run: failed to serialize policy refusal explainability: {err}")
        }
    }
}

/// Build the ADR 0026 policy decision for an unsigned `cortex run`
/// agent-response append into the local-development ledger.
///
/// Agent responses are `EventSource::Runtime` / `ChildAgent`, never
/// `EventSource::User`, so the attestation contributor is `Allow` by
/// construction. The runtime-mode contributor emits `Warn` because the
/// unsigned local ledger is the ADR 0037 §2 `DevOnly` mode and downstream
/// consumers must not pass those rows off as authority-grade.
fn local_development_ledger_policy() -> PolicyDecision {
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "cortex run: agent-response source tier gate satisfied",
            )
            .expect("static policy contribution is valid"),
            PolicyContribution::new(
                APPEND_ATTESTATION_REQUIRED_RULE_ID,
                PolicyOutcome::Allow,
                "cortex run: non-user agent-response does not require user attestation",
            )
            .expect("static policy contribution is valid"),
            PolicyContribution::new(
                APPEND_RUNTIME_MODE_RULE_ID,
                PolicyOutcome::Warn,
                "cortex run: unsigned local-development ledger row (ADR 0037 §2 DevOnly)",
            )
            .expect("static policy contribution is valid"),
        ],
        None,
    )
}

/// Build the ADR 0026 policy decision for a signed `cortex run
/// --trusted-history` agent-response append.
///
/// Phase 2.6 closure
/// (`docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`):
/// the `APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID` and
/// `APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID` contributors are derived
/// from `AuthorityRepo::revalidate` against the durable
/// `authority_key_timeline` and `authority_principal_timeline` rows for
/// the attestor key. `minimum_trust_tier = Verified` per audit §6.2 —
/// trusted run history sits below operator-grade by ADR 0035 / 0037.
///
/// On revalidation failure the function returns the corresponding
/// `Exit::PreconditionUnmet` after emitting the stable invariant
/// `run.trusted_history.operator_temporal_authority.revalidation_failed`.
/// On success the contributors carry the typed report state and the
/// downstream `JsonlLog::append_signed` primitive's structural gate
/// (`require_append_signed_key_state_not_break_glassed`) does the
/// fail-closed work if the operator-key was revoked between preflight
/// and append.
fn build_signed_local_ledger_policy(
    pool: &Pool,
    attestor: &InMemoryAttestor,
) -> Result<PolicyDecision, Exit> {
    let invariant = revalidation_failed_invariant("run.trusted_history");
    let now = chrono::Utc::now();
    let key_state = revalidate_operator_temporal_authority(
        pool,
        APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID,
        attestor.key_id(),
        now,
        TrustTier::Verified,
    )
    .map_err(|err| {
        eprintln!(
            "cortex run: {invariant}: failed to read authority timeline for key {}: {err}; no state was changed",
            attestor.key_id(),
        );
        Exit::PreconditionUnmet
    })?;
    if !key_state.report.valid_now {
        let reasons = key_state
            .report
            .reasons
            .iter()
            .map(|reason| reason.wire_str())
            .collect::<Vec<_>>()
            .join(",");
        eprintln!(
            "cortex run: {invariant}: operator temporal authority current use blocked for key {} (reasons: {reasons}); no state was changed",
            key_state.report.key_id,
        );
        return Err(Exit::PreconditionUnmet);
    }
    // Per-contributor split: `APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID`
    // is the ADR 0023 contributor (key lifecycle); the trust-tier
    // minimum is the ADR 0019 contributor. The current revalidation
    // pass enforces both axes simultaneously, so the same report
    // generates both contributors with consistent outcomes — the
    // primitive's structural gate ensures neither can be silently
    // omitted.
    let trust_tier = revalidate_operator_temporal_authority(
        pool,
        APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID,
        attestor.key_id(),
        now,
        TrustTier::Verified,
    )
    .map_err(|err| {
        eprintln!(
            "cortex run: {invariant}: failed to read principal timeline for key {}: {err}; no state was changed",
            attestor.key_id(),
        );
        Exit::PreconditionUnmet
    })?;
    let contributions = vec![key_state.contribution(), trust_tier.contribution()];
    Ok(compose_policy_outcomes(contributions, None))
}

/// Build the ADR 0026 policy decision for the JSONL <-> SQLite parity
/// invariant gate on a mirrored append from `cortex run`.
fn mirror_parity_satisfied_policy() -> PolicyDecision {
    compose_policy_outcomes(
        vec![PolicyContribution::new(
            MIRROR_APPEND_PARITY_INVARIANT_RULE_ID,
            PolicyOutcome::Allow,
            "cortex run: mirror parity preflight passes for an empty-or-consistent ledger",
        )
        .expect("static policy contribution is valid")],
        None,
    )
}

fn load_attestor_from_key_file(path: &Path) -> Result<InMemoryAttestor, Exit> {
    let bytes = fs::read(path).map_err(|err| {
        eprintln!(
            "cortex run: cannot read --attestation key file `{}`: {err}; no state was changed",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if bytes.len() != 32 {
        eprintln!(
            "cortex run: --attestation key file `{}` must be exactly 32 raw bytes (Ed25519 seed); got {} bytes; no state was changed",
            path.display(),
            bytes.len()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&bytes);
    Ok(InMemoryAttestor::from_seed(&seed))
}

#[derive(Debug)]
struct OfflineAdapter;

#[async_trait]
impl LlmAdapter for OfflineAdapter {
    fn adapter_id(&self) -> &'static str {
        "cli-offline"
    }

    async fn complete(&self, req: LlmRequest) -> Result<LlmResponse, LlmError> {
        let text = format!("offline response for {}", req.model);
        Ok(LlmResponse {
            text: text.clone(),
            parsed_json: None,
            model: req.model,
            usage: None,
            raw_hash: blake3_hex(text.as_bytes()),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use cortex_core::{
        BreakGlassAuthorization, BreakGlassReasonCode, BreakGlassScope, Event, EventId,
        EventSource, EventType, PolicyOutcome, RuntimeMode, SCHEMA_VERSION,
    };
    use cortex_runtime::{RunObservability, RunReport, RunTraceStatus};

    fn fake_event(text: &str) -> Event {
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc::now(),
            recorded_at: Utc::now(),
            source: EventSource::ChildAgent {
                model: "replay".into(),
            },
            event_type: EventType::AgentResponse,
            trace_id: None,
            session_id: Some("test".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"text": text}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    fn fake_report(context_policy_outcome: PolicyOutcome, runtime_mode: RuntimeMode) -> RunReport {
        RunReport {
            correlation_id: cortex_core::CorrelationId::new(),
            task: "diagnose".into(),
            context_pack_id: cortex_core::ContextPackId::new(),
            run_observability: RunObservability {
                audit_schema_version: 1,
                operation: "runtime.run".into(),
                status: RunTraceStatus::Completed,
                correlation_id: cortex_core::CorrelationId::new(),
                context_pack_id: cortex_core::ContextPackId::new(),
                adapter_id: "cli-offline".into(),
                model: "replay".into(),
                runtime_mode,
                proof_state: ClaimProofState::Partial,
                claim_ceiling: ClaimCeiling::LocalUnsigned,
                trusted_run_history: false,
                context_policy_outcome,
                response_hash: "deadbeef".into(),
            },
            adapter_id: "cli-offline".into(),
            model: "replay".into(),
            raw_hash: "deadbeef".into(),
            usage: None,
            prompt_hash: "feedface".into(),
            runtime_mode,
            proof_state: ClaimProofState::Partial,
            claim_ceiling: ClaimCeiling::LocalUnsigned,
            trusted_run_history: false,
            downgrade_reasons: vec![],
            context_policy_outcome,
            agent_response_event: fake_event("offline response for replay"),
        }
    }

    fn diagnostic_break_glass() -> BreakGlassAuthorization {
        BreakGlassAuthorization {
            permitted: true,
            attested: true,
            scope: BreakGlassScope {
                operation_type: "run.persist".into(),
                artifact_refs: vec!["agent_response_event".into()],
                not_before: None,
                not_after: None,
            },
            reason_code: BreakGlassReasonCode::DiagnosticOnly,
        }
    }

    #[test]
    fn allow_pack_composes_allow_persistence_decision() {
        let decision =
            run_persist_policy_decision(PolicyOutcome::Allow, RuntimeMode::LocalUnsigned, None);
        assert_eq!(decision.final_outcome, PolicyOutcome::Allow);
        assert!(decision.break_glass.is_none());
        let rule_ids: Vec<&str> = decision
            .contributing
            .iter()
            .map(|c| c.rule_id.as_str())
            .collect();
        assert!(rule_ids.contains(&RUN_PERSIST_CONTEXT_POLICY_OUTCOME_RULE_ID));
        assert!(rule_ids.contains(&RUN_PERSIST_RUNTIME_MODE_GATE_RULE_ID));
        assert!(rule_ids.contains(&RUN_PERSIST_DEVELOPMENT_LEDGER_AUTHORITY_RULE_ID));
    }

    #[test]
    fn reject_pack_composes_reject_persistence_decision_without_break_glass() {
        let decision =
            run_persist_policy_decision(PolicyOutcome::Reject, RuntimeMode::LocalUnsigned, None);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
        assert!(decision.break_glass.is_none());
    }

    #[test]
    fn quarantine_pack_composes_quarantine_persistence_decision_without_break_glass() {
        let decision = run_persist_policy_decision(
            PolicyOutcome::Quarantine,
            RuntimeMode::LocalUnsigned,
            None,
        );
        assert_eq!(decision.final_outcome, PolicyOutcome::Quarantine);
        assert!(decision.break_glass.is_none());
    }

    #[test]
    fn diagnostic_break_glass_elevates_quarantine_to_break_glass_with_forbidden_uses() {
        let break_glass = diagnostic_break_glass();
        let decision = run_persist_policy_decision(
            PolicyOutcome::Quarantine,
            RuntimeMode::LocalUnsigned,
            Some(&break_glass),
        );
        assert_eq!(decision.final_outcome, PolicyOutcome::BreakGlass);
        assert!(decision.break_glass.is_some());
        assert_eq!(
            decision.break_glass.as_ref().unwrap().reason_code,
            BreakGlassReasonCode::DiagnosticOnly
        );
    }

    #[test]
    fn diagnostic_break_glass_elevates_reject_to_break_glass() {
        let break_glass = diagnostic_break_glass();
        let decision = run_persist_policy_decision(
            PolicyOutcome::Reject,
            RuntimeMode::LocalUnsigned,
            Some(&break_glass),
        );
        assert_eq!(decision.final_outcome, PolicyOutcome::BreakGlass);
    }

    #[test]
    fn unbound_break_glass_does_not_elevate_reject() {
        let mut bg = diagnostic_break_glass();
        bg.attested = false;
        let decision = run_persist_policy_decision(
            PolicyOutcome::Reject,
            RuntimeMode::LocalUnsigned,
            Some(&bg),
        );
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
        assert!(decision.break_glass.is_none());
    }

    #[test]
    fn unknown_runtime_mode_rejects_persistence() {
        let decision =
            run_persist_policy_decision(PolicyOutcome::Allow, RuntimeMode::Unknown, None);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn dev_runtime_mode_quarantines_persistence() {
        let decision = run_persist_policy_decision(PolicyOutcome::Allow, RuntimeMode::Dev, None);
        assert_eq!(decision.final_outcome, PolicyOutcome::Quarantine);
    }

    #[test]
    fn mark_event_as_diagnostic_only_sets_forbidden_uses() {
        let mut event = fake_event("diag");
        let decision = run_persist_policy_decision(
            PolicyOutcome::Reject,
            RuntimeMode::LocalUnsigned,
            Some(&diagnostic_break_glass()),
        );
        mark_event_as_diagnostic_only(&mut event, &decision);
        let payload = event.payload.as_object().expect("payload object");
        assert_eq!(payload["ledger_authority"], "development_diagnostic_only");
        assert_eq!(payload["policy_outcome"], "break_glass");
        let forbidden = payload["forbidden_uses"]
            .as_array()
            .expect("forbidden_uses array");
        let names: Vec<&str> = forbidden
            .iter()
            .filter_map(serde_json::Value::as_str)
            .collect();
        assert!(names.contains(&"trusted_run_history"));
        assert!(names.contains(&"audit_export"));
    }

    #[test]
    fn parse_break_glass_flag_rejects_wrong_reason_code() {
        let bad = serde_json::json!({
            "permitted": true,
            "attested": true,
            "scope": {
                "operation_type": "run.persist",
                "artifact_refs": ["agent_response_event"],
                "not_before": null,
                "not_after": null
            },
            "reason_code": "operator_correction"
        })
        .to_string();
        let err = parse_break_glass_flag(Some(&bad)).expect_err("non-diagnostic reason rejected");
        assert_eq!(err, Exit::Usage);
    }

    #[test]
    fn parse_break_glass_flag_rejects_unbound_scope() {
        let bad = serde_json::json!({
            "permitted": true,
            "attested": true,
            "scope": {
                "operation_type": "",
                "artifact_refs": [],
                "not_before": null,
                "not_after": null
            },
            "reason_code": "diagnostic_only"
        })
        .to_string();
        let err = parse_break_glass_flag(Some(&bad)).expect_err("unbound scope rejected");
        assert_eq!(err, Exit::PreconditionUnmet);
    }

    #[test]
    fn parse_break_glass_flag_accepts_diagnostic_envelope() {
        let bg = serde_json::to_string(&diagnostic_break_glass()).unwrap();
        let parsed = parse_break_glass_flag(Some(&bg)).expect("diagnostic envelope parses");
        let parsed = parsed.expect("envelope produced");
        assert_eq!(parsed.reason_code, BreakGlassReasonCode::DiagnosticOnly);
        assert!(parsed.is_valid());
    }

    #[test]
    fn fake_report_helper_default_is_allow_outcome() {
        let report = fake_report(PolicyOutcome::Allow, RuntimeMode::LocalUnsigned);
        assert_eq!(report.context_policy_outcome, PolicyOutcome::Allow);
        assert_eq!(report.runtime_mode, RuntimeMode::LocalUnsigned);
    }
}