"""Offline verification lab for Claude Code Ch 32 (plugin-ref): Plugin layout, manifest, hooks & skills."""
import json
import re
from pathlib import Path
from tempfile import TemporaryDirectory
RUNTIME = "CPython 3.12.14 offline Claude Code plugin reference verifier"
VALID_HOOK_EVENTS = {"PreToolUse", "PostToolUse", "Notification", "Stop", "SubagentStop", "UserPromptSubmit"}
SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$")
def validate_plugin_dir(root: Path) -> dict:
manifest_path = root / ".claude-plugin" / "plugin.json"
errors = []
manifest = {}
if manifest_path.is_file():
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
for req in ("name", "version", "description"):
if not manifest.get(req):
errors.append(f"missing:{req}")
if manifest.get("version") and not SEMVER_RE.match(manifest["version"]):
errors.append("invalid_semver")
skills = sorted(p.parent.name for p in (root / "skills").glob("*/SKILL.md")) if (root / "skills").is_dir() else []
agents = sorted(p.stem for p in (root / "agents").glob("*.md")) if (root / "agents").is_dir() else []
has_hooks = (root / "hooks" / "hooks.json").is_file()
has_mcp = (root / ".mcp.json").is_file()
return {
"name": manifest.get("name"),
"version": manifest.get("version"),
"skills": skills,
"agents": agents,
"has_hooks": has_hooks,
"has_mcp": has_mcp,
"errors": errors,
}
def dispatch_hooks(hooks_cfg: dict, event: str, tool_name: str) -> list[str]:
assert event in VALID_HOOK_EVENTS
triggered = []
for entry in hooks_cfg.get(event, []):
matcher = entry.get("matcher", {})
expected_tool = matcher.get("tool")
if expected_tool in (None, "*", tool_name):
triggered.append(entry["handler"]["command"])
return triggered
def merge_hook_scopes(global_hooks: list[str], project_hooks: list[str], plugin_hooks: list[str]) -> list[str]:
return [*global_hooks, *project_hooks, *plugin_hooks]
def main() -> None:
cases = []
# Case 1: Standard plugin directory anatomy & plugin.json validation
with TemporaryDirectory(prefix="claude-plugin-lab-") as td:
root = Path(td) / "deploy-tools"
(root / ".claude-plugin").mkdir(parents=True)
(root / "skills" / "release-check").mkdir(parents=True)
(root / "agents").mkdir(parents=True)
(root / "hooks").mkdir(parents=True)
(root / ".claude-plugin" / "plugin.json").write_text(
json.dumps(
{
"name": "deploy-tools",
"displayName": "Deployment Tools",
"version": "1.2.0",
"description": "Automated pre-release checks and deployment workflow",
"userConfig": {"targetEnvironment": {"type": "string", "default": "staging"}},
},
ensure_ascii=False,
),
encoding="utf-8",
)
(root / "skills" / "release-check" / "SKILL.md").write_text("---\nname: release-check\n---\n# Check\n", encoding="utf-8")
(root / "agents" / "auditor.md").write_text("# Auditor Agent\n", encoding="utf-8")
(root / "hooks" / "hooks.json").write_text('{"PostToolUse": []}', encoding="utf-8")
(root / ".mcp.json").write_text('{"mcpServers": {}}', encoding="utf-8")
res1 = validate_plugin_dir(root)
exp1 = {
"name": "deploy-tools",
"version": "1.2.0",
"skills": ["release-check"],
"agents": ["auditor"],
"has_hooks": True,
"has_mcp": True,
"errors": [],
}
cases.append({"name": "plugin_layout_and_manifest", "expected": exp1, "actual": res1, "passed": res1 == exp1})
# Case 2: Lifecycle hook matcher dispatch
hooks_cfg = {
"PreToolUse": [{"matcher": {"tool": "Bash"}, "handler": {"type": "shell", "command": "guard-bash"}}],
"PostToolUse": [
{"matcher": {"tool": "Edit"}, "handler": {"type": "shell", "command": "run-prettier"}},
{"matcher": {"tool": "*"}, "handler": {"type": "shell", "command": "audit-log"}},
],
}
act2 = {
"pre_bash": dispatch_hooks(hooks_cfg, "PreToolUse", "Bash"),
"pre_read": dispatch_hooks(hooks_cfg, "PreToolUse", "Read"),
"post_edit": dispatch_hooks(hooks_cfg, "PostToolUse", "Edit"),
}
exp2 = {"pre_bash": ["guard-bash"], "pre_read": [], "post_edit": ["run-prettier", "audit-log"]}
cases.append({"name": "hook_event_matcher_dispatch", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: Multi-scope hook resolution order (global -> project -> plugin)
merged = merge_hook_scopes(["global:audit"], ["project:lint"], ["plugin:deploy-check"])
exp3 = ["global:audit", "project:lint", "plugin:deploy-check"]
cases.append({"name": "hook_scope_layering", "expected": exp3, "actual": merged, "passed": merged == exp3})
# Case 4: Invalid semver & missing fields detection
with TemporaryDirectory(prefix="claude-plugin-bad-") as td:
bad = Path(td) / "broken"
(bad / ".claude-plugin").mkdir(parents=True)
(bad / ".claude-plugin" / "plugin.json").write_text('{"name": "broken", "version": "v1"}', encoding="utf-8")
res4 = validate_plugin_dir(bad)
exp4 = ["missing:description", "invalid_semver"]
cases.append({"name": "invalid_manifest_rejection", "expected": exp4, "actual": res4["errors"], "passed": res4["errors"] == exp4})
print(json.dumps({"runtime": RUNTIME, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Claude Code 插件清单与 Hook 分发验证器(未调用线上 CLI 或市场接口)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Claude Code 插件清单与 Hook 分发验证器(未调用线上 CLI 或市场接口)。
入口文件:projects/claude-code-plugin-ref-lab/explore-plugin-ref.py
预期结果与验证条件观察提示
离线运行 4 项验证用例:标准插件目录结构与 plugin.json 校验、PreToolUse/PostToolUse 钩子匹配分发、全局/项目/插件三层作用域叠加顺序及非法 SemVer/缺字段拒绝,全部通过。
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3140.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip