use std::error::Error;
use std::num::NonZeroUsize;
use crate::port::{FakeAdapter, FakeBinary, FakeFileTree, FakeGit, FakeWorkspace};
use std::path::Path;
use crate::app::plan::load::{Loaded, load_set};
use crate::app::plan::read::read_inputs;
use crate::app::plan::sources::{Tree, fetch_sources};
use crate::port::ScriptStep;
use crate::types::lock::{
FileEntry, LockContents, LockedEntry, LockedSource, Lockfile, Owner, write_lock,
};
use crate::types::manifest::PackVersion;
use crate::types::name::{ItemName, PackName, ToolName};
use crate::types::op::OpPath;
use crate::types::op::{
ItemId, LuaType, Operation, Origin, Proposal, SkipReason, ValuesInput, ValuesResult,
};
use crate::types::pack::Pack;
use crate::types::project::{CommitId, GitTag, GitUrl, LocalPath, SubPath};
use crate::types::report::Diagnostics;
use crate::types::set::ValidSet;
use crate::types::tree::TreePath;
use crate::types::tree::{ContentHash, tree_hash};
pub(super) type TestResult = Result<(), Box<dyn Error>>;
pub(super) const REV_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
pub(super) const REV_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
pub(super) const URL: &str = "https://example.com/org/packs";
pub(super) fn shown(found: Diagnostics) -> Vec<String> {
found
.into_sorted()
.iter()
.map(ToString::to_string)
.collect()
}
pub(super) fn tool(name: &str) -> Result<ToolName, Box<dyn Error>> {
Ok(ToolName::new(name)?)
}
pub(super) fn pack(name: &str) -> Result<PackName, Box<dyn Error>> {
Ok(PackName::new(name)?)
}
pub(super) fn item(name: &str) -> Result<ItemName, Box<dyn Error>> {
Ok(ItemName::new(name)?)
}
pub(super) fn op(text: &str) -> Result<OpPath, Box<dyn Error>> {
Ok(OpPath::new(text)?)
}
pub(super) fn rev(text: &str) -> Result<CommitId, Box<dyn Error>> {
Ok(CommitId::new(text)?)
}
pub(super) fn url() -> Result<GitUrl, Box<dyn Error>> {
Ok(GitUrl::new(URL)?)
}
pub(super) fn git_tag(text: &str) -> Result<GitTag, Box<dyn Error>> {
Ok(GitTag::new(text)?)
}
pub(super) fn local(text: &str) -> Result<LocalPath, Box<dyn Error>> {
Ok(LocalPath::new(text)?)
}
pub(super) fn sub(text: &str) -> Result<SubPath, Box<dyn Error>> {
Ok(SubPath::new(text)?)
}
pub(super) fn files(root: &str, files: &[(&str, &str)]) -> FakeFileTree {
files
.iter()
.fold(FakeFileTree::new(root), |tree, (rel, text)| {
tree.file(rel, text.as_bytes())
})
}
pub(super) fn pack_files(root: &str, name: &str) -> FakeFileTree {
FakeFileTree::new(root)
.file(
"pack.toml",
format!(
"[pack]\nname = \"{name}\"\nversion = \"0.1.0\"\napi = 1\ndescription = \"d\"\n"
)
.as_bytes(),
)
.file("skills/status/SKILL.md", SKILL_MD.as_bytes())
}
pub(super) const SKILL_MD: &str = "---\nname: status\ndescription: d\n---\nBody\n";
pub(super) fn ext_files_reading(root: &str, tool: &str, reads: &[&str]) -> FakeFileTree {
let reads = if reads.is_empty() {
String::new()
} else {
let quoted: Vec<String> = reads.iter().map(|read| format!("\"{read}\"")).collect();
format!("reads = [{}]\n", quoted.join(", "))
};
FakeFileTree::new(root)
.file(
"extension.toml",
format!(
"[extension]\nname = \"{tool}\"\nversion = \"0.1.0\"\napi = 1\ndescription = \"d\"\nentry = \"adapter.lua\"\n{reads}"
)
.as_bytes(),
)
.file("adapter.lua", b"")
}
pub(super) fn ext_files(root: &str, tool: &str) -> FakeFileTree {
ext_files_reading(root, tool, &[])
}
pub(super) fn hash_of(tree: &FakeFileTree) -> Result<ContentHash, Box<dyn Error>> {
tree_hash(tree).map_err(|found| shown(found).join("; ").into())
}
pub(super) fn git_locked(
rev_text: &str,
tag: Option<&str>,
subdir: Option<&str>,
) -> Result<LockedSource, Box<dyn Error>> {
Ok(LockedSource::Git {
url: url()?,
tag: tag.map(git_tag).transpose()?,
subdir: subdir.map(sub).transpose()?,
rev: rev(rev_text)?,
})
}
pub(super) fn path_locked(dir: &str) -> Result<LockedSource, Box<dyn Error>> {
Ok(LockedSource::Path(local(dir)?))
}
pub(super) fn locked_pack(
name: &str,
source: LockedSource,
tree: ContentHash,
) -> Result<LockedEntry<PackName>, Box<dyn Error>> {
Ok(LockedEntry::new(
pack(name)?,
PackVersion::new("0.1.0")?,
source,
tree,
))
}
pub(super) fn locked_tool(
name: &str,
source: LockedSource,
tree: ContentHash,
) -> Result<LockedEntry<ToolName>, Box<dyn Error>> {
Ok(LockedEntry::new(
tool(name)?,
PackVersion::new("0.1.0")?,
source,
tree,
))
}
pub(super) fn locked_file(
path: &str,
bytes: &[u8],
owner: &str,
) -> Result<FileEntry, Box<dyn Error>> {
Ok(FileEntry::new(
sub(path)?,
ContentHash::of_bytes(bytes),
Owner::new(owner)?,
))
}
pub(super) fn lock_text(contents: LockContents) -> Result<String, Box<dyn Error>> {
let lock = Lockfile::new(Path::new("agentstacks.lock"), contents)
.map_err(|found| shown(found).join("; "))?;
Ok(write_lock(&lock))
}
pub(super) const PROJECT: &str = "api = 1\n\n[tools.claude]\npath = \"extensions/claude\"\n\n[packs.core]\npath = \"packs/core\"\n";
pub(super) type LoadedTrees = Loaded<Tree<FakeFileTree, FakeFileTree>>;
pub(super) fn loaded(scenario: &Scenario) -> Result<LoadedTrees, Diagnostics> {
let inputs = read_inputs(&scenario.workspace)?;
load_set(
&inputs,
fetch_sources(&inputs, &scenario.workspace, &scenario.git),
)
}
pub(super) fn single(project: &str, pack_tree: FakeFileTree) -> Result<Scenario, Box<dyn Error>> {
Scenario::new(project)
.path_source("packs/core", pack_tree)?
.path_source(
"extensions/claude",
ext_files("extensions/claude", "claude"),
)
}
pub(super) fn values_for(
set: &ValidSet,
tool_name: &str,
json: &str,
) -> Result<ValuesResult, Box<dyn Error>> {
let packs: Vec<&Pack> = set.packs().values().collect();
values_over(&packs, tool_name, json)
}
pub(super) fn values_over(
packs: &[&Pack],
tool_name: &str,
json: &str,
) -> Result<ValuesResult, Box<dyn Error>> {
let input = ValuesInput::new(tool(tool_name)?, packs);
let value: serde_json::Value = serde_json::from_str(json)?;
let object = value.as_object().ok_or("the answer is an object")?;
let entry = format!("{tool_name}/adapter.lua");
ValuesResult::read(object, &input, Path::new(&entry), |_| LuaType::Table)
.map_err(|found| shown(found).join("; ").into())
}
pub(super) fn origin(tool_name: &str, line: usize) -> Result<Origin, Box<dyn Error>> {
Ok(Origin::Extension {
tool: tool(tool_name)?,
file: TreePath::from_parts(&["adapter.lua"]),
line: NonZeroUsize::new(line).ok_or("a line starts at 1")?,
})
}
fn propose(
tool_name: &str,
line: usize,
operation: Operation,
) -> Result<ScriptStep, Box<dyn Error>> {
Ok(ScriptStep::Propose(Proposal {
op: operation,
origin: origin(tool_name, line)?,
}))
}
pub(super) fn write_step(
tool_name: &str,
line: usize,
path: &str,
content: &[u8],
covers: Vec<ItemId>,
) -> Result<ScriptStep, Box<dyn Error>> {
propose(
tool_name,
line,
Operation::Write {
path: op(path)?,
content: content.to_vec(),
covers,
},
)
}
pub(super) fn copy_step(
tool_name: &str,
line: usize,
path: &str,
file: ItemId,
) -> Result<ScriptStep, Box<dyn Error>> {
propose(
tool_name,
line,
Operation::Copy {
path: op(path)?,
file,
},
)
}
pub(super) fn skip_step(
tool_name: &str,
line: usize,
item: ItemId,
reason: &str,
) -> Result<ScriptStep, Box<dyn Error>> {
propose(
tool_name,
line,
Operation::Skip {
item,
reason: SkipReason::new(reason)?,
},
)
}
pub(super) fn read_step(path: &str) -> Result<ScriptStep, Box<dyn Error>> {
Ok(ScriptStep::Read(op(path)?))
}
pub(super) fn skill_file_id(
pack_name: &str,
skill_name: &str,
rel: &str,
) -> Result<ItemId, Box<dyn Error>> {
Ok(ItemId::skill_file(
&pack(pack_name)?,
&item(skill_name)?,
&TreePath::from_parts(&[rel]),
))
}
pub(super) fn hook_id(pack_name: &str, index: usize) -> Result<ItemId, Box<dyn Error>> {
Ok(ItemId::hook(&pack(pack_name)?, index))
}
#[derive(Default)]
pub(super) struct Scenario {
pub(super) workspace: FakeWorkspace,
pub(super) git: FakeGit,
pub(super) binary: FakeBinary,
pub(super) adapter: FakeAdapter,
}
impl Scenario {
pub(super) fn new(project: &str) -> Self {
Self {
workspace: FakeWorkspace::new().project(project),
..Self::default()
}
}
pub(super) fn workspace(mut self, edit: impl FnOnce(FakeWorkspace) -> FakeWorkspace) -> Self {
self.workspace = edit(std::mem::take(&mut self.workspace));
self
}
pub(super) fn git(mut self, edit: impl FnOnce(FakeGit) -> FakeGit) -> Self {
self.git = edit(std::mem::take(&mut self.git));
self
}
pub(super) fn binary(mut self, edit: impl FnOnce(FakeBinary) -> FakeBinary) -> Self {
self.binary = edit(std::mem::take(&mut self.binary));
self
}
pub(super) fn adapter(mut self, edit: impl FnOnce(FakeAdapter) -> FakeAdapter) -> Self {
self.adapter = edit(std::mem::take(&mut self.adapter));
self
}
pub(super) fn lock(self, text: &str) -> Self {
self.workspace(|workspace| workspace.lock(text))
}
pub(super) fn path_source(self, dir: &str, tree: FakeFileTree) -> Result<Self, Box<dyn Error>> {
let dir = local(dir)?;
Ok(self.workspace(|workspace| workspace.source(&dir, tree)))
}
}