aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
181
akode-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
181
akode-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
//! Reuse parsed manifest revisions within an explicitly owned plugin store.
|
||||
//! Store clones share the cache; independently created stores do not share entries or warnings.
|
||||
|
||||
use super::LoadedPluginManifest;
|
||||
use super::PluginManifestFormat;
|
||||
use super::UriPluginManifest;
|
||||
use super::parse_resolved_plugin_manifest;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
|
||||
use akode_utils_plugins::find_plugin_manifest_path;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const CAPACITY: usize = 128;
|
||||
const MAX_CACHABLE_INPUT_LEN: usize = 64 * 1024;
|
||||
|
||||
pub(crate) struct ManifestCache {
|
||||
state: Option<Mutex<ManifestCacheState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ManifestCacheState {
|
||||
entries: HashMap<(PathUri, PathUri), Entry>,
|
||||
recency: VecDeque<(PathUri, PathUri)>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
contents_digest: [u8; 32],
|
||||
overlay: Option<(PathUri, [u8; 32])>,
|
||||
manifest: UriPluginManifest,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ManifestCache {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ManifestCache")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ManifestCache {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Some(Mutex::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCache {
|
||||
pub(crate) fn disabled() -> Self {
|
||||
Self { state: None }
|
||||
}
|
||||
|
||||
pub(crate) fn load(&self, plugin_root: &Path) -> Option<LoadedPluginManifest> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root)?;
|
||||
let contents = fs::read_to_string(&manifest_path).ok()?;
|
||||
let is_agent_plugin =
|
||||
manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH);
|
||||
let overlay = if is_agent_plugin {
|
||||
let overlay_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
fs::read_to_string(&overlay_path)
|
||||
.ok()
|
||||
.map(|contents| (overlay_path, contents))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match parse_resolved_plugin_manifest(
|
||||
self,
|
||||
plugin_root,
|
||||
&manifest_path,
|
||||
&contents,
|
||||
overlay
|
||||
.as_ref()
|
||||
.map(|(path, contents)| (path.as_path(), contents.as_str())),
|
||||
) {
|
||||
Ok(manifest) => Some(LoadedPluginManifest {
|
||||
manifest,
|
||||
format: if is_agent_plugin {
|
||||
PluginManifestFormat::AgentPlugin
|
||||
} else {
|
||||
PluginManifestFormat::Legacy
|
||||
},
|
||||
}),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
path = %manifest_path.display(),
|
||||
"failed to parse plugin manifest: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse(
|
||||
&self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let Some(state) = &self.state else {
|
||||
return parse();
|
||||
};
|
||||
if contents
|
||||
.len()
|
||||
.saturating_add(overlay.map_or(0, |(_, value)| value.len()))
|
||||
> MAX_CACHABLE_INPUT_LEN
|
||||
{
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(&(root.clone(), path.clone()));
|
||||
// Unbounded inputs must not serialize unrelated parses behind the cache lock.
|
||||
return parse();
|
||||
}
|
||||
// Parsing is synchronous and does no filesystem I/O. Serializing cache misses also
|
||||
// prevents concurrent capability loaders from validating the same revision twice.
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.parse(root, path, contents, overlay, parse)
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCacheState {
|
||||
fn remove(&mut self, key: &(PathUri, PathUri)) -> Option<Entry> {
|
||||
let entry = self.entries.remove(key)?;
|
||||
self.recency.retain(|existing| existing != key);
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
&mut self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let key = (root.clone(), path.clone());
|
||||
let previous = self.remove(&key);
|
||||
let contents_digest = Sha256::digest(contents.as_bytes()).into();
|
||||
let overlay = overlay
|
||||
.map(|(path, contents)| (path.clone(), Sha256::digest(contents.as_bytes()).into()));
|
||||
if let Some(entry) = previous
|
||||
&& entry.contents_digest == contents_digest
|
||||
&& entry.overlay == overlay
|
||||
{
|
||||
let manifest = entry.manifest.clone();
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(key, entry);
|
||||
return Ok(manifest);
|
||||
}
|
||||
let manifest = parse()?;
|
||||
if self.entries.len() == CAPACITY
|
||||
&& let Some(oldest) = self.recency.pop_back()
|
||||
{
|
||||
self.entries.remove(&oldest);
|
||||
}
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(
|
||||
key,
|
||||
Entry {
|
||||
contents_digest,
|
||||
overlay,
|
||||
manifest: manifest.clone(),
|
||||
},
|
||||
);
|
||||
Ok(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "manifest_cache_tests.rs"]
|
||||
mod tests;
|
||||
303
akode-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
303
akode-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
@@ -0,0 +1,303 @@
|
||||
//! Verify parse reuse, revision invalidation, and diagnostic preservation.
|
||||
|
||||
use super::super::parse_legacy_plugin_manifest_uri;
|
||||
use super::super::parse_resolved_plugin_manifest;
|
||||
use super::ManifestCache;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use std::sync::Mutex;
|
||||
use tracing_test::internal::MockWriter;
|
||||
|
||||
#[test]
|
||||
fn repeated_revision_runs_parser_once_and_changes_run_it_again() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let first = r#"{"name":"demo","description":"first"}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed"}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
let mut results = Vec::new();
|
||||
for contents in std::iter::repeat_n(first, 220).chain([changed, first]) {
|
||||
results.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let original = results[0].clone();
|
||||
let mut revised = original.clone();
|
||||
revised.description = Some("changed".to_string());
|
||||
assert_eq!(
|
||||
results,
|
||||
std::iter::repeat_n(original.clone(), 220)
|
||||
.chain([revised, original])
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_fields_warn_once_until_the_manifest_changes() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join(".codex-plugin/plugin.json");
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let original =
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let cache = ManifestCache::default();
|
||||
let parse = |contents| {
|
||||
parse_resolved_plugin_manifest(
|
||||
&cache,
|
||||
directory.path(),
|
||||
&path,
|
||||
contents,
|
||||
/*overlay*/ None,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let first = parse(original);
|
||||
for _ in 0..220 {
|
||||
assert_eq!(parse(original), first);
|
||||
}
|
||||
let mut expected = first.clone();
|
||||
expected.description = Some("changed".to_string());
|
||||
assert_eq!(parse(changed), expected);
|
||||
assert_eq!(parse(original), first);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(logs.matches("ignoring interface.defaultPrompt").count(), 3);
|
||||
assert_eq!(logs.matches("ignoring interface.composerIcon").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_revision_and_resource_root_are_part_of_cached_parse() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let other_root = root.join("other").unwrap();
|
||||
let path = root.join("plugin.json").unwrap();
|
||||
let overlay_path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = serde_json::json!({
|
||||
"$schema": akode_utils_plugins::AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "demo"
|
||||
})
|
||||
.to_string();
|
||||
let first = r#"{"interface":{"defaultPrompt":"first"}}"#;
|
||||
let changed = r#"{"interface":{"defaultPrompt":"changed"}}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for (plugin_root, overlay) in [
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, changed))),
|
||||
(&root, None),
|
||||
(&other_root, None),
|
||||
] {
|
||||
let manifest = cache
|
||||
.parse(plugin_root, &path, &contents, overlay, || {
|
||||
parses.set(parses.get() + 1);
|
||||
super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let expected = super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(manifest, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_revision_is_retried_and_repair_is_visible() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let cache = ManifestCache::default();
|
||||
for contents in ["{", "{"] {
|
||||
assert!(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let repaired = r#"{"name":"repaired"}"#;
|
||||
assert_eq!(
|
||||
cache
|
||||
.parse(&root, &path, repaired, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired)
|
||||
})
|
||||
.unwrap(),
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_windows_paths_share_a_cached_revision() {
|
||||
let cache = ManifestCache::default();
|
||||
let parses = Cell::new(0);
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let mut manifests = Vec::new();
|
||||
for value in ["file:///C:/plugins/Demo", "file:///C:/plugins/demo"] {
|
||||
let root = PathUri::parse(value).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
manifests.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert_eq!(manifests[0], manifests[1]);
|
||||
assert_eq!(parses.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_revision_invalidates_previous_result_without_being_cached() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let small = r#"{"name":"demo"}"#;
|
||||
let large = format!("{}{small}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for contents in [small, small, &large, &large, small] {
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_parse_does_not_block_unrelated_manifest() {
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let large_path = root.join("large.json").unwrap();
|
||||
let small_path = root.join("small.json").unwrap();
|
||||
let large = format!("{}{{}}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
let (completed_tx, completed_rx) = mpsc::channel();
|
||||
let root = &root;
|
||||
let large_path = &large_path;
|
||||
let small_path = &small_path;
|
||||
let large = &large;
|
||||
let cache = &ManifestCache::default();
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, large_path, large, /*overlay*/ None, || {
|
||||
started_tx.send(()).unwrap();
|
||||
release_rx.recv().unwrap();
|
||||
parse_legacy_plugin_manifest_uri(root, large_path, large)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
started_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, small_path, "{}", /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(root, small_path, "{}")
|
||||
})
|
||||
.unwrap();
|
||||
completed_tx.send(()).unwrap();
|
||||
});
|
||||
let completed = completed_rx.recv_timeout(Duration::from_secs(10));
|
||||
release_tx.send(()).unwrap();
|
||||
assert_eq!(completed, Ok(()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_clones_reuse_validation_but_independent_stores_warn_again() {
|
||||
use crate::store::PluginStore;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("plugin");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin")).unwrap();
|
||||
std::fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" "}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let store = PluginStore::new(directory.path().to_path_buf());
|
||||
let cloned_store = store.clone();
|
||||
let first = store.manifest_cache.load(&root).unwrap().manifest;
|
||||
for _ in 0..220 {
|
||||
assert_eq!(
|
||||
cloned_store.manifest_cache.load(&root).unwrap().manifest,
|
||||
first
|
||||
);
|
||||
}
|
||||
let independent_store = PluginStore::new(directory.path().to_path_buf());
|
||||
assert_eq!(
|
||||
independent_store
|
||||
.manifest_cache
|
||||
.load(&root)
|
||||
.unwrap()
|
||||
.manifest,
|
||||
first
|
||||
);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(
|
||||
logs.matches("ignoring interface.defaultPrompt: prompt must not be empty")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_cache_parses_each_load() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let expected = parse_legacy_plugin_manifest_uri(&root, &path, contents).unwrap();
|
||||
let cache = ManifestCache::disabled();
|
||||
let parses = Cell::new(0);
|
||||
for _ in 0..3 {
|
||||
let result = cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
Reference in New Issue
Block a user