Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix: Git output decoding, PowerShell hook conditions and shared verifier redaction (#260 follow-ups) (#312)
Narendran Raghavanb6e5d496c7bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 262a8553..3550652c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -195,6 +195,9 @@ All notable changes to SkillEvaluator are documented in this file.### Fixed+- On Windows, repository root and source-link detection no longer break for+ repositories in non-ASCII folders: Git output is decoded as UTF-8 instead of+ the locale code page.- CI quality thresholds apply to every parallel scan worker. Report overviewsand detailed reports surface failed quality gates ahead of advisory findings,with links to the check that needs attention.diff --git a/scripts/ci/smoke_harbor_verifier.py b/scripts/ci/smoke_harbor_verifier.pyindex 31712317..c44deb74 100644--- a/scripts/ci/smoke_harbor_verifier.py+++ b/scripts/ci/smoke_harbor_verifier.py@@ -34,6 +34,7 @@ def check_staged(directory: Path) -> None:assert Path(sys.modules[name].__file__).resolve() == directory / (name + ".py")assert verifier["_shell_tokens"] is sys.modules["shell_lexing"]._shell_tokensassert verifier["check_error_recovery"] is shared_checks.check_error_recovery+ assert verifier["redact_secrets_in_log_line"] is sys.modules["secret_redaction"].redact_secrets_in_log_lineassert verifier["_shell_tokens"]("cat 2>/dev/null") == ["cat", "2>", "/dev/null"]for command, expected in [("python scripts/calc.py", True),diff --git a/src/skillevaluator/plugin_component_risk.py b/src/skillevaluator/plugin_component_risk.pyindex 1cee3010..cd28c5ff 100644--- a/src/skillevaluator/plugin_component_risk.py+++ b/src/skillevaluator/plugin_component_risk.py@@ -612,6 +612,21 @@ def _bash_grant_label(entry: str) -> str:return f"unrestricted {entry!r}"+# A scoped grant to show in a remediation, per shell tool.+_SCOPED_SHELL_EXAMPLES = {"Bash": "Bash(git status *)", "PowerShell": "PowerShell(Get-ChildItem *)"}+++def _shell_tool(tool: str) -> str:+ """The Claude Code shell tool a shell-tool name stands for: ``PowerShell`` for any spelling of it, else ``Bash``."""+ return "PowerShell" if tool.lower() == "powershell" else "Bash"+++def _grant_shell_tool(entry: str) -> str:+ """The shell tool a flagged shell grant names (``PowerShell`` for ``PowerShell(iex *)``)."""+ match = _TOOL_RULE_RE.fullmatch(entry)+ return _shell_tool(match.group(1)) if match is not None else "Bash"++def is_wildcard_tool(entry: str) -> bool:"""A wildcard grant of every tool (``*``) or every MCP tool (``mcp__*``)."""return "".join(entry.split()).lower() in _WILDCARD_TOOLS@@ -622,8 +637,9 @@ def _is_star_grant(entry: str) -> bool:return "".join(entry.split()) in {"*", "*(*)"}-def denies_every_bash_command(entries: Iterable[str] | None) -> bool:- """Whether a ``disallowedTools`` list removes the Bash tool, the way Claude Code matches it.+def denies_every_bash_command(entries: Iterable[str] | None, tool: str = "Bash") -> bool:+ """Whether a ``disallowedTools`` list removes the shell tool ``tool`` (``Bash`` or ``PowerShell``), the way+ Claude Code matches it.Tool names are case-sensitive (``bash`` denies nothing), and a rule whosecontent matches every command (``Bash(*)``, ``Bash()``) denies the whole tool.@@ -631,7 +647,7 @@ def denies_every_bash_command(entries: Iterable[str] | None) -> bool:"""for entry in entries or []:match = _TOOL_RULE_RE.fullmatch(entry)- if match is None or match.group(1) != "Bash":+ if match is None or match.group(1) != tool:continuecontent = match.group(2)if content is None or not content.strip(" \t\n\r*"):@@ -849,13 +865,22 @@ def analyze_agent(record.permission_mode = _string_field(frontmatter, "permissionMode", "permission-mode")record.inherits_all_tools = tools is None# Claude Code matches tool names case-sensitively: 'bash' denies nothing, and 'Bash(*)' denies all of Bash.- denies_bash = denies_every_bash_command(disallowed_tools)- bash = [entry for entry in tools if is_unrestricted_bash(entry)] if tools is not None else []- if (bash or tools is None) and not denies_bash:+ # Denying one shell tool leaves the other: 'disallowedTools: Bash' keeps a 'PowerShell' grant.+ bash = (+ [+ entry+ for entry in tools+ if is_unrestricted_bash(entry) and not denies_every_bash_command(disallowed_tools, _grant_shell_tool(entry))+ ]+ if tools is not None+ else []+ )+ if bash or (tools is None and not denies_every_bash_command(disallowed_tools)):# Advisory only: a subagent's tools list limits what it may call, it never pre-approves a tool,# so the session's permission prompts still apply. An agent that omits 'tools' inherits Bash too,# so both get the same severity.record.flags.append("unrestricted_bash")+ shell = _grant_shell_tool(bash[0]) if bash else "Bash"grant = (f"is granted {_bash_grant_label(bash[0])}"if bash@@ -869,7 +894,7 @@ def analyze_agent("prompts still apply)",file_path,"List the tools the subagent needs and scope the shell grant to exact commands (for example "- "Bash(git status *)), or deny Bash with disallowedTools.",+ f"{_SCOPED_SHELL_EXAMPLES[shell]}), or deny {shell} with disallowedTools.",component=component,))@@ -1013,10 +1038,11 @@ def _analyze_allowed_tools(for tool in allowed or []:if is_unrestricted_bash(tool):record.flags.append("unrestricted_bash")+ shell = _grant_shell_tool(tool)if claude_only:message = (f"{kind} '{name}' pre-approves {_bash_grant_label(tool)} in allowed-tools; {loader} ignores "- "allowed-tools (it has no Bash tool), but if Claude Code loads this "+ f"allowed-tools (it has no {shell} tool), but if Claude Code loads this "f"{kind} (claude --plugin-dir reads skills/ and commands/ from this folder), any shell command ""runs without a prompt while it is active")@@ -1031,9 +1057,14 @@ def _analyze_allowed_tools(f"plugin_{kind}_unrestricted_bash",message,file_path,- "Scope allowed-tools to the exact commands it needs, such as Bash(git status *).",+ f"Scope allowed-tools to the exact commands it needs, such as {_SCOPED_SHELL_EXAMPLES[shell]}.",component=component,- extra=claude_only_extra,+ # The inert-grant rewrite (a file Claude Code does not load either) names the same grant and tool.+ extra=(+ {**claude_only_extra, "shell_grant": _bash_grant_label(tool), "shell_tool": shell}+ if claude_only_extra+ else None+ ),))break@@ -1600,16 +1631,19 @@ def _condition_scope(condition: str, shell_tools: tuple[str, ...] = ("Bash",)) -"""The scope a handler's ``if`` condition allows, read as one permission rule (``Bash(git status)``).A shell rule that runs any command (``Bash``, ``Bash(*)``, an interpreter- prefix) is ``bash``; any other shell rule is ``narrow``. A write, fetch, or- MCP tool is ``scoped``; another tool is ``narrow``. ``None`` when the text is- not one rule, so the caller keeps the matcher's scope (fail closed).+ prefix, a PowerShell launcher such as ``PowerShell(iex *)``) is ``bash``; any+ other shell rule is ``narrow``. A write, fetch, or MCP tool is ``scoped``;+ another tool is ``narrow``. ``None`` when the text is not one rule, so the+ caller keeps the matcher's scope (fail closed)."""match = _TOOL_RULE_RE.fullmatch(condition)if match is None:return Nonetool, content = match.group(1), match.group(2)if tool in shell_tools:- rule = "Bash" if content is None else f"Bash({content})"+ # A PowerShell rule is read as one (its launchers run any command); other shell-tool names as Bash.+ shell = _shell_tool(tool)+ rule = shell if content is None else f"{shell}({content})"return ("bash", ()) if bash_rule_risk(rule) is not None else ("narrow", ())if tool in _SENSITIVE_TOOLS or tool.startswith("mcp__"):label = "mcp__server__tool" if tool.startswith("mcp__") else tooldiff --git a/src/skillevaluator/plugin_inventory.py b/src/skillevaluator/plugin_inventory.pyindex 54c03b85..4e18b3ed 100644--- a/src/skillevaluator/plugin_inventory.py+++ b/src/skillevaluator/plugin_inventory.py@@ -627,10 +627,15 @@ def _inert_grant_finding(finding: Finding) -> None:component = finding.metadata.get("plugin_component") or {}kind = str(component.get("type") or "component")name = str(component.get("name") or "")- grant = "a wildcard tool grant" if finding.check_name.endswith("_wildcard_tools") else "unrestricted 'Bash'"+ if finding.check_name.endswith("_wildcard_tools"):+ grant, shell = "a wildcard tool grant", "Bash"+ else:+ # The shell grant as the component analysis worded it ('PowerShell(iex *)' names PowerShell, not Bash).+ grant = str(finding.metadata.get("shell_grant") or "unrestricted 'Bash'")+ shell = str(finding.metadata.get("shell_tool") or "Bash")finding.message = (f"{kind} '{name}' pre-approves {grant} in allowed-tools, but the grant has no effect: Codex ignores "- f"allowed-tools (it has no Bash tool), and Claude Code does not load this {kind} from this folder"+ f"allowed-tools (it has no {shell} tool), and Claude Code does not load this {kind} from this folder")finding.severity = Severity.LOWfinding.suggestion = (diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex 4dfd91ca..5a519ec7 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -290,7 +290,6 @@ _EXECUTION_TOOL_HINTS = _shared_checks._EXECUTION_TOOL_HINTS_EXPORTED_MARK = _shared_checks._EXPORTED_MARK_FILE_READ_VERBS = _shared_checks._FILE_READ_VERBS_GLUED_AKIA_BODY = _shared_checks._GLUED_AKIA_BODY-_GLUED_KEY_BODY = _shared_checks._GLUED_KEY_BODY_GROUPING_TOKENS = _shared_checks._GROUPING_TOKENS_HEREDOC_DELIMITER_RE = _shared_checks._HEREDOC_DELIMITER_RE_HEREDOC_REDIRECTS = _shared_checks._HEREDOC_REDIRECTS@@ -574,46 +573,9 @@ DISPLAY_METRICS = []-LOG_SK_RE = re.compile(r"(?<![A-Za-z0-9_-])sk-[a-zA-Z0-9_-]{8,}|sk-" + _GLUED_KEY_BODY)-LOG_NVAPI_RE = re.compile(r"(?<![A-Za-z0-9_-])nvapi-[a-zA-Z0-9_-]{8,}|nvapi-" + _GLUED_KEY_BODY)-LOG_CRSR_RE = re.compile(r"(?<![A-Za-z0-9_-])crsr_[a-f0-9]{16,}")-OPENSHIFT_TOKEN_RE = re.compile(r"(?<![A-Za-z0-9_-])sha256~[A-Za-z0-9._~-]+")-LOG_YA29_RE = re.compile(r"(?<![A-Za-z0-9_-])ya29\.[A-Za-z0-9_-]{20,}")-# A JWT used to start at any ``\beyJ``, so in a run of JWT characters such as-# "eyJ-" * n every "-eyJ" was a start, and each start scanned to the end of the-# run looking for ".". Now a match starts only at the beginning of a run. The part-# of the run before its first ``\beyJ`` is captured as ``lead`` and written back-# unchanged, which keeps JWTs glued to a "-" (x-eyJ...) redacted. Later starts in-# the same run are never tried: their first segment reaches the same "." with-# fewer characters, so they could only fail where the first start failed. ``lead``-# stops at the first ``\beyJ`` and every earlier offset fails ``\beyJ``, so-# backtracking into it is cheap. No atomic groups or possessive quantifiers: the-# Harbor verifier copy runs on the task image's python3, which may predate 3.11.-LOG_JWT_RE = re.compile(- r"(?<![A-Za-z0-9_-])(?P<lead>(?:(?!\beyJ)[A-Za-z0-9_-])*)"- r"\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b"-)-# GitHub classic (ghp_/gho_/ghu_/ghs_/ghr_) and fine-grained (github_pat_) tokens.-# Single bounded character classes keep both patterns linear.-LOG_GITHUB_TOKEN_RE = re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,255}\b")-LOG_GITHUB_PAT_RE = re.compile(r"\bgithub_pat_[A-Za-z0-9_]{22,255}\b")---def redact_secrets_in_log_line(line, *, extra_secret_values=None):- """Best-effort mask common key shapes in Harbor verifier output text."""- for secret in sorted(set(extra_secret_values or ()), key=len, reverse=True):- if secret and len(secret) >= _MIN_EXACT_SECRET_LENGTH:- line = line.replace(secret, "<redacted>")- line = LOG_SK_RE.sub("sk-<redacted>", line)- line = LOG_NVAPI_RE.sub("nvapi-<redacted>", line)- line = LOG_CRSR_RE.sub("crsr_<redacted>", line)- line = LOG_GITHUB_TOKEN_RE.sub(lambda match: match.group()[:4] + "<redacted>", line)- line = LOG_GITHUB_PAT_RE.sub("github_pat_<redacted>", line)- line = OPENSHIFT_TOKEN_RE.sub("sha256~<redacted>", line)- line = LOG_YA29_RE.sub("ya29.<redacted>", line)- if "eyJ" not in line: # every JWT match contains "eyJ"; skip the scan on ordinary lines- return line- return LOG_JWT_RE.sub(r"\g<lead>jwt-<redacted>", line)+# checks.py imports this from secret_redaction.py, which _copy_verifier stages+# beside this file, so the verifier masks log text with the shared rules.+redact_secrets_in_log_line = _shared_checks.redact_secrets_in_log_line# ── ATIF Helpers ─────────────────────────────────────────────────────────────diff --git a/src/skillevaluator/utils/helpers.py b/src/skillevaluator/utils/helpers.pyindex 725ee51a..fd47ae98 100644--- a/src/skillevaluator/utils/helpers.py+++ b/src/skillevaluator/utils/helpers.py@@ -125,17 +125,33 @@ def find_bundled_plugin_skills(plugin_root: Path) -> list[Path]:]+def _git_output(args: list[str], cwd: Path, *, errors: str = "replace") -> str:+ """Run git in ``cwd`` and return its stripped stdout decoded as UTF-8.++ Git writes paths, refs and URLs as UTF-8 on every platform, so the locale+ code page (cp1252 on many Windows hosts) must not be used to decode them.+ ``errors`` is never ``"strict"``, so decoding cannot raise. The default+ ``"replace"`` suits display strings (URLs, refs) that are later written to+ UTF-8 reports, where surrogate escapes would fail to encode.+ """+ return subprocess.check_output(+ ["git", *args],+ cwd=str(cwd),+ stderr=subprocess.DEVNULL,+ text=True,+ encoding="utf-8",+ errors=errors,+ ).strip()++def resolve_git_root(local_path: Path) -> Path | None:"""Return the containing Git repository root without importing optional tiers."""resolved = local_path.resolve()working_dir = resolved if resolved.is_dir() else resolved.parenttry:- root = subprocess.check_output(- ["git", "rev-parse", "--show-toplevel"],- cwd=str(working_dir),- stderr=subprocess.DEVNULL,- text=True,- ).strip()+ # surrogateescape keeps non-UTF-8 path bytes losslessly (as POSIX+ # filesystem decoding does), so the result still names the real directory.+ root = _git_output(["rev-parse", "--show-toplevel"], working_dir, errors="surrogateescape")except (subprocess.CalledProcessError, FileNotFoundError, OSError):return Nonereturn Path(root).resolve() if root else None@@ -164,12 +180,7 @@ def resolve_git_remote_url(local_path: Path) -> str | None:try:# Get the remote origin URL- remote_url = subprocess.check_output(- ["git", "remote", "get-url", "origin"],- cwd=str(repo_root),- stderr=subprocess.DEVNULL,- text=True,- ).strip()+ remote_url = _git_output(["remote", "get-url", "origin"], repo_root)# Get the current branch.# In CI pipelines (detached HEAD), git returns "HEAD" so prefer an@@ -180,22 +191,12 @@ def resolve_git_remote_url(local_path: Path) -> str | None:# local_path may point into a different checkout. Resolve the# revision from the repository that contains local_path.try:- branch = subprocess.check_output(- ["git", "rev-parse", "HEAD"],- cwd=str(repo_root),- stderr=subprocess.DEVNULL,- text=True,- ).strip()+ branch = _git_output(["rev-parse", "HEAD"], repo_root)except subprocess.CalledProcessError:branch = ""if not branch:try:- branch = subprocess.check_output(- ["git", "rev-parse", "--abbrev-ref", "HEAD"],- cwd=str(repo_root),- stderr=subprocess.DEVNULL,- text=True,- ).strip()+ branch = _git_output(["rev-parse", "--abbrev-ref", "HEAD"], repo_root)except subprocess.CalledProcessError:branch = "main"if branch == "HEAD":diff --git a/tests/test_plugin_inventory.py b/tests/test_plugin_inventory.pyindex 42c46a60..bed8f147 100644--- a/tests/test_plugin_inventory.py+++ b/tests/test_plugin_inventory.py@@ -300,6 +300,33 @@ def test_cross_client_only_grants_are_advisory_with_loading_client(tmp_path):assert "loaded only by" in grants[0].message+ ("grant", "quoted", "shell"),+ [+ ("PowerShell(iex *)", "'PowerShell(iex *)' (an interpreter", "PowerShell"),+ ("Bash", "unrestricted 'Bash'", "Bash"),+ ],+)+def test_inert_codex_only_grant_names_the_granted_shell_tool(tmp_path, grant, quoted, shell):+ """Regression: an inert PowerShell grant was reworded as unrestricted 'Bash'."""+ tree(+ tmp_path,+ {+ ".claude-plugin/plugin.json": {"name": "demo", "skills": "./custom"},+ "custom/group/hidden/SKILL.md": SKILL.replace("demo", "hidden").replace("Bash", grant),+ },+ )+ result = inventory(tmp_path)+ grants = [finding for finding in result.findings if finding.check_name == "plugin_skill_unrestricted_bash"]+ assert len(grants) == 1+ assert grants[0].metadata.get("inert_grant")+ assert grants[0].severity == Severity.LOW+ assert f"pre-approves {quoted}" in grants[0].message+ assert f"(it has no {shell} tool)" in grants[0].message+ if shell != "Bash":+ assert "Bash" not in grants[0].message++def test_selected_claude_defaults_retain_grants_beside_inline_commands(tmp_path):tree(tmp_path,diff --git a/tests/tier3/test_github_token_redaction.py b/tests/tier3/test_github_token_redaction.pyindex 13d0a8b3..0c1c0024 100644--- a/tests/tier3/test_github_token_redaction.py+++ b/tests/tier3/test_github_token_redaction.py@@ -87,10 +87,8 @@ def _best_elapsed(pattern, text: str, repeats: int = 5) -> float:[secret_redaction.LOG_GITHUB_TOKEN_RE,secret_redaction.LOG_GITHUB_PAT_RE,- eval_template.LOG_GITHUB_TOKEN_RE,- eval_template.LOG_GITHUB_PAT_RE,],- ids=["host-classic", "host-fine-grained", "template-classic", "template-fine-grained"],+ ids=["classic", "fine-grained"],)def test_github_token_patterns_scale_linearly(pattern):small = _best_elapsed(pattern, _near_miss_text(250))diff --git a/tests/tier3/test_harbor_template_secret_patterns.py b/tests/tier3/test_harbor_template_secret_patterns.pyindex ab0e02b1..dcb76f10 100644--- a/tests/tier3/test_harbor_template_secret_patterns.py+++ b/tests/tier3/test_harbor_template_secret_patterns.py@@ -161,57 +161,10 @@ def test_security_constants_stay_in_sync_with_eval_core(name):)- "name",- [- "LOG_SK_RE",- "LOG_NVAPI_RE",- "LOG_CRSR_RE",- "OPENSHIFT_TOKEN_RE",- "LOG_YA29_RE",- "LOG_JWT_RE",- "LOG_GITHUB_TOKEN_RE",- "LOG_GITHUB_PAT_RE",- ],-)-def test_log_redaction_patterns_stay_in_sync_with_eval_core(name):+def test_template_uses_the_shared_log_redaction():from skillevaluator.tier3.eval_core import secret_redaction- assert hasattr(eval_template, name), f"template missing {name}"- assert _normalize(getattr(eval_template, name)) == _normalize(getattr(secret_redaction, name))--- "line",- [- "plain text with task-granularity is unchanged",- "token sk-Ab1Cd2Ef3Gh4Ij5Kl6Mn7Op8",- "catalog nvapi-Ab1Cd2Ef3Gh4Ij5Kl6Mn7Op8",- "cursor crsr_deadbeefcafebabe",- "openshift sha256~abcdefghijklmnop",- (- "jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."- "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJhZG1pbiI6dHJ1ZX0."- "SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"- ),- "google ya29." + "a0AXooCgs-abcdefghijklmnopqrstuvwxyz12345",- "runtime opaque-secret-value",- "github ghp_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8" + " and ghp_short",- "github github_pat_" + "11ABCDEFG0123456789_abcdefghijklmnopqrstuvwxyz0123",- ],-)-def test_template_log_redaction_matches_eval_core(line):- from skillevaluator.tier3.eval_core.secret_redaction import redact_secrets_in_log_line-- extra_secret_values = ["opaque-secret-value"]-- assert eval_template.redact_secrets_in_log_line(- line,- extra_secret_values=extra_secret_values,- ) == redact_secrets_in_log_line(- line,- extra_secret_values=extra_secret_values,- )+ assert eval_template.redact_secrets_in_log_line is secret_redaction.redact_secrets_in_log_line@pytest.mark.parametrize(diff --git a/tests/tier3/test_log_jwt_redaction.py b/tests/tier3/test_log_jwt_redaction.pyindex b1b105c7..ecedc905 100644--- a/tests/tier3/test_log_jwt_redaction.py+++ b/tests/tier3/test_log_jwt_redaction.py@@ -5,33 +5,13 @@from __future__ import annotations-import importlib.utilimport time-from pathlib import Pathimport pytestfrom skillevaluator.tier3.eval_core.secret_redaction import redact_secrets_in_log_line-_TEMPLATE = (- Path(__file__).resolve().parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"-)---def _load_template_module():- spec = importlib.util.spec_from_file_location("harbor_template_eval_log_jwt", _TEMPLATE)- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---eval_template = _load_template_module()--REDACTORS = pytest.mark.parametrize(- "redact",- [redact_secrets_in_log_line, eval_template.redact_secrets_in_log_line],- ids=["host", "template"],-)+REDACTORS = pytest.mark.parametrize("redact", [redact_secrets_in_log_line], ids=["shared"])def _fixture_secret(*parts: str) -> str:diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.pyindex 20854949..425b2d6a 100644--- a/tests/utils/test_helpers.py+++ b/tests/utils/test_helpers.py@@ -4,9 +4,12 @@"""Tests for skillevaluator.utils module."""import subprocess+import sysfrom pathlib import Pathfrom unittest.mock import patch+import pytest+from skillevaluator.utils import find_skills_in_directory, get_skill_name_from_pathfrom skillevaluator.utils.helpers import (_ssh_to_https,@@ -179,6 +182,28 @@ def _init_git_repo(path: Path, remote_url: str) -> str:return subprocess.check_output(["git", "-C", str(path), "rev-parse", "HEAD"], text=True).strip()+_REAL_CHECK_OUTPUT = subprocess.check_output+++def _cp1252_locale_check_output(*args, **kwargs):+ """Run the real command, decoding text output as a Windows cp1252 locale would."""+ if kwargs.get("text") and kwargs.get("encoding") is None:+ kwargs["encoding"] = "cp1252"+ return _REAL_CHECK_OUTPUT(*args, **kwargs)+++def _fake_git_output(outputs: dict[str, bytes]):+ """Return a check_output stand-in that emits raw git bytes decoded like a cp1252 locale."""++ def fake(cmd, **kwargs):+ raw = outputs[" ".join(cmd[1:])]+ if not kwargs.get("text"):+ return raw+ return raw.decode(kwargs.get("encoding") or "cp1252", kwargs.get("errors") or "strict")++ return fake++class TestResolveGitRoot:"""Tests for lightweight repository-root discovery used by base reports."""@@ -196,6 +221,28 @@ class TestResolveGitRoot:def test_returns_none_outside_git_repository(self, tmp_path: Path) -> None:assert resolve_git_root(tmp_path) is None+ @pytest.mark.parametrize("folder", ["café-skills", "Ýōrk-skills"])+ def test_non_ascii_root_decodes_git_output_as_utf8(self, tmp_path: Path, monkeypatch, folder: str) -> None:+ """Git prints UTF-8 paths; a cp1252 locale must neither garble them nor raise UnicodeDecodeError."""+ repo_root = tmp_path / folder+ _init_git_repo(repo_root, "[email protected]:example/project.git")+ monkeypatch.setattr(subprocess, "check_output", _cp1252_locale_check_output)++ assert resolve_git_root(repo_root) == repo_root.resolve()++ @pytest.mark.skipif(sys.platform == "win32", reason="non-UTF-8 path bytes are a POSIX filesystem case")+ def test_non_utf8_root_bytes_round_trip(self, tmp_path: Path, monkeypatch) -> None:+ """Undecodable path bytes are kept losslessly instead of raising or being replaced."""+ raw_root = str(tmp_path.resolve()).encode("utf-8") + b"/repo-\xff"+ monkeypatch.setattr(+ subprocess, "check_output", _fake_git_output({"rev-parse --show-toplevel": raw_root + b"\n"})+ )++ root = resolve_git_root(tmp_path)++ assert root is not None+ assert str(root).encode("utf-8", "surrogateescape") == raw_root+class TestResolveGitRemoteUrl:"""Tests for the Git remote URL resolver used in HTML report links."""@@ -275,3 +322,20 @@ class TestResolveGitRemoteUrl:url = resolve_git_remote_url(skill_dir)assert url == f"https://github.com/example/secondary/tree/{head}/skills/demo"++ def test_non_ascii_remote_and_branch_decode_as_utf8(self, tmp_path: Path, monkeypatch) -> None:+ """Remote URL and branch names from git are UTF-8 regardless of the locale code page."""+ repo_root = tmp_path / "repo"+ sub_dir = repo_root / "skills"+ sub_dir.mkdir(parents=True)+ outputs = {+ "rev-parse --show-toplevel": f"{repo_root.resolve()}\n".encode(),+ "remote get-url origin": "https://github.com/example/Ýōrk.git\n".encode(),+ "rev-parse --abbrev-ref HEAD": "feature/café\n".encode(),+ }+ monkeypatch.setattr(subprocess, "check_output", _fake_git_output(outputs))++ with patch.dict("os.environ", _clean_ci_env(), clear=True):+ url = resolve_git_remote_url(sub_dir)++ assert url == "https://github.com/example/Ýōrk/tree/feature/café/skills"diff --git a/tests/validators/test_plugin_component_risk.py b/tests/validators/test_plugin_component_risk.pyindex 5e358eff..a8fa8e10 100644--- a/tests/validators/test_plugin_component_risk.py+++ b/tests/validators/test_plugin_component_risk.py@@ -155,6 +155,27 @@ def test_agent_scoped_bash_and_accept_edits(tmp_path: Path) -> None:assert checks["plugin_agent_accept_edits"] == Severity.MEDIUM+def _suggestions(result: ValidationResult) -> dict[str, str]:+ return {finding.check_name: finding.suggestion or "" for finding in result.findings}++[email protected]("frontmatter", ["tools: PowerShell(pwsh *)\n", "tools: PowerShell\ndisallowedTools: Bash\n"])+def test_agent_powershell_grant_is_worded_by_powershell(tmp_path: Path, frontmatter: str) -> None:+ """Regression: the remediation for a PowerShell grant said to deny Bash, and denying Bash hid the grant."""+ result = _validate(_plugin(tmp_path, files={"agents/helper.md": _agent(frontmatter)}))++ assert _checks(result)["plugin_agent_unrestricted_bash"] == Severity.LOW+ suggestion = _suggestions(result)["plugin_agent_unrestricted_bash"]+ assert "PowerShell(Get-ChildItem *)" in suggestion+ assert "deny PowerShell with disallowedTools" in suggestion+ assert "Bash" not in suggestion+++def test_agent_powershell_grant_denied_by_disallowed_tools_is_quiet(tmp_path: Path) -> None:+ root = _plugin(tmp_path, files={"agents/helper.md": _agent("tools: PowerShell\ndisallowedTools: PowerShell\n")})+ assert "plugin_agent_unrestricted_bash" not in _checks(_validate(root))++def test_agent_wildcard_tools_is_medium(tmp_path: Path) -> None:root = _plugin(tmp_path, files={"agents/helper.md": _agent('tools: "*"\n')})assert _checks(_validate(root))["plugin_agent_wildcard_tools"] == Severity.MEDIUM@@ -272,6 +293,20 @@ def test_command_map_allowed_tools_are_checked(tmp_path: Path) -> None:assert _checks(result)["plugin_command_unrestricted_bash"] == Severity.HIGH+def test_command_powershell_grant_suggests_a_scoped_powershell_rule(tmp_path: Path) -> None:+ root = _plugin(+ tmp_path,+ files={"commands/run.md": "---\ndescription: Run.\nallowed-tools: PowerShell(iex *)\n---\nRun.\n"},+ )+ result = _validate(root)++ assert _checks(result)["plugin_command_unrestricted_bash"] == Severity.HIGH+ assert "'PowerShell(iex *)'" in _messages(result)["plugin_command_unrestricted_bash"]+ suggestion = _suggestions(result)["plugin_command_unrestricted_bash"]+ assert "PowerShell(Get-ChildItem *)" in suggestion+ assert "Bash" not in suggestion++# --------------------------------------------------------------------------- ## Hooks ## --------------------------------------------------------------------------- #@@ -318,6 +353,41 @@ def test_auto_approve_with_narrow_matcher_is_recorded_not_flagged(tmp_path: Pathassert _hook_rows(result)[0]["risk_flags"] == ["auto_approve"]+def _conditional_approve_hook(tmp_path: Path, matcher: str, condition: str) -> ValidationResult:+ handler = {"type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/a.sh", "if": condition}+ hooks = _hooks({"PreToolUse": [{"matcher": matcher, "hooks": [handler]}]})+ return _validate(_plugin(tmp_path, files={"hooks/hooks.json": hooks, "a.sh": _APPROVE_SCRIPT}))+++ "condition",+ [+ "PowerShell",+ "PowerShell(*)",+ "PowerShell(iex *)",+ "PowerShell(pwsh *)",+ "PowerShell(cmd.exe *)",+ "PowerShell(start-process *)",+ ],+)+def test_auto_approve_with_a_powershell_launcher_condition_is_high(tmp_path: Path, condition: str) -> None:+ """Regression: a PowerShell 'if' condition was read as a Bash rule, so its launchers looked narrow."""+ result = _conditional_approve_hook(tmp_path, "PowerShell", condition)+ assert _checks(result)["plugin_hook_auto_approve"] == Severity.HIGH+++ ("matcher", "condition"),+ [("PowerShell", "PowerShell(Get-ChildItem *)"), ("Bash", "Bash(git status)"), ("Bash", "Bash(iex *)")],+)+def test_auto_approve_with_a_scoped_shell_condition_is_not_flagged(+ tmp_path: Path, matcher: str, condition: str+) -> None:+ result = _conditional_approve_hook(tmp_path, matcher, condition)+ assert "plugin_hook_auto_approve" not in _checks(result)+ assert _hook_rows(result)[0]["risk_flags"] == ["auto_approve"]++@pytest.mark.parametrize("command",[