Skip to main content

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