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
//! End-to-end CLI acceptance tests for lane 1.C.
//!
//! These tests shell out to the compiled `cortex` binary via Cargo's
//! `CARGO_BIN_EXE_<name>` env var (set automatically for integration tests
//! in the same crate). They cover the acceptance criteria spelled out in
//! `docs/LANES.md` for tasks T-1.C.1, T-1.C.2, T-1.C.3, and T-1.C.4.
//!
//! The tests deliberately avoid in-process invocation: the CLI's exit-code
//! contract is what operators rely on, and only an out-of-process spawn
//! exercises the real `std::process::exit` path.

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

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

fn fixtures_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
}

fn run(args: &[&str]) -> std::process::Output {
    Command::new(cortex_bin())
        .args(args)
        .output()
        .expect("spawn cortex")
    // We do NOT inherit stdout/stderr here so tests can match against output.
}

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),
    );
}

// =====================================================================
// T-1.C.1: cortex init
// =====================================================================

#[test]
fn t_1_c_1_init_creates_db_and_event_log() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    let out = run(&[
        "init",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);
    assert_exit(&out, 0);
    assert!(db.exists(), "db file should exist after init");
    assert!(log.exists(), "event-log file should exist after init");
}

#[test]
fn t_1_c_1_init_is_idempotent() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    let args: Vec<&str> = vec![
        "init",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ];
    assert_exit(&run(&args), 0);
    let mtime_db_first = mtime(&db);
    let mtime_log_first = mtime(&log);

    // Run again. Both files MUST still exist and MUST not be re-truncated /
    // re-created โ€” we approximate "no new files written" by asserting the
    // file mtimes are unchanged. (We cannot directly observe file
    // creation without OS-level inotify; mtime invariance is a strong proxy
    // because `init` opens with `create_new` which would error if the file
    // existed, so the second run skipping that path is what keeps mtime
    // stable.)
    assert_exit(&run(&args), 0);
    assert_eq!(mtime(&db), mtime_db_first, "db must not be re-touched");
    assert_eq!(
        mtime(&log),
        mtime_log_first,
        "event log must not be re-touched"
    );
}

#[test]
fn t_1_c_1_init_bogus_flag_exits_usage() {
    let out = run(&["init", "--bogus"]);
    assert_exit(&out, 2);
}

#[cfg(unix)]
#[test]
fn t_1_c_1_init_validate_perms_rejects_loose_dir() {
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("loose");
    fs::create_dir(&dir).unwrap();
    fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
    let db = dir.join("cortex.db");
    let log = dir.join("events.jsonl");
    let out = run(&[
        "init",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
        "--validate-perms",
    ]);
    assert_exit(&out, 7);
}

#[test]
fn t_3_d_10_init_rejects_existing_wal_sidecar() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    std::fs::write(tmp.path().join("cortex.db-wal"), b"unverified wal").unwrap();

    let out = run(&[
        "init",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    assert!(
        !db.exists(),
        "init must not create db after sidecar preflight failure"
    );
    assert!(
        !log.exists(),
        "init must not create event log after sidecar preflight failure"
    );
}

// =====================================================================
// T-1.C.2: cortex ingest (idempotency anti-criterion is the headline)
// =====================================================================

#[test]
fn t_1_c_2_ingest_then_reingest_is_noop() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    let session = fixtures_dir().join("session-minimal.json");

    // First init (so paths exist).
    assert_exit(
        &run(&[
            "init",
            "--db",
            db.to_str().unwrap(),
            "--event-log",
            log.to_str().unwrap(),
        ]),
        0,
    );

    // First ingest.
    let first = run(&[
        "ingest",
        session.to_str().unwrap(),
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);
    assert_exit(&first, 0);
    let first_log_size = std::fs::metadata(&log).unwrap().len();
    let first_stdout = String::from_utf8_lossy(&first.stdout).to_string();
    assert!(first_stdout.contains("appended"));
    assert!(first_stdout.contains("chain_head"));

    // Second ingest โ€” MUST be a no-op.
    let second = run(&[
        "ingest",
        session.to_str().unwrap(),
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);
    assert_exit(&second, 0);
    let second_log_size = std::fs::metadata(&log).unwrap().len();
    assert_eq!(
        first_log_size, second_log_size,
        "re-ingest must not grow the JSONL log"
    );
    let second_stdout = String::from_utf8_lossy(&second.stdout).to_string();
    assert!(
        second_stdout.contains("appended_count = 0"),
        "second ingest stdout: {second_stdout}"
    );
}

// =====================================================================
// T-1.C.3: cortex audit verify
// =====================================================================

#[test]
fn t_1_c_3_audit_verify_clean_chain_is_ok() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    let session = fixtures_dir().join("session-minimal.json");

    assert_exit(
        &run(&[
            "init",
            "--db",
            db.to_str().unwrap(),
            "--event-log",
            log.to_str().unwrap(),
        ]),
        0,
    );
    assert_exit(
        &run(&[
            "ingest",
            session.to_str().unwrap(),
            "--db",
            db.to_str().unwrap(),
            "--event-log",
            log.to_str().unwrap(),
        ]),
        0,
    );

    let out = run(&[
        "audit",
        "verify",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);
    assert_exit(&out, 0);
}

#[test]
fn t_1_c_3_audit_verify_byte_corruption_returns_chain_corruption() {
    use std::io::Write;
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("cortex.db");
    let log = tmp.path().join("events.jsonl");
    let session = fixtures_dir().join("session-minimal.json");

    assert_exit(
        &run(&[
            "init",
            "--db",
            db.to_str().unwrap(),
            "--event-log",
            log.to_str().unwrap(),
        ]),
        0,
    );
    assert_exit(
        &run(&[
            "ingest",
            session.to_str().unwrap(),
            "--db",
            db.to_str().unwrap(),
            "--event-log",
            log.to_str().unwrap(),
        ]),
        0,
    );

    // Bytewise corrupt: append a malformed JSON line.
    let mut f = std::fs::OpenOptions::new().append(true).open(&log).unwrap();
    writeln!(f, "{{not json").unwrap();
    drop(f);

    let out = run(&[
        "audit",
        "verify",
        "--db",
        db.to_str().unwrap(),
        "--event-log",
        log.to_str().unwrap(),
    ]);
    assert_exit(&out, 6);
}

// =====================================================================
// T-1.C.4: cortex reflect
// =====================================================================

#[test]
fn t_1_c_4_reflect_stdout_matches_expected_fixture() {
    let out = run(&[
        "reflect",
        "--trace",
        "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW",
        "--model",
        "replay",
    ]);
    assert_exit(&out, 0);
    let expected = std::fs::read(fixtures_dir().join("reflect-expected.json")).unwrap();
    assert_eq!(
        out.stdout, expected,
        "reflect stdout did not match expected byte-for-byte\n--- got ---\n{}\n--- expected ---\n{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&expected),
    );
}

#[test]
fn t_1_c_4_reflect_persists_nothing() {
    // Drive reflect against a brand-new tmpdir as $HOME / data dir override.
    // We do not call `init`. After the run, no files in tmpdir should have
    // been created by reflect (the only file present is the binary's
    // tracing log, which goes to stderr via the writer config, not disk).
    let tmp = tempfile::tempdir().unwrap();
    let before: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
    assert!(before.is_empty(), "tmpdir should start empty");

    // We can't easily redirect $XDG_DATA_HOME on every platform here, so we
    // use a different angle: count files in CWD before and after. The
    // reflect command does no fs writes outside the (unused) data dir, and
    // running it from a clean tmpdir means the cwd is the worktree root.
    // The important guarantee is that reflect does not write to its own
    // fixtures dir or to the JSONL log path in $XDG_DATA_HOME.
    // We assert the simpler invariant: tmpdir stays empty after the call.
    let out = Command::new(cortex_bin())
        .current_dir(tmp.path())
        .args([
            "reflect",
            "--trace",
            "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW",
            "--model",
            "replay",
        ])
        .output()
        .expect("spawn cortex");
    assert_exit(&out, 0);
    let after: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
    assert!(
        after.is_empty(),
        "reflect must not write to the working directory"
    );
}

/// Build a tmp `--fixtures-dir` containing one signed fixture whose
/// `request_match.prompt_hash` matches `prompt_hash` and whose response
/// `text` body is `body_text`. Returns the tmpdir path so the test can pass
/// it as `--fixtures-dir`.
fn write_replay_fixture_dir(
    tmp_root: &Path,
    fixture_name: &str,
    prompt_hash: &str,
    body_text: &str,
) -> PathBuf {
    let fixture_path = tmp_root.join(fixture_name);
    let body_text_escaped = serde_json::Value::String(body_text.to_string()).to_string();
    let fixture_json = format!(
        "{{\
\"request_match\":{{\"model\":\"claude-3-5-sonnet-20240620\",\"prompt_hash\":\"{prompt_hash}\"}},\
\"response\":{{\"text\":{body_text_escaped},\"model\":\"claude-3-5-sonnet-20240620\"}}\
}}"
    );
    std::fs::write(&fixture_path, &fixture_json).unwrap();
    let fixture_hash = blake3_hex(fixture_json.as_bytes());
    std::fs::write(
        tmp_root.join("INDEX.toml"),
        format!("[[fixture]]\npath = \"{fixture_name}\"\nblake3 = \"{fixture_hash}\"\n"),
    )
    .unwrap();
    tmp_root.to_path_buf()
}

#[test]
fn t_1_c_4_reflect_quarantines_open_contradiction_and_suppresses_payload() {
    // SessionReflection with an open contradiction triggers
    // `AdmissionDecision::Quarantine` per ADR 0024. The reflect CLI must
    // suppress the candidate-shaped payload and emit a diagnostic envelope
    // whose `policy_outcome.final_outcome` is `quarantine`. The process MUST
    // exit Ok so operators can still inspect the explainability surface.
    let tmp = tempfile::tempdir().unwrap();
    // Trace + prompt hash pair for `trc_01ARZ3NDEKTSV4RRFFQ69G5FQQ`.
    let prompt_hash = "b8760ace962fe6210196ba5ef681c479599db7da361225f129a83f21598f4f05";
    let body = serde_json::json!({
        "trace_id": "trc_01ARZ3NDEKTSV4RRFFQ69G5FQQ",
        "episode_candidates": [{
            "summary": "Open contradiction demo.",
            "source_event_ids": ["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"],
            "domains": ["agents"],
            "entities": ["Cortex"],
            "candidate_meaning": null,
            "confidence": 0.5
        }],
        "memory_candidates": [{
            "memory_type": "strategic",
            "claim": "Reflection memory remains candidate-only.",
            "source_episode_indexes": [0],
            "applies_when": ["reflecting"],
            "does_not_apply_when": ["promoting"],
            "confidence": 0.8,
            "initial_salience": {
                "reusability": 0.5,
                "consequence": 0.5,
                "emotional_charge": 0.0
            }
        }],
        "contradictions": [{"claim": "conflict observed"}],
        "doctrine_suggestions": []
    })
    .to_string();
    let fixtures_dir = write_replay_fixture_dir(
        tmp.path(),
        "cortex-reflect-quarantine.json",
        prompt_hash,
        &body,
    );

    let out = Command::new(cortex_bin())
        .args([
            "reflect",
            "--trace",
            "trc_01ARZ3NDEKTSV4RRFFQ69G5FQQ",
            "--model",
            "replay",
            "--fixtures-dir",
            fixtures_dir.to_str().unwrap(),
        ])
        .output()
        .expect("spawn cortex");
    assert_exit(&out, 0);
    let stdout: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("envelope is valid JSON");
    assert_eq!(
        stdout["policy_outcome"]["final_outcome"], "quarantine",
        "policy outcome must be quarantine for an open contradiction: {stdout}"
    );
    assert!(
        stdout.get("payload").is_none() || stdout["payload"].is_null(),
        "quarantine envelope must not include candidate-shaped payload: {stdout}"
    );
    assert!(
        stdout["diagnostic"].is_object(),
        "quarantine envelope must include a diagnostic: {stdout}"
    );
    let contributing = stdout["policy_outcome"]["contributing"]
        .as_array()
        .expect("contributing must be an array");
    let discarded = stdout["policy_outcome"]["discarded"]
        .as_array()
        .expect("discarded must be an array");
    let rule_ids: Vec<&str> = contributing
        .iter()
        .chain(discarded.iter())
        .filter_map(|c| c["rule_id"].as_str())
        .collect();
    assert!(rule_ids.contains(&"reflect.admission_decision"));
    assert!(rule_ids.contains(&"reflect.fixture_integrity"));
    assert!(rule_ids.contains(&"reflect.adapter_authority_class"));
}

#[test]
fn t_1_c_4_reflect_rejects_unparseable_payload_with_quarantined_input_exit() {
    // A response body that is not a SessionReflection JSON triggers a parse
    // failure inside the admission contributor; per ADR 0026 ยง3 this fails
    // closed with `Reject` and the CLI exits `Exit::QuarantinedInput` (5).
    let tmp = tempfile::tempdir().unwrap();
    // Trace + prompt hash pair for `trc_01ARZ3NDEKTSV4RRFFQ69G5FRR`.
    let prompt_hash = "ac95f33f6ddcaefdb4f11400bbb686d61dd18c09b71f87c83b6a3cfaa81c5ba4";
    let body = serde_json::json!({"not_a": "session_reflection"}).to_string();
    let fixtures_dir =
        write_replay_fixture_dir(tmp.path(), "cortex-reflect-reject.json", prompt_hash, &body);

    let out = Command::new(cortex_bin())
        .args([
            "reflect",
            "--trace",
            "trc_01ARZ3NDEKTSV4RRFFQ69G5FRR",
            "--model",
            "replay",
            "--fixtures-dir",
            fixtures_dir.to_str().unwrap(),
        ])
        .output()
        .expect("spawn cortex");
    assert_exit(&out, 5);
    assert!(
        out.stdout.is_empty(),
        "reject path must not print candidate-shaped output: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("admission rejected"),
        "stderr must surface the reject reason: {stderr}"
    );
}

#[test]
fn t_1_c_4_reflect_fixture_integrity_failure_exits_quarantined_input() {
    // Build a fresh fixtures dir, copy the demo fixture, sign it, then
    // mutate the fixture bytes after signing so the adapter's hash check
    // fails on construction.
    let tmp = tempfile::tempdir().unwrap();
    let src = fixtures_dir()
        .join("replay")
        .join("cortex-reflect-trace-demo.json");
    let dst_fixture = tmp.path().join("cortex-reflect-trace-demo.json");
    std::fs::copy(&src, &dst_fixture).unwrap();
    let original_hash = blake3_hex(&std::fs::read(&dst_fixture).unwrap());
    std::fs::write(
        tmp.path().join("INDEX.toml"),
        format!(
            "[[fixture]]\npath = \"cortex-reflect-trace-demo.json\"\nblake3 = \"{original_hash}\"\n"
        ),
    )
    .unwrap();
    // Tamper after signing: append a byte. (Append, not overwrite, so the
    // file is still valid JSON-ish; the adapter only cares about the hash.)
    let mut bytes = std::fs::read(&dst_fixture).unwrap();
    bytes.push(b' ');
    std::fs::write(&dst_fixture, bytes).unwrap();

    let out = Command::new(cortex_bin())
        .args([
            "reflect",
            "--trace",
            "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW",
            "--model",
            "replay",
            "--fixtures-dir",
            tmp.path().to_str().unwrap(),
        ])
        .output()
        .expect("spawn cortex");
    assert_exit(&out, 5);
}

fn blake3_hex(bytes: &[u8]) -> String {
    // Re-export from cortex-llm would be cleaner but tests only depend on
    // the binary; do the BLAKE3 directly via the workspace `blake3` crate
    // dependency... which we don't have here. Shell out to `b3sum`?
    // Instead: spawn a tiny in-process hash via `cortex-llm`'s helper would
    // require adding cortex-llm as a dev-dep. The simplest path is to
    // include the helper inline using the workspace crate. We add `blake3`
    // as an inline dev-dep in Cargo.toml and use it here.
    blake3::hash(bytes).to_hex().to_string()
}

fn mtime(p: &Path) -> std::time::SystemTime {
    std::fs::metadata(p)
        .unwrap()
        .modified()
        .expect("filesystem supports mtime")
}