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:pcard:sprint:orc-02         -> sector "pcard",     kind "sprint"
15//! urn: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 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            // EPIC-LCLM: the Layer 0 function's knowledge locus (`function_mcard`).
48            "function",
49        ],
50    ),
51    ("doc", &["vault", "document"]),
52    ("pcard", &["program", "sprint", "fiber"]),
53    ("vcard", &["seal", "execution", "contract"]),
54    // Agent Identities (agent_identities.db)
55    ("agent", &["root", "actor"]),
56    ("node", &["did", "peer"]),
57    ("key", &["pub", "rotate"]),
58    // Execution History (execution_log.db)
59    ("execution", &["record", "trace", "migration"]),
60    ("telemetry", &["event"]),
61];
62
63/// The closed set of transition kinds (`INV-TAPE-04`). The KIND of a change is card content
64/// in the lifecycle sidecar, never a column.
65pub const CHANGE_CALCULUS: &[&str] = &[
66    "CREATE", "UPDATE", "SEAL", "RELOCATE", "ROTATE", "TOMBSTONE",
67];
68
69/// Split `urn:(?:mcard:<sector>|pcard|vcard):<kind>[:<subject>...]` into its parts.
70///
71/// Hand-rolled rather than a regex so the crate takes no new dependency; the grammar is
72/// small and the split is the whole of it.
73fn split_handle(handle: &str) -> Option<(&str, &str, Option<&str>)> {
74    let lower = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
75    if let Some(rest) = handle.strip_prefix("urn:pcard:") {
76        let (kind, subject) = match rest.split_once(':') {
77            Some((k, s)) => (k, Some(s)),
78            None => (rest, None),
79        };
80        if !lower(kind) {
81            return None;
82        }
83        return Some(("pcard", kind, subject));
84    }
85    if let Some(rest) = handle.strip_prefix("urn:vcard:") {
86        let (kind, subject) = match rest.split_once(':') {
87            Some((k, s)) => (k, Some(s)),
88            None => (rest, None),
89        };
90        if !lower(kind) {
91            return None;
92        }
93        return Some(("vcard", kind, subject));
94    }
95    // NAMESPACE-01: the window is CLOSED. The four tapes hold `urn:mcard:` and zero
96    // `urn:clm:` rows, so the old prefix fails — which is the point.
97    let rest = handle.strip_prefix("urn:mcard:")?;
98    let (sector, rest) = rest.split_once(':')?;
99    let (kind, subject) = match rest.split_once(':') {
100        Some((k, s)) => (k, Some(s)),
101        None => (rest, None),
102    };
103    if !lower(sector) || !lower(kind) {
104        return None;
105    }
106    Some((sector, kind, subject))
107}
108
109/// Decide the kind of a handle. Pure: no I/O, no state, no cache.
110pub fn kind_of(handle: &str) -> Option<HandleKind> {
111    let (sector, kind, subject) = split_handle(handle)?;
112    let declared = KIND_SECTORS
113        .iter()
114        .find(|(s, _)| *s == sector)
115        .map(|(_, kinds)| kinds.contains(&kind))
116        .unwrap_or(false);
117    Some(HandleKind {
118        sector: sector.to_string(),
119        kind: kind.to_string(),
120        handle: handle.to_string(),
121        declared,
122        subject: subject.map(str::to_string),
123    })
124}
125
126/// The sector of a handle, or `None`.
127pub fn sector_of(handle: &str) -> Option<&str> {
128    split_handle(handle).map(|(s, _, _)| s)
129}
130
131/// The kind within the sector, or `None`.
132pub fn kind_name_of(handle: &str) -> Option<&str> {
133    split_handle(handle).map(|(_, k, _)| k)
134}
135
136/// Is this handle in the given sector?
137pub fn is_sector(handle: &str, sector: &str) -> bool {
138    sector_of(handle) == Some(sector)
139}
140
141/// Is this handle's kind declared? An undeclared kind is a finding, not a `false`.
142pub fn is_declared(handle: &str) -> bool {
143    kind_of(handle).map(|k| k.declared).unwrap_or(false)
144}
145
146/// Every declared `sector:kind` pair, sorted — the drift check compares these to the hub.
147pub fn declared_kinds() -> Vec<String> {
148    let mut out: Vec<String> = KIND_SECTORS
149        .iter()
150        .flat_map(|(s, kinds)| kinds.iter().map(move |k| format!("{s}:{k}")))
151        .collect();
152    out.sort();
153    out
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn parses_the_declared_sectors() {
162        let k = kind_of("urn:pcard:sprint:orc-02").expect("a handle");
163        assert_eq!(k.sector, "pcard");
164        assert_eq!(k.kind, "sprint");
165        assert_eq!(k.subject.as_deref(), Some("orc-02"));
166        assert!(k.declared);
167
168        let v = kind_of("urn:vcard:seal:9f2c").expect("a handle");
169        assert_eq!(v.sector, "vcard");
170        assert_eq!(v.kind, "seal");
171        assert_eq!(v.subject.as_deref(), Some("9f2c"));
172        assert!(v.declared);
173    }
174
175    #[test]
176    fn a_subject_may_contain_colons() {
177        let k = kind_of("urn:mcard:node:did:key:z6Mk").expect("a handle");
178        assert_eq!(k.sector, "node");
179        assert_eq!(k.kind, "did");
180        assert_eq!(k.subject.as_deref(), Some("key:z6Mk"));
181    }
182
183    #[test]
184    fn an_undeclared_kind_is_a_finding_not_a_null() {
185        let k = kind_of("urn:mcard:bogus:thing").expect("well formed");
186        assert!(!k.declared, "an undeclared kind must report declared:false");
187    }
188
189    #[test]
190    fn a_non_handle_is_none() {
191        assert!(kind_of("not-a-handle").is_none());
192        assert!(kind_of("urn:mcard:Pcard:Sprint").is_none(), "the grammar is lowercase");
193        assert!(kind_of("urn:mcard:pcard").is_none(), "no kind");
194        assert!(kind_of("urn:pcard").is_none(), "no kind");
195        assert!(kind_of("urn:vcard").is_none(), "no kind");
196        assert!(kind_of("").is_none());
197    }
198
199    #[test]
200    fn declared_kinds_matches_the_other_bindings() {
201        // 36 pairs — the same count the TypeScript and Python bindings report.
202        // ORC-21 added doc (+2), ORC-24 added the 9 archetypes (+9), reaching 34,
203        // EPIC-LCLM added `function` (+1), reaching 35,
204        // and EPIC-CRD added `fiber` (+1), reaching 36.
205        assert_eq!(declared_kinds().len(), 36);
206    }
207}