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
//! Integration tests for `cortex decay {schedule, run, list, cancel, status}`.
//!
//! These tests spawn the `cortex` binary out-of-process and assert the CLI
//! contract: typed exit codes, the `--json` envelope shape, and the four
//! stable invariants the Phase 4.D D3-C' surface preserves:
//!
//! - `decay.schedule.scheduled_for_must_be_present_or_future`
//! - `decay.run.no_pending_jobs`
//! - `decay.cancel.terminal_state`
//! - `decay.run.operator_attestation_required_for_llm`
//!
//! The deterministic-concatenate `run` happy path requires real candidate
//! memory rows to compress; the test seeds them directly via
//! `MemoryRepo::insert_candidate` so the runner has well-formed sources.

use std::path::{Path, PathBuf};
use std::process::Command;

use chrono::{Duration, TimeZone, Utc};
use cortex_core::{Event, EventSource, EventType, MemoryId, SCHEMA_VERSION};
use cortex_llm::{
    ReplaySummaryFixture, ReplaySummaryFixtureEntry, SummaryRequest, SummaryResponse,
};
use cortex_memory::decay::summary::{
    canonical_signing_input, LlmSummaryOperatorAttestationEnvelope,
};
use cortex_memory::decay::{
    DECAY_LLM_SUMMARY_ATTESTATION_PURPOSE, DECAY_LLM_SUMMARY_ATTESTATION_SCHEMA_VERSION,
};
use cortex_store::migrate::apply_pending;
use cortex_store::repo::{EventRepo, MemoryCandidate, MemoryRepo};
use ed25519_dalek::{Signer, SigningKey};
use rusqlite::Connection;
use serde_json::json;

fn cortex_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_cortex"))
}

fn run_in(cwd: &Path, args: &[&str]) -> std::process::Output {
    Command::new(cortex_bin())
        .current_dir(cwd)
        .env("XDG_DATA_HOME", cwd.join("xdg"))
        .env("HOME", cwd)
        .args(args)
        .output()
        .expect("spawn cortex")
}

fn assert_exit(out: &std::process::Output, expected: i32) {
    let code = out.status.code().expect("process exited via signal");
    assert_eq!(
        code,
        expected,
        "expected exit {expected}, got {code}\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
}

fn parse_envelope(stdout: &[u8]) -> serde_json::Value {
    let text = std::str::from_utf8(stdout).expect("stdout is utf-8");
    serde_json::from_str(text).unwrap_or_else(|err| {
        panic!("expected --json stdout to parse as JSON envelope; err={err}; stdout={text}")
    })
}

fn init(tmp: &Path) -> PathBuf {
    let out = run_in(tmp, &["init"]);
    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let db_line = stdout
        .lines()
        .find(|line| line.starts_with("cortex init: db"))
        .expect("init stdout includes db path");
    let path = db_line
        .split_once('=')
        .expect("db line has equals")
        .1
        .trim()
        .split_once(" (")
        .expect("db line has status suffix")
        .0;
    PathBuf::from(path)
}

fn at(second: u32) -> chrono::DateTime<Utc> {
    Utc.with_ymd_and_hms(2026, 5, 13, 12, 0, second).unwrap()
}

fn ensure_source_event(pool: &Connection, second: u32) {
    let event_id = "evt_01ARZ3NDEKTSV4RRFFQ69G5FAV".parse().unwrap();
    let repo = EventRepo::new(pool);
    if repo
        .get_by_id(&event_id)
        .expect("query source event")
        .is_some()
    {
        return;
    }
    repo.append(&Event {
        id: event_id,
        schema_version: SCHEMA_VERSION,
        observed_at: at(second),
        recorded_at: at(second),
        source: EventSource::Tool {
            name: "decay-test".into(),
        },
        event_type: EventType::ToolResult,
        trace_id: None,
        session_id: Some("decay-test".into()),
        domain_tags: vec!["test".into()],
        payload: json!({"source": "decay-test", "second": second}),
        payload_hash: format!("payload-decay-{second}"),
        prev_event_hash: None,
        event_hash: format!("event-decay-{second}"),
    })
    .expect("append source event");
}

fn seed_candidate_memory(db_path: &Path, claim: &str, second: u32) -> MemoryId {
    let pool = Connection::open(db_path).expect("open initialised sqlite db");
    apply_pending(&pool).expect("apply migrations");
    ensure_source_event(&pool, second);
    let id = MemoryId::new();
    let candidate = MemoryCandidate {
        id,
        memory_type: "semantic".into(),
        claim: claim.into(),
        source_episodes_json: json!([]),
        source_events_json: json!(["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"]),
        domains_json: json!(["decay-test"]),
        salience_json: json!({"score": 0.5}),
        confidence: 0.75,
        authority: "candidate".into(),
        applies_when_json: json!({}),
        does_not_apply_when_json: json!([]),
        created_at: at(second),
        updated_at: at(second),
    };
    MemoryRepo::new(&pool)
        .insert_candidate(&candidate)
        .expect("insert candidate memory");
    id
}

fn schedule_candidate_compression(tmp: &Path, memory_ids: &str) -> serde_json::Value {
    let out = run_in(
        tmp,
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            memory_ids,
        ],
    );
    assert_exit(&out, 0);
    parse_envelope(&out.stdout)
}

#[test]
fn decay_schedule_candidate_compression_emits_job_id() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let m2 = seed_candidate_memory(&db_path, "beta", 2);
    let ids = format!("{m1},{m2}");
    let envelope = schedule_candidate_compression(tmp.path(), &ids);
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(envelope["exit_code"], 0);
    assert_eq!(envelope["outcome"], "ok");
    let job_id = envelope["report"]["job_id"].as_str().expect("job_id");
    assert!(
        job_id.starts_with("dcy_"),
        "decay job ids must carry the `dcy_` prefix; got `{job_id}`"
    );
    assert_eq!(envelope["report"]["kind"], "candidate_compression");
    assert_eq!(envelope["report"]["state"], "pending");
    assert_eq!(
        envelope["report"]["summary_method"],
        "deterministic_concatenate"
    );
    let refs = envelope["report"]["source_ids"]
        .as_array()
        .expect("source_ids is array");
    assert_eq!(refs.len(), 2);
    assert_eq!(refs[0].as_str().unwrap(), m1.to_string());
    assert_eq!(refs[1].as_str().unwrap(), m2.to_string());
}

#[test]
fn decay_schedule_episode_compression_emits_job_id() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());
    // For episode-compression, we don't need real episode rows at
    // schedule time — schedule just validates id shape and persists the
    // job row. The run path would refuse on missing sources; this test
    // is scoped to the schedule surface.
    let ep1 = cortex_core::EpisodeId::new();
    let ep2 = cortex_core::EpisodeId::new();
    let ids = format!("{ep1},{ep2}");
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "episode-compression",
            "--episode-ids",
            &ids,
        ],
    );
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(envelope["report"]["kind"], "episode_compression");
    assert_eq!(envelope["report"]["state"], "pending");
}

#[test]
fn decay_schedule_expired_principle_review_emits_job_id() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());
    let prn = cortex_core::PrincipleId::new();
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "expired-principle-review",
            "--principle-id",
            &prn.to_string(),
        ],
    );
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(envelope["report"]["kind"], "expired_principle_review");
    // ExpiredPrincipleReview persists summary_method='none' on the row.
    assert_eq!(envelope["report"]["summary_method"], "none");
}

#[test]
fn decay_schedule_refuses_past_scheduled_for_without_run_immediately() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "stale", 1);
    let past = (Utc::now() - Duration::hours(1)).to_rfc3339();
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &m1.to_string(),
            "--scheduled-for",
            &past,
        ],
    );
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(envelope["exit_code"], 7);
    assert_eq!(
        envelope["report"]["invariant"],
        "decay.schedule.scheduled_for_must_be_present_or_future"
    );

    // And: passing --run-immediately unsticks the path.
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &m1.to_string(),
            "--scheduled-for",
            &past,
            "--run-immediately",
        ],
    );
    assert_exit(&out, 0);
}

#[test]
fn decay_list_filters_by_state() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let m2 = seed_candidate_memory(&db_path, "beta", 2);
    let first = schedule_candidate_compression(tmp.path(), &m1.to_string());
    let _second = schedule_candidate_compression(tmp.path(), &m2.to_string());
    let first_id = first["report"]["job_id"].as_str().unwrap().to_string();

    // List with no filter: both jobs visible.
    let out = run_in(tmp.path(), &["--json", "decay", "list"]);
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.list");
    assert_eq!(envelope["report"]["job_count"], 2);

    // Cancel the first job so we have a non-Pending row.
    let cancel = run_in(
        tmp.path(),
        &[
            "decay",
            "cancel",
            &first_id,
            "--reason",
            "test cancellation",
        ],
    );
    assert_exit(&cancel, 0);

    // Filter Pending: only the still-pending second job shows up.
    let out = run_in(
        tmp.path(),
        &["--json", "decay", "list", "--state", "pending"],
    );
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    let filter = envelope["report"]["state_filter"]
        .as_array()
        .expect("state_filter array");
    assert_eq!(filter.len(), 1);
    assert_eq!(filter[0].as_str().unwrap(), "pending");
    assert_eq!(envelope["report"]["job_count"], 1);

    // Filter Cancelled: only the cancelled job shows up.
    let out = run_in(
        tmp.path(),
        &["--json", "decay", "list", "--state", "cancelled"],
    );
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["report"]["job_count"], 1);
    assert_eq!(envelope["report"]["jobs"][0]["id"], first_id);
    assert_eq!(envelope["report"]["jobs"][0]["state"], "cancelled");
}

#[test]
fn decay_run_specific_job_transitions_to_completed() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let m2 = seed_candidate_memory(&db_path, "beta", 2);
    let ids = format!("{m1},{m2}");
    let scheduled = schedule_candidate_compression(tmp.path(), &ids);
    let job_id = scheduled["report"]["job_id"].as_str().unwrap().to_string();

    let out = run_in(tmp.path(), &["--json", "decay", "run", "--job-id", &job_id]);
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.run");
    assert_eq!(envelope["report"]["job_id"], job_id);
    assert_eq!(envelope["report"]["to_state"], "completed");
    let result = envelope["report"]["result_memory_id"]
        .as_str()
        .expect("result_memory_id is set on completion");
    assert!(
        result.starts_with("mem_"),
        "result memory id should be a `mem_` ULID; got `{result}`"
    );

    // Status reflects the produced summary plus the superseded source set.
    let out = run_in(tmp.path(), &["--json", "decay", "status", &job_id]);
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["report"]["state"], "completed");
    let superseded = envelope["report"]["superseded_memory_ids"]
        .as_array()
        .expect("superseded_memory_ids is array");
    let superseded_ids: Vec<&str> = superseded
        .iter()
        .map(|v| v.as_str().expect("id is string"))
        .collect();
    assert!(
        superseded_ids.contains(&m1.to_string().as_str()),
        "expected superseded set to include source m1; got {superseded_ids:?}"
    );
    assert!(
        superseded_ids.contains(&m2.to_string().as_str()),
        "expected superseded set to include source m2; got {superseded_ids:?}"
    );
}

#[test]
fn decay_run_next_pending_when_queue_empty_emits_diagnostic() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());
    let out = run_in(tmp.path(), &["--json", "decay", "run", "--next-pending"]);
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.run");
    assert_eq!(envelope["exit_code"], 7);
    assert_eq!(envelope["report"]["invariant"], "decay.run.no_pending_jobs");
}

#[test]
fn decay_cancel_pending_job_transitions_to_cancelled() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let scheduled = schedule_candidate_compression(tmp.path(), &m1.to_string());
    let job_id = scheduled["report"]["job_id"].as_str().unwrap().to_string();
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "cancel",
            &job_id,
            "--reason",
            "operator changed mind",
        ],
    );
    assert_exit(&out, 0);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.cancel");
    assert_eq!(envelope["report"]["from_state"], "pending");
    assert_eq!(envelope["report"]["to_state"], "cancelled");
    assert_eq!(envelope["report"]["reason"], "operator changed mind");

    let status = run_in(tmp.path(), &["--json", "decay", "status", &job_id]);
    assert_exit(&status, 0);
    let envelope = parse_envelope(&status.stdout);
    assert_eq!(envelope["report"]["state"], "cancelled");
}

#[test]
fn decay_cancel_completed_job_refuses_with_stable_invariant() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let scheduled = schedule_candidate_compression(tmp.path(), &m1.to_string());
    let job_id = scheduled["report"]["job_id"].as_str().unwrap().to_string();

    // First, run the job to completed.
    let out = run_in(tmp.path(), &["decay", "run", "--job-id", &job_id]);
    assert_exit(&out, 0);

    // Then, the cancel must refuse fail-closed with the stable invariant.
    let out = run_in(
        tmp.path(),
        &["--json", "decay", "cancel", &job_id, "--reason", "too late"],
    );
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.cancel");
    assert_eq!(envelope["exit_code"], 7);
    assert_eq!(
        envelope["report"]["invariant"],
        "decay.cancel.terminal_state"
    );
}

#[test]
fn decay_cancel_cancelled_job_refuses_with_stable_invariant() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let scheduled = schedule_candidate_compression(tmp.path(), &m1.to_string());
    let job_id = scheduled["report"]["job_id"].as_str().unwrap().to_string();

    let out = run_in(
        tmp.path(),
        &["decay", "cancel", &job_id, "--reason", "first cancel"],
    );
    assert_exit(&out, 0);

    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "cancel",
            &job_id,
            "--reason",
            "second cancel",
        ],
    );
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(
        envelope["report"]["invariant"],
        "decay.cancel.terminal_state"
    );
}

#[test]
fn decay_run_llm_summary_refuses_without_operator_attestation() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);

    // Schedule an LLM-summary job (with a placeholder attestation file
    // so the schedule path's pre-check passes).
    let attestation_path = tmp.path().join("attestation.json");
    std::fs::write(&attestation_path, "{\"purpose\":\"placeholder\"}").unwrap();
    let scheduled = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &m1.to_string(),
            "--summary-method",
            "llm",
            "--operator-attestation",
            attestation_path.to_str().unwrap(),
        ],
    );
    assert_exit(&scheduled, 0);
    let envelope = parse_envelope(&scheduled.stdout);
    let job_id = envelope["report"]["job_id"].as_str().unwrap().to_string();

    // Running the LLM job WITHOUT --operator-attestation at run time
    // must refuse fail-closed under the stable invariant.
    let out = run_in(tmp.path(), &["--json", "decay", "run", "--job-id", &job_id]);
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.run");
    assert_eq!(envelope["exit_code"], 7);
    assert_eq!(
        envelope["report"]["invariant"],
        "decay.run.operator_attestation_required_for_llm"
    );
}

#[test]
fn decay_schedule_llm_without_attestation_refuses_at_schedule_time() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &m1.to_string(),
            "--summary-method",
            "llm",
        ],
    );
    assert_exit(&out, 7);
    let envelope = parse_envelope(&out.stdout);
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(
        envelope["report"]["invariant"],
        "decay.run.operator_attestation_required_for_llm"
    );
}

#[test]
fn decay_status_for_unknown_job_returns_precondition_unmet() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());
    // Use a structurally-valid but missing decay job id.
    let nonexistent = cortex_core::DecayJobId::new().to_string();
    let out = run_in(tmp.path(), &["--json", "decay", "status", &nonexistent]);
    assert_exit(&out, 7);
}

#[test]
fn decay_status_for_invalid_id_returns_usage() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());
    let out = run_in(tmp.path(), &["--json", "decay", "status", "not_a_valid_id"]);
    // Bad id shape is a Usage refusal — exits 2 like other clap-style
    // parse failures.
    assert_exit(&out, 2);
}

fn write_signed_attestation(dir: &Path, job_id: &str, model: &str, prompt_digest: &str) -> PathBuf {
    let signing_key = SigningKey::from_bytes(&[42u8; 32]);
    let mut s = String::with_capacity(signing_key.verifying_key().as_bytes().len() * 2);
    for b in signing_key.verifying_key().as_bytes() {
        s.push_str(&format!("{b:02x}"));
    }
    let verifying_key_hex = s;

    let envelope_no_sig = LlmSummaryOperatorAttestationEnvelope {
        schema_version: DECAY_LLM_SUMMARY_ATTESTATION_SCHEMA_VERSION,
        purpose: DECAY_LLM_SUMMARY_ATTESTATION_PURPOSE.into(),
        operator_verifying_key_hex: verifying_key_hex,
        operator_key_id: "cortex-operator-cli-test".into(),
        signed_at: Utc::now().to_rfc3339(),
        decay_job_id: job_id.to_string(),
        model_name: model.into(),
        prompt_template_blake3: prompt_digest.into(),
        signature_hex: String::new(),
    };
    let input = canonical_signing_input(&envelope_no_sig);
    let signature = signing_key.sign(&input);
    let mut sig_hex = String::with_capacity(64 * 2);
    for b in signature.to_bytes() {
        sig_hex.push_str(&format!("{b:02x}"));
    }

    let envelope_json = json!({
        "schema_version": envelope_no_sig.schema_version,
        "purpose": envelope_no_sig.purpose,
        "operator_verifying_key_hex": envelope_no_sig.operator_verifying_key_hex,
        "operator_key_id": envelope_no_sig.operator_key_id,
        "signed_at": envelope_no_sig.signed_at,
        "decay_job_id": envelope_no_sig.decay_job_id,
        "model_name": envelope_no_sig.model_name,
        "prompt_template_blake3": envelope_no_sig.prompt_template_blake3,
        "signature_hex": sig_hex,
    });

    let path = dir.join("attestation.json");
    std::fs::write(&path, serde_json::to_string(&envelope_json).unwrap()).unwrap();
    path
}

fn write_summary_fixture(
    dir: &Path,
    request: SummaryRequest,
    response: SummaryResponse,
) -> PathBuf {
    let fixture = ReplaySummaryFixture {
        entries: vec![ReplaySummaryFixtureEntry { request, response }],
    };
    let path = dir.join("fixture.json");
    std::fs::write(&path, serde_json::to_string_pretty(&fixture).unwrap()).unwrap();
    path
}

/// Maximum summary claim size in bytes — mirrors
/// `cortex_memory::decay::DECAY_SUMMARY_MAX_CLAIM_BYTES`.
const SUMMARY_MAX_CLAIM_BYTES: usize = 4096;

#[test]
fn decay_run_llm_summary_with_fixture_backend_completes() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());

    // Seed two candidate memories with known claims so we can predict the
    // exact SummaryRequest the runner will construct.
    let m1 = seed_candidate_memory(&db_path, "alpha source claim", 1);
    let m2 = seed_candidate_memory(&db_path, "beta source claim", 2);
    let ids = format!("{m1},{m2}");

    // Write a placeholder attestation for the schedule gate (its content is
    // not verified at schedule time, just its presence).
    let placeholder_attest = tmp.path().join("sched-attest.json");
    std::fs::write(&placeholder_attest, "{\"purpose\":\"placeholder\"}").unwrap();

    // Schedule an LLM-summary job.
    let scheduled = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &ids,
            "--summary-method",
            "llm",
            "--operator-attestation",
            placeholder_attest.to_str().unwrap(),
            "--run-immediately",
        ],
    );
    assert_exit(&scheduled, 0);
    let envelope = parse_envelope(&scheduled.stdout);
    let job_id = envelope["report"]["job_id"].as_str().unwrap().to_string();

    // Pins for the attestation and fixture.
    let model = "claude-sonnet-4-7@1";
    let prompt_digest = "blake3:0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
    let summary_text = "LLM-produced summary covering alpha and beta sources.";

    // Write the signed attestation envelope for this specific job.
    let attest_path = write_signed_attestation(tmp.path(), &job_id, model, prompt_digest);

    // Build the exact SummaryRequest the runner will construct: model +
    // prompt from the attestation, source claims from the memory rows in
    // insertion order, max_output_bytes = SUMMARY_MAX_CLAIM_BYTES, and
    // decay_job_id = the scheduled job id.
    let request = SummaryRequest {
        model_name: model.into(),
        prompt_template_blake3: prompt_digest.into(),
        source_claims: vec![
            "alpha source claim".to_string(),
            "beta source claim".to_string(),
        ],
        max_output_bytes: Some(SUMMARY_MAX_CLAIM_BYTES),
        decay_job_id: Some(job_id.clone()),
    };
    let response = SummaryResponse {
        claim: summary_text.into(),
        token_usage: None,
        model_name_echoed: model.into(),
    };
    let fixture_path = write_summary_fixture(tmp.path(), request, response);

    // Run the job with the fixture backend.
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "run",
            "--job-id",
            &job_id,
            "--operator-attestation",
            attest_path.to_str().unwrap(),
            "--summary-backend-fixture",
            fixture_path.to_str().unwrap(),
        ],
    );
    assert_exit(&out, 0);
    let run_envelope = parse_envelope(&out.stdout);
    assert_eq!(run_envelope["command"], "cortex.decay.run");
    assert_eq!(run_envelope["exit_code"], 0);
    assert_eq!(run_envelope["report"]["to_state"], "completed");
    let result_memory_id = run_envelope["report"]["result_memory_id"]
        .as_str()
        .expect("result_memory_id present on completed LLM-summary run");
    assert!(
        result_memory_id.starts_with("mem_"),
        "result memory id should carry `mem_` prefix; got `{result_memory_id}`"
    );
}

#[test]
fn decay_run_llm_summary_with_invalid_fixture_path_refuses() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);

    // Schedule an LLM-summary job (placeholder attestation for schedule gate).
    let placeholder_attest = tmp.path().join("sched-attest.json");
    std::fs::write(&placeholder_attest, "{\"purpose\":\"placeholder\"}").unwrap();
    let scheduled = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "schedule",
            "--kind",
            "candidate-compression",
            "--memory-ids",
            &m1.to_string(),
            "--summary-method",
            "llm",
            "--operator-attestation",
            placeholder_attest.to_str().unwrap(),
            "--run-immediately",
        ],
    );
    assert_exit(&scheduled, 0);
    let scheduled_env = parse_envelope(&scheduled.stdout);
    let job_id = scheduled_env["report"]["job_id"]
        .as_str()
        .unwrap()
        .to_string();

    // Write a real attestation (so the LLM-attestation gate doesn't fire
    // first and hide the fixture-invalid refusal under a different
    // invariant).
    let attest_path = write_signed_attestation(
        tmp.path(),
        &job_id,
        "claude-sonnet-4-7@1",
        "blake3:0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
    );

    // Point --summary-backend-fixture at a path that does not exist.
    let nonexistent = tmp.path().join("does-not-exist.json");
    let out = run_in(
        tmp.path(),
        &[
            "--json",
            "decay",
            "run",
            "--job-id",
            &job_id,
            "--operator-attestation",
            attest_path.to_str().unwrap(),
            "--summary-backend-fixture",
            nonexistent.to_str().unwrap(),
        ],
    );
    assert_exit(&out, 7);
    let run_envelope = parse_envelope(&out.stdout);
    assert_eq!(run_envelope["command"], "cortex.decay.run");
    assert_eq!(run_envelope["exit_code"], 7);
    assert_eq!(
        run_envelope["report"]["invariant"],
        "decay.run.summary_backend_fixture_invalid"
    );
}

#[test]
fn decay_json_envelope_carries_canonical_command_and_exit_code() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = init(tmp.path());
    let m1 = seed_candidate_memory(&db_path, "alpha", 1);
    let envelope = schedule_candidate_compression(tmp.path(), &m1.to_string());
    assert_eq!(envelope["command"], "cortex.decay.schedule");
    assert_eq!(envelope["exit_code"], 0);
    assert_eq!(envelope["outcome"], "ok");
    // The report carries the wire shapes the persistence layer uses.
    assert_eq!(envelope["report"]["kind"], "candidate_compression");
    assert_eq!(envelope["report"]["state"], "pending");
    assert!(envelope["report"]["scheduled_for"].is_string());
}