Skip to main content

aidaemon_memory/
types.rs

1//! Plain data types shared by stores, scorers and writers.
2
3use aidaemon_core::ChannelVisibility;
4use chrono::{DateTime, SecondsFormat, Utc};
5use serde::{Deserialize, Serialize};
6
7use crate::error::{MemoryError, Result};
8use crate::records::FactPrivacy;
9use crate::sqlite::{ExactChannelIds, FACT_RESTATEMENT_MIN_SIMILARITY, memory_visible};
10
11/// Longest fact value accepted, in characters.
12pub const MAX_FACT_VALUE_CHARS: usize = 4_000;
13
14/// Where a fact came from. Every field is optional so manual imports work,
15/// but writers in this crate fill in what they know.
16#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
17pub struct Provenance {
18    /// The agent run that produced the fact.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub run_id: Option<String>,
21    /// The session (conversation) it was stated in.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub session_id: Option<String>,
24    /// The snippet of conversation that supports the fact. Facts with an
25    /// excerpt score slightly higher (the provenance signal).
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub excerpt: Option<String>,
28}
29
30/// A durable piece of knowledge, keyed by `(scope, category, key)`.
31///
32/// At most one row per key is active; replaced values stay as superseded
33/// history and are never recalled.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct Fact {
36    pub id: String,
37    /// Whose memory this is: a user, session or agent id (see
38    /// [`crate::Memory::scope_for`]).
39    pub scope: String,
40    pub category: String,
41    pub key: String,
42    pub value: String,
43    /// 0.0-1.0, how sure the writer was.
44    pub confidence: f32,
45    pub source: Provenance,
46    pub created_at: DateTime<Utc>,
47    pub updated_at: DateTime<Utc>,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub superseded_at: Option<DateTime<Utc>>,
50    #[serde(default)]
51    pub recall_count: u32,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub last_recalled_at: Option<DateTime<Utc>>,
54}
55
56impl Fact {
57    pub fn is_active(&self) -> bool {
58        self.superseded_at.is_none()
59    }
60
61    /// Text used for embeddings and lexical search: category, readable key
62    /// and value.
63    pub fn search_text(&self) -> String {
64        fact_search_text(&self.category, &self.key, &self.value)
65    }
66}
67
68/// `"{category} {key words}: {value}"`, shared by every store so lexical and
69/// semantic signals see the same text.
70pub fn fact_search_text(category: &str, key: &str, value: &str) -> String {
71    format!("{} {}: {}", category, key.replace(['_', '-'], " "), value)
72}
73
74/// A fact to write. Normalized and validated by [`NewFact::normalized`]
75/// before it reaches a store.
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct NewFact {
78    pub scope: String,
79    pub category: String,
80    pub key: String,
81    pub value: String,
82    pub confidence: f32,
83    #[serde(default)]
84    pub source: Provenance,
85}
86
87impl NewFact {
88    pub fn new(
89        scope: impl Into<String>,
90        category: impl Into<String>,
91        key: impl Into<String>,
92        value: impl Into<String>,
93    ) -> Self {
94        Self {
95            scope: scope.into(),
96            category: category.into(),
97            key: key.into(),
98            value: value.into(),
99            confidence: 1.0,
100            source: Provenance::default(),
101        }
102    }
103
104    pub fn confidence(mut self, confidence: f32) -> Self {
105        self.confidence = confidence;
106        self
107    }
108
109    pub fn source(mut self, source: Provenance) -> Self {
110        self.source = source;
111        self
112    }
113
114    /// Trim and canonicalize the identifying fields (lowercase category,
115    /// snake_case key), clamp confidence, and reject empty or oversized input.
116    pub fn normalized(mut self) -> Result<Self> {
117        self.scope = self.scope.trim().to_string();
118        self.category = normalize_category(&self.category);
119        self.key = normalize_key(&self.key);
120        self.value = self.value.trim().to_string();
121        if self.scope.is_empty() {
122            return Err(MemoryError::Invalid("scope is empty".into()));
123        }
124        if self.category.is_empty() || self.key.is_empty() || self.value.is_empty() {
125            return Err(MemoryError::Invalid(
126                "category, key and value must be non-empty".into(),
127            ));
128        }
129        if self.value.chars().count() > MAX_FACT_VALUE_CHARS {
130            return Err(MemoryError::Invalid(format!(
131                "value longer than {MAX_FACT_VALUE_CHARS} characters"
132            )));
133        }
134        self.confidence = if self.confidence.is_finite() {
135            self.confidence.clamp(0.0, 1.0)
136        } else {
137            0.5
138        };
139        self.source.excerpt = self
140            .source
141            .excerpt
142            .map(|e| truncate_chars(e.trim(), 500))
143            .filter(|e| !e.is_empty());
144        Ok(self)
145    }
146}
147
148/// Lowercase and trim.
149pub fn normalize_category(category: &str) -> String {
150    category.trim().to_lowercase()
151}
152
153/// Lowercase snake_case: runs of whitespace, `-` and `.` become `_`.
154pub fn normalize_key(key: &str) -> String {
155    let mut out = String::with_capacity(key.len());
156    for c in key.trim().to_lowercase().chars() {
157        if c.is_whitespace() || c == '-' || c == '.' {
158            if !out.ends_with('_') {
159                out.push('_');
160            }
161        } else {
162            out.push(c);
163        }
164    }
165    out.trim_matches('_').to_string()
166}
167
168/// True when two values state the same thing modulo case and whitespace.
169/// Used to tell a restatement (reinforce) from a correction (supersede).
170pub fn same_value(a: &str, b: &str) -> bool {
171    let canon = |s: &str| {
172        s.split_whitespace()
173            .collect::<Vec<_>>()
174            .join(" ")
175            .to_lowercase()
176    };
177    canon(a) == canon(b)
178}
179
180/// What an upsert did.
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case", tag = "kind")]
183pub enum UpsertOutcome {
184    /// No active fact had this key.
185    Inserted { id: String },
186    /// The same value was already active; `updated_at` and confidence were
187    /// refreshed.
188    Reinforced { id: String },
189    /// A different value was active; it was marked superseded and kept as
190    /// history.
191    Superseded {
192        id: String,
193        previous_id: String,
194        previous_value: String,
195    },
196}
197
198impl UpsertOutcome {
199    /// Id of the now-active fact.
200    pub fn id(&self) -> &str {
201        match self {
202            Self::Inserted { id } | Self::Reinforced { id } | Self::Superseded { id, .. } => id,
203        }
204    }
205}
206
207/// A summary of a finished run or session.
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209pub struct Episode {
210    pub id: String,
211    pub scope: String,
212    pub session_id: String,
213    pub summary: String,
214    #[serde(default)]
215    pub topics: Vec<String>,
216    /// 0.1-1.0, see [`crate::episode_importance`].
217    pub importance: f32,
218    pub created_at: DateTime<Utc>,
219    #[serde(default)]
220    pub recall_count: u32,
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub last_recalled_at: Option<DateTime<Utc>>,
223}
224
225impl Episode {
226    /// Text used for embeddings and lexical search.
227    pub fn search_text(&self) -> String {
228        episode_search_text(&self.summary, &self.topics)
229    }
230}
231
232pub fn episode_search_text(summary: &str, topics: &[String]) -> String {
233    if topics.is_empty() {
234        summary.to_string()
235    } else {
236        format!("{summary} Topics: {}", topics.join(", "))
237    }
238}
239
240/// An episode to write.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242pub struct NewEpisode {
243    pub scope: String,
244    pub session_id: String,
245    pub summary: String,
246    #[serde(default)]
247    pub topics: Vec<String>,
248    pub importance: f32,
249}
250
251/// A stored vector plus the model that produced it. Vectors from a
252/// different model are ignored at recall time instead of being compared.
253#[derive(Debug, Clone, PartialEq)]
254pub struct StoredEmbedding {
255    pub model: String,
256    pub vector: Vec<f32>,
257}
258
259/// When a new fact counts as a near duplicate of an active one under another
260/// key. A threshold above 1.0 never matches; see [`MergeConfig::disabled`].
261#[derive(Debug, Clone, Copy, PartialEq)]
262pub struct MergeConfig {
263    /// Minimum cosine similarity when both sides have vectors from the same
264    /// model. Defaults to the daemon's restatement threshold.
265    pub semantic_threshold: f32,
266    /// Minimum share of words in common when they do not.
267    pub text_threshold: f32,
268}
269
270impl Default for MergeConfig {
271    fn default() -> Self {
272        Self {
273            semantic_threshold: FACT_RESTATEMENT_MIN_SIMILARITY,
274            text_threshold: 0.9,
275        }
276    }
277}
278
279impl MergeConfig {
280    /// Never merge across keys.
281    pub fn disabled() -> Self {
282        Self {
283            semantic_threshold: 2.0,
284            text_threshold: 2.0,
285        }
286    }
287}
288
289/// Which table of records an embedding refresh is working through.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum RecordKind {
293    Fact,
294    Episode,
295}
296
297/// A record whose vector is missing or came from another model.
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct StaleEmbedding {
300    pub kind: RecordKind,
301    pub id: String,
302    /// The text to embed ([`Fact::search_text`] / [`Episode::search_text`]).
303    pub text: String,
304    /// The model of the vector being replaced; `None` when there is no vector.
305    pub model: Option<String>,
306}
307
308/// Where a re-embedding pass stands. Plain data, so a host can persist it.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct ReembedCursor {
311    pub kind: RecordKind,
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub after_id: Option<String>,
314}
315
316/// What one [`crate::Memory::reembed_batch`] did.
317#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
318pub struct ReembedReport {
319    /// Stale records looked at.
320    pub processed: usize,
321    pub updated: usize,
322    /// Left as they were: the embedder returned a vector of the wrong size,
323    /// or the record changed since it was read.
324    pub skipped: usize,
325    /// Pass this to the next batch; `None` when the pass is finished.
326    pub next: Option<ReembedCursor>,
327}
328
329/// A fact as a store hands it back, with its embedding if it has one.
330#[derive(Debug, Clone, PartialEq)]
331pub struct FactRecord {
332    pub fact: Fact,
333    pub embedding: Option<StoredEmbedding>,
334}
335
336/// An episode as a store hands it back.
337#[derive(Debug, Clone, PartialEq)]
338pub struct EpisodeRecord {
339    pub episode: Episode,
340    pub embedding: Option<StoredEmbedding>,
341}
342
343/// Who may see a stored fact or episode. The default is the narrowest level,
344/// [`FactPrivacy::Private`], so a record nobody classified stays out of
345/// shared channels.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct FactAccess {
348    pub privacy: FactPrivacy,
349    /// The originating channel; only meaningful with [`FactPrivacy::Channel`].
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub channel_id: Option<String>,
352}
353
354impl Default for FactAccess {
355    fn default() -> Self {
356        Self::private()
357    }
358}
359
360impl FactAccess {
361    /// Direct messages with the owner only.
362    pub fn private() -> Self {
363        Self {
364            privacy: FactPrivacy::Private,
365            channel_id: None,
366        }
367    }
368
369    /// Shareable outside direct messages.
370    pub fn global() -> Self {
371        Self {
372            privacy: FactPrivacy::Global,
373            channel_id: None,
374        }
375    }
376
377    /// Only in `channel_id` (and the owner's direct messages).
378    pub fn channel(channel_id: impl Into<String>) -> Self {
379        Self {
380            privacy: FactPrivacy::Channel,
381            channel_id: Some(channel_id.into()),
382        }
383    }
384
385    /// Read from stored text. Anything unrecognized, and a channel level with
386    /// no channel, is private: never widen on data this build cannot read.
387    pub fn from_stored(privacy: &str, channel_id: Option<String>) -> Self {
388        match (privacy, channel_id) {
389            ("global", _) => Self::global(),
390            ("channel", Some(channel)) => Self::channel(channel),
391            _ => Self::private(),
392        }
393    }
394
395    /// The access that satisfies both sides. Used when two writes land on
396    /// one record, so restating something can never widen who sees it.
397    pub fn narrowest(&self, other: &Self) -> Self {
398        match (self.privacy, other.privacy) {
399            (FactPrivacy::Private, _) | (_, FactPrivacy::Private) => Self::private(),
400            (FactPrivacy::Global, _) => other.clone(),
401            (_, FactPrivacy::Global) => self.clone(),
402            (FactPrivacy::Channel, FactPrivacy::Channel) => {
403                if self.channel_id == other.channel_id {
404                    self.clone()
405                } else {
406                    Self::private()
407                }
408            }
409        }
410    }
411}
412
413/// Who a recall is for, as the host knows it. Uses the same visibility rule
414/// as the daemon's own store.
415#[derive(Debug, Clone, PartialEq, Eq)]
416pub struct RecallAudience {
417    pub visibility: ChannelVisibility,
418    pub channel_id: Option<String>,
419    pub requester_is_owner: bool,
420}
421
422impl RecallAudience {
423    pub fn new(
424        visibility: ChannelVisibility,
425        channel_id: Option<String>,
426        requester_is_owner: bool,
427    ) -> Self {
428        Self {
429            visibility,
430            channel_id,
431            requester_is_owner,
432        }
433    }
434
435    /// The owner in a direct conversation: sees everything in the scope.
436    pub fn owner() -> Self {
437        Self::new(ChannelVisibility::Private, None, true)
438    }
439
440    /// From a host's stored visibility text. An unrecognized value is the
441    /// most restrictive visibility, unlike
442    /// [`ChannelVisibility::from_str_lossy`], which defaults to `Internal`.
443    pub fn from_stored(
444        visibility: &str,
445        channel_id: Option<String>,
446        requester_is_owner: bool,
447    ) -> Self {
448        let visibility = match visibility {
449            "private" => ChannelVisibility::Private,
450            "private_group" => ChannelVisibility::PrivateGroup,
451            "public" => ChannelVisibility::Public,
452            "internal" => ChannelVisibility::Internal,
453            _ => ChannelVisibility::PublicExternal,
454        };
455        Self::new(visibility, channel_id, requester_is_owner)
456    }
457
458    /// Whether this audience may see a record with `access`. `None` means
459    /// the store could not say, which is treated as private.
460    pub fn may_see(&self, access: Option<&FactAccess>) -> bool {
461        let private = FactAccess::private();
462        let access = access.unwrap_or(&private);
463        memory_visible(
464            &ExactChannelIds,
465            access.privacy,
466            access.channel_id.as_deref(),
467            self.channel_id.as_deref(),
468            self.visibility,
469            self.requester_is_owner,
470        )
471    }
472
473    /// Sees every record whatever its access, so no lookup is needed.
474    pub fn sees_everything(&self) -> bool {
475        self.may_see(None)
476    }
477
478    /// The access of something learned in this audience's conversation:
479    /// a shared channel's record stays in that channel, anything else is
480    /// private. Sharing wider is a deliberate call to
481    /// [`crate::Memory::remember_with`].
482    pub fn access_for_writes(&self) -> FactAccess {
483        match (self.visibility, &self.channel_id) {
484            (ChannelVisibility::PrivateGroup | ChannelVisibility::Public, Some(channel_id)) => {
485                FactAccess::channel(channel_id.clone())
486            }
487            _ => FactAccess::private(),
488        }
489    }
490}
491
492/// The independently bounded retrieval signals behind a score (port of
493/// the daemon's `HybridSignals`). All 0.0-1.0.
494#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
495pub struct Signals {
496    pub semantic: f32,
497    pub lexical: f32,
498    pub graph: f32,
499    pub freshness: f32,
500    pub confidence: f32,
501    pub provenance: f32,
502}
503
504/// A scorer's verdict on one candidate.
505#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
506pub struct Score {
507    pub value: f32,
508    pub signals: Signals,
509}
510
511/// A recalled fact with its score.
512#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
513pub struct ScoredFact {
514    pub fact: Fact,
515    pub score: f32,
516    pub signals: Signals,
517}
518
519/// A recalled episode with its score.
520#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
521pub struct ScoredEpisode {
522    pub episode: Episode,
523    pub score: f32,
524    pub signals: Signals,
525}
526
527/// Counts reported by [`crate::MemoryStore::stats`].
528#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
529pub struct MemoryStats {
530    pub active_facts: u64,
531    pub superseded_facts: u64,
532    pub episodes: u64,
533    pub scopes: u64,
534}
535
536/// What one [`crate::Memory::decay`] pass changed.
537#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
538pub struct DecayReport {
539    /// Active facts whose recall count was lowered.
540    pub facts_decayed: u64,
541    pub episodes_decayed: u64,
542    /// Superseded fact versions deleted after the retention window.
543    pub superseded_deleted: u64,
544    /// Never-recalled episodes deleted after the retention window.
545    pub episodes_deleted: u64,
546}
547
548/// Decay and retention windows (ports of the daemon's `decay_memories` and
549/// `RetentionConfig` defaults). `None` disables a step.
550#[derive(Debug, Clone, Copy, PartialEq)]
551pub struct RetentionConfig {
552    /// Facts not recalled for this long lose a tenth of their recall count
553    /// (at least one) per pass. Default 14 days.
554    pub fact_recall_decay_after: Option<chrono::Duration>,
555    /// Episodes not recalled for this long lose one recall per pass.
556    /// Default 30 days.
557    pub episode_recall_decay_after: Option<chrono::Duration>,
558    /// Superseded fact versions older than this are deleted. Default 90 days.
559    pub superseded_retention: Option<chrono::Duration>,
560    /// Episodes never recalled and older than this are deleted. Default 365
561    /// days.
562    pub episode_retention: Option<chrono::Duration>,
563}
564
565impl Default for RetentionConfig {
566    fn default() -> Self {
567        Self {
568            fact_recall_decay_after: Some(chrono::Duration::days(14)),
569            episode_recall_decay_after: Some(chrono::Duration::days(30)),
570            superseded_retention: Some(chrono::Duration::days(90)),
571            episode_retention: Some(chrono::Duration::days(365)),
572        }
573    }
574}
575
576/// Fixed-width UTC timestamp so text comparison equals time comparison.
577pub(crate) fn ts(t: DateTime<Utc>) -> String {
578    t.to_rfc3339_opts(SecondsFormat::Micros, true)
579}
580
581pub(crate) fn parse_ts(s: &str) -> Option<DateTime<Utc>> {
582    DateTime::parse_from_rfc3339(s)
583        .ok()
584        .map(|t| t.with_timezone(&Utc))
585}
586
587/// Truncate to at most `max` characters on a char boundary.
588pub(crate) fn truncate_chars(s: &str, max: usize) -> String {
589    match s.char_indices().nth(max) {
590        Some((at, _)) => s[..at].to_string(),
591        None => s.to_string(),
592    }
593}
594
595pub(crate) fn new_id() -> String {
596    uuid::Uuid::new_v4().to_string()
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn keys_and_categories_are_canonical() {
605        assert_eq!(normalize_key("  Favorite Color "), "favorite_color");
606        assert_eq!(normalize_key("dog-name"), "dog_name");
607        assert_eq!(normalize_category(" Preference "), "preference");
608        assert!(same_value("Dark  Mode", "dark mode"));
609        assert!(!same_value("dark mode", "light mode"));
610    }
611
612    #[test]
613    fn stored_access_fails_closed() {
614        assert_eq!(
615            FactAccess::from_stored("global", None),
616            FactAccess::global()
617        );
618        assert_eq!(
619            FactAccess::from_stored("channel", Some("c1".into())),
620            FactAccess::channel("c1")
621        );
622        for unreadable in ["", "GLOBAL", "public", "everyone"] {
623            assert_eq!(
624                FactAccess::from_stored(unreadable, None),
625                FactAccess::private(),
626                "{unreadable}"
627            );
628        }
629        // A channel level that names no channel cannot be scoped.
630        assert_eq!(
631            FactAccess::from_stored("channel", None),
632            FactAccess::private()
633        );
634    }
635
636    #[test]
637    fn merged_access_never_widens() {
638        let (private, global) = (FactAccess::private(), FactAccess::global());
639        let (one, two) = (FactAccess::channel("c1"), FactAccess::channel("c2"));
640        assert_eq!(global.narrowest(&global), global);
641        assert_eq!(global.narrowest(&one), one);
642        assert_eq!(one.narrowest(&global), one);
643        assert_eq!(one.narrowest(&one), one);
644        assert_eq!(one.narrowest(&two), private);
645        assert_eq!(private.narrowest(&global), private);
646        assert_eq!(global.narrowest(&private), private);
647    }
648
649    #[test]
650    fn audience_visibility_matches_the_daemon_rule() {
651        use ChannelVisibility as V;
652        let group = RecallAudience::new(V::PrivateGroup, Some("c1".into()), true);
653        assert!(!group.may_see(Some(&FactAccess::private())));
654        assert!(group.may_see(Some(&FactAccess::global())));
655        assert!(group.may_see(Some(&FactAccess::channel("c1"))));
656        assert!(!group.may_see(Some(&FactAccess::channel("c2"))));
657        assert!(!group.may_see(None), "an unknown level is private");
658
659        let public = RecallAudience::new(V::Public, Some("c1".into()), true);
660        assert!(!public.may_see(Some(&FactAccess::private())));
661        assert!(!public.may_see(Some(&FactAccess::global())));
662
663        let external = RecallAudience::new(V::PublicExternal, Some("c1".into()), true);
664        assert!(!external.may_see(Some(&FactAccess::global())));
665        assert!(!external.may_see(Some(&FactAccess::channel("c1"))));
666
667        let guest_dm = RecallAudience::new(V::Private, None, false);
668        assert!(!guest_dm.may_see(Some(&FactAccess::private())));
669        assert!(guest_dm.may_see(Some(&FactAccess::global())));
670
671        assert!(RecallAudience::owner().sees_everything());
672        assert!(RecallAudience::new(V::Internal, None, true).sees_everything());
673        assert!(!group.sees_everything());
674    }
675
676    #[test]
677    fn unknown_visibility_text_is_the_most_restrictive() {
678        for unknown in ["", "PUBLIC", "dm", "internal "] {
679            let audience = RecallAudience::from_stored(unknown, None, true);
680            assert_eq!(audience.visibility, ChannelVisibility::PublicExternal);
681            assert!(!audience.may_see(Some(&FactAccess::global())));
682        }
683        assert_eq!(
684            RecallAudience::from_stored("private_group", None, true).visibility,
685            ChannelVisibility::PrivateGroup
686        );
687    }
688
689    #[test]
690    fn writes_stay_in_the_conversation_they_came_from() {
691        use ChannelVisibility as V;
692        let in_channel = |v| RecallAudience::new(v, Some("c1".into()), true).access_for_writes();
693        assert_eq!(in_channel(V::PrivateGroup), FactAccess::channel("c1"));
694        assert_eq!(in_channel(V::Public), FactAccess::channel("c1"));
695        assert_eq!(in_channel(V::Private), FactAccess::private());
696        assert_eq!(in_channel(V::Internal), FactAccess::private());
697        assert_eq!(in_channel(V::PublicExternal), FactAccess::private());
698        assert_eq!(
699            RecallAudience::new(V::Public, None, true).access_for_writes(),
700            FactAccess::private()
701        );
702    }
703
704    #[test]
705    fn invalid_facts_are_rejected() {
706        assert!(NewFact::new("s", "user", "", "x").normalized().is_err());
707        assert!(NewFact::new("", "user", "k", "x").normalized().is_err());
708        let f = NewFact::new("s", "user", "k", "x")
709            .confidence(7.0)
710            .normalized()
711            .unwrap();
712        assert_eq!(f.confidence, 1.0);
713    }
714}