#!/usr/bin/env python3 """ besci_validate.py — the one validator for the Behavioral Science Skills Library. The same file runs in four places, unchanged: - CI, on every pull request - inside besci-skill-creator, so authors check locally before submitting - inside besci-eval, as its structural check - inside the site's upload function, before a pull request is opened Usage: python besci_validate.py # validate every skill under skills/ python besci_validate.py path/to/skill-folder # validate one skill python besci_validate.py --json # machine-readable output python besci_validate.py --taxonomy FILE # use a specific taxonomy.yaml Exit codes: 0 no errors (warnings allowed), 1 errors found, 2 usage problem. Dependencies: PyYAML only. Python 3.8+. """ from __future__ import annotations import argparse import json import os import re import sys from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple try: import yaml except ImportError: # pragma: no cover sys.stderr.write("besci_validate.py needs PyYAML: pip install pyyaml\n") sys.exit(2) # --------------------------------------------------------------------------- # The spec, as constants. docs/skill-spec.md is the prose version of this. # --------------------------------------------------------------------------- SPEC_TOP_LEVEL_KEYS = {"name", "description", "license", "compatibility", "allowed-tools", "metadata"} ALLOWED_LICENSES = {"CC-BY-4.0", "MIT"} REQUIRED_SECTIONS = [ "What it does", "When to use it", "Before you start", "What it draws on", "How to do it", "Output template", "Where it goes wrong", "When to bring in a specialist", ] NA_ALLOWED_SECTIONS = {"Before you start", "When to bring in a specialist"} NA_PREFIX = "not applicable:" NA_MIN_REASON_CHARS = 20 USE_WHEN_SUBHEADING = "Use it when" DONT_USE_WHEN_SUBHEADING = "Do not use it when" MIN_USE_WHEN_BULLETS = 3 MIN_DONT_USE_BULLETS = 2 REQUIRED_METADATA = ["type", "stage", "version", "status", "authors", "org"] KNOWN_METADATA = set(REQUIRED_METADATA) | { "title", "tested_in", "weird", "tags", "consumes", "produces", "reviewed_by", "created", "updated", "catalog_snapshot", } MIN_EVALS = 3 MIN_EVALS_META = 1 # a meta-skill's test cases take any shape; it needs at least one # --- The November 2026 standard --------------------------------------------- # These rules apply to atomic skills. They were warnings while the library was # revised to the standard and are errors now. Set STRICT_V2 to False only to # check a skill written to the earlier standard. STRICT_V2 = True TESTED_IN_IDS = ["beyond-western-holds", "beyond-western-differs", "mainly-western", "not-applicable"] # metadata.weird was the earlier name of metadata.tested_in. Old values map to new ones. TESTED_IN_LEGACY = { "weird-only": "mainly-western", "untested-outside-weird": "mainly-western", "mixed-evidence": "beyond-western-differs", "likely-generalizes": "beyond-western-holds", "not-applicable": "not-applicable", } ADDS_LABEL = "**What this adds:**" EVIDENCE_LABEL = "**Where the evidence comes from:**" REPLICATION_LABEL = "**Replication status:**" SOFT_MAX_WORDS = 1000 # SKILL.md body, not counting the output template's code block SOFT_MAX_DESCRIPTION = 600 # the hard cap from the Agent Skills spec stays 1024 REQUIRED_REFERENCES = { "references/worked-example.md": ["The request", "The output"], "references/evidence.md": ["Sources", "Where it has been tested", "Replication", "What to check locally"], } CASE_ROLES = ["Full run", "Missing context", "Near the escalation point", "Wrong skill"] REVIEW_ROLE_PREFIX = "From an expert review" MIN_ASSERTIONS, MAX_ASSERTIONS = 3, 6 SOFT_MAX_EXPECTED_WORDS = 60 # Notes about how a skill was drafted or checked belong in the changelog or the # repository's planning files, not in the text a user or the AI reads. PROCESS_TERMS = ["dossier", "verified-crossref", "verified-fetch", "author to confirm", "plan-only citation"] SKILL_NAME_IN_TEXT_RE = re.compile(r"`([a-z]+(?:-[a-z0-9]+)+)`") # --- The conversational voice ------------------------------------- # Every skill carries the shared voice block in its Output template section and # ends its template with a closing that offers next moves. These were warnings # while the library was revised to the standard and are errors now. STRICT_VOICE = True VOICE_START = "" VOICE_END = "" CLOSING_HEADING = "Where you could go from here" DIRECTIVE_CLOSING_RE = re.compile( r"(\*\*\s*(next actions?|next steps?|check first|do this next|start with|your next step)\b" r"|^#+\s*(next actions?|next steps?)\b)", re.IGNORECASE | re.MULTILINE, ) MAX_SKILL_MD_LINES = 500 MAX_FILE_BYTES = 2 * 1024 * 1024 MAX_FOLDER_BYTES = 10 * 1024 * 1024 ALLOWED_EXTENSIONS = { ".md", ".txt", ".json", ".yaml", ".yml", ".csv", ".tsv", ".py", ".r", ".sh", ".html", ".css", ".js", ".png", ".jpg", ".jpeg", ".svg", ".gif", } NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$") SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+$") CITATION_HINT_RE = re.compile(r"(https?://|doi\.org|\b(19|20)\d{2}\b)") # --------------------------------------------------------------------------- # Data model # --------------------------------------------------------------------------- @dataclass class Finding: level: str # "error" | "warning" code: str message: str file: str = "SKILL.md" def as_dict(self) -> dict: return {"level": self.level, "code": self.code, "message": self.message, "file": self.file} @dataclass class Skill: path: str folder: str frontmatter: dict = field(default_factory=dict) metadata: dict = field(default_factory=dict) body: str = "" sections: "Dict[str, str]" = field(default_factory=dict) # heading -> text, in file order evals: Optional[dict] = None changelog: Optional[str] = None files: List[str] = field(default_factory=list) findings: List[Finding] = field(default_factory=list) @property def name(self) -> str: return str(self.frontmatter.get("name", "")) if isinstance(self.frontmatter, dict) else "" @property def errors(self) -> List[Finding]: return [f for f in self.findings if f.level == "error"] @property def warnings(self) -> List[Finding]: return [f for f in self.findings if f.level == "warning"] def error(self, code: str, message: str, file: str = "SKILL.md") -> None: self.findings.append(Finding("error", code, message, file)) def warn(self, code: str, message: str, file: str = "SKILL.md") -> None: self.findings.append(Finding("warning", code, message, file)) def voice(self, number: str, message: str, file: str = "SKILL.md") -> None: """A rule from the conversational-voice standard: a warning until STRICT_VOICE is on, then an error.""" if STRICT_VOICE: self.error("E" + number, message, file) else: self.warn("W" + number, message, file) def v2(self, number: str, message: str, file: str = "SKILL.md") -> None: """A rule from the November 2026 standard: a warning until STRICT_V2 is on, then an error.""" if STRICT_V2: self.error("E" + number, message, file) else: self.warn("W" + number, message, file) # --------------------------------------------------------------------------- # Taxonomy # --------------------------------------------------------------------------- def find_repo_root(start: str) -> Optional[str]: """Walk upward until a taxonomy.yaml is found.""" cur = os.path.abspath(start) while True: if os.path.exists(os.path.join(cur, "taxonomy.yaml")): return cur parent = os.path.dirname(cur) if parent == cur: return None cur = parent def load_taxonomy(path: Optional[str] = None) -> dict: """Load taxonomy.yaml. Falls back to a copy next to this script, then to built-in minimums.""" candidates = [] if path: candidates.append(path) root = find_repo_root(os.getcwd()) if root: candidates.append(os.path.join(root, "taxonomy.yaml")) here = os.path.dirname(os.path.abspath(__file__)) candidates.append(os.path.join(here, "taxonomy.yaml")) candidates.append(os.path.join(os.path.dirname(here), "taxonomy.yaml")) for c in candidates: if os.path.exists(c): with open(c, "r", encoding="utf-8") as fh: return yaml.safe_load(fh) or {} # Built-in minimum so the bundled copy still works without the file. return { "stages": [{"id": s} for s in ["define", "diagnose", "design", "measure", "test", "analyze", "implement", "other"]], "types": ["atomic", "meta"], "statuses": ["draft", "published", "deprecated"], "tested_in": [{"id": s} for s in TESTED_IN_IDS], "verbs": [], "io_types": [], } def _ids(items) -> List[str]: out = [] for it in items or []: if isinstance(it, dict): out.append(str(it.get("id", ""))) else: out.append(str(it)) return out # --------------------------------------------------------------------------- # Parsing # --------------------------------------------------------------------------- def split_frontmatter(text: str) -> Tuple[Optional[str], str]: """Return (yaml_text, body). yaml_text is None when no frontmatter block exists.""" if not text.startswith("---"): return None, text lines = text.splitlines(keepends=True) if lines[0].strip() != "---": return None, text for i in range(1, len(lines)): if lines[i].strip() == "---": return "".join(lines[1:i]), "".join(lines[i + 1:]) return None, text def split_sections(body: str) -> Dict[str, str]: """Split a markdown body on level-2 headings. Keeps order. Ignores headings inside fenced code.""" sections: Dict[str, str] = {} current: Optional[str] = None buf: List[str] = [] in_fence = False for line in body.splitlines(): if line.strip().startswith("```"): in_fence = not in_fence if not in_fence and line.startswith("## "): if current is not None: sections[current] = "\n".join(buf).strip() current = line[3:].strip() buf = [] continue if current is not None: buf.append(line) if current is not None: sections[current] = "\n".join(buf).strip() return sections def split_subsections(text: str) -> Dict[str, str]: """Split a section on level-3 headings.""" subs: Dict[str, str] = {} current: Optional[str] = None buf: List[str] = [] for line in text.splitlines(): if line.startswith("### "): if current is not None: subs[current] = "\n".join(buf).strip() current = line[4:].strip() buf = [] continue if current is not None: buf.append(line) if current is not None: subs[current] = "\n".join(buf).strip() return subs def bullets(text: str) -> List[str]: return [ln.strip()[2:].strip() for ln in text.splitlines() if ln.strip().startswith(("- ", "* "))] def split_list(value: Optional[str]) -> List[str]: """Metadata lists are comma-separated strings (the spec allows strings only).""" if not value: return [] return [v.strip() for v in str(value).split(",") if v.strip()] def strip_fences(text: str) -> str: """The text with fenced code blocks removed.""" out, in_fence = [], False for line in text.splitlines(): if line.strip().startswith("```"): in_fence = not in_fence continue if not in_fence: out.append(line) return "\n".join(out) def word_count(text: str) -> int: return len(text.split()) def strip_voice_block(text: str) -> str: """The text with the shared voice block removed; it does not count toward a skill's length.""" if VOICE_START not in text: return text head, rest = text.split(VOICE_START, 1) return head + (rest.split(VOICE_END, 1)[1] if VOICE_END in rest else "") def known_names(start: str) -> Optional[set]: """Every skill folder and workflow name in the repository, or None outside a repository.""" root = find_repo_root(start) if not root: return None names = set() skills = os.path.join(root, "skills") if os.path.isdir(skills): names |= {d for d in os.listdir(skills) if os.path.exists(os.path.join(skills, d, "SKILL.md"))} flows = os.path.join(root, "workflows") if os.path.isdir(flows): names |= {f[:-3] for f in os.listdir(flows) if f.endswith(".md")} return names or None def supporting_skills(start: str) -> Optional[set]: """Names listed under 'Supporting skills' in docs/canonical-sources.md, or None when that file cannot be found, as in a bundled copy.""" root = find_repo_root(start) path = os.path.join(root, "docs", "canonical-sources.md") if root else "" if not path or not os.path.exists(path): return None with open(path, "r", encoding="utf-8") as fh: text = fh.read() m = re.search(r"^## Supporting skills\s*$(.*?)(?=^## |\Z)", text, flags=re.MULTILINE | re.DOTALL) return set(re.findall(r"`([a-z0-9-]+)`", m.group(1))) if m else set() def level2_headings(text: str) -> List[str]: return [ln[3:].strip() for ln in strip_fences(text).splitlines() if ln.startswith("## ")] def read_text(skill: "Skill", rel: str) -> Optional[str]: full = os.path.join(skill.path, rel) if not os.path.exists(full): return None try: with open(full, "r", encoding="utf-8") as fh: return fh.read() except (OSError, UnicodeDecodeError): return None def tested_in_value(metadata: dict) -> str: """metadata.tested_in, or the value the earlier metadata.weird maps to.""" t = str(metadata.get("tested_in", "")).strip() if t: return t return TESTED_IN_LEGACY.get(str(metadata.get("weird", "")).strip(), "") def labelled_line(section_text: str, label: str) -> str: """The text that follows a bold label such as '**What this adds:**', up to the next blank line.""" if label not in section_text: return "" rest = section_text.split(label, 1)[1] return " ".join(rest.split("\n\n", 1)[0].split()).strip() def opening_paragraph(body: str) -> str: """The first paragraph of prose in a SKILL.md body, before any level-2 heading. Empty when the body opens with something else.""" head = re.split(r"^## ", body, maxsplit=1, flags=re.MULTILINE)[0] for para in re.split(r"\n\s*\n", head.strip()): para = para.strip() if not para or para.startswith(("#", "