use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use trusty_common::content::{ContentLock, DEV_CLASS_SOURCES, LOCK_FILE_NAME};
use trusty_common::integrity::Sha256Digest;
use super::*;
pub(crate) fn repo_root() -> PathBuf {
trusty_common::test_harness::test_repo_root().expect("resolve the checkout")
}
pub(crate) fn repo_content() -> ResolvedContent {
checkout_content(&repo_root()).expect("repo content")
}
fn roster() -> &'static AgentRoster {
static ROSTER: OnceLock<AgentRoster> = OnceLock::new();
ROSTER.get_or_init(|| AgentRoster::load(&repo_content()).expect("repo roster"))
}
fn asset(name: &str) -> &'static str {
roster().require(name).unwrap_or_else(|e| panic!("{e}"))
}
pub(crate) fn fake_checkout(root: &Path) {
for (_, rel) in DEV_CLASS_SOURCES {
std::fs::create_dir_all(root.join(rel)).expect("class dir");
}
std::fs::create_dir_all(root.join(".git")).expect(".git");
std::fs::write(root.join("Cargo.toml"), "[workspace]\nmembers = []\n").expect("Cargo.toml");
}
#[test]
fn not_installed_names_tm_content_install() {
let cache = tempfile::tempdir().expect("tempdir");
let err = resolve_content_in(cache.path(), DevOverride::Off).expect_err("nothing installed");
assert!(
matches!(err, AgentContentError::NotInstalled { .. }),
"got {err:?}"
);
let fetch_failed = AgentContentError::FetchFailed {
reason: "could not reach api.github.com".to_string(),
};
assert!(fetch_failed.is_not_installed());
for err in [err, AgentContentError::NoCacheDir, fetch_failed] {
let msg = err.to_string();
assert!(msg.contains("tm content install"), "{msg}");
assert!(msg.contains("run `tm content update`"), "{msg}");
for needle in [
"gh release download <tag> --repo bobmatnyc/trusty-tools",
"tm content install --from <dir>/<tag>.tar.gz",
] {
assert!(msg.contains(needle), "{needle} missing: {msg}");
}
}
}
#[test]
fn an_invalid_file_names_both_remedies() {
let err = AgentContentError::Invalid {
origin: "content-v0.2.0".to_string(),
path: "instructions/pm-instruction-package.json".to_string(),
reason: "unknown variant `newer-section`".to_string(),
};
let shown = err.to_string();
for needle in [
"instructions/pm-instruction-package.json",
"unknown variant `newer-section`",
"tm content update",
"upgrade tm",
] {
assert!(shown.contains(needle), "{needle} missing: {shown}");
}
assert!(!err.is_not_installed());
}
#[test]
fn an_unverifiable_bundle_is_a_content_error() {
let cache = tempfile::tempdir().expect("tempdir");
let lock = ContentLock::new("content-v0.1.0", Sha256Digest::of_bytes(b"pinned")).expect("lock");
std::fs::write(cache.path().join(lock.bundle_file_name()), b"tampered").expect("bundle");
lock.store(&cache.path().join(LOCK_FILE_NAME))
.expect("store");
let err = resolve_content_in(cache.path(), DevOverride::Off).expect_err("checksum mismatch");
assert!(
matches!(
err,
AgentContentError::Content {
source: ContentError::ChecksumMismatch { .. }
}
),
"got {err:?}"
);
}
#[test]
fn only_a_not_installed_error_is_claimed() {
let cache = tempfile::tempdir().expect("tempdir");
let missing = resolve_content_in(cache.path(), DevOverride::Off).expect_err("nothing");
assert!(missing.is_not_installed());
assert!(AgentContentError::NoCacheDir.is_not_installed());
assert!(report_not_installed(&missing, "test"));
assert!(report_not_installed(&missing, "test"));
let empty = AgentContentError::EmptyRoster {
origin: "test".to_string(),
};
assert!(!empty.is_not_installed());
assert!(!report_not_installed(&empty, "test"));
}
#[test]
fn an_empty_roster_is_an_error() {
let root = tempfile::tempdir().expect("tempdir");
fake_checkout(root.path());
let content = checkout_content(root.path()).expect("fake checkout resolves");
let err = AgentRoster::load(&content).expect_err("no agents");
assert!(
matches!(err, AgentContentError::EmptyRoster { .. }),
"got {err:?}"
);
assert!(err.to_string().contains("git pull"), "{err}");
}
#[test]
fn a_stale_checkout_names_git_pull_not_tm_content_update() {
let root = tempfile::tempdir().expect("tempdir");
fake_checkout(root.path());
std::fs::write(root.path().join("content/agents/engineer.md"), "e\n").expect("agent");
let content = checkout_content(root.path()).expect("fake checkout resolves");
let missing = AgentRoster::load(&content).expect_err("no foundation file");
let origin = describe_source(content.source());
let invalid = AgentContentError::Invalid {
origin: origin.clone(),
path: "instructions/pm-instruction-package.json".to_string(),
reason: "unknown variant".to_string(),
};
let root_shown = root.path().display().to_string();
for err in [missing, invalid] {
let msg = err.to_string();
assert!(msg.contains(&root_shown), "checkout root missing: {msg}");
assert!(msg.contains("git pull"), "git pull missing: {msg}");
assert!(msg.contains("outside"), "run-outside missing: {msg}");
assert!(!msg.contains("tm content update"), "false remedy: {msg}");
}
let installed = AgentContentError::Missing {
origin: "content-v0.2.0".to_string(),
path: "agents/BASE-AGENT.md".to_string(),
};
assert!(installed.to_string().contains("run `tm content update`"));
}
#[test]
fn a_roster_without_the_foundation_file_is_an_error() {
let root = tempfile::tempdir().expect("tempdir");
fake_checkout(root.path());
std::fs::write(
root.path().join("content/agents/engineer.md"),
"---\nname: e\n---\n",
)
.expect("agent");
let content = checkout_content(root.path()).expect("fake checkout resolves");
let err = AgentRoster::load(&content).expect_err("no foundation file");
match err {
AgentContentError::Missing { path, .. } => assert_eq!(path, "agents/BASE-AGENT.md"),
other => panic!("expected Missing, got {other:?}"),
}
}
#[test]
fn require_names_the_missing_file() {
let err = roster().require("no-such-agent.md").expect_err("absent");
assert!(err.to_string().contains("agents/no-such-agent.md"), "{err}");
}
#[test]
fn the_repository_roster_carries_every_agent() {
let dir = repo_root().join("content/agents");
let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
.expect("content/agents")
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".md"))
.collect();
on_disk.sort();
let mut loaded: Vec<String> = roster().iter().map(|(n, _)| n.to_string()).collect();
assert_eq!(loaded.len(), 43, "the roster must carry all 43 agent files");
let bases = loaded.iter().take_while(|n| n.starts_with("BASE-")).count();
assert_eq!(bases, 5, "the five BASE-* templates must come first");
loaded.sort();
assert_eq!(on_disk, loaded);
for (name, body) in roster().iter() {
assert!(!body.trim().is_empty(), "`{name}` is empty");
let file = std::fs::read_to_string(dir.join(name)).expect("read");
assert_eq!(file, body, "`{name}` does not hold the file it names");
}
}
#[test]
fn materialize_writes_every_roster_file() {
let out = tempfile::tempdir().expect("tempdir");
let dir = out.path().join("agents");
let written = roster().materialize(&dir).expect("materialize");
assert_eq!(written.len(), roster().len());
for (name, body) in roster().iter() {
assert_eq!(std::fs::read_to_string(dir.join(name)).expect("read"), body);
}
}
#[test]
fn credential_switching_is_forbidden_in_the_shipped_assets() {
for (name, body) in [
("BASE-AGENT.md", asset("BASE-AGENT.md")),
("version-control.md", asset("version-control.md")),
] {
let flat = body.replace('\n', " ");
assert!(
flat.contains("Never switch") && flat.contains("credential"),
"`{name}` must forbid switching to another `gh` \
account/token/credential to obtain a missing permission (#5680)"
);
}
assert!(
asset("version-control.md")
.contains("When the PM relays operator authorization to merge directly"),
"the credential-switching ban must leave the PM-relayed \
admin-merge authorization intact (#2842)"
);
}
#[test]
fn credential_rule_points_at_the_per_repo_identity_route() {
let flat = asset("BASE-AGENT.md").replace('\n', " ");
let rule_start = flat.find("One credential rule").expect("credential rule");
let rule = &flat[rule_start..];
let rule = &rule[..rule.find("**A PM `SendMessage`").unwrap_or(rule.len())];
assert!(
rule.contains("docs/reference/environment-variables.md#per-repo-gh-identity"),
"BASE-AGENT's credential rule must point at the per-repo gh identity \
route in environment-variables.md (#8557)"
);
}
#[test]
fn ops_agents_state_the_non_printing_credential_forms() {
let local = asset("local-ops.md").replace('\n', " ");
assert!(
local.contains("find-generic-password -s <service> >/dev/null 2>&1")
&& local.contains("Never add `-w` or `-g`")
&& local.contains("#8596"),
"`local-ops.md` must state the exit-status-only Keychain check (#8596)"
);
assert!(
local.contains("--password-stdin") && !local.contains("=$(security"),
"`local-ops.md` must consume a Keychain value inline, not via `FOO=$(…)`"
);
let gcp = asset("gcp-ops.md").replace('\n', " ");
assert!(
gcp.contains("Never run `gcloud auth [application-default] print-access-token`")
&& gcp.contains("Bearer $(gcloud auth print-access-token)")
&& gcp.contains("#8248"),
"`gcp-ops.md` must forbid a bare `print-access-token` run (#8248)"
);
}
#[test]
fn vercel_env_listing_prints_names_only() {
let skill = std::fs::read_to_string(repo_root().join("content/skills/tm-secrets.md"))
.expect("tm-secrets skill");
let bodies = [
("local-ops.md", asset("local-ops.md")),
("vercel-ops.md", asset("vercel-ops.md")),
("tm-secrets.md", skill.as_str()),
];
let needles = [
"vercel env ls <env> | awk 'NR>1{print $1}'",
"never `--json`",
"never the unfiltered table",
"#9158",
];
for (name, raw) in bodies {
let body = raw
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
for needle in needles {
assert!(
body.contains(&needle.to_lowercase()),
"`{name}` must require a names-only Vercel env listing (#9158): \
missing {needle:?}"
);
}
}
}
#[test]
fn ticketing_and_version_control_are_not_haiku() {
for (name, body) in [
("ticketing.md", asset("ticketing.md")),
("version-control.md", asset("version-control.md")),
] {
let frontmatter = body
.strip_prefix("---\n")
.and_then(|rest| rest.split_once("\n---"))
.map(|(fm, _)| fm)
.unwrap_or_else(|| panic!("`{name}` must open with YAML frontmatter"));
assert!(
!frontmatter.lines().any(|l| l.trim() == "model: haiku"),
"`{name}` frontmatter must not declare `model: haiku` (#7274); \
got:\n{frontmatter}"
);
assert!(
frontmatter.lines().any(|l| l.trim() == "model: sonnet"),
"`{name}` frontmatter must declare `model: sonnet` (#7274); \
got:\n{frontmatter}"
);
}
}
#[test]
fn worktree_removal_is_the_pms_in_the_shipped_base_agent() {
let flat = asset("BASE-AGENT.md").replace('\n', " ");
assert!(
flat.contains("Never remove a worktree") && flat.contains("#5791"),
"`BASE-AGENT.md` must forbid an agent removing a worktree (#5791)"
);
assert!(
flat.contains("the PM removes the task-owned path")
&& flat.contains("git worktree remove /absolute/repo/.claude/worktrees/task-name")
&& flat.contains("ownership, clean state, merged status and no other live"),
"`BASE-AGENT.md` must name the PM's replacement command, not just \
refuse (#5791)"
);
}
#[test]
fn self_analysis_reporting_ships_in_the_base_agent() {
let flat = asset("BASE-AGENT.md").replace('\n', " ");
for (fact, needle) in [
(
"the resident section exists",
"## Self-Improvement Reporting",
),
(
"the trigger names the point in the run",
"before your final report",
),
(
"the skill file is named",
"{{TM_SKILLS}}/self-improvement-loop/SKILL.md",
),
(
"the memory tag survives as a resident fact",
"`self-improvement-hypothesis`",
),
("a subagent never files directly", "No Subagent Fan-Out"),
] {
assert!(
flat.contains(needle),
"`BASE-AGENT.md` must state that {fact} (#6935, #6937, #7723)"
);
}
assert!(
!flat.contains("Skill(skill=\"self-improvement-loop\")"),
"BASE-AGENT must name `self-improvement-loop` in prose, not a \
modelled `Skill(...)` call — most agents' `tools:` omit `Skill` \
(#7683, #7723)"
);
}
#[test]
fn wait_exit_codes_and_improvement_block_headings_are_resident() {
let flat = asset("BASE-AGENT.md").replace('\n', " ");
for (fact, needle) in [
("exit 0 (met) is documented", "`0`"),
("exit 75 (pending) is documented", "`75`"),
("exit 1 (timeout) is documented", "`1`"),
("exit 2 (error) is documented", "`2`"),
("the command to re-issue on exit 75 is named", "`rerun=`"),
(
"the Improvement recommendations heading is named",
"Improvement recommendations",
),
("its Symptom field is named", "Symptom"),
("its Cause field is named", "Cause"),
("its Evidence field is named", "Evidence"),
("the Prompt feedback heading is named", "Prompt feedback"),
(
"the fast-loop memory tag is named",
"self-improvement-hypothesis",
),
] {
assert!(
flat.contains(needle),
"`BASE-AGENT.md` must state that {fact} (#7723 fix round)"
);
}
assert!(
flat.to_lowercase().contains("verbatim"),
"`BASE-AGENT.md` must require the `rerun=` command to be re-issued \
verbatim (#7723 fix round)"
);
}
#[test]
fn engineer_assets_name_no_repo_specific_doc_gate_script() {
const REPO_SPECIFIC_GATES: [&str; 3] = [
"check_test_pointers.sh",
"check_line_cap.sh",
"check_changelog_fragment.sh",
];
for (name, body) in [
("BASE-AGENT.md", asset("BASE-AGENT.md")),
("BASE-ENGINEER.md", asset("BASE-ENGINEER.md")),
("rust-engineer.md", asset("rust-engineer.md")),
] {
for gate in REPO_SPECIFIC_GATES {
assert!(
!body.contains(gate),
"`{name}` names `{gate}`, a script that exists in \
trusty-tools and not in every project (#7247) — tell the \
agent to read the project's own CLAUDE.md and `scripts/` \
instead of naming a filename"
);
}
}
}
#[test]
fn general_purpose_assets_state_no_repo_specific_literal() {
const REPO_SPECIFIC_LITERALS: [&str; 12] = [
"trusty-common",
"test_trusty_common_lanes.sh",
"check_sld.sh",
"check_line_cap.sh",
"check_test_pointers.sh",
"check_changelog_fragment.sh",
"check-pr-version-bump.sh",
"required-checks.sh",
"is-branch-caused.sh",
"memory-core",
"bobmatnyc/trusty-tools",
"crates/",
];
const FRAMEWORK_SCOPED: [&str; 4] = [
"mpm-agent-manager.md",
"mpm-skills-manager.md",
"ticketing.md",
"version-control.md",
];
for (name, body) in roster().iter() {
if FRAMEWORK_SCOPED.contains(&name) {
continue;
}
for literal in REPO_SPECIFIC_LITERALS {
if name == "BASE-AGENT.md" && literal == "bobmatnyc/trusty-tools" {
continue;
}
assert!(
!body.contains(literal),
"`{name}` states `{literal}`, which exists in trusty-tools \
and not in every project (#7270) — these assets deploy \
unchanged everywhere, so point the agent at the project's \
own CLAUDE.md and `scripts/` instead of naming a literal"
);
}
}
}
#[test]
fn base_templates_travel_with_the_roster() {
for base in [
"BASE-AGENT.md",
"BASE-ENGINEER.md",
"BASE-OPS.md",
"BASE-QA.md",
"BASE-RESEARCH.md",
] {
assert!(
roster().get(base).is_some(),
"`{base}` must ship alongside the agents that extend it"
);
}
}
#[test]
fn regression_proof_reverts_against_the_pre_fix_commit() {
assert!(
asset("BASE-ENGINEER.md").contains("git merge-base origin/main HEAD"),
"BASE-ENGINEER must name the pre-fix commit the revert targets (#7705)"
);
assert!(
asset("BASE-ENGINEER.md").contains("never to a bare"),
"BASE-ENGINEER must forbid reverting to a bare `origin/main` (#7705)"
);
assert!(
!asset("BASE-ENGINEER.md").contains("`git checkout origin/main -- <paths>`"),
"the moving-ref revert recipe must be gone, not merely warned about (#7705)"
);
assert!(
asset("BASE-ENGINEER.md").contains("`./scripts/<name>.sh`"),
"BASE-ENGINEER must state the executable gate-script spelling (#7705)"
);
}