crtx 0.1.0

CLI for the Cortex supervisory memory substrate.
//! Subcommand implementations for the `cortex` binary.
//!
//! Each module exposes a single `run(...)` entry point that returns
//! [`crate::exit::Exit`]. The top-level dispatcher in `main.rs` casts the
//! returned variant to a process exit code — there is no other side channel
//! for command success or failure.

pub mod audit;
pub mod backup;
pub mod completions;
pub mod compliance;
pub mod context;
pub mod decay;
pub mod doctor;
pub mod from_store;
pub mod ingest;
pub mod init;
pub mod memory;
pub mod migrate;
pub mod principle_promote;
pub mod principles;
pub mod proof;
pub mod reflect;
pub mod release;
pub mod restore;
pub mod run;
pub mod run_ledger_drill;
pub mod session;
pub mod sign;
pub mod temporal;

use crate::exit::Exit;
use crate::paths::DataLayout;

use cortex_core::SCHEMA_VERSION;
use cortex_store::migrate::apply_pending;
use cortex_store::Pool;

/// Open the default SQLite store after `cortex init` has created the DB path.
pub(crate) fn open_default_store(command: &str) -> Result<Pool, Exit> {
    let layout = DataLayout::resolve(None, None)?;
    if !layout.db_path.exists() {
        eprintln!(
            "cortex {command}: precondition unmet: database {} does not exist; run `cortex init` first. no state was changed.",
            layout.db_path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }

    let pool = Pool::open(&layout.db_path).map_err(|err| {
        eprintln!("cortex {command}: failed to open database: {err}");
        Exit::PreconditionUnmet
    })?;
    apply_pending(&pool).map_err(|err| {
        eprintln!("cortex {command}: failed to apply migrations: {err}");
        Exit::Internal
    })?;

    let report =
        cortex_store::verify::verify_schema_version(&pool, SCHEMA_VERSION).map_err(|err| {
            eprintln!("cortex {command}: failed to verify schema preconditions: {err}");
            Exit::PreconditionUnmet
        })?;
    if !report.is_ok() {
        for failure in &report.failures {
            eprintln!(
                "cortex {command}: {}: {}",
                failure.invariant(),
                failure.detail()
            );
        }
        eprintln!(
            "cortex {command}: hint: run `cortex doctor --repair` to apply pending migrations, \
             or `cortex migrate v2 --backup-manifest <path>` for a major version upgrade"
        );
        return Err(Exit::SchemaMismatch);
    }

    Ok(pool)
}
pub mod models;
pub mod serve;