1use std::sync::Arc;
42
43use greentic_aw_runtime::AgentRuntime;
44use greentic_aw_runtime::config::MemoryProviderRef;
45use greentic_aw_runtime::knowledge::{
46 IngestOutcome, Knowledge, KnowledgeChunk, KnowledgeError, KnowledgeQuery, KnowledgeResult,
47 RetrievedChunk,
48};
49use greentic_ext_runtime::ExtensionRuntime;
50use greentic_ext_runtime::host_ports::HostCallContext;
51use greentic_types::TenantCtx;
52
53pub const EXTENSION_PROVIDER_ID: &str = "provider.knowledge.extension";
56
57pub const EXTENSION_ID_PARAM: &str = "provider.knowledge.extension.extension_id";
64
65pub const TOOL_NAME_PARAM: &str = "provider.knowledge.extension.tool_name";
68
69const DEFAULT_LIMIT: usize = 5;
72
73pub(crate) const MAX_CHUNK_CHARS: usize = 4_000;
75
76pub(crate) const MAX_TOTAL_CHARS: usize = 24_000;
92
93const BACKEND_ID: &str = "runner-host.knowledge_ext";
100
101#[must_use]
108pub fn attach(base: AgentRuntime, ext: Arc<ExtensionRuntime>) -> AgentRuntime {
109 let inner = base.knowledge_backend();
110 base.with_knowledge(Arc::new(ExtensionKnowledge::new(ext, inner)))
111}
112
113enum Claim {
132 NotOurs,
134 Delegate {
136 extension_id: String,
137 tool_name: String,
138 },
139 Malformed(&'static str),
141}
142
143pub struct ExtensionKnowledge {
145 ext: Arc<ExtensionRuntime>,
146 inner: Option<Arc<dyn Knowledge>>,
149}
150
151impl ExtensionKnowledge {
152 #[must_use]
153 pub fn new(ext: Arc<ExtensionRuntime>, inner: Option<Arc<dyn Knowledge>>) -> Self {
154 Self { ext, inner }
155 }
156
157 fn claim_of(binding: &MemoryProviderRef) -> Claim {
159 if binding.provider != EXTENSION_PROVIDER_ID {
160 return Claim::NotOurs;
161 }
162 let read = |key: &str| -> Option<String> {
163 let value = binding.params.get(key)?.as_str()?.trim();
164 (!value.is_empty()).then(|| value.to_string())
165 };
166 let Some(extension_id) = read(EXTENSION_ID_PARAM) else {
167 return Claim::Malformed(EXTENSION_ID_PARAM);
168 };
169 let Some(tool_name) = read(TOOL_NAME_PARAM) else {
170 return Claim::Malformed(TOOL_NAME_PARAM);
171 };
172 Claim::Delegate {
173 extension_id,
174 tool_name,
175 }
176 }
177
178 async fn delegate_search(
179 &self,
180 tenant: &TenantCtx,
181 query: KnowledgeQuery,
182 binding: Option<&MemoryProviderRef>,
183 ) -> KnowledgeResult<Vec<RetrievedChunk>> {
184 match self.inner.as_ref() {
185 Some(inner) => inner.search_bound(tenant, query, binding).await,
186 None => Err(KnowledgeError::NotConfigured),
187 }
188 }
189}
190
191#[async_trait::async_trait]
192impl Knowledge for ExtensionKnowledge {
193 async fn ingest(
204 &self,
205 tenant: &TenantCtx,
206 chunks: Vec<KnowledgeChunk>,
207 ) -> KnowledgeResult<IngestOutcome> {
208 match self.inner.as_ref() {
209 Some(inner) => inner.ingest(tenant, chunks).await,
210 None => Ok(IngestOutcome::default()),
211 }
212 }
213
214 async fn search(
218 &self,
219 tenant: &TenantCtx,
220 query: KnowledgeQuery,
221 ) -> KnowledgeResult<Vec<RetrievedChunk>> {
222 self.delegate_search(tenant, query, None).await
223 }
224
225 async fn search_bound(
226 &self,
227 tenant: &TenantCtx,
228 query: KnowledgeQuery,
229 binding: Option<&MemoryProviderRef>,
230 ) -> KnowledgeResult<Vec<RetrievedChunk>> {
231 let (extension_id, tool_name) = match binding.map_or(Claim::NotOurs, Self::claim_of) {
232 Claim::NotOurs => return self.delegate_search(tenant, query, binding).await,
233 Claim::Malformed(key) => {
234 return Err(KnowledgeError::Backend(format!(
235 "knowledge binding names `{EXTENSION_PROVIDER_ID}` but its `{key}` param is \
236 missing or blank, so there is no retrieval target to invoke"
237 )));
238 }
239 Claim::Delegate {
240 extension_id,
241 tool_name,
242 } => (extension_id, tool_name),
243 };
244
245 let limit = query.limit.unwrap_or(DEFAULT_LIMIT).max(1);
246 let args = serde_json::json!({
247 "query": query.query,
248 "top_k": limit,
249 "tenant": tenant.tenant.as_str(),
250 "env": tenant.env.as_str(),
251 })
252 .to_string();
253
254 let ctx = HostCallContext {
272 tenant: Some(tenant.tenant.as_str().to_string()),
273 user_email: None,
274 };
275
276 let ext = Arc::clone(&self.ext);
286 let called = {
287 let extension_id = extension_id.clone();
288 let tool_name = tool_name.clone();
289 tokio::task::spawn_blocking(move || {
290 ext.invoke_tool_ctx(&extension_id, &tool_name, &args, &ctx)
291 })
292 .await
293 };
294
295 let raw = called
296 .map_err(|e| {
297 KnowledgeError::Backend(format!(
298 "knowledge retrieval task for '{extension_id}/{tool_name}' did not \
299 complete: {e}"
300 ))
301 })?
302 .map_err(|e| {
303 KnowledgeError::Backend(format!(
304 "knowledge retrieval tool '{extension_id}/{tool_name}' failed: {e}"
305 ))
306 })?;
307
308 parse_chunks(&raw, limit)
309 }
310
311 fn wrapped_backend(&self) -> Option<Arc<dyn Knowledge>> {
317 self.inner.clone()
318 }
319
320 fn backend_id(&self) -> &'static str {
321 BACKEND_ID
322 }
323}
324
325#[must_use]
336pub fn corpus_backend(runtime: &AgentRuntime) -> Option<Arc<dyn Knowledge>> {
337 corpus_in_chain(runtime.knowledge_backend())
338}
339
340fn corpus_in_chain(top: Option<Arc<dyn Knowledge>>) -> Option<Arc<dyn Knowledge>> {
343 let mut current = top;
344 while let Some(backend) = current {
345 let id = backend.backend_id();
346 if id != BACKEND_ID && id != crate::runner::knowledge_index::BACKEND_ID {
347 return Some(backend);
348 }
349 current = backend.wrapped_backend();
350 }
351 None
352}
353
354fn parse_chunks(raw: &str, limit: usize) -> KnowledgeResult<Vec<RetrievedChunk>> {
370 let body: serde_json::Value = serde_json::from_str(raw).map_err(|e| {
371 KnowledgeError::Backend(format!(
372 "knowledge retrieval returned a body that is not JSON: {e}"
373 ))
374 })?;
375
376 let items = body
377 .get("chunks")
378 .and_then(serde_json::Value::as_array)
379 .ok_or_else(|| {
380 KnowledgeError::Backend(
381 "knowledge retrieval returned no `chunks` array; expected \
382 {\"chunks\":[{\"text\":…}]}"
383 .to_string(),
384 )
385 })?;
386
387 let mut out = Vec::with_capacity(items.len().min(limit));
388 let mut budget = MAX_TOTAL_CHARS;
389
390 for (index, item) in items.iter().take(limit).enumerate() {
391 let text = item
392 .get("text")
393 .and_then(serde_json::Value::as_str)
394 .ok_or_else(|| {
395 KnowledgeError::Backend(format!(
396 "knowledge retrieval chunk {index} carries no `text` string"
397 ))
398 })?;
399
400 if budget == 0 {
401 break;
402 }
403 let text = truncate_chars(text, MAX_CHUNK_CHARS.min(budget));
404 budget = budget.saturating_sub(text.chars().count());
405
406 let score = item
413 .get("score")
414 .and_then(serde_json::Value::as_f64)
415 .filter(|s| s.is_finite())
416 .unwrap_or(0.0);
417
418 out.push(RetrievedChunk {
419 text,
420 score,
421 doc_id: item
422 .get("doc_id")
423 .and_then(serde_json::Value::as_str)
424 .map(str::to_string),
425 chunk_index: None,
426 metadata: item
427 .get("metadata")
428 .and_then(serde_json::Value::as_object)
429 .cloned()
430 .unwrap_or_default(),
431 });
432 }
433
434 Ok(out)
435}
436
437pub(crate) fn truncate_chars(text: &str, max: usize) -> String {
440 if text.chars().count() <= max {
441 return text.to_string();
442 }
443 text.chars().take(max).collect()
444}
445
446#[cfg(test)]
447#[allow(clippy::unwrap_used, clippy::expect_used)]
448mod tests {
449 use super::*;
450
451 fn body(chunks: serde_json::Value) -> String {
452 serde_json::json!({ "chunks": chunks }).to_string()
453 }
454
455 #[test]
456 fn a_missing_score_is_zero_and_the_service_order_is_kept() {
457 let raw = body(serde_json::json!([
458 { "text": "first" },
459 { "text": "second", "score": 0.9 },
460 { "text": "third", "score": 0.1 },
461 ]));
462 let chunks = parse_chunks(&raw, 10).expect("a well-formed body parses");
463
464 assert_eq!(
465 chunks.iter().map(|c| c.text.as_str()).collect::<Vec<_>>(),
466 ["first", "second", "third"],
467 "response order IS the ranking; re-sorting by score would promote \
468 the second hit over the service's own first choice"
469 );
470 assert_eq!(chunks[0].score, 0.0);
471 assert_eq!(chunks[1].score, 0.9);
472 }
473
474 #[test]
475 fn more_chunks_than_the_limit_are_truncated() {
476 let raw = body(serde_json::json!([
477 { "text": "a" }, { "text": "b" }, { "text": "c" }, { "text": "d" },
478 ]));
479 let chunks = parse_chunks(&raw, 2).unwrap();
480 assert_eq!(chunks.len(), 2);
481 assert_eq!(chunks[0].text, "a");
482 assert_eq!(chunks[1].text, "b");
483 }
484
485 #[test]
486 fn an_oversized_chunk_is_capped() {
487 let long = "x".repeat(MAX_CHUNK_CHARS + 500);
488 let raw = body(serde_json::json!([{ "text": long }]));
489 let chunks = parse_chunks(&raw, 5).unwrap();
490 assert_eq!(chunks[0].text.chars().count(), MAX_CHUNK_CHARS);
491 }
492
493 #[test]
494 fn the_total_character_budget_bounds_the_whole_retrieval() {
495 let long = "y".repeat(MAX_CHUNK_CHARS);
496 let items: Vec<serde_json::Value> = (0..20)
497 .map(|_| serde_json::json!({ "text": long }))
498 .collect();
499 let raw = body(serde_json::json!(items));
500 let chunks = parse_chunks(&raw, 20).unwrap();
501 let total: usize = chunks.iter().map(|c| c.text.chars().count()).sum();
502 assert!(
503 total <= MAX_TOTAL_CHARS,
504 "{total} characters exceeds the {MAX_TOTAL_CHARS}-character budget"
505 );
506 assert!(
507 !chunks.is_empty(),
508 "the budget must not empty the retrieval"
509 );
510 }
511
512 #[test]
513 fn a_multibyte_chunk_is_capped_without_panicking() {
514 let long = "é".repeat(MAX_CHUNK_CHARS + 10);
515 let raw = body(serde_json::json!([{ "text": long }]));
516 let chunks = parse_chunks(&raw, 5).unwrap();
517 assert_eq!(chunks[0].text.chars().count(), MAX_CHUNK_CHARS);
518 }
519
520 #[test]
521 fn a_body_that_is_not_json_is_a_backend_error_not_an_empty_result() {
522 let err = parse_chunks("not json at all", 5)
523 .expect_err("an unreadable body must not read as an empty corpus");
524 assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
525 }
526
527 #[test]
528 fn a_body_without_a_chunks_array_is_a_backend_error() {
529 let err = parse_chunks(r#"{"results":[]}"#, 5)
530 .expect_err("a differently-shaped body must not read as an empty corpus");
531 assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
532 }
533
534 #[test]
535 fn an_empty_chunks_array_is_an_honest_empty_result() {
536 let chunks = parse_chunks(r#"{"chunks":[]}"#, 5).unwrap();
537 assert!(chunks.is_empty());
538 }
539
540 #[test]
541 fn a_chunk_without_text_is_a_backend_error() {
542 let raw = body(serde_json::json!([{ "score": 0.5 }]));
543 let err = parse_chunks(&raw, 5).expect_err("a chunk with no text is unusable");
544 assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
545 }
546
547 #[test]
548 fn doc_id_and_metadata_ride_through_when_present() {
549 let raw = body(serde_json::json!([{
550 "text": "t", "score": 0.5, "doc_id": "kb/faq#12", "metadata": { "lang": "en" }
551 }]));
552 let chunks = parse_chunks(&raw, 5).unwrap();
553 assert_eq!(chunks[0].doc_id.as_deref(), Some("kb/faq#12"));
554 assert_eq!(chunks[0].metadata["lang"], "en");
555 }
556
557 fn binding(provider: &str, params: serde_json::Value) -> MemoryProviderRef {
558 MemoryProviderRef {
559 provider: provider.to_string(),
560 capability: "cap://dw.knowledge".to_string(),
561 params: params.as_object().cloned().unwrap_or_default(),
562 credential_ref: None,
563 }
564 }
565
566 #[test]
567 fn ids_are_read_from_the_bindings_params() {
568 let b = binding(
569 EXTENSION_PROVIDER_ID,
570 serde_json::json!({
571 EXTENSION_ID_PARAM: "greentic.rag-http",
572 TOOL_NAME_PARAM: "search_knowledge",
573 }),
574 );
575 assert!(matches!(
576 ExtensionKnowledge::claim_of(&b),
577 Claim::Delegate { extension_id, tool_name }
578 if extension_id == "greentic.rag-http" && tool_name == "search_knowledge"
579 ));
580 }
581
582 #[test]
583 fn another_provider_is_not_claimed() {
584 let b = binding(
585 "provider.knowledge.chronicle",
586 serde_json::json!({
587 EXTENSION_ID_PARAM: "greentic.rag-http",
588 TOOL_NAME_PARAM: "search_knowledge",
589 }),
590 );
591 assert!(
592 matches!(ExtensionKnowledge::claim_of(&b), Claim::NotOurs),
593 "a Chronicle binding must fall through to the wrapped backend"
594 );
595 }
596
597 #[test]
598 fn missing_or_blank_ids_do_not_claim_the_binding() {
599 let no_tool = binding(
600 EXTENSION_PROVIDER_ID,
601 serde_json::json!({ EXTENSION_ID_PARAM: "greentic.rag-http" }),
602 );
603 assert!(matches!(
604 ExtensionKnowledge::claim_of(&no_tool),
605 Claim::Malformed(TOOL_NAME_PARAM)
606 ));
607
608 let blank = binding(
609 EXTENSION_PROVIDER_ID,
610 serde_json::json!({ EXTENSION_ID_PARAM: " ", TOOL_NAME_PARAM: "search_knowledge" }),
611 );
612 assert!(matches!(
613 ExtensionKnowledge::claim_of(&blank),
614 Claim::Malformed(EXTENSION_ID_PARAM)
615 ));
616 }
617
618 #[tokio::test]
626 async fn a_binding_whose_target_does_not_read_is_reported_not_fallen_through() {
627 let inner = Arc::new(RecordingInner {
628 ingested: std::sync::Mutex::new(Vec::new()),
629 });
630 let broken = binding(
631 EXTENSION_PROVIDER_ID,
632 serde_json::json!({ EXTENSION_ID_PARAM: "greentic.rag-http" }),
633 );
634 let err = adapter(Some(inner))
635 .search_bound(
636 &tenant(),
637 KnowledgeQuery {
638 query: "q".into(),
639 limit: Some(3),
640 },
641 Some(&broken),
642 )
643 .await
644 .expect_err("a declared provider with no readable target is an error");
645
646 let KnowledgeError::Backend(message) = &err else {
647 panic!("expected a Backend error the loop will warn about, got {err:?}");
648 };
649 assert!(
650 message.contains(TOOL_NAME_PARAM),
651 "the diagnostic must name the key that did not read: {message}"
652 );
653 }
654
655 struct RecordingInner {
656 ingested: std::sync::Mutex<Vec<String>>,
657 }
658
659 #[async_trait::async_trait]
660 impl Knowledge for RecordingInner {
661 async fn ingest(
662 &self,
663 _tenant: &TenantCtx,
664 chunks: Vec<KnowledgeChunk>,
665 ) -> KnowledgeResult<IngestOutcome> {
666 let ids: Vec<String> = chunks.iter().map(|c| c.doc_id.clone()).collect();
667 self.ingested.lock().unwrap().extend(ids.clone());
668 Ok(IngestOutcome { chunk_ids: ids })
669 }
670
671 async fn search(
672 &self,
673 _tenant: &TenantCtx,
674 _query: KnowledgeQuery,
675 ) -> KnowledgeResult<Vec<RetrievedChunk>> {
676 Ok(vec![RetrievedChunk {
677 text: "from the wrapped backend".to_string(),
678 score: 1.0,
679 doc_id: None,
680 chunk_index: None,
681 metadata: serde_json::Map::new(),
682 }])
683 }
684 }
685
686 fn tenant() -> TenantCtx {
687 TenantCtx::new(
688 greentic_types::EnvId::try_from("dev").unwrap(),
689 greentic_types::TenantId::try_from("acme").unwrap(),
690 )
691 }
692
693 fn adapter(inner: Option<Arc<dyn Knowledge>>) -> ExtensionKnowledge {
694 ExtensionKnowledge {
695 ext: Arc::new(ExtensionRuntime::for_test().unwrap()),
696 inner,
697 }
698 }
699
700 #[tokio::test]
701 async fn ingest_is_a_no_op_with_nothing_wrapped() {
702 let outcome = adapter(None).ingest(&tenant(), vec![]).await.unwrap();
703 assert!(
704 outcome.chunk_ids.is_empty(),
705 "the corpus belongs to the customer's service; there is nothing to write"
706 );
707 }
708
709 #[tokio::test]
710 async fn ingest_with_a_corpus_still_succeeds_rather_than_failing_boot() {
711 let outcome = adapter(None)
712 .ingest(
713 &tenant(),
714 vec![KnowledgeChunk {
715 doc_id: "faq".into(),
716 chunk_index: 0,
717 text: "anything".into(),
718 metadata: serde_json::Map::new(),
719 embedding: None,
720 }],
721 )
722 .await
723 .expect("a pack carrying a corpus must not fail boot ingestion");
724 assert!(outcome.chunk_ids.is_empty());
725 }
726
727 #[tokio::test]
728 async fn a_wrapped_backend_still_receives_ingest_and_non_extension_searches() {
729 let inner = Arc::new(RecordingInner {
730 ingested: std::sync::Mutex::new(Vec::new()),
731 });
732 let wrapper = adapter(Some(inner.clone()));
733
734 wrapper
735 .ingest(
736 &tenant(),
737 vec![KnowledgeChunk {
738 doc_id: "faq".into(),
739 chunk_index: 0,
740 text: "t".into(),
741 metadata: serde_json::Map::new(),
742 embedding: None,
743 }],
744 )
745 .await
746 .unwrap();
747 assert_eq!(inner.ingested.lock().unwrap().as_slice(), ["faq"]);
748
749 let chronicle = binding("provider.knowledge.chronicle", serde_json::json!({}));
750 let hits = wrapper
751 .search_bound(
752 &tenant(),
753 KnowledgeQuery {
754 query: "q".into(),
755 limit: Some(3),
756 },
757 Some(&chronicle),
758 )
759 .await
760 .unwrap();
761 assert_eq!(hits[0].text, "from the wrapped backend");
762 }
763
764 #[test]
775 fn corpus_backend_walks_past_every_layer_of_this_adapter() {
776 fn corpus_recorder() -> Arc<dyn Knowledge> {
777 Arc::new(RecordingInner {
778 ingested: std::sync::Mutex::new(Vec::new()),
779 })
780 }
781 fn layer(inner: Option<Arc<dyn Knowledge>>) -> Option<Arc<dyn Knowledge>> {
782 Some(Arc::new(adapter(inner)))
783 }
784
785 assert!(
786 corpus_in_chain(None).is_none(),
787 "nothing mounted at all => no corpus backend"
788 );
789 assert!(
790 corpus_in_chain(layer(None)).is_none(),
791 "this adapter alone is not a corpus"
792 );
793 assert!(
794 corpus_in_chain(layer(layer(None))).is_none(),
795 "two stacked adapters must not read as a mounted corpus — this is \
796 exactly what a one-level `wrapped_backend()` check got wrong"
797 );
798 assert!(
799 corpus_in_chain(layer(Some(corpus_recorder()))).is_some(),
800 "a corpus directly under the adapter must stay visible to its host"
801 );
802 assert!(
803 corpus_in_chain(layer(layer(Some(corpus_recorder())))).is_some(),
804 "and must stay visible however many adapter layers sit above it"
805 );
806 }
807
808 #[test]
813 fn corpus_backend_skips_the_index_wrapper() {
814 let corpus: Arc<dyn Knowledge> = Arc::new(RecordingInner {
815 ingested: std::sync::Mutex::new(Vec::new()),
816 });
817 let index: Arc<dyn Knowledge> = Arc::new(
818 crate::runner::knowledge_index::ChronicleIndexKnowledge::new(
819 Some(corpus.clone()),
820 None,
821 None,
822 ),
823 );
824 let top: Arc<dyn Knowledge> = Arc::new(adapter(Some(index.clone())));
825
826 let found = corpus_in_chain(Some(top)).expect("the corpus is underneath");
827 assert!(
828 Arc::ptr_eq(&found, &corpus),
829 "found `{}` instead of the corpus",
830 found.backend_id()
831 );
832
833 let bare: Arc<dyn Knowledge> = Arc::new(adapter(Some(Arc::new(
834 crate::runner::knowledge_index::ChronicleIndexKnowledge::new(None, None, None),
835 ))));
836 assert!(
837 corpus_in_chain(Some(bare)).is_none(),
838 "the index wrapper alone is not a corpus"
839 );
840 }
841
842 #[tokio::test]
843 async fn with_nothing_wrapped_a_foreign_binding_is_not_configured() {
844 let chronicle = binding("provider.knowledge.chronicle", serde_json::json!({}));
845 let err = adapter(None)
846 .search_bound(
847 &tenant(),
848 KnowledgeQuery {
849 query: "q".into(),
850 limit: Some(3),
851 },
852 Some(&chronicle),
853 )
854 .await
855 .expect_err("no backend can serve a Chronicle binding here");
856 assert!(matches!(err, KnowledgeError::NotConfigured), "got {err:?}");
857 }
858}
859
860#[cfg(test)]
888mod call_site_ratchet {
889 use std::path::Path;
890
891 const CHRONICLE_MOUNT: &str = "runtime_ext::attach_all(";
895 const EXTENSION_MOUNT: &str = "knowledge_ext::attach(";
897 const CONSTRUCTOR: &str = "AgentRuntime::new(";
899 const INDEX_MOUNTS: &[&str] = &["knowledge_index::attach(", "index_mount.attach("];
902
903 const EXEMPT: &[(&str, usize, &str)] = &[
911 (
912 "src/runner/playbook_turn.rs",
913 2,
914 "a playbook turn, whose synthesised config is `knowledge: None` \
915 because a playbook has no corpus of its own BY CONTRACT — the \
916 document has no knowledge field at all, and knowledge reaches a \
917 playbook as an entry in its tool allow-list like any other \
918 capability. Mounting retrieval here would give a skill a corpus \
919 its author never declared and its caller cannot see. Pinned by \
920 `playbook_turn::tests::a_playbook_turn_carries_no_memory_and_no_knowledge`. \
921 The second is a test constructor: the OUTER agent of the run-context \
922 sharing tests, which answers from no corpus",
923 ),
924 (
925 "src/runner/run_context_policy.rs",
926 1,
927 "one test constructor: the policy tests only need a runtime to read \
928 its `SharePolicy` back, and answer from no corpus; the production \
929 path they model (`build_runtime_with_stores`) mounts",
930 ),
931 (
932 "src/runner/graph_node.rs",
933 2,
934 "the supervisor ROUTING runtime, whose synthesised config is \
935 `knowledge: None` with an empty tool list — it picks a branch and \
936 never answers from a corpus — plus one test constructor. Note the \
937 `agent_ref: None` inline path is NOT one of these: it shares the \
938 graph-agent constructor and skips the mount at run time, so it \
939 costs no allowance here",
940 ),
941 (
942 "src/runner/agent_node.rs",
943 4,
944 "four test constructors; both production paths mount. The fourth \
945 is `a_later_turn_without_attachments_replays_nothing`, which \
946 reads persisted history only and answers from no corpus",
947 ),
948 (
949 "src/runner/a2a_pack_source.rs",
950 1,
951 "one test constructor: the end-to-end test proves a pack's a2a \
952 sidecar reaches the LLM and the agent; it exercises no retrieval, \
953 and the production path it models (`build_runtime_with_stores`) \
954 mounts",
955 ),
956 (
957 "src/runner/operala_tools.rs",
958 1,
959 "one test constructor for the deep-worker tool context (#785); it \
960 dispatches tools and answers from no corpus, and the production \
961 runtime it borrows is built by `agent_node`, which mounts",
962 ),
963 (
964 "src/runner/runtime_ext.rs",
965 1,
966 "one test constructor: the seam's own unit tests need a runtime with \
967 nothing mounted, so every backend in the result is the extensions' \
968 doing",
969 ),
970 (
971 "src/runner/knowledge_index/tests.rs",
972 1,
973 "one test constructor: proves the graph lane's `IndexMount` reads \
974 credentials under the tenant it captured, over a runtime with \
975 nothing else mounted",
976 ),
977 (
978 "src/runner/engine.rs",
979 1,
980 "one test constructor; engine.rs builds no production AW runtime",
981 ),
982 ];
983
984 fn count_calls(text: &str, needle: &str) -> usize {
987 text.lines()
988 .filter(|l| {
989 let t = l.trim_start();
990 !t.starts_with("//") && !t.starts_with("*")
991 })
992 .map(|l| l.matches(needle).count())
993 .sum()
994 }
995
996 struct Site {
997 path: String,
998 chronicle: usize,
999 extension: usize,
1000 constructors: usize,
1001 }
1002
1003 fn sites() -> Vec<Site> {
1005 fn walk(dir: &Path, out: &mut Vec<Site>) {
1006 let Ok(entries) = std::fs::read_dir(dir) else {
1007 return;
1008 };
1009 for entry in entries.flatten() {
1010 let path = entry.path();
1011 if path.is_dir() {
1012 walk(&path, out);
1013 } else if path.extension().is_some_and(|e| e == "rs") {
1014 let Ok(text) = std::fs::read_to_string(&path) else {
1015 continue;
1016 };
1017 let rel = path.to_string_lossy().replace('\\', "/");
1018 if rel.ends_with("src/runner/knowledge_ext.rs") {
1019 continue; }
1021 let site = Site {
1022 path: rel,
1023 chronicle: count_calls(&text, CHRONICLE_MOUNT),
1024 extension: count_calls(&text, EXTENSION_MOUNT),
1025 constructors: count_calls(&text, CONSTRUCTOR),
1026 };
1027 if site.chronicle > 0 || site.extension > 0 || site.constructors > 0 {
1028 out.push(site);
1029 }
1030 }
1031 }
1032 }
1033 let mut out = Vec::new();
1034 walk(Path::new("src"), &mut out);
1035 out.sort_by(|a, b| a.path.cmp(&b.path));
1036 out
1037 }
1038
1039 fn exempted(path: &str) -> usize {
1040 EXEMPT
1041 .iter()
1042 .find(|(p, _, _)| *p == path)
1043 .map_or(0, |(_, n, _)| *n)
1044 }
1045
1046 #[test]
1049 fn constructor_anchor() {
1050 let offenders: Vec<_> = sites()
1051 .into_iter()
1052 .filter(|s| s.constructors > 0)
1053 .filter(|s| s.constructors != s.extension + exempted(&s.path))
1054 .map(|s| {
1055 format!(
1056 "{}: {} `AgentRuntime::new(`, {} `knowledge_ext::attach(`, {} exempted",
1057 s.path,
1058 s.constructors,
1059 s.extension,
1060 exempted(&s.path)
1061 )
1062 })
1063 .collect();
1064 assert!(
1065 offenders.is_empty(),
1066 "each of these builds an `AgentRuntime` without deciding about \
1067 extension-delegated retrieval. Mount `knowledge_ext::attach`, or add \
1068 the site to `EXEMPT` with a reason — a runtime that silently has no \
1069 retrieval is how the model came to answer from nothing before: {offenders:#?}"
1070 );
1071 }
1072
1073 #[test]
1078 fn mount_anchor() {
1079 let offenders: Vec<_> = sites()
1080 .into_iter()
1081 .filter(|s| s.chronicle > s.extension)
1082 .map(|s| {
1083 format!(
1084 "{}: {} chronicle, {} extension",
1085 s.path, s.chronicle, s.extension
1086 )
1087 })
1088 .collect();
1089 assert!(
1090 offenders.is_empty(),
1091 "these mount a knowledge corpus without also mounting \
1092 `knowledge_ext::attach`, so a worker binding \
1093 `provider.knowledge.extension` silently retrieves nothing and the \
1094 model answers from nothing instead: {offenders:#?}"
1095 );
1096 }
1097
1098 fn is_code(line: &str) -> bool {
1099 let t = line.trim_start();
1100 !t.starts_with("//") && !t.starts_with('*')
1101 }
1102
1103 fn starts_fn(line: &str) -> bool {
1104 let mut t = line.trim_start();
1105 for prefix in ["pub(crate) ", "pub(super) ", "pub ", "async ", "unsafe "] {
1106 t = t.strip_prefix(prefix).unwrap_or(t);
1107 }
1108 t.starts_with("fn ")
1109 }
1110
1111 fn names_index_mount(line: &str) -> bool {
1112 is_code(line) && INDEX_MOUNTS.iter().any(|m| line.contains(m))
1113 }
1114
1115 fn unindexed_mounts() -> Vec<String> {
1118 let mut out = Vec::new();
1119 for site in sites().into_iter().filter(|s| s.extension > 0) {
1120 let Ok(text) = std::fs::read_to_string(&site.path) else {
1121 continue;
1122 };
1123 let lines: Vec<&str> = text.lines().collect();
1124 for (i, line) in lines.iter().enumerate() {
1125 if !is_code(line) || !line.contains(EXTENSION_MOUNT) {
1126 continue;
1127 }
1128 let covered = lines[..=i]
1129 .iter()
1130 .rev()
1131 .take_while(|l| !starts_fn(l))
1132 .any(|l| names_index_mount(l));
1133 if !covered {
1134 out.push(format!("{}:{}", site.path, i + 1));
1135 }
1136 }
1137 }
1138 out
1139 }
1140
1141 #[test]
1146 fn every_extension_mount_also_mounts_the_index() {
1147 let offenders = unindexed_mounts();
1148 assert!(
1149 offenders.is_empty(),
1150 "these mount `knowledge_ext::attach` without a Chronicle-index mount \
1151 (`knowledge_index::attach(` or `index_mount.attach(`) earlier in the \
1152 same function: {offenders:#?}"
1153 );
1154 }
1155
1156 #[test]
1162 fn the_scanned_anchors_still_exist() {
1163 let sites = sites();
1164 let mounts: usize = sites.iter().map(|s| s.extension).sum();
1165 let corpora: usize = sites.iter().map(|s| s.chronicle).sum();
1166 let constructors: usize = sites.iter().map(|s| s.constructors).sum();
1167 let index_mounts: usize = sites
1168 .iter()
1169 .filter_map(|s| std::fs::read_to_string(&s.path).ok())
1170 .map(|text| text.lines().filter(|l| names_index_mount(l)).count())
1171 .sum();
1172 assert!(
1173 index_mounts >= 3,
1174 "expected the Chronicle-index mount beside each of the three \
1175 `knowledge_ext::attach` sites; found {index_mounts} — has \
1176 `knowledge_index::attach` or `index_mount.attach` been renamed?"
1177 );
1178 assert!(
1179 mounts >= 3,
1180 "expected the in-process `dw.agent`, out-of-process serve and \
1181 graph-node mounts; found {mounts} `knowledge_ext::attach` call sites"
1182 );
1183 assert!(
1184 corpora >= 3,
1185 "expected three corpus-extension mounts beside them; found {corpora} — \
1186 has `runtime_ext::attach_all` been renamed?"
1187 );
1188 assert!(
1189 constructors >= mounts,
1190 "found {constructors} `AgentRuntime::new(` against {mounts} mounts — \
1191 has the constructor been renamed?"
1192 );
1193 for (path, _, _) in EXEMPT {
1194 let found = sites.iter().find(|s| s.path == *path);
1195 assert!(
1196 found.is_some_and(|s| s.constructors > 0),
1197 "`EXEMPT` names {path}, which constructs no `AgentRuntime`. A \
1198 stale allowance hides the next unmounted construction added to \
1199 that file — remove it."
1200 );
1201 }
1202 }
1203}