aKode: rimossa la memoria nativa di Codex e le funzioni senza codice; meno chiamate al modello

Memoria nativa (memories) rimossa del tutto:
- features: memories, memory_tool, external_agent_memory_import, chronicle
  (alias telepathy) diventano Removed; le chiavi restano accettate e
  memories/memory_tool/[memories] producono un solo avviso senza link
  («La sezione [memories] e la chiave memory_tool non sono più usate da
  aKode: la memoria a lungo termine è il plugin memoria di imeAI.»).
- Tolti i crate memories/read, memories/write ed ext/memories, l'avvio
  della pipeline a ogni turno (app-server), l'estensione, /memories e la
  richiesta di attivazione nella TUI, `akode debug clear-memories`,
  l'importazione delle memorie da altri agenti (memory_import.rs,
  detect/memory.rs; il resto di /import resta).
- core: niente più MemoriesConfig, citazioni delle memorie, metriche e
  marcatura «polluted» dei thread; [memories] (MemoriesToml) resta solo
  come sezione accettata e ignorata.
- state: memories_1.sqlite e memories_v2_1.sqlite non vengono più aperti né
  cancellati; la colonna threads.memory_mode resta, nessuna migrazione.
- Protocollo app-server invariato per compatibilità col daemon:
  memory/reset risponde «non supportato» senza cancellare nulla,
  memory/status non è mai pronto, thread/memory/read non ha riassunto.

Altre rimozioni:
- I 14 flag dell'app desktop di OpenAI senza codice (tool_suggest,
  in_app_*, browser_use*, computer_use, bedrock_setup_wizard,
  workspace_dependencies) e analytics_plan_history: Removed, chiavi
  accettate; analytics_plan_history esce da /experimental.
- Skill: tolto l'esperimento «shadow selection» e i selettori collegati.

Meno chiamate al modello non richieste:
- Titoli dei thread: il primo messaggio dell'utente su una riga, troncato a
  36 caratteri; `[tui] auto_title = true` riattiva i titoli generati.
- `[tui] auto_recap` predefinito false; `goals` spento di default.

Privacy: installation_id e gli id di sessione/thread/finestra (e il blocco
dei metadati del turno che li ripete) vanno in client_metadata e negli
header di compatibilità solo ai provider locali (loopback, IP privati
10/8, 172.16/12, 192.168/16, host .local/.lan).

Domini OpenAI: tolti i link visibili (avviso dei flag deprecati, profili,
bubblewrap), l'attribuzione Codex nei commit (sempre spenta), la
riscrittura dell'URL della documentazione OpenAI via MCP e la
registrazione remota dell'exec-server verso host OpenAI (ora solo
loopback); il riconoscimento delle destinazioni OpenAI confronta i domini
etichetta per etichetta. Il binario non contiene più «openai.com» né
«chatgpt.com».

Test adattati (sicurezza compresa: guardian, ruolo ostile, exec-server
ora più restrittivo); rimossi solo quelli del codice tolto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-15 00:49:41 +01:00
parent 0da982206c
commit 854c7a66c9
269 changed files with 1194 additions and 27290 deletions

View File

@@ -13,6 +13,4 @@ pub struct SkillsExtensionConfig {
pub max_context_tokens: Option<NonZeroUsize>,
/// Whether bundled skills are eligible for discovery.
pub bundled_skills_enabled: bool,
/// Whether cheap skill selectors run in shadow mode without changing prompt contents.
pub shadow_selection_enabled: bool,
}

View File

@@ -1,58 +0,0 @@
mod character_ngram;
mod character_routing_card;
mod fielded_bm25;
mod lru;
mod lru_plus_character_routing;
mod lru_plus_lexical;
mod multi_query_lexical;
mod routing_card_lexical;
mod rrf_lexical_char;
mod weighted_lexical;
use akode_skills::SkillDependencies;
pub(crate) use character_ngram::CharacterNgramSkillSelector;
pub(crate) use character_routing_card::CharacterRoutingCardSkillSelector;
pub(crate) use fielded_bm25::FieldedBm25SkillSelector;
pub(crate) use lru::LruSkillSelector;
pub(crate) use lru_plus_character_routing::LruPlusCharacterRoutingSkillSelector;
pub(crate) use lru_plus_character_routing::LruPlusLexicalCharacterRoutingSkillSelector;
pub(crate) use lru_plus_lexical::LruPlusLexicalSkillSelector;
pub(crate) use multi_query_lexical::MultiQueryLexicalSkillSelector;
pub(crate) use routing_card_lexical::RoutingCardLexicalSkillSelector;
pub(crate) use rrf_lexical_char::RrfLexicalCharSkillSelector;
pub(crate) use weighted_lexical::WeightedLexicalSkillSelector;
/// Metadata searched by a cheap skill selector.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SkillSelectionDocument<'a> {
/// Caller-owned identifier returned in [`CheapSkillSelection::candidate_ids`].
pub id: usize,
pub name: &'a str,
pub short_description: Option<&'a str>,
pub description: &'a str,
pub dependencies: Option<&'a SkillDependencies>,
}
/// Bounded output from one cheap skill-selection method.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CheapSkillSelection {
pub candidate_ids: Vec<usize>,
pub query_term_count: usize,
pub query_truncated: bool,
pub candidate_set_truncated: bool,
}
/// Selects likely-relevant skills without changing the model-visible catalog.
///
/// Implementations must be deterministic, side-effect free, and cheap enough to run in shadow
/// mode on every turn. Callers must validate returned IDs against the supplied documents.
pub(crate) trait CheapSkillSelector: Send + Sync {
/// Low-cardinality identifier suitable for experiment metrics.
fn method(&self) -> &'static str;
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection;
}

View File

@@ -1,243 +0,0 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_QUERY_GRAMS: usize = 512;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_DOCUMENT_GRAMS: usize = 512;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const MIN_GRAM_CHARS: usize = 2;
const MAX_GRAM_CHARS: usize = 5;
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct CharacterNgramSkillSelector;
impl CheapSkillSelector for CharacterNgramSkillSelector {
fn method(&self) -> &'static str {
"character_ngram_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let (query_terms, query_terms_truncated) = query_terms(query);
let (query_grams, query_grams_truncated) = grams(&query_terms, MAX_QUERY_GRAMS);
let query_truncated =
query_bytes_truncated || query_terms_truncated || query_grams_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_grams.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let prepared = documents
.iter()
.take(MAX_CANDIDATES)
.map(PreparedDocument::new)
.collect::<Vec<_>>();
let document_frequencies = document_frequencies(&prepared);
let document_count = prepared.len() as f64;
let minimum_matches = query_grams.len().min(3);
let mut scored = prepared
.iter()
.filter_map(|document| {
let (score, matched_grams) = score_document(
document,
&query_grams,
&document_frequencies,
document_count,
);
(matched_grams >= minimum_matches).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.total_cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedDocument<'a> {
id: usize,
name: &'a str,
fields: [HashSet<String>; 3],
}
impl<'a> PreparedDocument<'a> {
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
Self {
id: document.id,
name: document.name,
fields: [
document_grams(document.name),
document_grams(document.short_description.unwrap_or_default()),
document_grams(document.description),
],
}
}
}
fn score_document(
document: &PreparedDocument<'_>,
query_grams: &[String],
document_frequencies: &HashMap<String, usize>,
document_count: f64,
) -> (f64, usize) {
query_grams.iter().fold((0.0, 0), |(score, matched), gram| {
let frequency = document_frequencies.get(gram).copied().unwrap_or_default() as f64;
if frequency == 0.0 {
return (score, matched);
}
let inverse_document_frequency =
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
let field_weight = document
.fields
.iter()
.enumerate()
.filter(|(_, field)| field.contains(gram))
.map(|(index, _)| FIELD_WEIGHTS[index])
.sum::<f64>();
if field_weight == 0.0 {
(score, matched)
} else {
(
score + inverse_document_frequency * field_weight,
matched + 1,
)
}
})
}
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
let mut frequencies = HashMap::new();
for document in documents {
let grams = document
.fields
.iter()
.flatten()
.map(String::as_str)
.collect::<HashSet<_>>();
for gram in grams {
*frequencies.entry(gram.to_string()).or_default() += 1;
}
}
frequencies
}
fn query_terms(query: &str) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in normalized_terms(query)
.into_iter()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
{
if !seen.insert(term.clone()) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn document_grams(value: &str) -> HashSet<String> {
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
let terms = normalized_terms(value)
.into_iter()
.take(MAX_DOCUMENT_TERMS)
.collect::<Vec<_>>();
grams(&terms, MAX_DOCUMENT_GRAMS).0.into_iter().collect()
}
fn grams(terms: &[String], limit: usize) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut grams = Vec::new();
for term in terms {
let characters = term.chars().collect::<Vec<_>>();
let minimum_gram_chars = if term.is_ascii() && characters.len() > MIN_GRAM_CHARS {
MIN_GRAM_CHARS + 1
} else {
MIN_GRAM_CHARS
};
for gram_size in minimum_gram_chars..=MAX_GRAM_CHARS.min(characters.len()) {
for start in 0..=characters.len() - gram_size {
let gram = characters[start..start + gram_size]
.iter()
.collect::<String>();
if !seen.insert(gram.clone()) {
continue;
}
if grams.len() == limit {
return (grams, true);
}
grams.push(gram);
}
}
}
(grams, false)
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "character_ngram_tests.rs"]
mod tests;

View File

@@ -1,79 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn ngrams_match_related_word_forms() {
let documents = [
document(/*id*/ 1, "presentations", "Create visual decks."),
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
];
let selection =
CharacterNgramSkillSelector.select("create a presentation", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn ngrams_tolerate_a_typo() {
let documents = [
document(/*id*/ 1, "postgresql", "Manage a relational database."),
document(/*id*/ 2, "postscript", "Render printable documents."),
];
let selection = CharacterNgramSkillSelector.select(
"repair my postgrez database",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn ngrams_match_cjk_without_word_boundaries() {
let documents = [
document(/*id*/ 1, "演示文稿", "创建幻灯片。"),
document(/*id*/ 2, "电子表格", "分析表格数据。"),
];
let selection =
CharacterNgramSkillSelector.select("帮我制作演示文稿", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn ngrams_report_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = CharacterNgramSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,136 +0,0 @@
use std::collections::HashMap;
use akode_utils_path_uri::LegacyAppPathString;
use crate::HostSkillsSnapshot;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillSourceKind;
use super::CharacterNgramSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_ROUTING_FIELD_BYTES: usize = 4 * 1024;
const MAX_DEPENDENCY_RECORDS: usize = 32;
const MAX_CANDIDATES: usize = 1_000;
#[derive(Clone, Debug, Default)]
pub(crate) struct CharacterRoutingCardSkillSelector {
routing_fields: HashMap<usize, String>,
}
impl CharacterRoutingCardSkillSelector {
pub(crate) fn new(catalog: &SkillCatalog, host_snapshot: Option<&HostSkillsSnapshot>) -> Self {
let host_skill_ids = catalog
.entries
.iter()
.enumerate()
.filter(|(_, entry)| {
entry.authority.kind == SkillSourceKind::Host && entry.is_model_visible()
})
.take(MAX_CANDIDATES)
.filter_map(|(id, entry)| {
let path = LegacyAppPathString::from_string(entry.main_prompt.as_str())
.to_inferred_path_uri()?;
Some((path, id))
})
.collect::<HashMap<_, _>>();
let routing_fields = host_snapshot
.into_iter()
.flat_map(|snapshot| snapshot.outcome().skills.iter())
.filter_map(|skill| {
let id = host_skill_ids.get(&skill.path_to_skills_md)?;
let interface = skill.interface.as_ref()?;
let mut field = String::new();
for value in [
interface.display_name.as_deref(),
interface.short_description.as_deref(),
interface.default_prompt.as_deref(),
]
.into_iter()
.flatten()
{
push_bounded(&mut field, value);
}
(!field.is_empty()).then_some((*id, field))
})
.take(MAX_CANDIDATES)
.collect();
Self { routing_fields }
}
}
impl CheapSkillSelector for CharacterRoutingCardSkillSelector {
fn method(&self) -> &'static str {
"character_routing_card_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CharacterNgramSkillSelector.select(query, documents, /*limit*/ 0);
}
let routing_fields = documents
.iter()
.take(MAX_CANDIDATES)
.map(|document| {
let mut field = String::new();
if let Some(description) = document.short_description {
push_bounded(&mut field, description);
}
if let Some(routing_field) = self.routing_fields.get(&document.id) {
push_bounded(&mut field, routing_field);
}
if let Some(dependencies) = document.dependencies {
for dependency in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
push_bounded(&mut field, dependency.value.as_str());
if let Some(description) = dependency.description.as_deref() {
push_bounded(&mut field, description);
}
}
}
field
})
.collect::<Vec<_>>();
let routing_documents = documents
.iter()
.zip(&routing_fields)
.map(|(document, field)| SkillSelectionDocument {
short_description: (!field.is_empty()).then_some(field.as_str()),
..*document
})
.collect::<Vec<_>>();
let selection = CharacterNgramSkillSelector.select(query, &routing_documents, limit);
CheapSkillSelection {
candidate_set_truncated: documents.len() > MAX_CANDIDATES
|| selection.candidate_set_truncated,
..selection
}
}
}
fn push_bounded(destination: &mut String, value: &str) {
if value.is_empty() || destination.len() == MAX_ROUTING_FIELD_BYTES {
return;
}
if !destination.is_empty() {
destination.push(' ');
}
let remaining = MAX_ROUTING_FIELD_BYTES.saturating_sub(destination.len());
let mut end = value.len().min(remaining);
while !value.is_char_boundary(end) {
end -= 1;
}
destination.push_str(&value[..end]);
}
#[cfg(test)]
#[path = "character_routing_card_tests.rs"]
mod tests;

View File

@@ -1,154 +0,0 @@
use crate::SkillLoadOutcome;
use akode_protocol::protocol::SkillScope;
use akode_skills::SkillDependencies;
use akode_skills::SkillInterface;
use akode_skills::SkillMetadata;
use akode_skills::SkillToolDependency;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillResourceId;
use super::*;
#[test]
fn host_interface_metadata_makes_unlisted_workflow_discoverable() {
let path = AbsolutePathBuf::try_from(std::env::temp_dir().join("routing-card/SKILL.md"))
.expect("temporary directory should be absolute");
let resource = path.to_string_lossy().to_string();
let mut outcome = SkillLoadOutcome::default();
outcome.skills.push(SkillMetadata {
name: "content-tools".to_string(),
description: "Prepare visual content.".to_string(),
short_description: None,
interface: Some(SkillInterface {
display_name: Some("Visual Assets".to_string()),
short_description: Some("Create illustrated assets.".to_string()),
icon_small: None,
icon_large: None,
brand_color: None,
default_prompt: Some("Create an animated pet spritesheet.".to_string()),
}),
dependencies: None,
policy: None,
path_to_skills_md: PathUri::from_abs_path(&path),
scope: SkillScope::User,
plugin_id: None,
});
let snapshot = HostSkillsSnapshot::new(std::sync::Arc::new(outcome));
let catalog = SkillCatalog {
is_partial: false,
entries: vec![SkillCatalogEntry::new(
SkillPackageId(resource.clone()),
SkillAuthority::new(SkillSourceKind::Host, "host"),
"content-tools",
"Prepare visual content.",
SkillResourceId::new(resource),
)],
..Default::default()
};
let selector = CharacterRoutingCardSkillSelector::new(&catalog, Some(&snapshot));
let documents = [document(
/*id*/ 0,
"content-tools",
"Prepare visual content.",
)];
let selection = selector.select(
"make an animated pet spritesheet",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![0], selection.candidate_ids);
}
#[test]
fn connector_dependencies_make_generic_skills_discoverable() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: Some("Post messages to team channels.".to_string()),
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
SkillSelectionDocument {
dependencies: Some(&dependencies),
..document(
/*id*/ 3,
"team-communication",
"Share updates with the team.",
)
},
document(/*id*/ 4, "documents", "Write project updates."),
];
let selector = CharacterRoutingCardSkillSelector::new(
&SkillCatalog::default(),
/*host_snapshot*/ None,
);
let selection = selector.select("post this update in Slack", &documents, /*limit*/ 20);
assert_eq!(Some(3), selection.candidate_ids.first().copied());
}
#[test]
fn strong_baseline_match_is_preserved_alongside_routing_match() {
let documents = [
document(/*id*/ 1, "presentation-tools", "Build meeting decks."),
document(/*id*/ 2, "content-tools", "Prepare visual content."),
];
let selector = CharacterRoutingCardSkillSelector {
routing_fields: HashMap::from([(
2,
"Create a presentation with PowerPoint slides".to_string(),
)]),
};
let selection = selector.select(
"create a PowerPoint presentation",
&documents,
/*limit*/ 2,
);
assert_eq!(vec![2, 1], selection.candidate_ids);
}
#[test]
fn long_routing_metadata_preserves_original_short_description_matches() {
let metadata = (0_u64..60)
.map(|index| format!("{:016x}", index.wrapping_mul(/*rhs*/ 0x9e37_79b9_7f4a_7c15)))
.collect::<Vec<_>>()
.join(" ");
let short_description = "zebra xylophone quasar";
let documents = [SkillSelectionDocument {
short_description: Some(short_description),
..document(/*id*/ 0, "content-tools", "Prepare visual content.")
}];
let selector = CharacterRoutingCardSkillSelector {
routing_fields: HashMap::from([(/*id*/ 0, metadata)]),
};
let selection = selector.select(short_description, &documents, /*limit*/ 20);
assert_eq!(vec![0], selection.candidate_ids);
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,239 +0,0 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
const K1: f64 = 1.2;
const B: f64 = 0.75;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FieldedBm25SkillSelector;
impl CheapSkillSelector for FieldedBm25SkillSelector {
fn method(&self) -> &'static str {
"fielded_bm25_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let (query_terms, query_terms_truncated) = query_terms(query);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_terms.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let prepared = documents
.iter()
.take(MAX_CANDIDATES)
.map(PreparedDocument::new)
.collect::<Vec<_>>();
let averages = average_field_lengths(&prepared);
let document_frequencies = document_frequencies(&prepared);
let document_count = prepared.len() as f64;
let mut scored = prepared
.iter()
.filter_map(|document| {
let score = score_document(
document,
&query_terms,
&document_frequencies,
document_count,
averages,
);
(score > 0.0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.total_cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedDocument<'a> {
id: usize,
name: &'a str,
fields: [Vec<String>; 3],
}
impl<'a> PreparedDocument<'a> {
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
Self {
id: document.id,
name: document.name,
fields: [
document_terms(document.name),
document_terms(document.short_description.unwrap_or_default()),
document_terms(document.description),
],
}
}
}
fn score_document(
document: &PreparedDocument<'_>,
query_terms: &[String],
document_frequencies: &HashMap<String, usize>,
document_count: f64,
average_field_lengths: [f64; 3],
) -> f64 {
query_terms.iter().fold(0.0, |score, query_term| {
let frequency = document_frequencies
.get(query_term)
.copied()
.unwrap_or_default() as f64;
if frequency == 0.0 {
return score;
}
let weighted_term_frequency =
document
.fields
.iter()
.enumerate()
.fold(0.0, |weighted, (field_index, terms)| {
let term_frequency =
terms.iter().filter(|term| *term == query_term).count() as f64;
if term_frequency == 0.0 {
return weighted;
}
let average_length = average_field_lengths[field_index];
let length_ratio = if average_length == 0.0 {
1.0
} else {
terms.len() as f64 / average_length
};
weighted
+ FIELD_WEIGHTS[field_index] * term_frequency / (1.0 - B + B * length_ratio)
});
if weighted_term_frequency == 0.0 {
return score;
}
let inverse_document_frequency =
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
score
+ inverse_document_frequency * weighted_term_frequency * (K1 + 1.0)
/ (weighted_term_frequency + K1)
})
}
fn average_field_lengths(documents: &[PreparedDocument<'_>]) -> [f64; 3] {
if documents.is_empty() {
return [0.0; 3];
}
let totals = documents.iter().fold([0usize; 3], |mut totals, document| {
for (index, field) in document.fields.iter().enumerate() {
totals[index] = totals[index].saturating_add(field.len());
}
totals
});
totals.map(|total| total as f64 / documents.len() as f64)
}
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
let mut frequencies = HashMap::new();
for document in documents {
let terms = document
.fields
.iter()
.flatten()
.map(String::as_str)
.collect::<HashSet<_>>();
for term in terms {
*frequencies.entry(term.to_string()).or_default() += 1;
}
}
frequencies
}
fn query_terms(query: &str) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in normalized_terms(query)
.into_iter()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
{
if !seen.insert(term.clone()) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn document_terms(value: &str) -> Vec<String> {
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
normalized_terms(value)
.into_iter()
.take(MAX_DOCUMENT_TERMS)
.collect()
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "fielded_bm25_tests.rs"]
mod tests;

View File

@@ -1,81 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn bm25_prioritizes_rare_terms() {
let documents = [
document(/*id*/ 1, "review-helper", "Review code and prose."),
document(
/*id*/ 2,
"terraform-review",
"Review Terraform infrastructure.",
),
document(/*id*/ 3, "document-review", "Review Word documents."),
];
let selection =
FieldedBm25SkillSelector.select("review terraform", &documents, /*limit*/ 20);
assert_eq!(vec![2, 3, 1], selection.candidate_ids);
}
#[test]
fn bm25_weights_names_above_descriptions() {
let documents = [
document(/*id*/ 1, "slides", "Create presentations."),
document(/*id*/ 2, "presentations", "Create and edit slides."),
];
let selection = FieldedBm25SkillSelector.select("slides", &documents, /*limit*/ 20);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn bm25_drops_candidates_without_matching_terms() {
let documents = [document(
/*id*/ 1,
"spreadsheets",
"Analyze tabular data.",
)];
let selection =
FieldedBm25SkillSelector.select("render a video", &documents, /*limit*/ 20);
assert!(selection.candidate_ids.is_empty());
}
#[test]
fn bm25_reports_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = FieldedBm25SkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,61 +0,0 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_CANDIDATES: usize = 1_000;
const MAX_QUERY_TERMS: usize = 64;
const MAX_RESULTS: usize = 50;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruSkillSelector {
recent_skill_ids: Vec<usize>,
}
impl LruSkillSelector {
pub(crate) fn new(recent_skill_ids: Vec<usize>) -> Self {
Self { recent_skill_ids }
}
}
impl CheapSkillSelector for LruSkillSelector {
fn method(&self) -> &'static str {
"lru_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let mut query_terms = query.split_whitespace();
let query_term_count = query_terms.by_ref().take(MAX_QUERY_TERMS).count();
let query_truncated = query_terms.next().is_some();
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
let eligible_ids = documents
.iter()
.take(MAX_CANDIDATES)
.map(|document| document.id)
.collect::<HashSet<_>>();
let mut seen_ids = HashSet::new();
CheapSkillSelection {
candidate_ids: self
.recent_skill_ids
.iter()
.copied()
.filter(|id| eligible_ids.contains(id) && seen_ids.insert(*id))
.take(limit.min(MAX_RESULTS))
.collect(),
query_term_count,
query_truncated,
candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_tests.rs"]
mod tests;

View File

@@ -1,136 +0,0 @@
use super::CharacterRoutingCardSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::LruSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
use super::rrf_lexical_char::fuse_rankings_with_constant;
const MAX_RESULTS: usize = 50;
const RRF_K: usize = 10;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusCharacterRoutingSkillSelector {
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
}
impl LruPlusCharacterRoutingSkillSelector {
pub(crate) fn new(
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
) -> Self {
Self {
lru_selector,
character_selector,
}
}
}
impl CheapSkillSelector for LruPlusCharacterRoutingSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_character_routing_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let character =
self.character_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[&recent.candidate_ids, &character.candidate_ids],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent.query_term_count.max(character.query_term_count),
query_truncated: recent.query_truncated || character.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusLexicalCharacterRoutingSkillSelector {
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
}
impl LruPlusLexicalCharacterRoutingSkillSelector {
pub(crate) fn new(
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
) -> Self {
Self {
lru_selector,
character_selector,
}
}
}
impl CheapSkillSelector for LruPlusLexicalCharacterRoutingSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_lexical_character_routing_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let lexical =
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
let character =
self.character_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[
&recent.candidate_ids,
&lexical.candidate_ids,
&character.candidate_ids,
],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent
.query_term_count
.max(lexical.query_term_count)
.max(character.query_term_count),
query_truncated: recent.query_truncated
|| lexical.query_truncated
|| character.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| lexical.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_plus_character_routing_tests.rs"]
mod tests;

View File

@@ -1,179 +0,0 @@
use akode_skills::SkillDependencies;
use akode_skills::SkillToolDependency;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn cold_start_uses_character_routing_metadata() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
document(/*id*/ 10, "compilation", "Compile Rust crates."),
SkillSelectionDocument {
dependencies: Some(&dependencies),
..document(/*id*/ 20, "team-communication", "Share team updates.")
},
];
let expected = CheapSkillSelection {
candidate_ids: vec![20],
query_term_count: 1,
..Default::default()
};
for selector in selectors(Vec::new(), CharacterRoutingCardSkillSelector::default()) {
let method = selector.method();
assert_eq!(
expected,
selector.select("slack", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn recent_and_text_matches_are_merged_without_duplicates() {
let documents = [
document(/*id*/ 10, "rust-build", "Inspect compiler errors."),
document(
/*id*/ 20,
"python-tools",
"Manage Python environments.",
),
document(/*id*/ 30, "monorepo", "Repository conventions."),
];
let expected = CheapSkillSelection {
candidate_ids: vec![20, 30, 10],
query_term_count: 1,
..Default::default()
};
for selector in selectors(
vec![30, 10, 20, 20, 999],
CharacterRoutingCardSkillSelector::default(),
) {
let method = selector.method();
assert_eq!(
expected,
selector.select("python", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn three_way_fusion_retains_short_exact_matches() {
let documents = [
document(/*id*/ 10, "ci", ""),
document(/*id*/ 20, "python", ""),
document(/*id*/ 30, "rust", ""),
];
let expected_rankings = [vec![20, 30], vec![20, 10, 30]];
for (selector, candidate_ids) in
selectors(vec![30], CharacterRoutingCardSkillSelector::default())
.into_iter()
.zip(expected_rankings)
{
let method = selector.method();
assert_eq!(
CheapSkillSelection {
candidate_ids,
query_term_count: 2,
..Default::default()
},
selector.select("ci python", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn fusion_is_deterministic_capped_and_reports_input_bounds() {
let documents = (0..1_001)
.map(|id| document(id, "python", ""))
.collect::<Vec<_>>();
let query = "python ".repeat(4 * 1024);
let expected_rankings = [
[0, 999].into_iter().chain(1..49).collect::<Vec<_>>(),
(0..11)
.chain(std::iter::once(999))
.chain(11..49)
.collect::<Vec<_>>(),
];
for (selector, candidate_ids) in selectors(
vec![1_000, 999, 999, 1_002],
CharacterRoutingCardSkillSelector::default(),
)
.into_iter()
.zip(expected_rankings)
{
let method = selector.method();
let expected = CheapSkillSelection {
candidate_ids,
query_term_count: 64,
query_truncated: true,
candidate_set_truncated: true,
};
assert_eq!(
expected,
selector.select(&query, &documents, /*limit*/ 50),
"{method}"
);
assert_eq!(
expected,
selector.select(&query, &documents, usize::MAX),
"{method}"
);
assert_eq!(
CheapSkillSelection {
candidate_ids: expected.candidate_ids[..7].to_vec(),
..expected
},
selector.select(&query, &documents, /*limit*/ 7),
"{method}"
);
assert_eq!(
CheapSkillSelection::default(),
selector.select(&query, &documents, /*limit*/ 0),
"{method}"
);
}
}
fn selectors(
recent_skill_ids: Vec<usize>,
character_selector: CharacterRoutingCardSkillSelector,
) -> [Box<dyn CheapSkillSelector>; 2] {
let lru_selector = LruSkillSelector::new(recent_skill_ids);
[
Box::new(LruPlusCharacterRoutingSkillSelector::new(
lru_selector.clone(),
character_selector.clone(),
)),
Box::new(LruPlusLexicalCharacterRoutingSkillSelector::new(
lru_selector,
character_selector,
)),
]
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,60 +0,0 @@
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::LruSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
use super::rrf_lexical_char::fuse_rankings_with_constant;
const MAX_RESULTS: usize = 50;
const RRF_K: usize = 10;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusLexicalSkillSelector {
lru_selector: LruSkillSelector,
}
impl LruPlusLexicalSkillSelector {
pub(crate) fn new(lru_selector: LruSkillSelector) -> Self {
Self { lru_selector }
}
}
impl CheapSkillSelector for LruPlusLexicalSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let lexical =
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[&recent.candidate_ids, &lexical.candidate_ids],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent.query_term_count.max(lexical.query_term_count),
query_truncated: recent.query_truncated || lexical.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| lexical.candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_plus_lexical_tests.rs"]
mod tests;

View File

@@ -1,119 +0,0 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn combined_selector_uses_lexical_results_before_invocation_history_exists() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::default()).select(
"manage python environments",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![20], selection.candidate_ids);
}
#[test]
fn combined_selector_merges_recent_and_newly_matching_skills() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
"manage python environments",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![20, 30, 10], selection.candidate_ids);
}
#[test]
fn combined_selector_promotes_skills_supported_by_both_signals() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
"investigate failing ci checks",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![10, 30], selection.candidate_ids);
}
#[test]
fn combined_fusion_keeps_a_top_ranked_skill_ahead_of_a_weak_overlap() {
let recent = std::iter::once(1)
.chain(100..148)
.chain(std::iter::once(2))
.collect::<Vec<_>>();
let lexical = (200..249).chain(std::iter::once(2)).collect::<Vec<_>>();
let fused = fuse_rankings_with_constant(
[&recent, &lexical],
/*limit*/ MAX_RESULTS,
/*rank_constant*/ RRF_K,
);
let top_ranked = fused
.iter()
.position(|candidate| *candidate == 1)
.expect("top-ranked skill should be selected");
let weak_overlap = fused
.iter()
.position(|candidate| *candidate == 2)
.expect("weak overlapping skill should be selected");
assert!(top_ranked < weak_overlap);
}

View File

@@ -1,60 +0,0 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn lru_selector_preserves_recent_invocation_order() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection =
LruSkillSelector::new(vec![30, 10]).select("continue", &documents, /*limit*/ 50);
assert_eq!(vec![30, 10], selection.candidate_ids);
}
#[test]
fn lru_selector_filters_stale_or_duplicate_skills_and_respects_the_limit() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
];
let selection =
LruSkillSelector::new(vec![99, 10, 10, 20]).select("yes", &documents, /*limit*/ 1);
assert_eq!(vec![10], selection.candidate_ids);
}

View File

@@ -1,166 +0,0 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
const MAX_QUERY_VIEWS: usize = 8;
const MAX_DECOMPOSITION_BYTES: usize = 4 * 1024;
const MAX_RESULTS: usize = 50;
const CONNECTORS: &[&str] = &[" and then ", " and ", " then ", " also "];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct MultiQueryLexicalSkillSelector;
impl CheapSkillSelector for MultiQueryLexicalSkillSelector {
fn method(&self) -> &'static str {
"multi_query_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let full_selection =
WeightedLexicalSkillSelector.select(query, documents, limit.min(MAX_RESULTS));
let views = query_views(query);
if views.len() <= 1 || limit == 0 {
return full_selection;
}
let mut candidates = HashMap::new();
record_candidates(&mut candidates, &full_selection, /*view_index*/ 0);
let mut query_truncated = full_selection.query_truncated;
let mut candidate_set_truncated = full_selection.candidate_set_truncated;
for (view_index, view) in views.into_iter().enumerate().skip(1) {
let selection =
WeightedLexicalSkillSelector.select(view, documents, limit.min(MAX_RESULTS));
query_truncated |= selection.query_truncated;
candidate_set_truncated |= selection.candidate_set_truncated;
record_candidates(&mut candidates, &selection, view_index);
}
let mut candidates = candidates.into_values().collect::<Vec<_>>();
candidates.sort_by(|left, right| {
left.best_rank
.cmp(&right.best_rank)
.then_with(|| {
left.full_query_rank
.unwrap_or(usize::MAX)
.cmp(&right.full_query_rank.unwrap_or(usize::MAX))
})
.then_with(|| right.view_count.cmp(&left.view_count))
.then_with(|| left.first_view.cmp(&right.first_view))
.then_with(|| left.id.cmp(&right.id))
});
CheapSkillSelection {
candidate_ids: candidates
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|candidate| candidate.id)
.collect(),
query_term_count: full_selection.query_term_count,
query_truncated,
candidate_set_truncated,
}
}
}
struct RankedCandidate {
id: usize,
best_rank: usize,
full_query_rank: Option<usize>,
view_count: usize,
first_view: usize,
}
fn record_candidates(
candidates: &mut HashMap<usize, RankedCandidate>,
selection: &CheapSkillSelection,
view_index: usize,
) {
for (rank, id) in selection.candidate_ids.iter().copied().enumerate() {
let rank = rank + 1;
candidates
.entry(id)
.and_modify(|candidate| {
candidate.best_rank = candidate.best_rank.min(rank);
candidate.view_count = candidate.view_count.saturating_add(1);
if view_index == 0 {
candidate.full_query_rank = Some(rank);
}
})
.or_insert(RankedCandidate {
id,
best_rank: rank,
full_query_rank: (view_index == 0).then_some(rank),
view_count: 1,
first_view: view_index,
});
}
}
fn query_views(query: &str) -> Vec<&str> {
let full_query = bounded(query, MAX_DECOMPOSITION_BYTES).trim();
if full_query.is_empty() {
return Vec::new();
}
let mut views = vec![full_query];
let mut seen = HashSet::from([full_query]);
for sentence in full_query.split(['\n', '\r', '.', '!', '?', ';']) {
for clause in split_connectors(sentence) {
let clause = clause.trim();
if clause.chars().count() >= 2 && seen.insert(clause) {
views.push(clause);
if views.len() == MAX_QUERY_VIEWS {
return views;
}
}
}
}
views
}
fn bounded(value: &str, max_bytes: usize) -> &str {
if value.len() <= max_bytes {
return value;
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
&value[..end]
}
fn split_connectors(value: &str) -> Vec<&str> {
let lowercase = value.to_ascii_lowercase();
let mut segments = Vec::new();
let mut start = 0;
while start < value.len() {
let next = CONNECTORS
.iter()
.filter_map(|connector| {
lowercase[start..]
.find(connector)
.map(|offset| (start + offset, connector.len()))
})
.min_by_key(|(position, _)| *position);
let Some((position, connector_length)) = next else {
break;
};
segments.push(&value[start..position]);
start = position + connector_length;
}
segments.push(&value[start..]);
segments
}
#[cfg(test)]
#[path = "multi_query_lexical_tests.rs"]
mod tests;

View File

@@ -1,92 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn multi_query_promotes_each_clause_leader() {
let documents = [
document(/*id*/ 1, "rust-format", "Format Rust source code."),
document(/*id*/ 2, "rust-lint", "Fix Rust source lint errors."),
document(/*id*/ 3, "rust-review", "Review Rust source code."),
document(
/*id*/ 4,
"ci-fix",
"Diagnose failing GitHub Actions checks.",
),
];
let selection = MultiQueryLexicalSkillSelector.select(
"format and review Rust source code, and then diagnose failing GitHub Actions checks",
&documents,
/*limit*/ 4,
);
assert!(selection.candidate_ids[..3].contains(&1));
assert!(selection.candidate_ids[..3].contains(&4));
}
#[test]
fn single_query_matches_the_underlying_selector() {
let documents = [
document(/*id*/ 1, "presentations", "Create visual decks."),
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
];
let expected =
WeightedLexicalSkillSelector.select("create presentations", &documents, /*limit*/ 20);
let actual = MultiQueryLexicalSkillSelector.select(
"create presentations",
&documents,
/*limit*/ 20,
);
assert_eq!(expected, actual);
}
#[test]
fn query_views_split_sentences_and_connectors() {
assert_eq!(
vec![
"format code and then fix tests; write a summary",
"format code",
"fix tests",
"write a summary",
],
query_views("format code and then fix tests; write a summary"),
);
}
#[test]
fn multi_query_preserves_bounded_input_signals() {
let long_query = format!("{}\nand inspect logs", "match ".repeat(4 * 1024));
let names = (0..=1_000)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match logs",
dependencies: None,
})
.collect::<Vec<_>>();
let selection =
MultiQueryLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,258 +0,0 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_FIELD_TERMS: usize = 256;
const MAX_DEPENDENCY_RECORDS: usize = 32;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RoutingCardLexicalSkillSelector;
impl CheapSkillSelector for RoutingCardLexicalSkillSelector {
fn method(&self) -> &'static str {
"routing_card_exact_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let query_phrase = normalize(query);
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_phrase.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let mut scored = documents
.iter()
.take(MAX_CANDIDATES)
.filter_map(|document| {
let prepared = PreparedRoutingCard::new(document);
let score = prepared.score(&query_phrase, &query_terms);
(score > 0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedRoutingCard {
name: String,
name_has_searchable_term: bool,
fields: RoutingFields,
}
struct RoutingFields {
name: HashSet<String>,
dependencies: HashSet<String>,
short_description: HashSet<String>,
description: HashSet<String>,
}
impl PreparedRoutingCard {
fn new(document: &SkillSelectionDocument<'_>) -> Self {
let name = normalize_bounded(document.name);
Self {
name_has_searchable_term: name.split_whitespace().any(is_searchable_query_term),
name,
fields: RoutingFields {
name: field_terms(document.name),
dependencies: dependency_terms(document),
short_description: field_terms(document.short_description.unwrap_or_default()),
description: field_terms(document.description),
},
}
}
fn score(&self, query_phrase: &str, query_terms: &[&str]) -> u32 {
let mut score = 0u32;
let name_phrase_matches = contains_phrase(query_phrase, &self.name);
if !self.name.is_empty()
&& ((self.name_has_searchable_term && name_phrase_matches) || query_phrase == self.name)
{
score = score.saturating_add(256);
}
let mut matched_query_terms = 0u32;
for query_term in query_terms {
let mut matched = false;
score = score.saturating_add(score_field(
&self.fields.name,
query_term,
/*weight*/ 80,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.dependencies,
query_term,
/*weight*/ 24,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.short_description,
query_term,
/*weight*/ 12,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.description,
query_term,
/*weight*/ 3,
&mut matched,
));
if matched {
matched_query_terms = matched_query_terms.saturating_add(1);
}
}
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
}
}
fn score_field(terms: &HashSet<String>, query_term: &str, weight: u32, matched: &mut bool) -> u32 {
if terms.contains(query_term) {
*matched = true;
weight
} else {
0
}
}
fn dependency_terms(document: &SkillSelectionDocument<'_>) -> HashSet<String> {
let mut terms = HashSet::new();
let Some(dependencies) = document.dependencies else {
return terms;
};
let mut remaining_bytes = MAX_DOCUMENT_BYTES;
for tool in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
extend_terms(&mut terms, &tool.value, &mut remaining_bytes);
if let Some(description) = tool.description.as_deref() {
extend_terms(&mut terms, description, &mut remaining_bytes);
}
if remaining_bytes == 0 || terms.len() >= MAX_FIELD_TERMS {
break;
}
}
terms
}
fn field_terms(value: &str) -> HashSet<String> {
normalized_terms(bounded(value, MAX_DOCUMENT_BYTES).0)
.into_iter()
.take(MAX_FIELD_TERMS)
.collect()
}
fn extend_terms(terms: &mut HashSet<String>, value: &str, remaining_bytes: &mut usize) {
let value = bounded(value, *remaining_bytes).0;
*remaining_bytes = remaining_bytes.saturating_sub(value.len());
for term in normalized_terms(value) {
if terms.len() == MAX_FIELD_TERMS {
return;
}
terms.insert(term);
}
}
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in query_phrase
.split_whitespace()
.filter(|term| is_searchable_query_term(term))
{
if !seen.insert(term) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn is_searchable_query_term(term: &str) -> bool {
term.chars().count() >= 2 && !STOP_WORDS.contains(&term)
}
fn normalize_bounded(value: &str) -> String {
normalize(bounded(value, MAX_DOCUMENT_BYTES).0)
}
fn normalize(value: &str) -> String {
normalized_terms(value).join(" ")
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn contains_phrase(haystack: &str, needle: &str) -> bool {
haystack == needle
|| haystack.starts_with(&format!("{needle} "))
|| haystack.ends_with(&format!(" {needle}"))
|| haystack.contains(&format!(" {needle} "))
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "routing_card_lexical_tests.rs"]
mod tests;

View File

@@ -1,134 +0,0 @@
use akode_skills::SkillDependencies;
use akode_skills::SkillToolDependency;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn dependency_names_outrank_description_only_matches() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: Some("Send messages to Slack channels.".to_string()),
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
SkillSelectionDocument {
id: 1,
name: "team-messaging",
short_description: None,
description: "Work with team communication.",
dependencies: Some(&dependencies),
},
document(
/*id*/ 2,
"documents",
"Send messages to Slack channels.",
),
];
let selection = RoutingCardLexicalSkillSelector.select(
"send this update to Slack",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn stop_word_name_requires_an_exact_query() {
let documents = [document(/*id*/ 1, "do", "Run a task.")];
let selection = RoutingCardLexicalSkillSelector.select("do", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
assert_eq!(0, selection.query_term_count);
let selection = RoutingCardLexicalSkillSelector.select(
"how do I format Rust",
&documents,
/*limit*/ 20,
);
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
}
#[test]
fn prefixes_do_not_match_field_terms() {
let documents = [document(
/*id*/ 1,
"presentations",
"Create presentations.",
)];
let selection =
RoutingCardLexicalSkillSelector.select("present", &documents, /*limit*/ 20);
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
}
#[test]
fn dependency_records_are_bounded() {
let mut tools = (0..MAX_DEPENDENCY_RECORDS)
.map(|_| SkillToolDependency {
r#type: "app".to_string(),
value: "shared".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
})
.collect::<Vec<_>>();
tools.push(SkillToolDependency {
r#type: "app".to_string(),
value: "unbounded".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
});
let dependencies = SkillDependencies { tools };
let document = SkillSelectionDocument {
id: 1,
name: "dependency-test",
short_description: None,
description: "Test dependencies.",
dependencies: Some(&dependencies),
};
assert_eq!(
HashSet::from(["shared".to_string()]),
dependency_terms(&document)
);
}
#[test]
fn selector_reports_bounded_inputs() {
let documents = [document(
/*id*/ 1,
"presentations",
"Create visual decks.",
)];
let query = "presentations ".repeat(MAX_QUERY_BYTES);
let selection = RoutingCardLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
assert!(selection.query_truncated);
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -1,93 +0,0 @@
use std::collections::HashMap;
use super::CharacterNgramSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
const MAX_FUSION_CANDIDATES: usize = 50;
const RRF_K: usize = 60;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RrfLexicalCharSkillSelector;
impl CheapSkillSelector for RrfLexicalCharSkillSelector {
fn method(&self) -> &'static str {
"rrf_lexical_char_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let lexical = WeightedLexicalSkillSelector.select(
query,
documents,
/*limit*/ MAX_FUSION_CANDIDATES,
);
let character = CharacterNgramSkillSelector.select(
query,
documents,
/*limit*/ MAX_FUSION_CANDIDATES,
);
let candidate_ids = fuse_rankings(
[&lexical.candidate_ids, &character.candidate_ids],
limit.min(MAX_FUSION_CANDIDATES),
);
CheapSkillSelection {
candidate_ids,
query_term_count: lexical.query_term_count.max(character.query_term_count),
query_truncated: lexical.query_truncated || character.query_truncated,
candidate_set_truncated: lexical.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
fn fuse_rankings<const N: usize>(rankings: [&[usize]; N], limit: usize) -> Vec<usize> {
fuse_rankings_with_constant(rankings, limit, RRF_K)
}
pub(super) fn fuse_rankings_with_constant<const N: usize>(
rankings: [&[usize]; N],
limit: usize,
rank_constant: usize,
) -> Vec<usize> {
let mut scores = HashMap::<usize, f64>::new();
let mut best_ranks = HashMap::<usize, usize>::new();
for ranking in rankings {
for (index, id) in ranking.iter().copied().enumerate() {
let rank = index + 1;
*scores.entry(id).or_default() += 1.0 / (rank_constant + rank) as f64;
best_ranks
.entry(id)
.and_modify(|best_rank| *best_rank = (*best_rank).min(rank))
.or_insert(rank);
}
}
let mut candidates = scores.into_iter().collect::<Vec<_>>();
candidates.sort_by(|(left_id, left_score), (right_id, right_score)| {
right_score
.total_cmp(left_score)
.then_with(|| best_ranks[left_id].cmp(&best_ranks[right_id]))
.then_with(|| left_id.cmp(right_id))
});
candidates
.into_iter()
.take(limit)
.map(|(id, _)| id)
.collect()
}
#[cfg(test)]
#[path = "rrf_lexical_char_tests.rs"]
mod tests;

View File

@@ -1,35 +0,0 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn fusion_prefers_candidates_supported_by_both_rankings() {
let fused = fuse_rankings([&[1, 2, 3], &[2, 3, 4]], /*limit*/ 4);
assert_eq!(vec![2, 3, 1, 4], fused);
}
#[test]
fn fusion_uses_rank_and_id_to_break_ties() {
let fused = fuse_rankings([&[20, 10], &[30]], /*limit*/ 3);
assert_eq!(vec![20, 30, 10], fused);
}
#[test]
fn selector_reports_the_combined_input_bounds() {
let documents = [SkillSelectionDocument {
id: 7,
name: "presentations",
short_description: None,
description: "Create visual decks.",
dependencies: None,
}];
let query = "presentation ".repeat(4 * 1024);
let selection = RrfLexicalCharSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(vec![7], selection.candidate_ids);
assert!(selection.query_truncated);
assert!(!selection.candidate_set_truncated);
}

View File

@@ -1,208 +0,0 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct WeightedLexicalSkillSelector;
impl CheapSkillSelector for WeightedLexicalSkillSelector {
fn method(&self) -> &'static str {
"weighted_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let query_phrase = normalize_phrase(query);
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_terms.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let mut scored = documents
.iter()
.take(MAX_CANDIDATES)
.filter_map(|document| {
let score = score_document(&query_phrase, &query_terms, document);
(score > 0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
fn score_document(
query_phrase: &str,
query_terms: &[&str],
document: &SkillSelectionDocument<'_>,
) -> u32 {
let name = normalize_bounded(document.name);
let short_description = document
.short_description
.map(normalize_bounded)
.unwrap_or_default();
let description = normalize_bounded(document.description);
let name_terms = phrase_terms(&name);
let short_description_terms = phrase_terms(&short_description);
let description_terms = phrase_terms(&description);
let mut score = 0u32;
if !name.is_empty() && contains_phrase(query_phrase, &name) {
score = score.saturating_add(256);
}
let mut matched_query_terms = 0u32;
for query_term in query_terms {
let mut matched = false;
if name == *query_term {
score = score.saturating_add(128);
matched = true;
} else if name_terms.contains(query_term) {
score = score.saturating_add(64);
matched = true;
} else if contains_related_term(&name_terms, query_term) {
score = score.saturating_add(24);
matched = true;
}
if short_description_terms.contains(query_term) {
score = score.saturating_add(16);
matched = true;
} else if contains_related_term(&short_description_terms, query_term) {
score = score.saturating_add(6);
matched = true;
}
if description_terms.contains(query_term) {
score = score.saturating_add(4);
matched = true;
} else if contains_related_term(&description_terms, query_term) {
score = score.saturating_add(1);
matched = true;
}
if matched {
matched_query_terms = matched_query_terms.saturating_add(1);
}
}
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
}
fn normalize_bounded(value: &str) -> String {
normalize_phrase(bounded(value, MAX_DOCUMENT_BYTES).0)
}
fn normalize_phrase(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut previous_was_separator = true;
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
previous_was_separator = false;
} else if !previous_was_separator {
normalized.push(' ');
previous_was_separator = true;
}
}
if previous_was_separator {
normalized.pop();
}
normalized
}
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in query_phrase
.split_whitespace()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(term))
{
if !seen.insert(term) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn phrase_terms(phrase: &str) -> HashSet<&str> {
phrase.split_whitespace().take(MAX_DOCUMENT_TERMS).collect()
}
fn contains_phrase(haystack: &str, needle: &str) -> bool {
haystack == needle
|| haystack.starts_with(&format!("{needle} "))
|| haystack.ends_with(&format!(" {needle}"))
|| haystack.contains(&format!(" {needle} "))
}
fn contains_related_term(terms: &HashSet<&str>, query_term: &str) -> bool {
if query_term.chars().count() < 4 {
return false;
}
terms.iter().any(|term| {
term.chars().count() >= 4 && (term.starts_with(query_term) || query_term.starts_with(*term))
})
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "weighted_lexical_tests.rs"]
mod tests;

View File

@@ -1,176 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn lexical_selector_prioritizes_an_exact_skill_name() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "slides-helper",
short_description: None,
description: "Create presentations and visual decks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "presentations",
short_description: None,
description: "Create or edit PowerPoint presentations.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "spreadsheets",
short_description: None,
description: "Analyze tabular data.",
dependencies: None,
},
];
let selection = WeightedLexicalSkillSelector.select(
"Use presentations to create a deck",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![20, 10], selection.candidate_ids);
assert!(!selection.query_truncated);
assert!(!selection.candidate_set_truncated);
}
#[test]
fn lexical_selector_uses_descriptions_and_drops_zero_score_candidates() {
let documents = [
SkillSelectionDocument {
id: 1,
name: "ci-helper",
short_description: Some("Diagnose continuous integration failures."),
description: "Inspect failing GitHub Actions checks and logs.",
dependencies: None,
},
SkillSelectionDocument {
id: 2,
name: "document-editor",
short_description: None,
description: "Edit Word documents.",
dependencies: None,
},
];
let selection = WeightedLexicalSkillSelector.select(
"Please diagnose the failing GitHub Actions check",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn lexical_selector_respects_requested_limit() {
let names = (0..10)
.map(|index| format!("lint-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "Fix lint errors.",
dependencies: None,
})
.collect::<Vec<_>>();
let selection =
WeightedLexicalSkillSelector.select("fix lint errors", &documents, /*limit*/ 3);
assert_eq!(3, selection.candidate_ids.len());
}
#[test]
fn lexical_selector_reports_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = WeightedLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
assert!(
selection
.candidate_ids
.iter()
.all(|id| *id < MAX_CANDIDATES)
);
}
#[test]
fn lexical_selector_caps_query_terms() {
let query = (0..=MAX_QUERY_TERMS)
.map(|index| format!("term{index}"))
.collect::<Vec<_>>()
.join(" ");
let documents = [SkillSelectionDocument {
id: 1,
name: "term0",
short_description: None,
description: "term0",
dependencies: None,
}];
let selection = WeightedLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(MAX_QUERY_TERMS, selection.query_term_count);
assert!(selection.query_truncated);
}
#[test]
fn lexical_selector_returns_nothing_for_stop_words_only() {
let documents = [SkillSelectionDocument {
id: 1,
name: "anything",
short_description: None,
description: "Do anything.",
dependencies: None,
}];
let selection =
WeightedLexicalSkillSelector.select("please use the", &documents, /*limit*/ 20);
assert_eq!(CheapSkillSelection::default(), selection);
}
#[test]
fn selector_can_be_used_behind_the_shared_trait() {
fn run(selector: &dyn CheapSkillSelector) -> CheapSkillSelection {
selector.select(
"review code",
&[SkillSelectionDocument {
id: 7,
name: "code-review",
short_description: None,
description: "Review code.",
dependencies: None,
}],
/*limit*/ 20,
)
}
assert_eq!(vec![7], run(&WeightedLexicalSkillSelector).candidate_ids);
}

View File

@@ -14,8 +14,6 @@ use akode_extension_api::ExtensionWarning;
use akode_extension_api::PromptFragment;
use akode_extension_api::PromptSlot;
use akode_extension_api::SkillInvocationContributor;
use akode_extension_api::SkillInvocationInput;
use akode_extension_api::SkillInvocationKind;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolCall;
@@ -56,7 +54,6 @@ use crate::render::truncate_utf8_to_bytes;
use crate::render_observability::CatalogSurface;
use crate::render_observability::record_catalog_render;
use crate::selection::collect_explicit_skill_mentions;
use crate::shadow_selection_experiment::ShadowSelectionExperiment;
use crate::sources::SkillProviders;
use crate::state::HostSkillsCatalogInWorldState;
use crate::state::SkillsSessionState;
@@ -73,7 +70,6 @@ struct SkillsExtension<C> {
providers: SkillProviders,
event_sink: Arc<dyn ExtensionEventSink>,
config_from_host: Arc<dyn Fn(&C) -> SkillsExtensionConfig + Send + Sync>,
shadow_selection: Arc<ShadowSelectionExperiment>,
}
#[derive(Default)]
@@ -291,26 +287,6 @@ where
fn requires_host_skill_discovery(&self) -> bool {
self.providers.has_host_provider()
}
fn on_skill_invocation<'a>(
&'a self,
input: SkillInvocationInput<'a>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
match input.kind {
SkillInvocationKind::Implicit => {
if let Some(state) = input
.thread_store
.get::<SkillsThreadState>()
.and_then(|state| state.shadow_selection_turn(input.turn_id))
{
state.record_invocation(input.skill_resource);
}
}
SkillInvocationKind::Explicit => {}
}
})
}
}
impl<C> TurnInputContributor for SkillsExtension<C>
@@ -362,26 +338,6 @@ where
}
let selected_entries = collect_explicit_skill_mentions(&input.user_input, &catalog);
let shadow_selection_turn = if config.shadow_selection_enabled {
let mut shadow_catalog = catalog.clone();
if let Some(host_skills) = host_skills {
shadow_catalog.extend(host_skills.clone());
}
let shadow_selected_entries =
collect_explicit_skill_mentions(&input.user_input, &shadow_catalog);
Some(self.shadow_selection.start(
&input,
shadow_catalog,
&shadow_selected_entries,
host_snapshot.clone(),
Arc::clone(&thread_state.recent_skill_invocations),
Arc::clone(&thread_state.shadow_task_context),
))
} else {
None
};
thread_state
.replace_shadow_selection_turn(input.turn_id.clone(), shadow_selection_turn);
let mut fragments: Vec<Box<dyn ContextualUserFragment + Send>> = Vec::new();
if config.include_instructions && !host_catalog_in_world_state {
let mut turn_catalog = catalog.clone();
@@ -602,7 +558,7 @@ pub fn install_with_providers<C>(
pub fn install_with_providers_and_metrics<C>(
registry: &mut ExtensionRegistryBuilder<C>,
providers: SkillProviders,
metrics_client: Option<MetricsClient>,
_metrics_client: Option<MetricsClient>,
config_from_host: impl Fn(&C) -> SkillsExtensionConfig + Send + Sync + 'static,
) where
C: Send + Sync + 'static,
@@ -611,7 +567,6 @@ pub fn install_with_providers_and_metrics<C>(
providers,
event_sink: registry.event_sink(),
config_from_host: Arc::new(config_from_host),
shadow_selection: Arc::new(ShadowSelectionExperiment::new(metrics_client)),
});
registry.thread_lifecycle_contributor(extension.clone());
registry.turn_lifecycle_contributor(Arc::new(SkillTelemetry));

View File

@@ -47,7 +47,6 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
omit_descriptions: false,
max_context_tokens: None,
bundled_skills_enabled: false,
shadow_selection_enabled: false,
},
});

View File

@@ -5,7 +5,6 @@ mod catalog_observability;
mod catalog_prompt;
mod catalog_state;
mod config;
mod dynamic_skill_selector;
mod extension;
mod fragments;
mod host_aliases;
@@ -22,7 +21,6 @@ mod render;
mod render_observability;
mod required;
mod selection;
mod shadow_selection_experiment;
mod sources;
mod state;
mod step_state;

View File

@@ -69,7 +69,7 @@ async fn discover_host_catalog(
) -> Option<SkillCatalog> {
let host_snapshot = HostSkillsSnapshot::for_step(input.step_store, input.turn_store)
.filter(|_| providers.has_host_provider())?;
if !config.include_instructions && !config.shadow_selection_enabled {
if !config.include_instructions {
return Some(SkillCatalog::default());
}
Some(

View File

@@ -1,363 +0,0 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn recent_invocations_refresh_recency_and_evict_old_skills() {
let history = RecentSkillInvocations::default();
for index in 0..=MAX_SHADOW_RESULTS {
history.record(format!("skill-{index}"));
}
history.record("skill-1".to_string());
let recent = history.snapshot();
assert_eq!(MAX_SHADOW_RESULTS, recent.len());
assert_eq!(Some("skill-1"), recent.first().map(String::as_str));
assert_eq!(Some("skill-2"), recent.last().map(String::as_str));
assert!(!recent.iter().any(|skill| skill == "skill-0"));
}
#[test]
fn rank_buckets_distinguish_results_above_twenty() {
assert_eq!("11_20", rank_bucket(Some(20)));
assert_eq!("21_50", rank_bucket(Some(21)));
assert_eq!("21_50", rank_bucket(Some(50)));
assert_eq!("miss", rank_bucket(Some(51)));
}
// These tests deliberately occupy the process-wide budget and must drain their
// workers before the next test starts.
static RANKING_TESTS: Semaphore = Semaphore::const_new(1);
#[tokio::test]
async fn turn_input_and_history_advance_while_ranking_is_blocked()
-> Result<(), Box<dyn std::error::Error>> {
use std::collections::BTreeMap;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::SkillInvocationInput;
use akode_extension_api::SkillInvocationKind;
use akode_extension_api::ThreadStartInput;
use akode_otel::MetricsConfig;
use akode_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
use crate::SkillProviders;
use crate::SkillsExtensionConfig;
use crate::SkillsThreadState;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillResourceId;
use crate::install_with_providers_and_metrics;
use crate::step_state::SkillsStepState;
let _serial = RANKING_TESTS.acquire().await.unwrap();
let slots = RANKING_SLOTS.acquire_many(2).await?;
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"akode-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new(),
Some(metrics.clone()),
SkillsExtensionConfig::clone,
);
let registry = builder.build();
let config = SkillsExtensionConfig {
include_instructions: false,
catalog_deltas_enabled: false,
omit_descriptions: false,
max_context_tokens: None,
bundled_skills_enabled: false,
shadow_selection_enabled: true,
};
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
for turn_id in ["first", "second"] {
let turn_store = ExtensionData::new(turn_id);
let host_catalog = SkillCatalog {
is_partial: false,
entries: ["x", "hidden", "selected"]
.into_iter()
.map(|name| {
let mut entry = SkillCatalogEntry::new(
SkillPackageId(name.to_string()),
SkillAuthority::new(SkillSourceKind::Host, "host"),
name,
"zzzz",
SkillResourceId::new(format!("{name}/SKILL.md")),
);
entry.prompt_visible = name != "hidden";
entry
})
.collect(),
warnings: Vec::new(),
};
turn_store.insert(SkillsStepState {
discovery_v2: false,
tools_enabled: false,
catalog: thread_store
.get::<SkillsThreadState>()
.unwrap()
.prepare_step_catalog(SkillCatalog::default(), /*discovery_v2*/ false),
host_catalog: Some(host_catalog),
config: config.clone(),
});
let fragments = tokio::time::timeout(
Duration::from_secs(10),
registry.turn_input_contributors()[0].contribute(
TurnInputContext {
step_store: &turn_store,
turn_id: turn_id.to_string(),
user_input: vec![UserInput::Skill {
name: "selected".to_string(),
path: "selected/SKILL.md".into(),
}],
environments: Vec::new(),
},
/*extension_metrics*/ None,
&session_store,
&thread_store,
&turn_store,
),
)
.await?;
assert!(fragments.is_empty());
tokio::task::yield_now().await;
// Synchronous ranking would emit run metrics despite the occupied budget;
// awaiting admission in contribute would instead time out above.
assert!(
metrics
.snapshot()?
.scope_metrics()
.all(|scope| { scope.metrics().all(|metric| metric.name() != RUN_METRIC) })
);
for resource in [
"x/SKILL.md",
"x\\SKILL.md",
"hidden/SKILL.md",
"selected/SKILL.md",
] {
registry.skill_invocation_contributors()[0]
.on_skill_invocation(SkillInvocationInput {
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
turn_id,
skill_resource: resource,
kind: SkillInvocationKind::Implicit,
})
.await;
}
assert_eq!(
vec!["x/SKILL.md"],
thread_store
.get::<SkillsThreadState>()
.unwrap()
.recent_skill_invocations
.snapshot()
);
}
// Both observers disappear before either ranking starts. Their queued unique
// invocations must still be scored against their own turn-start histories.
drop(thread_store);
drop(slots);
let mut runs = BTreeMap::new();
let mut hits = BTreeMap::new();
tokio::time::timeout(Duration::from_secs(10), async {
loop {
// snapshot() exports deltas, so retain observations across polls.
let snapshot = metrics.snapshot().unwrap();
for metric in snapshot.scope_metrics().flat_map(ScopeMetrics::metrics) {
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
continue;
};
for point in sum.data_points() {
let attribute = |key: &str| {
point
.attributes()
.find(|attribute| attribute.key.as_str() == key)
.unwrap()
.value
.as_str()
.to_string()
};
match metric.name() {
RUN_METRIC => {
*runs.entry(attribute("method")).or_insert(0) += point.value()
}
"codex.skills.shadow_selection.invocation" => {
assert_eq!("ascii_latin", attribute("query_script"));
*hits
.entry((attribute("method"), attribute("hit"), attribute("rank")))
.or_insert(0) += point.value();
}
_ => {}
}
}
}
if hits.values().sum::<u64>() >= 24 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
let mut expected_runs = BTreeMap::new();
let mut expected_hits = BTreeMap::new();
for (method, uses_history) in [
("weighted_lexical_v1", false),
("fielded_bm25_v1", false),
("character_ngram_v1", false),
("multi_query_lexical_v1", false),
("rrf_lexical_char_v1", false),
("routing_card_exact_v1", false),
("character_routing_card_v1", false),
("lru_v1", true),
("lru_plus_lexical_v1", true),
("lru_plus_character_routing_v1", true),
("lru_plus_lexical_character_routing_v1", true),
("task_context_fusion_v1", true),
] {
expected_runs.insert(method.to_string(), 2);
expected_hits.insert(
(method.to_string(), "false".to_string(), "miss".to_string()),
if uses_history { 1 } else { 2 },
);
if uses_history {
expected_hits.insert((method.to_string(), "true".to_string(), "1".to_string()), 1);
}
}
assert_eq!(expected_runs, runs);
assert_eq!(expected_hits, hits);
Ok(())
}
/// Hold an actual blocking worker until the test releases it. The timeout keeps a
/// failing assertion from leaving runtime shutdown stuck on the test worker.
struct BlockedSelector {
started: tokio::sync::mpsc::UnboundedSender<()>,
release: Mutex<std::sync::mpsc::Receiver<()>>,
}
impl CheapSkillSelector for BlockedSelector {
fn method(&self) -> &'static str {
"blocked_test"
}
fn select(
&self,
_query: &str,
_documents: &[SkillSelectionDocument<'_>],
_limit: usize,
) -> CheapSkillSelection {
self.started.send(()).unwrap();
self.release
.lock()
.unwrap()
.recv_timeout(Duration::from_secs(10))
.unwrap();
CheapSkillSelection::default()
}
}
#[tokio::test]
async fn ranking_budget_is_shared_and_held_until_blocking_work_finishes() {
let _serial = RANKING_TESTS.acquire().await.unwrap();
let mut workers = Vec::new();
for index in 0..3 {
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
let (release, releases) = std::sync::mpsc::channel();
// Separate experiment instances must share the same process-wide budget.
let experiment = Arc::new(ShadowSelectionExperiment {
selectors: vec![Box::new(BlockedSelector {
started,
release: Mutex::new(releases),
})],
metrics_client: None,
});
let query = ShadowQuery {
text: "test".to_string(),
truncated: false,
};
let input = ShadowSelectionInput {
catalog: SkillCatalog::default(),
host_snapshot: None,
task_snapshot: TaskContextSnapshot {
query: query.clone(),
recent_skills: Vec::new(),
},
query,
eligible_ids: HashSet::new(),
recent_skill_resources: Vec::new(),
};
let (invocations, pending) = tokio::sync::mpsc::unbounded_channel();
drop(invocations);
let mut worker = Box::pin(experiment.evaluate(input, pending, tracing::Span::none()));
// Polling to the first await deterministically attempts admission.
assert!(futures::poll!(worker.as_mut()).is_pending());
if index < 2 {
assert_eq!(
Some(()),
tokio::time::timeout(Duration::from_secs(10), starts.recv())
.await
.unwrap()
);
assert_eq!(1 - index, RANKING_SLOTS.available_permits());
} else {
assert!(starts.try_recv().is_err());
}
workers.push((tokio::spawn(worker), release, starts));
}
let (first, release_first, _) = workers.remove(0);
release_first.send(()).unwrap();
first.await.unwrap();
let (second, release_second, _) = workers.remove(0);
let (third, release_third, mut third_starts) = workers.remove(0);
assert_eq!(
Some(()),
tokio::time::timeout(Duration::from_secs(10), third_starts.recv())
.await
.unwrap()
);
assert_eq!(0, RANKING_SLOTS.available_permits());
// Cancelling evaluation cannot free a slot still occupied by blocking work.
third.abort();
assert!(third.await.unwrap_err().is_cancelled());
assert_eq!(0, RANKING_SLOTS.available_permits());
release_second.send(()).unwrap();
release_third.send(()).unwrap();
second.await.unwrap();
let _all_returned =
tokio::time::timeout(Duration::from_secs(10), RANKING_SLOTS.acquire_many(2))
.await
.unwrap()
.unwrap();
}

View File

@@ -1,607 +0,0 @@
//! Shadow-only skill ranking. Capture turn inputs before recording new relevance signals,
//! then evaluate on a blocking worker without delaying model input construction.
//! This experiment is temporary and should be removed after evaluation.
mod task_context;
use task_context::TaskContextSnapshot;
pub(crate) use task_context::ShadowTaskContext;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use std::time::Instant;
use crate::HostSkillsSnapshot;
use akode_extension_api::TurnInputContext;
use akode_otel::MetricsClient;
use akode_protocol::user_input::UserInput;
use tokio::sync::Semaphore;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use crate::dynamic_skill_selector::CharacterNgramSkillSelector;
use crate::dynamic_skill_selector::CharacterRoutingCardSkillSelector;
use crate::dynamic_skill_selector::CheapSkillSelection;
use crate::dynamic_skill_selector::CheapSkillSelector;
use crate::dynamic_skill_selector::FieldedBm25SkillSelector;
use crate::dynamic_skill_selector::LruPlusCharacterRoutingSkillSelector;
use crate::dynamic_skill_selector::LruPlusLexicalCharacterRoutingSkillSelector;
use crate::dynamic_skill_selector::LruPlusLexicalSkillSelector;
use crate::dynamic_skill_selector::LruSkillSelector;
use crate::dynamic_skill_selector::MultiQueryLexicalSkillSelector;
use crate::dynamic_skill_selector::RoutingCardLexicalSkillSelector;
use crate::dynamic_skill_selector::RrfLexicalCharSkillSelector;
use crate::dynamic_skill_selector::SkillSelectionDocument;
use crate::dynamic_skill_selector::WeightedLexicalSkillSelector;
const MAX_SHADOW_QUERY_BYTES: usize = 16 * 1024;
const MAX_SHADOW_RESULTS: usize = 50;
// Share the CPU budget across threads and extension registries. Admission happens
// only in the background; turn preparation never waits for a ranking slot.
static RANKING_SLOTS: Semaphore = Semaphore::const_new(2);
const RUN_METRIC: &str = "codex.skills.shadow_selection";
const DURATION_METRIC: &str = "codex.skills.shadow_selection.duration_ms";
const CATALOG_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.catalog_entries";
const SELECTED_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.selected_entries";
const QUERY_TERM_COUNT_METRIC: &str = "codex.skills.shadow_selection.query_terms";
const REDUCTION_BPS_METRIC: &str = "codex.skills.shadow_selection.reduction_bps";
pub(crate) struct ShadowSelectionExperiment {
selectors: Vec<Box<dyn CheapSkillSelector>>,
metrics_client: Option<MetricsClient>,
}
impl ShadowSelectionExperiment {
pub(crate) fn new(metrics_client: Option<MetricsClient>) -> Self {
Self {
selectors: vec![
Box::new(WeightedLexicalSkillSelector),
Box::new(FieldedBm25SkillSelector),
Box::new(CharacterNgramSkillSelector),
Box::new(MultiQueryLexicalSkillSelector),
Box::new(RrfLexicalCharSkillSelector),
Box::new(RoutingCardLexicalSkillSelector),
],
metrics_client,
}
}
/// Freeze prediction inputs before this turn can contribute new invocation history.
/// The returned state observes invocations even while its rankings are still pending.
pub(crate) fn start(
self: &Arc<Self>,
input: &TurnInputContext<'_>,
catalog: SkillCatalog,
explicitly_selected: &[SkillCatalogEntry],
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
recent_skill_invocations: Arc<RecentSkillInvocations>,
task_context: Arc<ShadowTaskContext>,
) -> ShadowSelectionTurnState {
let query = build_shadow_query(&input.user_input);
let task_snapshot = task_context.begin_turn(&input.turn_id, &query, &input.user_input);
let recent_skill_resources = recent_skill_invocations.snapshot();
let explicitly_selected_skill_resources = explicitly_selected
.iter()
.map(|entry| normalize_skill_resource(entry.main_prompt.as_str()))
.collect::<HashSet<_>>();
let mut eligible_ids = HashSet::new();
let mut eligible_skill_resources = HashSet::new();
for (id, entry) in catalog.entries.iter().enumerate() {
// Invocation observation covers host shell use.
if !entry.is_model_visible() || entry.authority.kind != SkillSourceKind::Host {
continue;
}
let resource = normalize_skill_resource(entry.main_prompt.as_str());
if !explicitly_selected_skill_resources.contains(&resource) {
eligible_ids.insert(id);
eligible_skill_resources.insert(resource);
}
}
let (invocations, pending_invocations) = tokio::sync::mpsc::unbounded_channel();
let state = ShadowSelectionTurnState {
turn_id: input.turn_id.clone(),
eligible_skill_resources,
seen_skill_resources: Mutex::new(HashSet::new()),
recent_skill_invocations,
task_context: Arc::clone(&task_context),
invocations,
};
// Explicit intent is a relevance signal even if the subsequent prompt read fails.
// It can update future turns now that this turn's prediction inputs are frozen.
for entry in explicitly_selected.iter().filter(|entry| {
entry.is_model_visible() && entry.authority.kind == SkillSourceKind::Host
}) {
task_context.record(
&input.turn_id,
normalize_skill_resource(entry.main_prompt.as_str()),
);
}
let selection_input = ShadowSelectionInput {
catalog,
host_snapshot,
query,
eligible_ids,
recent_skill_resources,
task_snapshot,
};
tokio::spawn(Arc::clone(self).evaluate(
selection_input,
pending_invocations,
tracing::Span::current(),
));
state
}
/// Own the rankings and drain observations for this turn, including those queued
/// during ranking. Dropping the turn's observer closes the channel after its last read.
async fn evaluate(
self: Arc<Self>,
input: ShadowSelectionInput,
mut invocations: tokio::sync::mpsc::UnboundedReceiver<String>,
parent: tracing::Span,
) {
let query_script = query_script_tag(&input.query.text);
let experiment = Arc::clone(&self);
let Ok(permit) = RANKING_SLOTS.acquire().await else {
return;
};
let ranked_selections = match tokio::task::spawn_blocking(move || {
// A cancelled async task must not release capacity while its blocking
// worker is still running. Release it before waiting for invocations.
let _permit = permit;
experiment.rank(input, parent)
})
.await
{
Ok(rankings) => rankings,
Err(error) => {
tracing::warn!(%error, "shadow skill selection failed");
return;
}
};
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
while let Some(skill_resource) = invocations.recv().await {
for selection in &ranked_selections {
let rank = selection
.skill_resources
.iter()
.position(|candidate| candidate == &skill_resource)
.map(|index| index + 1);
let tags = [
("method", selection.method),
("hit", bool_tag(rank.is_some())),
("rank", rank_bucket(rank)),
("query_script", query_script),
];
let _ = metrics_client.counter(
"codex.skills.shadow_selection.invocation",
/*inc*/ 1,
&tags,
);
}
}
}
#[tracing::instrument(
name = "skills.shadow_selection.rank",
level = "info",
parent = &parent,
skip_all,
fields(catalog_entries = input.eligible_ids.len())
)]
fn rank(&self, input: ShadowSelectionInput, parent: tracing::Span) -> Vec<RankedSelection> {
let ShadowSelectionInput {
catalog,
host_snapshot,
query,
eligible_ids,
recent_skill_resources,
task_snapshot,
} = input;
let documents = catalog
.entries
.iter()
.enumerate()
.filter(|(id, _)| eligible_ids.contains(id))
.map(|(id, entry)| SkillSelectionDocument {
id,
name: entry.name.as_str(),
short_description: entry.short_description.as_deref(),
description: entry.description.as_str(),
dependencies: entry.dependencies.as_ref(),
})
.collect::<Vec<_>>();
let eligible_skill_ids_by_resource = documents
.iter()
.map(|document| {
(
normalize_skill_resource(catalog.entries[document.id].main_prompt.as_str()),
document.id,
)
})
.collect::<HashMap<_, _>>();
let recent_skill_ids = recent_skill_resources
.iter()
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
.collect();
let routing_selector =
CharacterRoutingCardSkillSelector::new(&catalog, host_snapshot.as_deref());
let lru_selector = LruSkillSelector::new(recent_skill_ids);
let lru_plus_lexical_selector = LruPlusLexicalSkillSelector::new(lru_selector.clone());
let lru_plus_character_selector = LruPlusCharacterRoutingSkillSelector::new(
lru_selector.clone(),
routing_selector.clone(),
);
let lru_plus_lexical_character_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
lru_selector.clone(),
routing_selector.clone(),
);
let task_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
LruSkillSelector::new(
task_snapshot
.recent_skills
.iter()
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
.collect(),
),
routing_selector.clone(),
);
let mut ranked_selections = Vec::with_capacity(self.selectors.len() + 6);
for (method, selector, query) in self
.selectors
.iter()
.map(std::convert::AsRef::as_ref)
.chain([
&routing_selector as &dyn CheapSkillSelector,
&lru_selector as &dyn CheapSkillSelector,
&lru_plus_lexical_selector as &dyn CheapSkillSelector,
&lru_plus_character_selector as &dyn CheapSkillSelector,
&lru_plus_lexical_character_selector as &dyn CheapSkillSelector,
])
.map(|selector| (selector.method(), selector, &query))
.chain([(
"task_context_fusion_v1",
&task_selector as &dyn CheapSkillSelector,
&task_snapshot.query,
)])
{
let query_script = query_script_tag(&query.text);
let start = Instant::now();
let selection =
selector.select(&query.text, &documents, /*limit*/ MAX_SHADOW_RESULTS);
let duration = start.elapsed();
let selected_ids = sanitize_selected_ids(&selection, &eligible_ids);
self.record_metrics(ShadowSelectionObservation {
method,
selection: &selection,
query_truncated_before_selection: query.truncated,
query_script,
catalog_entry_count: documents.len(),
selected_entry_count: selected_ids.len(),
duration,
});
ranked_selections.push(RankedSelection {
method,
skill_resources: selected_ids
.iter()
.map(|id| normalize_skill_resource(catalog.entries[*id].main_prompt.as_str()))
.collect(),
});
tracing::debug!(
method,
catalog_entries = documents.len(),
selected_entries = selected_ids.len(),
query_terms = selection.query_term_count,
query_script,
query_truncated = query.truncated || selection.query_truncated,
candidate_set_truncated = selection.candidate_set_truncated,
"ran shadow skill selection"
);
}
ranked_selections
}
fn record_metrics(&self, observation: ShadowSelectionObservation<'_>) {
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
let ShadowSelectionObservation {
method,
selection,
query_truncated_before_selection,
query_script,
catalog_entry_count,
selected_entry_count,
duration,
} = observation;
let status = selection_status(selection, selected_entry_count);
let query_truncated =
bool_tag(query_truncated_before_selection || selection.query_truncated);
let candidate_set_truncated = bool_tag(selection.candidate_set_truncated);
let tags = [
("method", method),
("status", status),
("query_script", query_script),
("query_truncated", query_truncated),
("candidate_set_truncated", candidate_set_truncated),
];
let _ = metrics_client.counter(RUN_METRIC, /*inc*/ 1, &tags);
let _ = metrics_client.record_duration(DURATION_METRIC, duration, &tags);
let _ = metrics_client.histogram(
CATALOG_ENTRY_COUNT_METRIC,
metric_value(catalog_entry_count),
&tags,
);
let _ = metrics_client.histogram(
SELECTED_ENTRY_COUNT_METRIC,
metric_value(selected_entry_count),
&tags,
);
let _ = metrics_client.histogram(
QUERY_TERM_COUNT_METRIC,
metric_value(selection.query_term_count),
&tags,
);
let _ = metrics_client.histogram(
REDUCTION_BPS_METRIC,
reduction_bps(catalog_entry_count, selected_entry_count),
&tags,
);
}
}
pub(crate) struct ShadowSelectionTurnState {
turn_id: String,
eligible_skill_resources: HashSet<String>,
seen_skill_resources: Mutex<HashSet<String>>,
recent_skill_invocations: Arc<RecentSkillInvocations>,
task_context: Arc<ShadowTaskContext>,
invocations: tokio::sync::mpsc::UnboundedSender<String>,
}
impl ShadowSelectionTurnState {
/// Advance relevance history immediately; scoring can wait for the frozen rankings.
pub(crate) fn record_invocation(&self, skill_resource: &str) {
let skill_resource = normalize_skill_resource(skill_resource);
if !self.eligible_skill_resources.contains(&skill_resource)
|| !self
.seen_skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(skill_resource.clone())
{
return;
}
self.recent_skill_invocations.record(skill_resource.clone());
self.task_context
.record(&self.turn_id, skill_resource.clone());
let _ = self.invocations.send(skill_resource);
}
}
/// Owned turn-start inputs; workers never read the evolving relevance histories.
struct ShadowSelectionInput {
catalog: SkillCatalog,
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
query: ShadowQuery,
eligible_ids: HashSet<usize>,
recent_skill_resources: Vec<String>,
task_snapshot: TaskContextSnapshot,
}
#[derive(Default)]
pub(crate) struct RecentSkillInvocations {
skill_resources: Mutex<VecDeque<String>>,
}
impl RecentSkillInvocations {
fn snapshot(&self) -> Vec<String> {
self.skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.cloned()
.collect()
}
fn record(&self, skill_resource: String) {
let mut skill_resources = self
.skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(index) = skill_resources
.iter()
.position(|resource| resource == &skill_resource)
{
skill_resources.remove(index);
}
skill_resources.push_front(skill_resource);
skill_resources.truncate(MAX_SHADOW_RESULTS);
}
}
struct RankedSelection {
method: &'static str,
skill_resources: Vec<String>,
}
struct ShadowSelectionObservation<'a> {
method: &'static str,
selection: &'a CheapSkillSelection,
query_truncated_before_selection: bool,
query_script: &'static str,
catalog_entry_count: usize,
selected_entry_count: usize,
duration: Duration,
}
fn sanitize_selected_ids(
selection: &CheapSkillSelection,
eligible_ids: &HashSet<usize>,
) -> Vec<usize> {
let mut seen = HashSet::new();
selection
.candidate_ids
.iter()
.copied()
.filter(|id| eligible_ids.contains(id) && seen.insert(*id))
.take(MAX_SHADOW_RESULTS)
.collect()
}
fn selection_status(selection: &CheapSkillSelection, selected_entry_count: usize) -> &'static str {
if selected_entry_count > 0 {
"selected"
} else if selection.query_term_count == 0 {
"no_query_terms"
} else {
"no_matches"
}
}
fn reduction_bps(catalog_entry_count: usize, selected_entry_count: usize) -> i64 {
if catalog_entry_count == 0 {
return 0;
}
10_000i64.saturating_sub(ratio_bps(selected_entry_count, catalog_entry_count))
}
fn ratio_bps(numerator: usize, denominator: usize) -> i64 {
if denominator == 0 {
return 0;
}
let numerator = u128::try_from(numerator).unwrap_or(u128::MAX);
let denominator = u128::try_from(denominator).unwrap_or(u128::MAX);
let basis_points = numerator.saturating_mul(10_000) / denominator;
i64::try_from(basis_points).unwrap_or(i64::MAX)
}
fn metric_value(value: usize) -> i64 {
i64::try_from(value).unwrap_or(i64::MAX)
}
fn bool_tag(value: bool) -> &'static str {
if value { "true" } else { "false" }
}
fn rank_bucket(rank: Option<usize>) -> &'static str {
match rank {
Some(1) => "1",
Some(2..=5) => "2_5",
Some(6..=10) => "6_10",
Some(11..=20) => "11_20",
Some(21..=MAX_SHADOW_RESULTS) => "21_50",
Some(_) | None => "miss",
}
}
fn normalize_skill_resource(skill_resource: &str) -> String {
skill_resource.replace('\\', "/")
}
fn query_script_tag(query: &str) -> &'static str {
let mut has_ascii_latin = false;
let mut has_cjk = false;
let mut has_other = false;
for character in query.chars().filter(|character| character.is_alphabetic()) {
if character.is_ascii_alphabetic() {
has_ascii_latin = true;
} else if is_cjk(character) {
has_cjk = true;
} else {
has_other = true;
}
}
match (has_ascii_latin, has_cjk, has_other) {
(false, false, false) => "none",
(true, false, false) => "ascii_latin",
(false, true, false) => "cjk",
(false, false, true) => "other",
(true, true, false) | (true, false, true) | (false, true, true) | (true, true, true) => {
"mixed"
}
}
}
fn is_cjk(character: char) -> bool {
matches!(
character,
'\u{1100}'..='\u{11ff}'
| '\u{3040}'..='\u{30ff}'
| '\u{3100}'..='\u{312f}'
| '\u{3130}'..='\u{318f}'
| '\u{31a0}'..='\u{31bf}'
| '\u{31f0}'..='\u{31ff}'
| '\u{3400}'..='\u{4dbf}'
| '\u{4e00}'..='\u{9fff}'
| '\u{a960}'..='\u{a97f}'
| '\u{ac00}'..='\u{d7af}'
| '\u{d7b0}'..='\u{d7ff}'
| '\u{f900}'..='\u{faff}'
| '\u{20000}'..='\u{2fa1f}'
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ShadowQuery {
text: String,
truncated: bool,
}
fn build_shadow_query(inputs: &[UserInput]) -> ShadowQuery {
let mut text = String::new();
let mut truncated = false;
for input in inputs {
let part = match input {
UserInput::Text { text, .. } => text.as_str(),
UserInput::Skill { name, .. } | UserInput::Mention { name, .. } => name.as_str(),
_ => continue,
};
if part.is_empty() {
continue;
}
if !text.is_empty() && !push_bounded(&mut text, " ") {
truncated = true;
break;
}
if !push_bounded(&mut text, part) {
truncated = true;
break;
}
}
ShadowQuery { text, truncated }
}
fn push_bounded(destination: &mut String, value: &str) -> bool {
let remaining = MAX_SHADOW_QUERY_BYTES.saturating_sub(destination.len());
if value.len() <= remaining {
destination.push_str(value);
return true;
}
let mut end = remaining;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
destination.push_str(&value[..end]);
false
}
#[cfg(test)]
#[path = "experiment_tests.rs"]
mod tests;

View File

@@ -1,155 +0,0 @@
use std::collections::VecDeque;
use std::sync::Mutex;
use std::sync::PoisonError;
use akode_protocol::user_input::UserInput;
use akode_utils_string::take_bytes_at_char_boundary;
use super::ShadowQuery;
const MAX_PRIOR_REQUESTS: usize = 2;
const MAX_REQUEST_BYTES: usize = 2 * 1024;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_RECENT_SKILLS: usize = 50;
/// Shadow-only relevance history. New and reconstructed thread runtimes start cold.
#[derive(Default)]
pub(crate) struct ShadowTaskContext(Mutex<TaskContextState>);
#[derive(Default)]
struct TaskContextState {
prior_requests: VecDeque<ShadowQuery>,
recent_skills: VecDeque<String>,
pending: Option<PendingTurn>,
}
struct PendingTurn {
id: String,
request: Option<ShadowQuery>,
recent_skills: VecDeque<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct TaskContextSnapshot {
pub(super) query: ShadowQuery,
pub(super) recent_skills: Vec<String>,
}
impl ShadowTaskContext {
pub(super) fn begin_turn(
&self,
turn_id: &str,
current: &ShadowQuery,
inputs: &[UserInput],
) -> TaskContextSnapshot {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if state.pending.as_ref().is_none_or(|turn| turn.id != turn_id) {
if let Some(previous) = state.pending.take() {
if let Some(request) = previous.request {
state
.prior_requests
.retain(|prior| prior.text != request.text);
state.prior_requests.push_front(request);
state.prior_requests.truncate(MAX_PRIOR_REQUESTS);
}
for resource in previous.recent_skills.into_iter().rev() {
remember_skill(&mut state.recent_skills, resource);
}
}
state.pending = Some(PendingTurn {
id: turn_id.to_string(),
request: None,
recent_skills: VecDeque::new(),
});
}
let retained = take_bytes_at_char_boundary(&current.text, MAX_REQUEST_BYTES);
let text = take_bytes_at_char_boundary(&current.text, MAX_QUERY_BYTES);
let mut query = ShadowQuery {
text: text.to_string(),
truncated: current.truncated || text.len() < current.text.len(),
};
for prior in &state.prior_requests {
if prior.text == retained {
continue;
}
if !query.text.is_empty() && query.text.len() < MAX_QUERY_BYTES {
query.text.push('\n');
}
let part = take_bytes_at_char_boundary(
&prior.text,
MAX_QUERY_BYTES.saturating_sub(query.text.len()),
);
query.text.push_str(part);
query.truncated |= prior.truncated || part.len() < prior.text.len();
if part.len() < prior.text.len() {
break;
}
}
let recent_skills = state.recent_skills.iter().cloned().collect();
if is_substantive(&current.text, inputs)
&& let Some(pending) = state.pending.as_mut()
{
pending.request = Some(ShadowQuery {
text: retained.to_string(),
truncated: current.truncated || retained.len() < current.text.len(),
});
}
TaskContextSnapshot {
query,
recent_skills,
}
}
/// Records relevance evidence for future turns, never the active turn's predictions.
pub(super) fn record(&self, turn_id: &str, resource: String) {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(pending) = state.pending.as_mut().filter(|turn| turn.id == turn_id) {
remember_skill(&mut pending.recent_skills, resource);
}
}
}
fn remember_skill(skills: &mut VecDeque<String>, resource: String) {
skills.retain(|previous| previous != &resource);
skills.push_front(resource);
skills.truncate(MAX_RECENT_SKILLS);
}
fn is_substantive(text: &str, inputs: &[UserInput]) -> bool {
if inputs.iter().any(|input| {
matches!(input, UserInput::Skill { name, .. } | UserInput::Mention { name, .. } if !name.trim().is_empty())
}) {
return true;
}
let normalized = text
.split(|character: char| !character.is_alphanumeric())
.filter(|part| !part.is_empty())
.map(str::to_lowercase)
.collect::<Vec<_>>()
.join(" ");
!matches!(
normalized.as_str(),
"" | "yes"
| "yep"
| "yeah"
| "ok"
| "okay"
| "sure"
| "go"
| "go ahead"
| "continue"
| "please continue"
| "proceed"
| "do it"
| "do that"
| "try again"
| "retry"
| "thanks"
| "thank you"
)
}
#[cfg(test)]
#[path = "task_context_tests.rs"]
mod tests;

View File

@@ -1,112 +0,0 @@
use pretty_assertions::assert_eq;
use super::*;
fn query(text: &str) -> ShadowQuery {
ShadowQuery {
text: text.to_string(),
truncated: false,
}
}
fn begin(context: &ShadowTaskContext, turn_id: &str, text: &str) -> TaskContextSnapshot {
context.begin_turn(turn_id, &query(text), &[])
}
#[test]
fn prior_requests_survive_continuations_and_keep_short_substantive_input() {
let context = ShadowTaskContext::default();
begin(&context, "1", "Fix lint errors.");
assert_eq!(
query("continue\nFix lint errors."),
begin(&context, "2", "continue").query
);
begin(&context, "3", "OK!!!");
begin(&context, "4", "deploy");
begin(&context, "5", "修复测试");
assert_eq!(
query("continue\n修复测试\ndeploy"),
begin(&context, "6", "continue").query
);
assert_eq!(
query("deploy\n修复测试"),
begin(&context, "7", "deploy").query
);
assert!(is_substantive(
"go",
&[UserInput::Mention {
name: "go".to_string(),
path: "skill://go".to_string(),
}]
));
}
#[test]
fn current_turn_observations_are_pending_and_late_observations_are_ignored() {
let context = ShadowTaskContext::default();
begin(&context, "1", "continue");
context.record("1", "a".to_string());
assert_eq!(
Vec::<String>::new(),
begin(&context, "1", "continue").recent_skills
);
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
context.record("1", "late".to_string());
context.record("2", "a".to_string());
context.record("2", "b".to_string());
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
assert_eq!(
TaskContextSnapshot {
query: query("continue"),
recent_skills: vec!["b".to_string(), "a".to_string()],
},
begin(&context, "3", "continue")
);
assert_eq!(
TaskContextSnapshot {
query: query("continue"),
recent_skills: Vec::new(),
},
begin(&ShadowTaskContext::default(), "3", "continue")
);
}
#[test]
fn history_and_augmented_query_are_bounded_at_utf8_boundaries() {
let context = ShadowTaskContext::default();
let first = "界".repeat(MAX_REQUEST_BYTES);
let initial = begin(&context, "1", &first);
assert_eq!(
ShadowQuery {
text: take_bytes_at_char_boundary(&first, MAX_QUERY_BYTES).to_string(),
truncated: true,
},
initial.query
);
for index in 0..=MAX_RECENT_SKILLS {
context.record("1", format!("skill-{index}"));
}
begin(&context, "2", &"é".repeat(MAX_REQUEST_BYTES));
context.record("2", "skill-1".to_string());
let expected = format!(
"continue\n{}\n{}",
"é".repeat(MAX_REQUEST_BYTES / 2),
take_bytes_at_char_boundary(&first, MAX_REQUEST_BYTES)
);
assert_eq!(
TaskContextSnapshot {
query: ShadowQuery {
text: take_bytes_at_char_boundary(&expected, MAX_QUERY_BYTES).to_string(),
truncated: true,
},
recent_skills: std::iter::once("skill-1".to_string())
.chain(
(2..=MAX_RECENT_SKILLS)
.rev()
.map(|index| format!("skill-{index}"))
)
.collect(),
},
begin(&context, "3", "continue")
);
}

View File

@@ -24,9 +24,6 @@ use crate::catalog_state::ExecutorCatalogCacheKey;
use crate::catalog_state::SkillCatalogState;
use crate::provider::SkillListQuery;
use crate::provider::SkillReadRequest;
use crate::shadow_selection_experiment::RecentSkillInvocations;
use crate::shadow_selection_experiment::ShadowSelectionTurnState;
use crate::shadow_selection_experiment::ShadowTaskContext;
use crate::sources::SkillProviders;
use crate::step_state::SkillStepCatalog;
@@ -41,10 +38,7 @@ pub struct SkillsThreadState {
catalog_state: Mutex<SkillCatalogState>,
extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
aliases: SkillAliasState,
shadow_selection_turn: Mutex<Option<ShadowSelectionTurn>>,
pub(crate) executor_read_snapshot: Mutex<Option<ExecutorReadSnapshot>>,
pub(crate) recent_skill_invocations: Arc<RecentSkillInvocations>,
pub(crate) shadow_task_context: Arc<ShadowTaskContext>,
}
impl SkillsThreadState {
@@ -57,10 +51,7 @@ impl SkillsThreadState {
catalog_state: Mutex::new(SkillCatalogState::default()),
extension_metrics,
aliases: SkillAliasState::default(),
shadow_selection_turn: Mutex::new(None),
executor_read_snapshot: Mutex::new(None),
recent_skill_invocations: Arc::new(RecentSkillInvocations::default()),
shadow_task_context: Arc::new(ShadowTaskContext::default()),
}
}
@@ -242,33 +233,6 @@ impl SkillsThreadState {
) -> SkillProviderResult<SkillReadResult> {
providers.read(request).await
}
pub(crate) fn replace_shadow_selection_turn(
&self,
turn_id: String,
state: Option<ShadowSelectionTurnState>,
) {
*self
.shadow_selection_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
state.map(|state| ShadowSelectionTurn {
turn_id,
state: Arc::new(state),
});
}
pub(crate) fn shadow_selection_turn(
&self,
turn_id: &str,
) -> Option<Arc<ShadowSelectionTurnState>> {
self.shadow_selection_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.filter(|turn| turn.turn_id == turn_id)
.map(|turn| Arc::clone(&turn.state))
}
}
/// One bounded executor resource, retained for continuations until replacement or thread drop.
@@ -281,11 +245,6 @@ pub(crate) struct ExecutorReadSnapshot {
pub(crate) result: Arc<SkillReadResult>,
}
struct ShadowSelectionTurn {
turn_id: String,
state: Arc<ShadowSelectionTurnState>,
}
#[derive(Default)]
pub(crate) struct EmittedCatalogBudgetWarnings(Mutex<HashSet<String>>);

View File

@@ -32,8 +32,6 @@ use akode_extension_api::NoopTurnItemEmitter;
use akode_extension_api::PreviousWorldStateSection;
use akode_extension_api::RenderedWorldStateFragment;
use akode_extension_api::SelectedPluginSnapshot;
use akode_extension_api::SkillInvocationInput;
use akode_extension_api::SkillInvocationKind;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolCallSource;
@@ -44,7 +42,6 @@ use akode_extension_api::WorldStateContributionInput;
use akode_extension_api::WorldStateSectionContribution;
use akode_models_manager::model_info::model_info_from_slug;
use akode_otel::MetricsClient;
use akode_otel::MetricsConfig;
use akode_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC;
use akode_otel::THREAD_SKILLS_ENABLED_TOTAL_METRIC;
use akode_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC;
@@ -91,15 +88,10 @@ use akode_skills_extension::provider::SkillSearchRequest;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use assert_matches::assert_matches;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[path = "skills_extension/shadow_task_context_tests.rs"]
mod shadow_task_context_tests;
#[path = "skills_extension/catalog_delta_tests.rs"]
mod catalog_delta_tests;
@@ -344,8 +336,7 @@ async fn installed_extension_uses_host_service_snapshot() -> TestResult {
.ok_or("skill path should have a parent")?,
)?;
std::fs::write(&skill_path, DEMO_SKILL_CONTENTS)?;
let mut config = default_config();
config.shadow_selection_enabled = true;
let config = default_config();
let mut builder = ExtensionRegistryBuilder::new();
install(&mut builder, skills_extension_config);
@@ -963,293 +954,6 @@ async fn host_world_state_uses_provider_catalog_with_core_compatible_rendering()
Ok(())
}
#[tokio::test]
async fn shadow_selection_uses_host_catalog_when_instructions_are_disabled() -> TestResult {
let list_calls = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![test_entry(
SkillSourceKind::Host,
"host",
"host/lint-fix",
"lint-fix/SKILL.md",
)],
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: Some(Arc::clone(&list_calls)),
fail_first_list: false,
});
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"akode-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new().with_host_provider(provider),
Some(metrics.clone()),
skills_extension_config,
);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
let mut config = default_config();
config.include_instructions = false;
config.shadow_selection_enabled = true;
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
let turn_store = ExtensionData::new("turn-1");
let step_store = ExtensionData::new("step");
turn_store.insert(HostSkillsSnapshot::new(Arc::new(
SkillLoadOutcome::default(),
)));
let sections = prepared_world_state(
&registry,
&[],
WorldStateContributionInput {
previous_world_state: None,
step_store: &step_store,
model_info: &catalog_model_info(),
thread_id: akode_protocol::ThreadId::new(),
turn_id: "turn-1",
environments: &[],
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
},
)
.await;
let fragments = prepared_turn_input(
&registry,
TurnInputContext {
step_store: &step_store,
turn_id: "turn-1".to_string(),
user_input: vec![UserInput::Text {
text: "Fix lint errors.".to_string(),
text_elements: Vec::new(),
}],
environments: Vec::new(),
},
/*extension_metrics*/ None,
&session_store,
&thread_store,
&turn_store,
)
.await;
assert!(
world_state_section(&sections, "host_skills")
.render_diff(PreviousWorldStateSection::Absent)
.1
.is_none()
);
assert!(fragments.is_empty());
let snapshots = shadow_task_context_tests::collect_shadow_observations(
&metrics,
"codex.skills.shadow_selection.catalog_entries",
/*expected*/ 12,
)
.await?;
let catalog_entry_counts = snapshots
.iter()
.flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics)
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.filter(|metric| metric.name() == "codex.skills.shadow_selection.catalog_entries")
.flat_map(|metric| match metric.data() {
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
.data_points()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::sum),
data => panic!("unexpected shadow catalog metric data: {data:?}"),
})
.collect::<Vec<_>>();
assert!(
catalog_entry_counts.iter().all(|count| *count == 1.0),
"every shadow selector should see the cached host skill: {catalog_entry_counts:?}"
);
assert_eq!(1, list_calls.load(Ordering::Relaxed));
Ok(())
}
#[tokio::test]
async fn shadow_lru_selector_recovers_a_skill_invoked_on_an_earlier_turn() -> TestResult {
let provider = Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![test_entry(
SkillSourceKind::Host,
"host",
"host/lint-fix",
"lint-fix/SKILL.md",
)],
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
});
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"akode-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new().with_host_provider(provider),
Some(metrics.clone()),
skills_extension_config,
);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
let mut config = default_config();
config.include_instructions = false;
config.shadow_selection_enabled = true;
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
for (turn_id, text) in [("turn-1", "Fix lint errors."), ("turn-2", "continue")] {
let turn_store = ExtensionData::new(turn_id);
let fragments = prepared_turn_input(
&registry,
TurnInputContext {
step_store: &ExtensionData::new("step"),
turn_id: turn_id.to_string(),
user_input: vec![UserInput::Text {
text: text.to_string(),
text_elements: Vec::new(),
}],
environments: vec![akode_extension_api::TurnInputEnvironment {
environment_id: "test".to_string(),
cwd: PathUri::from_host_native_path(std::env::current_dir().expect("test cwd"))
.expect("absolute cwd"),
is_primary: true,
fs: &FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
}],
},
/*extension_metrics*/ None,
&session_store,
&thread_store,
&turn_store,
)
.await;
assert!(fragments.is_empty());
registry.skill_invocation_contributors()[0]
.on_skill_invocation(SkillInvocationInput {
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
turn_id,
skill_resource: "lint-fix/SKILL.md",
kind: SkillInvocationKind::Implicit,
})
.await;
}
let snapshots = shadow_task_context_tests::collect_shadow_observations(
&metrics,
"codex.skills.shadow_selection.invocation",
/*expected*/ 24,
)
.await?;
let selector_hits = snapshots
.iter()
.flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics)
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.filter(|metric| metric.name() == "codex.skills.shadow_selection.invocation")
.flat_map(|metric| match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => sum.data_points(),
data => panic!("unexpected shadow invocation metric data: {data:?}"),
})
.filter_map(|point| {
let method = point
.attributes()
.find(|attribute| attribute.key.as_str() == "method")?
.value
.as_str();
if !matches!(
method.as_ref(),
"lru_v1"
| "lru_plus_lexical_v1"
| "lru_plus_character_routing_v1"
| "lru_plus_lexical_character_routing_v1"
) {
return None;
}
let hit = point
.attributes()
.find(|attribute| attribute.key.as_str() == "hit")?
.value
.as_str()
.to_string();
Some((method.to_string(), hit, point.value()))
})
.fold(
std::collections::BTreeMap::new(),
|mut totals, (method, hit, count)| {
*totals.entry((method, hit)).or_insert(0) += count;
totals
},
)
.into_iter()
.map(|((method, hit), count)| (method, hit, count))
.collect::<Vec<_>>();
assert_eq!(
vec![
(
"lru_plus_character_routing_v1".to_string(),
"true".to_string(),
2,
),
(
"lru_plus_lexical_character_routing_v1".to_string(),
"true".to_string(),
2,
),
("lru_plus_lexical_v1".to_string(), "true".to_string(), 2),
("lru_v1".to_string(), "false".to_string(), 1),
("lru_v1".to_string(), "true".to_string(), 1),
],
selector_hits
);
Ok(())
}
#[tokio::test]
async fn selected_executor_catalog_caches_root_selections_per_turn_and_reuses_discovery_snapshots()
-> TestResult {
@@ -3223,7 +2927,6 @@ struct TestConfig {
catalog_deltas_enabled: bool,
omit_descriptions: bool,
bundled_skills_enabled: bool,
shadow_selection_enabled: bool,
}
fn default_config() -> TestConfig {
@@ -3232,7 +2935,6 @@ fn default_config() -> TestConfig {
catalog_deltas_enabled: false,
omit_descriptions: false,
bundled_skills_enabled: true,
shadow_selection_enabled: false,
}
}
@@ -3243,7 +2945,6 @@ fn skills_extension_config(config: &TestConfig) -> SkillsExtensionConfig {
omit_descriptions: config.omit_descriptions,
max_context_tokens: None,
bundled_skills_enabled: config.bundled_skills_enabled,
shadow_selection_enabled: config.shadow_selection_enabled,
}
}

View File

@@ -1,255 +0,0 @@
use std::collections::BTreeMap;
use opentelemetry_sdk::metrics::data::ResourceMetrics;
use pretty_assertions::assert_eq;
use super::*;
// The runtime reader emits deltas. Retain every snapshot while waiting for the
// background evaluations so assertions include observations from earlier polls.
pub(super) async fn collect_shadow_observations(
metrics: &MetricsClient,
name: &str,
expected: u64,
) -> Result<Vec<ResourceMetrics>, Box<dyn std::error::Error>> {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
let mut snapshots = Vec::new();
let mut total = 0;
loop {
let snapshot = metrics.snapshot()?;
total += snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.find(|metric| metric.name() == name)
.map(|metric| match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => sum
.data_points()
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
.sum::<u64>(),
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
.data_points()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::count)
.sum::<u64>(),
data => panic!("unexpected shadow metric data: {data:?}"),
})
.unwrap_or(0);
snapshots.push(snapshot);
if total >= expected {
assert_eq!(
expected, total,
"shadow observations must not be duplicated"
);
return Ok(snapshots);
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await?
}
struct FailedReads(StaticSkillProvider);
impl SkillProvider for FailedReads {
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
self.0.list(query)
}
fn read<'a>(
&'a self,
_request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
Box::pin(async { Err(SkillProviderError::new("read unavailable")) })
}
fn search(&self, request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
self.0.search(request)
}
}
fn text_input(text: &str) -> Vec<UserInput> {
vec![UserInput::Text {
text: text.to_string(),
text_elements: Vec::new(),
}]
}
fn explicit_input() -> Vec<UserInput> {
vec![UserInput::Skill {
name: "x".to_string(),
path: PathBuf::from("x/SKILL.md"),
}]
}
#[tokio::test]
async fn task_context_recovers_prior_requests_and_explicit_intent_without_changing_controls()
-> TestResult {
let mut opaque = test_entry(SkillSourceKind::Host, "host", "host/x", "x/SKILL.md");
opaque.description = "zzzz".to_string();
let provider = Arc::new(FailedReads(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![
test_entry(
SkillSourceKind::Host,
"host",
"host/lint-fix",
"lint-fix/SKILL.md",
),
opaque,
],
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}));
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"akode-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new().with_host_provider(provider),
Some(metrics.clone()),
skills_extension_config,
);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let mut config = default_config();
config.include_instructions = false;
config.shadow_selection_enabled = true;
for (thread_id, turns, resource) in [
(
"prior-request",
vec![
("a1", text_input("Fix lint errors.")),
("a2", text_input("continue")),
],
"lint-fix/SKILL.md",
),
(
"explicit-intent",
vec![("b1", explicit_input()), ("b2", text_input("continue"))],
"x/SKILL.md",
),
(
"same-turn",
vec![("c1", explicit_input()), ("c1", text_input("continue"))],
"x/SKILL.md",
),
(
"cold-thread",
vec![("d1", text_input("continue"))],
"x/SKILL.md",
),
] {
let thread_store = ExtensionData::new(thread_id);
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
let observed_turn = turns.last().ok_or("test needs a turn")?.0;
for (turn_id, user_input) in turns {
let fragments = prepared_turn_input(
&registry,
TurnInputContext {
step_store: &ExtensionData::new("step"),
turn_id: turn_id.to_string(),
user_input,
environments: vec![akode_extension_api::TurnInputEnvironment {
environment_id: "test".to_string(),
cwd: PathUri::from_host_native_path(
std::env::current_dir().expect("test cwd"),
)
.expect("absolute cwd"),
is_primary: true,
fs: &FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
}],
},
/*extension_metrics*/ None,
&session_store,
&thread_store,
&ExtensionData::new(turn_id),
)
.await;
assert!(fragments.is_empty());
}
registry.skill_invocation_contributors()[0]
.on_skill_invocation(SkillInvocationInput {
session_store: &session_store,
thread_store: &thread_store,
turn_store: &ExtensionData::new(observed_turn),
turn_id: observed_turn,
skill_resource: resource,
kind: SkillInvocationKind::Implicit,
})
.await;
}
let controls = [
"lru_v1",
"weighted_lexical_v1",
"lru_plus_lexical_v1",
"lru_plus_character_routing_v1",
"lru_plus_lexical_character_routing_v1",
];
let snapshots = collect_shadow_observations(
&metrics,
"codex.skills.shadow_selection.invocation",
/*expected*/ 48,
)
.await?;
let actual = snapshots
.iter()
.flat_map(ResourceMetrics::scope_metrics)
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.filter(|metric| metric.name() == "codex.skills.shadow_selection.invocation")
.flat_map(|metric| match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => sum.data_points(),
data => panic!("unexpected shadow metric: {data:?}"),
})
.filter_map(|point| {
let attribute = |key| {
point
.attributes()
.find(|value| value.key.as_str() == key)
.map(|value| value.value.as_str().to_string())
};
let method = attribute("method")?;
(controls.contains(&method.as_str()) || method == "task_context_fusion_v1")
.then(|| ((method, attribute("hit").expect("hit tag")), point.value()))
})
.fold(BTreeMap::new(), |mut totals, (key, count)| {
*totals.entry(key).or_insert(0) += count;
totals
});
let mut expected = controls
.into_iter()
.map(|method| ((method.to_string(), "false".to_string()), 4))
.collect::<BTreeMap<_, _>>();
expected.insert(
("task_context_fusion_v1".to_string(), "false".to_string()),
/*value*/ 2,
);
expected.insert(
("task_context_fusion_v1".to_string(), "true".to_string()),
/*value*/ 2,
);
assert_eq!(expected, actual);
Ok(())
}