Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1242
akode-rs/ext/skills/tests/executor_file_system_authority.rs
Normal file
1242
akode-rs/ext/skills/tests/executor_file_system_authority.rs
Normal file
File diff suppressed because it is too large
Load Diff
3388
akode-rs/ext/skills/tests/skills_extension.rs
Normal file
3388
akode-rs/ext/skills/tests/skills_extension.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,345 @@
|
||||
//! Multi-source budgeting and feature rollback through the skills extension.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn skill_sources_spend_the_same_remaining_budget() -> TestResult {
|
||||
let mut previous = serde_json::Map::new();
|
||||
let enabled = TestConfig {
|
||||
catalog_deltas_enabled: true,
|
||||
..default_config()
|
||||
};
|
||||
render_catalogs(&[], &enabled, &mut previous).await?;
|
||||
|
||||
// One release-notes row fits the 100-token budget. The larger entry sorts first.
|
||||
let large = "Detailed architectural guidance. ".repeat(40);
|
||||
let small = "Draft release notes. ".repeat(9);
|
||||
let entries = [
|
||||
("architecture-review", large.as_str()),
|
||||
("release-notes", small.as_str()),
|
||||
];
|
||||
let emitted = render_catalogs(&entries, &enabled, &mut previous).await?;
|
||||
assert_eq!(
|
||||
emitted
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("- ") && line.contains("release-notes"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(emitted.contains("- executor-release-notes:"), "{emitted}");
|
||||
assert!(!emitted.contains("architecture-review"), "{emitted}");
|
||||
let used = previous
|
||||
.values()
|
||||
.filter_map(|s| s["usage"]["tokens"].as_u64())
|
||||
.sum::<u64>();
|
||||
assert!((50..=100).contains(&used), "{used}");
|
||||
|
||||
let edited = [
|
||||
("architecture-review", "Review architecture."),
|
||||
("release-notes", small.as_str()),
|
||||
];
|
||||
assert_eq!(render_catalogs(&edited, &enabled, &mut previous).await?, "");
|
||||
let disabled = default_config();
|
||||
let empty = render_catalogs(&[], &disabled, &mut previous).await?;
|
||||
assert!(empty.contains("skills are currently available"), "{empty}");
|
||||
assert_eq!(render_catalogs(&[], &disabled, &mut previous).await?, "");
|
||||
let omitted = TestConfig {
|
||||
omit_descriptions: true,
|
||||
..enabled
|
||||
};
|
||||
previous.clear();
|
||||
let emitted =
|
||||
render_catalogs(&[("notes", "Hidden description.")], &enabled, &mut previous).await?;
|
||||
assert!(emitted.contains("description shown above"), "{emitted}");
|
||||
assert!(
|
||||
emitted.contains("- host-notes: Hidden description."),
|
||||
"{emitted}"
|
||||
);
|
||||
// Resume a snapshot written before the description policy was persisted.
|
||||
for snapshot in previous.values_mut() {
|
||||
snapshot.as_object_mut().unwrap().remove("omitDescriptions");
|
||||
}
|
||||
let emitted =
|
||||
render_catalogs(&[("notes", "Hidden description.")], &omitted, &mut previous).await?;
|
||||
assert!(
|
||||
emitted.contains("OR the task clearly matches a skill's name shown above, you must use that skill for that turn."),
|
||||
"{emitted}"
|
||||
);
|
||||
assert!(emitted.contains("- executor-notes: "), "{emitted}");
|
||||
assert!(!emitted.contains("Hidden description."), "{emitted}");
|
||||
assert_eq!(
|
||||
render_catalogs(&[("notes", "Edited description.")], &omitted, &mut previous).await?,
|
||||
""
|
||||
);
|
||||
// A policy change still refreshes instructions when no more rows fit the budget.
|
||||
let emitted =
|
||||
render_catalogs(&[("notes", "Edited description.")], &enabled, &mut previous).await?;
|
||||
assert!(emitted.contains("description shown above"), "{emitted}");
|
||||
assert!(!emitted.contains("- executor-notes:"), "{emitted}");
|
||||
assert!(!emitted.contains("- host-notes:"), "{emitted}");
|
||||
assert_eq!(
|
||||
render_catalogs(&[("notes", "Edited description.")], &enabled, &mut previous).await?,
|
||||
""
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grant_expiry_withdraws_only_missing_skills_when_metadata_budget_is_exhausted() -> TestResult
|
||||
{
|
||||
let enabled = TestConfig {
|
||||
catalog_deltas_enabled: true,
|
||||
..default_config()
|
||||
};
|
||||
let survivor = [("permanent", "Always available.")];
|
||||
let original = [("unrelated", "Removed independently.")];
|
||||
for grant_when_removed in [None, Some("granting-turn")] {
|
||||
let mut previous = serde_json::Map::new();
|
||||
let baseline = render_catalogs_for_step(
|
||||
&original,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
/*granting_turn*/ None,
|
||||
/*context_window*/ 60_000,
|
||||
)
|
||||
.await?;
|
||||
assert!(baseline.contains("- executor-unrelated:"), "{baseline}");
|
||||
let both = [
|
||||
original[0],
|
||||
survivor[0],
|
||||
("temporary", "Turn only."),
|
||||
("env-b/independent", "Available without the grant on env-1."),
|
||||
];
|
||||
let granted = render_catalogs_for_step(
|
||||
&both,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
Some("granting-turn"),
|
||||
/*context_window*/ 60_000,
|
||||
)
|
||||
.await?;
|
||||
assert!(granted.contains("- executor-permanent:"), "{granted}");
|
||||
assert!(granted.contains("- executor-independent:"), "{granted}");
|
||||
assert!(granted.contains("- executor-temporary:"), "{granted}");
|
||||
let expired = render_catalogs_for_step(
|
||||
&survivor,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
grant_when_removed,
|
||||
/*context_window*/ 1,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
expired,
|
||||
format!("\n## Selected-environment skills update\n{REVALIDATION}")
|
||||
);
|
||||
assert_eq!(
|
||||
render_catalogs_for_step(
|
||||
&survivor,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
/*granting_turn*/ None,
|
||||
/*context_window*/ 1
|
||||
)
|
||||
.await?,
|
||||
""
|
||||
);
|
||||
let restored = [survivor[0], ("temporary", "Turn only.")];
|
||||
for expected in [RESTORATION, ""] {
|
||||
assert_eq!(
|
||||
render_catalogs_for_step(
|
||||
&restored,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
Some("reapproved"),
|
||||
/*context_window*/ 1,
|
||||
)
|
||||
.await?,
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
render_catalogs_for_step(
|
||||
&survivor,
|
||||
&enabled,
|
||||
&mut previous,
|
||||
/*granting_turn*/ None,
|
||||
/*context_window*/ 1,
|
||||
)
|
||||
.await?,
|
||||
format!("\n## Selected-environment skills update\n{REVALIDATION}")
|
||||
);
|
||||
assert_eq!(
|
||||
render_catalogs_for_step(
|
||||
&[],
|
||||
&enabled,
|
||||
&mut previous,
|
||||
/*granting_turn*/ None,
|
||||
/*context_window*/ 1
|
||||
)
|
||||
.await?,
|
||||
""
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const RESTORATION: &str = "\n## Selected-environment skills update\nSome previously unavailable skills are available again. Verify current access before relying on a skill from this source.\n";
|
||||
const REVALIDATION: &str = "Some previously listed skills are no longer available. Verify current access before relying on a skill from this source.\n";
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_filesystem_catalog_revalidates_missing_rows_once() -> TestResult {
|
||||
let config = TestConfig {
|
||||
catalog_deltas_enabled: true,
|
||||
..default_config()
|
||||
};
|
||||
let mut previous = serde_json::Map::new();
|
||||
let survivor = [("stay", "Keep this skill.")];
|
||||
let both = [survivor[0], ("gone", "Temporarily available.")];
|
||||
render_catalogs_for_step(
|
||||
&both,
|
||||
&config,
|
||||
&mut previous,
|
||||
/*granting_turn*/ None,
|
||||
/*context_window*/ 60_000,
|
||||
)
|
||||
.await?;
|
||||
for snapshot in previous.values_mut() {
|
||||
snapshot.as_object_mut().unwrap().remove("tracksGrants");
|
||||
}
|
||||
assert_eq!(
|
||||
render_catalogs(&survivor, &config, &mut previous).await?,
|
||||
format!(
|
||||
"\n## Selected-environment skills update\n{REVALIDATION}\n## Host skills update\n{REVALIDATION}"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
render_catalogs(&survivor, &config, &mut previous).await?,
|
||||
""
|
||||
);
|
||||
assert_eq!(render_catalogs(&[], &config, &mut previous).await?, "");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn render_catalogs(
|
||||
skills: &[(&str, &str)],
|
||||
config: &TestConfig,
|
||||
previous: &mut serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
render_catalogs_for_step(
|
||||
skills, config, previous, /*granting_turn*/ None, /*context_window*/ 5_000,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn render_catalogs_for_step(
|
||||
skills: &[(&str, &str)],
|
||||
config: &TestConfig,
|
||||
previous: &mut serde_json::Map<String, serde_json::Value>,
|
||||
granting_turn: Option<&str>,
|
||||
context_window: i64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let turn_id = granting_turn.unwrap_or("turn");
|
||||
let step_store = ExtensionData::new("step");
|
||||
if granting_turn.is_some() {
|
||||
step_store.insert(akode_skills_extension::TurnSkillFilesystemGrants {
|
||||
environment_ids: ["env-1".to_string()].into(),
|
||||
});
|
||||
}
|
||||
let provider = |kind: SkillSourceKind| -> Result<_, akode_utils_path_uri::PathUriParseError> {
|
||||
let mut entries = Vec::new();
|
||||
for &(name, description) in skills {
|
||||
let (environment, name) = name.split_once('/').unwrap_or(("env-1", name));
|
||||
let name = format!("{kind}-{name}");
|
||||
let path = format!("/skills/{name}/SKILL.md");
|
||||
let mut entry = test_entry(kind.clone(), "skills", &format!("{kind}/{name}"), &path);
|
||||
if kind == SkillSourceKind::Executor {
|
||||
entry.main_prompt = SkillResourceId::environment(
|
||||
&path,
|
||||
environment,
|
||||
PathUri::parse(&format!("file://{path}"))?,
|
||||
);
|
||||
}
|
||||
entry.description = description.to_string();
|
||||
entries.push(entry.with_display_path(path));
|
||||
}
|
||||
Ok(Arc::new(StaticSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
entries,
|
||||
..Default::default()
|
||||
},
|
||||
read_requests: Arc::new(Mutex::new(Vec::new())),
|
||||
list_calls: None,
|
||||
fail_first_list: false,
|
||||
}))
|
||||
};
|
||||
let providers = SkillProviders::new()
|
||||
.with_executor_provider(provider(SkillSourceKind::Executor)?)
|
||||
.with_host_provider(provider(SkillSourceKind::Host)?);
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(&mut builder, providers, skills_extension_config);
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
registry.thread_lifecycle_contributors()[0]
|
||||
.on_thread_start(ThreadStartInput {
|
||||
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;
|
||||
start_registered_turn(®istry, &session_store, &thread_store, turn_id).await;
|
||||
let roots = [SelectedCapabilityRoot {
|
||||
id: "skills".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "env-1".to_string(),
|
||||
path: PathUri::parse("file:///skills")?,
|
||||
},
|
||||
}];
|
||||
let turn_store = ExtensionData::new(turn_id);
|
||||
turn_store.insert(HostSkillsSnapshot::new(Arc::new(
|
||||
SkillLoadOutcome::default(),
|
||||
)));
|
||||
let sections = prepared_world_state(
|
||||
®istry,
|
||||
&roots,
|
||||
WorldStateContributionInput {
|
||||
previous_world_state: Some(previous),
|
||||
step_store: &step_store,
|
||||
model_info: &ModelInfo {
|
||||
context_window: Some(context_window),
|
||||
include_skills_usage_instructions: true,
|
||||
..catalog_model_info()
|
||||
},
|
||||
thread_id: akode_protocol::ThreadId::new(),
|
||||
turn_id,
|
||||
environments: &[],
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
turn_store: &turn_store,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let mut emitted = String::new();
|
||||
for section in sections {
|
||||
let prior = previous.get(section.id()).map_or(
|
||||
PreviousWorldStateSection::Absent,
|
||||
PreviousWorldStateSection::Known,
|
||||
);
|
||||
let (snapshot, fragment) = section.render_diff(prior);
|
||||
if let Some(snapshot) = snapshot {
|
||||
previous.insert(section.id().to_string(), snapshot);
|
||||
}
|
||||
if let Some(fragment) = fragment {
|
||||
emitted.push_str(&fragment.body().clone().expect_text());
|
||||
}
|
||||
}
|
||||
Ok(emitted)
|
||||
}
|
||||
334
akode-rs/ext/skills/tests/skills_extension/discovery_v2_tests.rs
Normal file
334
akode-rs/ext/skills/tests/skills_extension/discovery_v2_tests.rs
Normal file
@@ -0,0 +1,334 @@
|
||||
//! Verifies metadata-only V2 skill projection and refresh without legacy discovery.
|
||||
|
||||
use super::*;
|
||||
use akode_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use akode_exec_server::DiscoveredPluginFiles;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_exec_server::ExecutorPlugin;
|
||||
use akode_exec_server::ExecutorSkill;
|
||||
use akode_skills::SkillDependencies;
|
||||
use akode_skills::SkillPolicy;
|
||||
use akode_skills::SkillToolDependency;
|
||||
use akode_skills_extension::ExecutorSkillProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn installation(
|
||||
environment_id: &str,
|
||||
) -> Result<ExecutorCapabilityDiscoveryV2Snapshot, Box<dyn std::error::Error>> {
|
||||
Ok(ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: environment_id.to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "local-name@marketplace".to_string(),
|
||||
display_name: "Local plugin".to_string(),
|
||||
version: "1".to_string(),
|
||||
root: PathUri::parse("file:///plugins/local-name/1")?,
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: akode_exec_server::CapabilityTextFile {
|
||||
path: PathUri::parse(
|
||||
"file:///plugins/local-name/1/.codex-plugin/plugin.json",
|
||||
)?,
|
||||
contents: r#"{"name":"local-name"}"#.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
},
|
||||
skills: vec![ExecutorSkill {
|
||||
name: "local-name:work".to_string(),
|
||||
description: "Environment description".to_string(),
|
||||
short_description: None,
|
||||
path: PathUri::parse(
|
||||
"file:///plugins/local-name/1/skills/other-directory/SKILL.md",
|
||||
)?,
|
||||
discovery_root: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestResult {
|
||||
let provider = Arc::new(ExecutorSkillProvider::new_with_restriction_product(
|
||||
/*restriction_product*/ None,
|
||||
));
|
||||
let dependencies = Some(SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "mcp".into(),
|
||||
value: "deploy".into(),
|
||||
description: None,
|
||||
transport: Some("stdio".into()),
|
||||
command: Some("deploy-mcp".into()),
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
}],
|
||||
});
|
||||
let skill_path = PathUri::parse("file:///executor/skills/dashboard/SKILL.md")?;
|
||||
let mut snapshots = vec![installation("remote-a")?, installation("remote-b")?];
|
||||
for snapshot in &mut snapshots {
|
||||
Arc::make_mut(snapshot.result.as_mut().unwrap())
|
||||
.skills
|
||||
.push(ExecutorSkill {
|
||||
name: "dashboard".to_string(),
|
||||
description: "Build a dashboard".to_string(),
|
||||
short_description: None,
|
||||
path: skill_path.clone(),
|
||||
discovery_root: Some(SkillDiscoveryRoot {
|
||||
id: "codex-home-skills".to_string(),
|
||||
path: PathUri::parse("file:///executor/skills")?,
|
||||
}),
|
||||
dependencies: dependencies.clone(),
|
||||
policy: Some(SkillPolicy {
|
||||
allow_implicit_invocation: Some(false),
|
||||
products: vec![],
|
||||
}),
|
||||
});
|
||||
}
|
||||
let query = SkillListQuery {
|
||||
turn_id: "turn-1".to_string(),
|
||||
executor_roots: Vec::new(),
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: false,
|
||||
mcp_resources: None,
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: Some(snapshots.clone()),
|
||||
};
|
||||
// Standalone skills without discovery-root metadata use the skills namespace.
|
||||
let mut fallback_query = query.clone();
|
||||
for snapshot in fallback_query
|
||||
.executor_capability_discovery_v2
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
{
|
||||
Arc::make_mut(snapshot.result.as_mut().unwrap()).skills[0].discovery_root = None;
|
||||
}
|
||||
let fallback = provider.list(fallback_query).await?;
|
||||
assert_eq!(fallback.entries.len(), 4);
|
||||
assert_eq!(
|
||||
fallback.entries[1].id.0,
|
||||
"skill://skills/executor/skills/dashboard"
|
||||
);
|
||||
assert_eq!(
|
||||
fallback.entries[1].main_prompt.environment_id(),
|
||||
Some("remote-a")
|
||||
);
|
||||
let catalog = provider.list(query).await?;
|
||||
assert_eq!(catalog.entries.len(), 4);
|
||||
let merged = catalog;
|
||||
for entries in [
|
||||
(&merged.entries[0], &merged.entries[2]),
|
||||
(&merged.entries[1], &merged.entries[3]),
|
||||
] {
|
||||
let (first, second) = entries;
|
||||
assert_eq!(first.main_prompt.environment_id(), Some("remote-a"));
|
||||
assert_eq!(second.main_prompt.environment_id(), Some("remote-b"));
|
||||
assert_eq!(first.authority, second.authority);
|
||||
assert_eq!(first.id, second.id);
|
||||
assert_ne!(first.main_prompt, second.main_prompt);
|
||||
assert!(first.sources.is_empty());
|
||||
assert!(second.sources.is_empty());
|
||||
}
|
||||
|
||||
let mut rebound = merged.entries[0].clone();
|
||||
rebound.main_prompt = merged.entries[2].main_prompt.clone();
|
||||
let mut deduplicated = SkillCatalog::default();
|
||||
deduplicated.push_entry(merged.entries[0].clone());
|
||||
deduplicated.push_entry(rebound);
|
||||
deduplicated.push_entry(merged.entries[2].clone());
|
||||
assert_eq!(
|
||||
deduplicated.entries,
|
||||
vec![merged.entries[0].clone(), merged.entries[2].clone()]
|
||||
);
|
||||
|
||||
let plugin = merged
|
||||
.entries
|
||||
.iter()
|
||||
.find(|entry| entry.plugin_id.is_some())
|
||||
.unwrap();
|
||||
assert_eq!(plugin.authority.id, "local-name@marketplace");
|
||||
assert_eq!(
|
||||
plugin.id.0,
|
||||
"skill://local-name@marketplace/plugins/local-name/1/skills/other-directory"
|
||||
);
|
||||
|
||||
let entry = merged
|
||||
.entries
|
||||
.iter()
|
||||
.find(|entry| entry.plugin_id.is_none())
|
||||
.unwrap();
|
||||
assert_eq!(entry.dependencies, dependencies);
|
||||
assert!(entry.enabled);
|
||||
assert!(!entry.prompt_visible);
|
||||
assert_eq!(entry.authority.id, "codex-home-skills");
|
||||
assert_eq!(
|
||||
entry.id.0,
|
||||
"skill://codex-home-skills/executor/skills/dashboard"
|
||||
);
|
||||
assert_eq!(
|
||||
entry.main_prompt,
|
||||
SkillResourceId::environment(entry.main_prompt.as_str(), "remote-a", skill_path.clone(),)
|
||||
);
|
||||
let providers = SkillProviders::new().with_executor_provider(provider);
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(&mut builder, providers, skills_extension_config);
|
||||
let registry = builder.build();
|
||||
let metrics = Arc::new(RecordingMetrics::default());
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
registry.thread_lifecycle_contributors()[0]
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &default_config(),
|
||||
session_source: &SessionSource::Cli,
|
||||
persistent_thread_state_available: true,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: Some(metrics.clone()),
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
let turn_store = ExtensionData::new("turn-1");
|
||||
let mut expected_metrics = Vec::new();
|
||||
for (description, failed_environment, count, status) in [
|
||||
(Some("original"), None, 4, "complete"),
|
||||
(Some("updated"), None, 4, "complete"),
|
||||
// A replacement executor can return a fresh discovery with identical inventory.
|
||||
(Some("updated"), None, 4, "complete"),
|
||||
(Some("updated"), Some("remote-b"), 2, "partial"),
|
||||
(None, None, 0, "complete"),
|
||||
] {
|
||||
if let Some(description) = description {
|
||||
for snapshot in &mut snapshots {
|
||||
if Some(snapshot.environment_id.as_str()) == failed_environment {
|
||||
snapshot.result = Err("discovery unavailable".to_string());
|
||||
} else {
|
||||
let mut response = snapshot.result.as_ref().unwrap().as_ref().clone();
|
||||
response.plugins[0].skills[0].description = description.to_string();
|
||||
snapshot.result = Ok(Arc::new(response));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
snapshots.clear();
|
||||
}
|
||||
expected_metrics.push(expected_catalog_entries("executor", status, count));
|
||||
for _ in 0..2 {
|
||||
let step_store = ExtensionData::new("step");
|
||||
step_store.insert(snapshots.clone());
|
||||
step_store.insert(SelectedPluginSnapshot {
|
||||
plugins: snapshots
|
||||
.iter()
|
||||
.map(|snapshot| akode_extension_api::SelectedPluginIdentity {
|
||||
selected_root_id: Some(format!(
|
||||
"{}:local-name@marketplace",
|
||||
snapshot.environment_id
|
||||
)),
|
||||
plugin_id: akode_core_plugin_common::PluginIdentity::Remote {
|
||||
remote_plugin_id: "Plugin_123".into(),
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
});
|
||||
let sections = prepared_world_state(
|
||||
®istry,
|
||||
&[],
|
||||
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 rendered = sections
|
||||
.iter()
|
||||
.filter_map(|section| section.render_diff(PreviousWorldStateSection::Absent).1)
|
||||
.map(|fragment| fragment.body().clone().expect_text())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if let Some(description) = description {
|
||||
assert!(
|
||||
rendered.contains("skill://local-name@marketplace/"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains(&format!("- local-name:work: {description}")),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(!rendered.contains("- dashboard:"), "{rendered}");
|
||||
} else {
|
||||
assert!(!rendered.contains("- local-name:work:"), "{rendered}");
|
||||
}
|
||||
assert_eq!(metrics.samples(), expected_metrics);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_empty_failed_and_partial_results_never_load_legacy_roots() -> TestResult {
|
||||
let provider =
|
||||
ExecutorSkillProvider::new_with_restriction_product(/*restriction_product*/ None);
|
||||
let successful = installation("executor-a")?;
|
||||
let failed = ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-b".to_string(),
|
||||
result: Err("discovery unavailable".to_string()),
|
||||
};
|
||||
let root = SelectedCapabilityRoot {
|
||||
id: "legacy".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "unavailable-legacy-executor".to_string(),
|
||||
path: PathUri::parse("file:///legacy").unwrap(),
|
||||
},
|
||||
};
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let query = |snapshots| SkillListQuery {
|
||||
turn_id: "turn-1".to_string(),
|
||||
// V2 must ignore this unavailable legacy root.
|
||||
executor_roots: vec![AccessedSelectedCapabilityRoot {
|
||||
root: &root,
|
||||
fs: &access,
|
||||
}],
|
||||
host_snapshot: None,
|
||||
include_host_skills: false,
|
||||
include_bundled_skills: false,
|
||||
mcp_resources: None,
|
||||
executor_capability_discovery: None,
|
||||
executor_capability_discovery_v2: Some(snapshots),
|
||||
};
|
||||
let successful_catalog = provider.list(query(vec![successful.clone()])).await?;
|
||||
let failure_warning =
|
||||
"Environment `executor-b` discovery failed: discovery unavailable".to_string();
|
||||
for (snapshots, expected) in [
|
||||
(Vec::new(), SkillCatalog::default()),
|
||||
(
|
||||
vec![failed.clone()],
|
||||
SkillCatalog {
|
||||
is_partial: true,
|
||||
entries: Vec::new(),
|
||||
warnings: vec![failure_warning.clone()],
|
||||
},
|
||||
),
|
||||
(
|
||||
vec![successful, failed],
|
||||
SkillCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec![failure_warning],
|
||||
..successful_catalog
|
||||
},
|
||||
),
|
||||
] {
|
||||
assert_eq!(provider.list(query(snapshots)).await?, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
//! Exercises V2 catalog merging, retained read routes, and unchanged legacy rendering.
|
||||
|
||||
use super::*;
|
||||
use akode_core_plugin_common::PluginIdentity;
|
||||
use akode_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_extension_api::SelectedPluginIdentity;
|
||||
use akode_extension_api::SelectedPluginSnapshot;
|
||||
use akode_extension_api::ToolEnvironment;
|
||||
use akode_extension_api::ToolExecutor;
|
||||
use akode_skills_extension::detect_implicit_skill_invocation;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "source_telemetry_tests.rs"]
|
||||
mod source_telemetry_tests;
|
||||
|
||||
#[path = "tool_metrics_tests.rs"]
|
||||
mod tool_metrics_tests;
|
||||
|
||||
#[path = "name_resolution_tests.rs"]
|
||||
mod name_resolution_tests;
|
||||
|
||||
/// A standalone executor skill whose package and alias root are independent of plugins.
|
||||
fn executor_skill(name: &str) -> SkillCatalogEntry {
|
||||
let package = format!("skill://Plugin_123/{name}");
|
||||
SkillCatalogEntry::new(
|
||||
SkillPackageId(package.clone()),
|
||||
SkillAuthority::new(SkillSourceKind::Executor, "env-1"),
|
||||
format!("deploy:{name}"),
|
||||
format!("Executor {name} description"),
|
||||
SkillResourceId::environment(
|
||||
format!("{package}/SKILL.md"),
|
||||
"env-1",
|
||||
PathUri::parse(&format!("file:///skills/{name}/SKILL.md"))
|
||||
.expect("valid executor skill path"),
|
||||
),
|
||||
)
|
||||
.with_display_path(format!("{package}/SKILL.md"))
|
||||
}
|
||||
|
||||
fn installed_skill(
|
||||
root: &str,
|
||||
name: &str,
|
||||
) -> Result<SkillCatalogEntry, Box<dyn std::error::Error>> {
|
||||
let package = format!("skill://{root}/{name}");
|
||||
Ok(SkillCatalogEntry::new(
|
||||
SkillPackageId(package.clone()),
|
||||
SkillAuthority::new(SkillSourceKind::Executor, root),
|
||||
format!("deploy:{name}"),
|
||||
format!("Installed {root} description"),
|
||||
SkillResourceId::environment(
|
||||
format!("{package}/SKILL.md"),
|
||||
"env-1",
|
||||
PathUri::parse(&format!("file:///skills/{root}/SKILL.md"))?,
|
||||
),
|
||||
)
|
||||
.with_display_path(format!("{package}/SKILL.md"))
|
||||
.with_remote_plugin_id(Some("Plugin_123".to_string()))
|
||||
.with_plugin_id(Some(root.to_string())))
|
||||
}
|
||||
|
||||
fn provider(entries: Vec<SkillCatalogEntry>) -> StaticSkillProvider {
|
||||
StaticSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries,
|
||||
warnings: Vec::new(),
|
||||
},
|
||||
read_requests: Arc::default(),
|
||||
list_calls: Some(Arc::default()),
|
||||
fail_first_list: false,
|
||||
}
|
||||
}
|
||||
|
||||
struct MergeHarness {
|
||||
registry: akode_extension_api::ExtensionRegistry<TestConfig>,
|
||||
catalog_metrics: Arc<RecordingMetrics>,
|
||||
session_store: ExtensionData,
|
||||
thread_store: ExtensionData,
|
||||
turn_store: ExtensionData,
|
||||
step_store: ExtensionData,
|
||||
roots: Vec<SelectedCapabilityRoot>,
|
||||
snapshots: Option<Vec<ExecutorCapabilityDiscoveryV2Snapshot>>,
|
||||
discovery: Option<ExecutorCapabilityDiscoverySnapshot>,
|
||||
}
|
||||
|
||||
impl MergeHarness {
|
||||
async fn new(
|
||||
executor: StaticSkillProvider,
|
||||
config: TestConfig,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
Self::with_metrics(executor, config, /*metrics*/ None).await
|
||||
}
|
||||
|
||||
async fn with_metrics(
|
||||
executor: StaticSkillProvider,
|
||||
config: TestConfig,
|
||||
metrics: Option<MetricsClient>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let providers = SkillProviders::new().with_executor_provider(Arc::new(executor));
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
install_with_providers_and_metrics(
|
||||
&mut builder,
|
||||
providers,
|
||||
metrics,
|
||||
skills_extension_config,
|
||||
);
|
||||
let harness = Self {
|
||||
registry: builder.build(),
|
||||
catalog_metrics: Arc::default(),
|
||||
session_store: ExtensionData::new("session"),
|
||||
thread_store: ExtensionData::new("thread"),
|
||||
turn_store: ExtensionData::new("turn-1"),
|
||||
step_store: ExtensionData::new("step-1"),
|
||||
discovery: None,
|
||||
snapshots: Some(vec![ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "env-1".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse::default())),
|
||||
}]),
|
||||
roots: vec![SelectedCapabilityRoot {
|
||||
id: "skills".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "env-1".to_string(),
|
||||
path: PathUri::parse("file:///skills")?,
|
||||
},
|
||||
}],
|
||||
};
|
||||
harness.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: Some(harness.catalog_metrics.clone()),
|
||||
session_store: &harness.session_store,
|
||||
thread_store: &harness.thread_store,
|
||||
})
|
||||
.await;
|
||||
start_registered_turn(
|
||||
&harness.registry,
|
||||
&harness.session_store,
|
||||
&harness.thread_store,
|
||||
"turn-1",
|
||||
)
|
||||
.await;
|
||||
Ok(harness)
|
||||
}
|
||||
|
||||
async fn tools(
|
||||
&self,
|
||||
step: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
step.get_or_init(|| self.catalog_metrics.clone() as Arc<dyn ExtensionMetrics>);
|
||||
if let Some(snapshots) = &self.snapshots {
|
||||
step.insert(snapshots.clone());
|
||||
}
|
||||
if let Some(discovery) = &self.discovery {
|
||||
step.insert(discovery.clone());
|
||||
}
|
||||
if let Some(plugins) = self.turn_store.get::<SelectedPluginSnapshot>() {
|
||||
step.insert(plugins.as_ref().clone());
|
||||
}
|
||||
let selected_plugins = step.get::<SelectedPluginSnapshot>().unwrap_or_default();
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
prepare_step(
|
||||
&self.registry,
|
||||
akode_extension_api::StepPreparationInput {
|
||||
selected_plugins: &selected_plugins,
|
||||
turn_id: self.turn_store.level_id(),
|
||||
ready_selected_capability_roots: &self
|
||||
.roots
|
||||
.iter()
|
||||
.map(|root| AccessedSelectedCapabilityRoot { root, fs: &access })
|
||||
.collect::<Vec<_>>(),
|
||||
executor_capability_discovery: self.discovery.as_ref(),
|
||||
executor_capability_discovery_v2: self.snapshots.as_deref(),
|
||||
session_store: &self.session_store,
|
||||
thread_store: &self.thread_store,
|
||||
turn_store: &self.turn_store,
|
||||
step_store: step,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
self.registry.tool_contributors()[0].tools_for_step(
|
||||
&self.session_store,
|
||||
&self.thread_store,
|
||||
step,
|
||||
)
|
||||
}
|
||||
|
||||
async fn render(&self) -> Result<String, Box<dyn std::error::Error>> {
|
||||
self.render_step(&self.step_store).await
|
||||
}
|
||||
|
||||
async fn render_step(
|
||||
&self,
|
||||
step_store: &ExtensionData,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let turn_store = &self.turn_store;
|
||||
if let Some(plugins) = turn_store.get::<akode_extension_api::SelectedPluginSnapshot>() {
|
||||
step_store.insert(plugins.as_ref().clone());
|
||||
}
|
||||
if let Some(snapshots) = &self.snapshots {
|
||||
step_store.insert(snapshots.clone());
|
||||
}
|
||||
if let Some(discovery) = &self.discovery {
|
||||
step_store.insert(discovery.clone());
|
||||
}
|
||||
let sections = prepared_world_state(
|
||||
&self.registry,
|
||||
&self.roots,
|
||||
WorldStateContributionInput {
|
||||
previous_world_state: None,
|
||||
step_store,
|
||||
model_info: &catalog_model_info(),
|
||||
thread_id: akode_protocol::ThreadId::new(),
|
||||
turn_id: turn_store.level_id(),
|
||||
environments: &[],
|
||||
extension_metrics: None,
|
||||
session_store: &self.session_store,
|
||||
thread_store: &self.thread_store,
|
||||
turn_store,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Ok(sections
|
||||
.iter()
|
||||
.filter_map(|section| section.render_diff(PreviousWorldStateSection::Absent).1)
|
||||
.map(|fragment| fragment.body().clone().expect_text())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn call_tool(
|
||||
tools: &[Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>],
|
||||
name: &str,
|
||||
arguments: Value,
|
||||
) -> Result<Value, FunctionCallError> {
|
||||
call_tool_with_budget(tools, name, arguments, TruncationPolicy::Bytes(10_000)).await
|
||||
}
|
||||
|
||||
async fn call_tool_with_budget(
|
||||
tools: &[Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>],
|
||||
name: &str,
|
||||
arguments: Value,
|
||||
truncation_policy: TruncationPolicy,
|
||||
) -> Result<Value, FunctionCallError> {
|
||||
let tool = tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name().name == name)
|
||||
.ok_or_else(|| FunctionCallError::RespondToModel("missing skill tool".to_string()))?;
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
};
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let cwd = PathUri::parse("file:///installed")
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
let result = tool
|
||||
.handle(ToolCall {
|
||||
turn_id: "turn-1".to_string(),
|
||||
call_id: "skill-test".to_string(),
|
||||
tool_name: tool.tool_name(),
|
||||
model: "test".to_string(),
|
||||
codex_turn_metadata: None,
|
||||
truncation_policy,
|
||||
source: ToolCallSource::Direct,
|
||||
conversation_history: ConversationHistory::default(),
|
||||
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
|
||||
attachment_store: Arc::new(InlineAttachmentStore),
|
||||
ephemeral: false,
|
||||
environments: ["env-1", "env-2", "env-3"]
|
||||
.into_iter()
|
||||
.map(|id| ToolEnvironment::new(id.to_string(), cwd.clone(), &access))
|
||||
.collect(),
|
||||
payload: payload.clone(),
|
||||
})
|
||||
.await?;
|
||||
// Skill tool output is never external context once only local sources remain.
|
||||
assert!(!result.contains_external_context());
|
||||
let response = result
|
||||
.post_tool_use_response("skill-test", &payload)
|
||||
.ok_or_else(|| FunctionCallError::RespondToModel("missing skill response".to_string()))?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn selected_plugins(roots: &[Option<&str>], disabled: &[&str]) -> SelectedPluginSnapshot {
|
||||
SelectedPluginSnapshot {
|
||||
plugins: roots
|
||||
.iter()
|
||||
.map(|root| SelectedPluginIdentity {
|
||||
selected_root_id: (*root).map(str::to_string),
|
||||
plugin_id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "Plugin_123".to_string(),
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
disabled_plugin_ids: disabled.iter().map(|id| (*id).to_string()).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_disabled_remote_plugin_blocks_executor_read_route() -> TestResult {
|
||||
let installed =
|
||||
installed_skill("matching", "work")?.with_plugin_id(Some("matching".to_string()));
|
||||
let harness = MergeHarness::new(provider(vec![installed.clone()]), default_config()).await?;
|
||||
harness.turn_store.insert(selected_plugins(
|
||||
&[None, Some("env-1:matching")],
|
||||
&["Plugin_123"],
|
||||
));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
assert!(!harness.render().await?.contains("- deploy:work:"));
|
||||
let result = call_tool(&tools, "read", json!({"package": installed.id.0})).await;
|
||||
assert_matches!(result, Err(FunctionCallError::RespondToModel(message)) if message == "skill package is not available");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v1_reads_preserve_response_shape_without_installations_tool() -> TestResult {
|
||||
let executor = installed_skill("first", "work")?;
|
||||
let mut disabled = MergeHarness::new(provider(vec![executor.clone()]), default_config()).await?;
|
||||
disabled.snapshots = None;
|
||||
assert_eq!(
|
||||
disabled
|
||||
.tools(&disabled.step_store)
|
||||
.await
|
||||
.iter()
|
||||
.map(|tool| tool.tool_name().name)
|
||||
.collect::<Vec<_>>(),
|
||||
["list", "read"],
|
||||
);
|
||||
disabled.render().await?;
|
||||
let tools = disabled.tools(&disabled.step_store).await;
|
||||
let expected = json!({
|
||||
"resource": executor.main_prompt.as_str(),
|
||||
"contents": "# Lint Fix\n\nRun the formatter.",
|
||||
"next_cursor": null,
|
||||
"skill_root": PathUri::parse("file:///skills/first")?.inferred_native_path_string(),
|
||||
});
|
||||
assert_eq!(
|
||||
call_tool(&tools, "read", json!({"package": executor.id.0})).await?,
|
||||
expected
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_rendering_and_tools_retain_their_step_catalog() -> TestResult {
|
||||
let installed =
|
||||
installed_skill("matching", "work")?.with_plugin_id(Some("matching".to_string()));
|
||||
let executor = provider(vec![installed.clone()]);
|
||||
let executor_calls = executor.list_calls.clone().unwrap();
|
||||
let harness = MergeHarness::new(executor, default_config()).await?;
|
||||
harness
|
||||
.turn_store
|
||||
.insert(selected_plugins(&[None, Some("env-1:matching")], &[]));
|
||||
// Preparation makes tools usable before any World State rendering.
|
||||
let original_tools = harness.tools(&harness.step_store).await;
|
||||
let early_list = call_tool(
|
||||
&original_tools,
|
||||
"list",
|
||||
json!({"authority": {"kind": "executor"}}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(early_list["skills"].as_array().unwrap().len(), 1);
|
||||
call_tool(&original_tools, "read", json!({"package": installed.id.0})).await?;
|
||||
assert_eq!(executor_calls.load(Ordering::SeqCst), 1);
|
||||
let original_rendering = harness.render().await?;
|
||||
assert!(original_rendering.contains("- deploy:work:"));
|
||||
let next_step = ExtensionData::new("step-2");
|
||||
harness
|
||||
.turn_store
|
||||
.insert(selected_plugins(&[], &["Plugin_123"]));
|
||||
let next_tools = harness.tools(&next_step).await;
|
||||
assert!(
|
||||
!harness
|
||||
.render_step(&next_step)
|
||||
.await?
|
||||
.contains("- deploy:work:")
|
||||
);
|
||||
// Re-preparing the old step must not replace its catalog with the new policy.
|
||||
assert_eq!(harness.render().await?, original_rendering);
|
||||
for (tools, allowed) in [(&original_tools, true), (&next_tools, false)] {
|
||||
let listed = call_tool(tools, "list", json!({"authority": {"kind": "executor"}})).await?;
|
||||
assert_eq!(
|
||||
listed["skills"].as_array().unwrap().len(),
|
||||
usize::from(allowed)
|
||||
);
|
||||
let read = call_tool(tools, "read", json!({"package": installed.id.0})).await;
|
||||
if allowed {
|
||||
read?;
|
||||
} else {
|
||||
assert_matches!(read, Err(FunctionCallError::RespondToModel(message)) if message == "skill package is not available");
|
||||
}
|
||||
}
|
||||
// Re-enabling the plugin reuses the raw projection, not the denied step's catalog.
|
||||
let enabled_step = ExtensionData::new("step-3");
|
||||
harness
|
||||
.turn_store
|
||||
.insert(selected_plugins(&[None, Some("env-1:matching")], &[]));
|
||||
let enabled_tools = harness.tools(&enabled_step).await;
|
||||
assert_eq!(
|
||||
harness.render_step(&enabled_step).await?,
|
||||
original_rendering
|
||||
);
|
||||
call_tool(&enabled_tools, "read", json!({"package": installed.id.0})).await?;
|
||||
assert_eq!(executor_calls.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_implicit_and_explicit_invocations_retain_their_step_catalog() -> TestResult {
|
||||
let installed =
|
||||
installed_skill("matching", "work")?.with_plugin_id(Some("matching".to_string()));
|
||||
let executor_provider = provider(vec![installed.clone()]);
|
||||
let reads = executor_provider.read_requests.clone();
|
||||
let harness = MergeHarness::new(executor_provider, default_config()).await?;
|
||||
harness
|
||||
.turn_store
|
||||
.insert(selected_plugins(&[None, Some("env-1:matching")], &[]));
|
||||
assert!(harness.render().await?.contains("- deploy:work:"));
|
||||
let workdir = PathUri::parse("file:///skills")?;
|
||||
let detect = |step_store| {
|
||||
detect_implicit_skill_invocation(
|
||||
&harness.turn_store,
|
||||
step_store,
|
||||
"env-1",
|
||||
"cat matching/SKILL.md",
|
||||
&workdir,
|
||||
/*native_workdir*/ None,
|
||||
)
|
||||
};
|
||||
let original = detect(&harness.step_store).expect("prepared step skill");
|
||||
assert_eq!(original.remote_plugin_id, installed.remote_plugin_id);
|
||||
assert_eq!(original.plugin_id.as_deref(), Some("matching"));
|
||||
assert_matches!(&original.location, akode_skills_extension::SkillInvocationLocation::Resource { id, .. } if id == installed.main_prompt.as_str());
|
||||
|
||||
let next_step = ExtensionData::new("step-2");
|
||||
harness.turn_store.insert(SelectedPluginSnapshot::default());
|
||||
harness.render_step(&next_step).await?;
|
||||
assert_eq!(
|
||||
detect(&harness.step_store).map(|invocation| (
|
||||
invocation.skill_name,
|
||||
invocation.plugin_id,
|
||||
invocation.remote_plugin_id,
|
||||
)),
|
||||
Some((
|
||||
original.skill_name,
|
||||
original.plugin_id,
|
||||
original.remote_plugin_id
|
||||
)),
|
||||
);
|
||||
assert!(detect(&next_step).is_none());
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
for (step_store, allowed) in [(&harness.step_store, true), (&next_step, false)] {
|
||||
let fragments = prepared_turn_input(
|
||||
&harness.registry,
|
||||
TurnInputContext {
|
||||
step_store,
|
||||
turn_id: "turn-1".to_string(),
|
||||
user_input: vec![UserInput::Mention {
|
||||
name: installed.name.clone(),
|
||||
path: installed.main_prompt.as_str().to_string(),
|
||||
}],
|
||||
environments: vec![akode_extension_api::TurnInputEnvironment {
|
||||
environment_id: "env-1".to_string(),
|
||||
cwd: PathUri::parse("file:///skills")?,
|
||||
is_primary: true,
|
||||
fs: &access,
|
||||
}],
|
||||
},
|
||||
/*extension_metrics*/ None,
|
||||
&harness.session_store,
|
||||
&harness.thread_store,
|
||||
&harness.turn_store,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(fragments.len(), usize::from(allowed));
|
||||
if allowed {
|
||||
assert!(
|
||||
fragments[0]
|
||||
.render()
|
||||
.expect_text()
|
||||
.contains("<name>deploy:work</name>")
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
read_request_keys(&reads),
|
||||
vec![(installed.authority, installed.id, installed.main_prompt)]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v1_retains_legacy_plugin_disablement() -> TestResult {
|
||||
let installed =
|
||||
installed_skill("legacy", "work")?.with_remote_plugin_id(/*remote_plugin_id*/ None);
|
||||
for disabled in [false, true] {
|
||||
let mut executor = provider(vec![installed.clone()]);
|
||||
executor.catalog.warnings = vec!["Executor warning".into()];
|
||||
let reads = executor.read_requests.clone();
|
||||
let mut harness = MergeHarness::new(executor, default_config()).await?;
|
||||
harness.snapshots = None;
|
||||
harness.discovery = Some(ExecutorCapabilityDiscoverySnapshot::new(
|
||||
&[],
|
||||
Vec::new(),
|
||||
Default::default(),
|
||||
));
|
||||
harness.turn_store.insert(SelectedPluginSnapshot {
|
||||
plugins: vec![SelectedPluginIdentity {
|
||||
selected_root_id: Some(installed.authority.id.clone()),
|
||||
plugin_id: PluginIdentity::Local {
|
||||
plugin_id: "legacy@marketplace".to_string(),
|
||||
},
|
||||
}],
|
||||
disabled_plugin_roots: if disabled {
|
||||
vec![installed.authority.id.clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
..Default::default()
|
||||
});
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
let rendered = harness.render().await?;
|
||||
assert_eq!(rendered.contains("Installed legacy description"), !disabled);
|
||||
let listed = call_tool(&tools, "list", json!({"authority": {"kind": "executor"}})).await?;
|
||||
assert_eq!(
|
||||
listed["skills"].as_array().unwrap().len(),
|
||||
usize::from(!disabled)
|
||||
);
|
||||
assert_eq!(listed["warnings"], json!(["Executor warning"]));
|
||||
let read = call_tool(&tools, "read", json!({"package": installed.id.0})).await;
|
||||
if disabled {
|
||||
assert_matches!(read, Err(FunctionCallError::RespondToModel(message)) if message == "skill package is not available");
|
||||
} else {
|
||||
read?;
|
||||
}
|
||||
assert_eq!(read_request_keys(&reads).len(), usize::from(!disabled));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Display names resolve through the same policy-checked routes as package locators.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn skill_names_preserve_package_and_alias_precedence_in_both_versions() -> TestResult {
|
||||
for discovery_v2 in [false, true] {
|
||||
let skill = executor_skill("work").with_alias_root("skill://Plugin_123");
|
||||
let mut hidden = executor_skill("hidden").hidden_from_prompt();
|
||||
hidden.name = skill.name.clone();
|
||||
let mut disabled = executor_skill("disabled").disabled();
|
||||
disabled.name = skill.name.clone();
|
||||
let disabled_package = disabled.id.0.clone();
|
||||
let mut entries = vec![skill.clone(), hidden, disabled];
|
||||
for (id, name) in [
|
||||
("package-shadow", skill.id.0.as_str()),
|
||||
("alias-shadow", "e0/work"),
|
||||
("disabled-package-shadow", disabled_package.as_str()),
|
||||
("disabled-alias-shadow", "e0/disabled"),
|
||||
] {
|
||||
let mut shadow = executor_skill(id);
|
||||
shadow.name = name.to_string();
|
||||
entries.push(shadow);
|
||||
}
|
||||
let mut harness = MergeHarness::new(provider(entries), default_config()).await?;
|
||||
if !discovery_v2 {
|
||||
harness.snapshots = None;
|
||||
}
|
||||
harness.turn_store.insert(selected_plugins(&[None], &[]));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
for tool in if discovery_v2 {
|
||||
vec!["read", "installations"]
|
||||
} else {
|
||||
vec!["read"]
|
||||
} {
|
||||
let expected = call_tool(&tools, tool, json!({"package": skill.id.0})).await?;
|
||||
for package in [skill.name.as_str(), "e0/work"] {
|
||||
assert_eq!(
|
||||
call_tool(&tools, tool, json!({"package": package})).await?,
|
||||
expected,
|
||||
"{tool}: {package} (discovery_v2={discovery_v2})",
|
||||
);
|
||||
}
|
||||
if tool == "read" {
|
||||
assert_eq!(expected["resource"], skill.main_prompt.as_str());
|
||||
}
|
||||
for package in [disabled_package.as_str(), "e0/disabled"] {
|
||||
assert_eq!(
|
||||
call_tool(&tools, tool, json!({"package": package})).await,
|
||||
Err(FunctionCallError::RespondToModel(
|
||||
"skill package is not available".to_string()
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ambiguous_skill_names_require_a_package_locator() -> TestResult {
|
||||
let prefix = format!("x:{}", "🦀".repeat(63));
|
||||
let mut first = executor_skill("work");
|
||||
first.name = format!("{prefix}🦀");
|
||||
let mut second = executor_skill("another");
|
||||
second.name = first.name.clone();
|
||||
let mut shorter = executor_skill("shorter");
|
||||
shorter.name = prefix.clone();
|
||||
let hidden = executor_skill("hidden").hidden_from_prompt();
|
||||
let disabled = executor_skill("disabled").disabled();
|
||||
let harness = MergeHarness::new(
|
||||
provider(vec![first.clone(), second, shorter, hidden, disabled]),
|
||||
default_config(),
|
||||
)
|
||||
.await?;
|
||||
harness.turn_store.insert(selected_plugins(&[None], &[]));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
for tool in ["read", "installations"] {
|
||||
for name in [&first.name, &prefix] {
|
||||
assert_eq!(
|
||||
call_tool(&tools, tool, json!({"package": name})).await,
|
||||
Err(FunctionCallError::RespondToModel(
|
||||
"skill name is ambiguous; use skills.list and pass the package for the intended skill".to_string(),
|
||||
)),
|
||||
);
|
||||
}
|
||||
for package in ["deploy:hidden", "deploy:disabled"] {
|
||||
assert_eq!(
|
||||
call_tool(&tools, tool, json!({"package": package})).await,
|
||||
Err(FunctionCallError::RespondToModel(
|
||||
"skill package is not available".to_string()
|
||||
)),
|
||||
);
|
||||
}
|
||||
call_tool(&tools, tool, json!({"package": first.id.0})).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
111
akode-rs/ext/skills/tests/skills_extension/preparation_tests.rs
Normal file
111
akode-rs/ext/skills/tests/skills_extension/preparation_tests.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
//! Exercises config reloads while preparation is waiting on executor discovery.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
struct PausedExecutor {
|
||||
entered: Notify,
|
||||
resume: Notify,
|
||||
queries: Mutex<Vec<bool>>,
|
||||
}
|
||||
|
||||
impl SkillProvider for PausedExecutor {
|
||||
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
|
||||
Box::pin(async move {
|
||||
self.queries
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(query.include_bundled_skills);
|
||||
self.entered.notify_one();
|
||||
self.resume.notified().await;
|
||||
Ok(SkillCatalog::default())
|
||||
})
|
||||
}
|
||||
|
||||
fn read<'a>(
|
||||
&'a self,
|
||||
_request: SkillReadRequest<'a>,
|
||||
) -> SkillProviderFuture<'a, SkillReadResult> {
|
||||
Box::pin(async { panic!("executor reads are not expected") })
|
||||
}
|
||||
|
||||
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
|
||||
Box::pin(async { panic!("executor searches are not expected") })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn config_reload_during_preparation_applies_to_next_step() -> TestResult {
|
||||
let executor = Arc::new(PausedExecutor {
|
||||
entered: Notify::new(),
|
||||
resume: Notify::new(),
|
||||
queries: Mutex::default(),
|
||||
});
|
||||
let providers = SkillProviders::new().with_executor_provider(executor.clone());
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(&mut builder, providers, skills_extension_config);
|
||||
let registry = builder.build();
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let turn = ExtensionData::new("turn");
|
||||
let config = default_config();
|
||||
let updated = TestConfig {
|
||||
bundled_skills_enabled: false,
|
||||
..config.clone()
|
||||
};
|
||||
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,
|
||||
thread_store: &thread,
|
||||
})
|
||||
.await;
|
||||
start_registered_turn(®istry, &session, &thread, "turn").await;
|
||||
let roots = vec![SelectedCapabilityRoot {
|
||||
id: "skills".into(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "env-1".into(),
|
||||
path: PathUri::parse("file:///skills")?,
|
||||
},
|
||||
}];
|
||||
let step = ExtensionData::new("step");
|
||||
let next_step = ExtensionData::new("next-step");
|
||||
let model_info = catalog_model_info();
|
||||
for store in [&step, &next_step] {
|
||||
let (_sections, ()) = tokio::join!(
|
||||
prepared_world_state(
|
||||
®istry,
|
||||
&roots,
|
||||
WorldStateContributionInput {
|
||||
previous_world_state: None,
|
||||
step_store: store,
|
||||
model_info: &model_info,
|
||||
thread_id: akode_protocol::ThreadId::new(),
|
||||
turn_id: "turn",
|
||||
environments: &[],
|
||||
extension_metrics: None,
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &turn,
|
||||
}
|
||||
),
|
||||
async {
|
||||
executor.entered.notified().await;
|
||||
registry.config_contributors()[0]
|
||||
.on_config_changed(&session, &thread, &config, &updated);
|
||||
executor.resume.notify_one();
|
||||
}
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
*executor.queries.lock().unwrap(),
|
||||
vec![true, false]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
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(
|
||||
®istry,
|
||||
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(())
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Verifies provider attribution follows the selected route, including cached reads.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing::field::Field;
|
||||
use tracing::field::Visit;
|
||||
use tracing::instrument::WithSubscriber;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::layer::Context;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ReadEvents(Arc<Mutex<Vec<Value>>>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fields(serde_json::Map<String, Value>);
|
||||
|
||||
impl Visit for Fields {
|
||||
fn record_str(&mut self, field: &Field, value: &str) {
|
||||
self.0.insert(field.name().into(), json!(value));
|
||||
}
|
||||
|
||||
fn record_bool(&mut self, field: &Field, value: bool) {
|
||||
self.0.insert(field.name().into(), json!(value));
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
|
||||
self.record_str(field, &format!("{value:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: tracing::Subscriber> Layer<S> for ReadEvents {
|
||||
fn on_event(&self, event: &tracing::Event<'_>, _context: Context<'_, S>) {
|
||||
let mut fields = Fields::default();
|
||||
event.record(&mut fields);
|
||||
if fields.0.get("event.name") == Some(&json!("codex.skill_read.source_selected")) {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(Value::Object(fields.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_events_cover_default_and_explicit_executor_reads() -> TestResult {
|
||||
let installed = installed_skill("matching", "work")?;
|
||||
let executor = provider(vec![installed.clone()]);
|
||||
let executor_reads = executor.read_requests.clone();
|
||||
let harness = MergeHarness::new(executor, default_config()).await?;
|
||||
harness
|
||||
.turn_store
|
||||
.insert(selected_plugins(&[None, Some("env-1:matching")], &[]));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
harness.render().await?;
|
||||
let events = ReadEvents::default();
|
||||
let subscriber = tracing_subscriber::registry().with(events.clone().with_filter(
|
||||
tracing_subscriber::filter::filter_fn(akode_otel::trace_export_filter),
|
||||
));
|
||||
// Prevent parallel tests with no subscriber from disabling this callsite globally.
|
||||
let _interest_cache_guard =
|
||||
tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
|
||||
async {
|
||||
for selector in [
|
||||
Value::Null,
|
||||
json!({"kind": "executor", "environment_id": "env-1"}),
|
||||
] {
|
||||
call_tool(
|
||||
&tools,
|
||||
"read",
|
||||
json!({"package": installed.id.0, "source": selector}),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
assert!(
|
||||
call_tool(&tools, "read", json!({"package": "missing"}))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
TestResult::Ok(())
|
||||
}
|
||||
.with_subscriber(subscriber)
|
||||
.await?;
|
||||
|
||||
let expected = [(); 2].map(|()| {
|
||||
json!({
|
||||
"message": "Selected skill read source",
|
||||
"event.name": "codex.skill_read.source_selected",
|
||||
"conversation.id": "thread",
|
||||
"turn_id": "turn-1",
|
||||
"call_id": "skill-test",
|
||||
"tool_namespace": "skills",
|
||||
"tool_name": "read",
|
||||
"skill_source": "executor",
|
||||
"skill_name": "deploy:work",
|
||||
"skill_plugin_id": "matching",
|
||||
"skill_resource_kind": "main_prompt",
|
||||
"is_continuation": false,
|
||||
})
|
||||
});
|
||||
assert_eq!(*events.0.lock().unwrap(), expected);
|
||||
assert_eq!(read_request_keys(&executor_reads).len(), 2);
|
||||
Ok(())
|
||||
}
|
||||
184
akode-rs/ext/skills/tests/skills_extension/tool_metrics_tests.rs
Normal file
184
akode-rs/ext/skills/tests/skills_extension/tool_metrics_tests.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
//! Checks bounded outcome metrics for skill reads and installation listings.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn read_result(outcome: &str, version: &str) -> RecordedCounter {
|
||||
RecordedCounter {
|
||||
name: "codex.skills.read.result".to_string(),
|
||||
increment: 1,
|
||||
tags: vec![
|
||||
("outcome".to_string(), outcome.to_string()),
|
||||
("discovery_version".to_string(), version.to_string()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn installations_result(outcome: &str, source_filter: &str) -> RecordedCounter {
|
||||
RecordedCounter {
|
||||
name: "codex.skills.installations.result".to_string(),
|
||||
increment: 1,
|
||||
tags: vec![
|
||||
("outcome".to_string(), outcome.to_string()),
|
||||
("source_filter".to_string(), source_filter.to_string()),
|
||||
("discovery_version".to_string(), "v2".to_string()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
|
||||
for discovery_version in ["v1", "v2"] {
|
||||
let mut executor = installed_skill("executor", "local")?
|
||||
.with_remote_plugin_id(/*remote_plugin_id*/ None)
|
||||
.with_plugin_id(/*plugin_id*/ None);
|
||||
executor.main_prompt = SkillResourceId::environment(
|
||||
executor.main_prompt.as_str(),
|
||||
"missing-environment",
|
||||
PathUri::parse("file:///skills/local/SKILL.md")?,
|
||||
);
|
||||
let mut harness = MergeHarness::new(
|
||||
provider(vec![
|
||||
executor,
|
||||
executor_skill("work").with_alias_root("skill://Plugin_123"),
|
||||
]),
|
||||
default_config(),
|
||||
)
|
||||
.await?;
|
||||
if discovery_version == "v1" {
|
||||
harness.snapshots = None;
|
||||
}
|
||||
harness.turn_store.insert(selected_plugins(&[None], &[]));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
let mut expected = Vec::new();
|
||||
for (arguments, budget, outcome) in [
|
||||
(
|
||||
json!({"package": "skill://Plugin_123/work"}),
|
||||
10_000,
|
||||
"success",
|
||||
),
|
||||
(json!({}), 10_000, "invalid_arguments"),
|
||||
(json!({"package": "missing"}), 10_000, "package_unavailable"),
|
||||
(json!({"package": "e99/work"}), 10_000, "unresolved_alias"),
|
||||
(
|
||||
json!({"package": "skill://executor/local"}),
|
||||
10_000,
|
||||
"environment_unavailable",
|
||||
),
|
||||
(
|
||||
json!({"package": "skill://Plugin_123/work", "source": {"kind": "executor", "environment_id": "missing"}}),
|
||||
10_000,
|
||||
"source_unavailable",
|
||||
),
|
||||
(
|
||||
json!({"package": "skill://Plugin_123/work", "cursor": "invalid"}),
|
||||
10_000,
|
||||
"invalid_cursor",
|
||||
),
|
||||
(
|
||||
json!({"package": "skill://Plugin_123/work"}),
|
||||
1,
|
||||
"response_budget",
|
||||
),
|
||||
] {
|
||||
if discovery_version == "v1" && outcome != "success" {
|
||||
continue;
|
||||
}
|
||||
let result =
|
||||
call_tool_with_budget(&tools, "read", arguments, TruncationPolicy::Bytes(budget))
|
||||
.await;
|
||||
assert_eq!(
|
||||
result.is_ok(),
|
||||
outcome == "success",
|
||||
"{outcome}: {result:?}"
|
||||
);
|
||||
expected.push(read_result(outcome, discovery_version));
|
||||
// Successful executor reads also record skill invocations; compare read outcomes only.
|
||||
let read_counters = harness
|
||||
.catalog_metrics
|
||||
.counters()
|
||||
.into_iter()
|
||||
.filter(|counter| counter.name == "codex.skills.read.result")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(read_counters, expected);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installations_report_outcomes_for_each_discovery_version() -> TestResult {
|
||||
let harness = MergeHarness::new(
|
||||
provider(vec![
|
||||
executor_skill("work").with_alias_root("skill://Plugin_123"),
|
||||
]),
|
||||
default_config(),
|
||||
)
|
||||
.await?;
|
||||
harness.turn_store.insert(selected_plugins(&[None], &[]));
|
||||
let tools = harness.tools(&harness.step_store).await;
|
||||
let mut expected = Vec::new();
|
||||
for (arguments, budget, outcome, source_filter) in [
|
||||
(
|
||||
json!({"package": "skill://Plugin_123/work"}),
|
||||
10_000,
|
||||
"success",
|
||||
"all",
|
||||
),
|
||||
(
|
||||
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": "env-1"}}),
|
||||
10_000,
|
||||
"success",
|
||||
"executor",
|
||||
),
|
||||
(
|
||||
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": "missing"}}),
|
||||
10_000,
|
||||
"empty",
|
||||
"executor",
|
||||
),
|
||||
(json!({}), 10_000, "invalid_arguments", "unparsed"),
|
||||
(json!({"package": ""}), 10_000, "invalid_package", "all"),
|
||||
(
|
||||
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": ""}}),
|
||||
10_000,
|
||||
"invalid_source",
|
||||
"executor",
|
||||
),
|
||||
(
|
||||
json!({"package": "e0/missing"}),
|
||||
10_000,
|
||||
"package_unavailable",
|
||||
"all",
|
||||
),
|
||||
(
|
||||
json!({"package": "e99/work"}),
|
||||
10_000,
|
||||
"unresolved_alias",
|
||||
"all",
|
||||
),
|
||||
(
|
||||
json!({"package": "e0/work", "cursor": "invalid"}),
|
||||
10_000,
|
||||
"invalid_cursor",
|
||||
"all",
|
||||
),
|
||||
(json!({"package": "e0/work"}), 1, "response_budget", "all"),
|
||||
] {
|
||||
let result = call_tool_with_budget(
|
||||
&tools,
|
||||
"installations",
|
||||
arguments,
|
||||
TruncationPolicy::Bytes(budget),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result.is_ok(),
|
||||
matches!(outcome, "success" | "empty"),
|
||||
"{outcome}: {result:?}"
|
||||
);
|
||||
expected.push(installations_result(outcome, source_filter));
|
||||
assert_eq!(harness.catalog_metrics.counters(), expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: ext/skills/tests/executor_file_system_authority.rs
|
||||
expression: "serde_json::to_string_pretty(&snapshot).expect(\"serialize catalog snapshot\")"
|
||||
---
|
||||
{
|
||||
"entries": [
|
||||
{
|
||||
"authority": {
|
||||
"id": "snapshot-root",
|
||||
"kind": "executor"
|
||||
},
|
||||
"dependencies": [
|
||||
{
|
||||
"command": null,
|
||||
"description": "Deployment server.",
|
||||
"transport": null,
|
||||
"type": "mcp",
|
||||
"url": null,
|
||||
"value": "deployer"
|
||||
}
|
||||
],
|
||||
"description": "Synthetic executor skill.",
|
||||
"enabled": true,
|
||||
"name": "snapshot-plugin:synthetic",
|
||||
"prompt_visible": false,
|
||||
"short_description": null
|
||||
}
|
||||
],
|
||||
"warnings": []
|
||||
}
|
||||
Reference in New Issue
Block a user