"""Validate the workshop Skill structure and inspect its optional files."""
import argparse
import json
from pathlib import Path
import re
from tempfile import TemporaryDirectory
import yaml
OPTIONAL_DIRECTORIES = ("assets", "references", "scripts")
OPTIONAL_FIELDS = ("allowed-tools", "compatibility", "license", "metadata")
SKILL_NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
def check(folder):
errors = []
file = folder / "SKILL.md"
if not file.is_file():
return {"valid": False, "errors": ["SKILL.md is missing"]}
first, opening, rest = file.read_text(encoding="utf-8").partition("\n")
if first != "---" or not opening:
return {"valid": False, "errors": ["opening YAML delimiter is missing"]}
lines = rest.splitlines()
if "---" not in lines:
return {"valid": False, "errors": ["closing YAML delimiter is missing"]}
stop = lines.index("---")
try:
fields = yaml.safe_load("\n".join(lines[:stop]))
except yaml.YAMLError:
return {"valid": False, "errors": ["invalid YAML"]}
if not isinstance(fields, dict):
return {"valid": False, "errors": ["frontmatter must be a mapping"]}
name = fields.get("name")
if not isinstance(name, str) or not (1 <= len(name) <= 64 and SKILL_NAME.fullmatch(name)):
errors.append("name must have 1–64 lowercase ASCII letters, numbers and single hyphen separators")
elif name != folder.name:
errors.append("name must match the directory")
description = fields.get("description")
if not isinstance(description, str) or not (description.strip() and len(description) <= 1024):
errors.append("description must be nonblank and at most 1024 characters")
if "compatibility" in fields:
compatible = fields["compatibility"]
if not isinstance(compatible, str) or not (1 <= len(compatible.strip()) and len(compatible) <= 500):
errors.append("compatibility must be a nonblank string of at most 500 characters")
if "metadata" in fields:
metadata = fields["metadata"]
if not isinstance(metadata, dict) or any(not isinstance(key, str) or not isinstance(value, str)
for key, value in metadata.items()):
errors.append("metadata must map strings to strings")
for field in ("allowed-tools", "license"):
if field in fields and not isinstance(fields[field], str):
errors.append(f"{field} must be a string")
return {"valid": not errors, "errors": errors,
"optional_fields": [field for field in OPTIONAL_FIELDS if field in fields],
"directories": [name for name in OPTIONAL_DIRECTORIES if (folder / name).is_dir()]}
def exercise():
source = Path(__file__).parent / "skills" / "sales-summary"
with TemporaryDirectory(prefix="mbsky-skill-structure-") as directory:
root = Path(directory)
def verify(folder_name, header):
folder = root / folder_name
folder.mkdir(exist_ok=True)
file = folder / "SKILL.md"
file.write_text(f"---\n{header}\n---\n\n# Review an inventory sample\n", encoding="utf8")
return check(folder)
required = [check(source)["valid"]]
for content in (
"name: minimum", "name: minimum\ndescription: ' '",
"name: minimum\ndescription: " + "x" * 1024,
"name: minimum\ndescription: " + "x" * 1025,
"name: [broken",
):
required.append(verify("minimum", content)["valid"])
names = [verify(folder, f"name: {name}\ndescription: Audit a local inventory.")["valid"]
for folder, name in [("a", "a"), ("b" * 64, "b" * 64), ("c" * 65, "c" * 65),
("RenderReport", "RenderReport"), ("audit_ledger", "audit_ledger"),
("leading", "-leading"), ("trailing", "trailing-"),
("double--gap", "double--gap"), ("parent", "another"),
("stage-audit-v2", "stage-audit-v2")]]
for name in OPTIONAL_DIRECTORIES:
(root / "full-inspection" / name).mkdir(parents=True)
header = ("name: full-inspection\ndescription: |\n Confirm approved inventory inputs\n"
" before reconciling totals.\nlicense: MIT\nmetadata:\n version: '2'\n"
"allowed-tools: Read\ncompatibility: ")
optional = verify("full-inspection", header + "local audit runner")
too_long = verify("full-inspection", header + "x" * 501)["valid"]
return {"required": required, "names": names, "yaml_version": yaml.__version__,
"optional": {"valid": optional["valid"], "too_long": too_long,
"fields": optional["optional_fields"], "directories": optional["directories"]}}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("folder", type=Path, nargs="?")
parser.add_argument("--exercise", action="store_true")
args = parser.parse_args()
if not args.exercise and args.folder is None:
parser.error("supply the skill directory or --exercise")
print(json.dumps(exercise() if args.exercise else check(args.folder), ensure_ascii=False))
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-foundations/check_skill.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
check_skill.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a340.zip