Skip to main content

greentic_runner_host/runner/
knowledge_ext.rs

1//! Knowledge retrieval delegated to a design-extension tool.
2//!
3//! The runner-host edge of a knowledge provider whose corpus lives OUTSIDE the
4//! platform: the operator binds a provider that names an installed `.gtxpack`
5//! extension and one of its tools, and every turn's auto-retrieval calls that
6//! tool instead of a corpus this process holds. What the tool then does — which
7//! service it talks to, over which protocol, with which credential — is the
8//! extension's business and is deliberately invisible here. That is what makes
9//! this a one-time change rather than one adapter per customer, so nothing in
10//! this file may grow a mention of a specific transport or service.
11//!
12//! ## Why the ids are read per call and not held as fields
13//!
14//! [`greentic_aw_runtime::AgentRuntime::knowledge`] is a RUNTIME-level field,
15//! set once when the runtime is built, while the provider choice arrives PER
16//! TURN in `AgentConfig`. The out-of-process serve path serves many agents from
17//! one runtime, so a runtime built around one worker's extension id would hand
18//! every other worker that same extension. The binding therefore travels down
19//! through [`greentic_aw_runtime::knowledge::Knowledge::search_bound`] and the
20//! ids are read from its `params` at call time.
21//!
22//! ## Why this wraps rather than replaces
23//!
24//! `with_knowledge` overwrites the runtime's backend. A corpus mount (a
25//! registered agent-runtime extension, see `runtime_ext`) and this one would
26//! otherwise each disable the other depending on call order, silently. So
27//! [`attach`] takes whatever is already mounted and delegates to it for every
28//! binding that is not this provider — including `ingest`, which is how a
29//! boot-ingested corpus keeps working.
30//!
31//! ## No cargo feature
32//!
33//! Unlike a corpus backend, this is built in rather than registered by the host
34//! binary. It drags nothing: the
35//! `ExtensionRuntime` it invokes is already mandatory on this path
36//! (`agent_node::build_ext_runtime` returning `None` disables `dw.agent` nodes
37//! outright). Gating it would force an operator who wants a customer's own
38//! retrieval service to rebuild the runner with an embedded database they never
39//! use.
40
41use 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
53/// The provider id a knowledge binding carries when retrieval is delegated to a
54/// design-extension tool. Written by the designer's composer; matched here.
55pub const EXTENSION_PROVIDER_ID: &str = "provider.knowledge.extension";
56
57/// The `params` key naming the extension to delegate retrieval to.
58///
59/// A contract with the designer's provider catalog (`block_id` in
60/// `assets/dw-providers-catalog.json`, mirrored by `EXTENSION_ID_PARAM` in its
61/// `agent_tool_deps`). A variant spelling on either side makes the feature
62/// inert while every layer still reports success, so do not invent one.
63pub const EXTENSION_ID_PARAM: &str = "provider.knowledge.extension.extension_id";
64
65/// The `params` key naming which of that extension's tools performs retrieval.
66/// Same contract and same discipline as [`EXTENSION_ID_PARAM`].
67pub const TOOL_NAME_PARAM: &str = "provider.knowledge.extension.tool_name";
68
69/// Chunks accepted when the query names no limit. The loop always sets one
70/// (`auto_top_k`), so this only bounds a direct caller.
71const DEFAULT_LIMIT: usize = 5;
72
73/// Characters kept from any single chunk.
74pub(crate) const MAX_CHUNK_CHARS: usize = 4_000;
75
76/// Characters kept across all chunks of one retrieval.
77///
78/// `augment_system_prompt` bullets everything it is handed straight into the
79/// system prompt, so an unbounded response is our token bill, not the
80/// customer's. The extension is expected to cap too; this is defence in depth at
81/// the boundary that is always crossed.
82///
83/// **This is a bound on PROMPT size, not on memory.** By the time either cap
84/// applies the response has already been materialised twice: the host's
85/// `http::fetch` reads the body with `resp.bytes()` and applies no size cap at
86/// the pinned ext-runtime rev, and the tool result reaches this module as an
87/// owned `String`. A multi-gigabyte response is therefore a host memory problem
88/// these constants do not touch. Neither introduced here nor fixable here — it
89/// needs a cap on the host's HTTP port — but the distinction has to be written
90/// down, because a reader who takes these for a memory guard will not go looking.
91pub(crate) const MAX_TOTAL_CHARS: usize = 24_000;
92
93/// Identifies this backend within a wrapper chain.
94///
95/// [`Knowledge::wrapped_backend`] unwraps one layer and cannot tell a corpus
96/// backend from a second delegating wrapper, so a host asking "is a corpus
97/// mounted" has to walk the chain past every layer that is this adapter. See
98/// [`corpus_backend`].
99const BACKEND_ID: &str = "runner-host.knowledge_ext";
100
101/// Mount extension-delegated knowledge retrieval, wrapping whatever backend is
102/// already mounted (see the module docs — this must not replace it).
103///
104/// Infallible and unconditional: the adapter only acts on a binding that names
105/// [`EXTENSION_PROVIDER_ID`], so mounting it on a runtime no worker binds it on
106/// changes nothing.
107#[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
113/// What one agent's knowledge binding means to this adapter.
114///
115/// The third arm is the reason this is an enum rather than an `Option`. A
116/// binding that NAMES [`EXTENSION_PROVIDER_ID`] but whose delegation target does
117/// not read — key absent, blank, or misspelled — must not be treated the same as
118/// a binding for some other provider. Falling through was quiet in two
119/// directions, and the second is the worse one:
120///
121/// - default build (nothing wrapped) it reached `NotConfigured`, logged at
122///   `debug`, and the worker answered ungrounded;
123/// - with a Chronicle corpus extension registered it reached `KnowledgeBridge`, which ignores
124///   the binding entirely and searches its own env-configured corpus — so the
125///   worker retrieved from **the wrong source** and reported success.
126///
127/// The provider id is an explicit operator declaration, so an unreadable target
128/// under it is an error, not a normal state. [`Claim::Malformed`] carries the
129/// offending key and becomes a `Backend` error, which the loop already turns
130/// into a warning plus a distinguishable trace step.
131enum Claim {
132    /// Some other provider — the wrapped backend's business, not ours.
133    NotOurs,
134    /// This provider, with a usable delegation target.
135    Delegate {
136        extension_id: String,
137        tool_name: String,
138    },
139    /// This provider, but the named `params` key is missing or blank.
140    Malformed(&'static str),
141}
142
143/// Retrieval performed by a design-extension tool named in the agent's binding.
144pub struct ExtensionKnowledge {
145    ext: Arc<ExtensionRuntime>,
146    /// The backend mounted before this one, if any. Every binding that is not
147    /// [`EXTENSION_PROVIDER_ID`] — and every `ingest` — goes here.
148    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    /// What a binding says about this adapter.
158    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    /// A no-op for the extension path: the corpus belongs to the customer's own
194    /// service and this runtime has nothing to write it to.
195    ///
196    /// Success rather than an error, deliberately — a pack that happens to
197    /// carry a corpus (an operator who bound documents and then switched
198    /// provider, say) must not fail boot ingestion over a corpus the retrieval
199    /// side simply will not read.
200    ///
201    /// A wrapped inner backend still receives it, so a Chronicle mount under
202    /// this one keeps ingesting exactly as before.
203    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    /// Retrieval with no binding in hand cannot know which extension to invoke,
215    /// so it can only be the wrapped backend's — or nothing. The agentic loop
216    /// always goes through [`Self::search_bound`].
217    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        // The caller's tenant travels with the call rather than the process
255        // default, so a tenant-aware host port sees it.
256        //
257        // Do NOT read that as "the extension's credential resolves per tenant".
258        // At the pinned ext-runtime rev (29b9cc5) `HostCallContext` is consulted
259        // at exactly ONE site — the LLM port, `host_state.rs:417`.
260        // `secrets::Host::get` forwards to `SecretsBackend::get(&uri)`, which
261        // takes no tenant at all, and the OAuth port reads its tenant from
262        // runtime-level config. So on the out-of-process serve path — the very
263        // path that serves many agents from one runtime, and the reason the
264        // binding has to travel per turn — the runtime is built with
265        // `build_ext_runtime(Arc::new(EnvSecretsBackend), None, None, &[])`
266        // (`agent_node.rs`, inside `build_agent_runtime`) and EVERY tenant's
267        // retrieval resolves the same env credential. Passing the tenant is
268        // correct and free once the port grows tenant awareness; today it is
269        // not a multi-tenancy guarantee, and a comment claiming otherwise is
270        // what would stop the next reader checking.
271        let ctx = HostCallContext {
272            tenant: Some(tenant.tenant.as_str().to_string()),
273            user_email: None,
274        };
275
276        // `invoke_tool_ctx` is synchronous (wasmtime sync) and instantiates a
277        // component, so it must never run on the async executor.
278        //
279        // The cost of that, spelled out because §6.2 records only its cause: the
280        // guest cannot bound its own call (`extension-host/http@0.1.0` carries
281        // no timeout field), so the ceiling is the host's 30 s. A hung customer
282        // service therefore pins one blocking-pool thread AND one turn for up to
283        // 30 s per retrieval — and `spawn_blocking` is not cancellable, so an
284        // abandoned turn does not release the thread any sooner.
285        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    /// [`attach`] is unconditional, so `AgentRuntime::has_knowledge()` is true on
312    /// every path that mounts this adapter — whether or not a corpus backend was
313    /// mounted underneath it. That makes `has_knowledge()` unable to answer "did
314    /// the corpus mount run", which is exactly the question the in-process
315    /// `dw.agent` regression guard exists to ask. This answers it instead.
316    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/// The first backend in the runtime's wrapper chain that is NOT this adapter
326/// or the Chronicle-index wrapper (`knowledge_index`) mounted beneath it —
327/// i.e. the corpus backend, if one was mounted underneath.
328///
329/// Walks the whole chain rather than unwrapping one layer:
330/// [`Knowledge::wrapped_backend`] returning `Some` only says "something is
331/// underneath", which a second delegating wrapper would satisfy just as well as
332/// a corpus. Since [`attach`] is unconditional, `AgentRuntime::has_knowledge()`
333/// cannot answer this question at all any more — every runner-host path has a
334/// backend mounted whether or not a corpus was.
335#[must_use]
336pub fn corpus_backend(runtime: &AgentRuntime) -> Option<Arc<dyn Knowledge>> {
337    corpus_in_chain(runtime.knowledge_backend())
338}
339
340/// The walk itself, split from [`corpus_backend`] so it can be exercised over a
341/// hand-built chain without standing up a whole `AgentRuntime`.
342fn 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
354/// Parse a retrieval tool's result into ranked chunks.
355///
356/// The ONE place third-party data enters the runtime, so every decision here is
357/// deliberate:
358///
359/// - **Response order is the ranking.** The chunks are not re-sorted; a service
360///   that returns its best hit first must see it stay first, and an absent
361///   `score` becomes `0.0` rather than dropping the chunk or inventing a rank.
362/// - **A body this function cannot read is an error, never an empty result.**
363///   Returning `Ok(vec![])` for a malformed or unexpected body is exactly the
364///   silent degrade this whole line of work exists to remove: the worker would
365///   answer confidently from nothing and no layer would say so.
366/// - **Both caps are applied here as well as in the extension**, because the
367///   extension is one artifact among many and this is the boundary that is
368///   always crossed.
369fn 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        // A missing — or non-numeric — score is 0.0, while a missing or
407        // non-string `text` above is a hard `Backend` error. The asymmetry is
408        // chosen, not an oversight: response ORDER is the ranking, so a score
409        // this function cannot read costs nothing but a trace field, whereas a
410        // chunk with no readable text is an empty bullet in the system prompt
411        // and there is no honest value to substitute for it.
412        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
437/// Truncate on a character boundary. Byte slicing would panic mid-codepoint on
438/// any non-ASCII corpus, which is most of them.
439pub(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    /// The companion to the test above, and the more important half: NOT
619    /// invoking is right, but doing it quietly is what made a drifted param key
620    /// dangerous. With a corpus backend wrapped, the old fall-through reached
621    /// `KnowledgeBridge`, which ignores the binding and searches its own
622    /// env-configured corpus — so the worker retrieved from the WRONG source and
623    /// reported success. A `Backend` error is what routes this through the
624    /// loop's warning and its distinguishable trace step.
625    #[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    /// `attach` is unconditional, so `has_knowledge()` can no longer tell a host
765    /// whether a CORPUS backend was mounted. [`corpus_backend`] is what answers
766    /// that now, and the in-process `dw.agent` regression guard depends on it —
767    /// so it has to report both cases, not merely be present.
768    ///
769    /// The doubled case is the point: `wrapped_backend()` alone says only
770    /// "something is underneath", which a SECOND copy of this adapter satisfies
771    /// exactly as well as a corpus does. Mounting twice is not hypothetical —
772    /// [`attach`] is called once per construction path and a fourth site could
773    /// stack one — and the guard must not read that as a corpus.
774    #[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    /// Every production site mounts the Chronicle-index wrapper directly
809    /// beneath this adapter, so the corpus sits two delegating layers down.
810    /// The walk must pass BOTH, or the in-process `dw.agent` guard would read
811    /// the index wrapper as a corpus and a worker with no corpus as having one.
812    #[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/// Ratchet: no `AgentRuntime` may be constructed without a decision about
861/// extension-delegated retrieval.
862///
863/// The mount is a bare statement whose omission compiles, boots, and serves —
864/// the runtime simply has no extension-delegated retrieval, `knowledge_active`
865/// stays false, and the model answers from nothing. That has already happened
866/// once on this exact seam: the comment above the in-process `dw.agent` mount
867/// records that a missed call site left `runtime.knowledge` at `None` and *"the
868/// model hallucinated instead of retrieving from the corpus that had already
869/// been ingested at boot."*
870///
871/// So this scans the source instead of trusting the call sites to stay in step,
872/// and it does so through TWO anchors, because neither catches the other's
873/// regression:
874///
875/// - [`constructor_anchor`] — every file constructing an `AgentRuntime` must
876///   mount this adapter as many times, minus an explicit, reasoned
877///   [`EXEMPT`] allowance. This is the one that catches the incident shape
878///   quoted above: **a brand-new construction path that mounts nothing at
879///   all**. Such a file names neither mount, so a mount-anchored scan never
880///   even looks at it. Modelled on the designer's
881///   `dw_test_chat/mcp_source.rs`, which anchors on the constructor with an
882///   exemption list precisely so that each site is a decision rather than an
883///   inference.
884/// - [`mount_anchor`] — a file that runs the registered corpus extensions must mount this
885///   adapter too. This catches the likelier near-term regression: a knowledge
886///   mount copied to a new site with only half the pair.
887#[cfg(test)]
888mod call_site_ratchet {
889    use std::path::Path;
890
891    /// The registered-extension mount (`runtime_ext`), whose call sites are the
892    /// corpus mount sites. It was `knowledge_mount::attach(` while the Chronicle
893    /// backend was compiled into this crate.
894    const CHRONICLE_MOUNT: &str = "runtime_ext::attach_all(";
895    /// This module's mount.
896    const EXTENSION_MOUNT: &str = "knowledge_ext::attach(";
897    /// Every runtime construction, mounted or not.
898    const CONSTRUCTOR: &str = "AgentRuntime::new(";
899    /// The Chronicle-index mount, in its two spellings: the direct call, and the
900    /// graph lane's pre-built mount context.
901    const INDEX_MOUNTS: &[&str] = &["knowledge_index::attach(", "index_mount.attach("];
902
903    /// Files that construct an `AgentRuntime` WITHOUT mounting this adapter, and
904    /// how many such constructions each is allowed.
905    ///
906    /// Every entry is a decision, and adding one means writing down why that
907    /// runtime must have no extension-delegated retrieval. A new constructor in
908    /// an exempt file changes its count and fails this test, so the exemption
909    /// covers the sites reasoned about here and never the next one.
910    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    /// Count non-comment occurrences of `needle`, so a doc comment naming a
985    /// mount or a constructor is never mistaken for one.
986    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    /// Every source file that mounts either backend or constructs a runtime.
1004    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; // this file, which defines all three names
1020                    }
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    /// The anchor that catches a NEW construction path mounting nothing: such a
1047    /// file names neither mount, so [`mount_anchor`] never sees it.
1048    #[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    /// The anchor that catches half a copied pair: a corpus mount without this
1074    /// adapter beside it. One-directional on purpose — the reverse (this
1075    /// adapter alone) is harmless: this adapter is unconditional, while which
1076    /// corpus extensions exist is the host binary's choice.
1077    #[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    /// Every `knowledge_ext::attach(` call, as `(path, line)`, that no
1116    /// Chronicle-index mount precedes within the same function.
1117    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    /// Every production knowledge mount carries the Chronicle-index wrapper
1142    /// too: a site with only `knowledge_ext` would silently answer a
1143    /// `provider.knowledge.chronicle-index` binding with `NotConfigured`, and
1144    /// the worker would retrieve nothing on that lane alone.
1145    #[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    /// Guards the guards. Both scans are textual, so a rename would leave them
1157    /// passing vacuously over a file set of zero — and an `EXEMPT` entry for a
1158    /// path that no longer constructs anything is debt hiding the next
1159    /// regression behind it, exactly as `ci/file_size_ratchet.py` treats a
1160    /// baselined file that is no longer over its cap.
1161    #[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}