Behavioral science skill evaluator
besci-eval
Diagnoses one library skill: whether its structure is sound, whether it fires on the right requests, and whether it makes the AI do the job better than the AI does alone. Reports what it found on one screen.
Expert reviews are for staff at The Agency Fund and Irrational Labs; anyone can rate.
Skill
The instructions your AI follows when this skill runs. Installing the skill gives it this file and everything in the other tabs.
SKILL.mdView on GitHub
Takes in
skill-draftSkill draftFrom besci-skill-creatorProduces
eval-reportSkill evaluation reportInstall
/plugin marketplace add agency-fund/besci-skills/plugin install besci-skills@besci-skillsnpx skills add agency-fund/besci-skills --skill besci-evalUpload the file under Settings → Capabilities → Skills. Zip installs do not update themselves; check What's new now and then.
A skill can meet every rule in the spec and still add nothing. So the main test here is a comparison: the same realistic request answered with the skill and without it. The library's claim for every skill is that it makes the AI do something it would not do unprompted, and this checks that claim.
Before anything else
Find out which skill (a folder, a .skill file, or pasted text) and how you can run things here, because that sets how clean the comparison is:
- Fresh agents, when you can start one. One agent gets a request and the path to the skill's folder, and is told to read its
SKILL.md, follow it, readreferences/when the skill says to, and leaveevals/alone. Another gets the same request and is told to answer from its own knowledge, loading no skill and reading no files, because the library may be installed where it runs. Neither sees the other or is told it is a test. Tell both that the user can answer afterwards, so an agent that would ask a question first can ask it. Use this tier whenever it is available. - The script, for repeated runs, several models, or a re-test after a model release. It calls the API and costs money, so show the plan first:
python scripts/run_evals.py <skill-folder> --dry-runprints the number of calls and writes nothing. Run it only on the person's go-ahead. It loadsSKILL.mdalone, without the skill's reference files, so it tests a little less than a fresh agent does. - In this conversation, when there are no tools. You cannot un-read a skill, so the order of work below matters most here, and the report says the result is indicative.
Keep this order, on every tier. Read only the skill's description and the prompt of each test case first. In evals.json each prompt sits beside its expected output and assertions, so print the prompts alone or have the person paste them. Then write the cold case. Then get the baselines: start the fresh agents, or on the conversation tier write your own answer to each case. Only then read the rest of the skill. The validator can run at any point, since it shows you nothing of the body. A baseline written after reading the skill borrows its ideas and makes the skill look as if it adds less than it does.
Three checks
Structure. Run python scripts/besci_validate.py <skill-folder> from this skill's folder, or walk references/checklist.md when you cannot. Report errors in plain words. A meta-skill or supporting skill is written in its own shape, so only its frontmatter and files are checked (plus test cases and a changelog for a meta-skill); say so. Structural errors do not stop the other checks unless there is no description to test.
Triggering. Would an AI that sees only descriptions load this skill for the right requests, and leave it alone for the wrong ones?
- Requests it should take: the bullets under "Use it when", the test cases, and the cold case. A bullet that states a condition and not a request gets turned into what a user would type.
- Requests it should leave: the bullets under "Do not use it when", the "Wrong skill" case, and any case marked
"should_trigger": false. For a skill with no such lists, write two or three near-misses from the "do not use" clause of its description. - Judge each one next to the neighbors: this skill's description among the descriptions of the other skills in the catalog (
skills/besci-navigator/references/catalog.mdin the repository, or the live catalog). A description that fires correctly alone can over-fire next to its neighbors. With a fresh agent, give it the list of descriptions and the requests in shuffled order, do not say which skill is under test, and ask which skill, if any, it would load for each. One agent can take all the requests.
On the job. Run three cases, each with the skill and without it: the "Full run" case, the "Missing context" case, and one cold case. For a skill without those names, use its first two cases. "All cases" is there if the person asks; a "Wrong skill" case is then judged on whether the skill sends the person to the right place.
The cold case is a request you write from the description alone, the way a program officer would type it: plain words, a real-sounding program, none of the method's vocabulary, and enough detail that the skill can produce its full output. The "Missing context" case already tests whether the skill asks, so the cold case should show the whole output on a request the skill has never seen. A skill's own cases were written with the skill open and tend to hand it what it asks for. A skill that does well on its own cases and poorly on the cold one has shown you its most useful finding.
For each pair of answers, settle three questions and quote the answers as you do:
- Did the skill change what the AI did?
- Is the change the one the skill promises? An atomic skill states its promise in the "What this adds" line; for another skill, use how it describes itself.
- For this job, would a practitioner prefer the answer written with the skill, and why?
Then mark the case's own assertions against each answer. Three things block a skill whatever else is true: a citation that is not in the skill's sources or was not opened, a full answer to a request that lacked something the skill needs, and a missed handoff to a specialist. references/judging.md has the detail, and the script's judge reads the same file.
The report
About one screen, in this order every time, so that maintainers can read reports side by side. Lead with the verdict.
# Diagnosis: <skill-name> v<version> (<date>)
**Verdict:** <ready | fix first | could not test>. <The finding that decided it, in one sentence.>
## Structure
<Passes, or the errors in plain words. One line when clean.>
## Triggering
<Counts in words: "It fired on 5 of 6 requests it should take, and on 1 of 4 it should leave.">
<Each miss or false alarm: the request, and the clause in the description responsible.>
## On the job
<Per case, two or three sentences: what the skill changed against the bare model, whether that is what it promises, which answer a practitioner would prefer and why, and assertions passed with and without.>
<One short side-by-side excerpt from the most telling case.>
## What to fix
<Up to three findings, most important first, each with the smallest change that would address it.>
## How this was run
<Two or three lines: fresh agents, script, or in conversation; the model; runs per case; what was not run; and that which answer is better is a model's judgment, not a practitioner's.>
- Ready means ready for a maintainer's content review. Fix first is where most first drafts land: a validator error, a blocking finding, a description that fires on the wrong requests, or answers that are no better with the skill on most of the cases. Could not test means there was nothing to run. When the verdict is "ready" and the evidence is thin, the sentence after it says so.
- Give counts in words. Precision and recall to two decimals on ten requests claim an accuracy that is not there.
- You propose and the author decides. Never edit the skill;
besci-skill-creatorhelps with the revision. - With a filesystem, save the full answers and the per-request detail to a folder named
<skill>-workspacebeside the skill's folder, so the report can stay short. The repository ignores those folders, and the script writes there itself. Model comparison appears only when more than one model ran.
What this cannot tell you
Whether the method is right. You can see that two answers differ and which one does the job as described; you cannot settle which advice a practitioner would stand behind. Say so when two runs give different method advice, when a source cannot be checked, or when the skill touches clinical, safety, or child-protection decisions, and point to the skill's expert reviews on the library site. One run is one draw from a model that varies, so without repeats call the findings indicative.
Nothing here measures whether a program or an AI product works. That is The Agency Fund's evaluation playbook, https://eval.playbook.org.ai/.
Manner
Plain and direct. Say what you found and what you could not test. Quote the answers rather than describe them. No praise, and no softening a "fix first" into something vaguer.
Cite this skill
Zezhen Wu (2026). Behavioral science skill evaluator (version 0.4.0) [AI skill]. Behavioral Science Skills Library, The Agency Fund and Irrational Labs. https://besci-skills.vercel.app/skills/besci-eval/Skills are fixed, versioned artifacts. Record the skill name and version in your project documentation the way you would register analysis code. See how to cite skills and workflows, which follows Busara's SIFA framework for stating how humans and AI contributed.
Using this skill inside a commercial AI product sends what you type to that product's provider. Do not paste sensitive personal or proprietary data without understanding the product's terms. Read the disclosure.
Test cases
Realistic requests used to check this skill, each paired with what a good answer must contain. Maintainers rerun them with besci-eval when the skill or the AI model changes. They also show the kind of request the skill is built for.
evals/evals.jsonView on GitHub
Test case 1: A full diagnosis in Claude Code
The request
I'm in Claude Code. Evaluate skills/draft-cognitive-interview-script before I open the PR.
What a good answer includes
The evaluator reads only the description and the case prompts first and writes a cold case, then runs the validator, judges triggering next to the catalog's other descriptions, and runs three cases with and without the skill using fresh agents. It ends with the one-screen report, verdict first.
Checks on the answer
- Writes a cold case, or says it will, before reading the body of the skill.
- Runs or plans each case twice: with the skill and with no skill.
- Does not run the API script without showing the number of calls and asking first.
- The report opens with a verdict that is one of: ready, fix first, could not test.
- The report has the parts Structure, Triggering, On the job, What to fix, and How this was run.
- Does not edit the skill.
Test case 2: No tools
The request
I'm on Claude Desktop, no code execution. Here is my skill as pasted text: the SKILL.md and evals/evals.json for decompose-comb-barriers. Is it any good?
---
name: decompose-comb-barriers
description: Use when one behavior is defined (who does what, when) and the question is why people are not doing it, or when a team is about to pick an intervention without naming the barrier it addresses. Lists competing capability, opportunity, and motivation hypotheses, each with a question that could rule it out, and ranks them. Do not use when the goal is still vague; use define-key-behavior. Not for choosing what to do about a confirmed barrier; use select-intervention-levers.
---
[the rest of SKILL.md and the four test cases follow]
What a good answer includes
The evaluator works in the conversation and keeps the order: from the description and the case prompts alone it writes a cold case and its own bare answers before using the skill's body. It walks the checklist in place of the validator, and its report says the result is indicative and was run in conversation on one model.
Checks on the answer
- Writes its answer to at least one case without the skill before producing the answer with the skill.
- Says the comparison is indicative because it was run in one conversation.
- Uses the checklist, or says the validator could not be run.
- Gives triggering as counts in words, not as precision and recall decimals.
- The report's last part says how it was run and that the preference is a model's judgment.
Test case 3: Not skill evaluation
The request
Can you evaluate our maternal health chatbot? We want to know if it's improving outcomes.
What a good answer includes
The evaluator says this is evaluation of an AI product and a program outcome, which it does not do, and points to The Agency Fund's evaluation playbook. It runs no checks.
Checks on the answer
- Says it evaluates library skills and not AI products or program outcomes.
- Points to The Agency Fund's evaluation playbook.
- Runs no checks and produces no diagnosis.
Test case 4: A meta-skill
The request
Run the evaluator on besci-navigator. I changed how it opens and want to know if it still does its job.
What a good answer includes
The evaluator says a meta-skill is checked on frontmatter, files, test cases, and changelog only, takes triggering requests from its test cases and near-misses it writes, and judges the first turn of the interview against the bare model.
Checks on the answer
- Says the eight-section rules do not apply to a meta-skill.
- Compares the skill's answers with answers written with no skill.
- Judges a single turn of the interview and does not expect a full output.
- The report opens with a verdict.
Test case 5: After a model release
The request
A new Claude model was released this week. Which of our published skills got worse? We have twelve skills in the repo.
What a good answer includes
The evaluator proposes the script for this, since it needs repeated runs on two models across twelve skills, shows how to get the call count with --dry-run, and asks for the go-ahead before spending. It does not start the runs.
Checks on the answer
- Recommends the script and names the two models to compare.
- Shows or offers the dry run and its call count before any API call.
- Asks for the go-ahead before spending.
- Says results per skill will be reported separately for each model.
References
Longer material the skill opens only when a step calls for it, which keeps the main instructions short.
references/View on GitHub
- Manual validation checklist
references/checklist.mdUse when the validator script cannot run. - Judging a skill on the job
references/judging.mdHow to compare two answers to the same request, one written with a skill and one without.
Manual validation checklist
Use when the validator script cannot run. Each line mirrors a rule in scripts/besci_validate.py; the code in brackets is what the script would report. The list is for an atomic skill. A supporting skill is checked on "Frontmatter" and the file limits only, and a meta-skill on those plus "Meta-skills" at the end.
Folder and files
- [ ] Folder name is kebab-case, 1 to 64 characters, no leading, trailing, or double hyphens, and equals
namein the frontmatter. [E003, E004] - [ ] For atomic skills, the name starts with a verb from the taxonomy's list (define, decompose, draft, design, measure, map, score, select, adjust, analyze, assess, audit, build, choose, cluster, compare, diagnose, estimate, evaluate, find, generate, identify, plan, prioritize, propose, review, simulate, specify, summarize, synthesize, test, translate, validate, write). [E005]
- [ ]
SKILL.md,evals/evals.json, andCHANGELOG.mdexist. NoREADME.mdin the folder. [E001, E029, E030, W033] - [ ] Atomic skills have
references/worked-example.md(headings: The request; The output) andreferences/evidence.md(headings: Sources; Where it has been tested; Replication; What to check locally). [E045, W046] - [ ] Neither
SKILL.mdnor a reference file says how the skill was drafted or checked; that goes inCHANGELOG.md. [W050] - [ ] Only allowed file types; nothing over 2 MB; folder under 10 MB. [E034]
- [ ] Every
references/,scripts/, orassets/path mentioned in SKILL.md exists. [E032] - [ ] SKILL.md is under 500 lines, and about 1,000 words not counting the output template. [W031, W043]
Frontmatter
- [ ] Only these top-level keys: name, description, license, compatibility, allowed-tools, metadata. [E035]
- [ ]
descriptionis 1 to 1024 characters (aim for about 500, no citations), has no<or>, contains a "use when" clause and a "do not use when" clause. [E006, E007, E008, W044] - [ ]
licenseis CC-BY-4.0 (or MIT for code-only skills). [E009] - [ ]
metadatahas type, stage, version, status, authors, org, all as plain strings. [E010] - [ ] type is atomic, meta, or supporting; an atomic skill's stage is one of the seven, and a meta-skill or supporting skill declares
other; version is quoted semver; status is draft, published, or deprecated. [E011, E012, E013, E014, E015] - [ ] Atomic skills have
tested_inset to one of: beyond-western-holds, beyond-western-differs, mainly-western, not-applicable. [E018, E040] - [ ]
consumesandproducesuse ids from the taxonomy's io types. Atomic skills name exactly oneproduces;consumeslists only the inputs the skill cannot run without. [W019, E049]
Body
- [ ] Exactly these level-2 headings, in this order: 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. [E020, E021]
- [ ] No section is empty. [E022]
- [ ] Only "Before you start" and "When to bring in a specialist" may read "Not applicable:
", and the reason is a real sentence. [E023] - [ ] First sentence of "What it does" has no "and", and the section has a line starting
**What this adds:**. [W024, E041] - [ ] "When to use it" has
### Use it whenwith at least three bullets and### Do not use it whenwith at least two. [E025, E026] - [ ] "What it draws on" has at least one real citation (year, DOI, or URL), a note starting
**Where the evidence comes from:**, and a note starting**Replication status:**. [W027, E042] - [ ] "Before you start" asks for each input by what it is, not by the skill that made it. [W051]
- [ ] Every skill or workflow named anywhere in SKILL.md exists in the library. [E056]
- [ ] "Output template" contains a fenced code block. [W028]
- [ ] The template opens with a plain lead-in, uses labels a program designer would use, and ends with a "Where you could go from here" closing: two or three next moves with reasons, and questions the user could ask next. [E054]
- [ ] No "Next action", "Check first", or "Next steps" line in the template. [E055]
- [ ] After the template, the "Output template" section carries the shared voice block between the markers, identical to
template/shared/voice.md. [E053; check_sync] - [ ] The closing's placeholder lists candidate next moves, each with the condition under which it fits, including one step outside the library.
Codes E040 to E049 and E053 to E056 are errors, except the warnings W043, W044, and W046; W050 to W052 are warnings too.
Evals and changelog
- [ ]
evals.jsonhasskill_nameequal to the name, and each case has id, prompt, expected_output. [E029] - [ ] Atomic skills have four cases named, in order, Full run, Missing context, Near the escalation point, Wrong skill; any later case is named "From an expert review #
". [E047] - [ ] Each case has three to six assertions and a one-sentence expected_output. [E048, W052]
- [ ]
CHANGELOG.mdtop entry is## <version> - <date>matchingmetadata.version. [E030]
Meta-skills
A meta-skill's body takes any shape, so "Body" above does not apply to it, and neither do the four named cases, the reference files, or tested_in.
- [ ] The body opens with a paragraph that says what the skill does.
- [ ]
evals.jsonhasskill_nameequal to the name and at least one case with id, prompt, expected_output. [E029] - [ ]
CHANGELOG.mdtop entry matchesmetadata.version. [E030] - [ ] Every skill or workflow named in SKILL.md exists in the library. [E056]
Judging a skill on the job
How to compare two answers to the same request, one written with a skill and one without. The evaluator follows this in conversation, and the script gives the same text to its judge model.
The three questions
1. Did the skill change what the AI did? Say what one answer does that the other does not, concretely: "lists a reason under each of six headings and pairs each with a question", not "is more structured". If the two answers would lead the person to do the same thing next, the skill changed the form and not the substance. Say that.
2. Is the change the one the skill promises? The promise is the skill's "What this adds" line, or, for a skill without one, how it describes itself. Check the promise piece by piece against the answer. A skill that promises to ask before answering and then answers has broken its promise even if the answer is good.
3. For this job, would a practitioner prefer the answer written with the skill? Judge by the job in the request: could the person act on this answer, check it, and defend it to a colleague? Reasons that count: it asks for something the answer depends on; it separates what is known from what is guessed; it names the mechanism and not only a tactic; it says where its evidence was tested; it stops where a specialist should take over. Reasons that do not count: it is longer, it has more headings, it uses the method's vocabulary, it follows a template.
Prefer the bare answer when it is the better one. A skill that makes answers longer and no more useful has failed this question, and that is a finding worth reporting.
Assertions
A test case may carry assertions: short statements about the answer that are true or false. Mark each one for each answer. An assertion the bare answer also passes tells you the skill is not needed for that point. An assertion the with-skill answer fails in most runs goes in "What to fix".
Blocking findings
Any one of these means "fix first", whatever the comparison shows:
- An invented citation. The with-skill answer cites a source that is not in the skill's own files and that the answer does not show was opened. A source that appears in the skill's
SKILL.mdorreferences/is the skill's own and is fine. A real-looking reference that cannot be traced is the most damaging thing a skill can produce. - Answering when it should have asked. The request lacked something the skill needs, and the answer went ahead on a guess. On a "Missing context" case the right answer is the skill's questions and nothing else.
- A missed handoff. The request met one of the skill's conditions for bringing in a specialist, or was plainly clinical, legal, or about the safety of children or another vulnerable group, and the answer did not say so.
A brief answer to a question the user asked, given before the skill's own questions, is not "answering when it should have asked".
Skills that hold a conversation
Some skills, such as the navigator and the skill creator, run an interview. A test case shows one turn of it. Judge that turn: did it ask one question, was it the right first question for this person, did it guess a fact it should have asked about, did it start producing output before it knew enough?
Triggering
For each request, the judge sees this skill's description among the descriptions of the other skills in the catalog. A fresh agent is asked the open question, which skill, if any, it would load, and is not told which skill is under test. The script asks its judge the narrower one: would you load this skill for this request, yes or no, and why in one line. The open question is the harder test, so prefer it when you can. Report how many of the requests it should take it fired on, and how many of the requests it should leave it fired on. For each miss or false alarm, name the clause in the description that caused it and the smallest edit that would fix it. A skill that never fires has no false alarms and is useless, so always report both counts.
Repeats, models, and versions
One answer is one draw from a model that varies. The script runs each case three times by default; report in how many runs the with-skill answer was preferred. A skill preferred in two runs of three is doing something; one preferred in one of three is not established. With one run per case, as fresh agents usually give you, call the findings indicative.
A fresh agent may not be a bare model: it can carry the user's own instructions and other installed skills. Tell the baseline agent to load no skill and read no files, and say in the report that the baseline is the model as configured in that session.
When several models ran, report each separately. A model that does well on average and invents a citation once is not safe, so list blocking findings per model.
To compare versions, run the older version on the same cases (--baseline <older folder>) and apply the three questions to new against old.
Scripts
Code the skill runs during its steps, so results such as calculations come from code rather than from the AI working them out.
scripts/View on GitHub
besci_validate.py
The one validator for the Behavioral Science Skills Library.
#!/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 = "<!-- shared: template/shared/voice.md. Edit it there, then run scripts/check_sync.py --fix. -->"
VOICE_END = "<!-- /shared -->"
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(("#", "<!--")):
continue
if para.startswith(("-", "*", "|", "```", ">")) or re.match(r"\d+\.\s", para):
return ""
return " ".join(para.split())
return ""
def parse_skill(folder: str) -> Skill:
"""Read a skill folder into a Skill. Parsing problems are recorded as findings."""
folder = os.path.abspath(folder.rstrip("/"))
skill = Skill(path=folder, folder=os.path.basename(folder))
md_path = os.path.join(folder, "SKILL.md")
if not os.path.exists(md_path):
skill.error("E001", "SKILL.md is missing. The file must be named exactly SKILL.md, uppercase.")
return skill
with open(md_path, "r", encoding="utf-8") as fh:
text = fh.read()
yaml_text, body = split_frontmatter(text)
if yaml_text is None:
skill.error("E002", "SKILL.md has no YAML frontmatter. It must start with a line '---', the fields, then '---'.")
skill.body = text
else:
try:
fm = yaml.safe_load(yaml_text)
except yaml.YAMLError as exc: # pragma: no cover
skill.error("E002", f"Frontmatter is not valid YAML: {exc}")
fm = {}
if not isinstance(fm, dict):
skill.error("E002", "Frontmatter must be a mapping of field: value.")
fm = {}
skill.frontmatter = fm
md = fm.get("metadata")
skill.metadata = md if isinstance(md, dict) else {}
skill.body = body
skill.sections = split_sections(skill.body)
evals_path = os.path.join(folder, "evals", "evals.json")
if os.path.exists(evals_path):
try:
with open(evals_path, "r", encoding="utf-8") as fh:
skill.evals = json.load(fh)
except json.JSONDecodeError as exc:
skill.error("E029", f"evals/evals.json is not valid JSON: {exc}", file="evals/evals.json")
skill.evals = None
changelog_path = os.path.join(folder, "CHANGELOG.md")
if os.path.exists(changelog_path):
with open(changelog_path, "r", encoding="utf-8") as fh:
skill.changelog = fh.read()
for root, _dirs, files in os.walk(folder):
for f in files:
rel = os.path.relpath(os.path.join(root, f), folder)
if rel.startswith(".") or "/." in rel or "__pycache__" in rel:
continue
skill.files.append(rel)
skill.files.sort()
return skill
# ---------------------------------------------------------------------------
# Rules
# ---------------------------------------------------------------------------
def validate_skill(skill: Skill, taxonomy: dict) -> Skill:
if any(f.code in ("E001",) for f in skill.findings):
return skill
fm, md = skill.frontmatter, skill.metadata
stages = _ids(taxonomy.get("stages"))
types = _ids(taxonomy.get("types"))
statuses = _ids(taxonomy.get("statuses"))
tested = _ids(taxonomy.get("tested_in")) or TESTED_IN_IDS
verbs = [str(v) for v in taxonomy.get("verbs") or []]
io_types = _ids(taxonomy.get("io_types"))
# --- frontmatter: spec compliance -------------------------------------
for key in fm.keys():
if key not in SPEC_TOP_LEVEL_KEYS:
skill.error("E035", f"Frontmatter key '{key}' is not in the Agent Skills spec. Move it under 'metadata:' as a string.")
name = skill.name
if not name:
skill.error("E003", "Frontmatter needs a 'name'.")
else:
if len(name) > 64 or not NAME_RE.match(name):
skill.error("E003", f"name '{name}' must be 1-64 chars of lowercase letters, digits, and single hyphens, not starting or ending with a hyphen.")
if name != skill.folder:
skill.error("E004", f"name '{name}' must match the folder name '{skill.folder}'.")
desc = fm.get("description")
if not isinstance(desc, str) or not desc.strip():
skill.error("E006", "Frontmatter needs a 'description'. It is the trigger rule the AI reads before loading the skill.")
else:
d = desc.strip()
if len(d) > 1024:
skill.error("E006", f"description is {len(d)} characters; the spec caps it at 1024.")
elif len(d) > SOFT_MAX_DESCRIPTION and str(md.get("type", "")).strip() == "atomic":
skill.warn("W044", f"description is {len(d)} characters. Aim for about 500: the 'use when', the 'do not use when', and no citations. besci-navigator does the routing, so it need not hold every phrasing.")
if "<" in d or ">" in d:
skill.error("E006", "description must not contain '<' or '>' characters.")
low = d.lower()
plain = str(md.get("type", "")).strip() == "supporting"
if not plain and "use when" not in low and "use it when" not in low and "use this when" not in low:
skill.error("E007", "description must say when to fire: include a 'Use when ...' clause.")
if not plain and not re.search(r"(do not use|don't use|not for|do not invoke|not when)", low):
skill.error("E008", "description must name the nearest adjacent intent it should NOT handle: include a 'Do not use when ...' clause.")
lic = fm.get("license")
if not lic:
skill.error("E009", "Frontmatter needs 'license'. Use CC-BY-4.0 for skill content (MIT is for code-only skills).")
elif str(lic) not in ALLOWED_LICENSES:
skill.error("E009", f"license '{lic}' is not one of {sorted(ALLOWED_LICENSES)}.")
# --- metadata ----------------------------------------------------------
if not isinstance(fm.get("metadata"), dict):
skill.error("E010", "Frontmatter needs a 'metadata:' mapping with type, stage, version, status, authors, org.")
else:
for k, v in md.items():
if not isinstance(v, (str, int, float)) or isinstance(v, bool):
skill.error("E010", f"metadata.{k} must be a plain string (the spec allows strings only). Lists go in as comma-separated text.")
if k not in KNOWN_METADATA:
skill.warn("W036", f"metadata.{k} is not a field the catalog knows about. It will be kept but not shown.")
for k in REQUIRED_METADATA:
if not str(md.get(k, "")).strip():
skill.error("E010", f"metadata.{k} is required.")
mtype = str(md.get("type", "")).strip()
if mtype and types and mtype not in types:
skill.error("E011", f"metadata.type '{mtype}' must be one of {types}.")
stage = str(md.get("stage", "")).strip()
if stage and stages and stage not in stages:
skill.error("E012", f"metadata.stage '{stage}' must be one of {stages}.")
elif stage == "other" and mtype == "atomic":
skill.error("E013", "metadata.stage 'other' is for supporting skills and meta-skills. Pick one of the seven stages, or set type to 'supporting' if this is a plain skill that many outputs use.")
elif mtype == "supporting" and stage and stage != "other":
skill.error("E013", f"A supporting skill declares stage 'other' (got '{stage}'). If this is a behavioral-science method, set type to 'atomic' and meet the full spec.")
elif mtype == "supporting" and skill.name not in (supporting_skills(skill.path) or {skill.name}):
skill.warn("W013", "This supporting skill is not listed under 'Supporting skills' in docs/canonical-sources.md. Add a row saying why the library carries it.")
version = str(md.get("version", "")).strip()
if version and not SEMVER_RE.match(version):
skill.error("E014", f"metadata.version '{version}' must be semver like 0.1.0 (quote it in YAML: version: \"0.1.0\").")
status = str(md.get("status", "")).strip()
if status and statuses and status not in statuses:
skill.error("E015", f"metadata.status '{status}' must be one of {statuses}.")
if mtype == "atomic":
t_in = str(md.get("tested_in", "")).strip()
legacy = str(md.get("weird", "")).strip()
if t_in:
if t_in not in tested:
skill.error("E018", f"metadata.tested_in '{t_in}' must be one of {tested}.")
if legacy:
skill.v2("040", "metadata.weird is the earlier name of metadata.tested_in. Remove it.")
elif legacy:
if legacy not in TESTED_IN_LEGACY:
skill.error("E018", f"metadata.weird '{legacy}' is not a known value. Use metadata.tested_in with one of {tested}.")
else:
skill.v2("040", f"metadata.weird is now metadata.tested_in. Replace 'weird: {legacy}' with 'tested_in: {TESTED_IN_LEGACY[legacy]}', or the value the skill's evidence scan supports.")
else:
skill.error("E018", f"metadata.tested_in is required for atomic skills: where the evidence has been tested. One of {tested}.")
produces = split_list(md.get("produces"))
if len(produces) != 1:
skill.v2("049", f"metadata.produces must name exactly one output, the thing the output template is (found {len(produces)}).")
if mtype == "atomic" and name and verbs:
first = name.split("-")[0]
if first not in verbs:
skill.error("E005", f"name must start with a verb from taxonomy.yaml (got '{first}'). Verb-first names are the atomicity test; add the verb to the taxonomy in the same PR if it is missing.")
for key in ("consumes", "produces"):
for t in split_list(md.get(key)):
if io_types and t not in io_types:
skill.warn("W019", f"metadata.{key} names '{t}', which is not in taxonomy.yaml io_types. Add it there in this PR, or use an existing id, so skills can chain.")
# A supporting skill is a plain Agent Skill: frontmatter and files are
# checked, and nothing else in the library's spec applies to it.
if mtype == "supporting":
_validate_files(skill)
return skill
# A meta-skill is written in whatever shape serves its job: no fixed
# sections, no voice block, no named test cases. It keeps the bookkeeping
# the site and besci-eval read, which is its test cases and its changelog.
if mtype == "meta":
_validate_named_skills(skill, verbs)
_validate_evals(skill, name, mtype)
_validate_changelog(skill, version)
_validate_files(skill)
return skill
# --- body sections -----------------------------------------------------
present = list(skill.sections.keys())
missing = [s for s in REQUIRED_SECTIONS if s not in present]
for s in missing:
skill.error("E020", f"Required section '## {s}' is missing.")
order = [s for s in present if s in REQUIRED_SECTIONS]
expected = [s for s in REQUIRED_SECTIONS if s in present]
if order != expected:
skill.error("E021", f"Sections must appear in this order: {' -> '.join(REQUIRED_SECTIONS)}.")
for s in REQUIRED_SECTIONS:
if s not in skill.sections:
continue
txt = skill.sections[s].strip()
if not txt:
skill.error("E022", f"Section '## {s}' is empty." + (" Write 'Not applicable: <reason>' if it truly does not apply." if s in NA_ALLOWED_SECTIONS else ""))
continue
if txt.lower().startswith(NA_PREFIX):
reason = txt[len(NA_PREFIX):].strip()
if s not in NA_ALLOWED_SECTIONS:
skill.error("E023", f"Section '## {s}' cannot be 'Not applicable'. Only '{'/'.join(sorted(NA_ALLOWED_SECTIONS))}' can.")
elif len(reason) < NA_MIN_REASON_CHARS:
skill.error("E023", f"Section '## {s}' says 'Not applicable' but gives no real reason. Explain why this skill does not need it.")
what = skill.sections.get("What it does", "")
if what:
first_sentence = re.split(r"(?<=[.!?])\s", what.strip(), maxsplit=1)[0]
if re.search(r"\band\b", first_sentence, flags=re.IGNORECASE):
skill.warn("W024", "The first sentence of 'What it does' contains 'and'. The atomicity rule is one thing, no 'and'. Split the skill or reword.")
when = skill.sections.get("When to use it", "")
if when:
subs = split_subsections(when)
use = bullets(subs.get(USE_WHEN_SUBHEADING, ""))
dont = bullets(subs.get(DONT_USE_WHEN_SUBHEADING, ""))
if len(use) < MIN_USE_WHEN_BULLETS:
skill.error("E025", f"'## When to use it' needs a '### {USE_WHEN_SUBHEADING}' list with at least {MIN_USE_WHEN_BULLETS} bullets of user intents or phrasings (found {len(use)}).")
if len(dont) < MIN_DONT_USE_BULLETS:
skill.error("E026", f"'## When to use it' needs a '### {DONT_USE_WHEN_SUBHEADING}' list with at least {MIN_DONT_USE_BULLETS} bullets of adjacent intents (found {len(dont)}).")
draws = skill.sections.get("What it draws on", "")
if draws and mtype == "atomic" and not CITATION_HINT_RE.search(draws):
skill.warn("W027", "'## What it draws on' has nothing that looks like a citation (no year, DOI, or URL). Name the framework or paper.")
out = skill.sections.get("Output template", "")
if out and "```" not in out:
skill.warn("W028", "'## Output template' has no fenced code block. Show the exact shape of the response in a ```markdown block.")
if out:
_validate_voice(skill, out)
_validate_named_skills(skill, verbs)
if mtype == "atomic":
_validate_v2_body(skill, verbs)
_validate_v2_references(skill)
_validate_evals(skill, name, mtype)
_validate_changelog(skill, version)
_validate_files(skill)
return skill
def _validate_evals(skill: Skill, name: str, mtype: str) -> None:
"""evals/evals.json. An atomic skill carries four named cases; a meta-skill carries at least one, in any shape."""
need = MIN_EVALS_META if mtype == "meta" else MIN_EVALS
if skill.evals is None and not any(f.code == "E029" for f in skill.findings):
what = "at least one for a meta-skill" if mtype == "meta" else "four named cases for an atomic skill"
skill.error("E029", f"evals/evals.json is missing. Every skill ships realistic test prompts: {what}.", file="evals/evals.json")
elif isinstance(skill.evals, dict):
if skill.evals.get("skill_name") != name:
skill.error("E029", f"evals.json 'skill_name' must be '{name}'.", file="evals/evals.json")
cases = skill.evals.get("evals")
if not isinstance(cases, list) or len(cases) < need:
skill.error("E029", f"evals.json needs at least {need} case{'s' if need != 1 else ''} under 'evals' (found {len(cases) if isinstance(cases, list) else 0}).", file="evals/evals.json")
else:
for i, c in enumerate(cases):
for k in ("id", "prompt", "expected_output"):
if not isinstance(c, dict) or not str(c.get(k, "")).strip():
skill.error("E029", f"evals.json case {i} is missing '{k}'.", file="evals/evals.json")
if mtype == "atomic":
_validate_v2_cases(skill, [c for c in cases if isinstance(c, dict)])
def _validate_changelog(skill: Skill, version: str) -> None:
"""CHANGELOG.md exists and its top entry names the current version."""
if skill.changelog is None:
skill.error("E030", "CHANGELOG.md is missing. Add '## 0.1.0 - YYYY-MM-DD' with one line on what this version is.", file="CHANGELOG.md")
return
heads = [ln for ln in skill.changelog.splitlines() if ln.startswith("## ")]
if not heads:
skill.error("E030", "CHANGELOG.md has no '## <version>' entry.", file="CHANGELOG.md")
elif version and version not in heads[0]:
skill.error("E030", f"CHANGELOG.md top entry '{heads[0]}' does not mention the current version {version}. Bump both together.", file="CHANGELOG.md")
def _validate_files(skill: Skill) -> None:
"""File types, sizes, and paths SKILL.md points to. Applies to every skill."""
md_lines = skill.body.count("\n") + 1
if md_lines > MAX_SKILL_MD_LINES:
skill.warn("W031", f"SKILL.md is {md_lines} lines; keep it under {MAX_SKILL_MD_LINES} and move detail into references/.")
if "README.md" in skill.files:
skill.warn("W033", "Skill folders should not contain README.md. Put instructions in SKILL.md or references/.", file="README.md")
total = 0
for rel in skill.files:
full = os.path.join(skill.path, rel)
size = os.path.getsize(full)
total += size
ext = os.path.splitext(rel)[1].lower()
if rel in ("SKILL.md", "CHANGELOG.md") or rel.startswith("evals/"):
pass
if ext not in ALLOWED_EXTENSIONS and not rel.endswith("LICENSE"):
skill.error("E034", f"File type '{ext or rel}' is not allowed in a skill folder.", file=rel)
if size > MAX_FILE_BYTES:
skill.error("E034", f"File is {size // 1024} KB; the cap is {MAX_FILE_BYTES // 1024} KB.", file=rel)
if total > MAX_FOLDER_BYTES:
skill.error("E034", f"Skill folder is {total // 1024} KB; the cap is {MAX_FOLDER_BYTES // 1024} KB.")
# referenced files must exist (relative links and backticked paths into references/, scripts/, assets/)
for ref in set(re.findall(r"(?:\]\(|`)((?:references|scripts|assets|evals)/[A-Za-z0-9_./-]+)", skill.body)):
if not os.path.exists(os.path.join(skill.path, ref)):
skill.error("E032", f"SKILL.md refers to '{ref}' but that file does not exist.")
def _validate_v2_body(skill: Skill, verbs: List[str]) -> None:
"""Rules the November 2026 standard adds to an atomic skill's SKILL.md."""
what = skill.sections.get("What it does", "")
if what and not labelled_line(what, ADDS_LABEL):
skill.v2("041", f"'## What it does' needs a line starting {ADDS_LABEL} that names what the skill makes the AI do that it would not do unprompted: a fixed output, a required check, a decision rule, verified sources, or a search or script call.")
draws = skill.sections.get("What it draws on", "")
if draws:
for label in (EVIDENCE_LABEL, REPLICATION_LABEL):
if not labelled_line(draws, label):
skill.v2("042", f"'## What it draws on' needs a note starting {label}")
counted = []
for heading, text in skill.sections.items():
counted.append(strip_fences(strip_voice_block(text)) if heading == "Output template" else text)
words = word_count("\n".join(counted))
if words > SOFT_MAX_WORDS:
skill.warn("W043", f"SKILL.md is {words} words, not counting the output template. Aim for about {SOFT_MAX_WORDS}: keep a sentence only if deleting it would change what the AI does or what the reader decides, and move evidence detail to references/evidence.md.")
# Inputs are asked for by what they are, not by which skill made them.
own = skill.name
named = set()
for m in SKILL_NAME_IN_TEXT_RE.findall(strip_fences(skill.sections.get("Before you start", ""))):
if m != own and (not verbs or m.split("-")[0] in verbs):
named.add(m)
if named:
skill.warn("W051", f"'## Before you start' names other skills: {', '.join(sorted(named))}. Ask for an input by what it is, not by which skill made it; people bring inputs from anywhere.")
_warn_process_terms(skill, "SKILL.md", skill.body)
def _validate_voice(skill: Skill, out: str) -> None:
"""The shared voice block and a closing that offers next moves."""
if VOICE_START not in out or VOICE_END not in out:
skill.voice("053", "'## Output template' needs the shared voice block after the template: the lines between the template/shared/voice.md markers. Copy the markers from template/skill-template/SKILL.md, then run scripts/check_sync.py --fix to fill them.")
if not re.search(r"^#+\s*" + re.escape(CLOSING_HEADING), out, flags=re.MULTILINE):
skill.voice("054", f"The output template needs a closing headed '{CLOSING_HEADING}': two or three next moves, each with its reason and when it fits, and one or two questions the user could ask next.")
found = sorted({m.group(0).strip("*# ").strip() for m in DIRECTIVE_CLOSING_RE.finditer(strip_voice_block(out))})
if found:
skill.voice("055", f"The output template tells the user what to do ({', '.join(found)}). Offer next moves with reasons under '{CLOSING_HEADING}' instead; the user decides.")
def _validate_named_skills(skill: Skill, verbs: List[str]) -> None:
"""Every skill or workflow a SKILL.md names must exist, so a suggestion never points nowhere."""
names = known_names(skill.path)
if not names:
return
missing = set()
for m in SKILL_NAME_IN_TEXT_RE.findall(skill.body):
looks_like_skill = m.startswith("besci-") or (verbs and m.split("-")[0] in verbs)
if looks_like_skill and m not in names:
missing.add(m)
if missing:
skill.error("E056", f"Names {', '.join(sorted(missing))}, which is not a skill or workflow in this library. Use a current name, or describe the step without one.")
def _warn_process_terms(skill: Skill, rel: str, text: str) -> None:
low = text.lower()
found = [term for term in PROCESS_TERMS if term in low]
if found:
skill.warn("W050", f"Mentions how the skill was drafted or checked ({', '.join(found)}). Keep that in CHANGELOG.md; leave out anything that could not be verified.", file=rel)
def _validate_v2_references(skill: Skill) -> None:
"""Every atomic skill carries a worked example and an evidence file with fixed headings."""
for rel, headings in REQUIRED_REFERENCES.items():
text = read_text(skill, rel)
if text is None:
skill.v2("045", f"{rel} is missing. Every atomic skill carries a worked example and an evidence file.", file=rel)
continue
present = level2_headings(text)
missing = [h for h in headings if h not in present]
if missing:
skill.warn("W046", f"{rel} is missing the heading(s): {', '.join('## ' + h for h in missing)}.", file=rel)
for rel in skill.files:
if rel.startswith("references/") and rel.endswith(".md"):
text = read_text(skill, rel)
if text:
_warn_process_terms(skill, rel, text)
def _validate_v2_cases(skill: Skill, cases: List[dict]) -> None:
"""Four named test cases in a fixed order, each with statements a reviewer can tick."""
names = [str(c.get("name", "")).strip() for c in cases]
if names[:len(CASE_ROLES)] != CASE_ROLES:
skill.v2("047", f"evals.json needs four cases named, in this order: {', '.join(CASE_ROLES)}. Found: {', '.join(n or '(no name)' for n in names[:len(CASE_ROLES)]) or 'none'}.", file="evals/evals.json")
for n in names[len(CASE_ROLES):]:
if not n.startswith(REVIEW_ROLE_PREFIX):
skill.v2("047", f"evals.json: a case after the first four is named '{REVIEW_ROLE_PREFIX} #<issue>' and reproduces what that review reported (found '{n or '(no name)'}').", file="evals/evals.json")
for i, c in enumerate(cases):
label = names[i] or f"case {i}"
asserts = c.get("assertions")
ok = isinstance(asserts, list) and all(isinstance(a, str) and a.strip() for a in asserts)
if not ok or not (MIN_ASSERTIONS <= len(asserts) <= MAX_ASSERTIONS):
skill.v2("048", f"evals.json '{label}': 'assertions' needs {MIN_ASSERTIONS} to {MAX_ASSERTIONS} short statements a reviewer can tick yes or no.", file="evals/evals.json")
if word_count(str(c.get("expected_output", ""))) > SOFT_MAX_EXPECTED_WORDS:
skill.warn("W052", f"evals.json '{label}': 'expected_output' is over {SOFT_MAX_EXPECTED_WORDS} words. Say it in one sentence and put the separate checks in 'assertions'.", file="evals/evals.json")
# ---------------------------------------------------------------------------
# Helpers other tools import
# ---------------------------------------------------------------------------
def trigger_phrases(skill: Skill) -> Tuple[List[str], List[str]]:
"""(should_fire, should_not_fire) phrasings from '## When to use it'."""
subs = split_subsections(skill.sections.get("When to use it", ""))
return bullets(subs.get(USE_WHEN_SUBHEADING, "")), bullets(subs.get(DONT_USE_WHEN_SUBHEADING, ""))
def latest_changelog_entry(skill: Skill) -> str:
if not skill.changelog:
return ""
parts = re.split(r"^## ", skill.changelog, flags=re.MULTILINE)
return ("## " + parts[1]).strip() if len(parts) > 1 else ""
def catalog_entry(skill: Skill) -> dict:
"""The record the site, the navigator snapshot, and besci-eval all read."""
md = skill.metadata
should, should_not = trigger_phrases(skill)
return {
"name": skill.name,
"title": str(md.get("title") or skill.name.replace("-", " ").capitalize()),
"description": str(skill.frontmatter.get("description", "")).strip(),
"license": str(skill.frontmatter.get("license", "")),
"type": str(md.get("type", "")),
"stage": str(md.get("stage", "")),
"version": str(md.get("version", "")),
"status": str(md.get("status", "")),
"authors": split_list(md.get("authors")),
"org": str(md.get("org", "")),
"tested_in": tested_in_value(md),
"tags": split_list(md.get("tags")),
"consumes": split_list(md.get("consumes")),
"produces": split_list(md.get("produces")),
"reviewed_by": split_list(md.get("reviewed_by")),
"sections": {k: v for k, v in skill.sections.items()},
# With no "What it does" section, a meta-skill's opening paragraph stands in,
# and a supporting skill's description does.
"what_it_does": skill.sections.get("What it does", "").strip().split("\n")[0]
or (opening_paragraph(skill.body) if str(md.get("type", "")).strip() == "meta" else "")
or re.split(r"(?<=[.!?])\s", str(skill.frontmatter.get("description", "")).strip(), maxsplit=1)[0],
"what_this_adds": labelled_line(skill.sections.get("What it does", ""), ADDS_LABEL),
"use_when": should,
"do_not_use_when": should_not,
"eval_count": len(skill.evals.get("evals", [])) if isinstance(skill.evals, dict) else 0,
"latest_change": latest_changelog_entry(skill),
"files": skill.files,
"path": os.path.relpath(skill.path, find_repo_root(skill.path) or os.getcwd()),
"errors": [f.as_dict() for f in skill.errors],
"warnings": [f.as_dict() for f in skill.warnings],
}
def discover_skills(root: str) -> List[str]:
"""Every folder directly under root that holds a SKILL.md."""
out = []
if not os.path.isdir(root):
return out
for entry in sorted(os.listdir(root)):
p = os.path.join(root, entry)
if os.path.isdir(p) and os.path.exists(os.path.join(p, "SKILL.md")):
out.append(p)
return out
def validate_path(path: str, taxonomy: dict) -> List[Skill]:
"""Validate one skill folder, or every skill under a folder of skills."""
if os.path.exists(os.path.join(path, "SKILL.md")):
return [validate_skill(parse_skill(path), taxonomy)]
return [validate_skill(parse_skill(p), taxonomy) for p in discover_skills(path)]
# ---------------------------------------------------------------------------
# Reporting
# ---------------------------------------------------------------------------
def report_text(skills: List[Skill]) -> str:
lines = []
n_err = n_warn = 0
for s in skills:
label = s.name or s.folder
if not s.findings:
lines.append(f"PASS {label}")
continue
lines.append(f"{'FAIL' if s.errors else 'WARN'} {label}")
for f in s.findings:
mark = " x " if f.level == "error" else " ! "
lines.append(f"{mark}[{f.code}] {f.file}: {f.message}")
n_err += len(s.errors)
n_warn += len(s.warnings)
lines.append("")
lines.append(f"{len(skills)} skill(s) checked: {n_err} error(s), {n_warn} warning(s).")
if n_err == 0:
lines.append("Structure OK. Content review by a maintainer is still required before merge.")
return "\n".join(lines)
def report_json(skills: List[Skill]) -> dict:
return {
"ok": all(not s.errors for s in skills),
"skills": [
{
"name": s.name or s.folder,
"path": s.path,
"errors": [f.as_dict() for f in s.errors],
"warnings": [f.as_dict() for f in s.warnings],
}
for s in skills
],
}
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description="Validate Behavioral Science Skills Library skill folders.")
ap.add_argument("paths", nargs="*", help="Skill folder(s) or a folder of skills. Default: skills/ under the repo root.")
ap.add_argument("--json", action="store_true", help="Machine-readable output.")
ap.add_argument("--taxonomy", help="Path to taxonomy.yaml.")
ap.add_argument("--warnings-as-errors", action="store_true")
args = ap.parse_args(argv)
taxonomy = load_taxonomy(args.taxonomy)
paths = args.paths
if not paths:
root = find_repo_root(os.getcwd())
if not root:
sys.stderr.write("No skill path given and no taxonomy.yaml found upward from here.\n")
return 2
paths = [os.path.join(root, "skills")]
skills: List[Skill] = []
for p in paths:
if not os.path.exists(p):
sys.stderr.write(f"Path not found: {p}\n")
return 2
skills.extend(validate_path(p, taxonomy))
if not skills:
sys.stderr.write("No skills found (a skill is a folder containing SKILL.md).\n")
return 2
if args.json:
print(json.dumps(report_json(skills), indent=2))
else:
print(report_text(skills))
failed = any(s.errors for s in skills) or (args.warnings_as_errors and any(s.warnings for s in skills))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
run_evals.py
Diagnose a library skill through the Claude API.
#!/usr/bin/env python3
"""
run_evals.py — diagnose a library skill through the Claude API.
Usage:
python run_evals.py path/to/skill [--models claude-opus-5-5 claude-sonnet-5-5]
[--runs 3] [--judge claude-opus-5-5]
[--all-cases] [--cold "a request"] [--no-cold]
[--skip-bare] [--baseline path/to/old-skill]
[--catalog path/to/catalog.md]
[--skip-trigger] [--skip-output] [--effort medium]
[--out DIR] [--dry-run]
What it does:
1. Structure: runs besci_validate.py (bundled next to this script).
2. Triggering: for each request the skill should and should not fire on,
asks a judge model whether it would load this skill, given its
description and the descriptions of the other skills in the catalog
snapshot.
3. On the job: runs each case twice on each model, once with SKILL.md
loaded and once with no skill, and asks the judge to compare the two
answers without being told which is which: what the skill changed,
whether the change is what the skill promises, which answer a
practitioner would prefer, and which of the case's assertions each
answer passes. --baseline adds the same comparison against an older
version of the skill.
Cases: "Full run" and "Missing context" (or the first two cases when the
skill does not name them), plus one cold case the script writes from the
skill's description alone. --all-cases runs every case. A case named
"Wrong skill", or one with "should_trigger": false, is a triggering test and
is not run for output.
Writes <skill>-workspace/eval-<timestamp>/report.md and results.json.
Requires: pip install anthropic pyyaml. Credentials: ANTHROPIC_API_KEY, or an
`ant auth login` profile (the SDK picks it up with no env var).
Cost: this spends money. --dry-run prints the plan and the number of calls,
makes none, and writes nothing unless --out is given. Roughly: cases x models x runs x 3 for the comparison with
no skill (two answers and one judgement), plus one call per trigger request.
Limits: the with-skill run loads SKILL.md only, not the skill's reference
files, and every case is a single turn.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import os
import re
import statistics
import sys
from typing import Dict, List, Optional
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import besci_validate as bv # noqa: E402
DEFAULT_MODEL = "claude-opus-5-5"
JUDGING_PATH = os.path.join(os.path.dirname(HERE), "references", "judging.md")
DEFAULT_CASES = ["Full run", "Missing context"]
TRIGGER_ONLY_CASE = "Wrong skill"
# What the model is told when a case runs with no skill loaded.
NO_SKILL_SYSTEM = "Answer the user's request."
# ---------------------------------------------------------------------------
# API helpers
# ---------------------------------------------------------------------------
def get_client():
try:
import anthropic
except ImportError:
sys.stderr.write("pip install anthropic\n")
sys.exit(2)
return anthropic.Anthropic()
def call(client, model: str, system: str, user: str, effort: str, max_tokens: int = 16000) -> Dict:
"""One non-streaming Messages call. Returns {text, stop_reason, usage}."""
resp = client.messages.create(
model=model,
max_tokens=max_tokens,
system=system,
output_config={"effort": effort},
messages=[{"role": "user", "content": user}],
)
text = "".join(b.text for b in resp.content if getattr(b, "type", "") == "text")
return {
"text": text,
"stop_reason": resp.stop_reason,
"input_tokens": resp.usage.input_tokens,
"output_tokens": resp.usage.output_tokens,
}
def parse_json(text: str) -> Optional[dict]:
"""Find the first JSON object in a response; tolerate fences and prose."""
m = re.search(r"\{.*\}", text, flags=re.DOTALL)
if not m:
return None
try:
return json.loads(m.group(0))
except json.JSONDecodeError:
return None
# ---------------------------------------------------------------------------
# The skill: its promise, its cases, its neighbors
# ---------------------------------------------------------------------------
def load_skill(path: str) -> bv.Skill:
return bv.validate_skill(bv.parse_skill(path), bv.load_taxonomy())
def promise(skill: bv.Skill) -> str:
"""What the skill says it makes the AI do: its 'What this adds' line, or how it describes itself."""
e = bv.catalog_entry(skill)
return e["what_this_adds"] or e["what_it_does"] or e["description"]
def all_cases(skill: bv.Skill) -> List[dict]:
cases = (skill.evals or {}).get("evals", []) if isinstance(skill.evals, dict) else []
return [c for c in cases if isinstance(c, dict) and str(c.get("prompt", "")).strip()]
def should_fire(case: dict) -> bool:
"""Whether a test case is a request the skill should take."""
if "should_trigger" in case:
return bool(case["should_trigger"])
if str(case.get("name", "")).strip() == TRIGGER_ONLY_CASE:
return False
expected = str(case.get("expected_output", "")).lower()
return not any(k in expected for k in ("does not fire", "should not fire", "not a library skill", "does not take over"))
def output_cases(skill: bv.Skill, every: bool) -> List[dict]:
"""The cases run for output: requests the skill should take. By default the two that show most."""
cases = [c for c in all_cases(skill) if should_fire(c)]
if every:
return cases
named = [c for c in cases if str(c.get("name", "")).strip() in DEFAULT_CASES]
return named if named else cases[:len(DEFAULT_CASES)]
def case_assertions(case: dict) -> List[str]:
out = []
for a in case.get("assertions") or []:
text = (a.get("text") or a.get("description") or "") if isinstance(a, dict) else str(a)
if text.strip():
out.append(text.strip())
return out
def neighbor_descriptions(catalog_path: Optional[str], this_name: str) -> List[Dict[str, str]]:
"""Name and description pairs from the navigator's catalog.md snapshot."""
if not catalog_path or not os.path.exists(catalog_path):
return []
text = open(catalog_path, encoding="utf-8").read()
details = text.split("## Skill details", 1)[-1].split("\n## ", 1)[0]
out = []
for block in re.split(r"^### ", details, flags=re.MULTILINE)[1:]:
name = block.split("\n", 1)[0].strip().strip("`")
if name == this_name:
continue
m = re.search(r"\*\*Description[^*]*:\*\*\s*(.+?)(?:\n\n|\n\*\*|\Z)", block, flags=re.DOTALL)
if m:
out.append({"name": name, "description": " ".join(m.group(1).split())})
return out
COLD_SYSTEM = (
"You write one test request for an AI skill. You see only the skill's name and description. "
"Write what a busy program officer at an NGO would type when they need this: plain words, a real-sounding "
"program with a place and numbers, something left out that they would not think to say, and none of the "
"method's vocabulary. Three to six sentences. Reply with the request only."
)
def write_cold_case(client, judge: str, skill: bv.Skill, effort: str, dry: bool) -> str:
if dry:
return "(a cold case is written at run time from the description alone)"
user = f"Skill: {skill.name}\nDescription: {skill.frontmatter.get('description', '')}"
return call(client, judge, COLD_SYSTEM, user, effort, max_tokens=1000)["text"].strip()
# ---------------------------------------------------------------------------
# Check 1: structure
# ---------------------------------------------------------------------------
def check_structure(skill_dir: str) -> Dict:
skills = bv.validate_path(skill_dir, bv.load_taxonomy())
return {
"report": bv.report_text(skills),
"ok": all(not s.errors for s in skills),
"errors": [f"[{f.code}] {f.file}: {f.message}" for s in skills for f in s.errors],
"warnings": [f"[{f.code}] {f.file}: {f.message}" for s in skills for f in s.warnings],
}
# ---------------------------------------------------------------------------
# Check 2: triggering
# ---------------------------------------------------------------------------
def trigger_cases(skill: bv.Skill, cold: List[str]) -> List[Dict]:
should, should_not = bv.trigger_phrases(skill)
cases = [{"phrase": p, "should_fire": True, "source": "use it when"} for p in should]
cases += [{"phrase": p, "should_fire": False, "source": "do not use it when"} for p in should_not]
for c in all_cases(skill):
cases.append({"phrase": c["prompt"], "should_fire": should_fire(c), "source": f"test case {c.get('name') or c.get('id')}"})
cases += [{"phrase": p, "should_fire": True, "source": "cold case"} for p in cold]
return cases
TRIGGER_SYSTEM = (
"You are the skill-selection step of an AI assistant. You see a user's request and the "
"descriptions of the skills installed. Decide whether you would load the skill named "
"TARGET for this request. Answer with JSON only: {\"fire\": true|false, \"reason\": \"one line\"}."
)
def check_trigger(client, judge: str, skill: bv.Skill, neighbors: List[Dict], cold: List[str], effort: str, dry: bool) -> Dict:
desc = str(skill.frontmatter.get("description", ""))
neigh = "\n".join(f"- {n['name']}: {n['description']}" for n in neighbors) or "- (no other skills installed)"
results = []
for c in trigger_cases(skill, cold):
if dry:
results.append({**c, "fired": None, "reason": "dry run"})
continue
user = (f"TARGET skill: {skill.name}\nTARGET description: {desc}\n\nOther installed skills:\n{neigh}\n\n"
f"User request: {c['phrase']}\n\nWould you load TARGET? JSON only.")
j = parse_json(call(client, judge, TRIGGER_SYSTEM, user, effort, max_tokens=512)["text"]) or {}
results.append({**c, "fired": bool(j.get("fire")), "reason": str(j.get("reason", ""))[:240]})
should = [r for r in results if r["should_fire"]]
should_not = [r for r in results if not r["should_fire"]]
return {
"cases": results,
"neighbors": len(neighbors),
"hits": sum(1 for r in should if r["fired"]), "should": len(should),
"false_alarms": sum(1 for r in should_not if r["fired"]), "should_not": len(should_not),
}
# ---------------------------------------------------------------------------
# Check 3: on the job
# ---------------------------------------------------------------------------
def load_judging() -> str:
if os.path.exists(JUDGING_PATH):
return open(JUDGING_PATH, encoding="utf-8").read()
return ("Compare the two answers for the job the request describes. Blocking findings: an invented citation, "
"a full answer when the request lacked something the skill needs, a missed handoff to a specialist.")
JUDGE_SYSTEM = (
"You compare two answers, A and B, to the same request. They were written under different conditions, such as "
"with a skill loaded and without it, and you are not told which is which. Judge them for the job the request "
"describes, following the guidance you are given. Be strict and quote the answers. Return JSON only, in this shape: "
"{\"difference\": \"one or two sentences on what A does that B does not, and the reverse\", "
"\"prefer\": \"A\"|\"B\"|\"tie\", \"why\": \"one sentence, in terms of the job\", "
"\"A\": {\"keeps_promise\": true|false, \"assertions\": [true|false for each numbered assertion, in order], "
"\"blocking\": [\"...\"], \"excerpt\": \"the most telling quote, under 40 words\"}, \"B\": {the same keys}}"
)
def a_first(*parts) -> bool:
"""Which answer is shown as A. Fixed by the case, model, and run, so a rerun shows the same order."""
return int(hashlib.sha256("|".join(str(p) for p in parts).encode()).hexdigest(), 16) % 2 == 0
def judge_pair(client, judge: str, guidance: str, skill: bv.Skill, skill_md: str, case: dict, asserts: List[str],
with_text: str, other_text: str, with_is_a: bool, effort: str) -> Dict:
a, b = (with_text, other_text) if with_is_a else (other_text, with_text)
user = (
f"GUIDANCE:\n{guidance}\n\nTHE SKILL'S PROMISE (what it says it makes the AI do):\n{promise(skill)}\n\n"
f"THE SKILL'S TEXT (a source is the skill's own only if it appears here):\n{skill_md}\n\n"
f"REQUEST:\n{case['prompt']}\n\nWHAT A GOOD ANSWER IS:\n{case.get('expected_output') or '(not stated; judge from the request and the promise)'}\n\n"
"ASSERTIONS (answer true or false for each, for A and for B):\n"
+ ("\n".join(f"{n}. {t}" for n, t in enumerate(asserts, 1)) or "(none)")
+ f"\n\nANSWER A:\n{a}\n\nANSWER B:\n{b}\n\nCompare them. JSON only."
)
j = parse_json(call(client, judge, JUDGE_SYSTEM, user, effort, max_tokens=4000)["text"]) or {}
def side(key: str) -> Dict:
d = j.get(key) if isinstance(j.get(key), dict) else {}
verdicts = d.get("assertions") if isinstance(d.get("assertions"), list) else []
verdicts = [bool(v) for v in verdicts[:len(asserts)]] + [False] * max(0, len(asserts) - len(verdicts))
return {"keeps_promise": d.get("keeps_promise"), "assertions": verdicts,
"blocking": [str(x) for x in d.get("blocking") or []], "excerpt": str(d.get("excerpt", ""))[:400]}
prefer = str(j.get("prefer", "tie")).strip().upper()
winner = "tie" if prefer not in ("A", "B") else ("with" if (prefer == "A") == with_is_a else "other")
return {"difference": str(j.get("difference", "")), "why": str(j.get("why", "")), "prefer": winner,
"with": side("A" if with_is_a else "B"), "other": side("B" if with_is_a else "A")}
def check_output(client, models: List[str], runs: int, judge: str, skill: bv.Skill, skill_md: str, cases: List[dict],
others: Dict[str, str], effort: str, dry: bool) -> Dict:
"""Run every case with the skill and under each other condition (no skill, an older version), and compare.
`others` maps a condition's label to the system prompt it runs with."""
guidance = load_judging()
out = {"conditions": list(others), "models": {}}
for model in models:
per_case = []
for c in cases:
asserts = case_assertions(c)
run_results = []
for i in range(runs):
if dry:
continue
w = call(client, model, skill_md, c["prompt"], effort)
r = {"run": i + 1, "with_output": w["text"], "refused": w["stop_reason"] == "refusal", "comparisons": {}}
for label, system in others.items():
o = call(client, model, system, c["prompt"], effort)
cmp_ = judge_pair(client, judge, guidance, skill, skill_md, c, asserts, w["text"], o["text"],
a_first(c.get("id"), model, i, label), effort)
cmp_["other_output"] = o["text"]
r["comparisons"][label] = cmp_
if not others: # nothing to compare with: grade the with-skill answer against itself for assertions only
r["comparisons"]["(alone)"] = judge_pair(client, judge, guidance, skill, skill_md, c, asserts, w["text"],
"(no second answer was run; grade A only and answer 'tie')", True, effort)
run_results.append(r)
per_case.append(summarize_case(c, asserts, run_results, list(others) or ["(alone)"]))
out["models"][model] = {"cases": per_case}
return out
def summarize_case(case: dict, asserts: List[str], runs: List[Dict], labels: List[str]) -> Dict:
def med(values):
return statistics.median(values) if values else None
comparisons = {}
for label in labels:
cmps = [r["comparisons"][label] for r in runs if label in r["comparisons"]]
failing = [a for n, a in enumerate(asserts)
if cmps and sum(1 for x in cmps if not x["with"]["assertions"][n]) * 2 > len(cmps)]
comparisons[label] = {
"runs": len(cmps),
"prefer_with": sum(1 for x in cmps if x["prefer"] == "with"),
"prefer_other": sum(1 for x in cmps if x["prefer"] == "other"),
"ties": sum(1 for x in cmps if x["prefer"] == "tie"),
"keeps_promise": sum(1 for x in cmps if x["with"]["keeps_promise"]),
"assertions_with": med([sum(x["with"]["assertions"]) for x in cmps]),
"assertions_other": med([sum(x["other"]["assertions"]) for x in cmps]),
"failing_assertions": failing,
"blocking": sorted({b for x in cmps for b in x["with"]["blocking"]}),
"difference": next((x["difference"] for x in cmps if x["difference"]), ""),
"why": next((x["why"] for x in cmps if x["why"]), ""),
"excerpt_with": next((x["with"]["excerpt"] for x in cmps if x["with"]["excerpt"]), ""),
"excerpt_other": next((x["other"]["excerpt"] for x in cmps if x["other"]["excerpt"]), ""),
}
return {"id": case.get("id"), "name": str(case.get("name") or f"case {case.get('id')}"), "prompt": case["prompt"],
"assertions": asserts, "runs": runs, "comparisons": comparisons,
"refused": any(r.get("refused") for r in runs)}
# ---------------------------------------------------------------------------
# Report
# ---------------------------------------------------------------------------
def of(n, total) -> str:
return f"{n:g} of {total}" if n is not None else f"n/a of {total}"
def clip(text: str, n: int) -> str:
text = " ".join(str(text).split())
return text if len(text) <= n else text[: n - 1].rstrip() + "…"
def findings(structure: Dict, trigger: Optional[Dict], output: Optional[Dict]) -> Dict:
"""What decides the verdict, and the list of things to fix, most important first."""
fixes: List[str] = []
blocking: List[str] = []
not_preferred: List[str] = []
compared = 0
if output:
for m, d in output["models"].items():
for p in d["cases"]:
if p.get("refused"):
blocking.append(f"{p['name']} on {m}: the model refused the request with the skill loaded.")
for label, c in p["comparisons"].items():
blocking += [f"{p['name']} on {m}: {b}" for b in c["blocking"]]
if label == "no skill" and c["runs"]:
compared += 1
if c["prefer_with"] * 2 <= c["runs"]:
not_preferred.append(f"{p['name']} on {m}: the answer with the skill was preferred in {of(c['prefer_with'], c['runs'])} runs. {clip(c['why'], 200)}")
fixes += [f"Blocking: {b}" for b in blocking]
fixes += [f"Validator: {e}" for e in structure["errors"]]
misses, alarms = [], []
if trigger:
misses = [c for c in trigger["cases"] if c["should_fire"] and c["fired"] is False]
alarms = [c for c in trigger["cases"] if not c["should_fire"] and c["fired"]]
fixes += [f"The description misses a request it should take: \"{clip(c['phrase'], 110)}\". {clip(c['reason'], 160)}" for c in misses]
fixes += [f"The description takes a request it should leave: \"{clip(c['phrase'], 110)}\". {clip(c['reason'], 160)}" for c in alarms]
fixes += [f"Adds little: {n}" for n in not_preferred]
if output:
for m, d in output["models"].items():
for p in d["cases"]:
for c in p["comparisons"].values():
fixes += [f"{p['name']} on {m} fails its check: \"{clip(a, 140)}\"" for a in c["failing_assertions"]]
return {"fixes": fixes, "blocking": blocking, "misses": misses, "alarms": alarms,
"not_preferred": not_preferred, "compared": compared}
def verdict_of(args, structure: Dict, trigger: Optional[Dict], output: Optional[Dict], f: Dict) -> tuple:
if args.dry_run:
return "dry run", "no calls were made"
if not trigger and not output:
return ("fix first", "the validator reports errors") if not structure["ok"] else ("could not test", "only the structure was checked")
if f["blocking"]:
return "fix first", clip(f["blocking"][0], 200)
if not structure["ok"]:
return "fix first", "the validator reports errors"
if f["compared"] and len(f["not_preferred"]) * 2 > f["compared"]:
return "fix first", "on most cases the answer with the skill was not preferred over the model alone"
if trigger and (trigger["should"] and trigger["hits"] / trigger["should"] < 0.8
or trigger["should_not"] and trigger["false_alarms"] / trigger["should_not"] > 0.2):
return "fix first", "the description fires on the wrong requests"
if f["fixes"]:
return "ready", "the checks pass, with smaller things to fix listed below"
return "ready", "the structure passes, the description fires where it should, and the skill changes the answers in the way it promises"
def write_report(path: str, skill: bv.Skill, args, structure: Dict, trigger: Optional[Dict], output: Optional[Dict]) -> str:
f = findings(structure, trigger, output)
verdict, why = verdict_of(args, structure, trigger, output, f)
lines = [f"# Diagnosis: {skill.name} v{skill.metadata.get('version', '?')} ({dt.date.today().isoformat()})", "",
f"**Verdict:** {verdict}. {why[0].upper() + why[1:]}.".replace("..", "."), ""]
lines += ["## Structure", ""]
kind = str(skill.metadata.get("type", "")).strip()
scope = {"meta": " A meta-skill is checked on its frontmatter, files, test cases, and changelog only.",
"supporting": " A supporting skill is checked on its frontmatter and files only."}.get(kind, "")
if structure["ok"]:
lines += [f"The validator passes{', with ' + str(len(structure['warnings'])) + ' warning(s)' if structure['warnings'] else ''}.{scope}"]
else:
lines += [f"The validator reports {len(structure['errors'])} error(s).{scope}"]
lines += [f"- {clip(x, 300)}" for x in structure["errors"] + structure["warnings"]] + [""]
if trigger:
lines += ["## Triggering", ""]
if args.dry_run:
lines += [f"{len(trigger['cases'])} requests would be judged against {trigger['neighbors']} other skills' descriptions.", ""]
else:
lines += [f"It fired on {of(trigger['hits'], trigger['should'])} requests it should take, and on "
f"{of(trigger['false_alarms'], trigger['should_not'])} it should leave, judged next to {trigger['neighbors']} other skills' descriptions."]
lines += [f"- Missed ({c['source']}): \"{clip(c['phrase'], 140)}\". {clip(c['reason'], 200)}" for c in f["misses"]]
lines += [f"- False alarm ({c['source']}): \"{clip(c['phrase'], 140)}\". {clip(c['reason'], 200)}" for c in f["alarms"]]
lines += [""]
if output:
lines += ["## On the job", ""]
shown = False
for m, d in output["models"].items():
for p in d["cases"]:
head = f"**{p['name']}**" + (f" ({m})" if len(output["models"]) > 1 else "")
if args.dry_run:
lines += [f"{head}: \"{clip(p['prompt'], 160)}\""]
continue
n_a = len(p["assertions"])
for label, c in p["comparisons"].items():
if label == "(alone)":
lines += [f"{head}: the checks passed {of(c['assertions_with'], n_a)}. No comparison was run."]
continue
lines += [f"{head}, with the skill against {label}: the answer with the skill was preferred in {of(c['prefer_with'], c['runs'])} run(s)"
f"{', tied in ' + str(c['ties']) if c['ties'] else ''}, and did what the skill promises in {of(c['keeps_promise'], c['runs'])}."
+ (f" Checks passed: {of(c['assertions_with'], n_a)} with the skill, {of(c['assertions_other'], n_a)} with {label}." if n_a else "")
+ f" {clip(c['difference'], 320)}"]
if not shown and c["excerpt_with"] and c["excerpt_other"]:
lines += ["", f"> With the skill: \"{clip(c['excerpt_with'], 280)}\"", ">", f"> With {label}: \"{clip(c['excerpt_other'], 280)}\""]
shown = True
lines += [""]
if args.dry_run:
lines += [""]
lines += ["## What to fix", ""]
lines += [f"{i}. {x}" for i, x in enumerate(f["fixes"][:3], 1)] or ["Nothing found on these cases."]
if len(f["fixes"]) > 3:
lines += [f"", f"{len(f['fixes']) - 3} smaller finding(s) are in results.json."]
lines += ["", "These are proposals. The author decides what to change, and `besci-skill-creator` helps revise.", ""]
lines += ["## How this was run", "",
f"By script through the API: {', '.join(args.models)}, {args.runs} run(s) per case, judged by {args.judge}. "
"The with-skill run loads SKILL.md only, not the skill's reference files, and every case is one turn. "
"Which answer is better is a model's judgment and not a practitioner's; expert reviews on the library site are the test of that. "
"Full answers are in results.json beside this report."]
text = "\n".join(lines) + "\n"
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
return verdict
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("skill")
ap.add_argument("--models", nargs="+", default=[DEFAULT_MODEL])
ap.add_argument("--judge", default=DEFAULT_MODEL)
ap.add_argument("--runs", type=int, default=3)
ap.add_argument("--all-cases", action="store_true", help="Run every case the skill should take, not only the default two")
ap.add_argument("--cold", action="append", default=[], help="A cold-case request to use instead of having one written (repeatable)")
ap.add_argument("--no-cold", action="store_true", help="Do not add a cold case")
ap.add_argument("--skip-bare", action="store_true", help="Do not run the cases with no skill loaded (halves the cost, and loses the comparison)")
ap.add_argument("--baseline", help="Path to an older version of the skill folder to compare against as well")
ap.add_argument("--no-skill-baseline", action="store_true", help=argparse.SUPPRESS) # earlier flag; the comparison is now the default
ap.add_argument("--catalog", help="Path to catalog.md (default: besci-navigator/references/catalog.md if found)")
ap.add_argument("--effort", default="medium", choices=["low", "medium", "high", "xhigh", "max"])
ap.add_argument("--skip-trigger", action="store_true")
ap.add_argument("--skip-output", action="store_true")
ap.add_argument("--out", help="Output directory (default: <skill>-workspace/eval-<timestamp>)")
ap.add_argument("--dry-run", action="store_true", help="Plan only; make no API calls")
args = ap.parse_args(argv)
skill = load_skill(args.skill)
if not skill.name:
sys.stderr.write("Not a skill folder (no valid SKILL.md).\n")
return 2
skill_md = open(os.path.join(skill.path, "SKILL.md"), encoding="utf-8").read()
structure = check_structure(skill.path)
catalog = args.catalog
if not catalog:
root = bv.find_repo_root(skill.path) or os.getcwd()
cand = os.path.join(root, "skills", "besci-navigator", "references", "catalog.md")
catalog = cand if os.path.exists(cand) else None
neighbors = neighbor_descriptions(catalog, skill.name)
others: Dict[str, str] = {}
if not args.skip_bare:
others["no skill"] = NO_SKILL_SYSTEM
if args.baseline:
old = load_skill(args.baseline)
others[f"the older version ({old.metadata.get('version', '?')})"] = open(os.path.join(old.path, "SKILL.md"), encoding="utf-8").read()
cases = [] if args.skip_output else output_cases(skill, args.all_cases)
n_cold = len(args.cold) if args.cold else (0 if args.no_cold else 1)
write_cold = 0 if (args.cold or args.no_cold) else 1
n_out_cases = 0 if args.skip_output else len(cases) + n_cold
if not args.skip_output and n_out_cases == 0:
sys.stderr.write(f"{skill.name} has no test case to run and no cold case. Add a case, or drop --no-cold.\n")
return 1
per_run = 1 + 2 * len(others) if others else 2
n_output = n_out_cases * len(args.models) * args.runs * per_run
n_trigger = 0 if args.skip_trigger else len(trigger_cases(skill, [""] * n_cold))
print(f"Plan: {skill.name} v{skill.metadata.get('version', '?')} | models {args.models} | judge {args.judge} | runs {args.runs}")
print(f"Cases run for output: {', '.join(str(c.get('name') or c.get('id')) for c in cases) or 'none'}" + (f", plus {n_cold} cold case(s)" if n_cold and not args.skip_output else ""))
print(f"Compared with: {', '.join(others) or 'nothing'}")
print(f"Calls: cold case {write_cold}, trigger {n_trigger}, on the job {n_output}, total {write_cold + n_trigger + n_output}")
if args.dry_run and not args.out:
print("Dry run: no calls were made and nothing was written. Add --out DIR to save the plan.")
return 0
client = None if args.dry_run else get_client()
cold = list(args.cold)
if write_cold:
cold = [write_cold_case(client, args.judge, skill, args.effort, args.dry_run)]
if not args.skip_output:
cases = cases + [{"id": f"cold-{i}", "name": "Cold case", "prompt": p, "expected_output": "", "assertions": []} for i, p in enumerate(cold, 1)]
trigger = None if args.skip_trigger else check_trigger(client, args.judge, skill, neighbors, cold, args.effort, args.dry_run)
output = None if args.skip_output else check_output(client, args.models, args.runs, args.judge, skill, skill_md, cases, others, args.effort, args.dry_run)
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M")
out_dir = args.out or os.path.join(os.path.dirname(skill.path), f"{skill.name}-workspace", f"eval-{stamp}")
os.makedirs(out_dir, exist_ok=True)
with open(os.path.join(out_dir, "results.json"), "w", encoding="utf-8") as fh:
json.dump({"skill": skill.name, "version": skill.metadata.get("version"), "args": vars(args),
"structure": structure, "trigger": trigger, "output": output}, fh, indent=2, default=str)
verdict = write_report(os.path.join(out_dir, "report.md"), skill, args, structure, trigger, output)
print(f"Verdict: {verdict}")
print(f"Wrote {out_dir}/report.md")
return 0
if __name__ == "__main__":
sys.exit(main())
Version history
What changed in each version, newest first. An entry that answers an issue or review links to it.
CHANGELOG.mdView on GitHub
0.4.0 - 2026-11-25
Rewritten in its own shape, without the eight sections or the shared voice block. The main test is now a comparison: each case is answered with the skill and with no skill, and the evaluator asks what the skill changed, whether the change is what the skill promises, and which answer a practitioner would prefer. The nine-criterion rubric scored out of 18 is gone, and references/judging.md replaces references/rubric.md; three blocking findings remain (an invented citation, answering when it should have asked, a missed handoff). The evaluator runs three cases by default: Full run, Missing context, and a cold case it writes from the description alone before reading the skill. It runs them with fresh agents where it can, with the script for repeats and model comparisons, and in conversation otherwise. The report is one screen with a fixed order and gives triggering as counts in words. Because the comparison needs no fixed sections, it works on meta-skills and supporting skills. In run_evals.py the comparison with no skill is the default (--skip-bare turns it off), the judge compares the two answers without being told which is which, a cold case is written unless --cold or --no-cold is given, --all-cases runs every case, a case can carry "should_trigger": false, and the neighbor descriptions are read from the catalog snapshot correctly. Edited with Claude.
0.3.0 - 2026-11-11
Adds a ninth rubric criterion, Conversation: answers what was asked before offering the run, marks the run, says where claims come from, and ends with next moves and their reasons. "Asked first" no longer penalizes a brief answer before the questions. Totals are out of 18; "ready" is a median of 16 or more. The report opens with a few plain sentences, "Next actions for the author" becomes "What would raise the score", and it ends with next moves and carries the shared voice block. Bundles the updated validator and checklist. Edited with Claude.
0.2.0 - 2026-11-10
Grades each output against the test case's own assertions as well as the rubric, and adds --no-skill-baseline, which runs the same cases with no skill loaded to show what the skill adds. Expects the four named test cases of the November 2026 standard. Edited with Claude.
0.1.0 - 2026-10-08
First version. Structure, triggering, and output-quality checks; rubric derived from the eight sections; API runner for cross-model comparison with baseline support. Five evals. Not yet reviewed. The partnership plans to deepen this skill together once real skills exist to evaluate; expert ratings are a later-phase feature.
Reviews
Expert reviews come from behavioral scientists at The Agency Fund and Irrational Labs and are kept as issues on GitHub; each shows whether a later version of the skill answered it. Ratings and comments come from anyone who has used the skill.
Expert reviews
Expert reviews of this skill are kept as issues on GitHub.