Skip to main content

clm_rust_core/
handle_kind.rs

1//! The Handle Kind Decider (Rust binding).
2//!
3//! `INV-TAPE-01a` — TYPE DETECTION IS THE KERNEL'S.
4//!
5//! `card` has no type column. What a card *is* is named by its **handle** (`INV-TAPE-03`),
6//! and decided by the kernel's `kindOf`. This module is the **Rust binding** of that
7//! decision, not a second implementation: it carries the same grammar and the same declared
8//! sector set as `kernel/clm_js_core/src/shared/handleKind.ts` and
9//! `kernel/clm_py_core/clm/cross_cutting/handle_kind.py`, and
10//! `scripts/ci/check_handle_kind.py` runs the TypeScript and Python bindings over one shared
11//! fixture set and asserts they agree. A runtime that derives a kind independently has
12//! reintroduced the removed `card_type` column as code.
13//! ```text
14//! urn:mcard:pcard:sprint:orc-02   -> sector "pcard",     kind "sprint"
15//! urn:mcard:vcard:seal:<hash>     -> sector "vcard",     kind "seal"
16//! urn:mcard:telemetry:event:n:7   -> sector "telemetry", kind "event"
17//! ```
18//! THE GRAMMAR IS DECLARED BY THE HUB, IMPLEMENTED BY THE KERNEL. The hub's
19//! `registry/handle_taxonomy.yaml` is the declaration; this embedded set is the
20//! implementation, and the drift check asserts they are equal.
21
22/// The decided kind of a handle.
23///
24/// `declared` distinguishes "an undeclared kind" from "not a handle at all" — which is what
25/// makes an undeclared prefix a *finding* rather than a silent miss.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct HandleKind {
28    pub sector: String,
29    pub kind: String,
30    pub handle: String,
31    pub declared: bool,
32    pub subject: Option<String>,
33}
34
35/// The declared sectors and their kinds. Must equal the hub's `handle_taxonomy.yaml`.
36pub const KIND_SECTORS: &[(&str, &[&str])] = &[
37    // Content Memory (content_memory.db)
38    (
39        "mcard",
40        &[
41            "content", "knowledge", "schema", "contract", "registry", "record", "projection",
42            "derived", "lifecycle",
43            // ORC-24: the nine archetypes (`clm/schema/archetypes/`) as kinds — an
44            // archetype is `<kind>_<sector>`, so the kind is derived, not hand-mapped.
45            "artifact", "commit", "design_decision", "feedback", "specification",
46            "sprint_status", "telemetry", "test_result",
47        ],
48    ),
49    ("doc", &["vault", "document"]),
50    ("pcard", &["program", "sprint"]),
51    ("vcard", &["seal", "execution", "contract"]),
52    // Agent Identities (agent_identities.db)
53    ("agent", &["root", "actor"]),
54    ("node", &["did", "peer"]),
55    ("key", &["pub", "rotate"]),
56    // Execution History (execution_log.db)
57    ("execution", &["record", "trace", "migration"]),
58    ("telemetry", &["event"]),
59];
60
61/// The closed set of transition kinds (`INV-TAPE-04`). The KIND of a change is card content
62/// in the lifecycle sidecar, never a column.
63pub const CHANGE_CALCULUS: &[&str] = &[
64    "CREATE", "UPDATE", "SEAL", "RELOCATE", "ROTATE", "TOMBSTONE",
65];
66
67/// Split `urn:mcard:<sector>:<kind>[:<subject>...]` into its parts.
68///
69/// Hand-rolled rather than a regex so the crate takes no new dependency; the grammar is
70/// small and the split is the whole of it.
71fn split_handle(handle: &str) -> Option<(&str, &str, Option<&str>)> {
72    // NAMESPACE-01: the window is CLOSED. The four tapes hold `urn:mcard:` and zero
73    // `urn:clm:` rows, so the old prefix fails — which is the point.
74    let rest = handle.strip_prefix("urn:mcard:")?;
75    let (sector, rest) = rest.split_once(':')?;
76    let (kind, subject) = match rest.split_once(':') {
77        Some((k, s)) => (k, Some(s)),
78        None => (rest, None),
79    };
80    let lower = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
81    if !lower(sector) || !lower(kind) {
82        return None;
83    }
84    Some((sector, kind, subject))
85}
86
87/// Decide the kind of a handle. Pure: no I/O, no state, no cache.
88pub fn kind_of(handle: &str) -> Option<HandleKind> {
89    let (sector, kind, subject) = split_handle(handle)?;
90    let declared = KIND_SECTORS
91        .iter()
92        .find(|(s, _)| *s == sector)
93        .map(|(_, kinds)| kinds.contains(&kind))
94        .unwrap_or(false);
95    Some(HandleKind {
96        sector: sector.to_string(),
97        kind: kind.to_string(),
98        handle: handle.to_string(),
99        declared,
100        subject: subject.map(str::to_string),
101    })
102}
103
104/// The sector of a handle, or `None`.
105pub fn sector_of(handle: &str) -> Option<&str> {
106    split_handle(handle).map(|(s, _, _)| s)
107}
108
109/// The kind within the sector, or `None`.
110pub fn kind_name_of(handle: &str) -> Option<&str> {
111    split_handle(handle).map(|(_, k, _)| k)
112}
113
114/// Is this handle in the given sector?
115pub fn is_sector(handle: &str, sector: &str) -> bool {
116    sector_of(handle) == Some(sector)
117}
118
119/// Is this handle's kind declared? An undeclared kind is a finding, not a `false`.
120pub fn is_declared(handle: &str) -> bool {
121    kind_of(handle).map(|k| k.declared).unwrap_or(false)
122}
123
124/// Every declared `sector:kind` pair, sorted — the drift check compares these to the hub.
125pub fn declared_kinds() -> Vec<String> {
126    let mut out: Vec<String> = KIND_SECTORS
127        .iter()
128        .flat_map(|(s, kinds)| kinds.iter().map(move |k| format!("{s}:{k}")))
129        .collect();
130    out.sort();
131    out
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn parses_the_declared_sectors() {
140        let k = kind_of("urn:mcard:pcard:sprint:orc-02").expect("a handle");
141        assert_eq!(k.sector, "pcard");
142        assert_eq!(k.kind, "sprint");
143        assert_eq!(k.subject.as_deref(), Some("orc-02"));
144        assert!(k.declared);
145    }
146
147    #[test]
148    fn a_subject_may_contain_colons() {
149        let k = kind_of("urn:mcard:node:did:key:z6Mk").expect("a handle");
150        assert_eq!(k.sector, "node");
151        assert_eq!(k.kind, "did");
152        assert_eq!(k.subject.as_deref(), Some("key:z6Mk"));
153    }
154
155    #[test]
156    fn an_undeclared_kind_is_a_finding_not_a_null() {
157        let k = kind_of("urn:mcard:bogus:thing").expect("well formed");
158        assert!(!k.declared, "an undeclared kind must report declared:false");
159    }
160
161    #[test]
162    fn a_non_handle_is_none() {
163        assert!(kind_of("not-a-handle").is_none());
164        assert!(kind_of("urn:mcard:Pcard:Sprint").is_none(), "the grammar is lowercase");
165        assert!(kind_of("urn:mcard:pcard").is_none(), "no kind");
166        assert!(kind_of("").is_none());
167    }
168
169    #[test]
170    fn declared_kinds_matches_the_other_bindings() {
171        // 34 pairs — the same count the TypeScript and Python bindings report.
172        // ORC-21 added doc (+2), and ORC-24 added the 9 archetypes (+9), reaching 34.
173        assert_eq!(declared_kinds().len(), 34);
174    }
175}