use std::sync::Arc;
use greentic_aw_runtime::AgentRuntime;
use greentic_aw_runtime::config::MemoryProviderRef;
use greentic_aw_runtime::knowledge::{
IngestOutcome, Knowledge, KnowledgeChunk, KnowledgeError, KnowledgeQuery, KnowledgeResult,
RetrievedChunk,
};
use greentic_ext_runtime::ExtensionRuntime;
use greentic_ext_runtime::host_ports::HostCallContext;
use greentic_types::TenantCtx;
pub const EXTENSION_PROVIDER_ID: &str = "provider.knowledge.extension";
pub const EXTENSION_ID_PARAM: &str = "provider.knowledge.extension.extension_id";
pub const TOOL_NAME_PARAM: &str = "provider.knowledge.extension.tool_name";
const DEFAULT_LIMIT: usize = 5;
pub(crate) const MAX_CHUNK_CHARS: usize = 4_000;
pub(crate) const MAX_TOTAL_CHARS: usize = 24_000;
const BACKEND_ID: &str = "runner-host.knowledge_ext";
#[must_use]
pub fn attach(base: AgentRuntime, ext: Arc<ExtensionRuntime>) -> AgentRuntime {
let inner = base.knowledge_backend();
base.with_knowledge(Arc::new(ExtensionKnowledge::new(ext, inner)))
}
enum Claim {
NotOurs,
Delegate {
extension_id: String,
tool_name: String,
},
Malformed(&'static str),
}
pub struct ExtensionKnowledge {
ext: Arc<ExtensionRuntime>,
inner: Option<Arc<dyn Knowledge>>,
}
impl ExtensionKnowledge {
#[must_use]
pub fn new(ext: Arc<ExtensionRuntime>, inner: Option<Arc<dyn Knowledge>>) -> Self {
Self { ext, inner }
}
fn claim_of(binding: &MemoryProviderRef) -> Claim {
if binding.provider != EXTENSION_PROVIDER_ID {
return Claim::NotOurs;
}
let read = |key: &str| -> Option<String> {
let value = binding.params.get(key)?.as_str()?.trim();
(!value.is_empty()).then(|| value.to_string())
};
let Some(extension_id) = read(EXTENSION_ID_PARAM) else {
return Claim::Malformed(EXTENSION_ID_PARAM);
};
let Some(tool_name) = read(TOOL_NAME_PARAM) else {
return Claim::Malformed(TOOL_NAME_PARAM);
};
Claim::Delegate {
extension_id,
tool_name,
}
}
async fn delegate_search(
&self,
tenant: &TenantCtx,
query: KnowledgeQuery,
binding: Option<&MemoryProviderRef>,
) -> KnowledgeResult<Vec<RetrievedChunk>> {
match self.inner.as_ref() {
Some(inner) => inner.search_bound(tenant, query, binding).await,
None => Err(KnowledgeError::NotConfigured),
}
}
}
#[async_trait::async_trait]
impl Knowledge for ExtensionKnowledge {
async fn ingest(
&self,
tenant: &TenantCtx,
chunks: Vec<KnowledgeChunk>,
) -> KnowledgeResult<IngestOutcome> {
match self.inner.as_ref() {
Some(inner) => inner.ingest(tenant, chunks).await,
None => Ok(IngestOutcome::default()),
}
}
async fn search(
&self,
tenant: &TenantCtx,
query: KnowledgeQuery,
) -> KnowledgeResult<Vec<RetrievedChunk>> {
self.delegate_search(tenant, query, None).await
}
async fn search_bound(
&self,
tenant: &TenantCtx,
query: KnowledgeQuery,
binding: Option<&MemoryProviderRef>,
) -> KnowledgeResult<Vec<RetrievedChunk>> {
let (extension_id, tool_name) = match binding.map_or(Claim::NotOurs, Self::claim_of) {
Claim::NotOurs => return self.delegate_search(tenant, query, binding).await,
Claim::Malformed(key) => {
return Err(KnowledgeError::Backend(format!(
"knowledge binding names `{EXTENSION_PROVIDER_ID}` but its `{key}` param is \
missing or blank, so there is no retrieval target to invoke"
)));
}
Claim::Delegate {
extension_id,
tool_name,
} => (extension_id, tool_name),
};
let limit = query.limit.unwrap_or(DEFAULT_LIMIT).max(1);
let args = serde_json::json!({
"query": query.query,
"top_k": limit,
"tenant": tenant.tenant.as_str(),
"env": tenant.env.as_str(),
})
.to_string();
let ctx = HostCallContext {
tenant: Some(tenant.tenant.as_str().to_string()),
user_email: None,
};
let ext = Arc::clone(&self.ext);
let called = {
let extension_id = extension_id.clone();
let tool_name = tool_name.clone();
tokio::task::spawn_blocking(move || {
ext.invoke_tool_ctx(&extension_id, &tool_name, &args, &ctx)
})
.await
};
let raw = called
.map_err(|e| {
KnowledgeError::Backend(format!(
"knowledge retrieval task for '{extension_id}/{tool_name}' did not \
complete: {e}"
))
})?
.map_err(|e| {
KnowledgeError::Backend(format!(
"knowledge retrieval tool '{extension_id}/{tool_name}' failed: {e}"
))
})?;
parse_chunks(&raw, limit)
}
fn wrapped_backend(&self) -> Option<Arc<dyn Knowledge>> {
self.inner.clone()
}
fn backend_id(&self) -> &'static str {
BACKEND_ID
}
}
#[must_use]
pub fn corpus_backend(runtime: &AgentRuntime) -> Option<Arc<dyn Knowledge>> {
corpus_in_chain(runtime.knowledge_backend())
}
fn corpus_in_chain(top: Option<Arc<dyn Knowledge>>) -> Option<Arc<dyn Knowledge>> {
let mut current = top;
while let Some(backend) = current {
let id = backend.backend_id();
if id != BACKEND_ID && id != crate::runner::knowledge_index::BACKEND_ID {
return Some(backend);
}
current = backend.wrapped_backend();
}
None
}
fn parse_chunks(raw: &str, limit: usize) -> KnowledgeResult<Vec<RetrievedChunk>> {
let body: serde_json::Value = serde_json::from_str(raw).map_err(|e| {
KnowledgeError::Backend(format!(
"knowledge retrieval returned a body that is not JSON: {e}"
))
})?;
let items = body
.get("chunks")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| {
KnowledgeError::Backend(
"knowledge retrieval returned no `chunks` array; expected \
{\"chunks\":[{\"text\":…}]}"
.to_string(),
)
})?;
let mut out = Vec::with_capacity(items.len().min(limit));
let mut budget = MAX_TOTAL_CHARS;
for (index, item) in items.iter().take(limit).enumerate() {
let text = item
.get("text")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
KnowledgeError::Backend(format!(
"knowledge retrieval chunk {index} carries no `text` string"
))
})?;
if budget == 0 {
break;
}
let text = truncate_chars(text, MAX_CHUNK_CHARS.min(budget));
budget = budget.saturating_sub(text.chars().count());
let score = item
.get("score")
.and_then(serde_json::Value::as_f64)
.filter(|s| s.is_finite())
.unwrap_or(0.0);
out.push(RetrievedChunk {
text,
score,
doc_id: item
.get("doc_id")
.and_then(serde_json::Value::as_str)
.map(str::to_string),
chunk_index: None,
metadata: item
.get("metadata")
.and_then(serde_json::Value::as_object)
.cloned()
.unwrap_or_default(),
});
}
Ok(out)
}
pub(crate) fn truncate_chars(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
text.chars().take(max).collect()
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
fn body(chunks: serde_json::Value) -> String {
serde_json::json!({ "chunks": chunks }).to_string()
}
#[test]
fn a_missing_score_is_zero_and_the_service_order_is_kept() {
let raw = body(serde_json::json!([
{ "text": "first" },
{ "text": "second", "score": 0.9 },
{ "text": "third", "score": 0.1 },
]));
let chunks = parse_chunks(&raw, 10).expect("a well-formed body parses");
assert_eq!(
chunks.iter().map(|c| c.text.as_str()).collect::<Vec<_>>(),
["first", "second", "third"],
"response order IS the ranking; re-sorting by score would promote \
the second hit over the service's own first choice"
);
assert_eq!(chunks[0].score, 0.0);
assert_eq!(chunks[1].score, 0.9);
}
#[test]
fn more_chunks_than_the_limit_are_truncated() {
let raw = body(serde_json::json!([
{ "text": "a" }, { "text": "b" }, { "text": "c" }, { "text": "d" },
]));
let chunks = parse_chunks(&raw, 2).unwrap();
assert_eq!(chunks.len(), 2);
assert_eq!(chunks[0].text, "a");
assert_eq!(chunks[1].text, "b");
}
#[test]
fn an_oversized_chunk_is_capped() {
let long = "x".repeat(MAX_CHUNK_CHARS + 500);
let raw = body(serde_json::json!([{ "text": long }]));
let chunks = parse_chunks(&raw, 5).unwrap();
assert_eq!(chunks[0].text.chars().count(), MAX_CHUNK_CHARS);
}
#[test]
fn the_total_character_budget_bounds_the_whole_retrieval() {
let long = "y".repeat(MAX_CHUNK_CHARS);
let items: Vec<serde_json::Value> = (0..20)
.map(|_| serde_json::json!({ "text": long }))
.collect();
let raw = body(serde_json::json!(items));
let chunks = parse_chunks(&raw, 20).unwrap();
let total: usize = chunks.iter().map(|c| c.text.chars().count()).sum();
assert!(
total <= MAX_TOTAL_CHARS,
"{total} characters exceeds the {MAX_TOTAL_CHARS}-character budget"
);
assert!(
!chunks.is_empty(),
"the budget must not empty the retrieval"
);
}
#[test]
fn a_multibyte_chunk_is_capped_without_panicking() {
let long = "é".repeat(MAX_CHUNK_CHARS + 10);
let raw = body(serde_json::json!([{ "text": long }]));
let chunks = parse_chunks(&raw, 5).unwrap();
assert_eq!(chunks[0].text.chars().count(), MAX_CHUNK_CHARS);
}
#[test]
fn a_body_that_is_not_json_is_a_backend_error_not_an_empty_result() {
let err = parse_chunks("not json at all", 5)
.expect_err("an unreadable body must not read as an empty corpus");
assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
}
#[test]
fn a_body_without_a_chunks_array_is_a_backend_error() {
let err = parse_chunks(r#"{"results":[]}"#, 5)
.expect_err("a differently-shaped body must not read as an empty corpus");
assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
}
#[test]
fn an_empty_chunks_array_is_an_honest_empty_result() {
let chunks = parse_chunks(r#"{"chunks":[]}"#, 5).unwrap();
assert!(chunks.is_empty());
}
#[test]
fn a_chunk_without_text_is_a_backend_error() {
let raw = body(serde_json::json!([{ "score": 0.5 }]));
let err = parse_chunks(&raw, 5).expect_err("a chunk with no text is unusable");
assert!(matches!(err, KnowledgeError::Backend(_)), "got {err:?}");
}
#[test]
fn doc_id_and_metadata_ride_through_when_present() {
let raw = body(serde_json::json!([{
"text": "t", "score": 0.5, "doc_id": "kb/faq#12", "metadata": { "lang": "en" }
}]));
let chunks = parse_chunks(&raw, 5).unwrap();
assert_eq!(chunks[0].doc_id.as_deref(), Some("kb/faq#12"));
assert_eq!(chunks[0].metadata["lang"], "en");
}
fn binding(provider: &str, params: serde_json::Value) -> MemoryProviderRef {
MemoryProviderRef {
provider: provider.to_string(),
capability: "cap://dw.knowledge".to_string(),
params: params.as_object().cloned().unwrap_or_default(),
credential_ref: None,
}
}
#[test]
fn ids_are_read_from_the_bindings_params() {
let b = binding(
EXTENSION_PROVIDER_ID,
serde_json::json!({
EXTENSION_ID_PARAM: "greentic.rag-http",
TOOL_NAME_PARAM: "search_knowledge",
}),
);
assert!(matches!(
ExtensionKnowledge::claim_of(&b),
Claim::Delegate { extension_id, tool_name }
if extension_id == "greentic.rag-http" && tool_name == "search_knowledge"
));
}
#[test]
fn another_provider_is_not_claimed() {
let b = binding(
"provider.knowledge.chronicle",
serde_json::json!({
EXTENSION_ID_PARAM: "greentic.rag-http",
TOOL_NAME_PARAM: "search_knowledge",
}),
);
assert!(
matches!(ExtensionKnowledge::claim_of(&b), Claim::NotOurs),
"a Chronicle binding must fall through to the wrapped backend"
);
}
#[test]
fn missing_or_blank_ids_do_not_claim_the_binding() {
let no_tool = binding(
EXTENSION_PROVIDER_ID,
serde_json::json!({ EXTENSION_ID_PARAM: "greentic.rag-http" }),
);
assert!(matches!(
ExtensionKnowledge::claim_of(&no_tool),
Claim::Malformed(TOOL_NAME_PARAM)
));
let blank = binding(
EXTENSION_PROVIDER_ID,
serde_json::json!({ EXTENSION_ID_PARAM: " ", TOOL_NAME_PARAM: "search_knowledge" }),
);
assert!(matches!(
ExtensionKnowledge::claim_of(&blank),
Claim::Malformed(EXTENSION_ID_PARAM)
));
}
#[tokio::test]
async fn a_binding_whose_target_does_not_read_is_reported_not_fallen_through() {
let inner = Arc::new(RecordingInner {
ingested: std::sync::Mutex::new(Vec::new()),
});
let broken = binding(
EXTENSION_PROVIDER_ID,
serde_json::json!({ EXTENSION_ID_PARAM: "greentic.rag-http" }),
);
let err = adapter(Some(inner))
.search_bound(
&tenant(),
KnowledgeQuery {
query: "q".into(),
limit: Some(3),
},
Some(&broken),
)
.await
.expect_err("a declared provider with no readable target is an error");
let KnowledgeError::Backend(message) = &err else {
panic!("expected a Backend error the loop will warn about, got {err:?}");
};
assert!(
message.contains(TOOL_NAME_PARAM),
"the diagnostic must name the key that did not read: {message}"
);
}
struct RecordingInner {
ingested: std::sync::Mutex<Vec<String>>,
}
#[async_trait::async_trait]
impl Knowledge for RecordingInner {
async fn ingest(
&self,
_tenant: &TenantCtx,
chunks: Vec<KnowledgeChunk>,
) -> KnowledgeResult<IngestOutcome> {
let ids: Vec<String> = chunks.iter().map(|c| c.doc_id.clone()).collect();
self.ingested.lock().unwrap().extend(ids.clone());
Ok(IngestOutcome { chunk_ids: ids })
}
async fn search(
&self,
_tenant: &TenantCtx,
_query: KnowledgeQuery,
) -> KnowledgeResult<Vec<RetrievedChunk>> {
Ok(vec![RetrievedChunk {
text: "from the wrapped backend".to_string(),
score: 1.0,
doc_id: None,
chunk_index: None,
metadata: serde_json::Map::new(),
}])
}
}
fn tenant() -> TenantCtx {
TenantCtx::new(
greentic_types::EnvId::try_from("dev").unwrap(),
greentic_types::TenantId::try_from("acme").unwrap(),
)
}
fn adapter(inner: Option<Arc<dyn Knowledge>>) -> ExtensionKnowledge {
ExtensionKnowledge {
ext: Arc::new(ExtensionRuntime::for_test().unwrap()),
inner,
}
}
#[tokio::test]
async fn ingest_is_a_no_op_with_nothing_wrapped() {
let outcome = adapter(None).ingest(&tenant(), vec![]).await.unwrap();
assert!(
outcome.chunk_ids.is_empty(),
"the corpus belongs to the customer's service; there is nothing to write"
);
}
#[tokio::test]
async fn ingest_with_a_corpus_still_succeeds_rather_than_failing_boot() {
let outcome = adapter(None)
.ingest(
&tenant(),
vec![KnowledgeChunk {
doc_id: "faq".into(),
chunk_index: 0,
text: "anything".into(),
metadata: serde_json::Map::new(),
embedding: None,
}],
)
.await
.expect("a pack carrying a corpus must not fail boot ingestion");
assert!(outcome.chunk_ids.is_empty());
}
#[tokio::test]
async fn a_wrapped_backend_still_receives_ingest_and_non_extension_searches() {
let inner = Arc::new(RecordingInner {
ingested: std::sync::Mutex::new(Vec::new()),
});
let wrapper = adapter(Some(inner.clone()));
wrapper
.ingest(
&tenant(),
vec![KnowledgeChunk {
doc_id: "faq".into(),
chunk_index: 0,
text: "t".into(),
metadata: serde_json::Map::new(),
embedding: None,
}],
)
.await
.unwrap();
assert_eq!(inner.ingested.lock().unwrap().as_slice(), ["faq"]);
let chronicle = binding("provider.knowledge.chronicle", serde_json::json!({}));
let hits = wrapper
.search_bound(
&tenant(),
KnowledgeQuery {
query: "q".into(),
limit: Some(3),
},
Some(&chronicle),
)
.await
.unwrap();
assert_eq!(hits[0].text, "from the wrapped backend");
}
#[test]
fn corpus_backend_walks_past_every_layer_of_this_adapter() {
fn corpus_recorder() -> Arc<dyn Knowledge> {
Arc::new(RecordingInner {
ingested: std::sync::Mutex::new(Vec::new()),
})
}
fn layer(inner: Option<Arc<dyn Knowledge>>) -> Option<Arc<dyn Knowledge>> {
Some(Arc::new(adapter(inner)))
}
assert!(
corpus_in_chain(None).is_none(),
"nothing mounted at all => no corpus backend"
);
assert!(
corpus_in_chain(layer(None)).is_none(),
"this adapter alone is not a corpus"
);
assert!(
corpus_in_chain(layer(layer(None))).is_none(),
"two stacked adapters must not read as a mounted corpus — this is \
exactly what a one-level `wrapped_backend()` check got wrong"
);
assert!(
corpus_in_chain(layer(Some(corpus_recorder()))).is_some(),
"a corpus directly under the adapter must stay visible to its host"
);
assert!(
corpus_in_chain(layer(layer(Some(corpus_recorder())))).is_some(),
"and must stay visible however many adapter layers sit above it"
);
}
#[test]
fn corpus_backend_skips_the_index_wrapper() {
let corpus: Arc<dyn Knowledge> = Arc::new(RecordingInner {
ingested: std::sync::Mutex::new(Vec::new()),
});
let index: Arc<dyn Knowledge> = Arc::new(
crate::runner::knowledge_index::ChronicleIndexKnowledge::new(
Some(corpus.clone()),
None,
None,
),
);
let top: Arc<dyn Knowledge> = Arc::new(adapter(Some(index.clone())));
let found = corpus_in_chain(Some(top)).expect("the corpus is underneath");
assert!(
Arc::ptr_eq(&found, &corpus),
"found `{}` instead of the corpus",
found.backend_id()
);
let bare: Arc<dyn Knowledge> = Arc::new(adapter(Some(Arc::new(
crate::runner::knowledge_index::ChronicleIndexKnowledge::new(None, None, None),
))));
assert!(
corpus_in_chain(Some(bare)).is_none(),
"the index wrapper alone is not a corpus"
);
}
#[tokio::test]
async fn with_nothing_wrapped_a_foreign_binding_is_not_configured() {
let chronicle = binding("provider.knowledge.chronicle", serde_json::json!({}));
let err = adapter(None)
.search_bound(
&tenant(),
KnowledgeQuery {
query: "q".into(),
limit: Some(3),
},
Some(&chronicle),
)
.await
.expect_err("no backend can serve a Chronicle binding here");
assert!(matches!(err, KnowledgeError::NotConfigured), "got {err:?}");
}
}
#[cfg(test)]
mod call_site_ratchet {
use std::path::Path;
const CHRONICLE_MOUNT: &str = "runtime_ext::attach_all(";
const EXTENSION_MOUNT: &str = "knowledge_ext::attach(";
const CONSTRUCTOR: &str = "AgentRuntime::new(";
const INDEX_MOUNTS: &[&str] = &["knowledge_index::attach(", "index_mount.attach("];
const EXEMPT: &[(&str, usize, &str)] = &[
(
"src/runner/playbook_turn.rs",
2,
"a playbook turn, whose synthesised config is `knowledge: None` \
because a playbook has no corpus of its own BY CONTRACT — the \
document has no knowledge field at all, and knowledge reaches a \
playbook as an entry in its tool allow-list like any other \
capability. Mounting retrieval here would give a skill a corpus \
its author never declared and its caller cannot see. Pinned by \
`playbook_turn::tests::a_playbook_turn_carries_no_memory_and_no_knowledge`. \
The second is a test constructor: the OUTER agent of the run-context \
sharing tests, which answers from no corpus",
),
(
"src/runner/run_context_policy.rs",
1,
"one test constructor: the policy tests only need a runtime to read \
its `SharePolicy` back, and answer from no corpus; the production \
path they model (`build_runtime_with_stores`) mounts",
),
(
"src/runner/graph_node.rs",
2,
"the supervisor ROUTING runtime, whose synthesised config is \
`knowledge: None` with an empty tool list — it picks a branch and \
never answers from a corpus — plus one test constructor. Note the \
`agent_ref: None` inline path is NOT one of these: it shares the \
graph-agent constructor and skips the mount at run time, so it \
costs no allowance here",
),
(
"src/runner/agent_node.rs",
3,
"three test constructors; both production paths mount",
),
(
"src/runner/a2a_pack_source.rs",
1,
"one test constructor: the end-to-end test proves a pack's a2a \
sidecar reaches the LLM and the agent; it exercises no retrieval, \
and the production path it models (`build_runtime_with_stores`) \
mounts",
),
(
"src/runner/operala_tools.rs",
1,
"one test constructor for the deep-worker tool context (#785); it \
dispatches tools and answers from no corpus, and the production \
runtime it borrows is built by `agent_node`, which mounts",
),
(
"src/runner/runtime_ext.rs",
1,
"one test constructor: the seam's own unit tests need a runtime with \
nothing mounted, so every backend in the result is the extensions' \
doing",
),
(
"src/runner/knowledge_index/tests.rs",
1,
"one test constructor: proves the graph lane's `IndexMount` reads \
credentials under the tenant it captured, over a runtime with \
nothing else mounted",
),
(
"src/runner/engine.rs",
1,
"one test constructor; engine.rs builds no production AW runtime",
),
];
fn count_calls(text: &str, needle: &str) -> usize {
text.lines()
.filter(|l| {
let t = l.trim_start();
!t.starts_with("//") && !t.starts_with("*")
})
.map(|l| l.matches(needle).count())
.sum()
}
struct Site {
path: String,
chronicle: usize,
extension: usize,
constructors: usize,
}
fn sites() -> Vec<Site> {
fn walk(dir: &Path, out: &mut Vec<Site>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let rel = path.to_string_lossy().replace('\\', "/");
if rel.ends_with("src/runner/knowledge_ext.rs") {
continue; }
let site = Site {
path: rel,
chronicle: count_calls(&text, CHRONICLE_MOUNT),
extension: count_calls(&text, EXTENSION_MOUNT),
constructors: count_calls(&text, CONSTRUCTOR),
};
if site.chronicle > 0 || site.extension > 0 || site.constructors > 0 {
out.push(site);
}
}
}
}
let mut out = Vec::new();
walk(Path::new("src"), &mut out);
out.sort_by(|a, b| a.path.cmp(&b.path));
out
}
fn exempted(path: &str) -> usize {
EXEMPT
.iter()
.find(|(p, _, _)| *p == path)
.map_or(0, |(_, n, _)| *n)
}
#[test]
fn constructor_anchor() {
let offenders: Vec<_> = sites()
.into_iter()
.filter(|s| s.constructors > 0)
.filter(|s| s.constructors != s.extension + exempted(&s.path))
.map(|s| {
format!(
"{}: {} `AgentRuntime::new(`, {} `knowledge_ext::attach(`, {} exempted",
s.path,
s.constructors,
s.extension,
exempted(&s.path)
)
})
.collect();
assert!(
offenders.is_empty(),
"each of these builds an `AgentRuntime` without deciding about \
extension-delegated retrieval. Mount `knowledge_ext::attach`, or add \
the site to `EXEMPT` with a reason — a runtime that silently has no \
retrieval is how the model came to answer from nothing before: {offenders:#?}"
);
}
#[test]
fn mount_anchor() {
let offenders: Vec<_> = sites()
.into_iter()
.filter(|s| s.chronicle > s.extension)
.map(|s| {
format!(
"{}: {} chronicle, {} extension",
s.path, s.chronicle, s.extension
)
})
.collect();
assert!(
offenders.is_empty(),
"these mount a knowledge corpus without also mounting \
`knowledge_ext::attach`, so a worker binding \
`provider.knowledge.extension` silently retrieves nothing and the \
model answers from nothing instead: {offenders:#?}"
);
}
fn is_code(line: &str) -> bool {
let t = line.trim_start();
!t.starts_with("//") && !t.starts_with('*')
}
fn starts_fn(line: &str) -> bool {
let mut t = line.trim_start();
for prefix in ["pub(crate) ", "pub(super) ", "pub ", "async ", "unsafe "] {
t = t.strip_prefix(prefix).unwrap_or(t);
}
t.starts_with("fn ")
}
fn names_index_mount(line: &str) -> bool {
is_code(line) && INDEX_MOUNTS.iter().any(|m| line.contains(m))
}
fn unindexed_mounts() -> Vec<String> {
let mut out = Vec::new();
for site in sites().into_iter().filter(|s| s.extension > 0) {
let Ok(text) = std::fs::read_to_string(&site.path) else {
continue;
};
let lines: Vec<&str> = text.lines().collect();
for (i, line) in lines.iter().enumerate() {
if !is_code(line) || !line.contains(EXTENSION_MOUNT) {
continue;
}
let covered = lines[..=i]
.iter()
.rev()
.take_while(|l| !starts_fn(l))
.any(|l| names_index_mount(l));
if !covered {
out.push(format!("{}:{}", site.path, i + 1));
}
}
}
out
}
#[test]
fn every_extension_mount_also_mounts_the_index() {
let offenders = unindexed_mounts();
assert!(
offenders.is_empty(),
"these mount `knowledge_ext::attach` without a Chronicle-index mount \
(`knowledge_index::attach(` or `index_mount.attach(`) earlier in the \
same function: {offenders:#?}"
);
}
#[test]
fn the_scanned_anchors_still_exist() {
let sites = sites();
let mounts: usize = sites.iter().map(|s| s.extension).sum();
let corpora: usize = sites.iter().map(|s| s.chronicle).sum();
let constructors: usize = sites.iter().map(|s| s.constructors).sum();
let index_mounts: usize = sites
.iter()
.filter_map(|s| std::fs::read_to_string(&s.path).ok())
.map(|text| text.lines().filter(|l| names_index_mount(l)).count())
.sum();
assert!(
index_mounts >= 3,
"expected the Chronicle-index mount beside each of the three \
`knowledge_ext::attach` sites; found {index_mounts} — has \
`knowledge_index::attach` or `index_mount.attach` been renamed?"
);
assert!(
mounts >= 3,
"expected the in-process `dw.agent`, out-of-process serve and \
graph-node mounts; found {mounts} `knowledge_ext::attach` call sites"
);
assert!(
corpora >= 3,
"expected three corpus-extension mounts beside them; found {corpora} — \
has `runtime_ext::attach_all` been renamed?"
);
assert!(
constructors >= mounts,
"found {constructors} `AgentRuntime::new(` against {mounts} mounts — \
has the constructor been renamed?"
);
for (path, _, _) in EXEMPT {
let found = sites.iter().find(|s| s.path == *path);
assert!(
found.is_some_and(|s| s.constructors > 0),
"`EXEMPT` names {path}, which constructs no `AgentRuntime`. A \
stale allowance hides the next unmounted construction added to \
that file — remove it."
);
}
}
}