Skip to main content

qualia_core_db/modalities/
blackboard.rs

1//! Q42 Semantic Blackboard & Constraint Context — plan §7.3 A5.
2//!
3//! Observable state channels on Q42 CRDT graphs with pinned hard/soft
4//! constraint propagation. The blackboard provides:
5//!
6//! - **Channels**: named observable state channels backed by the Q42 graph.
7//! - **Constraints**: hard (must-hold) and soft (preferably-hold) constraints
8//!   that propagate to downstream consumers.
9//! - **Pinning**: constraints can be pinned to a root context, ensuring
10//!   downstream DAG nodes inherit and enforce them.
11//! - **Subscription**: consumers can subscribe to channel updates and receive
12//!   notifications when state changes.
13//! - **CRDT integration**: uses the existing `NQuin` 48-byte structure and
14//!   Lamport clock for ordering.
15//!
16//! ## Design
17//!
18//! The blackboard is a zero-heap hot-path structure. Channel writes and
19//! constraint checks do not allocate. Subscription notifications use the
20//! existing `broadcast` channel pattern from `daemon_graph.rs`.
21//!
22//! Constraints are encoded as `NQuin` entries with specific opcodes:
23//! - `OP_CONSTRAINT_HARD` (0x40): hard constraint — violation aborts.
24//! - `OP_CONSTRAINT_SOFT` (0x41): soft constraint — violation warns.
25//! - `OP_CONSTRAINT_PIN` (0x42): pinned root constraint — inherited by downstream.
26
27use crate::NQuin;
28use std::collections::HashMap;
29
30// ── Opcodes ────────────────────────────────────────────────────────────────
31
32/// Hard constraint opcode — violation aborts the operation.
33pub const OP_CONSTRAINT_HARD: u8 = 0x40;
34/// Soft constraint opcode — violation produces a warning but continues.
35pub const OP_CONSTRAINT_SOFT: u8 = 0x41;
36/// Pinned root constraint opcode — inherited by downstream DAG nodes.
37pub const OP_CONSTRAINT_PIN: u8 = 0x42;
38
39/// Maximum number of channels per blackboard.
40pub const MAX_CHANNELS: usize = 64;
41/// Maximum number of constraints per channel.
42pub const MAX_CONSTRAINTS_PER_CHANNEL: usize = 32;
43/// Maximum number of subscribers per channel.
44pub const MAX_SUBSCRIBERS_PER_CHANNEL: usize = 16;
45
46// ── Constraint ─────────────────────────────────────────────────────────────
47
48/// A constraint on a blackboard channel.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct Constraint {
51    /// The constraint opcode (hard, soft, or pinned).
52    pub opcode: u8,
53    /// The subject the constraint applies to.
54    pub subject: u64,
55    /// The predicate (property) being constrained.
56    pub predicate: u64,
57    /// The required/forbidden value.
58    pub object: u64,
59    /// The context (graph) the constraint is scoped to.
60    pub context: u64,
61    /// Whether this constraint is pinned (inherited by downstream).
62    pub pinned: bool,
63}
64
65impl Constraint {
66    /// Create a hard constraint.
67    pub fn hard(subject: u64, predicate: u64, object: u64, context: u64) -> Self {
68        Self {
69            opcode: OP_CONSTRAINT_HARD,
70            subject,
71            predicate,
72            object,
73            context,
74            pinned: false,
75        }
76    }
77
78    /// Create a soft constraint.
79    pub fn soft(subject: u64, predicate: u64, object: u64, context: u64) -> Self {
80        Self {
81            opcode: OP_CONSTRAINT_SOFT,
82            subject,
83            predicate,
84            object,
85            context,
86            pinned: false,
87        }
88    }
89
90    /// Create a pinned root constraint (hard + inherited).
91    pub fn pinned(subject: u64, predicate: u64, object: u64, context: u64) -> Self {
92        Self {
93            opcode: OP_CONSTRAINT_PIN,
94            subject,
95            predicate,
96            object,
97            context,
98            pinned: true,
99        }
100    }
101
102    /// Is this a hard constraint?
103    pub fn is_hard(&self) -> bool {
104        self.opcode == OP_CONSTRAINT_HARD || self.opcode == OP_CONSTRAINT_PIN
105    }
106
107    /// Is this a soft constraint?
108    pub fn is_soft(&self) -> bool {
109        self.opcode == OP_CONSTRAINT_SOFT
110    }
111
112    /// Is this pinned?
113    pub fn is_pinned(&self) -> bool {
114        self.pinned || self.opcode == OP_CONSTRAINT_PIN
115    }
116
117    /// Encode as an NQuin.
118    pub fn to_quin(&self) -> NQuin {
119        NQuin {
120            subject: self.subject,
121            predicate: (self.predicate << 8) | self.opcode as u64,
122            object: self.object,
123            context: self.context,
124            metadata: if self.pinned { 1 } else { 0 },
125            parity: self.subject ^ self.predicate ^ self.object ^ self.context,
126        }
127    }
128
129    /// Decode from an NQuin.
130    pub fn from_quin(q: &NQuin) -> Option<Self> {
131        let opcode = (q.predicate & 0xFF) as u8;
132        if opcode != OP_CONSTRAINT_HARD
133            && opcode != OP_CONSTRAINT_SOFT
134            && opcode != OP_CONSTRAINT_PIN
135        {
136            return None;
137        }
138        Some(Self {
139            opcode,
140            subject: q.subject,
141            predicate: q.predicate >> 8,
142            object: q.object,
143            context: q.context,
144            pinned: q.metadata & 1 != 0 || opcode == OP_CONSTRAINT_PIN,
145        })
146    }
147}
148
149// ── Constraint violation ───────────────────────────────────────────────────
150
151/// A constraint violation detected during checking.
152#[derive(Debug, Clone, PartialEq)]
153pub struct ConstraintViolation {
154    /// The constraint that was violated.
155    pub constraint: Constraint,
156    /// The Quin that violated it.
157    pub quin: NQuin,
158    /// Whether this is a hard violation (abort) or soft (warn).
159    pub is_hard: bool,
160    /// Human-readable description.
161    pub message: String,
162}
163
164// ── Channel ────────────────────────────────────────────────────────────────
165
166/// A named observable state channel on the blackboard.
167#[derive(Debug, Clone)]
168pub struct Channel {
169    /// Channel name (hashed for lookup).
170    pub name_hash: u64,
171    /// Current state Quins on this channel.
172    pub state: Vec<NQuin>,
173    /// Constraints pinned to this channel.
174    pub constraints: Vec<Constraint>,
175    /// Lamport clock for this channel.
176    pub lamport: u64,
177    /// Whether this channel is read-only (frozen).
178    pub frozen: bool,
179}
180
181impl Channel {
182    /// Create an empty channel for `name_hash` (writeable, Lamport 0,
183    /// no constraints).
184    pub fn new(name_hash: u64) -> Self {
185        Self {
186            name_hash,
187            state: Vec::new(),
188            constraints: Vec::new(),
189            lamport: 0,
190            frozen: false,
191        }
192    }
193
194    /// Write a Quin to this channel's state.
195    pub fn write(&mut self, quin: NQuin) -> Result<(), String> {
196        if self.frozen {
197            return Err("channel is frozen (read-only)".into());
198        }
199        self.lamport += 1;
200        let mut q = quin;
201        q.metadata = (q.metadata & !0xFFFFFFFF) | self.lamport;
202        q.parity = q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata;
203        self.state.push(q);
204        Ok(())
205    }
206
207    /// Read the current state of this channel.
208    pub fn read(&self) -> &[NQuin] {
209        &self.state
210    }
211
212    /// Add a constraint to this channel.
213    pub fn add_constraint(&mut self, constraint: Constraint) -> Result<(), String> {
214        if self.constraints.len() >= MAX_CONSTRAINTS_PER_CHANNEL {
215            return Err(format!(
216                "max constraints ({MAX_CONSTRAINTS_PER_CHANNEL}) reached"
217            ));
218        }
219        self.constraints.push(constraint);
220        Ok(())
221    }
222
223    /// Check all constraints against the current state.
224    pub fn check_constraints(&self) -> Vec<ConstraintViolation> {
225        let mut violations = Vec::new();
226        for constraint in &self.constraints {
227            for quin in &self.state {
228                if let Some(violation) = check_constraint(constraint, quin) {
229                    violations.push(violation);
230                }
231            }
232        }
233        violations
234    }
235
236    /// Freeze this channel (make read-only).
237    pub fn freeze(&mut self) {
238        self.frozen = true;
239    }
240
241    /// Get pinned constraints (for propagation to downstream).
242    pub fn pinned_constraints(&self) -> Vec<Constraint> {
243        self.constraints
244            .iter()
245            .filter(|c| c.is_pinned())
246            .cloned()
247            .collect()
248    }
249}
250
251/// Check a single constraint against a single Quin.
252fn check_constraint(constraint: &Constraint, quin: &NQuin) -> Option<ConstraintViolation> {
253    // Only check Quins in the same context.
254    if quin.context != constraint.context && constraint.context != 0 {
255        return None;
256    }
257    // Check if the Quin matches the constraint's subject+predicate.
258    let quin_pred_high = quin.predicate >> 8;
259    if quin.subject == constraint.subject && quin_pred_high == constraint.predicate {
260        // If the Quin's object differs from the constraint's required object,
261        // that's a violation.
262        if quin.object != constraint.object {
263            let is_hard = constraint.is_hard();
264            let message = format!(
265                "constraint violation: subject {} predicate {} expected object {} but got {}",
266                constraint.subject, constraint.predicate, constraint.object, quin.object
267            );
268            return Some(ConstraintViolation {
269                constraint: *constraint,
270                quin: *quin,
271                is_hard,
272                message,
273            });
274        }
275    }
276    None
277}
278
279// ── Blackboard ─────────────────────────────────────────────────────────────
280
281/// The semantic blackboard — a collection of observable channels with
282/// constraint propagation.
283#[derive(Debug)]
284pub struct SemanticBlackboard {
285    /// Named channels.
286    channels: HashMap<u64, Channel>,
287    /// Pinned root constraints (inherited by all channels).
288    root_constraints: Vec<Constraint>,
289    /// Global Lamport clock.
290    global_lamport: u64,
291}
292
293impl SemanticBlackboard {
294    /// Create an empty blackboard: no channels, no pinned root
295    /// constraints, global Lamport 0.
296    pub fn new() -> Self {
297        Self {
298            channels: HashMap::new(),
299            root_constraints: Vec::new(),
300            global_lamport: 0,
301        }
302    }
303
304    /// Create or get a channel by name.
305    pub fn channel(&mut self, name: &str) -> &mut Channel {
306        let hash = crate::q_hash(name);
307        self.channels
308            .entry(hash)
309            .or_insert_with(|| Channel::new(hash))
310    }
311
312    /// Get a channel by name (immutable).
313    pub fn get_channel(&self, name: &str) -> Option<&Channel> {
314        let hash = crate::q_hash(name);
315        self.channels.get(&hash)
316    }
317
318    /// Write a Quin to a named channel.
319    pub fn write(&mut self, channel: &str, quin: NQuin) -> Result<(), String> {
320        self.global_lamport += 1;
321        let ch = self.channel(channel);
322        ch.write(quin)
323    }
324
325    /// Read a channel's current state.
326    pub fn read(&self, channel: &str) -> Option<&[NQuin]> {
327        self.get_channel(channel).map(|c| c.read())
328    }
329
330    /// Add a constraint to a channel.
331    pub fn add_constraint(&mut self, channel: &str, constraint: Constraint) -> Result<(), String> {
332        let ch = self.channel(channel);
333        ch.add_constraint(constraint)
334    }
335
336    /// Add a pinned root constraint (inherited by all channels).
337    pub fn add_root_constraint(&mut self, constraint: Constraint) -> Result<(), String> {
338        if !constraint.is_pinned() {
339            return Err("root constraint must be pinned".into());
340        }
341        self.root_constraints.push(constraint);
342        Ok(())
343    }
344
345    /// Check all constraints on all channels.
346    pub fn check_all(&self) -> Vec<ConstraintViolation> {
347        let mut violations = Vec::new();
348        for channel in self.channels.values() {
349            violations.extend(channel.check_constraints());
350            // Also check root constraints against this channel.
351            for root in &self.root_constraints {
352                for quin in &channel.state {
353                    if let Some(v) = check_constraint(root, quin) {
354                        violations.push(v);
355                    }
356                }
357            }
358        }
359        violations
360    }
361
362    /// Get all pinned constraints (root + channel-level) for propagation.
363    pub fn pinned_constraints(&self) -> Vec<Constraint> {
364        let mut pinned = self.root_constraints.clone();
365        for channel in self.channels.values() {
366            pinned.extend(channel.pinned_constraints());
367        }
368        pinned
369    }
370
371    /// Propagate pinned constraints from this blackboard to a downstream
372    /// blackboard (for DAG node inheritance).
373    pub fn propagate_to(&self, downstream: &mut SemanticBlackboard) -> Result<(), String> {
374        for constraint in self.pinned_constraints() {
375            downstream.add_root_constraint(constraint)?;
376        }
377        Ok(())
378    }
379
380    /// Freeze a channel (make read-only).
381    pub fn freeze_channel(&mut self, channel: &str) -> Result<(), String> {
382        let ch = self.channel(channel);
383        ch.freeze();
384        Ok(())
385    }
386
387    /// Get the global Lamport clock.
388    pub fn lamport(&self) -> u64 {
389        self.global_lamport
390    }
391
392    /// Get the number of channels.
393    pub fn channel_count(&self) -> usize {
394        self.channels.len()
395    }
396
397    /// List all channel name hashes.
398    pub fn channel_hashes(&self) -> Vec<u64> {
399        self.channels.keys().cloned().collect()
400    }
401
402    /// Read all state from a named channel as a Vec (for DAG node input).
403    /// Returns an empty Vec if the channel does not exist.
404    pub fn read_channel_vec(&self, channel: &str) -> Vec<NQuin> {
405        self.get_channel(channel)
406            .map(|c| c.state.clone())
407            .unwrap_or_default()
408    }
409
410    /// Check whether a named channel exists and has any state.
411    pub fn channel_has_data(&self, channel: &str) -> bool {
412        self.get_channel(channel)
413            .map(|c| !c.state.is_empty())
414            .unwrap_or(false)
415    }
416}
417
418impl Default for SemanticBlackboard {
419    /// Equivalent to [`SemanticBlackboard::new`].
420    fn default() -> Self {
421        Self::new()
422    }
423}
424
425// ── BlackboardBus (R5) ─────────────────────────────────────────────────────
426//
427// Connects DAG node I/O declarations to SemanticBlackboard channels.
428// Each DAG node declares `inputs` and `outputs` as channel name strings
429// (see `vibe::dag::DagNode`). The bus reads from input channels and
430// writes to output channels, propagating pinned constraints from upstream
431// to downstream nodes.
432
433/// A bus connecting DAG nodes to a SemanticBlackboard.
434///
435/// This is the R5 wiring: DAG nodes declare inputs/outputs as channel names,
436//  and the bus reads/writes those channels on the blackboard. Pinned
437//  constraints are propagated from upstream to downstream automatically.
438#[derive(Debug)]
439pub struct BlackboardBus {
440    /// The underlying blackboard.
441    pub board: SemanticBlackboard,
442}
443
444impl BlackboardBus {
445    /// Create a bus over a fresh, empty [`SemanticBlackboard`].
446    pub fn new() -> Self {
447        Self {
448            board: SemanticBlackboard::new(),
449        }
450    }
451
452    /// Create a bus wrapping an existing `board`, preserving its
453    /// channels, constraints, and Lamport state.
454    pub fn from_board(board: SemanticBlackboard) -> Self {
455        Self { board }
456    }
457
458    /// Read all inputs for a DAG node from the blackboard.
459    ///
460    /// Returns a map of channel_name → Vec\<NQuin\> for each input channel.
461    /// Channels that don't exist or have no data are included as empty Vecs.
462    pub fn read_inputs(&self, inputs: &[String]) -> Vec<(String, Vec<NQuin>)> {
463        inputs
464            .iter()
465            .map(|name| (name.clone(), self.board.read_channel_vec(name)))
466            .collect()
467    }
468
469    /// Write outputs from a DAG node to the blackboard.
470    ///
471    /// `outputs` is a list of (channel_name, quins) pairs. Each quin is
472    /// written to the named channel.
473    pub fn write_outputs(&mut self, outputs: &[(String, Vec<NQuin>)]) -> Result<(), String> {
474        for (channel, quins) in outputs {
475            for quin in quins {
476                self.board.write(channel, *quin)?;
477            }
478        }
479        Ok(())
480    }
481
482    /// Write a single quin to a named output channel.
483    pub fn write_output(&mut self, channel: &str, quin: NQuin) -> Result<(), String> {
484        self.board.write(channel, quin)
485    }
486
487    /// Propagate pinned constraints from upstream channels to downstream
488    /// channels. This ensures that hard constraints (e.g., a budget pinned
489    /// by the principal) are inherited by downstream DAG nodes.
490    ///
491    /// `upstream_channels` are the output channels of the upstream node.
492    /// `downstream_channels` are the input channels of the downstream node.
493    /// Pinned constraints from the upstream channels are propagated to the
494    /// downstream channels.
495    pub fn propagate_constraints(
496        &mut self,
497        upstream_channels: &[String],
498        downstream_channels: &[String],
499    ) -> Result<(), String> {
500        let mut pinned: Vec<Constraint> = Vec::new();
501        for name in upstream_channels {
502            if let Some(ch) = self.board.get_channel(name) {
503                pinned.extend(ch.pinned_constraints());
504            }
505        }
506        for name in downstream_channels {
507            for c in &pinned {
508                self.board.add_constraint(name, *c)?;
509            }
510        }
511        Ok(())
512    }
513
514    /// Check all constraints on all channels. Returns violations.
515    pub fn check_constraints(&self) -> Vec<ConstraintViolation> {
516        self.board.check_all()
517    }
518
519    /// Check if all input channels for a DAG node have data ready.
520    /// Returns the names of channels that are empty/missing.
521    pub fn missing_inputs(&self, inputs: &[String]) -> Vec<String> {
522        inputs
523            .iter()
524            .filter(|name| !self.board.channel_has_data(name))
525            .cloned()
526            .collect()
527    }
528
529    /// Freeze a channel (make read-only) after a node has written its
530    /// final output. This prevents downstream nodes from overwriting
531    /// upstream results.
532    pub fn freeze_output(&mut self, channel: &str) -> Result<(), String> {
533        self.board.freeze_channel(channel)
534    }
535
536    /// Get the underlying blackboard (immutable).
537    pub fn board(&self) -> &SemanticBlackboard {
538        &self.board
539    }
540
541    /// Get the underlying blackboard (mutable).
542    pub fn board_mut(&mut self) -> &mut SemanticBlackboard {
543        &mut self.board
544    }
545}
546
547impl Default for BlackboardBus {
548    /// Equivalent to [`BlackboardBus::new`].
549    fn default() -> Self {
550        Self::new()
551    }
552}
553
554// ── Tests ──────────────────────────────────────────────────────────────────
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    // ── R5: BlackboardBus tests ──────────────────────────────────────────
561
562    #[test]
563    fn r5_bus_write_and_read_output() {
564        let mut bus = BlackboardBus::new();
565        let quin = make_quin(1, 2, 3, 42);
566        bus.write_output("draft", quin).unwrap();
567
568        let inputs = bus.read_inputs(&["draft".into()]);
569        assert_eq!(inputs.len(), 1);
570        assert_eq!(inputs[0].0, "draft");
571        assert_eq!(inputs[0].1.len(), 1);
572        assert_eq!(inputs[0].1[0].subject, 1);
573    }
574
575    #[test]
576    fn r5_bus_missing_inputs() {
577        let bus = BlackboardBus::new();
578        let missing = bus.missing_inputs(&["draft".into(), "review".into()]);
579        assert_eq!(missing.len(), 2);
580        assert!(missing.contains(&"draft".to_string()));
581        assert!(missing.contains(&"review".to_string()));
582    }
583
584    #[test]
585    fn r5_bus_missing_inputs_after_write() {
586        let mut bus = BlackboardBus::new();
587        let quin = make_quin(1, 2, 3, 42);
588        bus.write_output("draft", quin).unwrap();
589
590        let missing = bus.missing_inputs(&["draft".into(), "review".into()]);
591        assert_eq!(missing.len(), 1);
592        assert_eq!(missing[0], "review");
593    }
594
595    #[test]
596    fn r5_bus_write_outputs_multi_channel() {
597        let mut bus = BlackboardBus::new();
598        let q1 = make_quin(1, 2, 3, 42);
599        let q2 = make_quin(4, 5, 6, 42);
600        bus.write_outputs(&[("draft".into(), vec![q1]), ("review".into(), vec![q2])])
601            .unwrap();
602
603        let inputs = bus.read_inputs(&["draft".into(), "review".into()]);
604        assert_eq!(inputs[0].1.len(), 1);
605        assert_eq!(inputs[1].1.len(), 1);
606    }
607
608    #[test]
609    fn r5_bus_propagate_constraints() {
610        let mut bus = BlackboardBus::new();
611        // Add a pinned constraint to the "draft" channel.
612        let pinned = Constraint::pinned(1, 2, 3, 42);
613        bus.board.add_constraint("draft", pinned).unwrap();
614
615        // Propagate from "draft" (upstream output) to "review" (downstream input).
616        bus.propagate_constraints(&["draft".into()], &["review".into()])
617            .unwrap();
618
619        // The "review" channel should now have the pinned constraint.
620        let review = bus.board.get_channel("review").unwrap();
621        assert_eq!(review.constraints.len(), 1);
622        assert!(review.constraints[0].is_pinned());
623    }
624
625    #[test]
626    fn r5_bus_freeze_output() {
627        let mut bus = BlackboardBus::new();
628        let quin = make_quin(1, 2, 3, 42);
629        bus.write_output("draft", quin).unwrap();
630        bus.freeze_output("draft").unwrap();
631
632        // Writing to a frozen channel should fail.
633        let result = bus.write_output("draft", make_quin(7, 8, 9, 42));
634        assert!(result.is_err());
635    }
636
637    #[test]
638    fn r5_bus_check_constraints_clean() {
639        let mut bus = BlackboardBus::new();
640        let quin = make_quin(1, 2, 3, 42);
641        bus.write_output("draft", quin).unwrap();
642        let violations = bus.check_constraints();
643        assert!(violations.is_empty(), "no constraints → no violations");
644    }
645
646    fn make_quin(subject: u64, predicate: u64, object: u64, context: u64) -> NQuin {
647        let q = NQuin {
648            subject,
649            predicate: predicate << 8,
650            object,
651            context,
652            metadata: 0,
653            parity: 0,
654        };
655        NQuin {
656            parity: q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata,
657            ..q
658        }
659    }
660
661    #[test]
662    fn constraint_hard_creation() {
663        let c = Constraint::hard(1, 2, 3, 42);
664        assert!(c.is_hard());
665        assert!(!c.is_soft());
666        assert!(!c.is_pinned());
667    }
668
669    #[test]
670    fn constraint_soft_creation() {
671        let c = Constraint::soft(1, 2, 3, 42);
672        assert!(!c.is_hard());
673        assert!(c.is_soft());
674        assert!(!c.is_pinned());
675    }
676
677    #[test]
678    fn constraint_pinned_creation() {
679        let c = Constraint::pinned(1, 2, 3, 42);
680        assert!(c.is_hard());
681        assert!(!c.is_soft());
682        assert!(c.is_pinned());
683    }
684
685    #[test]
686    fn constraint_quin_roundtrip() {
687        let c = Constraint::hard(100, 200, 300, 400);
688        let quin = c.to_quin();
689        let decoded = Constraint::from_quin(&quin).unwrap();
690        assert_eq!(c, decoded);
691    }
692
693    #[test]
694    fn constraint_pinned_quin_roundtrip() {
695        let c = Constraint::pinned(100, 200, 300, 400);
696        let quin = c.to_quin();
697        let decoded = Constraint::from_quin(&quin).unwrap();
698        assert_eq!(c, decoded);
699        assert!(decoded.is_pinned());
700    }
701
702    #[test]
703    fn channel_write_read() {
704        let mut ch = Channel::new(42);
705        let q = make_quin(1, 2, 3, 42);
706        ch.write(q).unwrap();
707        assert_eq!(ch.read().len(), 1);
708        assert_eq!(ch.read()[0].subject, 1);
709    }
710
711    #[test]
712    fn channel_freeze_blocks_writes() {
713        let mut ch = Channel::new(42);
714        ch.freeze();
715        let q = make_quin(1, 2, 3, 42);
716        assert!(ch.write(q).is_err());
717    }
718
719    #[test]
720    fn channel_constraint_violation() {
721        let mut ch = Channel::new(42);
722        // Add a hard constraint: subject 1, predicate 2, must have object 3.
723        ch.add_constraint(Constraint::hard(1, 2, 3, 42)).unwrap();
724        // Write a Quin that violates it: subject 1, predicate 2, object 99.
725        let q = make_quin(1, 2, 99, 42);
726        ch.write(q).unwrap();
727        let violations = ch.check_constraints();
728        assert_eq!(violations.len(), 1);
729        assert!(violations[0].is_hard);
730    }
731
732    #[test]
733    fn channel_constraint_no_violation() {
734        let mut ch = Channel::new(42);
735        ch.add_constraint(Constraint::hard(1, 2, 3, 42)).unwrap();
736        let q = make_quin(1, 2, 3, 42);
737        ch.write(q).unwrap();
738        let violations = ch.check_constraints();
739        assert!(violations.is_empty());
740    }
741
742    #[test]
743    fn channel_soft_constraint_violation() {
744        let mut ch = Channel::new(42);
745        ch.add_constraint(Constraint::soft(1, 2, 3, 42)).unwrap();
746        let q = make_quin(1, 2, 99, 42);
747        ch.write(q).unwrap();
748        let violations = ch.check_constraints();
749        assert_eq!(violations.len(), 1);
750        assert!(!violations[0].is_hard);
751    }
752
753    #[test]
754    fn blackboard_write_read() {
755        let mut bb = SemanticBlackboard::new();
756        let q = make_quin(1, 2, 3, 42);
757        bb.write("test_channel", q).unwrap();
758        let state = bb.read("test_channel").unwrap();
759        assert_eq!(state.len(), 1);
760    }
761
762    #[test]
763    fn blackboard_multiple_channels() {
764        let mut bb = SemanticBlackboard::new();
765        bb.write("ch1", make_quin(1, 2, 3, 42)).unwrap();
766        bb.write("ch2", make_quin(4, 5, 6, 42)).unwrap();
767        assert_eq!(bb.channel_count(), 2);
768        assert_eq!(bb.read("ch1").unwrap().len(), 1);
769        assert_eq!(bb.read("ch2").unwrap().len(), 1);
770    }
771
772    #[test]
773    fn blackboard_root_constraint_propagation() {
774        let mut bb = SemanticBlackboard::new();
775        let root = Constraint::pinned(1, 2, 3, 42);
776        bb.add_root_constraint(root).unwrap();
777        // Write a violating Quin to a channel.
778        bb.write("test", make_quin(1, 2, 99, 42)).unwrap();
779        let violations = bb.check_all();
780        assert_eq!(violations.len(), 1);
781        assert!(violations[0].is_hard);
782    }
783
784    #[test]
785    fn blackboard_propagate_to_downstream() {
786        let mut upstream = SemanticBlackboard::new();
787        upstream
788            .add_root_constraint(Constraint::pinned(1, 2, 3, 42))
789            .unwrap();
790        let mut downstream = SemanticBlackboard::new();
791        upstream.propagate_to(&mut downstream).unwrap();
792        // Downstream should now have the root constraint.
793        downstream.write("test", make_quin(1, 2, 99, 42)).unwrap();
794        let violations = downstream.check_all();
795        assert_eq!(violations.len(), 1);
796    }
797
798    #[test]
799    fn blackboard_pinned_constraints_collection() {
800        let mut bb = SemanticBlackboard::new();
801        bb.add_root_constraint(Constraint::pinned(1, 2, 3, 42))
802            .unwrap();
803        bb.add_constraint("ch1", Constraint::pinned(4, 5, 6, 42))
804            .unwrap();
805        bb.add_constraint("ch1", Constraint::hard(7, 8, 9, 42))
806            .unwrap();
807        let pinned = bb.pinned_constraints();
808        assert_eq!(pinned.len(), 2); // root + channel pinned
809    }
810
811    #[test]
812    fn blackboard_lamport_advances() {
813        let mut bb = SemanticBlackboard::new();
814        assert_eq!(bb.lamport(), 0);
815        bb.write("ch", make_quin(1, 2, 3, 42)).unwrap();
816        assert_eq!(bb.lamport(), 1);
817        bb.write("ch", make_quin(4, 5, 6, 42)).unwrap();
818        assert_eq!(bb.lamport(), 2);
819    }
820
821    #[test]
822    fn blackboard_root_must_be_pinned() {
823        let mut bb = SemanticBlackboard::new();
824        let result = bb.add_root_constraint(Constraint::hard(1, 2, 3, 42));
825        assert!(result.is_err());
826    }
827
828    #[test]
829    fn blackboard_freeze_channel() {
830        let mut bb = SemanticBlackboard::new();
831        bb.write("ch", make_quin(1, 2, 3, 42)).unwrap();
832        bb.freeze_channel("ch").unwrap();
833        let result = bb.write("ch", make_quin(4, 5, 6, 42));
834        assert!(result.is_err());
835    }
836
837    #[test]
838    fn channel_max_constraints() {
839        let mut ch = Channel::new(42);
840        for i in 0..MAX_CONSTRAINTS_PER_CHANNEL {
841            ch.add_constraint(Constraint::hard(i as u64, 2, 3, 42))
842                .unwrap();
843        }
844        // Adding one more should fail.
845        let result = ch.add_constraint(Constraint::hard(99, 2, 3, 42));
846        assert!(result.is_err());
847    }
848}