Skip to main content

qualia_core_db/modalities/
epistemic.rs

1use crate::NQuin;
2
3pub const OP_KNOWS: u8 = 0x20;
4pub const OP_BELIEVES: u8 = 0x21;
5pub const OP_COMMON_KNOWLEDGE: u8 = 0x22;
6pub const OP_INTENT_LOCK: u8 = 0x23;
7pub const OP_IS_LOCKED: u8 = 0x24;
8pub const OP_NAMESPACE_LOCK: u8 = 0x25;
9pub const OP_NAMESPACE_IS_LOCKED: u8 = 0x26;
10
11pub const CERTAINTY_BIT_SHIFT: u32 = 8;
12pub const NESTING_BIT_SHIFT: u32 = 16;
13
14// Named epistemic-strength bands for the `certainty` byte — the assertive/doxastic axis
15// (see core-ontologies/modal-junctures.n3). A juncture verb maps to a band; the eval is
16// Active at >= 128, so Knows/Affirms/Believes/Recognizes/Considers are Active and
17// Supposes/Suspects/Speculates/Doubts are Uncertain ("speculates" = a low-certainty
18// belief). The ILLOCUTIONARY speech acts (proclaims/declares/recommends/undertakes) are a
19// SEPARATE axis, not certainty — they route to deontic / soft-deontic / performative.
20pub const CERTAINTY_KNOWS: u8 = 255;
21pub const CERTAINTY_AFFIRMS: u8 = 230;
22pub const CERTAINTY_BELIEVES: u8 = 200;
23pub const CERTAINTY_RECOGNIZES: u8 = 200;
24pub const CERTAINTY_CONSIDERS: u8 = 128;
25pub const CERTAINTY_SUPPOSES: u8 = 100;
26pub const CERTAINTY_SUSPECTS: u8 = 80;
27pub const CERTAINTY_SPECULATES: u8 = 50;
28pub const CERTAINTY_DOUBTS: u8 = 20;
29
30#[derive(Debug, PartialEq, Clone, Copy)]
31pub enum EpistemicStatus {
32    Active,
33    Uncertain,
34    Skipped,
35}
36
37#[derive(Debug)]
38pub enum EpistemicError {
39    BufferOverflow,
40    NodeLocked(u64),      // Hash of the locked node
41    NamespaceLocked(u64), // Hash of the locked namespace context
42}
43
44#[derive(Debug, Clone, Copy)]
45pub struct EpistemicVerdict {
46    pub claim: NQuin,
47    pub status: EpistemicStatus,
48    pub certainty: u8,
49}
50
51/// Evaluates a slice of Quins for epistemic/doxastic claims.
52pub fn evaluate_epistemic_frame(
53    quins: &[NQuin],
54    agent_did_hash: u64, // 0 = accept all agents
55    world_hash: u64,     // 0 = accept all worlds
56    out: &mut [EpistemicVerdict],
57) -> Result<usize, EpistemicError> {
58    let mut count = 0;
59
60    for q in quins {
61        if world_hash != 0 && q.context != world_hash {
62            continue;
63        }
64        if agent_did_hash != 0 && q.subject != agent_did_hash {
65            continue;
66        }
67
68        let opcode = (q.predicate & 0xFF) as u8;
69        if opcode != OP_KNOWS && opcode != OP_BELIEVES && opcode != OP_COMMON_KNOWLEDGE {
70            continue;
71        }
72
73        let certainty = ((q.predicate >> CERTAINTY_BIT_SHIFT) & 0xFF) as u8;
74
75        let status = if certainty >= 128 || opcode == OP_KNOWS || opcode == OP_COMMON_KNOWLEDGE {
76            EpistemicStatus::Active
77        } else {
78            EpistemicStatus::Uncertain
79        };
80
81        if count >= out.len() {
82            return Err(EpistemicError::BufferOverflow);
83        }
84
85        out[count] = EpistemicVerdict {
86            claim: *q,
87            status,
88            certainty,
89        };
90        count += 1;
91    }
92
93    Ok(count)
94}
95
96/// Returns whether an agent has an active knowledge claim for the supplied
97/// claim fingerprint. This is the scalar, zero-allocation form used by
98/// inference guards between token steps; callers that need every verdict use
99/// `evaluate_epistemic_frame` above.
100#[inline]
101pub fn agent_knows(quins: &[NQuin], agent_did_hash: u64, claim_fingerprint: u64) -> bool {
102    quins.iter().any(|q| {
103        let opcode = (q.predicate & 0xFF) as u8;
104        let certainty = ((q.predicate >> CERTAINTY_BIT_SHIFT) & 0xFF) as u8;
105        (agent_did_hash == 0 || q.subject == agent_did_hash)
106            && q.object == claim_fingerprint
107            && (opcode == OP_KNOWS
108                || opcode == OP_COMMON_KNOWLEDGE
109                || (opcode == OP_BELIEVES && certainty >= 128))
110    })
111}
112
113/// Checks if any nodes requested by an intent quin are locked by another agent.
114pub fn check_node_locks(
115    intent_quins: &[NQuin],
116    current_graph: &[NQuin],
117    agent_did_hash: u64,
118) -> Result<(), EpistemicError> {
119    for i_quin in intent_quins {
120        let opcode = (i_quin.predicate & 0xFF) as u8;
121
122        // 1. Check Namespace Locks First
123        if opcode == OP_NAMESPACE_LOCK {
124            let target_namespace = i_quin.object;
125            // Ensure no other agent holds a namespace lock on this target
126            for c_quin in current_graph {
127                let c_opcode = (c_quin.predicate & 0xFF) as u8;
128                if c_opcode == OP_NAMESPACE_IS_LOCKED && c_quin.object == target_namespace {
129                    if c_quin.subject != agent_did_hash {
130                        return Err(EpistemicError::NamespaceLocked(target_namespace));
131                    }
132                }
133            }
134        }
135
136        // 2. Check Standard Node Locks
137        if opcode == OP_INTENT_LOCK {
138            let target_node = i_quin.object;
139            let target_namespace = i_quin.context; // The namespace context of the intent
140
141            for c_quin in current_graph {
142                let c_opcode = (c_quin.predicate & 0xFF) as u8;
143
144                // If the entire namespace is locked by another agent, reject the node lock
145                if c_opcode == OP_NAMESPACE_IS_LOCKED && c_quin.object == target_namespace {
146                    if c_quin.subject != agent_did_hash {
147                        return Err(EpistemicError::NamespaceLocked(target_namespace));
148                    }
149                }
150
151                // If the specific node is locked by another agent, reject the node lock
152                if c_opcode == OP_IS_LOCKED && c_quin.object == target_node {
153                    if c_quin.subject != agent_did_hash {
154                        return Err(EpistemicError::NodeLocked(target_node));
155                    }
156                }
157            }
158        }
159    }
160    Ok(())
161}
162
163// ─── Multi-agent epistemic operators (E, C, D), introspection, AGM revision ───────
164
165// AGM belief revision (expand / contract / revise over a signed-literal belief base) lives in
166// `modal.rs` and is re-exported here — belief revision IS an epistemic operation.
167pub use crate::modalities::modal::{
168    contract as agm_contract, expand as agm_expand, is_consistent as belief_set_consistent,
169    revise as agm_revise, Belief,
170};
171
172/// **Everyone-knows** `E φ`: every agent in the group knows φ. `agent_knows[i]` = does agent i know φ?
173pub fn everyone_knows(agent_knows: &[bool]) -> bool {
174    !agent_knows.is_empty() && agent_knows.iter().all(|&k| k)
175}
176
177/// **Distributed knowledge** `D φ`: the group COLLECTIVELY knows φ by pooling — φ is entailed by
178/// the union of what agents individually know. Modelled over fact-fragments: φ is distributed-
179/// known iff every fragment in `required` appears in `known` (the union of all agents' fragments).
180pub fn distributed_knowledge(required: &[u64], known: &[u64]) -> bool {
181    !required.is_empty() && required.iter().all(|r| known.contains(r))
182}
183
184/// **Common knowledge** `C φ`: practically established by a PUBLIC ANNOUNCEMENT to the whole group
185/// (everyone knows φ, everyone knows that everyone knows, ad infinitum). Holds iff the announcement
186/// was perceived by everyone.
187#[inline]
188pub fn common_knowledge_via_announcement(everyone_perceived: bool) -> bool {
189    everyone_perceived
190}
191
192/// **Positive introspection** (axiom 4): `Kφ → KKφ` — knowing implies knowing that one knows.
193#[inline]
194pub fn positive_introspection(knows_p: bool) -> bool {
195    knows_p
196}
197
198/// **Negative introspection** (axiom 5, S5): `¬Kφ → K¬Kφ` — not-knowing implies knowing one doesn't.
199#[inline]
200pub fn negative_introspection(knows_p: bool) -> bool {
201    !knows_p
202}
203
204/// The **Muddy Children** deduction: after the public announcement "at least one is muddy", each
205/// silent round eliminates a hypothesis; a muddy child deduces it is muddy exactly at
206/// `round == num_muddy` (1-indexed). Shows how common knowledge + iterated "I don't know" produces
207/// knowledge. Returns whether a muddy child KNOWS its own state at `round`.
208pub fn muddy_child_knows(num_muddy: u32, round: u32) -> bool {
209    num_muddy > 0 && round >= num_muddy
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate::q_hash;
216
217    #[test]
218    fn test_epistemic_evaluation() {
219        let mut out = Vec::with_capacity(10);
220        for _ in 0..10 {
221            out.push(EpistemicVerdict {
222                claim: NQuin::default(),
223                status: EpistemicStatus::Skipped,
224                certainty: 0,
225            });
226        }
227
228        let agent_a = q_hash("agent_a");
229        let agent_b = q_hash("agent_b");
230        let world_w = q_hash("world_w");
231
232        let mut q_knows = NQuin::default();
233        q_knows.subject = agent_a;
234        q_knows.predicate = (200u64 << CERTAINTY_BIT_SHIFT) | (OP_KNOWS as u64);
235        q_knows.context = world_w;
236
237        let mut q_believes_low = NQuin::default();
238        q_believes_low.subject = agent_a;
239        q_believes_low.predicate = (50u64 << CERTAINTY_BIT_SHIFT) | (OP_BELIEVES as u64);
240        q_believes_low.context = world_w;
241
242        let mut q_wrong_world = NQuin::default();
243        q_wrong_world.subject = agent_a;
244        q_wrong_world.predicate = (200u64 << CERTAINTY_BIT_SHIFT) | (OP_KNOWS as u64);
245        q_wrong_world.context = q_hash("other_world");
246
247        let quins = [q_knows, q_believes_low, q_wrong_world];
248
249        // 1. Single-agent K_a(p)
250        let count = evaluate_epistemic_frame(&quins, agent_a, world_w, &mut out).unwrap();
251        assert_eq!(count, 2);
252        assert_eq!(out[0].status, EpistemicStatus::Active); // Knows
253        assert_eq!(out[1].status, EpistemicStatus::Uncertain); // Believes low certainty
254
255        // 2. World filter
256        let mut out2 = Vec::with_capacity(10);
257        for _ in 0..10 {
258            out2.push(EpistemicVerdict {
259                claim: NQuin::default(),
260                status: EpistemicStatus::Skipped,
261                certainty: 0,
262            });
263        }
264        let count2 = evaluate_epistemic_frame(&quins, 0, q_hash("other_world"), &mut out2).unwrap();
265        assert_eq!(count2, 1);
266
267        // 3. Agent filter
268        let count3 = evaluate_epistemic_frame(&quins, agent_b, 0, &mut out2).unwrap();
269        assert_eq!(count3, 0);
270
271        // 4. Empty slice
272        let count4 = evaluate_epistemic_frame(&[], 0, 0, &mut out2).unwrap();
273        assert_eq!(count4, 0);
274    }
275
276    #[test]
277    fn epistemic_strength_bands_map_to_active_or_uncertain() {
278        // The named certainty bands (modal-junctures.n3) route through the eval: confident
279        // attitudes (knows/believes/considers) are Active; tentative ones (supposes/
280        // speculates/doubts) are Uncertain — "speculates" as a low-certainty belief.
281        let agent = q_hash("agent");
282        let world = q_hash("world");
283        let mk = |band: u8| {
284            let mut q = NQuin::default();
285            q.subject = agent;
286            q.predicate = ((band as u64) << CERTAINTY_BIT_SHIFT) | (OP_BELIEVES as u64);
287            q.context = world;
288            q
289        };
290        let mut out = vec![
291            EpistemicVerdict {
292                claim: NQuin::default(),
293                status: EpistemicStatus::Skipped,
294                certainty: 0,
295            };
296            4
297        ];
298
299        for b in [CERTAINTY_KNOWS, CERTAINTY_BELIEVES, CERTAINTY_CONSIDERS] {
300            evaluate_epistemic_frame(&[mk(b)], agent, world, &mut out).unwrap();
301            assert_eq!(
302                out[0].status,
303                EpistemicStatus::Active,
304                "band {b} should be Active"
305            );
306        }
307        for b in [CERTAINTY_SUPPOSES, CERTAINTY_SPECULATES, CERTAINTY_DOUBTS] {
308            evaluate_epistemic_frame(&[mk(b)], agent, world, &mut out).unwrap();
309            assert_eq!(
310                out[0].status,
311                EpistemicStatus::Uncertain,
312                "band {b} should be Uncertain"
313            );
314        }
315    }
316
317    #[test]
318    fn test_namespace_lock_blocks_node_lock() {
319        let agent_a = q_hash("agent_a");
320        let agent_b = q_hash("agent_b");
321        let target_namespace = q_hash("specialized_libs/");
322        let target_node = q_hash("specialized_libs/file.rs");
323
324        // Graph: Agent A holds a namespace lock on specialized_libs/
325        let mut namespace_locked = NQuin::default();
326        namespace_locked.subject = agent_a;
327        namespace_locked.predicate = OP_NAMESPACE_IS_LOCKED as u64;
328        namespace_locked.object = target_namespace;
329
330        let current_graph = vec![namespace_locked];
331
332        // Intent: Agent B tries to lock a specific node within that namespace
333        let mut intent_node_lock = NQuin::default();
334        intent_node_lock.subject = agent_b;
335        intent_node_lock.predicate = OP_INTENT_LOCK as u64;
336        intent_node_lock.object = target_node;
337        intent_node_lock.context = target_namespace;
338
339        let result = check_node_locks(&[intent_node_lock], &current_graph, agent_b);
340        assert!(
341            matches!(result, Err(EpistemicError::NamespaceLocked(ns)) if ns == target_namespace)
342        );
343
344        // Intent: Agent A tries to lock a node within their own namespace lock -> Should Succeed
345        let mut intent_node_lock_a = NQuin::default();
346        intent_node_lock_a.subject = agent_a;
347        intent_node_lock_a.predicate = OP_INTENT_LOCK as u64;
348        intent_node_lock_a.object = target_node;
349        intent_node_lock_a.context = target_namespace;
350
351        let result_a = check_node_locks(&[intent_node_lock_a], &current_graph, agent_a);
352        assert!(result_a.is_ok());
353    }
354
355    #[test]
356    fn multi_agent_operators_and_introspection() {
357        // Everyone-knows: all agents must know it.
358        assert!(everyone_knows(&[true, true, true]));
359        assert!(!everyone_knows(&[true, false, true]));
360        assert!(!everyone_knows(&[]));
361        // Distributed knowledge: pooled fragments cover the requirement.
362        let (a, b, c) = (q_hash("f:a"), q_hash("f:b"), q_hash("f:c"));
363        assert!(distributed_knowledge(&[a, b], &[a, b, c]));
364        assert!(
365            !distributed_knowledge(&[a, b], &[a, c]),
366            "missing fragment b"
367        );
368        // Common knowledge via public announcement.
369        assert!(common_knowledge_via_announcement(true));
370        assert!(!common_knowledge_via_announcement(false));
371        // Introspection axioms (S5).
372        assert!(positive_introspection(true) && !positive_introspection(false));
373        assert!(negative_introspection(false) && !negative_introspection(true));
374    }
375
376    #[test]
377    fn muddy_children_deduction() {
378        // 2 muddy children: nobody knows in round 1; each deduces at round 2.
379        assert!(!muddy_child_knows(2, 1));
380        assert!(muddy_child_knows(2, 2));
381        // 1 muddy child knows immediately (round 1, from the announcement).
382        assert!(muddy_child_knows(1, 1));
383    }
384
385    #[test]
386    fn common_knowledge_propagation_across_two_agents() {
387        // Two agents both know φ (OP_KNOWS, certainty 255) in the same world.
388        // When everyone knows φ and a public announcement is made, φ becomes
389        // common knowledge. This tests the propagation path:
390        //   individual knowledge → everyone-knows → common knowledge
391        let agent_a = q_hash("agent_a");
392        let agent_b = q_hash("agent_b");
393        let world_w = q_hash("world_w");
394
395        let mk_knows = |agent: u64| {
396            let mut q = NQuin::default();
397            q.subject = agent;
398            q.predicate = (255u64 << CERTAINTY_BIT_SHIFT) | (OP_KNOWS as u64);
399            q.context = world_w;
400            q
401        };
402
403        let quins = [mk_knows(agent_a), mk_knows(agent_b)];
404
405        // Evaluate: both agents' knowledge claims should be Active
406        let mut out = [EpistemicVerdict {
407            claim: NQuin::default(),
408            status: EpistemicStatus::Skipped,
409            certainty: 0,
410        }; 4];
411        let count = evaluate_epistemic_frame(&quins, 0, world_w, &mut out).unwrap();
412        assert_eq!(count, 2, "both agents' claims must be evaluated");
413        assert_eq!(out[0].status, EpistemicStatus::Active);
414        assert_eq!(out[1].status, EpistemicStatus::Active);
415
416        // Both agents know → everyone_knows is true
417        let agent_knows = [
418            out[0].status == EpistemicStatus::Active,
419            out[1].status == EpistemicStatus::Active,
420        ];
421        assert!(everyone_knows(&agent_knows), "everyone knows φ");
422
423        // Public announcement → common knowledge
424        assert!(
425            common_knowledge_via_announcement(everyone_knows(&agent_knows)),
426            "φ becomes common knowledge when everyone knows and it is publicly announced"
427        );
428    }
429
430    #[test]
431    fn agm_belief_revision_is_available_in_the_epistemic_namespace() {
432        // The AGM operators (from modal.rs) are re-exported here; revise is consistent.
433        let p = Belief {
434            atom: 1,
435            positive: true,
436        };
437        let not_p = Belief {
438            atom: 1,
439            positive: false,
440        };
441        let mut out = [Belief {
442            atom: 0,
443            positive: true,
444        }; 4];
445        let n = agm_revise(&[not_p], p, &mut out);
446        assert!(out[..n].contains(&p) && !out[..n].contains(&not_p));
447        assert!(belief_set_consistent(&out[..n]));
448        let _ = agm_expand;
449        let _ = agm_contract;
450    }
451}