1mod cosmic;
9mod cosmic_ext;
10mod ids;
11mod local;
12mod logic;
13mod specialized;
14mod stdlib;
15mod suggest;
16
17pub use ids::{ALL_INVOKE_IDS, INVOKE_ID_COUNT};
18pub use local::{invoke_local, payload_from_args, sample_to_value};
19pub use suggest::did_you_mean;
20
21use crate::animation::presets::list_all_presets;
22use crate::animation::AnimationFamily;
23use crate::value::Value;
24
25pub fn is_known(path: &str) -> bool {
27 canonical_id(path).is_some()
28}
29
30pub fn canonical_id(path: &str) -> Option<&'static str> {
37 if path == "Statistics.ols" {
38 return Some("Statistics.linear_regression");
39 }
40 if path == "Econ.welfare" {
41 return Some("Econ.utilitarian_welfare");
42 }
43 if let Some(id) = lookup_static(path) {
44 return Some(id);
45 }
46 if animation_preset(path).is_some() {
47 return Some("Animation.evaluate_preset");
48 }
49 None
50}
51
52fn utf8_eq_ignore_case(a: &str, b: &str) -> bool {
55 a.to_lowercase() == b.to_lowercase()
56}
57
58pub fn family_of(path: &str) -> Option<&str> {
60 let dot = path.find('.')?;
61 Some(&path[..dot])
62}
63
64pub fn granted_covers(granted: &[&str], path: &str) -> bool {
66 if let Some(id) = canonical_id(path) {
67 if granted.iter().any(|g| *g == id || *g == path) {
68 return true;
69 }
70 if let Some(fam) = family_of(id) {
71 if granted.iter().any(|g| utf8_eq_ignore_case(g, fam)) {
72 return true;
73 }
74 }
75 if let Some(fam) = family_of(path) {
76 if granted.iter().any(|g| utf8_eq_ignore_case(g, fam)) {
77 return true;
78 }
79 }
80 return false;
81 }
82 if looks_like_catalog_path(path) {
83 return false;
84 }
85 true
86}
87
88pub fn looks_like_catalog_path(path: &str) -> bool {
91 if animation_preset(path).is_some() {
92 return true;
93 }
94 let Some(fam) = family_of(path) else {
95 return false;
96 };
97 let prefix = format!("{fam}.");
98 ALL_INVOKE_IDS.iter().any(|id| id.starts_with(&prefix))
99}
100
101pub fn animation_preset(path: &str) -> Option<(&'static str, &'static str)> {
103 let name = path.strip_prefix("Animation.")?;
104 for info in list_all_presets() {
105 if info.preset == name {
106 return Some((info.family, info.preset));
107 }
108 }
109 None
110}
111
112pub fn apply_preset_alias(path: &str, payload: &mut Value) {
116 let Some((family, preset)) = animation_preset(path) else {
117 return;
118 };
119 let Value::Record(map) = payload else {
120 return;
121 };
122 map.entry("family".into())
123 .or_insert_with(|| Value::String(family.into()));
124 map.entry("preset".into())
125 .or_insert_with(|| Value::String(preset.into()));
126}
127
128pub fn parse_family_from_preset(family: &str) -> Option<AnimationFamily> {
130 AnimationFamily::from_name(family)
131}
132
133fn lookup_static(path: &str) -> Option<&'static str> {
134 ALL_INVOKE_IDS.iter().copied().find(|id| *id == path)
135}
136
137pub fn family_grant(family: &str) -> String {
139 family.to_string()
140}
141
142pub fn methods_for_family(family: &str) -> Vec<&'static str> {
144 let prefix = format!("{family}.");
145 ALL_INVOKE_IDS
146 .iter()
147 .copied()
148 .filter(|id| id.starts_with(&prefix))
149 .collect()
150}
151
152pub fn families() -> Vec<&'static str> {
154 let mut out = Vec::new();
155 for id in ALL_INVOKE_IDS {
156 if let Some(fam) = family_of(id) {
157 if !out.contains(&fam) {
158 out.push(fam);
159 }
160 }
161 }
162 out
163}
164
165pub fn describe(path: &str) -> String {
167 if let Some((family, preset)) = animation_preset(path) {
168 return format!(
169 "Animation preset `{preset}` (family {family}) → `Animation.evaluate_preset`"
170 );
171 }
172 if let Some(id) = canonical_id(path) {
173 if id == "GraphAuthoring.process" || id == "N3Logic.evaluate" {
174 return format!(
175 "catalog `{id}` — graph host invoke (fail-closed; lease with `using {}`). Natural persons are rdfs:Class + SHACL/ShEx; owl:Thing is forbidden for persons.",
176 family_of(id).unwrap_or("graph")
177 );
178 }
179 if let Some(fam) = family_of(id) {
180 return format!(
181 "catalog `{id}` — {fam} host invoke (fail-closed; lease with `using {fam};`)"
182 );
183 }
184 return format!("catalog `{id}` — host invoke (fail-closed)");
185 }
186 if looks_like_catalog_path(path) {
187 return match did_you_mean(path) {
188 Some(hint) => format!("unknown catalog path `{path}`; did you mean `{hint}`?"),
189 None => format!("unknown catalog path `{path}`"),
190 };
191 }
192 format!("ident `{path}`")
193}
194
195pub(crate) mod envelope_admission {
202 use crate::error::{DiagCode, Diagnostic};
203 use crate::span::Span;
204 use crate::value::Value;
205
206 pub(crate) const HEADER_BYTES: usize = 128;
207 pub(crate) const DIRECTORY_BYTES: usize = 128;
208 pub(crate) const INDEX_DOMAIN: &[u8] = b"QUALIA-FIELD-INDEX-v1\0";
209 pub(crate) const MAX_ENTRIES: usize = 4096;
210 pub(crate) const MAX_METADATA_BYTES: usize = 4 << 20;
211 pub(crate) const MAX_CONTAINER_BYTES: usize = 64 << 20;
212
213 const FORBIDDEN_SOURCE_KEYS: &[&str] = &[
214 "filename",
215 "file",
216 "file_name",
217 "path",
218 "filepath",
219 "file_path",
220 "hmc",
221 "hmc_path",
222 "bundle",
223 "bundle_path",
224 "zip",
225 "url",
226 "uri",
227 ];
228
229 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
230 pub(crate) enum EnvelopeFamily {
231 EmfV4,
232 QacV1,
233 }
234
235 impl EnvelopeFamily {
236 pub(crate) const fn magic(self) -> &'static [u8; 8] {
237 match self {
238 Self::EmfV4 => b"Q42EMF64",
239 Self::QacV1 => b"qac\0\0\0\0\0",
240 }
241 }
242
243 pub(crate) const fn version(self) -> u16 {
244 match self {
245 Self::EmfV4 => 4,
246 Self::QacV1 => 1,
247 }
248 }
249
250 pub(crate) const fn label(self) -> &'static str {
251 match self {
252 Self::EmfV4 => "Q42EMF64",
253 Self::QacV1 => "qac\\0\\0\\0\\0\\0",
254 }
255 }
256
257 pub(crate) const fn mode_allowed(self, mode: u16) -> bool {
258 match self {
259 Self::EmfV4 => matches!(mode, 0x0100..=0x0107 | 0 | 1 | 3),
260 Self::QacV1 => matches!(mode, 0x0100..=0x0105),
261 }
262 }
263 }
264
265 #[derive(Clone, Copy, Debug)]
266 pub(crate) struct AdmittedEntry<'a> {
267 pub(crate) mode: u16,
268 pub(crate) revision: u16,
269 pub(crate) flags: u32,
270 pub(crate) stream_id: u32,
271 pub(crate) frame_id: u32,
272 pub(crate) start_tick: i64,
273 pub(crate) time_count: u64,
274 pub(crate) spatial_key: u64,
275 pub(crate) payload_offset: u64,
276 pub(crate) stored_bytes: u64,
277 pub(crate) decoded_bytes: u64,
278 pub(crate) record_count: u64,
279 pub(crate) stride: u32,
280 pub(crate) descriptor_id: u32,
281 pub(crate) digest: &'a [u8],
282 pub(crate) payload: &'a [u8],
283 }
284
285 #[derive(Debug)]
286 pub(crate) struct AdmittedEnvelope<'a> {
287 pub(crate) family: EnvelopeFamily,
288 pub(crate) version: u16,
289 pub(crate) flags: u32,
290 pub(crate) total_bytes: u64,
291 pub(crate) metadata: &'a [u8],
292 pub(crate) index_digest: &'a [u8],
293 pub(crate) entries: Vec<AdmittedEntry<'a>>,
294 }
295
296 #[derive(Clone, Copy, Debug)]
297 pub(crate) struct BuildEntry<'a> {
298 pub(crate) mode: u16,
299 pub(crate) revision: u16,
300 pub(crate) flags: u32,
301 pub(crate) stream_id: u32,
302 pub(crate) frame_id: u32,
303 pub(crate) start_tick: i64,
304 pub(crate) time_count: u64,
305 pub(crate) spatial_key: u64,
306 pub(crate) record_count: u64,
307 pub(crate) stride: u32,
308 pub(crate) descriptor_id: u32,
309 pub(crate) payload: &'a [u8],
310 }
311
312 #[inline]
313 fn u16le(b: &[u8], o: usize) -> u16 {
314 u16::from_le_bytes([b[o], b[o + 1]])
315 }
316
317 #[inline]
318 fn u32le(b: &[u8], o: usize) -> u32 {
319 u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
320 }
321
322 #[inline]
323 fn u64le(b: &[u8], o: usize) -> u64 {
324 u64::from_le_bytes([
325 b[o],
326 b[o + 1],
327 b[o + 2],
328 b[o + 3],
329 b[o + 4],
330 b[o + 5],
331 b[o + 6],
332 b[o + 7],
333 ])
334 }
335
336 #[inline]
337 fn put16(b: &mut [u8], o: usize, v: u16) {
338 b[o..o + 2].copy_from_slice(&v.to_le_bytes());
339 }
340
341 #[inline]
342 fn put32(b: &mut [u8], o: usize, v: u32) {
343 b[o..o + 4].copy_from_slice(&v.to_le_bytes());
344 }
345
346 #[inline]
347 fn put64(b: &mut [u8], o: usize, v: u64) {
348 b[o..o + 8].copy_from_slice(&v.to_le_bytes());
349 }
350
351 pub(crate) fn crc32c(data: &[u8]) -> u32 {
353 let mut crc = 0xFFFF_FFFFu32;
354 for &byte in data {
355 crc ^= u32::from(byte);
356 for _ in 0..8 {
357 crc = (crc >> 1) ^ (0x82F6_3B78 & 0u32.wrapping_sub(crc & 1));
358 }
359 }
360 !crc
361 }
362
363 fn block_crc32c(block: &[u8]) -> u32 {
364 let mut copy = [0u8; 128];
365 copy.copy_from_slice(&block[..128]);
366 copy[124..128].fill(0);
367 crc32c(©)
368 }
369
370 const BLAKE3_IV: [u32; 8] = [
372 0x6A09_E667,
373 0xBB67_AE85,
374 0x3C6E_F372,
375 0xA54F_F53A,
376 0x510E_527F,
377 0x9B05_688C,
378 0x1F83_D9AB,
379 0x5BE0_CD19,
380 ];
381 const MSG_PERMUTATION: [usize; 16] = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];
382 const FLAG_CHUNK_START: u32 = 1 << 0;
383 const FLAG_CHUNK_END: u32 = 1 << 1;
384 const FLAG_PARENT: u32 = 1 << 2;
385 const FLAG_ROOT: u32 = 1 << 3;
386 const BLAKE3_BLOCK_LEN: usize = 64;
387 const BLAKE3_CHUNK_LEN: usize = 1024;
388
389 #[inline]
390 fn blake3_g(s: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize, mx: u32, my: u32) {
391 s[a] = s[a].wrapping_add(s[b]).wrapping_add(mx);
392 s[d] = (s[d] ^ s[a]).rotate_right(16);
393 s[c] = s[c].wrapping_add(s[d]);
394 s[b] = (s[b] ^ s[c]).rotate_right(12);
395 s[a] = s[a].wrapping_add(s[b]).wrapping_add(my);
396 s[d] = (s[d] ^ s[a]).rotate_right(8);
397 s[c] = s[c].wrapping_add(s[d]);
398 s[b] = (s[b] ^ s[c]).rotate_right(7);
399 }
400
401 fn blake3_round(s: &mut [u32; 16], m: &[u32; 16]) {
402 blake3_g(s, 0, 4, 8, 12, m[0], m[1]);
403 blake3_g(s, 1, 5, 9, 13, m[2], m[3]);
404 blake3_g(s, 2, 6, 10, 14, m[4], m[5]);
405 blake3_g(s, 3, 7, 11, 15, m[6], m[7]);
406 blake3_g(s, 0, 5, 10, 15, m[8], m[9]);
407 blake3_g(s, 1, 6, 11, 12, m[10], m[11]);
408 blake3_g(s, 2, 7, 8, 13, m[12], m[13]);
409 blake3_g(s, 3, 4, 9, 14, m[14], m[15]);
410 }
411
412 fn blake3_compress(
413 cv: &[u32; 8],
414 block_words: &[u32; 16],
415 counter: u64,
416 block_len: u32,
417 flags: u32,
418 ) -> [u32; 16] {
419 let mut s = [
420 cv[0],
421 cv[1],
422 cv[2],
423 cv[3],
424 cv[4],
425 cv[5],
426 cv[6],
427 cv[7],
428 BLAKE3_IV[0],
429 BLAKE3_IV[1],
430 BLAKE3_IV[2],
431 BLAKE3_IV[3],
432 counter as u32,
433 (counter >> 32) as u32,
434 block_len,
435 flags,
436 ];
437 let mut m = *block_words;
438 for round in 0..7 {
439 blake3_round(&mut s, &m);
440 if round < 6 {
441 let mut next = [0u32; 16];
442 for i in 0..16 {
443 next[i] = m[MSG_PERMUTATION[i]];
444 }
445 m = next;
446 }
447 }
448 for i in 0..8 {
449 s[i] ^= s[i + 8];
450 s[i + 8] ^= cv[i];
451 }
452 s
453 }
454
455 fn words_from_block(block: &[u8; BLAKE3_BLOCK_LEN]) -> [u32; 16] {
456 let mut words = [0u32; 16];
457 for (i, w) in words.iter_mut().enumerate() {
458 let o = i * 4;
459 *w = u32::from_le_bytes([block[o], block[o + 1], block[o + 2], block[o + 3]]);
460 }
461 words
462 }
463
464 #[derive(Clone, Copy)]
465 struct Blake3Output {
466 input_cv: [u32; 8],
467 block_words: [u32; 16],
468 counter: u64,
469 block_len: u32,
470 flags: u32,
471 }
472
473 impl Blake3Output {
474 fn chaining_value(&self) -> [u32; 8] {
475 let out = blake3_compress(
476 &self.input_cv,
477 &self.block_words,
478 self.counter,
479 self.block_len,
480 self.flags,
481 );
482 let mut cv = [0u32; 8];
483 cv.copy_from_slice(&out[..8]);
484 cv
485 }
486
487 fn root_bytes(&self) -> [u8; 32] {
488 let out = blake3_compress(
489 &self.input_cv,
490 &self.block_words,
491 0,
492 self.block_len,
493 self.flags | FLAG_ROOT,
494 );
495 let mut bytes = [0u8; 32];
496 for (i, &w) in out[..8].iter().enumerate() {
497 bytes[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes());
498 }
499 bytes
500 }
501 }
502
503 struct Blake3ChunkState {
504 cv: [u32; 8],
505 chunk_counter: u64,
506 block: [u8; BLAKE3_BLOCK_LEN],
507 block_len: u8,
508 blocks_compressed: u8,
509 }
510
511 impl Blake3ChunkState {
512 fn new(chunk_counter: u64) -> Self {
513 Self {
514 cv: BLAKE3_IV,
515 chunk_counter,
516 block: [0u8; BLAKE3_BLOCK_LEN],
517 block_len: 0,
518 blocks_compressed: 0,
519 }
520 }
521
522 fn len(&self) -> usize {
523 BLAKE3_BLOCK_LEN * usize::from(self.blocks_compressed) + usize::from(self.block_len)
524 }
525
526 fn start_flag(&self) -> u32 {
527 if self.blocks_compressed == 0 {
528 FLAG_CHUNK_START
529 } else {
530 0
531 }
532 }
533
534 fn update(&mut self, mut input: &[u8]) {
535 while !input.is_empty() {
536 if usize::from(self.block_len) == BLAKE3_BLOCK_LEN {
537 let words = words_from_block(&self.block);
538 let flags = self.start_flag();
539 let out = blake3_compress(
540 &self.cv,
541 &words,
542 self.chunk_counter,
543 BLAKE3_BLOCK_LEN as u32,
544 flags,
545 );
546 self.cv.copy_from_slice(&out[..8]);
547 self.blocks_compressed += 1;
548 self.block = [0u8; BLAKE3_BLOCK_LEN];
549 self.block_len = 0;
550 }
551 let want = BLAKE3_BLOCK_LEN - usize::from(self.block_len);
552 let take = want.min(input.len());
553 self.block[usize::from(self.block_len)..usize::from(self.block_len) + take]
554 .copy_from_slice(&input[..take]);
555 self.block_len += take as u8;
556 input = &input[take..];
557 }
558 }
559
560 fn output(&self) -> Blake3Output {
561 Blake3Output {
562 input_cv: self.cv,
563 block_words: words_from_block(&self.block),
564 counter: self.chunk_counter,
565 block_len: u32::from(self.block_len),
566 flags: self.start_flag() | FLAG_CHUNK_END,
567 }
568 }
569 }
570
571 fn parent_output(left: [u32; 8], right: [u32; 8]) -> Blake3Output {
572 let mut block_words = [0u32; 16];
573 block_words[..8].copy_from_slice(&left);
574 block_words[8..].copy_from_slice(&right);
575 Blake3Output {
576 input_cv: BLAKE3_IV,
577 block_words,
578 counter: 0,
579 block_len: BLAKE3_BLOCK_LEN as u32,
580 flags: FLAG_PARENT,
581 }
582 }
583
584 pub(crate) struct Blake3Hasher {
585 chunk_state: Blake3ChunkState,
586 cv_stack: Vec<[u32; 8]>,
587 }
588
589 impl Blake3Hasher {
590 pub(crate) fn new() -> Self {
591 Self {
592 chunk_state: Blake3ChunkState::new(0),
593 cv_stack: Vec::new(),
594 }
595 }
596
597 fn add_chunk_cv(&mut self, mut new_cv: [u32; 8], mut total_chunks: u64) {
598 while total_chunks & 1 == 0 {
599 let left = self.cv_stack.pop().expect("cv_stack non-empty");
600 new_cv = parent_output(left, new_cv).chaining_value();
601 total_chunks >>= 1;
602 }
603 self.cv_stack.push(new_cv);
604 }
605
606 pub(crate) fn update(&mut self, mut input: &[u8]) {
607 while !input.is_empty() {
608 if self.chunk_state.len() == BLAKE3_CHUNK_LEN {
609 let chunk_cv = self.chunk_state.output().chaining_value();
610 let total_chunks = self.chunk_state.chunk_counter + 1;
611 self.add_chunk_cv(chunk_cv, total_chunks);
612 self.chunk_state = Blake3ChunkState::new(total_chunks);
613 }
614 let want = BLAKE3_CHUNK_LEN - self.chunk_state.len();
615 let take = want.min(input.len());
616 self.chunk_state.update(&input[..take]);
617 input = &input[take..];
618 }
619 }
620
621 pub(crate) fn finalize(&self) -> [u8; 32] {
622 let mut output = self.chunk_state.output();
623 let mut idx = self.cv_stack.len();
624 while idx > 0 {
625 idx -= 1;
626 output = parent_output(self.cv_stack[idx], output.chaining_value());
627 }
628 output.root_bytes()
629 }
630 }
631
632 pub(crate) fn blake3_hash(input: &[u8]) -> [u8; 32] {
633 let mut h = Blake3Hasher::new();
634 h.update(input);
635 h.finalize()
636 }
637
638 fn compute_index_digest(header_128: &[u8], directory: &[u8], metadata: &[u8]) -> [u8; 32] {
639 let mut root_header = [0u8; HEADER_BYTES];
640 root_header.copy_from_slice(&header_128[..HEADER_BYTES]);
641 root_header[56..88].fill(0);
642 root_header[124..128].fill(0);
643 let mut h = Blake3Hasher::new();
644 h.update(INDEX_DOMAIN);
645 h.update(&root_header);
646 h.update(directory);
647 h.update(metadata);
648 h.finalize()
649 }
650
651 fn align_up(n: u64, a: u64) -> Result<u64, String> {
652 n.checked_add(a - 1)
653 .map(|v| v & !(a - 1))
654 .ok_or_else(|| "integer overflow during envelope alignment".to_string())
655 }
656
657 fn validate_padding_zero(bytes: &[u8], start: u64, len: u64) -> Result<(), String> {
658 let s = usize::try_from(start).map_err(|_| "padding start overflow".to_string())?;
659 let l = usize::try_from(len).map_err(|_| "padding len overflow".to_string())?;
660 let slice = bytes
661 .get(s..s.saturating_add(l))
662 .ok_or_else(|| "container truncated inside alignment padding".to_string())?;
663 if slice.iter().any(|&b| b != 0) {
664 return Err("non-zero bytes inside container alignment padding".to_string());
665 }
666 Ok(())
667 }
668
669 fn tlv_item(bytes: &[u8]) -> Result<(&[u8], &[u8], &[u8]), String> {
670 let h = bytes
671 .get(..16)
672 .ok_or_else(|| "truncated metadata TLV item header".to_string())?;
673 let n = usize::try_from(u32le(h, 8)).map_err(|_| "metadata TLV length".to_string())?;
674 let padded = (n + 7) & !7;
675 let val = bytes
676 .get(16..16 + n)
677 .ok_or_else(|| "truncated metadata TLV item payload".to_string())?;
678 let pad = bytes
679 .get(16 + n..16 + padded)
680 .ok_or_else(|| "truncated metadata TLV item padding".to_string())?;
681 if pad.iter().any(|&b| b != 0) {
682 return Err("non-zero padding inside metadata TLV".to_string());
683 }
684 Ok((h, val, &bytes[16 + padded..]))
685 }
686
687 pub(crate) fn validate_metadata_tlv(mut bytes: &[u8]) -> Result<(), String> {
688 if bytes.len() > MAX_METADATA_BYTES {
689 return Err("metadata exceeds MAX_METADATA_BYTES".to_string());
690 }
691 let mut prev_block_id = 0u32;
692 while !bytes.is_empty() {
693 let (bh, mut body, tail) = tlv_item(bytes)?;
694 bytes = tail;
695 let block_id = u32le(bh, 0);
696 if block_id <= prev_block_id || (u32le(bh, 12) & !1) != 0 {
697 return Err("invalid or unordered metadata block".to_string());
698 }
699 prev_block_id = block_id;
700 let mut prev_key = 0u16;
701 while !body.is_empty() {
702 let (fh, _val, ftail) = tlv_item(body)?;
703 body = ftail;
704 let key = u16le(fh, 0);
705 if key <= prev_key || (fh[3] & !1) != 0 || u32le(fh, 12) != 0 {
706 return Err("invalid or unordered metadata field".to_string());
707 }
708 prev_key = key;
709 }
710 }
711 Ok(())
712 }
713
714 pub(crate) fn reject_forbidden_bytes_signature(bytes: &[u8]) -> Result<(), String> {
715 if bytes.len() >= 4 && (&bytes[..4] == b"PK\x03\x04" || &bytes[..4] == b"PK\x05\x06") {
716 return Err("ZIP/HMC container streaming is forbidden inside Vibe catalog".to_string());
717 }
718 if bytes.len() >= 3 && &bytes[..3] == b"HMC" {
719 return Err(".hmc sniffing is forbidden inside Vibe catalog".to_string());
720 }
721 if bytes.len() >= 4 && &bytes[..4] == b"QBDL" {
722 return Err("QBDL stream headers must be admitted by QDNF, not Vibe catalog".to_string());
723 }
724 let trimmed = bytes.iter().copied().find(|b| !b.is_ascii_whitespace());
725 if matches!(trimmed, Some(b'{') | Some(b'[')) {
726 return Err("JSON is forbidden as native binary container body".to_string());
727 }
728 Ok(())
729 }
730
731 pub(crate) fn reject_forbidden_source_keys(
732 args: &Value,
733 span: Span,
734 ) -> Result<(), Diagnostic> {
735 let Value::Record(rec) = args else {
736 return Err(Diagnostic::new(
737 DiagCode::E100,
738 span,
739 "catalog invocation requires a Record argument with already-admitted binary bytes",
740 ));
741 };
742 for key in FORBIDDEN_SOURCE_KEYS {
743 if rec.contains_key(*key) {
744 return Err(Diagnostic::new(
745 DiagCode::E300,
746 span,
747 format!(
748 "forbidden source/path key `{key}`: Vibe catalog operates only on already-admitted binary containers by identity/bytes, never filenames or .hmc sniffing"
749 ),
750 ));
751 }
752 }
753 Ok(())
754 }
755
756 pub(crate) fn decode_byte_list(val: &Value, field: &str, span: Span) -> Result<Vec<u8>, Diagnostic> {
757 match val {
758 Value::List(items) => {
759 if items.is_empty() {
760 return Err(Diagnostic::new(
761 DiagCode::E100,
762 span,
763 format!("binary `{field}` must not be empty"),
764 ));
765 }
766 let mut out = Vec::with_capacity(items.len());
767 for item in items {
768 match item {
769 Value::U64(n) if *n <= 255 => out.push(*n as u8),
770 Value::I64(n) if (0..=255).contains(n) => out.push(*n as u8),
771 _ => {
772 return Err(Diagnostic::new(
773 DiagCode::E100,
774 span,
775 format!("binary `{field}` elements must be u8 integers 0..=255"),
776 ))
777 }
778 }
779 }
780 if let Err(reason) = reject_forbidden_bytes_signature(&out) {
781 return Err(Diagnostic::new(DiagCode::E300, span, reason));
782 }
783 Ok(out)
784 }
785 Value::String(_) => Err(Diagnostic::new(
786 DiagCode::E100,
787 span,
788 format!(
789 "`{field}` must be binary bytes (List<u8>), never JSON or string path"
790 ),
791 )),
792 _ => Err(Diagnostic::new(
793 DiagCode::E100,
794 span,
795 format!("`{field}` must be binary bytes (List<u8>)"),
796 )),
797 }
798 }
799
800 pub(crate) fn extract_binary_bytes(
801 args: &Value,
802 keys: &[&str],
803 span: Span,
804 ) -> Result<Vec<u8>, Diagnostic> {
805 reject_forbidden_source_keys(args, span)?;
806 let Value::Record(rec) = args else {
807 unreachable!();
808 };
809 for key in keys {
810 if let Some(val) = rec.get(*key) {
811 return decode_byte_list(val, key, span);
812 }
813 }
814 Err(Diagnostic::new(
815 DiagCode::E100,
816 span,
817 format!("missing binary payload field (expected one of: {})", keys.join(", ")),
818 ))
819 }
820
821 pub(crate) fn bytes_to_vibe_list(bytes: &[u8]) -> Value {
822 Value::List(bytes.iter().map(|&b| Value::U64(u64::from(b))).collect())
823 }
824
825 pub(crate) fn admit_envelope<'a>(
826 bytes: &'a [u8],
827 expected_family: EnvelopeFamily,
828 ) -> Result<AdmittedEnvelope<'a>, String> {
829 reject_forbidden_bytes_signature(bytes)?;
830 if bytes.len() < HEADER_BYTES {
831 return Err("container shorter than 128-byte header".to_string());
832 }
833 if bytes.len() > MAX_CONTAINER_BYTES {
834 return Err("container exceeds MAX_CONTAINER_BYTES".to_string());
835 }
836 let h = &bytes[..HEADER_BYTES];
837 if &h[..8] != expected_family.magic() {
838 return Err(format!(
839 "container family magic mismatch (expected {})",
840 expected_family.label()
841 ));
842 }
843 let version = u16le(h, 8);
844 if version != expected_family.version() {
845 return Err(format!(
846 "unsupported {} version {version} (expected {})",
847 expected_family.label(),
848 expected_family.version()
849 ));
850 }
851 let stored_hdr_crc = u32le(h, 124);
852 let got_hdr_crc = block_crc32c(h);
853 if stored_hdr_crc != got_hdr_crc {
854 return Err(format!(
855 "header CRC-32C mismatch: stored {stored_hdr_crc:#010x}, computed {got_hdr_crc:#010x}"
856 ));
857 }
858 let flags = u32le(h, 12);
859 let total_bytes = u64le(h, 16);
860 let dir_offset = u64le(h, 24);
861 let entry_count = u32le(h, 32);
862 let entry_bytes = u16le(h, 36);
863 let index_ver = u16le(h, 38);
864 if u16le(h, 10) != HEADER_BYTES as u16
865 || (flags & !1) != 0
866 || total_bytes != bytes.len() as u64
867 || dir_offset != HEADER_BYTES as u64
868 || entry_bytes != DIRECTORY_BYTES as u16
869 || index_ver != 1
870 || h[88..124].iter().any(|&b| b != 0)
871 {
872 return Err("invalid envelope header fields or non-zero reserved bytes".to_string());
873 }
874 if entry_count == 0 || entry_count as usize > MAX_ENTRIES {
875 return Err(format!(
876 "container entry_count must be in 1..={MAX_ENTRIES}, got {entry_count}"
877 ));
878 }
879 let dir_len = u64::from(entry_count)
880 .checked_mul(DIRECTORY_BYTES as u64)
881 .ok_or_else(|| "directory byte length overflow".to_string())?;
882 let meta_start = (HEADER_BYTES as u64)
883 .checked_add(dir_len)
884 .ok_or_else(|| "metadata offset overflow".to_string())?;
885 let meta_len = u64le(h, 48);
886 if u64le(h, 40) != meta_start || meta_len > MAX_METADATA_BYTES as u64 {
887 return Err("invalid metadata offset or metadata limit exceeded".to_string());
888 }
889 let dir_end = usize::try_from(meta_start).map_err(|_| "dir_end overflow".to_string())?;
890 let directory = bytes
891 .get(HEADER_BYTES..dir_end)
892 .ok_or_else(|| "truncated envelope directory".to_string())?;
893 let meta_end_u64 = meta_start
894 .checked_add(meta_len)
895 .ok_or_else(|| "metadata end overflow".to_string())?;
896 let meta_end =
897 usize::try_from(meta_end_u64).map_err(|_| "metadata end overflow".to_string())?;
898 let metadata = bytes
899 .get(dir_end..meta_end)
900 .ok_or_else(|| "truncated envelope metadata".to_string())?;
901 validate_metadata_tlv(metadata)?;
902
903 let alignment = if (flags & 1) != 0 { 4096u64 } else { 64u64 };
904 let mut next = align_up(meta_end_u64, alignment)?;
905 validate_padding_zero(bytes, meta_end_u64, next - meta_end_u64)?;
906
907 let expected_index = compute_index_digest(h, directory, metadata);
908 if expected_index != h[56..88] {
909 return Err("envelope BLAKE3 index commitment mismatch".to_string());
910 }
911
912 let mut prior_key: Option<(u32, i64, u64, u16, u32)> = None;
913 let mut entries = Vec::with_capacity(entry_count as usize);
914 for (idx, row) in directory.chunks_exact(DIRECTORY_BYTES).enumerate() {
915 let stored_row_crc = u32le(row, 124);
916 let got_row_crc = block_crc32c(row);
917 if stored_row_crc != got_row_crc {
918 return Err(format!("directory row {idx} CRC-32C mismatch"));
919 }
920 if row[78..80].iter().any(|&b| b != 0) || row[116..124].iter().any(|&b| b != 0) {
921 return Err(format!("directory row {idx} has non-zero reserved bytes"));
922 }
923 let mode = u16le(row, 0);
924 if !expected_family.mode_allowed(mode) {
925 return Err(format!(
926 "unsupported mode {mode:#06x} in {} container (row {idx})",
927 expected_family.label()
928 ));
929 }
930 let revision = u16le(row, 2);
931 if revision == 0 {
932 return Err(format!("directory row {idx} has zero revision"));
933 }
934 let e_flags = u32le(row, 4);
935 let stream_id = u32le(row, 8);
936 let frame_id = u32le(row, 12);
937 let start_tick = u64le(row, 16) as i64;
938 let time_count = u64le(row, 24);
939 let spatial_key = u64le(row, 32);
940 let payload_offset = u64le(row, 40);
941 let stored_bytes = u64le(row, 48);
942 let decoded_bytes = u64le(row, 56);
943 let record_count = u64le(row, 64);
944 let stride = u32le(row, 72);
945 let codec = u16le(row, 76);
946 let descriptor_id = u32le(row, 112);
947
948 if codec != 0 {
949 return Err(format!("unsupported compression codec {codec} at row {idx}"));
950 }
951 if (e_flags & !7) != 0 || descriptor_id == 0 || stride == 0 || record_count == 0 {
952 return Err(format!("invalid directory invariants at row {idx}"));
953 }
954 if (e_flags & 2 == 0 && (start_tick != 0 || time_count != 0))
955 || (e_flags & 2 != 0 && (time_count == 0 || stream_id == 0))
956 || (e_flags & 4 == 0 && spatial_key != 0)
957 || (e_flags & 4 != 0 && frame_id == 0)
958 {
959 return Err(format!("inconsistent time/spatial flags at directory row {idx}"));
960 }
961 let key = (stream_id, start_tick, spatial_key, mode, descriptor_id);
962 if prior_key.is_some_and(|p| p >= key) {
963 return Err(format!("non-ascending directory order at row {idx}"));
964 }
965 prior_key = Some(key);
966
967 let expected_size = record_count
968 .checked_mul(u64::from(stride))
969 .ok_or_else(|| format!("size overflow at row {idx}"))?;
970 if expected_size != stored_bytes
971 || expected_size != decoded_bytes
972 || payload_offset != next
973 {
974 return Err(format!("extent/offset mismatch at directory row {idx}"));
975 }
976 let p_start = usize::try_from(payload_offset)
977 .map_err(|_| "payload_offset overflow".to_string())?;
978 let p_len =
979 usize::try_from(stored_bytes).map_err(|_| "stored_bytes overflow".to_string())?;
980 let payload = bytes
981 .get(p_start..p_start.saturating_add(p_len))
982 .ok_or_else(|| format!("truncated payload at row {idx}"))?;
983 let actual_digest = blake3_hash(payload);
984 if actual_digest != row[80..112] {
985 return Err(format!("payload BLAKE3 digest mismatch at row {idx}"));
986 }
987 let end = next
988 .checked_add(stored_bytes)
989 .ok_or_else(|| "payload end overflow".to_string())?;
990 next = align_up(end, alignment)?;
991 validate_padding_zero(bytes, end, next - end)?;
992
993 entries.push(AdmittedEntry {
994 mode,
995 revision,
996 flags: e_flags,
997 stream_id,
998 frame_id,
999 start_tick,
1000 time_count,
1001 spatial_key,
1002 payload_offset,
1003 stored_bytes,
1004 decoded_bytes,
1005 record_count,
1006 stride,
1007 descriptor_id,
1008 digest: &row[80..112],
1009 payload,
1010 });
1011 }
1012 if next != bytes.len() as u64 {
1013 return Err("trailing bytes after final aligned container payload".to_string());
1014 }
1015
1016 Ok(AdmittedEnvelope {
1017 family: expected_family,
1018 version,
1019 flags,
1020 total_bytes,
1021 metadata,
1022 index_digest: &h[56..88],
1023 entries,
1024 })
1025 }
1026
1027 pub(crate) fn select_admitted_entry<'a, 'b>(
1028 env: &'b AdmittedEnvelope<'a>,
1029 args: &Value,
1030 span: Span,
1031 ) -> Result<(usize, &'b AdmittedEntry<'a>), Diagnostic> {
1032 let Value::Record(rec) = args else {
1033 return Err(Diagnostic::new(DiagCode::E100, span, "expected Record args"));
1034 };
1035 let by_idx = match rec.get("entry_index").or_else(|| rec.get("slice_index")) {
1036 None => None,
1037 Some(Value::U64(u)) => Some(
1038 usize::try_from(*u)
1039 .map_err(|_| Diagnostic::new(DiagCode::E100, span, "entry_index overflow"))?,
1040 ),
1041 Some(Value::I64(i)) if *i >= 0 => Some(*i as usize),
1042 _ => {
1043 return Err(Diagnostic::new(
1044 DiagCode::E100,
1045 span,
1046 "entry_index must be a non-negative integer",
1047 ))
1048 }
1049 };
1050 let by_id = match rec.get("entry_id") {
1051 None => None,
1052 Some(Value::U64(u)) if *u > 0 && *u <= u64::from(u32::MAX) => Some(*u as u32),
1053 Some(Value::I64(i)) if *i > 0 && *i <= i64::from(u32::MAX) => Some(*i as u32),
1054 Some(Value::String(s)) => {
1055 let parsed = s.trim().parse::<u32>().ok().filter(|&id| id > 0);
1056 Some(parsed.ok_or_else(|| {
1057 Diagnostic::new(
1058 DiagCode::E300,
1059 span,
1060 "entry_id must be a positive numeric entry descriptor_id, never a filename",
1061 )
1062 })?)
1063 }
1064 _ => {
1065 return Err(Diagnostic::new(
1066 DiagCode::E100,
1067 span,
1068 "entry_id must be a positive descriptor_id",
1069 ))
1070 }
1071 };
1072
1073 let resolved_idx = match (by_idx, by_id) {
1074 (Some(idx), Some(id)) => {
1075 let entry = env.entries.get(idx).ok_or_else(|| {
1076 Diagnostic::new(
1077 DiagCode::E100,
1078 span,
1079 format!("entry_index {idx} out of bounds (count={})", env.entries.len()),
1080 )
1081 })?;
1082 if entry.descriptor_id != id {
1083 return Err(Diagnostic::new(
1084 DiagCode::E300,
1085 span,
1086 format!(
1087 "entry_index {idx} descriptor_id {} conflicts with requested entry_id {id}",
1088 entry.descriptor_id
1089 ),
1090 ));
1091 }
1092 idx
1093 }
1094 (Some(idx), None) => {
1095 if idx >= env.entries.len() {
1096 return Err(Diagnostic::new(
1097 DiagCode::E100,
1098 span,
1099 format!("entry_index {idx} out of bounds (count={})", env.entries.len()),
1100 ));
1101 }
1102 idx
1103 }
1104 (None, Some(id)) => env
1105 .entries
1106 .iter()
1107 .position(|e| e.descriptor_id == id)
1108 .ok_or_else(|| {
1109 Diagnostic::new(
1110 DiagCode::E300,
1111 span,
1112 format!("admitted container has no entry with descriptor_id {id}"),
1113 )
1114 })?,
1115 (None, None) => 0,
1116 };
1117 Ok((resolved_idx, &env.entries[resolved_idx]))
1118 }
1119
1120 pub(crate) fn build_envelope(
1121 family: EnvelopeFamily,
1122 alignment_4096: bool,
1123 metadata: &[u8],
1124 entries: &[BuildEntry<'_>],
1125 ) -> Result<Vec<u8>, String> {
1126 if entries.is_empty() || entries.len() > MAX_ENTRIES {
1127 return Err(format!("entries count must be 1..={MAX_ENTRIES}"));
1128 }
1129 validate_metadata_tlv(metadata)?;
1130 let flags: u32 = if alignment_4096 { 1 } else { 0 };
1131 let alignment = if alignment_4096 { 4096u64 } else { 64u64 };
1132 let meta_start = (HEADER_BYTES + entries.len() * DIRECTORY_BYTES) as u64;
1133 let meta_end = meta_start
1134 .checked_add(metadata.len() as u64)
1135 .ok_or_else(|| "metadata overflow".to_string())?;
1136 let mut next = align_up(meta_end, alignment)?;
1137
1138 let mut prior_key: Option<(u32, i64, u64, u16, u32)> = None;
1139 for (i, e) in entries.iter().enumerate() {
1140 if !family.mode_allowed(e.mode) {
1141 return Err(format!(
1142 "mode {:#06x} is not admitted for {}",
1143 e.mode,
1144 family.label()
1145 ));
1146 }
1147 if e.revision == 0 || e.descriptor_id == 0 || e.stride == 0 || e.record_count == 0 {
1148 return Err(format!("entry {i} requires non-zero revision, descriptor_id, stride, and record_count"));
1149 }
1150 if (e.flags & !7) != 0
1151 || (e.flags & 2 == 0 && (e.start_tick != 0 || e.time_count != 0))
1152 || (e.flags & 2 != 0 && (e.time_count == 0 || e.stream_id == 0))
1153 || (e.flags & 4 == 0 && e.spatial_key != 0)
1154 || (e.flags & 4 != 0 && e.frame_id == 0)
1155 {
1156 return Err(format!("entry {i} invalid time/spatial flags"));
1157 }
1158 let size = e
1159 .record_count
1160 .checked_mul(u64::from(e.stride))
1161 .ok_or_else(|| "entry size overflow".to_string())?;
1162 if size != e.payload.len() as u64 {
1163 return Err(format!(
1164 "entry {i} payload length {} != record_count * stride ({size})",
1165 e.payload.len()
1166 ));
1167 }
1168 let key = (e.stream_id, e.start_tick, e.spatial_key, e.mode, e.descriptor_id);
1169 if prior_key.is_some_and(|p| p >= key) {
1170 return Err(format!("entry {i} violates ascending directory key order"));
1171 }
1172 prior_key = Some(key);
1173 next = align_up(
1174 next.checked_add(size).ok_or_else(|| "container size overflow".to_string())?,
1175 alignment,
1176 )?;
1177 }
1178
1179 let total_len = usize::try_from(next).map_err(|_| "total container size overflow".to_string())?;
1180 if total_len > MAX_CONTAINER_BYTES {
1181 return Err("built container exceeds MAX_CONTAINER_BYTES".to_string());
1182 }
1183 let mut out = vec![0u8; total_len];
1184 let meta_start_usize = meta_start as usize;
1185 out[meta_start_usize..meta_start_usize + metadata.len()].copy_from_slice(metadata);
1186 let mut cursor = align_up(meta_end, alignment)? as usize;
1187
1188 for (index, e) in entries.iter().enumerate() {
1189 let end = cursor + e.payload.len();
1190 out[cursor..end].copy_from_slice(e.payload);
1191 let row = &mut out[HEADER_BYTES + index * DIRECTORY_BYTES..HEADER_BYTES + (index + 1) * DIRECTORY_BYTES];
1192 put16(row, 0, e.mode);
1193 put16(row, 2, e.revision);
1194 put32(row, 4, e.flags);
1195 put32(row, 8, e.stream_id);
1196 put32(row, 12, e.frame_id);
1197 put64(row, 16, e.start_tick as u64);
1198 put64(row, 24, e.time_count);
1199 put64(row, 32, e.spatial_key);
1200 put64(row, 40, cursor as u64);
1201 put64(row, 48, e.payload.len() as u64);
1202 put64(row, 56, e.payload.len() as u64);
1203 put64(row, 64, e.record_count);
1204 put32(row, 72, e.stride);
1205 row[80..112].copy_from_slice(&blake3_hash(e.payload));
1206 put32(row, 112, e.descriptor_id);
1207 let row_crc = crc32c(row);
1208 put32(row, 124, row_crc);
1209 cursor = align_up(end as u64, alignment)? as usize;
1210 }
1211
1212 {
1213 let h = &mut out[..HEADER_BYTES];
1214 h[..8].copy_from_slice(family.magic());
1215 put16(h, 8, family.version());
1216 put16(h, 10, HEADER_BYTES as u16);
1217 put32(h, 12, flags);
1218 put64(h, 16, total_len as u64);
1219 put64(h, 24, HEADER_BYTES as u64);
1220 put32(h, 32, entries.len() as u32);
1221 put16(h, 36, DIRECTORY_BYTES as u16);
1222 put16(h, 38, 1);
1223 put64(h, 40, meta_start);
1224 put64(h, 48, metadata.len() as u64);
1225 }
1226 let idx_digest = compute_index_digest(
1227 &out[..HEADER_BYTES],
1228 &out[HEADER_BYTES..meta_start_usize],
1229 &out[meta_start_usize..meta_start_usize + metadata.len()],
1230 );
1231 out[56..88].copy_from_slice(&idx_digest);
1232 let hdr_crc = crc32c(&out[..HEADER_BYTES]);
1233 put32(&mut out[..HEADER_BYTES], 124, hdr_crc);
1234
1235 admit_envelope(&out, family)?;
1236 Ok(out)
1237 }
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242 use super::*;
1243
1244 #[test]
1245 fn up02_catalog_knows_all_16_new_ids_without_pulse_or_net_streaming() {
1246 let up02_ids = [
1247 "Emf.openContainer",
1248 "Emf.buildContainer",
1249 "Emf.verifyContainer",
1250 "Emf.sonifyField",
1251 "Emf.evaluateDipole",
1252 "Qac.openContainer",
1253 "Qac.buildContainer",
1254 "Qac.renderBinaural",
1255 "Qac.evaluateDirectivity",
1256 "Qac.sonifyEmf",
1257 "Dicom.parseDataset",
1258 "Dicom.verifyDataset",
1259 "Dicom.toEmfField",
1260 "Dicom.reconstructVolume",
1261 "Sensing.admitEvidence",
1262 "Sensing.verifyCalibration",
1263 ];
1264 for id in up02_ids {
1265 assert!(is_known(id), "catalog missing `{id}`");
1266 assert_eq!(canonical_id(id), Some(id));
1267 let family = family_of(id).expect("family_of");
1268 assert!(granted_covers(&[id], id));
1269 assert!(granted_covers(&[family], id));
1270 assert!(looks_like_catalog_path(id));
1271 }
1272 assert_eq!(methods_for_family("Emf").len(), 5);
1273 assert_eq!(methods_for_family("Qac").len(), 5);
1274 assert_eq!(methods_for_family("Dicom").len(), 4);
1275 assert!(methods_for_family("Sensing").contains(&"Sensing.admitEvidence"));
1276 assert!(methods_for_family("Sensing").contains(&"Sensing.verifyCalibration"));
1277 assert!(!is_known("Pulse.stream"));
1278 assert!(!is_known("Net.stream"));
1279 assert!(!is_known("Bundle.streamHmc"));
1280 }
1281
1282 #[test]
1283 fn up02_crc32c_and_blake3_vectors_and_multi_entry_admission() {
1284 use envelope_admission::{
1285 admit_envelope, blake3_hash, build_envelope, crc32c, BuildEntry, EnvelopeFamily,
1286 };
1287 assert_eq!(crc32c(b"123456789"), 0xE306_9283);
1288 assert_eq!(
1289 blake3_hash(b""),
1290 [
1291 0xaf, 0x13, 0x49, 0xb9, 0xf5, 0xf9, 0xa1, 0xa6, 0xa0, 0x40, 0x4d, 0xea, 0x36,
1292 0xdc, 0xc9, 0x49, 0x9b, 0xcb, 0x25, 0xc9, 0xad, 0xc1, 0x12, 0xb7, 0xcc, 0x9a,
1293 0x93, 0xca, 0xe4, 0x1f, 0x32, 0x62,
1294 ]
1295 );
1296 let big = vec![0x42u8; 2050];
1298 let big_hash = blake3_hash(&big);
1299 assert_ne!(big_hash, blake3_hash(b""));
1300
1301 let p1 = vec![1u8; 64];
1302 let p2 = vec![2u8; 64];
1303 let emf_bytes = build_envelope(
1304 EnvelopeFamily::EmfV4,
1305 false,
1306 &[],
1307 &[
1308 BuildEntry {
1309 mode: 0x0100,
1310 revision: 1,
1311 flags: 0,
1312 stream_id: 0,
1313 frame_id: 0,
1314 start_tick: 0,
1315 time_count: 0,
1316 spatial_key: 0,
1317 record_count: 1,
1318 stride: 64,
1319 descriptor_id: 101,
1320 payload: &p1,
1321 },
1322 BuildEntry {
1323 mode: 0x0101,
1324 revision: 1,
1325 flags: 0,
1326 stream_id: 0,
1327 frame_id: 0,
1328 start_tick: 0,
1329 time_count: 0,
1330 spatial_key: 0,
1331 record_count: 1,
1332 stride: 64,
1333 descriptor_id: 102,
1334 payload: &p2,
1335 },
1336 ],
1337 )
1338 .expect("build multi-entry EMF v4 container");
1339 let view = admit_envelope(&emf_bytes, EnvelopeFamily::EmfV4).expect("admits EMF v4");
1340 assert_eq!(view.entries.len(), 2);
1341 assert_eq!(view.entries[0].descriptor_id, 101);
1342 assert_eq!(view.entries[1].descriptor_id, 102);
1343 assert!(admit_envelope(&emf_bytes, EnvelopeFamily::QacV1).is_err());
1344
1345 let mut corrupt = emf_bytes.clone();
1347 let last = corrupt.len() - 1;
1348 corrupt[last] ^= 0xFF;
1349 assert!(admit_envelope(&corrupt, EnvelopeFamily::EmfV4).is_err());
1350 }
1351
1352 #[test]
1353 fn catalog_contains_animation_and_hid() {
1354 assert!(is_known("Animation.evaluate_preset"));
1355 assert!(is_known("HID.poll"));
1356 assert!(is_known("GraphDatabase.sparql"));
1357 assert!(is_known("GraphDatabase.volume_open"));
1358 assert!(is_known("GraphDatabase.volume_commit"));
1359 assert!(is_known("GraphDatabase.lexicon_manifest"));
1360 assert!(is_known("DeonticLogic.evaluate"));
1361 assert!(is_known("N3Logic.evaluate"));
1362 assert!(is_known("GraphAuthoring.process"));
1363 assert!(is_known("LegalLogic.compute"));
1364 assert!(describe("GraphAuthoring.process").contains("owl:Thing"));
1365 }
1366
1367 #[test]
1368 fn preset_alias_resolves() {
1369 assert_eq!(
1370 canonical_id("Animation.orbit_spin"),
1371 Some("Animation.evaluate_preset")
1372 );
1373 assert!(animation_preset("Animation.orbit_spin").is_some());
1374 }
1375
1376 #[test]
1377 fn preset_alias_fills_family_and_preset() {
1378 let mut payload = payload_from_args(&[Value::F64(0.2)], &[]);
1379 apply_preset_alias("Animation.glass_reveal", &mut payload);
1380 let Value::Record(map) = payload else {
1381 panic!("expected record");
1382 };
1383 assert_eq!(
1384 map.get("family"),
1385 Some(&Value::String("hud_glass_ui".into()))
1386 );
1387 assert_eq!(
1388 map.get("preset"),
1389 Some(&Value::String("glass_reveal".into()))
1390 );
1391 assert_eq!(map.get("t"), Some(&Value::F64(0.2)));
1392 }
1393
1394 #[test]
1395 fn using_family_covers_methods() {
1396 let g = ["Animation"];
1397 assert!(granted_covers(&g, "Animation.evaluate_preset"));
1398 assert!(granted_covers(&g, "Animation.orbit_spin"));
1399 assert!(!granted_covers(&g, "HID.poll"));
1400 }
1401
1402 #[test]
1403 fn unknown_family_method_is_catalog_shaped() {
1404 assert!(looks_like_catalog_path("Animation.not_a_real_preset"));
1405 assert!(!is_known("Animation.not_a_real_preset"));
1406 assert!(!looks_like_catalog_path("math.sin"));
1407 }
1408
1409 #[test]
1410 fn families_include_render_and_deontic() {
1411 let fams = families();
1412 assert!(fams.contains(&"Render"));
1413 assert!(fams.contains(&"DeonticLogic"));
1414 assert!(fams.contains(&"Animation"));
1415 }
1416
1417 #[test]
1418 fn describe_mentions_lease() {
1419 let d = describe("DeonticLogic.evaluate");
1420 assert!(d.contains("DeonticLogic.evaluate"));
1421 assert!(d.contains("using DeonticLogic"));
1422 }
1423
1424 #[test]
1425 fn suggest_nearby_id() {
1426 let s = did_you_mean("HID.pol");
1427 assert!(s.is_some());
1428 assert!(s.unwrap().contains("HID.poll"));
1429 }
1430}