clm-kernel 0.0.20

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! The Handle Kind Decider (Rust binding).
//!
//! `INV-TAPE-01a` — TYPE DETECTION IS THE KERNEL'S.
//!
//! `card` has no type column. What a card *is* is named by its **handle** (`INV-TAPE-03`),
//! and decided by the kernel's `kindOf`. This module is the **Rust binding** of that
//! decision, not a second implementation: it carries the same grammar and the same declared
//! sector set as `kernel/clm_js_core/src/shared/handleKind.ts` and
//! `kernel/clm_py_core/clm/cross_cutting/handle_kind.py`, and
//! `scripts/ci/check_handle_kind.py` runs the TypeScript and Python bindings over one shared
//! fixture set and asserts they agree. A runtime that derives a kind independently has
//! reintroduced the removed `card_type` column as code.
//! ```text
//! urn:pcard:sprint:orc-02         -> sector "pcard",     kind "sprint"
//! urn:vcard:seal:<hash>           -> sector "vcard",     kind "seal"
//! urn:mcard:telemetry:event:n:7   -> sector "telemetry", kind "event"
//! ```
//! THE GRAMMAR IS DECLARED BY THE HUB, IMPLEMENTED BY THE KERNEL. The hub's
//! `registry/handle_taxonomy.yaml` is the declaration; this embedded set is the
//! implementation, and the drift check asserts they are equal.

/// The decided kind of a handle.
///
/// `declared` distinguishes "an undeclared kind" from "not a handle at all" — which is what
/// makes an undeclared prefix a *finding* rather than a silent miss.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HandleKind {
    pub sector: String,
    pub kind: String,
    pub handle: String,
    pub declared: bool,
    pub subject: Option<String>,
}

/// The declared sectors and their kinds. Must equal the hub's `handle_taxonomy.yaml`.
pub const KIND_SECTORS: &[(&str, &[&str])] = &[
    // Content Memory (content_memory.db)
    (
        "mcard",
        &[
            "content", "knowledge", "schema", "contract", "registry", "record", "projection",
            "derived", "lifecycle",
            // ORC-24: the archetypes (`clm/schema/archetypes/`) as kinds — an
            // archetype is `<kind>_<sector>`, so the kind is derived, not hand-mapped.
            "artifact", "commit", "design_decision", "feedback", "specification",
            "sprint_status", "telemetry", "test_result",
            // EPIC-LCLM: the Layer 0 function's knowledge locus (`function_mcard`).
            "function",
        ],
    ),
    ("doc", &["vault", "document"]),
    ("pcard", &["program", "sprint", "fiber"]),
    ("vcard", &["seal", "execution", "contract"]),
    // Agent Identities (agent_identities.db)
    ("agent", &["root", "actor"]),
    ("node", &["did", "peer"]),
    ("key", &["pub", "rotate"]),
    // Execution History (execution_log.db)
    ("execution", &["record", "trace", "migration"]),
    ("telemetry", &["event"]),
];

/// Sprint 530: the change calculus is a Layer 0 primitive; re-exported here for callers.
pub use crate::layer0::transition::CHANGE_CALCULUS;

/// Split `urn:(?:mcard:<sector>|pcard|vcard):<kind>[:<subject>...]` into its parts.
///
/// Hand-rolled rather than a regex so the crate takes no new dependency; the grammar is
/// small and the split is the whole of it.
fn split_handle(handle: &str) -> Option<(&str, &str, Option<&str>)> {
    let lower = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
    if let Some(rest) = handle.strip_prefix("urn:pcard:") {
        let (kind, subject) = match rest.split_once(':') {
            Some((k, s)) => (k, Some(s)),
            None => (rest, None),
        };
        if !lower(kind) {
            return None;
        }
        return Some(("pcard", kind, subject));
    }
    if let Some(rest) = handle.strip_prefix("urn:vcard:") {
        let (kind, subject) = match rest.split_once(':') {
            Some((k, s)) => (k, Some(s)),
            None => (rest, None),
        };
        if !lower(kind) {
            return None;
        }
        return Some(("vcard", kind, subject));
    }
    // NAMESPACE-01: the window is CLOSED. The four tapes hold `urn:mcard:` and zero
    // `urn:clm:` rows, so the old prefix fails — which is the point.
    let rest = handle.strip_prefix("urn:mcard:")?;
    let (sector, rest) = rest.split_once(':')?;
    let (kind, subject) = match rest.split_once(':') {
        Some((k, s)) => (k, Some(s)),
        None => (rest, None),
    };
    if !lower(sector) || !lower(kind) {
        return None;
    }
    Some((sector, kind, subject))
}

/// Decide the kind of a handle. Pure: no I/O, no state, no cache.
pub fn kind_of(handle: &str) -> Option<HandleKind> {
    let (sector, kind, subject) = split_handle(handle)?;
    let declared = KIND_SECTORS
        .iter()
        .find(|(s, _)| *s == sector)
        .map(|(_, kinds)| kinds.contains(&kind))
        .unwrap_or(false);
    Some(HandleKind {
        sector: sector.to_string(),
        kind: kind.to_string(),
        handle: handle.to_string(),
        declared,
        subject: subject.map(str::to_string),
    })
}

/// The sector of a handle, or `None`.
pub fn sector_of(handle: &str) -> Option<&str> {
    split_handle(handle).map(|(s, _, _)| s)
}

/// The kind within the sector, or `None`.
pub fn kind_name_of(handle: &str) -> Option<&str> {
    split_handle(handle).map(|(_, k, _)| k)
}

/// Is this handle in the given sector?
pub fn is_sector(handle: &str, sector: &str) -> bool {
    sector_of(handle) == Some(sector)
}

/// Is this handle's kind declared? An undeclared kind is a finding, not a `false`.
pub fn is_declared(handle: &str) -> bool {
    kind_of(handle).map(|k| k.declared).unwrap_or(false)
}

/// Every declared `sector:kind` pair, sorted — the drift check compares these to the hub.
pub fn declared_kinds() -> Vec<String> {
    let mut out: Vec<String> = KIND_SECTORS
        .iter()
        .flat_map(|(s, kinds)| kinds.iter().map(move |k| format!("{s}:{k}")))
        .collect();
    out.sort();
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_the_declared_sectors() {
        let k = kind_of("urn:pcard:sprint:orc-02").expect("a handle");
        assert_eq!(k.sector, "pcard");
        assert_eq!(k.kind, "sprint");
        assert_eq!(k.subject.as_deref(), Some("orc-02"));
        assert!(k.declared);

        let v = kind_of("urn:vcard:seal:9f2c").expect("a handle");
        assert_eq!(v.sector, "vcard");
        assert_eq!(v.kind, "seal");
        assert_eq!(v.subject.as_deref(), Some("9f2c"));
        assert!(v.declared);
    }

    #[test]
    fn a_subject_may_contain_colons() {
        let k = kind_of("urn:mcard:node:did:key:z6Mk").expect("a handle");
        assert_eq!(k.sector, "node");
        assert_eq!(k.kind, "did");
        assert_eq!(k.subject.as_deref(), Some("key:z6Mk"));
    }

    #[test]
    fn an_undeclared_kind_is_a_finding_not_a_null() {
        let k = kind_of("urn:mcard:bogus:thing").expect("well formed");
        assert!(!k.declared, "an undeclared kind must report declared:false");
    }

    #[test]
    fn a_non_handle_is_none() {
        assert!(kind_of("not-a-handle").is_none());
        assert!(kind_of("urn:mcard:Pcard:Sprint").is_none(), "the grammar is lowercase");
        assert!(kind_of("urn:mcard:pcard").is_none(), "no kind");
        assert!(kind_of("urn:pcard").is_none(), "no kind");
        assert!(kind_of("urn:vcard").is_none(), "no kind");
        assert!(kind_of("").is_none());
    }

    #[test]
    fn declared_kinds_matches_the_other_bindings() {
        // 36 pairs — the same count the TypeScript and Python bindings report.
        // ORC-21 added doc (+2), ORC-24 added the 9 archetypes (+9), reaching 34,
        // EPIC-LCLM added `function` (+1), reaching 35,
        // and EPIC-CRD added `fiber` (+1), reaching 36.
        assert_eq!(declared_kinds().len(), 36);
    }
}