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

@@ -10,29 +10,21 @@ use akode_extension_api::WorldStateSectionContribution;
use crate::world_state::git_attribution_world_state_section;
/// Local default for commit and pull request attribution. aKode never fetches a
/// remote workspace policy, so attribution stays disabled.
const ATTRIBUTION_ENABLED_BY_DEFAULT: bool = false;
/// Contributes model instructions for agent-created git commits and pull requests.
/// Cancels commit and pull request attribution instructions inherited from Codex histories.
/// aKode never fetches a remote workspace policy, so attribution stays disabled.
#[derive(Clone)]
struct GitAttributionExtension {
enabled: bool,
}
struct GitAttributionExtension;
impl ContextContributor for GitAttributionExtension {
fn contribute_world_state<'a>(
&'a self,
_input: WorldStateContributionInput<'a>,
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
let enabled = self.enabled;
Box::pin(async move { vec![git_attribution_world_state_section(enabled)] })
Box::pin(async move { vec![git_attribution_world_state_section()] })
}
}
/// Installs the git-attribution contributor into the extension registry.
pub fn install<C: Sync>(registry: &mut ExtensionRegistryBuilder<C>) {
registry.prompt_contributor(Arc::new(GitAttributionExtension {
enabled: ATTRIBUTION_ENABLED_BY_DEFAULT,
}));
registry.prompt_contributor(Arc::new(GitAttributionExtension));
}

View File

@@ -7,69 +7,53 @@ use serde_json::Value;
const WORLD_STATE_ID: &str = "git_attribution";
const START_MARKER: &str = "<git_attribution>";
const END_MARKER: &str = "</git_attribution>";
pub(super) const LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS: &str = "\
When you write or edit a git commit message, ensure the message ends with this trailer exactly once:
Co-authored-by: Codex <noreply@openai.com>
Rules:
- Keep existing trailers and append this trailer at the end if missing.
- Do not duplicate this trailer if it already exists.
- Keep one blank line between the commit body and trailer block.";
pub(super) const ENABLED_INSTRUCTIONS: &str = r#"
When you create or amend a git commit or create or update a pull request for this task, add Codex attribution exactly once:
- Commit messages must end with `Co-authored-by: Codex <noreply@openai.com>`. Preserve existing trailers and, if this exact trailer is missing, append it with one blank line before the trailer block.
- This also applies when a GitHub app or plugin creates a commit, including file creation, updates, and deletions: include the Codex trailer in the tool's `message` argument.
- Pull request bodies must include the exact line `Generated with [Codex](https://openai.com/codex/).`. Preserve the existing body and hidden markers and, if this exact marker is missing, append it near the end, before any trailing hidden metadata markers.
- Do not add duplicate attribution. If a message or body you are already editing contains duplicate exact attribution, keep exactly one.
- Ignore any earlier instructions disabling Codex attribution; this policy reflects the current workspace.
- Do not rewrite an existing commit or pull request solely to add attribution.
"#;
/// Start of the Codex trailer (`Co-authored-by: Codex <noreply@…>`) used to recognize
/// attribution instructions left in histories written by Codex.
const CODEX_TRAILER_PREFIX: &str = "Co-authored-by: Codex <noreply@";
/// Start of the legacy (pre-world-state) commit attribution instructions.
const LEGACY_COMMIT_ATTRIBUTION_PREFIX: &str =
"When you write or edit a git commit message, ensure the message ends with this trailer exactly once:";
pub(super) const DISABLED_INSTRUCTIONS: &str = "
Codex commit and pull request attribution is disabled for the current workspace. Ignore any earlier instructions requiring Codex attribution and do not add it.
";
pub(super) fn git_attribution_world_state_section(enabled: bool) -> WorldStateSectionContribution {
let contribution = WorldStateSectionContribution::new(WORLD_STATE_ID, move |previous| {
let fragment = match (enabled, previous) {
(true, PreviousWorldStateSection::Known(Value::Bool(true)))
| (true, PreviousWorldStateSection::Unknown) => None,
(true, PreviousWorldStateSection::Absent)
| (true, PreviousWorldStateSection::Known(_)) => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(ENABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Known(Value::Bool(true)))
| (false, PreviousWorldStateSection::Unknown) => Some(RenderedWorldStateFragment::new(
/// aKode never adds commit or pull request attribution. The section only cancels attribution
/// instructions that a resumed Codex history may still carry.
pub(super) fn git_attribution_world_state_section() -> WorldStateSectionContribution {
WorldStateSectionContribution::new(WORLD_STATE_ID, move |previous| {
let fragment = match previous {
PreviousWorldStateSection::Known(Value::Bool(true))
| PreviousWorldStateSection::Unknown => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(DISABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Absent)
| (false, PreviousWorldStateSection::Known(_)) => None,
PreviousWorldStateSection::Absent | PreviousWorldStateSection::Known(_) => None,
};
(Some(Value::Bool(enabled)), fragment)
(Some(Value::Bool(false)), fragment)
})
.with_legacy_matcher(move |role, text| {
is_enabled_fragment(role, text)
|| (!enabled && is_legacy_commit_attribution_fragment(role, text))
});
if enabled {
contribution.with_retained_fragment_matcher(is_enabled_fragment)
} else {
contribution
}
is_enabled_fragment(role, text) || is_legacy_commit_attribution_fragment(role, text)
})
}
fn is_legacy_commit_attribution_fragment(role: &str, text: &str) -> bool {
role == "developer" && text.trim() == LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS
let text = text.trim();
role == "developer"
&& text.starts_with(LEGACY_COMMIT_ATTRIBUTION_PREFIX)
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Do not duplicate this trailer if it already exists.")
}
fn is_enabled_fragment(role: &str, text: &str) -> bool {
role == "developer"
&& text.trim_start().starts_with(START_MARKER)
&& text.contains("Co-authored-by: Codex <noreply@openai.com>")
&& (text.contains("Generated with [Codex](https://openai.com/codex/).")
|| text.contains("Generated with Codex."))
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Generated with [Codex](")
&& text.trim_end().ends_with(END_MARKER)
|| role == "developer"
&& text.trim_start().starts_with(START_MARKER)
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Generated with Codex.")
&& text.trim_end().ends_with(END_MARKER)
}

View File

@@ -16,8 +16,6 @@ pub(crate) fn build_reviewer_config(parent_config: &Config) -> anyhow::Result<Co
// Approvals wait for TurnComplete; post-turn compaction must not delay it.
config.model_post_turn_compact_threshold_percent = 0;
config.include_skill_instructions = false;
config.memories.use_memories = false;
config.memories.dedicated_tools = false;
// An explicit disabled config prevents model defaults from reactivating it.
config.token_budget_startup_config = None;
config.token_budget = Some(TokenBudgetConfig::default());

View File

@@ -1,9 +0,0 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "memories",
compile_data = glob([
"templates/**",
]),
crate_name = "akode_memories_extension",
)

View File

@@ -1,34 +0,0 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-memories-extension"
version.workspace = true
[lib]
name = "akode_memories_extension"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-core = { workspace = true }
akode-extension-api = { workspace = true }
akode-features = { workspace = true }
akode-otel = { workspace = true }
akode-protocol = { workspace = true }
akode-tools = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-output-truncation = { workspace = true }
akode-utils-template = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros"] }

View File

@@ -1,186 +0,0 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::future::Future;
/// Storage interface behind the memories tools.
///
/// Implementations should return paths relative to the memory store and enforce
/// their own storage-specific access rules. The local implementation uses the
/// filesystem today; a later implementation can satisfy the same contract from a
/// remote backend.
pub trait MemoriesBackend: Clone + Send + Sync + 'static {
fn add_ad_hoc_note(
&self,
request: AddAdHocMemoryNoteRequest,
) -> impl Future<Output = Result<AddAdHocMemoryNoteResponse, MemoriesBackendError>> + Send;
fn list(
&self,
request: ListMemoriesRequest,
) -> impl Future<Output = Result<ListMemoriesResponse, MemoriesBackendError>> + Send;
fn read(
&self,
request: ReadMemoryRequest,
) -> impl Future<Output = Result<ReadMemoryResponse, MemoriesBackendError>> + Send;
fn search(
&self,
request: SearchMemoriesRequest,
) -> impl Future<Output = Result<SearchMemoriesResponse, MemoriesBackendError>> + Send;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddAdHocMemoryNoteRequest {
pub filename: String,
pub note: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AddAdHocMemoryNoteResponse {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListMemoriesRequest {
pub path: Option<String>,
pub cursor: Option<String>,
pub max_results: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ListMemoriesResponse {
pub path: Option<String>,
pub entries: Vec<MemoryEntry>,
pub next_cursor: Option<String>,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadMemoryRequest {
pub path: String,
pub line_offset: usize,
pub max_lines: Option<usize>,
pub max_tokens: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ReadMemoryResponse {
pub path: String,
pub start_line_number: usize,
pub content: String,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchMemoriesRequest {
pub queries: Vec<String>,
pub match_mode: SearchMatchMode,
pub path: Option<String>,
pub cursor: Option<String>,
pub context_lines: usize,
pub case_sensitive: bool,
pub normalized: bool,
pub max_results: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct SearchMemoriesResponse {
pub queries: Vec<String>,
pub match_mode: SearchMatchMode,
pub path: Option<String>,
pub matches: Vec<MemorySearchMatch>,
pub next_cursor: Option<String>,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SearchMatchMode {
Any,
AllOnSameLine,
AllWithinLines {
#[schemars(range(min = 1))]
line_count: usize,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MemoryEntry {
pub path: String,
pub entry_type: MemoryEntryType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MemoryEntryType {
File,
Directory,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MemorySearchMatch {
pub path: String,
pub match_line_number: usize,
pub content_start_line_number: usize,
pub content: String,
pub matched_queries: Vec<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum MemoriesBackendError {
#[error("filename '{filename}' {reason}")]
InvalidFilename { filename: String, reason: String },
#[error("ad-hoc note must not be empty")]
EmptyAdHocNote,
#[error("ad-hoc note '{filename}' already exists")]
AdHocNoteAlreadyExists { filename: String },
#[error("path '{path}' {reason}")]
InvalidPath { path: String, reason: String },
#[error("cursor '{cursor}' {reason}")]
InvalidCursor { cursor: String, reason: String },
#[error("path '{path}' was not found")]
NotFound { path: String },
#[error("line_offset must be a 1-indexed line number")]
InvalidLineOffset,
#[error("max_lines must be a positive integer")]
InvalidMaxLines,
#[error("line_offset exceeds file length")]
LineOffsetExceedsFileLength,
#[error("path '{path}' is not a file")]
NotFile { path: String },
#[error("queries must not be empty or contain empty strings")]
EmptyQuery,
#[error("all_within_lines.line_count must be a positive integer")]
InvalidMatchWindow,
#[error("I/O error while reading memories: {0}")]
Io(#[from] std::io::Error),
}
impl MemoriesBackendError {
pub fn invalid_filename(filename: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidFilename {
filename: filename.into(),
reason: reason.into(),
}
}
pub fn invalid_path(path: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidPath {
path: path.into(),
reason: reason.into(),
}
}
pub fn invalid_cursor(cursor: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidCursor {
cursor: cursor.into(),
reason: reason.into(),
}
}
}

View File

@@ -1,174 +0,0 @@
use std::sync::Arc;
use akode_core::config::Config;
use akode_core::context::ContextualUserFragment;
use akode_core::context::MemoryContextFragment;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ContentItemKind;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::PromptFragment;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolContributor;
use akode_features::Feature;
use akode_otel::MetricsClient;
use akode_protocol::MemoryVersion;
use akode_utils_absolute_path::AbsolutePathBuf;
use crate::local::LocalMemoriesBackend;
use crate::prompts::build_memory_tool_developer_instructions;
use crate::tools;
/// Contributes Codex memory read-path prompt context and memory read tools.
#[derive(Clone, Default)]
pub(crate) struct MemoriesExtension {
metrics_client: Option<MetricsClient>,
}
impl MemoriesExtension {
fn new(metrics_client: Option<MetricsClient>) -> Self {
Self { metrics_client }
}
}
#[derive(Clone, Debug)]
pub(crate) struct MemoriesExtensionConfig {
pub(crate) enabled: bool,
pub(crate) dedicated_tools: bool,
pub(crate) codex_home: AbsolutePathBuf,
pub(crate) version: MemoryVersion,
}
impl MemoriesExtensionConfig {
fn from_config(config: &Config) -> Self {
Self {
enabled: config.features.enabled(Feature::MemoryTool) && config.memories.use_memories,
dedicated_tools: config.memories.dedicated_tools,
codex_home: config.codex_home.clone(),
version: config.memories.version,
}
}
}
impl ContextContributor for MemoriesExtension {
fn contribute_thread_context<'a>(
&'a self,
_session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<PromptFragment>> + Send + 'a>> {
Box::pin(async move {
let Some(config) = thread_store.get::<MemoriesExtensionConfig>() else {
return Vec::new();
};
if !config.enabled {
return Vec::new();
}
let Some(instructions) =
build_memory_tool_developer_instructions(&config.codex_home, config.version).await
else {
return Vec::new();
};
let instructions = match config.version {
MemoryVersion::V1 => vec![instructions],
MemoryVersion::V2 => {
// Keep the complete summary while respecting each fragment's byte cap.
let mut remaining = instructions.as_str();
let mut fragments = Vec::new();
while !remaining.is_empty() {
let end = remaining.floor_char_boundary(remaining.len().min(8_900));
fragments.push(
MemoryContextFragment::ReadInstructions(remaining[..end].to_string())
.render()
.into_text()
.unwrap_or_default(),
);
remaining = &remaining[end..];
}
fragments
}
};
instructions
.into_iter()
.map(|instructions| {
PromptFragment::developer_policy(
instructions,
ContentItemKind(MemoryContextFragment::READ_INSTRUCTIONS_KIND.to_string()),
)
})
.collect()
})
}
}
impl ThreadLifecycleContributor<Config> for MemoriesExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input
.thread_store
.insert(MemoriesExtensionConfig::from_config(input.config));
})
}
}
impl ConfigContributor<Config> for MemoriesExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
let mut config = MemoriesExtensionConfig::from_config(new_config);
if let Some(previous) = thread_store.get::<MemoriesExtensionConfig>() {
// The initial summary and retrieval tools must use the same namespace.
config.version = previous.version;
}
thread_store.insert(config);
}
}
impl ToolContributor for MemoriesExtension {
fn tools(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<
Arc<dyn for<'call> akode_extension_api::ToolExecutor<akode_extension_api::ToolCall<'call>>>,
> {
let Some(config) = thread_store.get::<MemoriesExtensionConfig>() else {
return Vec::new();
};
if !config.enabled || !config.dedicated_tools {
return Vec::new();
}
tools::memory_tools(
LocalMemoriesBackend::from_memory_root(
config
.codex_home
.join(config.version.directory_name())
.to_path_buf(),
),
self.metrics_client.clone(),
)
}
}
/// Installs the memories extension contributors into the extension registry.
pub fn install(
registry: &mut ExtensionRegistryBuilder<Config>,
metrics_client: Option<MetricsClient>,
) {
let extension = Arc::new(MemoriesExtension::new(metrics_client));
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.prompt_contributor(extension.clone());
registry.tool_contributor(extension);
}

View File

@@ -1,25 +0,0 @@
mod backend;
mod extension;
mod local;
mod metrics;
mod prompts;
mod schema;
mod tools;
pub use extension::install;
pub(crate) const DEFAULT_LIST_MAX_RESULTS: usize = 2_000;
pub(crate) const MAX_LIST_RESULTS: usize = 2_000;
pub(crate) const DEFAULT_SEARCH_MAX_RESULTS: usize = 200;
pub(crate) const MAX_SEARCH_RESULTS: usize = 200;
pub(crate) const DEFAULT_READ_MAX_TOKENS: usize = 20_000;
pub(crate) const MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT: usize = 2_500;
pub(crate) const MEMORY_TOOLS_NAMESPACE: &str = "memories";
pub(crate) const ADD_AD_HOC_NOTE_TOOL_NAME: &str = "add_ad_hoc_note";
pub(crate) const LIST_TOOL_NAME: &str = "list";
pub(crate) const READ_TOOL_NAME: &str = "read";
pub(crate) const SEARCH_TOOL_NAME: &str = "search";
#[cfg(test)]
mod tests;

View File

@@ -1,123 +0,0 @@
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::backend::MemoriesBackendError;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
mod ad_hoc_note;
mod list;
mod path;
mod read;
mod search;
#[derive(Debug, Clone)]
pub(crate) struct LocalMemoriesBackend {
root: PathBuf,
}
impl LocalMemoriesBackend {
pub(crate) fn from_memory_root(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
async fn resolve_scoped_path(
&self,
relative_path: Option<&str>,
) -> Result<PathBuf, MemoriesBackendError> {
let Some(relative_path) = relative_path else {
return Ok(self.root.clone());
};
let relative = Path::new(relative_path);
if relative.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(MemoriesBackendError::invalid_path(
relative_path,
"must stay within the memories root",
));
}
if relative.components().any(path::is_hidden_component) {
return Err(MemoriesBackendError::NotFound {
path: relative_path.to_string(),
});
}
let components = relative.components().collect::<Vec<_>>();
let mut scoped_path = self.root.clone();
for (idx, component) in components.iter().enumerate() {
scoped_path.push(component.as_os_str());
let Some(metadata) = Self::metadata_or_none(&scoped_path).await? else {
for remaining_component in components.iter().skip(idx + 1) {
scoped_path.push(remaining_component.as_os_str());
}
return Ok(scoped_path);
};
path::reject_symlink(
&path::display_relative_path(&self.root, &scoped_path),
&metadata,
)?;
if idx + 1 < components.len() && !metadata.is_dir() {
return Err(MemoriesBackendError::invalid_path(
relative_path,
"traverses through a non-directory path component",
));
}
}
Ok(scoped_path)
}
async fn metadata_or_none(
path: &Path,
) -> Result<Option<std::fs::Metadata>, MemoriesBackendError> {
match tokio::fs::symlink_metadata(path).await {
Ok(metadata) => Ok(Some(metadata)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
}
impl MemoriesBackend for LocalMemoriesBackend {
async fn add_ad_hoc_note(
&self,
request: AddAdHocMemoryNoteRequest,
) -> Result<AddAdHocMemoryNoteResponse, MemoriesBackendError> {
ad_hoc_note::add_ad_hoc_note(self, request).await
}
async fn list(
&self,
request: ListMemoriesRequest,
) -> Result<ListMemoriesResponse, MemoriesBackendError> {
list::list(self, request).await
}
async fn read(
&self,
request: ReadMemoryRequest,
) -> Result<ReadMemoryResponse, MemoriesBackendError> {
read::read(self, request).await
}
async fn search(
&self,
request: SearchMemoriesRequest,
) -> Result<SearchMemoriesResponse, MemoriesBackendError> {
search::search(self, request).await
}
}

View File

@@ -1,147 +0,0 @@
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::MemoriesBackendError;
use super::LocalMemoriesBackend;
use super::path::reject_symlink;
const AD_HOC_NOTES_DIR: &[&str] = &["extensions", "ad_hoc", "notes"];
const AD_HOC_NOTE_FILENAME_MAX_BYTES: usize = 128;
const AD_HOC_NOTE_SLUG_MAX_BYTES: usize = 80;
const TIMESTAMP_PREFIX_LEN: usize = "YYYY-MM-DDTHH-MM-SS-".len();
pub(super) async fn add_ad_hoc_note(
backend: &LocalMemoriesBackend,
request: AddAdHocMemoryNoteRequest,
) -> Result<AddAdHocMemoryNoteResponse, MemoriesBackendError> {
validate_filename(&request.filename)?;
if request.note.trim().is_empty() {
return Err(MemoriesBackendError::EmptyAdHocNote);
}
let notes_dir = ensure_notes_dir(backend).await?;
let path = notes_dir.join(&request.filename);
let mut file = match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(MemoriesBackendError::AdHocNoteAlreadyExists {
filename: request.filename,
});
}
Err(err) => return Err(err.into()),
};
file.write_all(request.note.as_bytes())?;
Ok(AddAdHocMemoryNoteResponse {})
}
async fn ensure_notes_dir(
backend: &LocalMemoriesBackend,
) -> Result<std::path::PathBuf, MemoriesBackendError> {
ensure_directory(&backend.root).await?;
let mut path = backend.root.clone();
for component in AD_HOC_NOTES_DIR {
path.push(component);
ensure_directory(&path).await?;
}
Ok(path)
}
async fn ensure_directory(path: &Path) -> Result<(), MemoriesBackendError> {
match LocalMemoriesBackend::metadata_or_none(path).await? {
Some(metadata) => {
reject_symlink(&path.display().to_string(), &metadata)?;
if metadata.is_dir() {
return Ok(());
}
return Err(MemoriesBackendError::invalid_path(
path.display().to_string(),
"must be a directory",
));
}
None => tokio::fs::create_dir(path).await?,
}
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(path).await? else {
return Err(MemoriesBackendError::NotFound {
path: path.display().to_string(),
});
};
reject_symlink(&path.display().to_string(), &metadata)?;
if !metadata.is_dir() {
return Err(MemoriesBackendError::invalid_path(
path.display().to_string(),
"must be a directory",
));
}
Ok(())
}
fn validate_filename(filename: &str) -> Result<(), MemoriesBackendError> {
if filename.len() > AD_HOC_NOTE_FILENAME_MAX_BYTES {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must be at most 128 bytes",
));
}
let Some(stem) = filename.strip_suffix(".md") else {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must end with .md",
));
};
let Some(slug) = stem.get(TIMESTAMP_PREFIX_LEN..) else {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must use YYYY-MM-DDTHH-MM-SS-<slug>.md",
));
};
if !has_valid_timestamp_prefix(stem) {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must use YYYY-MM-DDTHH-MM-SS-<slug>.md",
));
}
if slug.is_empty() || slug.len() > AD_HOC_NOTE_SLUG_MAX_BYTES {
return Err(MemoriesBackendError::invalid_filename(
filename,
"slug must be 1 to 80 bytes",
));
}
if !slug
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
{
return Err(MemoriesBackendError::invalid_filename(
filename,
"slug must contain only lowercase ASCII letters, digits, or hyphens",
));
}
Ok(())
}
fn has_valid_timestamp_prefix(stem: &str) -> bool {
let bytes = stem.as_bytes();
bytes.len() > TIMESTAMP_PREFIX_LEN
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes[10] == b'T'
&& bytes[13] == b'-'
&& bytes[16] == b'-'
&& bytes[19] == b'-'
&& are_digits(&bytes[0..4])
&& are_digits(&bytes[5..7])
&& are_digits(&bytes[8..10])
&& are_digits(&bytes[11..13])
&& are_digits(&bytes[14..16])
&& are_digits(&bytes[17..19])
}
fn are_digits(bytes: &[u8]) -> bool {
bytes.iter().all(u8::is_ascii_digit)
}

View File

@@ -1,77 +0,0 @@
use crate::MAX_LIST_RESULTS;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackendError;
use crate::backend::MemoryEntry;
use crate::backend::MemoryEntryType;
use super::LocalMemoriesBackend;
use super::path::display_relative_path;
use super::path::is_hidden_path;
use super::path::read_sorted_dir_entries;
use super::path::reject_symlink;
pub(super) async fn list(
backend: &LocalMemoriesBackend,
request: ListMemoriesRequest,
) -> Result<ListMemoriesResponse, MemoriesBackendError> {
let max_results = request.max_results.min(MAX_LIST_RESULTS);
let start = backend.resolve_scoped_path(request.path.as_deref()).await?;
let start_index = match request.cursor.as_deref() {
Some(cursor) => cursor.parse::<usize>().map_err(|_| {
MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer")
})?,
None => 0,
};
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else {
return Err(MemoriesBackendError::NotFound {
path: request.path.unwrap_or_default(),
});
};
reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?;
let mut entries = if metadata.is_file() {
vec![MemoryEntry {
path: display_relative_path(&backend.root, &start),
entry_type: MemoryEntryType::File,
}]
} else if metadata.is_dir() {
let mut entries = Vec::new();
for (path, file_type) in read_sorted_dir_entries(&start).await? {
if is_hidden_path(&path) || file_type.is_symlink() {
continue;
}
let entry_type = if file_type.is_dir() {
MemoryEntryType::Directory
} else if file_type.is_file() {
MemoryEntryType::File
} else {
continue;
};
entries.push(MemoryEntry {
path: display_relative_path(&backend.root, &path),
entry_type,
});
}
entries
} else {
Vec::new()
};
if start_index > entries.len() {
return Err(MemoriesBackendError::invalid_cursor(
start_index.to_string(),
"exceeds result count",
));
}
let end_index = start_index.saturating_add(max_results).min(entries.len());
let next_cursor = (end_index < entries.len()).then(|| end_index.to_string());
let truncated = next_cursor.is_some();
Ok(ListMemoriesResponse {
path: request.path,
entries: entries.drain(start_index..end_index).collect(),
next_cursor,
truncated,
})
}

View File

@@ -1,65 +0,0 @@
use std::fs::FileType;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::backend::MemoriesBackendError;
/// Returns lexically sorted paths and their cached, non-symlink-following file types.
///
/// Missing directories and entries that disappear during iteration are ignored.
pub(super) async fn read_sorted_dir_entries(
dir_path: &Path,
) -> Result<Vec<(PathBuf, FileType)>, MemoriesBackendError> {
let mut dir = match tokio::fs::read_dir(dir_path).await {
Ok(dir) => dir,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => return Err(err.into()),
};
let mut entries = Vec::new();
while let Some(entry) = dir.next_entry().await? {
let file_type = match entry.file_type().await {
Ok(file_type) => file_type,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => return Err(err.into()),
};
entries.push((entry.path(), file_type));
}
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
Ok(entries)
}
pub(super) fn reject_symlink(
path: &str,
metadata: &std::fs::Metadata,
) -> Result<(), MemoriesBackendError> {
if metadata.file_type().is_symlink() {
return Err(MemoriesBackendError::invalid_path(
path,
"must not be a symlink",
));
}
Ok(())
}
pub(super) fn is_hidden_component(component: Component<'_>) -> bool {
matches!(
component,
Component::Normal(name) if name.to_string_lossy().starts_with('.')
)
}
pub(super) fn is_hidden_path(path: &Path) -> bool {
path.file_name()
.is_some_and(|name| name.to_string_lossy().starts_with('.'))
}
pub(super) fn display_relative_path(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.components()
.map(|component| component.as_os_str().to_string_lossy())
.filter(|component| !component.is_empty())
.collect::<Vec<_>>()
.join("/")
}

View File

@@ -1,90 +0,0 @@
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_output_truncation::truncate_text;
use crate::DEFAULT_READ_MAX_TOKENS;
use crate::backend::MemoriesBackendError;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use super::LocalMemoriesBackend;
use super::path::reject_symlink;
pub(super) async fn read(
backend: &LocalMemoriesBackend,
request: ReadMemoryRequest,
) -> Result<ReadMemoryResponse, MemoriesBackendError> {
if request.line_offset == 0 {
return Err(MemoriesBackendError::InvalidLineOffset);
}
if request.max_lines == Some(0) {
return Err(MemoriesBackendError::InvalidMaxLines);
}
let path = backend
.resolve_scoped_path(Some(request.path.as_str()))
.await?;
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else {
return Err(MemoriesBackendError::NotFound { path: request.path });
};
reject_symlink(&request.path, &metadata)?;
if !metadata.is_file() {
return Err(MemoriesBackendError::NotFile { path: request.path });
}
let original_content = tokio::fs::read_to_string(&path).await?;
let start_byte = line_start_byte_offset(&original_content, request.line_offset)?;
let end_byte = line_end_byte_offset(&original_content, start_byte, request.max_lines);
let content_from_offset = &original_content[start_byte..end_byte];
let max_tokens = if request.max_tokens == 0 {
DEFAULT_READ_MAX_TOKENS
} else {
request.max_tokens
};
let content = truncate_text(content_from_offset, TruncationPolicy::Tokens(max_tokens));
let truncated = end_byte < original_content.len() || content != content_from_offset;
Ok(ReadMemoryResponse {
path: request.path,
start_line_number: request.line_offset,
content,
truncated,
})
}
fn line_start_byte_offset(
content: &str,
line_offset: usize,
) -> Result<usize, MemoriesBackendError> {
if line_offset == 1 {
return Ok(0);
}
let mut current_line = 1;
for (idx, ch) in content.char_indices() {
if ch == '\n' {
current_line += 1;
if current_line == line_offset {
return Ok(idx + 1);
}
}
}
Err(MemoriesBackendError::LineOffsetExceedsFileLength)
}
fn line_end_byte_offset(content: &str, start_byte: usize, max_lines: Option<usize>) -> usize {
let Some(max_lines) = max_lines else {
return content.len();
};
let mut lines_seen = 1;
for (relative_idx, ch) in content[start_byte..].char_indices() {
if ch == '\n' {
if lines_seen == max_lines {
return start_byte + relative_idx + 1;
}
lines_seen += 1;
}
}
content.len()
}

View File

@@ -1,336 +0,0 @@
use std::borrow::Cow;
use std::path::Path;
use crate::MAX_SEARCH_RESULTS;
use crate::backend::MemoriesBackendError;
use crate::backend::MemorySearchMatch;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
use super::LocalMemoriesBackend;
use super::path::display_relative_path;
use super::path::is_hidden_path;
use super::path::read_sorted_dir_entries;
use super::path::reject_symlink;
pub(super) async fn search(
backend: &LocalMemoriesBackend,
request: SearchMemoriesRequest,
) -> Result<SearchMemoriesResponse, MemoriesBackendError> {
let queries = request
.queries
.iter()
.map(|query| query.trim().to_string())
.collect::<Vec<_>>();
if queries.is_empty() || queries.iter().any(std::string::String::is_empty) {
return Err(MemoriesBackendError::EmptyQuery);
}
if matches!(
request.match_mode,
SearchMatchMode::AllWithinLines { line_count: 0 }
) {
return Err(MemoriesBackendError::InvalidMatchWindow);
}
let max_results = request.max_results.min(MAX_SEARCH_RESULTS);
let start = backend.resolve_scoped_path(request.path.as_deref()).await?;
let start_index = match request.cursor.as_deref() {
Some(cursor) => cursor.parse::<usize>().map_err(|_| {
MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer")
})?,
None => 0,
};
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else {
return Err(MemoriesBackendError::NotFound {
path: request.path.unwrap_or_default(),
});
};
reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?;
let matcher = SearchMatcher::new(
queries.clone(),
request.match_mode.clone(),
request.case_sensitive,
request.normalized,
)?;
let mut matches = Vec::new();
search_entries(
&backend.root,
&start,
&metadata,
&matcher,
request.context_lines,
&mut matches,
)
.await?;
matches.sort_by(|left, right| {
left.path
.cmp(&right.path)
.then(left.match_line_number.cmp(&right.match_line_number))
});
if start_index > matches.len() {
return Err(MemoriesBackendError::invalid_cursor(
start_index.to_string(),
"exceeds result count",
));
}
let end_index = start_index.saturating_add(max_results).min(matches.len());
let next_cursor = (end_index < matches.len()).then(|| end_index.to_string());
let truncated = next_cursor.is_some();
Ok(SearchMemoriesResponse {
queries,
match_mode: request.match_mode,
path: request.path,
matches: matches.drain(start_index..end_index).collect(),
next_cursor,
truncated,
})
}
async fn search_entries(
root: &Path,
current: &Path,
current_metadata: &std::fs::Metadata,
matcher: &SearchMatcher,
context_lines: usize,
matches: &mut Vec<MemorySearchMatch>,
) -> Result<(), MemoriesBackendError> {
if current_metadata.is_file() {
search_file(root, current, matcher, context_lines, matches).await?;
return Ok(());
}
if !current_metadata.is_dir() {
return Ok(());
}
let mut pending = vec![current.to_path_buf()];
while let Some(dir_path) = pending.pop() {
for (path, _) in read_sorted_dir_entries(&dir_path).await? {
if is_hidden_path(&path) {
continue;
}
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else {
continue;
};
if metadata.file_type().is_symlink() {
continue;
}
if metadata.is_dir() {
pending.push(path);
} else if metadata.is_file() {
search_file(root, &path, matcher, context_lines, matches).await?;
}
}
}
Ok(())
}
async fn search_file(
root: &Path,
path: &Path,
matcher: &SearchMatcher,
context_lines: usize,
matches: &mut Vec<MemorySearchMatch>,
) -> Result<(), MemoriesBackendError> {
let content = match tokio::fs::read_to_string(path).await {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::InvalidData => return Ok(()),
Err(err) => return Err(err.into()),
};
let lines = content.lines().collect::<Vec<_>>();
let line_matches = lines
.iter()
.map(|line| matcher.matched_query_flags(line))
.collect::<Vec<_>>();
match &matcher.match_mode {
SearchMatchMode::Any => {
for (idx, matched_query_flags) in line_matches.iter().enumerate() {
if matched_query_flags.iter().any(|matched| *matched) {
matches.push(build_search_match(
root,
path,
&lines,
idx,
idx,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
SearchMatchMode::AllOnSameLine => {
for (idx, matched_query_flags) in line_matches.iter().enumerate() {
if matched_query_flags.iter().all(|matched| *matched) {
matches.push(build_search_match(
root,
path,
&lines,
idx,
idx,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
SearchMatchMode::AllWithinLines { line_count } => {
let mut windows = Vec::new();
for start_index in 0..lines.len() {
if !line_matches[start_index].iter().any(|matched| *matched) {
continue;
}
let last_allowed_index = start_index
.saturating_add(line_count.saturating_sub(1))
.min(lines.len().saturating_sub(1));
let mut matched_query_flags = vec![false; matcher.queries.len()];
for (end_index, line_match_flags) in line_matches
.iter()
.enumerate()
.take(last_allowed_index + 1)
.skip(start_index)
{
for (idx, matched) in line_match_flags.iter().enumerate() {
matched_query_flags[idx] |= matched;
}
if matched_query_flags.iter().all(|matched| *matched) {
windows.push((start_index, end_index, matched_query_flags));
break;
}
}
}
for (idx, (start_index, end_index, matched_query_flags)) in windows.iter().enumerate() {
let strictly_contains_another_window = windows.iter().enumerate().any(
|(other_idx, (other_start_index, other_end_index, _))| {
idx != other_idx
&& start_index <= other_start_index
&& end_index >= other_end_index
&& (start_index != other_start_index || end_index != other_end_index)
},
);
if strictly_contains_another_window {
continue;
}
matches.push(build_search_match(
root,
path,
&lines,
*start_index,
*end_index,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
Ok(())
}
fn build_search_match(
root: &Path,
path: &Path,
lines: &[&str],
match_start_index: usize,
match_end_index: usize,
context_lines: usize,
matched_queries: Vec<String>,
) -> MemorySearchMatch {
let content_start_index = match_start_index.saturating_sub(context_lines);
let content_end_index = match_end_index
.saturating_add(context_lines)
.saturating_add(1)
.min(lines.len());
MemorySearchMatch {
path: display_relative_path(root, path),
match_line_number: match_start_index + 1,
content_start_line_number: content_start_index + 1,
content: lines[content_start_index..content_end_index].join("\n"),
matched_queries,
}
}
struct SearchMatcher {
queries: Vec<String>,
prepared_queries: Vec<String>,
comparison: SearchComparison,
match_mode: SearchMatchMode,
}
impl SearchMatcher {
fn new(
queries: Vec<String>,
match_mode: SearchMatchMode,
case_sensitive: bool,
normalized: bool,
) -> Result<Self, MemoriesBackendError> {
let comparison = SearchComparison::new(case_sensitive, normalized);
let prepared_queries = queries
.iter()
.map(|query| comparison.prepare(query))
.map(Cow::into_owned)
.collect::<Vec<_>>();
if prepared_queries.iter().any(std::string::String::is_empty) {
return Err(MemoriesBackendError::EmptyQuery);
}
Ok(Self {
queries,
prepared_queries,
comparison,
match_mode,
})
}
fn matched_query_flags(&self, line: &str) -> Vec<bool> {
let line = self.comparison.prepare(line);
self.prepared_queries
.iter()
.map(|query| line.as_ref().contains(query))
.collect()
}
fn matched_queries(&self, matched_query_flags: &[bool]) -> Vec<String> {
self.queries
.iter()
.zip(matched_query_flags)
.filter_map(|(query, matched)| matched.then_some(query.clone()))
.collect()
}
}
#[derive(Clone, Copy)]
struct SearchComparison {
case_sensitive: bool,
normalized: bool,
}
impl SearchComparison {
fn new(case_sensitive: bool, normalized: bool) -> Self {
Self {
case_sensitive,
normalized,
}
}
fn prepare<'a>(self, value: &'a str) -> Cow<'a, str> {
if self.case_sensitive && !self.normalized {
return Cow::Borrowed(value);
}
let value = if self.case_sensitive {
Cow::Borrowed(value)
} else {
Cow::Owned(value.to_lowercase())
};
if !self.normalized {
return value;
}
Cow::Owned(
value
.chars()
.filter(|ch| ch.is_alphanumeric())
.collect::<String>(),
)
}
}

View File

@@ -1,69 +0,0 @@
use akode_otel::MetricsClient;
use crate::MEMORY_TOOLS_NAMESPACE;
pub(crate) const MEMORIES_TOOL_CALL_METRIC: &str = "codex.memories.tool.call";
pub(crate) fn record_tool_call(
metrics_client: Option<&MetricsClient>,
operation: &str,
scope: &str,
success: bool,
truncated: &str,
) {
let Some(metrics_client) = metrics_client else {
return;
};
let tool = format!("{MEMORY_TOOLS_NAMESPACE}/{operation}");
let _ = metrics_client.counter(
MEMORIES_TOOL_CALL_METRIC,
/*inc*/ 1,
&[
("tool", tool.as_str()),
("operation", operation),
("scope", scope),
("status", status_tag(success)),
("truncated", truncated),
],
);
}
pub(crate) fn scope_from_path(path: &str) -> &'static str {
let path = path.trim_matches('/');
let path = path.strip_prefix("./").unwrap_or(path);
if path.is_empty() {
"root"
} else if path == "MEMORY.md" {
"memory_md"
} else if path == "memory_summary.md" {
"memory_summary"
} else if path == "raw_memories.md" {
"raw_memories"
} else if path == "rollout_summaries" || path.starts_with("rollout_summaries/") {
"rollout_summaries"
} else if path == "skills" || path.starts_with("skills/") {
"skills"
} else if path == "extensions/ad_hoc/notes" || path.starts_with("extensions/ad_hoc/notes/") {
"ad_hoc_notes"
} else {
"other"
}
}
pub(crate) fn scope_from_optional_path(path: Option<&str>, default: &'static str) -> &'static str {
path.map_or(default, scope_from_path)
}
pub(crate) fn truncated_tag(truncated: Option<bool>) -> &'static str {
match truncated {
Some(true) => "true",
Some(false) => "false",
None => "unknown",
}
}
fn status_tag(success: bool) -> &'static str {
if success { "succeeded" } else { "failed" }
}

View File

@@ -1,68 +0,0 @@
use crate::MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT;
use akode_protocol::MemoryVersion;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_output_truncation::truncate_text;
use akode_utils_template::Template;
use std::sync::LazyLock;
use tokio::fs;
static MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
parse_embedded_template(
include_str!("../templates/memories/read_path.md"),
"memories/read_path.md",
)
});
static MEMORY_V2_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
parse_embedded_template(
include_str!("../templates/memories/read_path_v2.md"),
"memories/read_path_v2.md",
)
});
fn parse_embedded_template(source: &'static str, template_name: &str) -> Template {
match Template::parse(source) {
Ok(template) => template,
Err(err) => panic!("embedded template {template_name} is invalid: {err}"),
}
}
/// Build the memory read-path prompt that is added to developer instructions.
///
/// Large `memory_summary.md` files are truncated at
/// [MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT].
pub(crate) async fn build_memory_tool_developer_instructions(
codex_home: &AbsolutePathBuf,
version: MemoryVersion,
) -> Option<String> {
let base_path = codex_home.join(version.directory_name());
let memory_summary_path = base_path.join("memory_summary.md");
let memory_summary = fs::read_to_string(&memory_summary_path)
.await
.ok()?
.trim()
.to_string();
let memory_summary = truncate_text(
&memory_summary,
TruncationPolicy::Tokens(MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT),
);
if memory_summary.is_empty() {
return None;
}
let base_path = base_path.display().to_string();
let template = match version {
MemoryVersion::V1 => &MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_TEMPLATE,
MemoryVersion::V2 => &MEMORY_V2_TEMPLATE,
};
template
.render([
("base_path", base_path.as_str()),
("memory_summary", memory_summary.as_str()),
])
.ok()
}
#[cfg(test)]
#[path = "prompts_tests.rs"]
mod tests;

View File

@@ -1,66 +0,0 @@
use super::*;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tokio::fs as tokio_fs;
#[tokio::test]
async fn build_memory_tool_developer_instructions_renders_embedded_template() {
let temp = tempdir().unwrap();
let codex_home = AbsolutePathBuf::from_absolute_path(temp.path()).unwrap();
let memories_dir = codex_home.join("memories");
tokio_fs::create_dir_all(&memories_dir).await.unwrap();
tokio_fs::write(
memories_dir.join("memory_summary.md"),
"Short memory summary for tests.",
)
.await
.unwrap();
let instructions = build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V1)
.await
.unwrap();
assert!(instructions.contains(&format!(
"- {}/memory_summary.md (already provided below; do NOT open again)",
memories_dir.display()
)));
assert!(instructions.contains("Short memory summary for tests."));
assert_eq!(
instructions
.matches("========= MEMORY_SUMMARY BEGINS =========")
.count(),
1
);
}
#[tokio::test]
async fn v2_reads_only_its_own_summary_without_falling_back_to_v1()
-> Result<(), Box<dyn std::error::Error>> {
let home = tempdir()?;
let codex_home = AbsolutePathBuf::from_absolute_path(home.path())?;
let v1 = codex_home.join("memories");
let v2 = codex_home.join("memories_v2");
tokio_fs::create_dir_all(&v1).await?;
tokio_fs::write(v1.join("memory_summary.md"), "v1\nlegacy content").await?;
assert_eq!(
build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V2).await,
None
);
tokio_fs::create_dir_all(&v2).await?;
tokio_fs::write(v2.join("memory_summary.md"), "v1\nnew pipeline content").await?;
let instructions = build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V2)
.await
.expect("v2 instructions");
assert!(instructions.contains("new pipeline content"));
assert!(!instructions.contains("legacy content"));
assert!(instructions.contains("do not retrieve history speculatively"));
assert!(instructions.contains(&format!("{}/rollout_summaries/", v2.display())));
assert!(
build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V1)
.await
.expect("v1 instructions")
.contains("legacy content")
);
Ok(())
}

View File

@@ -1,42 +0,0 @@
use schemars::JsonSchema;
use schemars::r#gen::SchemaSettings;
use serde_json::Map;
use serde_json::Value;
pub(crate) fn input_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ false)
}
pub(crate) fn output_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ true)
}
fn schema_for<T: JsonSchema>(option_add_null_type: bool) -> Value {
let schema = SchemaSettings::draft2019_09()
.with(|settings| {
settings.inline_subschemas = true;
settings.option_add_null_type = option_add_null_type;
})
.into_generator()
.into_root_schema_for::<T>();
let schema_value = serde_json::to_value(schema)
.unwrap_or_else(|err| panic!("generated tool schema should serialize: {err}"));
let Value::Object(mut schema_object) = schema_value else {
unreachable!("root tool schema must be an object");
};
let mut tool_schema = Map::new();
for key in [
"properties",
"required",
"type",
"additionalProperties",
"$defs",
"definitions",
] {
if let Some(value) = schema_object.remove(key) {
tool_schema.insert(key.to_string(), value);
}
}
Value::Object(tool_schema)
}

View File

@@ -1,617 +0,0 @@
use std::path::Path;
use std::sync::Arc;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::NoopTurnItemEmitter;
use akode_extension_api::PromptSlot;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolCallSource;
use akode_extension_api::ToolContributor;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolPayload;
use akode_protocol::models::ContentItem;
use akode_tools::ToolOutput;
use akode_utils_absolute_path::test_support::PathBufExt;
use akode_utils_absolute_path::test_support::PathExt;
use akode_utils_absolute_path::test_support::test_path_buf;
use akode_utils_output_truncation::TruncationPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::backend::MemoryEntry;
use crate::backend::MemoryEntryType;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::extension::MemoriesExtension;
use crate::extension::MemoriesExtensionConfig;
use crate::local::LocalMemoriesBackend;
#[test]
fn memory_tool_namespace_matches_responses_api_identifier() {
assert!(!crate::MEMORY_TOOLS_NAMESPACE.is_empty());
assert!(
crate::MEMORY_TOOLS_NAMESPACE
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
);
}
#[test]
fn tools_are_not_contributed_without_thread_config() {
let extension = MemoriesExtension::default();
assert!(
extension
.tools(
&ExtensionData::new("session"),
&ExtensionData::new("thread"),
)
.is_empty()
);
}
#[test]
fn tools_are_not_contributed_when_disabled() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: false,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
assert!(
extension
.tools(&ExtensionData::new("session"), &thread_store)
.is_empty()
);
}
#[test]
fn tools_are_not_contributed_when_dedicated_tools_disabled() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: false,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
assert!(
extension
.tools(&ExtensionData::new("session"), &thread_store)
.is_empty()
);
}
#[test]
fn tools_are_contributed_when_enabled_with_dedicated_tools() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
let tool_names = extension
.tools(&ExtensionData::new("session"), &thread_store)
.into_iter()
.map(|tool| tool.tool_name())
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![
memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
memory_tool_name(crate::LIST_TOOL_NAME),
memory_tool_name(crate::READ_TOOL_NAME),
memory_tool_name(crate::SEARCH_TOOL_NAME),
]
);
}
#[test]
fn install_registers_dedicated_tool_contributor() {
let mut builder = ExtensionRegistryBuilder::<akode_core::config::Config>::new();
crate::install(&mut builder, /*metrics_client*/ None);
let registry = builder.build();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
let tool_names = registry
.tool_contributors()
.iter()
.flat_map(|contributor| contributor.tools(&ExtensionData::new("session"), &thread_store))
.map(|tool| tool.tool_name())
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![
memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
memory_tool_name(crate::LIST_TOOL_NAME),
memory_tool_name(crate::READ_TOOL_NAME),
memory_tool_name(crate::SEARCH_TOOL_NAME),
]
);
}
#[test]
fn ad_hoc_tool_definition_includes_filename_contract() {
let tool = memory_tool(
Path::new("/tmp/codex-home/memories"),
crate::ADD_AD_HOC_NOTE_TOOL_NAME,
);
let spec = serde_json::to_value(tool.spec()).expect("serialize tool spec");
let filename = spec
.pointer("/tools/0/parameters/properties/filename")
.expect("filename parameter should be in tool schema");
assert_eq!(filename.pointer("/type"), Some(&json!("string")));
assert!(
filename
.pointer("/description")
.and_then(serde_json::Value::as_str)
.is_some_and(|description| description.contains("YYYY-MM-DDTHH-MM-SS-<slug>.md"))
);
}
#[tokio::test]
async fn prompt_contribution_uses_memory_summary_when_enabled() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memories_dir = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memories_dir)
.await
.expect("create memories dir");
tokio::fs::write(
memories_dir.join("memory_summary.md"),
"Remember repository-specific implementation preferences.",
)
.await
.expect("write memory summary");
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: false,
codex_home: tempdir.path().abs(),
});
let fragments = extension
.contribute_thread_context(&ExtensionData::new("session"), &thread_store)
.await;
assert_eq!(fragments.len(), 1);
assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy);
assert!(matches!(
fragments[0].content(),
ContentItem::InputText { text }
if text.contains("Remember repository-specific implementation preferences.")
));
}
#[tokio::test]
async fn add_ad_hoc_note_tool_creates_note_file() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let tool = memory_tool(&memory_root, crate::ADD_AD_HOC_NOTE_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"filename": "2026-05-26T13-42-08-remember-review-style.md",
"note": "Remember to keep PR review comments concise.",
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("ad-hoc note should be written");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({}))
);
assert_eq!(
tokio::fs::read_to_string(
memory_root
.join("extensions/ad_hoc/notes")
.join("2026-05-26T13-42-08-remember-review-style.md")
)
.await
.expect("read ad-hoc note"),
"Remember to keep PR review comments concise."
);
}
#[tokio::test]
async fn add_ad_hoc_note_tool_rejects_paths_as_filenames() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let tool = memory_tool(&memory_root, crate::ADD_AD_HOC_NOTE_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"filename": "../2026-05-26T13-42-08-remember-review-style.md",
"note": "Remember to keep PR review comments concise.",
})
.to_string(),
};
let result = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload,
})
.await;
let err = match result {
Ok(_) => panic!("path-like filename should be rejected"),
Err(err) => err,
};
assert!(err.to_string().contains("filename"));
assert!(err.to_string().contains("YYYY-MM-DDTHH-MM-SS"));
}
#[tokio::test]
async fn read_tool_reads_memory_file() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(
memory_root.join("MEMORY.md"),
"first line\nsecond needle line\nthird line\n",
)
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::READ_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"path": "MEMORY.md",
"line_offset": 2,
"max_lines": 1
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::READ_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("read should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"path": "MEMORY.md",
"content": "second needle line\n",
"start_line_number": 2,
"truncated": true
}))
);
}
#[tokio::test]
async fn local_listing_and_search_ignore_symlinks() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let outside_root = tempdir.path().join("outside");
std::fs::create_dir_all(memory_root.join("nested")).expect("create memories directory");
std::fs::create_dir_all(&outside_root).expect("create outside directory");
for (path, content) in [
(memory_root.join("a.md"), "visible needle"),
(memory_root.join("nested/z.md"), "nested needle"),
(outside_root.join("secret.md"), "outside needle"),
] {
std::fs::write(path, content).expect("write memory fixture");
}
#[cfg(unix)]
std::os::unix::fs::symlink(&outside_root, memory_root.join("linked-directory"))
.expect("create memory fixture symlink");
let backend = LocalMemoriesBackend::from_memory_root(&memory_root);
let listing = backend
.list(ListMemoriesRequest {
path: None,
cursor: None,
max_results: 10,
})
.await
.expect("list visible memories");
assert_eq!(
listing,
ListMemoriesResponse {
path: None,
entries: vec![
MemoryEntry {
path: "a.md".to_string(),
entry_type: MemoryEntryType::File,
},
MemoryEntry {
path: "nested".to_string(),
entry_type: MemoryEntryType::Directory,
},
],
next_cursor: None,
truncated: false,
}
);
let response = backend
.search(SearchMemoriesRequest {
queries: vec!["needle".to_string()],
match_mode: SearchMatchMode::Any,
path: None,
cursor: None,
context_lines: 0,
case_sensitive: false,
normalized: false,
max_results: 10,
})
.await
.expect("search visible memories");
let paths = response
.matches
.iter()
.map(|matched| matched.path.as_str())
.collect::<Vec<_>>();
assert_eq!(paths, vec!["a.md", "nested/z.md"]);
}
#[tokio::test]
async fn search_tool_accepts_multiple_queries() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(
memory_root.join("MEMORY.md"),
"alpha only\nneedle only\nalpha needle\n",
)
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"queries": ["alpha", "needle"],
"case_sensitive": false
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("search should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "any"
},
"path": null,
"matches": [
{
"path": "MEMORY.md",
"match_line_number": 1,
"content_start_line_number": 1,
"content": "alpha only",
"matched_queries": ["alpha"]
},
{
"path": "MEMORY.md",
"match_line_number": 2,
"content_start_line_number": 2,
"content": "needle only",
"matched_queries": ["needle"]
},
{
"path": "MEMORY.md",
"match_line_number": 3,
"content_start_line_number": 3,
"content": "alpha needle",
"matched_queries": ["alpha", "needle"]
}
],
"next_cursor": null,
"truncated": false
}))
);
}
#[tokio::test]
async fn search_tool_accepts_windowed_all_match_mode() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(memory_root.join("MEMORY.md"), "alpha\nmiddle\nneedle\n")
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "all_within_lines",
"line_count": 3
}
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("search should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "all_within_lines",
"line_count": 3
},
"path": null,
"matches": [
{
"path": "MEMORY.md",
"match_line_number": 1,
"content_start_line_number": 1,
"content": "alpha\nmiddle\nneedle",
"matched_queries": ["alpha", "needle"]
}
],
"next_cursor": null,
"truncated": false
}))
);
}
#[tokio::test]
async fn search_tool_rejects_legacy_single_query() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"query": "needle",
})
.to_string(),
};
let result = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload,
})
.await;
let err = match result {
Ok(_) => panic!("legacy query field should be rejected"),
Err(err) => err,
};
assert!(err.to_string().contains("unknown field"));
assert!(err.to_string().contains("query"));
}
fn memory_tool(
memory_root: &Path,
tool_name: &str,
) -> Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>> {
let expected_tool_name = memory_tool_name(tool_name);
crate::tools::memory_tools(
LocalMemoriesBackend::from_memory_root(memory_root),
/*metrics_client*/ None,
)
.into_iter()
.find(|tool| tool.tool_name() == expected_tool_name)
.unwrap_or_else(|| panic!("{tool_name} tool should be registered"))
}
fn memory_tool_name(tool_name: &str) -> ToolName {
ToolName::namespaced(crate::MEMORY_TOOLS_NAMESPACE, tool_name)
}

View File

@@ -1,94 +0,0 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::ADD_AD_HOC_NOTE_TOOL_NAME;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::MemoriesBackend;
use crate::metrics::record_tool_call;
use super::backend_error_to_function_call;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct AddAdHocNoteArgs {
/// Name of the note file to create, in
/// YYYY-MM-DDTHH-MM-SS-<slug>.md format. The slug must use only lowercase
/// ASCII letters, digits, and hyphens.
#[schemars(
length(min = 24, max = 128),
regex(pattern = r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]{0,79}\.md$")
)]
filename: String,
/// Verbatim Markdown note to append to the ad-hoc memory notes.
#[schemars(length(min = 1))]
note: String,
}
#[derive(Clone)]
pub(super) struct AddAdHocNoteTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for AddAdHocNoteTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(ADD_AD_HOC_NOTE_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<AddAdHocNoteArgs, AddAdHocMemoryNoteResponse>(
ADD_AD_HOC_NOTE_TOOL_NAME,
"Create one append-only ad-hoc memory note after the user explicitly asks Codex to remember, forget, or update something.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> AddAdHocNoteTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: AddAdHocNoteArgs = parse_args(&call)?;
let response = backend
.add_ad_hoc_note(AddAdHocMemoryNoteRequest {
filename: args.filename,
note: args.note,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
ADD_AD_HOC_NOTE_TOOL_NAME,
"ad_hoc_notes",
response.is_ok(),
"not_applicable",
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -1,102 +0,0 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_LIST_MAX_RESULTS;
use crate::LIST_TOOL_NAME;
use crate::MAX_LIST_RESULTS;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_optional_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::clamp_max_results;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ListArgs {
path: Option<String>,
cursor: Option<String>,
#[schemars(range(min = 1))]
max_results: Option<usize>,
}
#[derive(Clone)]
pub(super) struct ListTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for ListTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(LIST_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<ListArgs, ListMemoriesResponse>(
LIST_TOOL_NAME,
"List immediate files and directories under a path in the Codex memories store.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> ListTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ListArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "root");
let response = backend
.list(ListMemoriesRequest {
path: args.path,
cursor: args.cursor,
max_results: clamp_max_results(
args.max_results,
DEFAULT_LIST_MAX_RESULTS,
MAX_LIST_RESULTS,
),
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
LIST_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -1,113 +0,0 @@
use std::sync::Arc;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_extension_api::parse_tool_input_schema;
use akode_otel::MetricsClient;
use akode_tools::ResponsesApiNamespace;
use akode_tools::ResponsesApiNamespaceTool;
use akode_tools::default_namespace_description;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
use crate::MEMORY_TOOLS_NAMESPACE;
use crate::backend::MemoriesBackend;
use crate::backend::MemoriesBackendError;
use crate::schema;
mod ad_hoc_note;
mod list;
mod read;
mod search;
pub(crate) fn memory_tools<B>(
backend: B,
metrics_client: Option<MetricsClient>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>
where
B: MemoriesBackend,
{
vec![
Arc::new(ad_hoc_note::AddAdHocNoteTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(list::ListTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(read::ReadTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(search::SearchTool {
backend,
metrics_client,
}),
]
}
pub(super) fn memory_tool_name(name: &str) -> ToolName {
ToolName::namespaced(MEMORY_TOOLS_NAMESPACE, name)
}
pub(super) fn memory_function_tool<I: JsonSchema, O: JsonSchema>(
name: &str,
description: &str,
) -> ToolSpec {
let tool = ResponsesApiTool {
name: name.to_string(),
description: description.to_string(),
strict: false,
defer_loading: None,
parameters: parse_tool_input_schema(&schema::input_schema_for::<I>())
.unwrap_or_else(|err| panic!("generated input schema for {name} should parse: {err}")),
output_schema: Some(schema::output_schema_for::<O>().into()),
};
ToolSpec::Namespace(ResponsesApiNamespace {
name: MEMORY_TOOLS_NAMESPACE.to_string(),
description: default_namespace_description(MEMORY_TOOLS_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
})
}
fn parse_args<T: for<'de> Deserialize<'de>>(call: &ToolCall<'_>) -> Result<T, FunctionCallError> {
let arguments = call.function_arguments()?;
let value = if arguments.trim().is_empty() {
Value::Object(serde_json::Map::new())
} else {
serde_json::from_str(arguments)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?
};
serde_json::from_value(value).map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
}
fn clamp_max_results(requested: Option<usize>, default: usize, max: usize) -> usize {
requested.unwrap_or(default).clamp(1, max)
}
fn backend_error_to_function_call(err: MemoriesBackendError) -> FunctionCallError {
match err {
MemoriesBackendError::InvalidPath { .. }
| MemoriesBackendError::InvalidCursor { .. }
| MemoriesBackendError::InvalidFilename { .. }
| MemoriesBackendError::NotFound { .. }
| MemoriesBackendError::InvalidLineOffset
| MemoriesBackendError::InvalidMaxLines
| MemoriesBackendError::LineOffsetExceedsFileLength
| MemoriesBackendError::NotFile { .. }
| MemoriesBackendError::EmptyQuery
| MemoriesBackendError::EmptyAdHocNote
| MemoriesBackendError::AdHocNoteAlreadyExists { .. }
| MemoriesBackendError::InvalidMatchWindow => {
FunctionCallError::RespondToModel(err.to_string())
}
MemoriesBackendError::Io(_) => FunctionCallError::Fatal(err.to_string()),
}
}

View File

@@ -1,99 +0,0 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_READ_MAX_TOKENS;
use crate::READ_TOOL_NAME;
use crate::backend::MemoriesBackend;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ReadArgs {
path: String,
#[schemars(range(min = 1))]
line_offset: Option<usize>,
#[schemars(range(min = 1))]
max_lines: Option<usize>,
}
#[derive(Clone)]
pub(super) struct ReadTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for ReadTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(READ_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<ReadArgs, ReadMemoryResponse>(
READ_TOOL_NAME,
"Read a Codex memory file by relative path, optionally starting at a 1-indexed line offset and limiting the number of lines returned.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> ReadTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ReadArgs = parse_args(&call)?;
let path = args.path;
let scope = scope_from_path(path.as_str());
let response = backend
.read(ReadMemoryRequest {
path: path.clone(),
line_offset: args.line_offset.unwrap_or(1),
max_lines: args.max_lines,
max_tokens: DEFAULT_READ_MAX_TOKENS,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
READ_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -1,119 +0,0 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_SEARCH_MAX_RESULTS;
use crate::MAX_SEARCH_RESULTS;
use crate::SEARCH_TOOL_NAME;
use crate::backend::MemoriesBackend;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_optional_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::clamp_max_results;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct SearchArgs {
#[schemars(length(min = 1))]
queries: Vec<String>,
match_mode: Option<SearchMatchMode>,
path: Option<String>,
cursor: Option<String>,
#[schemars(range(min = 0))]
context_lines: Option<usize>,
case_sensitive: Option<bool>,
normalized: Option<bool>,
#[schemars(range(min = 1))]
max_results: Option<usize>,
}
#[derive(Clone)]
pub(super) struct SearchTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for SearchTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(SEARCH_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<SearchArgs, SearchMemoriesResponse>(
SEARCH_TOOL_NAME,
"Search Codex memory files for substring matches, optionally normalizing separators or requiring all query substrings on the same line or within a line window.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> SearchTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: SearchArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "all");
let response = backend.search(args.into_request()).await;
record_tool_call(
self.metrics_client.as_ref(),
SEARCH_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}
impl SearchArgs {
fn into_request(self) -> SearchMemoriesRequest {
SearchMemoriesRequest {
queries: self.queries,
match_mode: self.match_mode.unwrap_or(SearchMatchMode::Any),
path: self.path,
cursor: self.cursor,
context_lines: self.context_lines.unwrap_or(0),
case_sensitive: self.case_sensitive.unwrap_or(true),
normalized: self.normalized.unwrap_or(false),
max_results: clamp_max_results(
self.max_results,
DEFAULT_SEARCH_MAX_RESULTS,
MAX_SEARCH_RESULTS,
),
}
}
}

View File

@@ -1,130 +0,0 @@
## Memory
You have access to a memory folder with guidance from prior runs. It can save
time and help you stay consistent. Use it whenever it is likely to help.
Decision boundary: should you use memory for a new user query?
- Skip memory ONLY when the request is clearly self-contained and does not need
workspace history, conventions, or prior decisions.
- Hard skip examples: current time/date, simple translation, simple sentence
rewrite, one-line shell command, trivial formatting.
- Use memory by default when ANY of these are true:
- the query mentions workspace/repo/module/path/files in MEMORY_SUMMARY below,
- the user asks for prior context / consistency / previous decisions,
- the task is ambiguous and could depend on earlier project choices,
- the ask is a non-trivial and related to MEMORY_SUMMARY below.
- If unsure, do a quick memory pass.
Memory layout (general -> specific):
- {{ base_path }}/memory_summary.md (already provided below; do NOT open again)
- {{ base_path }}/MEMORY.md (searchable registry; primary file to query)
- {{ base_path }}/skills/<skill-name>/ (skill folder)
- SKILL.md (entrypoint instructions)
- scripts/ (optional helper scripts)
- examples/ (optional example outputs)
- templates/ (optional templates)
- {{ base_path }}/rollout_summaries/ (per-rollout recaps + evidence snippets)
- The paths of these entries can be found in {{ base_path }}/MEMORY.md or {{ base_path }}/rollout_summaries/ as `rollout_path`
- These files are append-only `jsonl`: `session_meta.payload.id` identifies the session, `turn_context` marks turn boundaries, `event_msg` is the lightweight status stream, and `response_item` contains actual messages, tool calls, and tool outputs.
- For efficient lookup, prefer matching the filename suffix or `session_meta.payload.id`; avoid broad full-content scans unless needed.
Quick memory pass (when applicable):
1. Skim the MEMORY_SUMMARY below and extract task-relevant keywords.
2. Search {{ base_path }}/MEMORY.md using those keywords.
3. Only if MEMORY.md directly points to rollout summaries/skills, open the 1-2
most relevant files under {{ base_path }}/rollout_summaries/ or
{{ base_path }}/skills/.
4. If above are not clear and you need exact commands, error text, or precise evidence, search over `rollout_path` for more evidence.
5. If there are no relevant hits, stop memory lookup and continue normally.
Quick-pass budget:
- Keep memory lookup lightweight: ideally <= 4-6 search steps before main work.
- Avoid broad scans of all rollout summaries.
During execution: if you hit repeated errors, confusing behavior, or suspect
relevant prior context, redo the quick memory pass.
How to decide whether to verify memory:
- Consider both risk of drift and verification effort.
- If a fact is likely to drift and is cheap to verify, verify it before
answering.
- If a fact is likely to drift but verification is expensive, slow, or
disruptive, it is acceptable to answer from memory in an interactive turn,
but you should say that it is memory-derived, note that it may be stale, and
consider offering to refresh it live.
- If a fact is lower-drift and expensive to verify, it is usually fine to
answer from memory directly.
When answering from memory without current verification:
- If you rely on memory for a fact that you did not verify in the current turn,
say so briefly in the final answer.
- If that fact is plausibly drift-prone or comes from an older note, older
snapshot, or prior run summary, say that it may be stale or outdated.
- If live verification was skipped and a refresh would be useful in the
interactive context, consider offering to verify or refresh it live.
- Do not present unverified memory-derived facts as confirmed-current.
- Prefer a short refresh offer for interactive questions, especially about prior
results, commands, timing, or older snapshots.
Memory citation requirements:
- If ANY relevant memory files were used: append exactly one
`<oai-mem-citation>` block as the VERY LAST content of the final reply.
Normal responses should include the answer first, then append the
`<oai-mem-citation>` block at the end.
- Use this exact structure for programmatic parsing:
```
<oai-mem-citation>
<citation_entries>
MEMORY.md:234-236|note=[responsesapi citation extraction code pointer]
rollout_summaries/2026-02-17T21-23-02-LN3m-example.md:10-12|note=[weekly report format]
</citation_entries>
<rollout_ids>
019c6e27-e55b-73d1-87d8-4e01f1f75043
019c7714-3b77-74d1-9866-e1f484aae2ab
</rollout_ids>
</oai-mem-citation>
```
- `citation_entries` is for rendering:
- one citation entry per line
- format: `<file>:<line_start>-<line_end>|note=[<how memory was used>]`
- use file paths relative to the memory base path (for example, `MEMORY.md`,
`rollout_summaries/...`, `skills/...`)
- only cite files actually used under the memory base path (do not cite
workspace files as memory citations)
- if you used `MEMORY.md` and then a rollout summary/skill file, cite both
- list entries in order of importance (most important first)
- `note` should be short, single-line, and use simple characters only (avoid
unusual symbols, no newlines)
- `rollout_ids` is for us to track what previous rollouts you find useful:
- include one rollout id per line
- rollout ids should look like UUIDs (for example,
`019c6e27-e55b-73d1-87d8-4e01f1f75043`)
- include unique ids only; do not repeat ids
- an empty `<rollout_ids>` section is allowed if no rollout ids are available
- you can find rollout ids in rollout summary files and MEMORY.md
- do not include file paths or notes in this section
- For every `citation_entries`, try to find and cite the corresponding rollout id if possible
- Never include memory citations inside pull-request messages.
- Never cite blank lines; double-check ranges.
Updating memories:
You can update the memories **only** when explicitly asked by the user. This must always come from a direct request from the user.
- Write your update in {{ base_path }}/extensions/ad_hoc/notes/
- Each update must be one small file containing what you want to add/delete/update from the memories.
- The name of this file must be `<timestamp>-<short slug>.md`
- Do not try to edit the memory files yourself, only add one update note in {{ base_path }}/extensions/ad_hoc/notes/
========= MEMORY_SUMMARY BEGINS =========
{{ memory_summary }}
========= MEMORY_SUMMARY ENDS =========
When memory is likely relevant, start with the quick memory pass above before
deep repo exploration.

View File

@@ -1,44 +0,0 @@
## Memory
Use the injected MEMORY_SUMMARY as historical context: apply the user's actual
preferences, corrections, decisions, and supported task scope. Its exact
rollout, source, pull-request, discussion, and document pointers can guide
independently useful work without an extra lookup merely to rediscover them.
Read a matching rollout under `{{ base_path }}/rollout_summaries/` when its
additional evidence, wording, chronology, or uncertainty could change your
answer; otherwise do not retrieve history speculatively. Search selectively
when a genuinely needed route is missing.
Memory is not proof of current behavior. For consequential or changeable
claims, use judgment about drift, verification cost, and harm; inspect the
actual owning source when warranted and acknowledge material uncertainty.
Batch independent useful lookups. Follow current instructions, cite only
memory actually used, never in pull requests, and update memory only when the
user explicitly asks. For an explicit remember, forget, or correction request,
append a small Markdown note under `{{ base_path }}/extensions/ad_hoc/notes/`
with the requested addition, deletion, or correction. Do not edit generated
memory files directly; consolidation applies these notes.
Memory citations:
When a read rollout summary informs the answer, append one citation block at
the end of the final reply, outside code fences. Do not cite `memory_summary.md`.
<oai-mem-citation>
<citation_entries>
rollout_summaries/example.md:8-10|note=[used prior context]
</citation_entries>
<rollout_ids>
019c6e27-e55b-73d1-87d8-4e01f1f75043
</rollout_ids>
</oai-mem-citation>
Use actual source paths relative to `{{ base_path }}` and line ranges from the
search or read, with one entry per line and short single-line notes. Include
unique relevant rollout UUIDs already available; leave `rollout_ids` empty if
none are available. Do not reread files or make extra tool calls solely to
construct or check citations or obtain rollout IDs.
========= MEMORY_SUMMARY BEGINS =========
{{ memory_summary }}
========= MEMORY_SUMMARY ENDS =========

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(())
}

View File

@@ -8,7 +8,7 @@ Tool for accessing the internet.
Examples of different commands available in this tool:
* `search_query`: {"search_query": [{"q": "What is the capital of France?"}, {"q": "What is the capital of belgium?"}]}. Searches the internet for a given query (and optionally with a domain or recency filter)
* `image_query`: {"image_query":[{"q": "waterfalls"}]}.
* `open`: {"open": [{"ref_id": "turn0search0"}, {"ref_id": "https://www.openai.com", "lineno": 120}]}
* `open`: {"open": [{"ref_id": "turn0search0"}, {"ref_id": "https://www.example.com", "lineno": 120}]}
* `click`: {"click": [{"ref_id": "turn0fetch3", "id": 17}]}
* `find`: {"find": [{"ref_id": "turn0fetch3", "pattern": "Annie Case"}]}
* `screenshot`: {"screenshot": [{"ref_id": "turn1view0", "pageno": 0}, {"ref_id": "turn1view0", "pageno": 3}]}