Behavioral science skill creator

besci-skill-creator

Meta-skillv0.5.0metadraftThe Agency Fund

Grills an author about a behavioral-science method, then drafts a skill folder that meets the library's standard.

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

Nothing declared.

besci-skill-creator

Produces

skill-draftSkill draftUsed by besci-eval

See it on the map

Install

/plugin marketplace add agency-fund/besci-skills
/plugin install besci-skills@besci-skills

Interview the author relentlessly about every aspect of their method until you reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one by one. The root is the four gates in section 1 of references/skill-spec.md: the skill does one thing, the task is common, it adds something, and it is distinct from every skill in the catalog.

Ask the questions one at a time, waiting for the author's answer to each before asking the next. Asking multiple questions at once is bewildering. A reply holds one question and nothing after it.

Format a question like so:

❓ **<question title>**: <question body, including the choices when there are some>

➡️ <your recommended answer>

For each question that is a decision, give your recommended answer. A question about the author's own experience of the method (where it goes wrong, what a good result looks like) has no recommended answer: ask it plainly, leave the ➡️ line out, and do not guess. Ask about the method in the author's terms, not about the spec's sections; references/interview-guide.md has questions that work.

If a fact can be found in the environment (the sources list, the catalog, a citation, a file they shared, etc.), look it up rather than asking the author, and say what you found. The decisions are the author's: put each one to them and wait for the answer.

Do not draft until the author confirms you have reached a shared understanding. Then follow references/drafting.md.

Cite this skill

Zezhen Wu (2026). Behavioral science skill creator (version 0.5.0) [AI skill]. Behavioral Science Skills Library, The Agency Fund and Irrational Labs. https://besci-skills.vercel.app/skills/besci-skill-creator/

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 method and no source material

The request

I'm a behavioral scientist at Irrational Labs. I want to turn the 'saying-is-believing' technique from Walton & Cohen's belonging work into a skill for the besci-skills library. Users would be NGO program staff designing a storytelling intervention. Can you help me build it? I'm in Claude Code.

What a good answer includes

The interview starts and nothing is drafted: one question on the first gate (what the skill does in one sentence), with a recommended answer, and the gates it can check itself (common, distinct) reported as looked up rather than asked.

Checks on the answer

  • Asks exactly one question and stops.
  • The question is about a gate and carries a recommended answer.
  • The question is about the method, not about sections of the spec.
  • Does not ask the author which sources name the task or whether a similar skill exists; it looks these up or says it will.
  • Does not write SKILL.md or any other file yet.

Test case 2: A workflow presented as a skill

The request

Make me a skill that designs a complete behavior change program for an NGO, from understanding the problem to designing the intervention and planning the evaluation.

What a good answer includes

The first gate fails: this is several skills. The creator proposes the split, notes that most of the pieces already exist in the library, and asks which one to build now. It does not draft one large skill.

Checks on the answer

  • Says the request is more than one skill.
  • Proposes a split into named pieces.
  • Asks which piece to build now, or points to the existing skills or a workflow that cover it.
  • Does not draft a skill that covers the whole program.

Test case 3: A revision after a review

The request

The reviewer said the trigger rule on my skill draft-norms-vignette is too vague and it fires on requests that belong to write-social-norm-message. Can you fix it? The repo is open here.

What a good answer includes

The creator reads the skill's folder, changelog, and any open expert review first, then asks one question, with a recommended answer, about what should change before it edits anything.

Checks on the answer

  • Reads, or says it will read, the skill folder and its changelog before proposing a change.
  • Asks one question about the intended change before editing a file.
  • Does not rewrite parts of the skill the request did not mention.
  • Mentions that the version and the changelog change together, or that the changelog entry cites the review.

Test case 4: Not for this library

The request

I want to create a skill that formats Excel spreadsheets with our company's brand colors.

What a good answer includes

The creator says this is not a behavioral-science library skill and points to Anthropic's general skill-creator, without starting the interview.

Checks on the answer

  • Says the skill does not belong in this library.
  • Points to Anthropic's general skill-creator.
  • Does not start the interview.

Test case 5: A source to read first

The request

Here's a chapter from our field playbook on running a barrier analysis with doers and non-doers. Turn it into a library skill. [chapter text follows: purpose, the doer/non-doer survey, sample of 45 and 45, the six standard determinant questions, tabulation, and the rule for calling a difference meaningful]

What a good answer includes

The creator works from the source and asks only what it does not answer, such as where the method goes wrong in practice or what a good result looks like, and checks the early gates, including whether an existing skill already produces this output.

Checks on the answer

  • Does not ask the author to restate what the chapter already says.
  • Asks one question at a time, and only about what the source does not cover.
  • Raises at least one early gate: one thing, common, adds something, or distinct from existing skills.
  • Does not write the whole folder in the first reply.

References

Longer material the skill opens only when a step calls for it, which keeps the main instructions short.

references/View on GitHub

Canonical sources

references/canonical-sources.md60 linesView on GitHub

An atomic skill earns its place when its task is a named step or tool in two or more of the sources on this page (docs/skill-spec.md, section 1). The list is fixed so that the test gives the same answer whoever applies it. Change it by pull request, with agreement from maintainers of both organizations.

Each citation below was checked against the publisher's page or the DOI record.

Behavioral design processes

Code Source
BCW Michie, S., van Stralen, M. M., & West, R. (2011). The behaviour change wheel: A new method for characterising and designing behaviour change interventions. Implementation Science, 6, 42. https://doi.org/10.1186/1748-5908-6-42. With Michie, S., Atkins, L., & West, R. (2014). The Behaviour Change Wheel: A Guide to Designing Interventions. Silverback Publishing.
BIT The Behavioural Insights Team. Kettle, S., & Persian, R. (2022). Target, Explore, Solution, Trial, Scale: An introduction to running simple behavioural insights projects. https://www.bi.team/wp-content/uploads/2022/11/BIT-Handbook-How-to-run-simple-BI-projects.pdf. Service, O., et al. (2014). EAST: Four simple ways to apply behavioural insights, and its 2024 revised edition, https://bi.team/wp-content/uploads/2014/04/BIT-EAST.pdf. Gyani, A., Tindall, K., & Gallagher, R. (2022). Explore Field Guide. https://www.bi.team/wp-content/uploads/2022/11/BIT-Explore-Field-Guide.pdf. Haynes, L., Service, O., Goldacre, B., & Torgerson, D. (2012). Test, Learn, Adapt. Cabinet Office.
BD Datta, S., & Mullainathan, S. (2012). Behavioral Design: A New Approach to Development Policy. CGD Policy Paper 016. https://www.cgdev.org/sites/default/files/Datta_Mullainathan_Behavioral_Design.pdf (journal version: Review of Income and Wealth, 60(1), 2014, https://doi.org/10.1111/roiw.12093). With Barrows, A., Dabney, N., Hayes, J., & Rosenberg, R. (2018). Behavioral Design Teams. ideas42.
OECD OECD (2019). Tools and Ethics for Applied Behavioural Insights: The BASIC Toolkit. https://doi.org/10.1787/9ea76a8f-en
WB World Bank (2015). World Development Report 2015: Mind, Society, and Behavior. https://doi.org/10.1596/978-1-4648-0342-0. With Gauri, V. (2018). eMBeDding for impact and scale in developing contexts. Behavioural Public Policy, 2(2), 256–262. https://doi.org/10.1017/bpp.2018.11
IM Intervention Mapping. Fernandez, M. E., Ruiter, R. A. C., Markham, C. M., & Kok, G. (2019). Intervention Mapping: Theory- and evidence-based health promotion program planning: Perspective and examples. Frontiers in Public Health, 7, 209. https://doi.org/10.3389/fpubh.2019.00209. Original: Bartholomew, L. K., Parcel, G. S., & Kok, G. (1998). Health Education & Behavior, 25(5), 545–563. https://doi.org/10.1177/109019819802500502
BUS Jang, C., Koki, E., Nyaga, R., Okafor, A., Singh, J., Vang, A., & Wendel, S. (2024). The Busara toolkit: leveraging behavioral science for development. Busara Groundwork No. 10. https://doi.org/10.62372/WQSB6195
DBC Designing for Behavior Change. The TOPS Program (2017). Designing for Behavior Change: A Practical Field Guide. Food Security and Nutrition Network Social and Behavioral Change Task Force (2013). Designing for Behavior Change: For Agriculture, Natural Resource Management, Health and Nutrition. Kittle, B. (2017). A Practical Guide to Conducting a Barrier Analysis (2nd ed.). Helen Keller International.
UNI UNICEF (2022). Social & Behaviour Change at UNICEF: Programme Guidance. https://www.sbcguidance.org/. With Petit, V. (2019). The Behavioural Drivers Model. UNICEF. https://www.unicef.org/mena/reports/behavioural-drivers-model

Methods references

Code Source
JPAL Abdul Latif Jameel Poverty Action Lab. Research Resources. https://www.povertyactionlab.org/research-resources. With Glennerster, R., & Takavarasha, K. (2013). Running Randomized Evaluations: A Practical Guide. Princeton University Press.
MRC Skivington, K., Matthews, L., Simpson, S. A., et al. (2021). A new framework for developing and evaluating complex interventions: update of Medical Research Council guidance. BMJ, 374, n2061. https://doi.org/10.1136/bmj.n2061
SUR Bjärkefur, K., Cardoso de Andrade, L., Daniels, B., & Jones, M. R. (2021). Development Research in Practice: The DIME Analytics Data Handbook. World Bank. https://doi.org/10.1596/978-1-4648-1694-9. With Groves, R. M., Fowler, F. J., Couper, M. P., Lepkowski, J. M., Singer, E., & Tourangeau, R. (2009). Survey Methodology (2nd ed.). Wiley.
EXP World Health Organization & ExpandNet (2010). Nine steps for developing a scaling-up strategy. https://www.who.int/publications/i/item/9789241500319. World Health Organization & ExpandNet (2011). Beginning with the end in mind. https://www.who.int/publications/i/item/9789241502320

Wise interventions

Code Source
WW Walton, G. M., & Wilson, T. D. (2018). Wise interventions: Psychological remedies for social and personal problems. Psychological Review, 125(5), 617–655. https://doi.org/10.1037/rev0000115

This source counts toward the two-source test like any other. It is also the first framework in the next section.

Frameworks the library carries by choice

A skill built on one of these skips the "common" test only. It still has to state what it adds and be distinct, and it says whose method it is.

Framework Why the library carries it Source
Wise interventions A distinct way of thinking about behavior change, through the meaning people make of themselves and their situation, that the process frameworks above do not cover. Walton & Wilson (2018), above
The Agency Fund's agency framework The definition and measurement of agency are central to the work of one of the library's two founding organizations. The Agency Fund. Cited in the two agency skills.
The Agency Fund's AI evaluation playbook Teams that build AI tools for social programs need a way to decide what to evaluate next. One skill carries the playbook's main idea. Wu, Z., On, R., Walsh, J., Korley, E., Madon, T., & Wong, L. (2025). AI Evaluation in the Social Sector: A Living Playbook. https://eval.playbook.org.ai/
Busara's SIFA The library asks users to disclose how people and AI contributed to a piece of work; SIFA is the format it points to. Busara. Cited in draft-sifa-declaration.

Supporting skills

A supporting skill is not a behavioral-science method. It does a job the outputs of many skills share, and it declares type: supporting and the stage other. It is a plain skill: the spec's sections, test cases, reference files, and inclusion tests do not apply to it, so this table is the only gate. A skill belongs here only if several skills' outputs would use it. The validator warns on a supporting skill that this table does not name.

Skill Why the library carries it Whose practice
write-in-academic-voice Several skills end in a written report. One writing skill gives those reports the same register, and report-producing skills name it. Zezhen Wu's revision rules for research prose, carried as he wrote them.

A limit of this list

It is thin on analysis. Only JPAL and MRC say anything about analyzing results, so a statistical procedure can fail the two-source test for that reason alone. Propose the source first, then the skill.

Manual validation checklist

references/checklist.md53 linesView on GitHub

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 name in 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, and CHANGELOG.md exist. No README.md in the folder. [E001, E029, E030, W033]
  • [ ] Atomic skills have references/worked-example.md (headings: The request; The output) and references/evidence.md (headings: Sources; Where it has been tested; Replication; What to check locally). [E045, W046]
  • [ ] Neither SKILL.md nor a reference file says how the skill was drafted or checked; that goes in CHANGELOG.md. [W050]
  • [ ] Only allowed file types; nothing over 2 MB; folder under 10 MB. [E034]
  • [ ] Every references/, scripts/, or assets/ 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]
  • [ ] description is 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]
  • [ ] license is CC-BY-4.0 (or MIT for code-only skills). [E009]
  • [ ] metadata has 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_in set to one of: beyond-western-holds, beyond-western-differs, mainly-western, not-applicable. [E018, E040]
  • [ ] consumes and produces use ids from the taxonomy's io types. Atomic skills name exactly one produces; consumes lists 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 when with at least three bullets and ### Do not use it when with 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.json has skill_name equal 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.md top entry is ## <version> - <date> matching metadata.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.json has skill_name equal to the name and at least one case with id, prompt, expected_output. [E029]
  • [ ] CHANGELOG.md top entry matches metadata.version. [E030]
  • [ ] Every skill or workflow named in SKILL.md exists in the library. [E056]

Drafting

references/drafting.md20 linesView on GitHub

What to do once the author confirms a shared understanding.

A new skill

  1. Check every source. Resolve the DOI or open the page, and confirm author, year, and title. Never write a citation from memory; leave out what you cannot check and tell the author which ones. Run the evidence scan in section 7 of skill-spec.md; it sets tested_in and fills the evidence file.
  2. Draft the folder from ../assets/skill-template/: SKILL.md with the eight sections, four named test cases, the changelog, the worked example, and the evidence file. interview-guide.md maps what you heard to each section. Keep the author's wording where it is good. Set version 0.1.0 and status draft.
  3. Validate. Run python scripts/besci_validate.py <skill-folder> from the skill-creator's folder and fix every error. With no filesystem, walk checklist.md and give the files as text blocks.
  4. Show one real output. Run the "Full run" test case with only the drafted skill, show the author the output, and fix what an expert would object to.
  5. Hand over. Run python scripts/package_skill.py <skill-folder>. Tell the author whether the validator passed, what is still open, and how to submit: the .skill file to a maintainer or https://besci-skills.vercel.app/upload/, or a pull request with the folder under skills/.

Revising a skill

Read the skill's folder, changelog, and any open expert review before the first question, and grill on what should change. Change only what the answers call for. Bump the version and write the changelog entry in the same change. When it answers an expert review, the entry cites it ("Addresses expert review #42 (Jane Doe): ..."), a test case named "From an expert review #42" reproduces it, and the pull request says "Closes #42".

A supporting skill

A skill that does a job many skills' outputs share, such as writing, and is not a method. Keep the author's text, add the frontmatter from section 13 of skill-spec.md, and draft its row for "Supporting skills" in docs/canonical-sources.md. A maintainer decides whether the library carries it.

Interview guide

references/interview-guide.md120 linesView on GitHub

Questions that work when interviewing an author about a method, and how to turn the answers into a library skill. The interview follows the method and the author; this file is a map of the ground, to check against, and not a script to read out. Put these to the author one at a time, with your recommended answer when the question is a decision, and ask a question only once the ones it depends on are settled.

The gates

One thing. Ask: "In one sentence, what does the skill do?" Listen for "and". Tests to apply silently:

  • One verb at the front: decompose, draft, define, design, measure, score, map, adjust.
  • One input, one output.
  • A behavioral scientist could do it in one sitting with one method.
Good Why
Decompose a defined behavior into COM-B barrier hypotheses one verb, one input, one output
Draft a saying-is-believing exercise for a target population one thing out
Adjust a published effect size for publication bias one operation
Too broad Split into
Design a behavior change program define the behavior; diagnose barriers; select levers; draft content; plan the test
Apply behavioral science to a chatbot which operation? ask
Analyze this program and tell me what's wrong diagnose barriers; review a prior intervention; audit the ethics

When it fails: "That reads as two skills, A and B. B would take A's output as its input. Which one do we build now?"

Common. "Which two sources on the library's list name this task as a step or tool?" Read canonical-sources.md yourself first and offer the two you would pick. If only one names it, say so: the skill needs a maintainer to decide whether the library carries the framework.

Adds something. "If I asked a good AI model to do this with no skill, what would it get wrong or leave out?" The answer becomes the **What this adds:** line. "It would be less rigorous" is not an answer yet. Push to a fixed output, a required check, a decision rule, verified sources, or a search or script call.

Distinct. Read the catalog and name the nearest existing skill: "The library has decompose-comb-barriers. How is what yours produces different from that?"

The ground, with questions that work

What it is for, and who reaches for it.

  • "Who is stuck, and on what, at the moment they need this?"
  • "Give me three things a colleague might type when they need it. In their words, not the method's." Aim for one that names the method, one that describes the situation and does not name it, and one near-miss that should still fire.
  • "What is the nearest thing someone might ask that this should not handle? Where should they go?" Get at least two.

How an expert does it.

  • "Walk me through it as you would do it on a real case. What is the first thing you look at?"
  • At each step: "What does someone new get wrong here?" and "Why does this step come before the next?"
  • "Is there a step people skip that you never would?"

What it needs before it starts.

  • "What do you need to know before you can do this well?"
  • "What is the most common way someone gives you too little, and what goes wrong when you guess?"
  • If the author says nothing is needed, ask the second question once more with an example. If the answer is still nothing, accept it and write their reason into the section.

What good looks like.

  • "Show me, or describe, a result you were happy with. What is on the page?"
  • "If I handed you two results, how would you tell the good one from the bad one in thirty seconds?"
  • "What would you tell the reader to check before relying on it?"

Where it goes wrong.

  • "When have you seen this method go wrong in practice?"
  • "What would an AI model do with this that an expert never would?"
  • A failure that only repeats a step does not count. Patterns worth asking about by name: leading questions, a confident result from thin input, mislabeling, results that run too long, moralizing, reaching for the fashionable technique whatever the fit.

Where a specialist takes over.

  • "When would you tell someone to stop and call you, or someone like you?"
  • "What kind of specialist, and what should they bring to that conversation?"
  • Push on "never": "Take a high-stakes case: clinical, legal, children, a large budget. Still no point where you would want a specialist in the room?"

What it rests on.

  • "What does this rest on? A framework, a paper, a playbook, or your own practice?"
  • "Which countries and populations was it studied in, and what should someone working elsewhere check before trusting it?"
  • "Has it replicated? Mixed, contested, a single study?"
  • For each source, get enough to find it, then open it yourself and confirm author, year, and title. Leave out what you cannot open.

What happens next.

  • "After someone has this result, what do they usually do? When would each of those be the wrong move?"

Weak answers and how to push:

The author says Ask
"It's based on best practice." "Whose practice, written down where?"
"It helps teams think about barriers." "What does a team have at the end that it did not have at the start?"
"It depends." "On what? Give me the two cases that differ most."
"The model should use judgment." "What would you look at to make that call?"

From the interview to the eight sections

The author never sees this table. It is how you sort what you heard.

What you heard Where it goes
The one sentence; what the AI gets wrong unprompted ## What it does, with the **What this adds:** line
What people type; the nearest things it should not handle description, and ## When to use it with its two lists
What the expert needs first, and what to assume when it is missing ## Before you start. Name each input by what it is, not by the skill that made it
Frameworks and sources; where tested; replication ## What it draws on, references/evidence.md, metadata.tested_in
The steps, with the reason for each ## How to do it, in the imperative. Anything longer than a screen moves to references/
What a good result looks like; what to check before relying on it; what people do next ## Output template: a fenced block that opens with a plain lead-in, uses labels a program designer would use, and ends with "Where you could go from here". The shared voice block follows it; copy the markers from the template
When it has gone wrong; what a model would do ## Where it goes wrong, at least three, plus what is out of scope
When to stop and call someone ## When to bring in a specialist
A real case the author described references/worked-example.md, and the "Full run" test case

The description. "Use when" plus the situation, the phrasings, "Do not use when" plus the nearest neighbor, "Not for" plus the second neighbor. About 500 characters, no citations. Read it back and ask: would a model that sees only this fire at the right moments?

  • Weak: "This skill helps you decompose barriers using COM-B." A summary, with no trigger and no exclusion.
  • Strong: "Use when one behavior is already defined (who does what, when) and you need to know why it is not happening... Do not use when the goal is still vague; use define-key-behavior. Not for choosing interventions."

The name. Verb first, kebab-case, a verb from the taxonomy's list, American spelling: decompose-comb-barriers, not comb-barrier-decomposer.

The four test cases, named and in this order. Draft them, then ask the author: "Do these sound like your users?"

  1. Full run: a complete request with realistic context; expects the whole output.
  2. Missing context: a thin request; expects the skill's questions and nothing else.
  3. Near the escalation point: expects what the skill can safely do, and the specialist named.
  4. Wrong skill: a request that belongs to a neighboring skill; expects to be sent there.

expected_output is one sentence. assertions holds three to six statements a reviewer can tick yes or no, and never the answer text.

Metadata. Recommend a stage and say why. Two or three tags from the taxonomy's suggested list. produces is the one thing the output template is; consumes lists only the inputs the skill cannot run without. tested_in comes from the evidence scan.

Showing the output

When you show the author the "Full run" output, be plain about how it did. "Partly" is the common verdict on a first draft. Useful questions: "What would you cross out?", "What is missing that you would have said?", "Would you put your name on this?"

Skill specification

references/skill-spec.md371 linesView on GitHub

This is the authoring guideline for the skills in the Behavioral Science Skills Library. Sections 1 to 12 describe an atomic skill; supporting skills (section 13) and meta-skills (section 14) are written in their own shape. The validator in scripts/besci_validate.py enforces everything marked required. besci-skill-creator interviews you against this spec; you can also write a skill by hand with template/skill-template/.

A skill is a folder:

skills/<name>/
├── SKILL.md                      required: frontmatter + eight sections
├── evals/evals.json              required: four named test cases
├── CHANGELOG.md                  required: one entry per version
├── references/worked-example.md  required for atomic skills
├── references/evidence.md        required for atomic skills
├── references/                   optional: other material loaded on demand
├── scripts/                      optional: code the AI can run
└── assets/                       optional: templates used in output

No README.md inside a skill folder. Every skill sits directly under skills/, with its stage and type in metadata, so reclassifying a skill is a one-line edit and its install link and URL never change.

1. What earns a place

An atomic skill stays in the library if it passes three tests.

  1. Common. Its task is a named step or tool in two or more of the sources in docs/canonical-sources.md. One study's technique does not pass.
  2. Adds something. One line can state what the skill makes the AI do that it would not do unprompted. That line goes in the skill (section 4).
  3. Distinct. No other skill produces the same output template.

The library also carries a few frameworks by choice; docs/canonical-sources.md lists them. A skill built on one of them skips the first test only, and says whose method it is.

A supporting skill takes none of the three tests. It is not a behavioral-science method; it does a job the outputs of many skills share, such as writing. It is a plain skill, and this spec does not apply to it beyond section 13. It earns its place by being listed under "Supporting skills" in docs/canonical-sources.md, with the reason the library carries it.

2. The name

Required. Kebab-case, 1 to 64 characters, matches the folder name, and starts with a verb from the verbs list in taxonomy.yaml. Meta-skills (besci-*) are exempt from the verb rule.

The verb-first name is the atomicity rule applied to the folder: if you cannot start the name with one verb, you have more than one skill.

Good Not this
decompose-comb-barriers comb-barrier-decomposer
define-key-behavior behavior-definition
draft-cognitive-interview-script cognitive-interviews

American spelling throughout: behavior, analyze, program.

3. Frontmatter

Only the keys allowed by the Agent Skills spec may appear at the top level. Everything the catalog needs goes under metadata as plain strings. Lists are comma-separated strings, because the spec allows string values only.

---
name: decompose-comb-barriers
description: >-
  Use when one behavior is already defined (who does what, when) and you
  need to know why it is not happening. Lists competing capability,
  opportunity, and motivation barriers with a question that tests each.
  Do not use when the goal is still vague; use define-key-behavior. Not
  for choosing interventions; use select-intervention-levers.
license: CC-BY-4.0
metadata:
  title: Find out why people are not doing a behavior
  type: atomic
  stage: diagnose
  version: "0.2.0"
  status: draft
  authors: "Nikhil Ravichandar"
  org: IL
  tested_in: beyond-western-differs
  tags: "com-b, behavior-change-wheel"
  consumes: "target-behavior-brief"
  produces: "comb-barrier-hypotheses"
---
Field Required Rule
name yes See section 2.
description yes The compressed trigger rule. It must contain a "Use when ..." clause and a "Do not use when ..." clause naming the nearest adjacent intent, and no < or >. This is the only text the AI reads before deciding to load the skill. Aim for about 500 characters and leave citations out; besci-navigator does the routing, so the description need not hold every phrasing. The validator warns above 600 characters and fails above 1024.
license yes CC-BY-4.0 for skill content. MIT only for a skill that is code with no method content.
metadata.title no Human-readable name for the catalog. Defaults to the name.
metadata.type yes atomic, meta (section 14), or supporting (section 13).
metadata.stage yes One of define, diagnose, design, measure, test, analyze, implement, or other. The seven are strong recommendations. other is for supporting skills (section 13) and for meta-skills (section 14); an atomic skill in other is an error (E013). See the crosswalk in docs/taxonomy.md.
metadata.version yes Semver, quoted: "0.2.0". Bump in the same change as the CHANGELOG entry.
metadata.status yes draft, published, or deprecated. Submit as draft; a maintainer sets published on merge.
metadata.authors yes Names or GitHub handles, comma-separated.
metadata.org yes TAF, IL, or community.
metadata.tested_in atomic only Where the evidence has been tested: beyond-western-holds, beyond-western-differs, mainly-western, or not-applicable. The value follows from the evidence scan (section 7).
metadata.tags no Free-form, comma-separated. See suggested_tags in taxonomy.yaml for consistent spelling.
metadata.consumes no The inputs the skill cannot run without, as ids from io_types in taxonomy.yaml. It matches the "Required" questions in "Before you start". Leave optional inputs out.
metadata.produces atomic only Exactly one io_types id: the thing the output template is.
metadata.reviewed_by no Set by the reviewer at merge.

consumes and produces draw the arrows on the site's map. An arrow says one skill's output can feed another; it is a suggestion for building a workflow, not a rule about where an input must come from.

4. The eight sections

Required, in this order, each as a level-2 heading with exactly this text. The validator fails on a missing, empty, or reordered section.

Keep SKILL.md to about 1,000 words, not counting the output template. Apply one test to every sentence: it stays only if deleting it would change what the AI does or what the reader decides. The validator warns above 1,000 words.

## What it does

One sentence, no "and". Then one labeled line:

**What this adds:** <what the skill makes the AI do that it would not do unprompted>

The line names concrete behavior: a fixed output, a required check, a decision rule, verified sources, or a search or script call. "Structured" and "rigorous" do not count. The site shows this line at the top of the skill's page.

## When to use it

The full trigger rule. The description is the compressed version that fires the skill; this section is the complete list, read by people on the site and by besci-eval, which turns every bullet into a trigger test. Two level-3 subheadings, exactly:

### Use it when
- (at least three) user intents or phrasings that should invoke this skill
### Do not use it when
- (at least two) adjacent intents that should not, each naming where to go instead

"Do not use it when" names where to go instead. A skill may also name other skills as next moves in its closing (see "Output template"). It never asks for an input by the skill that made it; see "Before you start". The validator fails on a named skill or workflow that does not exist.

## Before you start

The questions the skill asks the user before it produces its output. A skill should not produce output on a guess it could have checked with one question. List the questions, say which are required, and say what the skill assumes if an answer is missing.

These questions come before the output, not before every reply. If the user asked a question rather than asked for the output ("how do I know if this is ethical?"), the skill answers it first in a few plain sentences, then offers the run. The shared voice block says so at run time.

Ask for an input by what it is ("a confirmed barrier, from interviews or any diagnosis"), not by which skill made it. People bring inputs from anywhere.

May be "Not applicable: " when the skill does not need to ask, for instance because it transforms an input the user has already supplied in full. The reason must be a real sentence.

## What it draws on

The evidence base: the framework, paper, or practice the skill puts to work. List each source as a full citation with a link, followed by one line on what it supports in the skill. Then two labeled notes:

**Where the evidence comes from:** <three sentences at most>

**Replication status:** <one sentence>
  • Where the evidence comes from says which countries and populations were studied, what was found outside wealthy Western countries, and what to check where the user works.
  • Replication status says replicated, mixed, contested, or single-study.

The fuller account goes in references/evidence.md. "Common sense" or "general best practice" is not an evidence base. If the skill encodes a practitioner's method, say so and name the practitioner.

## How to do it

The procedure, step by step, in the imperative. Explain why a step matters where it isn't obvious; a model follows a reasoned instruction better than a bare command. Point to references/ files for detail, one level deep.

## Output template

The exact shape of the response, in a fenced markdown block, with placeholders in angle brackets. A user and a reviewer should be able to tell from this block alone whether a run of the skill did its job.

Three parts every template has:

  • A plain lead-in. The template opens with a placeholder for two or three sentences to the user: what this is, and the one thing in it that matters most for them.
  • Plain labels. Write labels in words a program designer would use ("How the answer tells them apart", not "Discriminates because"). Keep a method's own term only where the user will need it to read the literature, and gloss it the first time ("Capability (can they do it?)").
  • The closing. The template ends with this block, so the user is never left with an order. Its placeholder lists the candidate next moves, each with the condition under which it fits: other library skills, by name, and at least one step outside the library (records to check, people to ask). The model offers the two or three that fit what the run found, not the whole list. A next move is a suggestion; the user decides.
## Where you could go from here
<One line saying the <output> is done.>
<Two or three next moves that fit what this run found, each with why it would help and when it fits. Candidates:
- `<other-skill>`, when <condition>
- `<other-skill>`, when <condition>
- <a step outside the library>, when <condition>>
Questions you could ask next: "<question>" · "<question>"

After the fenced template, the section carries the shared voice block between the markers in template/skill-template/SKILL.md. Its source is template/shared/voice.md; scripts/check_sync.py --fix fills it, and CI fails if a copy drifts. Edit the source, never the copy. The block does not count toward the length limit. It tells the model how to talk at run time: answer a question before offering the run, mark when the run starts and finishes, use the user's words, say where each claim comes from, and close with reasoned options rather than an instruction.

## Where it goes wrong

Known failure modes and out-of-scope cases: what the model tends to do wrong with this method, what inputs break it, what it must refuse to do. A failure mode that only repeats a step from "How to do it" does not belong here.

## When to bring in a specialist

The escalation point: the conditions under which the skill tells the user the question has outgrown the tool. Be concrete ("if the behavior involves clinical risk", "if the sample is below 200 and the effect size is unknown"). Say what kind of specialist and what to bring to them.

May be "Not applicable: " for a narrow technical skill with no judgement call the user could get wrong. Same rule: a real reason.

5. Test cases: evals/evals.json

Required. Four cases, named and in this order. The format extends the one Anthropic's skill-creator uses.

name What the case tests
Full run A realistic request with enough context. The skill produces the whole output template.
Missing context A request that lacks a required input. The skill asks its "Before you start" questions and produces nothing else.
Near the escalation point A request that meets a condition under "When to bring in a specialist". The skill does what it safely can and names the specialist.
Wrong skill A request that belongs to a neighboring skill. The skill says where to go and does not produce its output.
{
  "skill_name": "decompose-comb-barriers",
  "evals": [
    {
      "id": 1,
      "name": "Full run",
      "prompt": "A realistic request a user would actually type, with the context they'd actually give.",
      "expected_output": "One sentence on what a good answer is.",
      "files": [],
      "assertions": [
        "A statement a reviewer can tick yes or no.",
        "Another, about what must be present.",
        "Another, about what must not be present."
      ]
    }
  ]
}
  • expected_output is one sentence.
  • assertions holds three to six short statements, each one check. besci-eval marks them against the answer written with the skill and the answer written without it.
  • Write prompts the way your users talk, not the way the skill talks.

A fifth case where a review reported a failure. When an expert review reports that the skill got something wrong, the version that answers it adds a case that reproduces the failure, named From an expert review #<issue number>.

Trigger tests are not written here. besci-eval derives them from ## When to use it.

6. Reference files

Required for atomic skills: references/worked-example.md and references/evidence.md, with the headings below. Other reference files are allowed when SKILL.md points to them; each opens with one line saying what it is for.

references/worked-example.md
# Worked example: <the case in a few words>

A full run of the skill on a realistic case, showing the output it should produce. The case is illustrative, not a real program.

## The request

<what the user gave>

## The output

<the filled output template, in one fenced block>

Use the case that fits the skill. Leave out who drafted the example and where it was ported from.

references/evidence.md
# Evidence: <skill title>

## Sources

- <full citation with a link>. Supports: <what it supports in the skill>.

## Where it has been tested

Searched <month and year>.

| Source | Type | Countries | Finding |
|---|---|---|---|
| <citation with a link> | <review or single study> | <...> | <...> |

<one or two sentences: which part of the mechanism depends on local conditions>

## Replication

<what held, what failed, what is contested>

## What to check locally

1. <...>

7. The evidence scan

Every atomic skill that makes a claim about how people behave runs this scan before it is written or revised, and records the result in references/evidence.md.

  1. Reviews first. Look for systematic reviews or meta-analyses of the technique. Record whether they include samples outside wealthy Western countries, how many, and whether the effect differs by region or income level.
  2. Then individual studies. Find the two or three strongest studies from low- and middle-income or non-Western settings, with field trials ahead of lab studies.
  3. Then the explicit null. If neither step finds anything, say so and name what was searched.
  4. State what depends on local conditions. Name the part of the mechanism that could differ (literacy, formal accounts, who decides in the household, trust in the sender) and the one thing to check locally.

About five searches per skill is enough. This is a scan, not a systematic review.

The result sets metadata.tested_in:

Value Label What earns it
beyond-western-holds Tested beyond wealthy Western countries; results hold A systematic review, or at least two field studies outside wealthy Western countries, point the same way as the original evidence.
beyond-western-differs Tested beyond wealthy Western countries; results differ Studies outside wealthy Western countries exist, and their results differ from the original evidence or from each other.
mainly-western Tested mainly in wealthy Western countries The scan found fewer than two field studies outside wealthy Western countries.
not-applicable Not applicable The skill is a procedure that makes no claim about how people behave.

When a review pools studies from outside wealthy Western countries, its overall result decides between "holds" and "differs"; record single trials that went the other way in the table.

Verify every source. Resolve the DOI or open the page, and confirm author, year, and title, before the source goes into a skill. Leave out anything that cannot be verified; do not flag it and keep it. Never write a citation from memory.

8. Skills that search for or read studies

A skill whose job at run time is to find studies, or to read the studies it is given, carries references/citing-sources.md, a shared file that scripts/check_sync.py keeps identical across those skills. Its rules: open every source before citing it; take effect sizes from the results, and say "abstract only" when that is all that was read; never output a link that was not opened; say "no evidence found" when no study addresses the claim, and do not issue a verdict; and when no search tool is available, say so first and give no links or effect sizes.

9. Version history: CHANGELOG.md

Required. Newest first. The top entry must contain the current metadata.version.

# Changelog

## 0.2.0 - 2026-11-10
Addresses expert review #42 (Jane Doe): the first run now checks every link before showing it.

Patch for wording, minor for new behavior, major when the output template changes shape. Before 1.0, a change of shape bumps the minor version. Name the reviewer in the entry that marks a skill published. An entry that answers an expert review cites the issue in the form above; the site uses it to mark the review answered. The changelog is also where a note on how a version was drafted belongs, including any use of AI.

10. Files

Allowed types: markdown, text, JSON, YAML, CSV, Python, R, shell, HTML, CSS, JavaScript, PNG, JPG, SVG, GIF. 2 MB per file, 10 MB per skill. Every path SKILL.md mentions under references/, scripts/, or assets/ must exist.

11. Style

  • Write for a program designer or M&E lead who has never met a behavioral scientist. Define a term the first time you use it.
  • Use plain words for where evidence comes from: "wealthy Western countries", not the acronym WEIRD.
  • Imperative mood in "How to do it". Explain the why in one clause when a step is not obvious.
  • Ask before producing the output. A skill that gives a confident answer to an underspecified request is a failure mode, not a feature. A question the user asked is answered first, though; asking comes before the output, not before every reply.
  • Suggest, do not direct. The library offers next moves with reasons and says which it would lean toward; the user decides. No "Next action", "Check first", or "Next steps" lines.
  • Sound like a colleague, not a form. Plain sentences around the structured output, the user's own words for their program, and no praise.
  • Name the mechanism, not just the tactic. "Send a reminder" is a tactic; "reduce the attention cost at the moment of action" is a mechanism.
  • Cite what you draw on, and only what you have verified.
  • Keep notes on how the skill was drafted or checked out of SKILL.md and references/. They go in CHANGELOG.md.

12. Running the validator

uv run scripts/besci_validate.py skills/<name>     # one skill
uv run scripts/besci_validate.py                    # all skills
uv run scripts/besci_validate.py --json             # for tools

Exit 0 means the structure is right. Content review by a maintainer is still required before merge.

Everything this document marks required is an error (codes starting with E), and so is naming a skill or workflow that does not exist. The length limits and a note in SKILL.md or references/ on how the skill was drafted are warnings (codes starting with W). A warning needs a decision, not silence.

13. Supporting skills

A supporting skill (type: supporting, stage: other) is a plain skill: it meets the Agent Skills spec and is otherwise written in whatever shape suits it. A skill written elsewhere can be carried as it is.

It needs:

  • SKILL.md with a name that matches the folder, a description, a license, and the six required metadata fields: type, stage, version, status, authors, org.
  • A row under "Supporting skills" in docs/canonical-sources.md. The validator warns without one (W013).
  • Files within the limits of section 10.

Nothing else in this document applies: no eight sections, no "Use when" clause, no verb-first name, no test cases, no reference files, no evidence scan, no tested_in or produces, no voice block, no changelog. The site shows the skill's text and its reviews, and no other tabs.

A skill that names a supporting skill says what to do when it is not installed, so that it still works alone.

14. Meta-skills

A meta-skill (type: meta, stage: other) works on the library itself: besci-navigator, besci-skill-creator, besci-eval. Its body is written in whatever shape serves its job. A fixed set of sections made these skills longer and stiffer than their jobs needed, so sections 4 to 8 do not apply: no eight sections, no shared voice block, no named test cases, no worked example or evidence file, no tested_in.

It needs:

  • The frontmatter of section 3. The description still carries a "Use when" clause and a "Do not use when" clause, because the AI reads it to decide between the meta-skill and the skill a user named.
  • An opening paragraph that says what the skill does. The catalog and the site show it.
  • evals/evals.json with skill_name and at least one case. Each case has id, prompt, and expected_output; name and assertions are optional and their wording is free. A case the skill should leave alone carries "should_trigger": false, and besci-eval uses it as a triggering test.
  • CHANGELOG.md, as in section 9.
  • Files within the limits of section 10, and every skill or workflow it names must exist.

The style rules of section 11 still describe how a meta-skill talks to people. Each one states the manner it needs in its own words.

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

scripts/besci_validate.py951 linesView on GitHubDownload

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())

package_skill.py

scripts/package_skill.py59 linesView on GitHubDownload

Zip one skill folder into <name>.skill for Claude Desktop / claude.ai upload.

#!/usr/bin/env python3
"""
package_skill.py — zip one skill folder into <name>.skill for Claude Desktop / claude.ai upload.

Usage:
  python package_skill.py path/to/skill-folder [--out DIR]

A .skill file is a plain zip whose single top-level folder is the skill folder.
Excludes __pycache__, .DS_Store, hidden files, and *-workspace directories.
No dependencies beyond the standard library.
"""
import argparse
import os
import sys
import zipfile

SKIP_DIRS = {"__pycache__", ".git"}


def should_skip(rel: str) -> bool:
    parts = rel.split(os.sep)
    if any(p in SKIP_DIRS or p.startswith(".") or p.endswith("-workspace") for p in parts):
        return True
    return False


def package(folder: str, out_dir: str) -> str:
    folder = os.path.abspath(folder.rstrip("/"))
    name = os.path.basename(folder)
    if not os.path.exists(os.path.join(folder, "SKILL.md")):
        raise SystemExit(f"{folder} has no SKILL.md")
    os.makedirs(out_dir, exist_ok=True)
    out_path = os.path.join(out_dir, f"{name}.skill")
    with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf:
        for root, dirs, files in os.walk(folder):
            dirs[:] = [d for d in dirs if not should_skip(os.path.relpath(os.path.join(root, d), folder))]
            for f in sorted(files):
                full = os.path.join(root, f)
                rel = os.path.relpath(full, folder)
                if should_skip(rel):
                    continue
                zf.write(full, os.path.join(name, rel))
    return out_path


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("folder")
    ap.add_argument("--out", default=".", help="Output directory (default: current directory)")
    args = ap.parse_args()
    path = package(args.folder, args.out)
    print(f"Wrote {path} ({os.path.getsize(path) // 1024} KB)")
    print("Upload it in Claude: Settings > Capabilities > Skills > Upload skill.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Assets

Files the skill uses as starting points, such as templates. They ship with the skill but aren't instructions.

assets/View on GitHub

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.5.0 - 2026-11-25

Asks one question at a time, as grill-me does, and waits for the answer before the next. Version 0.4.0 told the creator to ask every open question in one round of numbered questions. The rounds wording and the two-question template are gone. Recommended answers are for decisions only: a question about the author's own experience of the method is asked plainly, without a guessed answer. The rule to word each question so "yes" accepts the recommendation is gone. The interview guide, the revising step, and the test cases follow. Edited with Claude.

0.4.0 - 2026-11-25

Rewritten to follow Matt Pocock's grilling skill (https://github.com/mattpocock/skills, MIT license, copyright Matt Pocock) nearly word for word: the skill is mapped as a design tree rooted in the spec's four gates and grilled in rounds of numbered questions, each with a recommended answer. Facts such as the sources list and the catalog are looked up, not asked. Drafting waits until the author confirms a shared understanding; the drafting, revising, and supporting-skill steps move to the new references/drafting.md. The fourteen-phase interview, report template, and voice block are gone. Edited with Claude.

0.3.3 - 2026-11-24

Wording only: the interview guide and the bundled spec no longer point to decision records that have left the repository. Edited with Claude.

0.3.2 - 2026-11-24

Wording only: the metadata phase and the checklist say that the stage other is for meta-skills and for supporting skills, which are plain skills the interview and the checklist do not cover. Edited with Claude.

0.3.1 - 2026-11-13

Wording only: the pointer for writing a workflow no longer names the navigator's guide mode, which the navigator no longer has. Edited with Claude.

0.3.0 - 2026-11-11

Follows the conversational-voice standard when drafting a skill: a plain lead-in, plain labels, and a "Where you could go from here" closing in every output template; asks what people do next so the closing lists candidate next moves with their conditions; copies the shared voice-block markers. Its own report now opens with a few plain sentences, calls "Submit" "How to submit it", ends with next moves, and carries the shared voice block. Bundles the updated spec, template, and validator. Edited with Claude.

0.2.0 - 2026-11-10

Follows the November 2026 skill standard: asks for the "what this adds" line, runs the evidence scan and sets tested_in, checks every citation and leaves out what cannot be checked, drafts four named test cases with assertions, and writes references/worked-example.md and references/evidence.md. Edited with Claude.

0.1.1 - 2026-10-13

Trigger examples and one eval prompt use the repository's new name, besci-skills. No change to behavior.

0.1.0 - 2026-10-08

First version. Fourteen-phase interview against docs/skill-spec.md, bundled validator and packager, manual checklist for environments without code execution, one self-test pass. Five evals. Not yet reviewed.

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.

See all expert reviews of this skill on GitHub

Ratings and comments

Ratings show here once the site can reach its database.