agents-kit 0.0.1

Rust agent control Kit for Codex, OpenCode, and provider-backed Custom runtimes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Inputs for privately managed knowledge ingestion and retrieval policy.
//!
//! These values carry caller-authored sources and scope choices, not retrieval
//! internals or Database adapters. Nonempty ingestion atomically replaces the
//! addressed source set. An empty request is a **no-op after scope validation**;
//! it is not a deletion request. The receiving operation validates which scopes
//! it owns and whether the selected backend supports managed knowledge.
//!
//! Retrieval is private and happens during a prompt. [`KnowledgePolicy::only`]
//! narrows eligible owner scopes; it does not promise that a model will quote
//! every source or follow requested wording. Database scope is shared only when
//! callers deliberately supply the same Database domain. Agent and Workspace
//! shutdown preserve sources for reopen; Conversation close removes its owned
//! sources. Reopen must receive a compatible Database as well as control-plane
//! storage; missing or mismatched persisted knowledge is an error.
//!
//! # Local ingestion and scope validation
//!
//! This executes ingestion with embedded Lance StateStore and memory LanceDB
//! Database, without inference or an Ollama server. These are separate products:
//! the StateStore holds control-plane records; the Database holds source content.
//! The request carries sources, never private retrieval context or an adapter.
//!
//! ```
//! use std::{num::NonZeroUsize, time::Duration};
//! use agents_kit::{AgentBackend, AgentBuilder, AgentStorage};
//! use agents_kit::config::{AgentConfig, CustomAgentConfig, CustomLoopLimits, CustomToolApproval};
//! use agents_kit::knowledge::{IngestKnowledgeRequest, KnowledgePolicy, KnowledgeScope, KnowledgeSource};
//! use agents_kit::{model::ModelSelector, tool::ToolSelection};
//! use providers_kit::{Provider, ProviderConfig,
//!     config::{OllamaConfig, ProviderKind, TransportConfig}};
//! use storage_kit::{Database, StateStore,
//!     database::config::{DatabaseConfig, LanceConfig},
//!     state::config::{LanceStateStoreConfig, StateStoreConfig}};
//! # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
//! # runtime.block_on(async {
//! let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory())).await?;
//! let database = Database::connect(DatabaseConfig::lance(
//!     LanceConfig::embedded_path("memory://"))).await?;
//! let custom = CustomAgentConfig::new(ModelSelector::new("exact-model")?,
//!     ToolSelection::None, CustomLoopLimits::new(4, 0, 1)?, CustomToolApproval::Deny)?;
//! let config = AgentConfig::new(custom.into(), Duration::from_secs(10), NonZeroUsize::MIN)?;
//! let provider = Provider::from_config(ProviderConfig::new(
//!     ProviderKind::Ollama(OllamaConfig::local()), TransportConfig::default()))?;
//! let agent = AgentBuilder::create(config, AgentStorage::new(store))
//!     .with_provider(provider).with_knowledge_database(database).build().await?;
//! let outcome = async {
//!     agent.ingest_knowledge(IngestKnowledgeRequest::new(vec![
//!         KnowledgeSource::text("runbook", "Incident runbook", "Escalate service incidents.")?,
//!     ])?.with_scope(KnowledgeScope::Agent)).await?;
//!     agent.ingest_knowledge(IngestKnowledgeRequest::new(vec![])?
//!         .with_scope(KnowledgeScope::Agent)).await?; // retains the runbook
//!     let invalid = agent.ingest_knowledge(IngestKnowledgeRequest::new(vec![])?
//!         .with_scope(KnowledgeScope::Conversation)).await.unwrap_err();
//!     assert_eq!(invalid.kind(), agents_kit::error::ErrorKind::InvalidInput);
//!     let request = agents_kit::prompt::PromptRequest::new("How are incidents escalated?")?
//!         .with_knowledge_policy(KnowledgePolicy::only(vec![KnowledgeScope::Agent])?)?;
//!     assert_eq!(request.knowledge_policy(),
//!         Some(&KnowledgePolicy::Only(vec![KnowledgeScope::Agent])));
//!     // Sending this request through a Conversation requires the configured model.
//!     Ok::<(), Box<dyn std::error::Error>>(())
//! }.await;
//! let shutdown = agent.shutdown().await;
//! outcome?;
//! shutdown?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! # })?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::{BTreeMap, BTreeSet};

use crate::{AgentId, ConversationId, KitError, WorkspaceId};

const RETRIEVAL_SCOPE_ORDER: [KnowledgeScope; 4] = [
    KnowledgeScope::Conversation,
    KnowledgeScope::Workspace,
    KnowledgeScope::Agent,
    KnowledgeScope::Database,
];

/// Complete portable lineage for one semantic-knowledge owner.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(tag = "scope", rename_all = "snake_case")]
pub(crate) enum KnowledgeOwnerId {
    /// Shared data in the caller-supplied managed Database domain.
    Database,
    /// Data owned by one agent.
    Agent {
        /// Owning durable agent identity.
        agent_id: AgentId,
    },
    /// Data owned by one workspace and its agent.
    Workspace {
        /// Owning durable agent identity.
        agent_id: AgentId,
        /// Owning durable workspace identity.
        workspace_id: WorkspaceId,
    },
    /// Data owned by one conversation, workspace, and agent.
    Conversation {
        /// Owning durable agent identity.
        agent_id: AgentId,
        /// Owning durable workspace identity.
        workspace_id: WorkspaceId,
        /// Owning durable conversation identity.
        conversation_id: ConversationId,
    },
}

/// Positive limits for one structured knowledge response.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct KnowledgeBudget {
    chunks: usize,
    bytes: usize,
}

/// Validated semantic retrieval input.
#[derive(Clone, Debug)]
pub(crate) struct KnowledgeRetrievalRequest {
    query: String,
    owner: KnowledgeOwnerId,
    policy: KnowledgePolicy,
    budget: KnowledgeBudget,
}

/// Structured semantic context returned by a knowledge implementation.
#[derive(Clone, Debug)]
pub(crate) struct KnowledgeContext {
    snippets: Vec<KnowledgeSnippet>,
}

/// One ranked piece of structured semantic context.
#[derive(Clone, Debug)]
pub(crate) struct KnowledgeSnippet {
    source_id: String,
    title: String,
    text: String,
    owner: KnowledgeOwnerId,
    relevance_score: Option<f64>,
    provenance: KnowledgeProvenance,
    metadata: BTreeMap<String, serde_json::Value>,
}

/// Optional source location and structured provenance metadata.
#[derive(Clone, Debug, Default)]
pub(crate) struct KnowledgeProvenance {
    locator: Option<String>,
    metadata: BTreeMap<String, serde_json::Value>,
}

#[derive(
    Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
)]
#[serde(rename_all = "snake_case")]
/// A portable ownership scope from which managed knowledge may be retrieved.
pub enum KnowledgeScope {
    /// Sources shared through the caller-supplied managed Database domain.
    Database,
    /// Sources owned by the agent.
    Agent,
    /// Sources owned by the current workspace.
    Workspace,
    /// Sources owned by the current conversation.
    Conversation,
}

/// Retrieval policy for managed knowledge.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgePolicy {
    /// Applies normal inherited retrieval behavior.
    Default,
    /// Excludes managed-knowledge retrieval.
    Disabled,
    /// Retrieves only from the selected ownership scopes.
    Only(
        /// A nonempty selection without duplicate scopes.
        Vec<KnowledgeScope>,
    ),
}

impl KnowledgePolicy {
    /// Validates and constructs an exact scope selection.
    ///
    /// # Errors
    /// Returns InvalidInput for no scopes or duplicate scopes.
    ///
    /// ```
    /// use agents_kit::knowledge::{KnowledgePolicy, KnowledgeScope};
    /// let policy = KnowledgePolicy::only(vec![KnowledgeScope::Workspace])?;
    /// assert_eq!(policy, KnowledgePolicy::Only(vec![KnowledgeScope::Workspace]));
    /// assert!(KnowledgePolicy::only(vec![]).is_err());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn only(scopes: Vec<KnowledgeScope>) -> Result<Self, KitError> {
        let policy = Self::Only(scopes);
        policy.validate()?;
        Ok(policy)
    }

    pub(crate) fn validate(&self) -> Result<(), KitError> {
        let Self::Only(scopes) = self else {
            return Ok(());
        };
        if scopes.is_empty() {
            return Err(KitError::invalid_input(
                "knowledge scope selection must not be empty",
            ));
        }
        let mut sorted = scopes.clone();
        sorted.sort();
        sorted.dedup();
        if sorted.len() != scopes.len() {
            return Err(KitError::invalid_input(
                "knowledge scope selection must not contain duplicates",
            ));
        }
        Ok(())
    }
}

/// Caller-authored content for managed-knowledge ingestion.
///
/// Prefer [`KnowledgeSource::text`] and [`KnowledgeSource::bytes`] so source
/// identity and content are validated at construction.
///
/// # Examples
///
/// ```
/// use agents_kit::knowledge::{IngestKnowledgeRequest, KnowledgeSource};
///
/// let source = KnowledgeSource::text(
///     "operations-handbook",
///     "Operations handbook",
///     "Escalate service incidents.",
/// )?;
/// let request = IngestKnowledgeRequest::new(vec![source])?;
/// assert_eq!(request.sources()[0].source_id(), "operations-handbook");
/// # Ok::<(), agents_kit::KitError>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum KnowledgeSource {
    /// UTF-8 source content.
    Text {
        /// Stable caller-owned source identity.
        source_id: String,
        /// Human-readable source title.
        title: String,
        /// Nonempty UTF-8 source content.
        text: String,
    },
    /// Binary source content with an explicit MIME type.
    Bytes {
        /// Stable caller-owned source identity.
        source_id: String,
        /// Human-readable source title.
        title: String,
        /// Nonempty exact source bytes.
        bytes: Vec<u8>,
        /// Nonempty unpadded MIME type.
        mime_type: String,
    },
}

impl KnowledgeSource {
    /// Validates and constructs a text source.
    ///
    /// # Errors
    /// Returns InvalidInput for empty content, or empty/padded source identity or title. Text content itself is preserved exactly.
    ///
    /// ```
    /// use agents_kit::knowledge::KnowledgeSource;
    /// let source = KnowledgeSource::text("guide", "Guide", " Keep this spacing. ")?;
    /// assert_eq!(source.source_id(), "guide");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn text(
        source_id: impl Into<String>,
        title: impl Into<String>,
        text: impl Into<String>,
    ) -> Result<Self, KitError> {
        let source = Self::Text {
            source_id: source_id.into(),
            title: title.into(),
            text: text.into(),
        };
        source.validate()?;
        Ok(source)
    }

    /// Validates and constructs a binary source.
    ///
    /// # Errors
    /// Returns InvalidInput for empty bytes, or empty/padded source identity, title, or MIME type.
    ///
    /// ```
    /// use agents_kit::knowledge::KnowledgeSource;
    /// let source = KnowledgeSource::bytes("file", "File", vec![1, 2], "application/octet-stream")?;
    /// assert_eq!(source.title(), "File");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn bytes(
        source_id: impl Into<String>,
        title: impl Into<String>,
        bytes: Vec<u8>,
        mime_type: impl Into<String>,
    ) -> Result<Self, KitError> {
        let source = Self::Bytes {
            source_id: source_id.into(),
            title: title.into(),
            bytes,
            mime_type: mime_type.into(),
        };
        source.validate()?;
        Ok(source)
    }

    /// Returns the stable caller-owned source identity.
    ///
    /// ```
    /// use agents_kit::knowledge::KnowledgeSource;
    /// let source = KnowledgeSource::text("guide", "Guide", "contents")?;
    /// assert_eq!(source.source_id(), "guide");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn source_id(&self) -> &str {
        match self {
            Self::Text { source_id, .. } | Self::Bytes { source_id, .. } => source_id,
        }
    }

    /// Returns the human-readable title.
    ///
    /// ```
    /// use agents_kit::knowledge::KnowledgeSource;
    /// let source = KnowledgeSource::text("guide", "Guide", "contents")?;
    /// assert_eq!(source.title(), "Guide");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn title(&self) -> &str {
        match self {
            Self::Text { title, .. } | Self::Bytes { title, .. } => title,
        }
    }

    pub(crate) fn validate(&self) -> Result<(), KitError> {
        let (source_id, title) = match self {
            Self::Text {
                source_id,
                title,
                text,
            } => {
                if text.is_empty() {
                    return Err(KitError::invalid_input("knowledge text must not be empty"));
                }
                (source_id, title)
            }
            Self::Bytes {
                source_id,
                title,
                bytes,
                mime_type,
            } => {
                if bytes.is_empty() {
                    return Err(KitError::invalid_input("knowledge bytes must not be empty"));
                }
                Self::validate_text("knowledge MIME type", mime_type)?;
                (source_id, title)
            }
        };
        Self::validate_text("knowledge source id", source_id)?;
        Self::validate_text("knowledge source title", title)
    }

    fn validate_text(label: &str, value: &str) -> Result<(), KitError> {
        if value.is_empty() || value.trim() != value {
            return Err(KitError::invalid_input(format!(
                "{label} must be nonempty and unpadded"
            )));
        }
        Ok(())
    }
}

/// Validated source set for one managed-knowledge ingestion operation.
///
/// ```
/// use agents_kit::knowledge::{IngestKnowledgeRequest, KnowledgeSource};
/// let request = IngestKnowledgeRequest::new(vec![
///     KnowledgeSource::text("guide", "Guide", "Escalate incidents.")?,
/// ])?;
/// assert_eq!(request.sources().len(), 1);
/// # Ok::<(), agents_kit::KitError>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IngestKnowledgeRequest {
    sources: Vec<KnowledgeSource>,
    scope: Option<KnowledgeScope>,
}

impl IngestKnowledgeRequest {
    /// Validates sources and rejects duplicate source identities.
    ///
    /// # Errors
    /// Returns InvalidInput for invalid sources or repeated source identities. An empty source set is valid and is a no-op after the receiving operation validates the selected scope; it never requests deletion.
    ///
    /// ```
    /// use agents_kit::knowledge::IngestKnowledgeRequest;
    /// let request = IngestKnowledgeRequest::new(vec![])?;
    /// assert!(request.sources().is_empty());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn new(sources: Vec<KnowledgeSource>) -> Result<Self, KitError> {
        let request = Self {
            sources,
            scope: None,
        };
        request.validate()?;
        Ok(request)
    }

    /// Selects an explicit scope instead of the receiving operation's default.
    #[must_use]
    ///
    /// ```
    /// use agents_kit::knowledge::{IngestKnowledgeRequest, KnowledgeScope};
    /// let request = IngestKnowledgeRequest::new(vec![])?.with_scope(KnowledgeScope::Workspace);
    /// assert_eq!(request.scope(), Some(KnowledgeScope::Workspace));
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn with_scope(mut self, scope: KnowledgeScope) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Borrows the validated sources in caller-provided order.
    ///
    /// ```
    /// use agents_kit::knowledge::{IngestKnowledgeRequest, KnowledgeSource};
    /// let request = IngestKnowledgeRequest::new(vec![KnowledgeSource::text("guide", "Guide", "contents")?])?;
    /// assert_eq!(request.sources()[0].source_id(), "guide");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn sources(&self) -> &[KnowledgeSource] {
        &self.sources
    }

    /// Returns the explicitly selected scope, when present.
    #[must_use]
    ///
    /// ```
    /// use agents_kit::knowledge::IngestKnowledgeRequest;
    /// assert_eq!(IngestKnowledgeRequest::new(vec![])?.scope(), None);
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn scope(&self) -> Option<KnowledgeScope> {
        self.scope
    }

    /// Consumes the request into validated sources and optional scope.
    #[must_use]
    ///
    /// ```
    /// use agents_kit::knowledge::IngestKnowledgeRequest;
    /// let (sources, scope) = IngestKnowledgeRequest::new(vec![])?.into_parts();
    /// assert!(sources.is_empty());
    /// assert_eq!(scope, None);
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn into_parts(self) -> (Vec<KnowledgeSource>, Option<KnowledgeScope>) {
        (self.sources, self.scope)
    }

    pub(crate) fn validate(&self) -> Result<(), KitError> {
        let mut ids = std::collections::BTreeSet::new();
        for source in &self.sources {
            source.validate()?;
            if !ids.insert(source.source_id()) {
                return Err(KitError::invalid_input(
                    "knowledge source ids must be unique within one request",
                ));
            }
        }
        Ok(())
    }
}

impl KnowledgeOwnerId {
    fn scope(&self) -> KnowledgeScope {
        match self {
            Self::Database => KnowledgeScope::Database,
            Self::Agent { .. } => KnowledgeScope::Agent,
            Self::Workspace { .. } => KnowledgeScope::Workspace,
            Self::Conversation { .. } => KnowledgeScope::Conversation,
        }
    }

    fn owner_for_scope(&self, scope: KnowledgeScope) -> Option<Self> {
        match (self, scope) {
            (Self::Database, KnowledgeScope::Database)
            | (Self::Agent { .. }, KnowledgeScope::Database)
            | (Self::Workspace { .. }, KnowledgeScope::Database)
            | (Self::Conversation { .. }, KnowledgeScope::Database) => Some(Self::Database),
            (Self::Agent { agent_id }, KnowledgeScope::Agent)
            | (Self::Workspace { agent_id, .. }, KnowledgeScope::Agent)
            | (Self::Conversation { agent_id, .. }, KnowledgeScope::Agent) => Some(Self::Agent {
                agent_id: agent_id.clone(),
            }),
            (
                Self::Workspace {
                    agent_id,
                    workspace_id,
                },
                KnowledgeScope::Workspace,
            )
            | (
                Self::Conversation {
                    agent_id,
                    workspace_id,
                    ..
                },
                KnowledgeScope::Workspace,
            ) => Some(Self::Workspace {
                agent_id: agent_id.clone(),
                workspace_id: workspace_id.clone(),
            }),
            (
                Self::Conversation {
                    agent_id,
                    workspace_id,
                    conversation_id,
                },
                KnowledgeScope::Conversation,
            ) => Some(Self::Conversation {
                agent_id: agent_id.clone(),
                workspace_id: workspace_id.clone(),
                conversation_id: conversation_id.clone(),
            }),
            _ => None,
        }
    }

    pub(crate) fn ingestion_owner(
        &self,
        selected: Option<KnowledgeScope>,
    ) -> Result<Self, KitError> {
        self.owner_for_scope(selected.unwrap_or_else(|| self.scope()))
            .ok_or_else(|| {
                KitError::invalid_input(
                    "selected knowledge scope is not applicable to this receiver",
                )
            })
    }

    pub(crate) fn retrieval_owners(&self, policy: &KnowledgePolicy) -> Result<Vec<Self>, KitError> {
        policy.validate()?;
        let selected = match policy {
            KnowledgePolicy::Default => None,
            KnowledgePolicy::Disabled => return Ok(Vec::new()),
            KnowledgePolicy::Only(scopes) => {
                for scope in scopes {
                    if self.owner_for_scope(*scope).is_none() {
                        return Err(KitError::invalid_input(
                            "selected knowledge scope is not applicable to this owner",
                        ));
                    }
                }
                Some(scopes.iter().copied().collect::<BTreeSet<_>>())
            }
        };
        Ok(RETRIEVAL_SCOPE_ORDER
            .into_iter()
            .filter(|scope| {
                selected
                    .as_ref()
                    .is_none_or(|selected| selected.contains(scope))
            })
            .filter_map(|scope| self.owner_for_scope(scope))
            .collect())
    }
}

impl KnowledgeBudget {
    /// Constructs positive chunk and UTF-8 text-byte limits.
    pub(crate) fn new(chunks: usize, bytes: usize) -> Result<Self, KitError> {
        if chunks == 0 || bytes == 0 {
            return Err(KitError::invalid_input(
                "knowledge chunk and byte budgets must be positive",
            ));
        }
        Ok(Self { chunks, bytes })
    }

    /// Returns the maximum number of snippets.
    #[must_use]
    pub(crate) fn chunks(&self) -> usize {
        self.chunks
    }

    /// Returns the maximum aggregate snippet-text bytes.
    #[must_use]
    pub(crate) fn bytes(&self) -> usize {
        self.bytes
    }
}

impl KnowledgeRetrievalRequest {
    /// Validates and constructs one semantic retrieval request.
    pub(crate) fn new(
        query: String,
        owner: KnowledgeOwnerId,
        policy: KnowledgePolicy,
        budget: KnowledgeBudget,
    ) -> Result<Self, KitError> {
        let request = Self {
            query,
            owner,
            policy,
            budget,
        };
        request.validate()?;
        Ok(request)
    }

    /// Returns the exact caller-authored query.
    pub(crate) fn query(&self) -> &str {
        &self.query
    }

    /// Returns the complete requested owner lineage.
    pub(crate) fn owner(&self) -> &KnowledgeOwnerId {
        &self.owner
    }

    /// Returns the validated retrieval policy.
    pub(crate) fn policy(&self) -> &KnowledgePolicy {
        &self.policy
    }

    /// Returns the response budget.
    #[must_use]
    pub(crate) fn budget(&self) -> KnowledgeBudget {
        self.budget
    }

    pub(crate) fn validate(&self) -> Result<(), KitError> {
        if self.query.is_empty() || self.query.trim() != self.query {
            return Err(KitError::invalid_input(
                "knowledge query must be nonempty and unpadded",
            ));
        }
        self.owner.retrieval_owners(&self.policy).map(|_| ())
    }

    pub(crate) fn validate_context(&self, context: &KnowledgeContext) -> Result<(), KitError> {
        self.validate()?;
        context
            .validate()
            .map_err(|_| KitError::invalid_state("knowledge backend returned malformed context"))?;
        if context.snippets.len() > self.budget.chunks {
            return Err(KitError::invalid_state(
                "knowledge backend exceeded the requested chunk budget",
            ));
        }
        let allowed = self.owner.retrieval_owners(&self.policy)?;
        let mut previous_scope = None;
        let mut text_bytes = 0_usize;
        for snippet in &context.snippets {
            let scope = allowed
                .iter()
                .position(|owner| owner == &snippet.owner)
                .ok_or_else(|| {
                    KitError::invalid_state(
                        "knowledge backend returned an owner outside the requested lineage",
                    )
                })?;
            if previous_scope.is_some_and(|previous| scope < previous) {
                return Err(KitError::invalid_state(
                    "knowledge backend returned snippets outside policy precedence",
                ));
            }
            previous_scope = Some(scope);
            text_bytes = text_bytes.checked_add(snippet.text.len()).ok_or_else(|| {
                KitError::invalid_state("knowledge backend text-byte count overflowed")
            })?;
            if text_bytes > self.budget.bytes {
                return Err(KitError::invalid_state(
                    "knowledge backend exceeded the requested byte budget",
                ));
            }
        }
        Ok(())
    }
}

impl KnowledgeContext {
    /// Validates and constructs structured context.
    pub(crate) fn new(snippets: Vec<KnowledgeSnippet>) -> Result<Self, KitError> {
        let context = Self { snippets };
        context.validate()?;
        Ok(context)
    }

    /// Borrows snippets in semantic precedence and backend rank order.
    pub(crate) fn snippets(&self) -> &[KnowledgeSnippet] {
        &self.snippets
    }

    fn validate(&self) -> Result<(), KitError> {
        for snippet in &self.snippets {
            snippet.validate()?;
        }
        Ok(())
    }
}

impl KnowledgeSnippet {
    /// Validates and constructs one structured knowledge snippet.
    pub(crate) fn new(
        source_id: String,
        title: String,
        text: String,
        owner: KnowledgeOwnerId,
        relevance_score: Option<f64>,
        provenance: KnowledgeProvenance,
        metadata: BTreeMap<String, serde_json::Value>,
    ) -> Result<Self, KitError> {
        let snippet = Self {
            source_id,
            title,
            text,
            owner,
            relevance_score,
            provenance,
            metadata,
        };
        snippet.validate()?;
        Ok(snippet)
    }

    /// Returns the caller-owned source identity.
    pub(crate) fn source_id(&self) -> &str {
        &self.source_id
    }

    /// Returns the human-readable source title.
    pub(crate) fn title(&self) -> &str {
        &self.title
    }

    /// Returns exact snippet text.
    pub(crate) fn text(&self) -> &str {
        &self.text
    }

    fn validate(&self) -> Result<(), KitError> {
        for (label, value) in [
            ("knowledge source id", self.source_id.as_str()),
            ("knowledge source title", self.title.as_str()),
        ] {
            if value.is_empty() || value.trim() != value {
                return Err(KitError::invalid_input(format!(
                    "{label} must be nonempty and unpadded"
                )));
            }
        }
        if self.text.trim().is_empty() {
            return Err(KitError::invalid_input(
                "knowledge snippet text must be nonblank",
            ));
        }
        if self
            .relevance_score
            .is_some_and(|score| !score.is_finite() || score < 0.0)
        {
            return Err(KitError::invalid_input(
                "knowledge relevance score must be finite and nonnegative",
            ));
        }
        self.provenance.validate()?;
        if self
            .metadata
            .keys()
            .any(|key| key.is_empty() || key.trim() != key)
        {
            return Err(KitError::invalid_input(
                "knowledge metadata keys must be nonempty and unpadded",
            ));
        }
        Ok(())
    }
}

impl KnowledgeProvenance {
    fn validate(&self) -> Result<(), KitError> {
        if self
            .locator
            .as_ref()
            .is_some_and(|locator| locator.is_empty() || locator.trim() != locator)
        {
            return Err(KitError::invalid_input(
                "knowledge provenance locator must be nonempty and unpadded",
            ));
        }
        if self
            .metadata
            .keys()
            .any(|key| key.is_empty() || key.trim() != key)
        {
            return Err(KitError::invalid_input(
                "knowledge provenance metadata keys must be nonempty and unpadded",
            ));
        }
        Ok(())
    }
}