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
//! `cortex backup` — local offline SQLite + JSONL backup bundle creation.

use std::fs;
use std::io::{Error, ErrorKind, Read};
use std::path::{Path, PathBuf};

use chrono::{SecondsFormat, Utc};
use clap::Args;
use cortex_core::{AuthorityClass, ClaimCeiling, ClaimProofState, RuntimeMode};
use cortex_ledger::{
    audit::{verify_chain, verify_schema_migration_v1_to_v2_boundary},
    JsonlError,
};
use rusqlite::Connection;
use serde::Serialize;

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

const MANIFEST_FILENAME: &str = "BACKUP_MANIFEST";
const SQLITE_BUNDLE_FILENAME: &str = "cortex.db";
const JSONL_BUNDLE_FILENAME: &str = "events.jsonl";

/// Manifest `kind` emitted for a backup of a pre-v2 (or freshly initialised,
/// not yet migrated) store. The schema version recorded alongside is **1**:
/// this represents the *baseline* the schema v2 migrate compares against, not
/// the running tool's `cortex_core::SCHEMA_VERSION`.
const PRE_V2_BACKUP_KIND: &str = "cortex_pre_v2_backup";

/// Manifest `kind` emitted for a backup of a store that has already crossed
/// the v1→v2 boundary (a `schema_migration.v1_to_v2` row exists in the JSONL
/// mirror). The schema version recorded alongside is the running tool's
/// `cortex_core::SCHEMA_VERSION`. These bundles are unrelated to the migrate
/// preflight contract — `cortex migrate v2 --backup-manifest` rejects them so
/// operators cannot accidentally feed a post-cutover bundle into a fresh
/// migration.
const POST_V2_BACKUP_KIND: &str = "cortex_post_v2_backup";

/// Schema version recorded in a `cortex_pre_v2_backup` manifest. Always 1,
/// regardless of the running tool's `cortex_core::SCHEMA_VERSION`. See the
/// matching constant in `cortex-cli/src/cmd/migrate.rs`.
const PRE_V2_BACKUP_SCHEMA_VERSION: u16 = 1;

/// `cortex backup` flags.
#[derive(Debug, Args)]
pub struct BackupArgs {
    /// New output directory for the backup bundle. Must not already exist.
    #[arg(long, value_name = "DIR")]
    pub output: PathBuf,
}

#[derive(Debug, Serialize)]
struct BackupManifest {
    kind: &'static str,
    schema_version: u16,
    sqlite_store: &'static str,
    jsonl_mirror: &'static str,
    tool_version: &'static str,
    backup_timestamp: String,
    sqlite_store_size_bytes: u64,
    sqlite_store_blake3: String,
    jsonl_mirror_size_bytes: u64,
    jsonl_mirror_blake3: String,
    jsonl_mirror_audit_status: &'static str,
    jsonl_mirror_audit_rows_scanned: usize,
    jsonl_mirror_audit_failures: usize,
    /// Per-table SQLite row counts captured at backup time. Used by
    /// `cortex migrate v2` as the input side of the post-migrate count-mismatch
    /// refusal helper (the boundary append adds exactly one event; every other
    /// counted table must remain byte-identical pre- and post-migrate).
    table_row_counts: BackupTableRowCounts,
    /// ADR 0037 §5 amendment: typed truth-ceiling triad. `cortex backup`
    /// operates entirely under local-unsigned runtime mode (no signed
    /// ledger append, no external anchor) and verifies the copied JSONL
    /// hash chain as part of the bundle audit, so a successful manifest
    /// carries `proof_state=full_chain_verified` and
    /// `claim_ceiling=local_unsigned`. An operator inspecting the
    /// bundle offline can recompute the truth ceiling from these fields
    /// without re-running `cortex backup`.
    runtime_mode: RuntimeMode,
    proof_state: ClaimProofState,
    claim_ceiling: ClaimCeiling,
    authority_class: AuthorityClass,
}

/// Per-table SQLite row counts captured by `cortex backup`.
///
/// The field set is deliberately closed at the four tables the v2 cutover
/// touches as bulk-row carriers: `events` (chain rows; +1 after the boundary
/// append), `traces`, `episodes`, and `memories`. Other tables (`principles`,
/// `doctrine`, `audit_records`, etc.) are excluded because they are not part of
/// the v2 expand/backfill input/output equation and would otherwise pin
/// unrelated state into the schema-v2 refusal gate.
#[derive(Debug, Clone, Copy, Serialize)]
struct BackupTableRowCounts {
    events: u64,
    traces: u64,
    episodes: u64,
    memories: u64,
}

#[derive(Debug)]
struct BundleArtifacts {
    sqlite_store_size_bytes: u64,
    sqlite_store_blake3: String,
    jsonl_mirror_size_bytes: u64,
    jsonl_mirror_blake3: String,
    jsonl_mirror_audit: JsonlCopyAudit,
    table_row_counts: BackupTableRowCounts,
    /// Whether a `schema_migration.v1_to_v2` boundary row was observed in the
    /// JSONL mirror. Drives the manifest `kind` / `schema_version` pair:
    /// `cortex_pre_v2_backup` + 1 when absent, `cortex_post_v2_backup` +
    /// running `SCHEMA_VERSION` when present.
    boundary_present: bool,
}

#[derive(Debug)]
struct JsonlCopyAudit {
    status: &'static str,
    rows_scanned: usize,
    failures: usize,
}

/// Run the backup command.
pub fn run(args: BackupArgs) -> Exit {
    let json = output::json_enabled();
    match run_inner(&args) {
        Ok(manifest_path) => {
            if json {
                let manifest_value = match fs::read(&manifest_path).and_then(|bytes| {
                    serde_json::from_slice::<serde_json::Value>(&bytes)
                        .map_err(std::io::Error::other)
                }) {
                    Ok(value) => value,
                    Err(err) => {
                        eprintln!(
                            "cortex backup: failed to re-read manifest {} for JSON output: {err}",
                            manifest_path.display()
                        );
                        return Exit::Internal;
                    }
                };
                let payload = serde_json::json!({
                    "bundle_dir": args.output.display().to_string(),
                    "manifest_path": manifest_path.display().to_string(),
                    "manifest": manifest_value,
                    "restore_verification": "not_performed",
                });
                let envelope = Envelope::new("cortex.backup", Exit::Ok, payload);
                output::emit(&envelope, Exit::Ok)
            } else {
                println!(
                    "cortex backup: local offline bundle = {}",
                    args.output.display()
                );
                println!("cortex backup: manifest = {}", manifest_path.display());
                println!("cortex backup: copied JSONL audit = verified.");
                println!("cortex backup: restore verification not performed.");
                Exit::Ok
            }
        }
        Err(exit) => {
            if json {
                let payload = serde_json::json!({
                    "status": "error",
                    "bundle_dir": args.output.display().to_string(),
                });
                let envelope = Envelope::new("cortex.backup", exit, payload);
                output::emit(&envelope, exit)
            } else {
                exit
            }
        }
    }
}

fn run_inner(args: &BackupArgs) -> Result<PathBuf, Exit> {
    let layout = DataLayout::resolve(None, None)?;
    require_existing_file(&layout.db_path, "SQLite store")?;
    require_existing_file(&layout.event_log_path, "JSONL mirror")?;
    checkpoint_or_reject_active_sqlite_sidecars(&layout.db_path)?;

    reject_existing_path(&args.output, "output")?;

    let parent = args.output.parent().filter(|p| !p.as_os_str().is_empty());
    if let Some(parent) = parent {
        ensure_output_parent(parent)?;
    }

    let staging = staging_dir_for(&args.output);
    reject_existing_path(&staging, "staging path")?;

    fs::create_dir(&staging).map_err(|err| {
        eprintln!(
            "cortex backup: failed to create staging directory {}: {err}",
            staging.display()
        );
        Exit::PreconditionUnmet
    })?;

    match populate_staging_bundle(&layout, &staging) {
        Ok(()) => {}
        Err(exit) => {
            cleanup_staging(&staging);
            return Err(exit);
        }
    }

    if let Err(exit) = reject_existing_path(&args.output, "output") {
        cleanup_staging(&staging);
        return Err(exit);
    }

    publish_staging_bundle(&staging, &args.output).map_err(|err| {
        cleanup_staging(&staging);
        eprintln!(
            "cortex backup: failed to publish backup bundle {}: {err}",
            args.output.display()
        );
        Exit::PreconditionUnmet
    })?;

    Ok(args.output.join(MANIFEST_FILENAME))
}

fn reject_existing_path(path: &Path, label: &str) -> Result<(), Exit> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            eprintln!(
                "cortex backup: precondition unmet: {label} {} is a symlink; no state was changed.",
                path.display()
            );
            Err(Exit::PreconditionUnmet)
        }
        Ok(_) => {
            eprintln!(
                "cortex backup: precondition unmet: {label} {} already exists; no state was changed.",
                path.display()
            );
            Err(Exit::PreconditionUnmet)
        }
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
        Err(err) => {
            eprintln!(
                "cortex backup: failed to inspect {label} {}: {err}; no state was changed.",
                path.display()
            );
            Err(Exit::PreconditionUnmet)
        }
    }
}

fn ensure_output_parent(parent: &Path) -> Result<(), Exit> {
    match fs::symlink_metadata(parent) {
        Ok(metadata) => require_output_parent_directory(parent, &metadata),
        Err(err) if err.kind() == ErrorKind::NotFound => {
            fs::create_dir_all(parent).map_err(|err| {
                eprintln!(
                    "cortex backup: failed to create output parent {}: {err}",
                    parent.display()
                );
                Exit::PreconditionUnmet
            })?;
            let metadata = fs::symlink_metadata(parent).map_err(|err| {
                eprintln!(
                    "cortex backup: failed to inspect output parent {}: {err}; no state was changed.",
                    parent.display()
                );
                Exit::PreconditionUnmet
            })?;
            require_output_parent_directory(parent, &metadata)
        }
        Err(err) => {
            eprintln!(
                "cortex backup: failed to inspect output parent {}: {err}; no state was changed.",
                parent.display()
            );
            Err(Exit::PreconditionUnmet)
        }
    }
}

fn require_output_parent_directory(parent: &Path, metadata: &fs::Metadata) -> Result<(), Exit> {
    if metadata.file_type().is_symlink() {
        eprintln!(
            "cortex backup: precondition unmet: output parent {} is a symlink; no state was changed.",
            parent.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if !metadata.is_dir() {
        eprintln!(
            "cortex backup: precondition unmet: output parent {} is not a directory; no state was changed.",
            parent.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(())
}

fn checkpoint_or_reject_active_sqlite_sidecars(db_path: &Path) -> Result<(), Exit> {
    let sidecars = sqlite_sidecar_paths(db_path);
    if sidecars.iter().any(|sidecar| sidecar.exists()) {
        let pool = Connection::open(db_path).map_err(|err| {
            eprintln!(
                "cortex backup: failed to open SQLite store {} for WAL checkpoint: {err}; backup bundle was not published.",
                db_path.display()
            );
            Exit::PreconditionUnmet
        })?;
        pool.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
            .map_err(|err| {
                eprintln!(
                    "cortex backup: SQLite WAL checkpoint failed for {}: {err}; backup bundle was not published.",
                    db_path.display()
                );
                Exit::PreconditionUnmet
            })?;
        drop(pool);
    }

    let wal_path = &sidecars[0];
    match fs::symlink_metadata(wal_path) {
        Ok(metadata) if metadata.len() > 0 => {
            eprintln!(
                "cortex backup: precondition unmet: active SQLite WAL sidecar {} still contains {} bytes after checkpoint; backup bundle was not published. Run a snapshot-safe backup path before claiming SQLite backup completeness.",
                wal_path.display(),
                metadata.len()
            );
            Err(Exit::PreconditionUnmet)
        }
        Ok(_) => Ok(()),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
        Err(err) => {
            eprintln!(
                "cortex backup: failed to inspect SQLite WAL sidecar {}: {err}; backup bundle was not published.",
                wal_path.display()
            );
            Err(Exit::PreconditionUnmet)
        }
    }
}

fn sqlite_sidecar_paths(db_path: &Path) -> [PathBuf; 2] {
    [
        db_path.with_file_name(format!(
            "{}-wal",
            db_path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("cortex.db")
        )),
        db_path.with_file_name(format!(
            "{}-shm",
            db_path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("cortex.db")
        )),
    ]
}

fn populate_staging_bundle(layout: &DataLayout, staging: &Path) -> Result<(), Exit> {
    let sqlite_store = staging.join(SQLITE_BUNDLE_FILENAME);
    let jsonl_mirror = staging.join(JSONL_BUNDLE_FILENAME);
    copy_artifact(&layout.db_path, &sqlite_store, "SQLite store")?;
    copy_artifact(&layout.event_log_path, &jsonl_mirror, "JSONL mirror")?;

    let artifacts = BundleArtifacts {
        sqlite_store_size_bytes: file_size(&sqlite_store, "copied SQLite store")?,
        sqlite_store_blake3: blake3_file(&sqlite_store, "copied SQLite store")?,
        jsonl_mirror_size_bytes: file_size(&jsonl_mirror, "copied JSONL mirror")?,
        jsonl_mirror_blake3: blake3_file(&jsonl_mirror, "copied JSONL mirror")?,
        jsonl_mirror_audit: audit_verify_copied_jsonl(&jsonl_mirror)?,
        table_row_counts: count_backup_tables(&sqlite_store)?,
        boundary_present: detect_v1_to_v2_boundary(&jsonl_mirror)?,
    };
    write_manifest(staging, artifacts)
}

/// Decide whether the copied JSONL mirror already carries a `schema_migration.v1_to_v2`
/// boundary row. Used to pick the manifest `kind` (pre vs. post cutover); we deliberately
/// pass `required=false` so a clean pre-cutover mirror returns an empty
/// `boundary_rows` set rather than reporting a missing-boundary failure.
fn detect_v1_to_v2_boundary(jsonl_mirror: &Path) -> Result<bool, Exit> {
    match verify_schema_migration_v1_to_v2_boundary(jsonl_mirror, false) {
        Ok(report) => Ok(!report.boundary_rows.is_empty()),
        Err(err) => {
            eprintln!(
                "cortex backup: failed to inspect copied JSONL mirror `{}` for v1-to-v2 boundary state: {err}; backup bundle was not published.",
                jsonl_mirror.display()
            );
            Err(map_jsonl_verify_err(&err))
        }
    }
}

fn count_backup_tables(sqlite_store: &Path) -> Result<BackupTableRowCounts, Exit> {
    // Open the COPIED SQLite store read-only and count the four v2-cutover-bearing
    // tables. A freshly created store (e.g. `cortex init` without any subsequent
    // `cortex ingest`) does not yet have the v1 tables physically present — that
    // is the v1 store's contract: migrations run when the first read/write
    // command opens it. In that case a count of 0 is the correct pre-migrate
    // baseline. We only fail closed when the SQLite copy is structurally broken.
    //
    // We use the SQLite URI form with `immutable=1` so the connection does not
    // create the `-wal` / `-shm` sidecars next to the copied store. Without
    // this, Windows would leave stale sidecars in the staging directory and
    // the subsequent `publish_staging_bundle` rename would fail with
    // "directory is not empty" because the sidecars block `remove_dir`.
    let uri = format!(
        "file:{}?mode=ro&immutable=1",
        sqlite_store.display().to_string().replace('\\', "/")
    );
    let pool = Connection::open_with_flags(
        &uri,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_URI,
    )
    .map_err(|err| {
        eprintln!(
            "cortex backup: failed to open copied SQLite store for table-count manifest field {}: {err}",
            sqlite_store.display()
        );
        Exit::PreconditionUnmet
    })?;
    let counts = BackupTableRowCounts {
        events: optional_table_count(&pool, "events")?,
        traces: optional_table_count(&pool, "traces")?,
        episodes: optional_table_count(&pool, "episodes")?,
        memories: optional_table_count(&pool, "memories")?,
    };
    drop(pool);
    Ok(counts)
}

fn optional_table_count(pool: &Connection, table: &'static str) -> Result<u64, Exit> {
    let exists: i64 = pool
        .query_row(
            "SELECT EXISTS (
                SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1
            );",
            [table],
            |row| row.get(0),
        )
        .map_err(|err| {
            eprintln!(
                "cortex backup: failed to inspect sqlite_master for table `{table}` in copied SQLite store: {err}"
            );
            Exit::PreconditionUnmet
        })?;
    if exists == 0 {
        return Ok(0);
    }
    let sql = format!("SELECT COUNT(*) FROM {table};");
    pool.query_row(&sql, [], |row| row.get::<_, u64>(0))
        .map_err(|err| {
            eprintln!(
                "cortex backup: failed to read row count for table `{table}` from copied SQLite store: {err}"
            );
            Exit::PreconditionUnmet
        })
}

fn audit_verify_copied_jsonl(path: &Path) -> Result<JsonlCopyAudit, Exit> {
    match verify_chain(path) {
        Ok(report) if report.ok() => Ok(JsonlCopyAudit {
            status: "verified",
            rows_scanned: report.rows_scanned,
            failures: report.failures.len(),
        }),
        Ok(report) => {
            for failure in &report.failures {
                eprintln!(
                    "cortex backup: copied JSONL audit failure at line {}: {:?}",
                    failure.line, failure.reason
                );
            }
            eprintln!(
                "cortex backup: copied JSONL audit verification failed for `{}`; backup bundle was not published.",
                path.display()
            );
            Err(Exit::IntegrityFailure)
        }
        Err(err) => {
            eprintln!(
                "cortex backup: copied JSONL audit verification failed for `{}`: {err}; backup bundle was not published.",
                path.display()
            );
            Err(map_jsonl_verify_err(&err))
        }
    }
}

fn map_jsonl_verify_err(err: &JsonlError) -> Exit {
    match err {
        JsonlError::Decode { .. } | JsonlError::ChainBroken(_) => Exit::ChainCorruption,
        JsonlError::Validation(_) => Exit::PreconditionUnmet,
        JsonlError::Io { .. } | JsonlError::Encode(_) => Exit::Internal,
    }
}

fn require_existing_file(path: &Path, label: &str) -> Result<(), Exit> {
    let metadata = fs::metadata(path).map_err(|_| {
        eprintln!(
            "cortex backup: precondition unmet: {label} {} does not exist; no state was changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if !metadata.is_file() {
        eprintln!(
            "cortex backup: precondition unmet: {label} {} is not a file; no state was changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(())
}

fn copy_artifact(source: &Path, destination: &Path, label: &str) -> Result<(), Exit> {
    fs::copy(source, destination).map_err(|err| {
        eprintln!(
            "cortex backup: failed to copy {label} {} to {}: {err}",
            source.display(),
            destination.display()
        );
        Exit::PreconditionUnmet
    })?;
    Ok(())
}

fn file_size(path: &Path, label: &str) -> Result<u64, Exit> {
    fs::metadata(path)
        .map(|metadata| metadata.len())
        .map_err(|err| {
            eprintln!(
                "cortex backup: failed to read {label} metadata {}: {err}",
                path.display()
            );
            Exit::PreconditionUnmet
        })
}

fn blake3_file(path: &Path, label: &str) -> Result<String, Exit> {
    let mut file = fs::File::open(path).map_err(|err| {
        eprintln!(
            "cortex backup: failed to open {label} {}: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let mut hasher = blake3::Hasher::new();
    let mut buffer = [0_u8; 16 * 1024];
    loop {
        let read = file.read(&mut buffer).map_err(|err| {
            eprintln!(
                "cortex backup: failed to read {label} {}: {err}",
                path.display()
            );
            Exit::PreconditionUnmet
        })?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(format!("blake3:{}", hasher.finalize().to_hex()))
}

fn write_manifest(staging: &Path, artifacts: BundleArtifacts) -> Result<(), Exit> {
    // Boundary-conditional manifest typing:
    // * No boundary row in the JSONL mirror → this is a pre-cutover (or
    //   freshly initialised) store. Emit `kind=cortex_pre_v2_backup` with
    //   `schema_version=1`: the v2 migrate preflight contract expects to
    //   compare against the v1 baseline regardless of the running tool's
    //   `SCHEMA_VERSION` constant (see `cortex-cli/src/cmd/migrate.rs`
    //   `PRE_V2_BACKUP_SCHEMA_VERSION`). This is what the standard backup-
    //   then-migrate operator flow produces.
    // * Boundary row observed → the store has already been cut over. Emit
    //   `kind=cortex_post_v2_backup` with the running `SCHEMA_VERSION` so
    //   downstream tooling can tell post-cutover bundles apart from the
    //   pre-cutover artifact that `cortex migrate v2 --backup-manifest`
    //   accepts.
    let (kind, schema_version) = if artifacts.boundary_present {
        (POST_V2_BACKUP_KIND, cortex_core::SCHEMA_VERSION)
    } else {
        (PRE_V2_BACKUP_KIND, PRE_V2_BACKUP_SCHEMA_VERSION)
    };
    // ADR 0037 §5 amendment: `cortex backup` always runs under
    // `local_unsigned` runtime mode — it does not append signed rows or
    // anchor externally. A successful manifest carries
    // `proof_state=full_chain_verified` because the audit pass on the
    // copied JSONL succeeded (a failed pass returns an error before we
    // reach this constructor). `authority_class=observed` reflects that
    // the bundle is an audit-visible local snapshot, not an operator
    // attestation. The composed `claim_ceiling` clamps to the weakest
    // signal — `local_unsigned`.
    let runtime_mode = RuntimeMode::LocalUnsigned;
    let proof_state = ClaimProofState::FullChainVerified;
    let authority_class = AuthorityClass::Observed;
    let claim_ceiling = cortex_core::effective_ceiling(
        runtime_mode,
        authority_class,
        proof_state,
        ClaimCeiling::LocalUnsigned,
    );

    let manifest = BackupManifest {
        kind,
        schema_version,
        sqlite_store: SQLITE_BUNDLE_FILENAME,
        jsonl_mirror: JSONL_BUNDLE_FILENAME,
        tool_version: env!("CARGO_PKG_VERSION"),
        backup_timestamp: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
        sqlite_store_size_bytes: artifacts.sqlite_store_size_bytes,
        sqlite_store_blake3: artifacts.sqlite_store_blake3,
        jsonl_mirror_size_bytes: artifacts.jsonl_mirror_size_bytes,
        jsonl_mirror_blake3: artifacts.jsonl_mirror_blake3,
        jsonl_mirror_audit_status: artifacts.jsonl_mirror_audit.status,
        jsonl_mirror_audit_rows_scanned: artifacts.jsonl_mirror_audit.rows_scanned,
        jsonl_mirror_audit_failures: artifacts.jsonl_mirror_audit.failures,
        table_row_counts: artifacts.table_row_counts,
        runtime_mode,
        proof_state,
        claim_ceiling,
        authority_class,
    };

    let tmp_path = staging.join(format!("{MANIFEST_FILENAME}.tmp"));
    let manifest_path = staging.join(MANIFEST_FILENAME);
    let manifest_bytes = serde_json::to_vec_pretty(&manifest).map_err(|err| {
        eprintln!("cortex backup: failed to serialize backup manifest: {err}");
        Exit::Internal
    })?;
    fs::write(&tmp_path, manifest_bytes).map_err(|err| {
        eprintln!(
            "cortex backup: failed to write temporary manifest {}: {err}",
            tmp_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    fs::rename(&tmp_path, &manifest_path).map_err(|err| {
        eprintln!(
            "cortex backup: failed to publish manifest {}: {err}",
            manifest_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    Ok(())
}

fn publish_staging_bundle(staging: &Path, output: &Path) -> Result<(), Error> {
    fs::create_dir(output)?;
    let publish_result = (|| {
        fs::rename(
            staging.join(SQLITE_BUNDLE_FILENAME),
            output.join(SQLITE_BUNDLE_FILENAME),
        )?;
        fs::rename(
            staging.join(JSONL_BUNDLE_FILENAME),
            output.join(JSONL_BUNDLE_FILENAME),
        )?;
        fs::rename(
            staging.join(MANIFEST_FILENAME),
            output.join(MANIFEST_FILENAME),
        )?;
        fs::remove_dir(staging)
    })();

    if publish_result.is_err() {
        cleanup_staging(staging);
        cleanup_output(output);
    }
    publish_result
}

fn staging_dir_for(output: &Path) -> PathBuf {
    let parent = output.parent().filter(|p| !p.as_os_str().is_empty());
    let name = output
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("cortex-backup");
    let staging_name = format!(".{name}.staging");
    parent
        .map(|parent| parent.join(&staging_name))
        .unwrap_or_else(|| PathBuf::from(staging_name))
}

fn cleanup_staging(staging: &Path) {
    if staging.exists() {
        let _ = fs::remove_dir_all(staging);
    }
}

fn cleanup_output(output: &Path) {
    if output.exists() {
        let _ = fs::remove_dir_all(output);
    }
}