diff --git a/README.md b/README.md index 417c258..2d869e6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,11 @@ # skills -A collection of claude skills we think are generic enough to be useful to everyone + +A collection of Claude skills we think are generic enough to be useful to everyone. + +## Skills + +- **[skill-review](./skill-review/)** — Review Claude Code skills against substantive quality standards: a closed 7-category rubric (Structural Discipline, Integrity, Test Coverage, Security, Content Quality, Convention, Cost) with structured JSON output and a determinism contract. Complements Anthropic's `plugin-dev:skill-reviewer` (which covers structural checks) by focusing on whether a skill gives Claude the right kind of content, has appropriate test coverage, and is shaped and placed well. + +## Using a skill + +Each skill is a self-contained directory with a `SKILL.md` entrypoint. Drop it into `~/.claude/skills/` (personal), a repo's `.claude/skills/` (project-local), or a plugin, and Claude Code will pick it up. diff --git a/skill-review/SKILL.md b/skill-review/SKILL.md new file mode 100644 index 0000000..d62358d --- /dev/null +++ b/skill-review/SKILL.md @@ -0,0 +1,145 @@ +--- +name: skill-review +description: > + Review Claude Code skills against substantive quality standards — a 7-category + rubric with JSON output, single-pass full-rubric review, and a determinism contract. + Complements Anthropic's `plugin-dev:skill-reviewer` (structural checks). + Use for: "review a skill", "check skill quality", "does this skill need evals", + "review skill quality". +version: 0.1.0 +--- + +# Skill Review + +## Purpose + +Review skills for substantive quality signals that Anthropic's `plugin-dev:skill-reviewer` does not cover. That agent handles structural concerns (frontmatter format, word count, writing style, progressive disclosure). This skill focuses on **substance** — whether the skill gives Claude the right kind of content, has appropriate test coverage, uses hooks effectively, and lives in the right location. + +The rubric is **authoritative and closed.** Every finding type the reviewer can surface is enumerated in the per-category reference files. Reviewers match against the rubric; they do not invent new buckets. If a concern doesn't fit any enumerated finding type, it belongs in the out-of-rubric channel — never inline as Critical/Major/Minor. + +**Closed does not mean conservative.** "Closed" constrains the *set* of finding types you may emit — it does **not** mean you should hesitate to apply the ones that exist. The two are independent: never invent a new finding type, AND never withhold a defined one when its predicate plausibly matches. The judgment-bound finding types — `operational-guardrail-untested` (Test Coverage), `contradictory-instructions` and the three Behaviour sub-checks (Integrity), `procedure-smell-with-consequence` (Content Quality), the orchestration pair (Cost/Convention) — are the ones a reviewer most often *under*-fires, because the defect is buried in an otherwise-sound skill and nothing jumps out on a first read. For these types, **`pass` is a claim that must be earned, not a default**: a category may be marked `pass` only after you have positively checked the predicate (enumerated every guardrail and cross-checked it against the evals, read every referenced script, compared every same-condition instruction pair) and found it does not hold — not merely because no red flag was salient. When a defined predicate plausibly matches, fire it; absence of an obvious problem is not evidence of absence. + +## How a Review Runs + +A review is a **single pass**: load every category reference, evaluate all seven categories against the skill, and emit the full JSON. There is no triage gate — no category is skipped for looking clean, so a finding can never be missed because its category's deep-dive reference was never opened. This trades token spend for recall by construction. + +1. **Read the skill folder and the scripts it invokes.** SKILL.md body and frontmatter, `references/` listing, `evals/` listing, and any scripts the skill ships **or invokes** — both scripts under the skill's own `scripts/` and shared scripts at the plugin root (e.g. `${CLAUDE_PLUGIN_ROOT}/scripts/...`) that the SKILL.md references and tells Claude to run. A skill whose scripts live at the plugin level is the common case, not the exception — Glob for the referenced script paths and read them; do not treat "no `scripts/` dir inside the skill folder" as "no scripts to review". Every check in this skill is performed by reading — Read, Grep, and Glob are the only tools needed. Note the skill's **reach** (a widely-shared skill published in a plugin/marketplace vs a personal or project-local skill) and its diff status (`M` if it's being modified in this PR) — Test Coverage and the stale-eval checks depend on both. +2. **Load all seven category references.** Read every deep-dive listed in [Reference Files](#reference-files) before evaluating. Load `suggested-rewrites.md` too if any finding will need a rewrite. Each reference owns the finding types, severity tiers, false-positive guardrails, and rewrite policy for its category — applying a category without its reference loaded is not permitted. +3. **Evaluate every category.** Apply each reference's rubric to the skill by reading it directly. A category with no matching finding emits `{"status": "pass", "findings": []}`; otherwise it emits its findings with `finding_type`, `severity`, `deterministic`, `location`, `explanation`, `fix`, and optionally `suggested_rewrite`. A skill that is mostly deterministic glue (pinned queries, fixed tool/MCP call sequences, output templates) — counting body **and** `references/` — is the `script-extractable-orchestration` (Cost) / `orchestration-shaped-skill` (Convention) pair; single-pass already loads both references every run, so no triage hint is needed to reach it. +4. **Emit structured JSON.** Output the full JSON — all seven categories, including the ones that passed clean — per the [Output Contract](#output-contract) below. This skill's contract ends at the JSON. + +## Categories + +| Category | Scope | Deep dive | +|----------|-------|-----------| +| **Structural Discipline** | Body shape and progressive-disclosure hygiene | [`structural.md`](./references/structural.md) | +| **Integrity** | Claims resolve: cross-plugin / MCP / command references resolve, instructed tools are declared in `allowed-tools`, paired files match, prose counts agree, instructions don't contradict each other, bundled scripts work | [`integrity.md`](./references/integrity.md) | +| **Test Coverage** | Evals exist for skills with broad reach; operational guardrails are exercised; evals actually test what they claim (no stale or false-coverage evals) | [`test-coverage.md`](./references/test-coverage.md) | +| **Security** | No credential exposure, no plaintext-secret instructions, safe shell idioms, transport security not disabled | [`security.md`](./references/security.md) | +| **Content Quality** | Context vs instructions, procedure smell, weak completion criteria, no-op instructions — does the body teach Claude something it couldn't derive, without restating defaults | [`content-quality.md`](./references/content-quality.md) | +| **Convention** | Placement + triggering: where the skill lives (personal / project / plugin), similar-skill duplication, hook integration, invocation mode (a skill that can't usefully auto-fire — slash-command-only or a sealed-input sub-routine — still shaped for auto-fire), repo-convention adherence (frontmatter fields — e.g. an agent's `model:` — vs the repo's documented conventions) | [`convention.md`](./references/convention.md) | +| **Cost** | Runtime token-spending patterns: bash chains, MCP result-size, field projection, response style | [`cost.md`](./references/cost.md) | + +**Category boundaries worth calling out:** +- **Structural vs Cost** — both touch token waste, but Structural owns *body shape* (length, body↔references duplication, flat reference lists) and Cost owns *runtime spending patterns* (script-extractable chains, MCP defaults, response narration). Body↔references duplication is Structural even though it also wastes tokens. +- **Content Quality vs Convention** — Content Quality is about what's *in* the body (context vs instructions). Convention is about where the skill *lives* and how it *fires* (placement, similar skills, hooks). A skill can have perfect content but a missing hook, or vice versa. +- **Integrity vs Security** — both read the skill's bundled scripts, but they ask different questions. Integrity asks *do the skill's claims hold?* — both that named things resolve (file/skill/command/MCP tool exists) and that the code it ships actually works (no crash, no hardcoded-environment break, no silently-wrong output). Security asks *is it safe?* (credential exposure, injection, path traversal). A `rm -rf "$unvalidated"` is Security; a `KeyError` on a documented input or a call to a non-existent MCP tool is Integrity. A defect that is both → file the more severe. +- **Cost ⊕ Convention for deterministic orchestration** — the one *intentional* two-finding case. A skill that is mostly deterministic glue end-to-end (pinned queries + fixed call sequences + output templating, often hiding in `references/`) is filed in BOTH Cost (`script-extractable-orchestration`, the per-session token-cost lens) AND Convention (`orchestration-shaped-skill`, the marketplace-shape lens). Both are **Major by default** with a strict firing bar (fire on *dominance* of glue, never mere presence) and share one extract-glue fix — move the pipeline into a bundled `scripts/` file, keep a thin skill over the judgment kernel; never recommend deleting the skill. A *single* extractable chain in an otherwise-sound skill is Cost-only (`scriptable-bash-chain`), not this pair. + +Each category reference is self-contained. It defines the scope, the finding types in its rubric, the severity tier each one carries, the false-positive guardrails, the non-obvious constraints reviewers must apply, and the rewrite policy for its category. To find out what a Major finding in Integrity looks like, read `integrity.md` — no other file owns that information. + +If a candidate finding doesn't clearly belong to any category, it's an out-of-rubric concern — log it in the JSON `out_of_rubric[]` channel (see [Output Contract](#output-contract)). Do not invent a new category to fit it. + +## Output Contract + +**The reviewer's final message MUST be a single fenced ```json``` code block matching the schema below — and nothing else.** No preceding markdown headings, no trailing prose, no "## Skill Review" wrapper, no narration. The JSON is the artifact. Downstream consumers (a CI action's markdown renderer, dashboards, anyone running the skill locally) parse this JSON; whatever decoration the LLM might add is wasted tokens and breaks the parser. + +```json +{ + "skill": "", + "categories": [ + { + "name": "Structural Discipline", + "status": "pass", + "findings": [] + }, + { + "name": "Integrity", + "status": "findings", + "findings": [ + { + "finding_type": "broken-cross-plugin-reference", + "severity": "major", + "deterministic": true, + "location": "SKILL.md:42", + "explanation": "Reference `acme-tools:nonexistent-skill` does not resolve in the repo.", + "fix": "Create the skill, fix the reference, or remove the claim.", + "suggested_rewrite": null + } + ] + }, + { + "name": "Content Quality", + "status": "findings", + "findings": [ + { + "finding_type": "procedure-smell-with-consequence", + "severity": "major", + "deterministic": false, + "location": "SKILL.md:22-38", + "explanation": "Section `## Checking Deployments` is a 6-step numbered procedure teaching generic deploy-tool usage Claude already knows. Concrete behavior caused: in a sample review fixture, Claude followed the steps verbatim instead of adapting to the user's actual question about a stuck stage.", + "fix": "Replace the numbered procedure with declarative context (which stages tend to get stuck, what locked stages mean, common quirks).", + "suggested_rewrite": "## Deployment Context\n\n- **Stuck stages**: The `asset-compile` stage is the most common bottleneck — it can take 15-20 minutes. If longer, check the sub-deployment logs for OOM kills.\n- **Locked stages**: A locked production stage usually means an active incident — check the incident channel before unlocking. Only on-call can unlock production.\n- **Approval flow**: Production stages need the PR author's team lead approval. Staging auto-approves. Missing approval often means the author merged from a fork.\n- **Rollback signals**: >2 rollbacks in the last hour for the same app may indicate an active incident — check the incident thread before re-deploying." + } + ] + } + ], + "out_of_rubric": [ + { + "location": "SKILL.md:54", + "explanation": "Skill body declares an unusual prompt-caching strategy that doesn't fit any current finding type.", + "rationale": "Cost concern, but not the bash-chain, MCP-result-size, field-projection, or response-style pattern. Logged for monthly rubric review." + } + ] +} +``` + +Field rules: + +- `categories[]` includes all seven categories in rubric order, even when empty. Status is `pass` when `findings: []`, `findings` otherwise. +- `finding_type` is a kebab-case identifier defined in the per-category reference. Reviewers do not invent new identifiers. +- `severity` is `critical | major | minor` — the value the category reference assigns to that finding type, including any explicit escalation predicate. +- `deterministic: true` indicates the finding follows mechanically from reading the file (e.g. cross-plugin reference resolution, prose-vs-table count, a documented-convention frontmatter-field check) and so must be stable across reruns. `false` indicates judgment-bound (rerun variance is expected). The determinism eval filters on this flag. +- `location`, `explanation`, `fix` are required on every finding. `suggested_rewrite` is the rewrite block content per the per-category rewrite policy; `null` when the policy is "describe in prose only". +- `out_of_rubric[]` uses the same shape as a finding (minus `finding_type`, `severity`, `deterministic`) — `location`, `explanation`, and `rationale` are required. These never appear in the PR comment; they're logged for monthly rubric review (a maintainer promotes a finding type with ≥3 instances or a security implication via a follow-up PR). + +## Determinism Contract + +Same skill + same rubric → same findings. The contract is *not* "byte-identical output" — LLM prose varies. The contract is: + +- **Severity stability** — every deterministic finding type produces the same severity across runs. +- **Finding-set stability** — the set of deterministic finding types reported as present is identical across runs. +- **Order stability** — categories appear in rubric order; findings within a category appear in rubric order. +- **Not promised** — prose `explanation` wording, prose `fix` wording, prose inside `suggested_rewrite`. LLM variance is allowed there by construction. + +The `deterministic` field on each finding sets its testing contract: + +| `deterministic` | Meaning | Determinism-eval scope | +|---|---|---| +| `true` | Follows mechanically from reading the file — cross-plugin / MCP / command reference resolution, paired-file byte-diff, prose-vs-table count, documented-convention frontmatter-field check | In scope — assert finding presence + severity across reruns, allow prose variance | +| `false` | Judgment-bound (procedure smell, similar-skill verdict, behaviour bugs, stale evals, etc.) | Out of scope — filtered out of the determinism eval | + +Mark a finding `deterministic: true` only when its presence and severity follow mechanically from the file — never on a judgment call. A deterministic finding that flickers between runs is a bug in the reviewer, not acceptable LLM variance. + +## Reference Files + +Load all seven category references at the start of every review — each category is evaluated every run. Load `suggested-rewrites.md` as well whenever a finding will carry a rewrite. + +- [`references/structural.md`](./references/structural.md) — Structural Discipline (body↔references duplication, conditional reference loading). Load when assessing structural findings. +- [`references/integrity.md`](./references/integrity.md) — Integrity (existence + equivalence; cross-plugin reference blast-radius rules). Load when assessing integrity findings. +- [`references/test-coverage.md`](./references/test-coverage.md) — Test Coverage (eval-requirement by reach, operational-guardrail-untested predicate, eval-quality minors). Load when assessing eval coverage. +- [`references/security.md`](./references/security.md) — Security (credential paste, plaintext secrets, executable-script bugs). Load when assessing security findings. +- [`references/content-quality.md`](./references/content-quality.md) — Content Quality (procedure smell, context-vs-instructions, the rewrite method). Load when assessing what's in the skill body. Hook integration is NOT here — see `convention.md`. +- [`references/convention.md`](./references/convention.md) — Convention (placement, similar-skill duplication, hook integration, repo-convention adherence like an agent's `model:` field). Load when assessing placement and triggering findings. +- [`references/cost.md`](./references/cost.md) — Cost (bash chains, MCP result-size nudges, field projection, response-style discipline). Load when assessing token-efficiency findings. +- [`references/suggested-rewrites.md`](./references/suggested-rewrites.md) — Cross-cutting **format** spec for the rewrite block (details block, placement, authoring constraints). The decision *whether* to rewrite for a given finding lives in that finding's category reference. Load when producing a rewrite. diff --git a/skill-review/references/content-quality.md b/skill-review/references/content-quality.md new file mode 100644 index 0000000..694812d --- /dev/null +++ b/skill-review/references/content-quality.md @@ -0,0 +1,238 @@ +# Content Quality — Detailed Criteria + +## Scope + +Whether the body provides project-specific context Claude couldn't know, or over-prescribes step-by-step procedures Claude could derive itself. + +This category is about **what's in the body** — context vs instructions. It does NOT cover *how the skill fires* (hook integration moved to [`convention.md`](./convention.md) because triggering is a placement/triggering concern, not a content-quality concern). + +This category lives entirely in AI judgment. Detection requires understanding what counts as "context Claude couldn't know" vs "instruction Claude could derive." + +## When This Applies + +Severity tiers in scope: **Critical** (rare), **Major** (rare), **Minor** (typical). + +- **Critical** — declared procedure produces wrong or dangerous output on normal inputs. +- **Major** — procedure smell OR a weak completion criterion, WITH a citable concrete behavior it causes. Don't escalate on taste alone. +- **Minor** — procedure smell, a weak completion criterion, or a no-op instruction, without concrete consequence; over-prescription patterns. + +## Determinism + +**Every finding type in this category is judgment-bound** (`deterministic: false`). Detection requires distinguishing context from instruction and judging whether a numbered list is "procedure smell" vs "checklist of things to verify". Rerun variance is expected; the determinism eval explicitly filters Content Quality findings out of its tuple-equality assertion — it only asserts equality on the deterministic subset across all categories. + +--- + +## Context vs Instructions — The Core Distinction + +Good skills provide **context Claude couldn't know without the skill author**. Bad skills provide **step-by-step procedures Claude could figure out on its own**. + +Claude already knows how to query APIs, write migrations, parse logs, and follow standard workflows. What it doesn't know: + +- How a particular project has configured its tools (environments, datasets, column names) +- Project-specific conventions and quirks that differ from standard setups +- Known footguns and workarounds specific to this codebase or infrastructure +- Which tools/datasets/endpoints to use for which scenarios + +### Good Context Examples + +**Telemetry/observability skill** — tells Claude project-specific configuration: +> Always query with `env: "live"` (NOT "production" — the tool stores it as `live`). Dataset: `svc-metrics`. The fields `latency_ms`, `route`, and `tenant_id` are always present; `session_id` only appears on user-facing spans. When querying DB-level span fields, do NOT filter on `is_entrypoint=true` — those attributes live on child spans. + +This is perfect: environment names, dataset names, column availability, and an exception rule that Claude couldn't derive from the tool's generic documentation. + +**Tooling skill** — warns about a known tool bug: +> An MCP tool whose fully-qualified name exceeds the runtime's 64-character limit fails to register and can crash the session — prefer a shorter-named alias if the server offers one. + +This is the kind of footgun context that saves hours of debugging. + +**Create-migration skill** — documents a project's framework quirks: +> This project uses advisory locks for migrations. The managed database doesn't support foreign keys. Always use `algorithm: :instant` when available. + +These are deviations from the framework's standard behaviour that Claude would get wrong without this context. + +### Bad Context Examples (Procedure Smell) + +**Over-prescribed deployment checker:** +> 1. First, open the deploy tool and check the deployment status +> 2. Then, look at the pipeline stages +> 3. Next, check if there are any locked stages +> 4. If a stage is locked, check who locked it +> 5. Then check the approval status +> 6. Finally, check the rollback history + +This is procedure smell. Claude already knows how to use the deploy tool's MCP tools. The skill should instead tell Claude what's *unusual* about this project's deployment pipeline — which stages tend to get stuck, what locked stages mean organizationally, common deployment quirks. + +**Over-prescribed query workflow:** +> Step 1: Open the telemetry tool. Step 2: Select the `svc-metrics` dataset. Step 3: Add a filter for env=live. Step 4: Set the time range to last 1 hour. + +Compare with the good version above. Same information, but the good version gives configuration facts while the bad version gives instructions. + +### Procedure Smell Heuristics + +Flag a skill when: + +- **Numbered step lists** dominate the content ("Step 1:", "Step 2:", "1.", "2.", "3.") +- **Sequential instructions** assume a specific order ("First... Then... Next... Finally...") +- **The content reads like a tutorial** rather than a reference +- **Removing the steps would leave no content** — if the only value is the ordering, the skill is over-prescribing +- **Each step describes something Claude already knows** — "open the tool", "select the option", "click the button" + +Do NOT flag when: + +- Steps describe a genuinely non-obvious order that matters (e.g., "run migration before seeding because advisory locks require it") +- The procedure encodes project-specific workflow requirements, not generic tool usage +- The numbered list is a checklist of things to verify, not a procedure to follow + +### The Composability Principle + +Skills are composable context blocks — Claude mixes and matches them to accomplish tasks. A skill that tries to orchestrate an entire workflow from end to end is fragile. Skills should provide the building blocks (context, configuration, known-issues) and let Claude compose the workflow based on the user's actual request. + +When a skill violates this: + +- Claude may skip steps it deems unnecessary (and often it's right to) +- The skill becomes brittle when workflows change +- The skill can't be combined with other skills effectively +- Users get frustrated when Claude follows the rigid procedure instead of adapting + +### Temporal Self-Reference — Edit History in the Body + +Skills accumulate edit-history phrasing as they're iterated: "X **now** does Y", "this **no longer** does Z", "we **switched** to W", "that bug **is fixed**, so it returns cleanly". The change was interesting to the author at the moment of editing, but the consumer never saw the prior version — to them the "now / no longer" frame is dead weight, and worse, it rots: the "now" is true only relative to an edit nobody reading the skill can see. Skill bodies should read in **timeless present tense** — state that *X does Y*. + +A skill's own change history already lives in version control (and, for plugins, a derived changelog). The body is the wrong place either way — a self-referential "we changed X to Y" duplicates that history where nothing keeps it in sync. The fix is to drop the edit-history phrasing, not to relocate it: version control is the source of truth. + +**Two kinds of temporal phrasing — only the first is a finding. The deciding factor is whether the consumer collides with the "before", NOT whether the change is about the skill itself:** + +| Kind | Does the consumer still meet the "before"? | Typical subject | Action | +|------|--------------------------------------------|-----------------|--------| +| **Self-reference / dead edit-history** | No — the old state lived only in a past revision of the skill, or is otherwise invisible to the reader (they just use the current form). | usually the skill / its script, but also an external system whose change the skill merely narrates ("the upstream service **now** supports X") | **Flag.** Flatten to present tense. | +| **World-state** | Yes — the old form is still live (old catalog rows, deployed configs, an endpoint that still 405s) and the consumer hits it. | an external entity: a renamed table, a moved endpoint, a deprecated flag. | **Do not flag.** The before→after mapping is reconciliation knowledge. | + +**The distinguishing test:** *does the "before" state still exist somewhere the consumer will encounter it?* If yes — old catalog rows, deployed configs, historical dashboards, an endpoint that still 405s — keep the mapping; it's content. If the "before" only ever existed in a prior revision of the skill text, it's edit history; flatten it. + +World-state phrasing to **leave alone** (the mapping is the payload): + +- "the `incidents` table was renamed to `issues`" — an agent querying the warehouse will see both names; the alias is the Rosetta stone. +- "the API moved its MCP endpoint from `/api/ai/mcp` to `/api/mcp/public`; the old path now returns HTTP 405" — the skill's job is to fix stale configs that still point at the old path. +- "(formerly 'Free tier')", "(formerly % Actioned)" — aliases the consumer meets in existing reports. + +Self-reference to **flag and flatten**: + +- "that bug is fixed, so it now returns cleanly" → "returns cleanly" (or drop entirely if the working behaviour is already stated). +- "the upstream service now supports SSO as a first-class option" → "supports SSO as a first-class option". +- "do not assume the script shortens the line — it no longer does" → "it does not". + +**When the framing wraps a load-bearing fact, keep the fact — flatten only the framing.** Self-reference often rides on top of a real current-state fact (an ordering constraint, a config value, a reason). "We switched the dedup step to run before enrichment" carries an ordering constraint that still governs behaviour — flatten to "Dedup runs before enrichment", do not drop the sentence. Drop a sentence wholesale only when nothing but edit history remains once the framing is gone (e.g. a since-fixed bug whose working behaviour is already stated elsewhere). + +Severity: **Minor** by default (cosmetic rot). Escalate to **Major** only when the stale "now" actively misleads — e.g. "now returns cleanly" describing behaviour that has since regressed, where the temporal claim asserts something currently false. + +**Out of scope / false-positive guardrails — do NOT flag:** + +- **Explicit changelog / version-history sections** (`## Changelog`, `**v0.2.0** — …`). Temporal phrasing is correct there — that's the one place edit-history belongs. (Whether such a section should live in the body at all is a separate, larger question; note it, don't flatten it.) +- **World-state changes** (the right column above). +- **Domain vocabulary** — "No longer relevant" as a triage *verdict*, "used to filter" in its *purpose* sense, "has since changed" as a *conditional the skill reasons about* ("if the code has since changed, …"). +- **Dated provenance with an audit trail** — "(added 2026-04-27)" attached to a fact the author deliberately timestamped so a maintainer can judge staleness. That's a knowledge-base convention, not rot. + +The finding type is `temporal-self-reference` (`deterministic: false` — distinguishing self-reference from world-state needs the judgment of "does the old form still exist out there?", which a regex can't make). + +### Generating Suggested Rewrites + +When a review flags procedure smell or poor context quality, **generate a concrete rewrite of the problematic section** — don't just describe the problem. Authors ignore abstract feedback ("this has procedure smell") but act on tangible alternatives they can copy-paste. + +**The Rewrite Method:** + +To transform a procedural section into context: + +1. **Extract the facts** — What does Claude learn from each step that it couldn't infer? Dataset names, column names, environment values, tool quirks, known gotchas. +2. **Discard the choreography** — Remove ordering words ("First", "Then", "Next"), generic tool instructions ("Open the tool", "Run the query"), and anything Claude already knows how to do. +3. **Restructure as reference** — Present the extracted facts as declarative statements, tables, or constraint lists. + +**Rewrite Example — Deployment Checker:** + +Before (procedure smell): +```markdown +## Checking Deployments + +1. First, open the deploy tool and check the deployment status using `deploy_find` +2. Then, look at the pipeline stages with `deploy_list_pipeline_stages` +3. Next, check if there are any locked stages with `deploy_locked_stages` +4. If a stage is locked, check who locked it and why +5. Then check the approval status with `deploy_approvals` +6. Finally, check the rollback history with `deploy_rollback_history` +``` + +After (context): +```markdown +## Deployment Context + +- **Stuck stages**: The `asset-compile` stage is the most common bottleneck — it can take 15-20 minutes. If it's been longer, check for OOM kills in the sub-deployment logs. +- **Locked stages**: A locked production stage usually means someone is actively investigating an incident. Check the incident channel before attempting to unlock. Only on-call can unlock production. +- **Approval flow**: Deployments need approval from the PR author's team lead for production stages. Staging auto-approves. If approval is missing, the author may have merged from a fork (no team association). +- **Rollback signals**: If `deploy_rollback_history` shows >2 rollbacks in the last hour for the same app, there may be an active incident — check the deployment's incident thread before re-deploying. +``` + +**What to include in the suggested rewrite:** + +- Be a **complete replacement** for the flagged section — ready to copy-paste into SKILL.md +- Preserve all project-specific facts from the original (don't lose real context buried in procedure) +- Be shorter than the original (removing choreography naturally reduces length) +- Use declarative structure: tables, constraint lists, "when X, Y applies" patterns +- Include section headers that match the original so the author can do a clean swap + +**What NOT to include:** + +- Don't invent context that wasn't in the original — only restructure what's already there +- Don't add new recommendations beyond what the skill already covers +- Don't change the skill's scope or intent + +--- + +## Beyond Procedure Smell — Completion Criteria and No-Ops + +Procedure smell is over-prescription of *steps*. Two adjacent defects over-prescribe nothing yet still degrade a skill: a fuzzy stop condition, and a line that restates a default. Both are Content Quality (they're about what's in the body), both are judgment-bound, and both are under-fired — nothing jumps out on a first read, so the skill looks fine until you ask the no-op test of each instruction. + +### Weak completion criterion (`finding_type`: `weak-completion-criterion`) + +**Pattern.** A skill drives a multi-step or open-ended task but its stop condition can't distinguish *done* from *not-done* — "review the code", "produce a change list", "investigate until you understand it", "leave the code in good shape". When the criterion is fuzzy, Claude's attention slips to the finishing state and it declares completion early (premature completion): the work reads as finished without being finished. (A criterion that is *already* both observable and exhaustive for the task it gates — "all tests pass" for a test-fixing skill whose whole job is the suite — is not this finding; the defect is a criterion that is unobservable *or* observable-but-under-scoped, not the mere presence of a final step.) + +**Fix.** Sharpen the criterion into something **checkable** (done vs not-done is observable) and **exhaustive where it matters** ("every model touched in this PR has a corresponding migration entry", not "produce a change list"). When a *later* step is what tempts the early exit — Claude races to the visible finish and skips the legwork of the current one — the structural fix is to split the sequence so the current step must close before the next becomes visible; name that split in the fix. + +**Severity.** Minor by default. **Major** when you can cite a concrete behavior the fuzzy criterion causes (an eval or fixture where Claude stopped short). Same "don't escalate on taste" bar as procedure smell. + +**Deterministic.** No — judging whether a stop condition is checkable-and-exhaustive vs fuzzy is judgment-bound. + +**How to spot it.** Find the skill's completion language — "report your findings", "when done", "produce X", the last step of a numbered list. Ask two questions: (1) could two reasonable runs disagree on whether the task is finished (unobservable)? and (2) could a run satisfy the criterion while leaving load-bearing work the skill is responsible for undone (observable but under-scoped — e.g. "all migration files reviewed" when the real job is classifying every statement)? If either holds, and the skill drives real work (not a pure-context block), it's a weak criterion. + +### No-op instruction (`finding_type`: `no-op-instruction`) + +**Pattern.** A body line instructs behavior Claude already does by default — "be thorough", "think carefully", "use good judgment", "make sure your answer is correct", "be helpful". It pays context tokens to say nothing and dilutes the load-bearing instructions next to it. A weak leading word ("be thorough") is the common shape: the line names a virtue the model already aims at, so it changes no behavior. + +**The no-op test.** Run it on each sentence in isolation: *would removing this sentence change Claude's behavior versus its default?* If not, it's a no-op — delete the whole sentence rather than trimming words from it. + +**Fix.** Delete the line. If the author actually wanted *more* than the default — real extra thoroughness, not the baseline — restating the default won't get it: replace the weak word with a strong leading word that genuinely shifts behavior ("exhaustively enumerate every X", "relentless"), or attach a concrete, checkable bar. The technique stays; the no-op wording goes. + +**Severity.** Minor. + +**Deterministic.** No — deciding a line restates the default (vs carries project-specific teeth) is judgment. + +**How to spot it.** Scan for exhortations with no project-specific object: adjectives of diligence ("careful", "thorough", "diligent"), generic quality reminders ("ensure correctness", "do a good job"). A line is a no-op only when stripping it leaves behavior unchanged — an exhortation tied to a real footgun ("be careful: the managed database silently drops the FK") is context, not a no-op. + +--- + +## Out of Scope / False-Positive Guardrails + +- **Numbered checklists are not always procedure smell.** A checklist of *things to verify* (not steps to perform in order) is fine — it's a reference structure, not a runbook. +- **Sequential steps for genuinely sequential dependencies are not procedure smell.** "Run the migration before seeding because advisory locks require it" is real ordering context Claude couldn't derive. +- **Hook integration is NOT a Content Quality finding.** Whether a skill should auto-fire on a file write, command, or tool invocation is a placement / triggering concern. See [`convention.md`](./convention.md) § Hook Integration. +- **A fuzzy-sounding criterion in a pure-context skill is not `weak-completion-criterion`.** A context/reference block has no task to complete — there's no step whose stop condition could be premature. Fire only when the skill drives real multi-step work. +- **Emphasis tied to a project-specific footgun is not a no-op.** "Be careful — advisory locks make this non-reentrant" carries teeth Claude couldn't derive. The no-op test fails only when removing the line changes nothing versus default behavior. + +## Rewrite Policy + +**Produce a suggested rewrite for every procedure-smell / vague-context / `temporal-self-reference` finding that touches SKILL.md.** For `temporal-self-reference`, the rewrite restates the sentence in present tense — keeping the facts that still describe current behaviour and dropping the edit history itself (what changed, the prior behaviour, a since-fixed bug). The edit history is not a current-state fact, so dropping it is not "losing a fact": e.g. "filtering used to time out from a bug that is now fixed, so it returns cleanly" reduces to "filtering returns cleanly" (or to nothing, if that is already stated elsewhere). This is the category where rewrites are most load-bearing — abstract feedback ("this is procedure-smell") doesn't move authors, but a concrete replacement section does. The Rewrite Method earlier in this file is the authoring guide; [`suggested-rewrites.md`](./suggested-rewrites.md) owns the format spec (collapsible block, placement, authoring constraints). + +**`weak-completion-criterion` also gets a suggested rewrite** — the sharpened, checkable criterion is concrete and copy-pasteable, so it carries the same load-bearing value. **`no-op-instruction` gets prose only by default** ("delete lines X–Y — they restate the default"); attach a `suggested_rewrite` only when the fix is a strong-leading-word replacement rather than a deletion, in which case the rewrite is the replacement line. + +## Notes for Implementers + +- Content Quality is the category with the highest false-positive risk. Detection lives entirely in AI judgment because "is this context Claude couldn't know?" requires understanding the broader domain. +- The Suggested Rewrites mechanism is a key product of this category — see `references/suggested-rewrites.md` for format/authoring constraints. The rewrite is the actionable artifact; the finding alone is too abstract to act on. diff --git a/skill-review/references/convention.md b/skill-review/references/convention.md new file mode 100644 index 0000000..004e959 --- /dev/null +++ b/skill-review/references/convention.md @@ -0,0 +1,337 @@ +# Convention — Detailed Criteria + +## Scope + +Placement + triggering. Six concerns live here: + +1. **Placement** — where a skill lives (personal, project, or a shared plugin). +2. **Similar-skill duplication** — whether another skill in scope covers the same job. +3. **Hook integration** — whether a deterministic trigger event would improve how the skill fires. +4. **Repo-convention adherence** — does the skill follow the repo's own documented frontmatter/authoring conventions. +5. **Skill-vs-script shape** — whether a skill is built as an end-to-end deterministic orchestrator when it should be a thin context block over a bundled script. +6. **Invocation mode** — whether a skill that can't usefully auto-fire (slash-command-only, or a sealed-input sub-routine) is needlessly shaped for it, paying description budget + router noise for discovery it never uses. + +## When This Applies + +Severity tiers in scope: **Major**, **Minor**. + +- **Major** — skill in a clearly-wrong location (the wrong-placement predicate), unambiguous duplicate skill should be merged, a description that carries _no routing signal at all_ (pure feature inventory with nothing a router can match on), a skill shaped as an end-to-end deterministic orchestrator (the orchestration-shaped-skill predicate, Major by default), or a widely-shared skill that can't usefully auto-fire shipping a full multi-trigger auto-fire description (the invocation-mode-mismatch escalation). +- **Minor** — similar-skill differentiation suggestions, hook-integration opportunities, convention drift (frontmatter field violations), a description that leads with a feature list but still contains some trigger signal, a single extractable chain in an otherwise context-rich skill (prefer Cost's `scriptable-bash-chain` for that case), or a skill that can't usefully auto-fire still shipping a multi-trigger auto-fire description (the invocation-mode-mismatch default). + +## Determinism + +Convention findings are mostly judgment-bound. Placement requires deciding whether referenced tools/datasets/workflows are broadly applicable; similar-skill detection surfaces candidates by reading, but the merge/differentiate/leave-alone verdict is judgment; the description-as-routing-signal finding is judgment (distinguishing a feature inventory from a purpose statement); the repo-convention frontmatter-field check is the lone deterministic finding in this category (a field-value comparison against a documented rule). + +--- + +## Skill Placement (the wrong-placement predicate) + +### Decision Tree + +Evaluate a skill's placement by matching its content scope to the right location: + +| Content Scope | Correct Location | +| -------------------------------------------------------- | --------------------------------------------------- | +| Personal workflow, individual preferences | Local `~/.claude/skills/` on the engineer's machine | +| Unproven, might help others, or new to one team | Its own new plugin, or a team plugin | +| Team-specific workflows or data (cross-repo) | A team plugin | +| Broadly useful workflow or tool (cross-repo, cross-team) | A widely-shared plugin published to a marketplace | +| Specific codebase context | Repo-level `.claude/rules/` or `.claude/skills/` | + +### Rule of Thumb + +If the skill only makes sense in one codebase, it belongs in that repo. If it works across repos but only for one team, it belongs in a team plugin. If it would help every engineer, it belongs in a broadly-shared plugin. + +### Common Misplacements + +**General content in a team plugin.** Signal: the skill's content is about general development practices (debugging, testing, code review) but lives in a team-specific plugin. Fix: move to a broadly-shared plugin, or add team-specific context that justifies the placement. + +**Team-specific content in a broadly-shared plugin.** Signal: the skill references team-specific tools, datasets, or workflows that most engineers wouldn't encounter. Fix: move to the appropriate team plugin. If the team doesn't have a plugin yet, suggest creating one. Severity: **Major** (the wrong-placement predicate). **Deterministic:** No — "team-specific" requires judging whether the referenced tools, datasets, or workflows have broad applicability. + +**Repo-level content in a plugin.** Signal: the skill's context is tightly coupled to a specific codebase — file paths, class names, architecture patterns that only make sense in one repo. Fix: move to the repo's `.claude/skills/` or `.claude/rules/` directory. + +### Rules vs Skills + +A rule is a simplified skill — context triggered when a specific part of the codebase is accessed. Consider a rule instead of a skill when: + +- The context applies only to specific files or directories +- There's no need for references, scripts, or examples +- The content is short (a few paragraphs) +- The trigger is file-path-based, not intent-based + +Rules live in `/.claude/rules/` and are simpler to maintain than full skills. + +### Promotion Criteria + +When a repo- or team-specific skill grows to wide adoption, consider promoting it to a broadly-shared plugin: + +- Multiple teams or repos would benefit from the same context +- The skill's content is generalizable beyond one codebase + +### New / unproven skills + +Don't dump a new or unproven skill into a broadly-shared plugin prematurely — once a skill is used from a given path, users come to depend on that path and it's hard to migrate out. Recommend instead: + +- **Its own new plugin** — for a standalone skill. +- **A team plugin** — when it fits an existing team's plugin. + +Once several teams depend on it, it can be promoted into a broadly-shared plugin. + +### Checking Placement + +When reviewing a skill's placement: + +1. Read the SKILL.md content and identify the scope (personal, team, broadly-useful, repo-specific) +2. Check the current location from the directory path +3. Compare scope to location using the decision tree above +4. If mismatched, recommend the correct location with reasoning +5. If the content is borderline, note that it could go either way and explain the trade-off + +--- + +## Skill-vs-Script Shape (the orchestration-shaped-skill predicate) + +**`finding_type`: `orchestration-shaped-skill`.** + +The shape lens on the same smell that [`cost.md`](./cost.md) catches as `script-extractable-orchestration`. A skill is a **context block** Claude composes into a task — facts, configuration, known footguns, judgment guidance. A skill is mis-shaped when it is instead an **end-to-end deterministic orchestrator**: its dominant content is a fixed pipeline (pinned queries, a set sequence of tool/MCP calls, output templates, format conversions) that an LLM re-derives from prose every run, with genuine judgment a thin minority. That belongs as a bundled script with a thin skill on top — not as prose the model re-executes. + +This is the same idea as **Rules vs Skills** above (a rule is a simplified skill) pushed one step further: when the deterministic surface is large enough to be _code_, the right container is a `scripts/` file, not a SKILL.md. + +### Finding type + +| Finding type | Severity | Det? | +| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ---- | +| Skill is shaped as an end-to-end deterministic orchestrator; the deterministic pipeline should be a bundled script with a thin skill on top | **Major** (default) | N | + +**Pattern.** The skill's substantive content is dominated by deterministic specification — fixed queries, hardcoded IDs/values, set call sequences, exact output templates, mechanical conversions — and the genuine judgment (fuzzy classification, NL synthesis, content-contingent decisions the author couldn't enumerate) is a thin minority. Count body **and** `references/`. + +**Fix (extract-glue — never "delete the skill").** Recommend restructuring: move the deterministic pipeline into a bundled `scripts/` file the skill invokes, and keep the SKILL.md as the thin layer that runs the script and handles the judgment kernel. Name which sections are pipeline and which are kernel. Do not tell the author to remove the skill — the kernel is what keeps it a skill. + +**Severity.** **Major by default** — a mis-shaped skill carries its full deterministic surface into every session's context and re-derivation, and the shape is hard to migrate once users depend on the skill path. Downgrade to **Minor** only when the orchestration is a _single_ extractable chain in an otherwise context-rich skill — and in that case prefer Cost's `scriptable-bash-chain`. No Critical. + +**Deterministic.** No — estimating the glue:judgment ratio and judging "this is an orchestrator, not a context block" is judgment-bound. + +**Firing bar (Major-by-default ⇒ strict).** Fire on _dominance_, not _presence_ — almost every skill has some glue. Do NOT fire when the deterministic steps feed a genuine judgment output that is the skill's product; do NOT fire on pure-context / pure-reference skills (all project-specific facts, no executed sequence — that is the ideal skill shape); do NOT fire on small skills (<100 lines measured across SKILL.md body **plus** `references/` combined — not the body alone, since glue hides in references). + +**Boundary with Cost.** Same defect, two lenses: Cost (`script-extractable-orchestration`) owns the _per-session token-cost mechanism_; Convention (`orchestration-shaped-skill`) owns the _shape_ judgment ("should this be a skill at all, or a script with a thin skill?"). When a skill is mostly glue end-to-end, file **both** (one finding per category — the rubric already files two when a skill is both mispriced and misplaced). When only a single chain is extractable from an otherwise-sound skill, file Cost alone. Both share the extract-glue fix; neither ever recommends deletion. + +--- + +## Similar Skills / Duplication Risk + +Duplication is the most expensive form of skill rot — two skills in different plugins that cover the same job drift apart, surprise Claude's trigger matcher, and force authors to maintain the same project-specific facts in two places. + +This dimension surfaces potential overlap between the skill under review and other skills in scope so the author can decide: **merge**, **differentiate**, or **leave alone**. + +### What "Similar" Means + +Similarity is not a single threshold — it's a layered signal. A pair of skills is only a rot candidate when **two or more** signals line up. A single signal alone is noise. + +### Signal Hierarchy + +| Signal | Strength | Detection | +| ------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------ | +| Near-duplicate sentences in `description` frontmatter | Strong | Sentence-level overlap, not just shared domain words | +| Overlapping trigger phrases (the quoted `"..."` phrases in descriptions) | Strong | Same user-facing verb + object ("check CI status", "create a PR") | +| Same underlying tool + same audience + same verb | Strong | Both "query the warehouse for revenue", both "post a release note" | +| Identical `allowed-tools` + overlapping domain | Medium | Same MCP + same reference files | +| Related names with overlapping scope | Medium | `foo-data` vs `foo-query`, `investigate-X` vs `X-investigator` | +| Same plugin + same broad domain (observability, PRs, data) | Weak | Not enough alone — most plugins specialize in a domain | +| Shared trigger words but different objects | Weak | Both mention "review" but one reviews PRs, other reviews skills | + +### False-Positive Patterns + +These look similar but are **intentional** — flagging them is noise. + +| Pattern | Why it's fine | +| -------------------------------------------------- | --------------------------------------------------------------- | +| Regional variants (`-us`, `-eu`, `-au`) | Deliberate separation for data-residency compliance | +| Environment variants (`-experimental`, `-staging`) | Different maturity tiers | +| Same domain, different backends | Two different observability tools — different data | +| Same tool, different datasets | Same query tool over a production app vs an analytics warehouse | +| General skill + specialized workflow | A general query skill vs a specific named runbook | +| Same verb, different audience | A query skill for engineers vs one for analysts | + +### Detection Method + +Extract 3-5 distinctive nouns/verbs from the skill's purpose — domain terms, not generic words like "query" or "check". Then: + +1. `Glob plugins/*/skills/*/SKILL.md` and `.claude/skills/*/SKILL.md` to enumerate candidate skills. +2. `Grep` those distinctive terms across the frontmatter `description:` lines to surface adjacent skills. +3. Read the top matches' full SKILL.md files and apply the signal hierarchy above to decide: merge, differentiate, or leave alone. + +Does **not** render a merge/differentiate/leave-alone verdict automatically — that requires judgment on whether the lexical overlap reflects real scope overlap. + +### Recommended Actions + +For each surfaced candidate, suggest **one** of these three — don't hedge. + +**Merge.** Both skills do substantially the same job. Consolidating reduces drift and simplifies discovery. + +- When: Strong description overlap, same audience, same underlying tool, no meaningful scope distinction. +- Suggest: which skill survives (usually the one with better evals, more recent updates, or the more comprehensive references/), and a one-line note on what facts need to carry over from the other. +- Severity: typically **Major** if unambiguous, **Minor** if borderline. + +**Differentiate.** The skills are genuinely distinct but their descriptions or trigger phrases conflate them. Claude's router will pick the wrong one. + +- When: both skills have legitimate non-overlapping use cases, but the descriptions share trigger phrases or fail to call out the distinction. +- Suggest: a concrete edit to the description of the skill under review — sharpen the triggers to exclude the other skill's scope. +- Severity: **Minor**. + +**Leave alone.** The similarity is superficial or intentional. Document the decision so the next reviewer doesn't re-flag it. + +- When: regional/environment variants, same domain but different backends/datasets, or general skill + specialized workflow. +- Suggest: nothing to change — but optionally note the distinction in the description for future clarity. + +--- + +## Hook Integration + +Not all skills need hooks. Only suggest a hook when there is a **concrete, deterministic trigger event** — a specific file being written, a specific command being run, or a specific tool being invoked. "No hook needed" is a valid and common verdict for intent-based skills. + +### Finding Types + +| Finding type | Severity | Det? | +| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | ---- | +| Hook would improve triggering determinism (specific file write, CLI command, or tool invocation event) | Minor (informational) | N | +| "No hook needed" — intent-based or broad-domain skill | n/a (informational only, not surfaced as a finding) | N | + +### When Hooks Add Value + +**File-write patterns.** The skill applies when specific files are created or modified. A PreToolUse Write hook matching the file path ensures the skill loads. Example: a migration skill applies when writing to `db/migrate/*.rb` — hook matches the path. + +**Command patterns.** The skill applies when a specific shell command is run. A PreToolUse Bash hook matching the command pattern triggers deterministically. Example: a create-PR skill firing on `gh pr create`. + +**Tool invocation patterns.** The skill applies when a specific MCP tool is called. A PreToolUse hook on the tool name triggers deterministically. Example: an observability skill could hook on its server's tool-name pattern (`mcp____*`) to load context before queries. + +**Eval reliability.** The skill has good evals but they fail intermittently because description-based triggering is non-deterministic. A hook provides deterministic triggering during eval runs. Mention this separately from the core triggering concern — it's a test-infrastructure benefit, not a runtime triggering improvement. + +### When Hooks Are Unnecessary + +**Intent-based skills.** The skill triggers on user intent expressed in natural language, with no specific file/command/tool trigger. Example: a "learn" skill — there's no file or command that would fire it; the description handles triggering. + +**Broad domain skills.** Many different actions could apply, making a specific hook impractical. Example: a "code-review" skill applies to any code review activity — too broad a trigger surface for a single hook. + +**Reliably-triggered skills.** The description already triggers reliably in practice. If users consistently get the skill when they need it, a hook adds complexity without value. Test this by reviewing `trigger-evals.json` results or skill-activation telemetry. + +### Pragmatic Assessment Framework + +When reviewing for hook opportunities, ask: + +1. **Specific file pattern?** Skills mentioning directories, file extensions, or path patterns → suggest PreToolUse Write hook with path matcher. +2. **Specific command?** Skills applying when running specific CLI commands → suggest PreToolUse Bash hook with command matcher. +3. **Specific tool?** Skills wrapping or guiding MCP tool usage → suggest PreToolUse hook on the tool name. +4. **None of the above?** → "No hook needed. Description-based triggering is appropriate for this skill." + +### Hook Configuration Reference + +Hooks live in the plugin's `hooks.json`: + +```json +{ + "hooks": [ + { + "type": "command", + "event": "PreToolUse", + "matcher": "Write", + "command": "path/to/hook-script.sh" + } + ] +} +``` + +The hook script receives tool input as JSON on stdin and can output instructions for Claude. Exit code 0 = allow, exit code 2 = block with message. + +--- + +## Description as a Routing Signal + +**`finding_type`: `description-as-routing-signal`.** + +A skill's `description` is loaded into every session and is the surface Claude's router matches against. It must state **what the skill is for and when to reach for it** — a routing signal. When the first sentence instead enumerates the skill's _implementation features_ ("does duplicate-check, scoring, ownership routing, and a draft GitHub issue"), it reads as a body summary, not a trigger, and the router has nothing crisp to match — the skill mis-fires or fails to fire. + +This is the **semantic** half of description quality. The mechanical description-shape concerns — over-length, preamble, keyword spray — are **out of this skill's scope**. This finding is only the judgment call that can't be made mechanically: "does the first sentence route, or does it summarise the body?" + +### Finding type + +| Finding type | Severity | Det? | +| -------------------------------------------------------------------- | ---------------------------------------------------------- | ---- | +| Description summarises the body instead of stating purpose + trigger | Minor, or Major when there is **no** routing signal at all | N | + +**Pattern.** The description's opening leads with a feature/implementation inventory rather than an action-led purpose statement. The canonical fix shape is a single sentence naming the job and the trigger: _"Triage a Continuous Improvement submission — check duplicates, score feasibility, route ownership, and draft a GitHub issue."_ + +**Severity.** Minor by default (a feature-list opener that still contains some matchable trigger signal). **Major** only when the description carries no routing signal at all — pure feature inventory a router can't act on. Do not escalate on taste; if a reasonable trigger phrase is present, it's Minor. + +**Deterministic.** No — distinguishing "feature inventory" from "purpose statement" is judgment. Follow the project's skill-description style guidance (and Anthropic's public guidance on writing skill descriptions); cite it in the fix. + +**Fix.** Rewrite the first sentence as an action-led purpose + trigger. This is the one description finding that gets a suggested rewrite (see Rewrite Policy below) — the corrected `description:` line. + +**Boundary.** If the only problem is mechanical description shape (length, preamble, keyword spray), there is NO Convention finding — those are out of this skill's scope. This finding requires a _semantic_ defect: does the first sentence route, or summarise the body? + +## Invocation Mode (the invocation-mode-mismatch predicate) + +**`finding_type`: `invocation-mode-mismatch`.** + +A skill's `name` + `description` load into every session's system prompt and compete in Claude's router. That cost buys _discovery_ — the router can auto-fire the skill when user intent matches. A skill that **can't usefully auto-fire** — a slash-command-only skill, or a sealed-input sub-routine that consumes a structured object a router could never supply — never needs that discovery, so the auto-fire surface is pure overhead: context budget spent and router noise added for a skill that will never usefully auto-fire. The mismatch is such a skill shaped as if it wants discovery. (Being dispatched by another skill, or carrying `user-invocable: false`, does _not_ by itself put a skill here — a dispatched or non-user-invocable skill can still be a legitimate intent-driven auto-fire skill.) + +### Finding type + +| Finding type | Severity | Det? | +| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---- | +| Skill that can't usefully auto-fire (slash-command-only, or a sealed-input sub-routine) still ships a multi-trigger auto-fire description | **Minor** (default); **Major** for a widely-shared skill with a full auto-fire description | N | + +**Pattern.** A skill carries an auto-fire surface that does no useful work. Two things must both hold. **(1) Auto-fire can't help this skill** — it is either slash-command-only (declares "run via /", "only when the user explicitly asks", "invoked intentionally") or a sealed-input sub-routine that consumes a structured object an upstream orchestrator/adapter produces (e.g. "consumes a TriageContext and emits a sealed TriageResult"), so a router auto-fire from a bare user prompt could never supply what it needs. **(2) It is shaped to court the router anyway** — its `description:` is a multi-trigger surface ("Use when the user mentions X, asks to Y, says Z…") built to win an auto-fire it can't use. That wasted description is the defect. (Setting `disable-model-invocation: true` is good hygiene for such a skill, but a clean one-line description with the field merely unset is the acceptable precision boundary — do not fire on a missing field alone.) **What does NOT establish (1):** `argument-hint` / `$ARGUMENTS` (auto-fire skills carry those too), `user-invocable: false` (it blocks _user_ invocation, leaving the skill model-reached — many auto-fire skills set it), or "dispatched by X" / "never invoked directly" on their own (a dispatched skill can still be a legitimate auto-fire skill). A skill whose auto-fire is its actual purpose — it acts on free-form user intent, like a context or domain skill — is never in scope, however rich its triggers. + +There are **two** correct end states, depending on how the skill is reached: + +- **Slash-command skill** (the user runs `/`): `disable-model-invocation: true` plus one action-led purpose line that names the invocation — e.g. "Stress-test a Linear issue's plan against the codebase; runs only when the user invokes /grill-me." Lead with the verb: a description starting "Use when…" fails the no-preamble convention many description linters (and Anthropic's guidance) enforce. +- **Helper-only skill** (dispatched by another skill / orchestrator, never user-run): `disable-model-invocation: true` plus a one-line description of _what it does and who dispatches it_ — e.g. "Dispatched by the triage orchestrator to verify hypotheses against live code and return a TriageResult." Do NOT rewrite a helper-only "called by / dispatched by" description into user-invocation text; that misstates how the skill runs. (Note: a `user-invocable: false` skill is _not_ user-invoked-only — that field blocks the user from invoking it, leaving it model- or dispatch-reached. The field that turns auto-fire off is `disable-model-invocation: true`.) + +**Fix.** Collapse the multi-trigger `description:` to a one-line purpose statement matching how the skill is reached — an action-led purpose line naming the slash invocation for command skills, or a _what-it-does + who-dispatches_ line for sub-routines — and set `disable-model-invocation: true` so the router can't fire a skill that can't use the invocation. Never convert a sub-routine's "called by / dispatched by" description into user-invocation text, and never lead a rewritten description with "Use when…" — the no-preamble convention rejects that, so lead with the action verb. Cite the project's skill-description style guidance. + +**Severity.** Minor by default. **Escalate to Major when** the skill is widely shared AND the `description:` is a full multi-trigger auto-fire surface — there the wasted description loads into thousands of sessions and the router noise competes against skills that _do_ need to fire. Cite the predicate; silent escalation is not allowed. + +**Deterministic.** No — the `disable-model-invocation` field value is a mechanical read, but judging "auto-fire can't usefully serve this skill" is judgment-bound, so the finding overall is `deterministic: false`. + +**How to spot it.** (1) Decide whether auto-fire could do useful work for the skill: a slash-command-only skill or a sealed-input sub-routine cannot, while an intent-driven context/domain skill can — never infer "can't auto-fire" from `argument-hint`, `user-invocable: false`, or "dispatched by X" alone. (2) If it can't usefully auto-fire, check the `description:`: a multi-trigger auto-fire surface is the defect. A clean one-line description is the acceptable boundary even if `disable-model-invocation` is unset — don't fire on the missing field alone. (3) Fire only when the skill is in scope AND ships a multi-trigger auto-fire description. A model-invoked skill whose rich trigger description does real routing work is correct and normal — not this finding. + +**Boundary with `description-as-routing-signal`.** That finding fixes a _model-invoked_ skill whose description fails to route (sharpen the triggers so it fires). This finding _drops a wasted auto-fire surface_ from a skill that can't usefully auto-fire (collapse the multi-trigger description; set the field for sealed-input sub-routines). They point in opposite directions — never file both on the same skill. Mechanical description-shape (length, preamble, keyword spray) stays out of scope; this is the semantic call of whether the invocation _mode_ fits the skill's purpose. + +## Repo-Convention Findings + +**`finding_type`: `repo-convention-violation`.** + +**Pattern.** The skill's (or a bundled agent's) frontmatter violates a convention the repo documents for itself — in its `CLAUDE.md`, contributing guide, or authoring docs. The canonical example: an agent declares `model: inherit` where the repo's documented default is a specific model (e.g. `model: sonnet` unless the task explicitly justifies a larger one), and `inherit` can silently resolve to a pricier model. Other examples: a required metadata field omitted, a naming convention the repo enforces. + +**Detection.** Read the repo's own documented conventions, then compare the skill's frontmatter field values against them (a field-value comparison). Only flag against a convention the repo actually documents — do not invent one. + +**Severity.** Minor. + +**Deterministic.** Yes — frontmatter field comparison against a documented rule. + +**Fix.** Change the field to the documented value (e.g. `model: inherit` → `model: sonnet`), and note the justification in the PR description if the convention allows an exception. + +--- + +## Out of Scope / False-Positive Guardrails + +- **Single signals don't trigger duplication findings.** A pair of skills sharing one weak signal is noise. Require ≥2 signals from the hierarchy to flag. +- **Regional and experimental variants are intentional.** Regional variants (`-us`/`-eu`/`-au`) and `-experimental` twins exist for deliberate reasons (data-residency compliance, maturity tiers); never flag them as duplicates. +- **"No hook needed" is the most common hook verdict.** Don't manufacture hook opportunities to fill the category. Intent-based and broad-domain skills are correctly described-triggered. +- **Cost-efficiency patterns are NOT in this category.** Bash chains, MCP result-size nudges, field projection, and response-style discipline live in [`cost.md`](./cost.md). A skill in the wrong location AND with expensive bash chains gets two findings, one per category. +- **`orchestration-shaped-skill` deliberately co-fires with Cost.** It is the one intentional cross-category pair: the same deterministic-orchestration smell is filed in Cost (`script-extractable-orchestration`) AND Convention (`orchestration-shaped-skill`) when a skill is mostly glue end-to-end. This is by design. A single extractable chain in an otherwise-sound skill is Cost only. +- **Body shape findings are NOT in this category.** Body↔references duplication and flat-reference-list problems live in [`structural.md`](./structural.md). +- **Model invocation is the correct default — do NOT fire `invocation-mode-mismatch` on most skills.** Auto-fire is how the great majority of skills are meant to work. Fire only when auto-fire can't do useful work for the skill (slash-command-only, or a sealed-input sub-routine) AND it still ships a multi-trigger auto-fire description that courts the router. Never fire from `argument-hint` / `$ARGUMENTS`, `user-invocable: false`, or "dispatched by X" / "never invoked directly" on their own. A clean one-line description is the acceptable boundary — do not fire on a missing `disable-model-invocation: true` alone. And never fire merely because a description is long — mechanical description shape is out of scope. +- **Content-quality findings are NOT in this category.** Procedure smell and context-vs-instructions live in [`content-quality.md`](./content-quality.md). Hook integration is here because triggering is a placement/fit concern, but procedure smell is still about _what's in the body_. +- **Only flag a repo-convention violation against a documented convention.** If the repo doesn't document the rule, there's no finding — don't impose a convention from another project. + +## Rewrite Policy + +**Produce a suggested rewrite for three findings: the similar-skill "differentiate" verdict, the `description-as-routing-signal` finding, and `invocation-mode-mismatch`.** For "differentiate", write the sharpened `description:` text that explicitly redirects the user to the neighbor skill. For `description-as-routing-signal`, write the corrected first sentence as an action-led purpose + trigger per the project's skill-description style guidance. For `invocation-mode-mismatch`, the rewrite is the corrected frontmatter — `disable-model-invocation: true` plus the collapsed one-line `description:` as an action-led purpose statement (naming the slash invocation for command skills, or a what-it-does + who-dispatches line for sub-routines; never user-invocation text for a sub-routine, and never a "Use when…" preamble). In all three the rewrite is frontmatter, not the whole skill (see [`suggested-rewrites.md`](./suggested-rewrites.md) for the rewrite-block format). + +**For everything else in this category, describe the fix in prose.** `orchestration-shaped-skill` — describe the extraction: name which sections are the deterministic pipeline (to move into `scripts/`) and which are the judgment kernel (to keep in the thin skill); do not author the script yourself. Placement findings — explain why the current location is wrong and which location (or `~/.claude/` / `.claude/rules/`) is right; do not relocate the skill yourself. Merge / leave-alone verdicts for similar skills get prose only. Hook-integration findings — describe the trigger opportunity ("Add a PreToolUse Bash hook matching `gh pr create`…"); the author writes the hook script themselves. Repo-convention findings get a one-line "change to the documented value" — no rewrite block. + +## Notes for Implementers + +- Placement and similar-skill duplication are both **structure** concerns. They're together because they're both about how a skill sits relative to its neighbors — not because they're token-efficiency concerns. +- The repo-convention finding is a "field value violates a documented rule" concern — which is why it's a Convention finding and the lone deterministic one here. Only fire it against a convention the repo actually documents. diff --git a/skill-review/references/cost.md b/skill-review/references/cost.md new file mode 100644 index 0000000..1790f24 --- /dev/null +++ b/skill-review/references/cost.md @@ -0,0 +1,133 @@ +# Cost — Detailed Criteria + +## Scope + +Token efficiency: patterns in a skill's body that cost output tokens or context tokens per session without commensurate value. Every skill's name + description loads into every Claude Code session at startup; every body line and reference file is paid for by every session that activates the skill. Small wastes compound across a fleet of sessions. + +## When This Applies + +Severity tiers in scope: **Major**, **Minor**. + +- **Minor** — default for every cost pattern EXCEPT script-extractable orchestration. +- **Major** — two routes: (1) the per-pattern escalation predicates below (each combines broad reach + a body-size or chain-length threshold); silent escalation is forbidden, the reviewer must cite the predicate. (2) **Script-extractable orchestration is Major by default** — the only cost pattern whose smell is severe enough that the whole-skill shape, not a per-pattern threshold, sets the severity (see its section below). Its high default severity is paired with a deliberately strict firing bar. + +## Determinism + +Every finding type in this category is **judgment-bound** (`deterministic: false`). Distinguishing a sequential bash chain (no decision points between steps) from "worked examples illustrating different cases" requires judgment, and so does deciding whether existing prose qualifies as a Response Style section. + +The exception is the size half of each escalation predicate (line count, chain count, reach) — those are mechanically checkable. The size threshold is deterministic; the underlying match is judgment-bound. + +--- + +## Cost Patterns + +The remaining cost patterns are all judgment-based — paraphrased duplication and tool-cost mismatches can't be detected by regex. (Body↔references duplication moved to [`structural.md`](./structural.md) — it's about body shape, not cost mechanism. Conditional reference loading is the flat-reference pattern and also lives in `structural.md` — it's about reference-section shape.) + +### Scriptable bash chains in skill body + +**Anti-pattern.** Skill body contains 3+ fenced bash blocks that string together `gh`/`curl`/`grep`/`jq`/`awk` into a sequential chain (no decision points between steps). The LLM has to re-derive these steps every session. + +**Fix.** If the steps are deterministic (no judgment), put them in a shell script. The LLM calls the script once, parses the JSON output, and only handles parts requiring reasoning. + +**How to spot it.** Look for sequential code blocks that read like a runbook — no decisions between them, just "run A, parse output, run B with parsed value, run C". That's a script, not skill content. Note: worked examples (one block showing the expected shape of a single call) are fine; the anti-pattern is a _chain_. + +**Severity.** Minor by default. **Escalate to Major when both:** the skill is widely shared (published in a plugin/marketplace, loaded by many sessions) AND ≥3 chained bash blocks form a sequential runbook (no decision points between them). Each chained block in a high-traffic skill multiplies token cost across thousands of sessions. + +**Deterministic.** No — distinguishing a sequential chain from "worked examples illustrating different cases" requires judgment about whether the steps have decision points. + +### Script-extractable orchestration (whole-skill glue) + +**`finding_type`: `script-extractable-orchestration`.** + +**Anti-pattern.** The whole-skill generalization of the bash-chain pattern above. A skill's _dominant content_ is a fixed, deterministic pipeline — pinned queries, hardcoded IDs/values, a set sequence of tool/MCP calls, exact output templates, and mechanical format conversions (e.g. markdown→Slack) — that the LLM re-derives from prose every session instead of executing a script once. The bash-chain pattern only sees `gh`/`curl`/`jq` blocks _in the body_; this one fires when the same deterministic orchestration is spread across MCP calls and `references/` files, where the bash-chain detector structurally misses it. The tell: heavy "run _exactly_ this query", "do NOT deviate", "verified " language — deterministic spec wearing a skill costume — and a payoff that is mostly gathering + formatting + posting, with genuine reasoning a thin minority. + +**Fix (extract-glue — never "delete the skill").** Move the deterministic gathering/formatting/posting into a bundled `scripts/` file the skill invokes once; keep the SKILL.md as the thin layer that tells the script what to run and then handles only the genuine judgment — classification, synthesis, decisions the author could not pre-script. The recommendation is _always_ restructuring (thin skill over a bundled script), never removal: even a heavily-glue skill usually has a judgment kernel worth keeping as a skill. Describe the extraction in prose (no rewrite block — see Rewrite Policy); name which sections are the deterministic pipeline and which are the judgment kernel. + +**How to spot it.** Estimate the ratio of _deterministic specification_ (fixed queries, hardcoded IDs/values, set call sequences, output templates, conversion rules) to _genuine judgment_ (fuzzy classification, natural-language synthesis/summarization, decisions contingent on content the author couldn't enumerate). Count body **and** `references/` — the glue often hides in a "data sources" reference. Fire ONLY when deterministic spec is the **dominant majority** of the skill's substantive content AND the judgment content is a thin minority. This is a ratio judgment, not a presence check. + +**Severity.** **Major by default.** A skill shaped as deterministic orchestration pays its full re-derivation cost on every session — and, when run on a schedule / headless (a cron or unattended job), every single day with no human in the loop — while risking that the LLM silently varies a query that was meant to be fixed. Downgrade to **Minor** only in the narrow case of a _single_ extractable deterministic chain inside an otherwise judgment-rich skill — and prefer the `scriptable-bash-chain` finding type for that case. No Critical: this is a cost/shape smell, not a correctness defect (a pipeline that produces _wrong_ output is Integrity). + +**Deterministic.** No (`deterministic: false`) — estimating the glue:judgment ratio is judgment-bound. + +**Guardrails (Major-by-default demands a strict firing bar — do NOT let this become a noise machine).** + +- Fire on _dominance_, never on _presence_. Almost every good skill contains some deterministic glue; that is not the defect. +- Do NOT fire when the deterministic steps exist to _feed_ a genuine judgment output (classification, synthesis) that is the skill's primary product — that's a correct skill shape. +- Do NOT fire on pure-reference / pure-context skills (all project-specific facts Claude couldn't derive — dataset names, column quirks, tool IDs — and no executed sequence). Context is facts Claude needs, not a sequence Claude runs; see [`content-quality.md`](./content-quality.md) § Good Context. A skill being _all facts_ is ideal, not glue. +- Do NOT fire on small skills. The floor is <100 lines measured across the skill's _total_ substantive content — SKILL.md body **plus** `references/` — NOT the body alone (unlike the Response-Style floor, which is body-only). Glue characteristically hides in a reference file, so a 60-line body with a 200-line pinned-query reference is in scope; a genuinely small skill (body + references both tiny) is not. +- A single illustrative tool call / worked example is not orchestration. + +**Boundary with Convention.** Cost owns the _token-cost mechanism_ (the LLM re-deriving a deterministic pipeline every session). Convention owns the _shape_ lens of the same smell (a skill built as an end-to-end orchestrator rather than a context block) — `orchestration-shaped-skill` in [`convention.md`](./convention.md). They are the same defect seen from two angles and share the extract-glue fix. When a skill is mostly glue end-to-end, file **both** (one per category, as the rubric does for a skill that is both mispriced and misplaced); when only a single chain is extractable from an otherwise-sound skill, file Cost alone. + +### MCP result-size nudges (`num_results`, `limit`, depth) + +**Anti-pattern.** Skill calls an MCP tool that supports a size-limiting parameter (a search tool's `num_results`; a SQL tool's row limit; a chat-read tool's message depth), but the skill doesn't tell Claude to set one. Default result sets are often large. + +**Fix.** Add explicit guidance in the skill: "When calling X, set `num_results` to 5 unless you specifically need more." For tools whose defaults return large payloads on every call, this is the single biggest lever. + +**How to spot it.** Identify the MCP tools the skill calls. For each, check the tool's schema (do its inputs include limit/depth/result-size params?) and check the skill's prose — does it mention a sensible default for that parameter, or leave it implicit? + +**Severity.** Minor. + +**Deterministic.** No — requires judging which tool calls in the skill are high-volume enough to warrant a size nudge. + +### Field selection / projection — ask for less + +**Anti-pattern.** Skill calls an MCP that returns full entity payloads when only 3–4 fields are needed. Output tokens are dominated by JSON the LLM reads and then paraphrases. + +**Fix.** Two-sided: (1) tell Claude to request only the fields it needs in the skill prose; (2) push the MCP server itself to support field projection (companion change in the server's repo). Either side alone helps; both together compound. + +**How to spot it.** Read example tool calls in the skill. Do they ask for specific fields, or fetch defaults? If the MCP supports projection and the skill doesn't use it, flag. + +**Severity.** Minor. + +**Deterministic.** No — requires judging which fields the skill actually consumes downstream. + +### Response Style discipline (banning narration) + +**Anti-pattern.** Skill body lacks guidance against narration ("Now I'll run the query...", "Let me check...", "The results show that..."), so Claude generates these output tokens that add no information for the user. + +**Fix.** Add a `## Response Style` (or similar) section to high-traffic skills explicitly banning narration and result-paraphrasing. Even short guidance moves the needle measurably. + +**How to spot it.** This applies to _high-volume_ skills (widely shared, activated frequently — which broadly correlates with skill body size). For those skills, check whether a Response Style / Output Style section exists. For small / low-traffic skills, the cost-benefit doesn't justify the guidance — see the suppression floor below. + +**Severity.** **Suppression floor — do NOT flag at all when SKILL.md body < 100 non-frontmatter lines.** Below that, the skill emits too little output for Response Style discipline to move the needle measurably, so a finding here is noise — not even Minor. This is the calibration that keeps the pattern from over-firing on every mid-sized skill. At or above the floor: **Minor by default; escalate to Major when** the skill is widely shared (the high-traffic case where narration cost compounds across thousands of sessions). The 100-line gate is the single threshold for both the floor and the escalation — below it nothing fires, at/above it the reach decides Minor vs Major. + +**Deterministic.** No — judging whether existing prose qualifies as a Response Style section (vs. scattered tone guidance) requires reading the body. The body-line-count half of the predicate IS mechanical; the Response-Style-presence half is not. + +--- + +## Severity Escalation for Cost Patterns (rollup) + +The per-pattern severity blocks above name each escalation predicate explicitly. This rollup table is the canonical view; the per-pattern blocks are authoritative. + +| Pattern | Default | Escalate to Major when | +| ------------------------- | ----------------------- | ---------------------------------------------------------------- | +| Scriptable bash chains | Minor | widely-shared skill AND ≥3 chained bash blocks | +| MCP result-size nudges | Minor | — (case-by-case only) | +| Field projection | Minor | — (case-by-case only) | +| Response Style discipline | Minor (only ≥100 lines) | widely-shared skill AND SKILL.md body ≥100 non-frontmatter lines | + +Response Style discipline has a **suppression floor**: do not flag it at all below 100 non-frontmatter lines (not even Minor). At/above the floor it's Minor, escalating to Major for widely-shared skills. + +If escalating, cite the predicate explicitly per the escalation rule in the parent severity rubric — silent escalation is not allowed. + +--- + +## Out of Scope / False-Positive Guardrails + +- **Worked examples (one bash block) are not the bash-chain pattern.** The anti-pattern is the _chain_ of 3+ blocks forming a sequential runbook. +- **Body↔references duplication is NOT a Cost finding.** Same byte saved, but it's a body-shape concern. Lives in [`structural.md`](./structural.md). +- **Flat reference list is NOT a Cost finding.** Same reasoning — body-shape concern. Lives in [`structural.md`](./structural.md). +- **Tool steering / cheaper-tool selection** is too situational to live as a catalog pattern. Surface case-by-case in specific reviews, not as a Cost finding. +- **Cost-aware _guardrails_** (session-cost triggers, subagent fan-out warnings) are hook-level concerns, not per-skill review concerns. +- **Placement and similar-skill duplication are NOT Cost findings**, even though duplicate skills waste both context budget and engineering time. They live in [`convention.md`](./convention.md) — they're placement/structure concerns. + +## Rewrite Policy + +**Do not produce a suggested rewrite for Cost findings.** Point at the anti-pattern instance (line range or section name), name the lever (script extraction, `num_results` nudge, field projection, response-style discipline), and let the author apply the lever. The fix is structural (extract to script, add a sentence, restructure tool prose) — the author owns where and how. Format spec for the (unused-here) rewrite block lives in [`suggested-rewrites.md`](./suggested-rewrites.md). + +## Notes for Implementers + +- The escalation predicates are calibrated against fleet data — body ≥100 lines and ≥3 chained blocks are the thresholds at which the cost mechanism compounds measurably across thousands of sessions. Don't loosen them without new evidence. +- Cost is the most likely category to grow new finding types over time (new MCP servers, new model behaviors). Each new pattern should be backed by a concrete example demonstrating the cost mechanism before it lands in this rubric — the out-of-rubric channel collects candidates for periodic review. diff --git a/skill-review/references/integrity.md b/skill-review/references/integrity.md new file mode 100644 index 0000000..9722205 --- /dev/null +++ b/skill-review/references/integrity.md @@ -0,0 +1,181 @@ +# Integrity — Detailed Criteria + +## Scope + +Claims made in the skill hold against reality. Three sub-checks: + +- **Existence** — every named file, skill, agent, command, slash-command, MCP tool, script, or cross-plugin reference points to something that actually exists, **and every tool the body instructs Claude to call is declared in `allowed-tools`** so the call isn't blocked at runtime. +- **Equivalence** — files declaring "must stay identical" actually match; counts and totals claimed in prose match what's in the referenced tables; **two instructions in the skill's files don't contradict each other** (the skill doesn't say X here and not-X there). +- **Behaviour** — executable code the skill ships **or invokes** (scripts under the skill's own `scripts/`, shared scripts at the plugin root the SKILL.md references, and runnable `bash`/`python` blocks the body tells Claude to run) actually works as documented: no crash on a documented-valid input, no hardcoded-environment break, no silently-wrong output. + +The Existence and Equivalence sub-checks are **binary** — either a reference resolves or it doesn't, either two paired files match or they don't, and there is no "polish" tier for them. The Behaviour sub-check is **judgment-bound** — it requires reading the code and reasoning about what it does — and it is the one place this category carries a Critical tier (a silently-wrong result is worse than a loud missing reference). See [`security.md`](./security.md) for the *safety* of those same scripts; Integrity asks only whether they **work**. + +## When This Applies + +Severity tiers in scope: **Critical** (Behaviour sub-check only), **Major**. + +- **Critical** — a bundled script produces *silently-wrong output* on normal inputs (the `logic-bug-produces-wrong-output` finding). This is the one Integrity violation that fails *silently*: no missing-file signal, no stack trace, just a wrong answer the author trusts. Existence and Equivalence violations are never Critical — Claude surfaces a missing reference rather than silently doing the wrong thing. +- **Major** — every Existence and Equivalence finding (broken references, an instructed tool missing from `allowed-tools`, divergent rubrics, contradicted counts, contradictory instructions), plus Behaviour findings that fail *loudly* (a script that crashes on a documented input, or breaks on any machine but the author's). +- **Minor** — not in scope. A reference either resolves or it doesn't; code either works or it doesn't. There is no partial-integrity tier. + +## Blast Radius + +Integrity's existence checks resolve against **the repo / marketplace under review** — the set of skills, agents, commands, and plugins that ship from the same source the skill under review ships from. A reference is "broken" only when it names something that *should* live in that source but doesn't. References to namespaces that resolve **outside** that source — Claude Code's runtime, Anthropic's official marketplace, or any third-party plugin not present in this repo — are out of blast radius and are never flagged (the reviewer can't see them, and their absence here is expected). See the out-of-blast-radius rule below for the exact exclusions. + +## Existence Sub-Check + +### Cross-plugin reference doesn't resolve + +**Pattern.** SKILL.md or a reference file mentions `:` (e.g. `acme-tools:foo`) where `` ships from the repo under review, and the referenced item is absent from this repo. + +**Severity.** Major. + +**Deterministic.** Yes — same-repo existence check across the plugins that ship from this repo. Out-of-blast-radius prefixes are pre-excluded, so the match decision is a single boolean. + +**Fix.** Either create the referenced item, fix the reference, or remove the claim. + +### MCP tool reference doesn't resolve + +**Pattern.** The skill body or a reference file names an MCP tool that doesn't exist — a made-up name (`sf_query`), a stale name from before a server rename, or a short-form name where the skill will actually receive the fully-qualified one (`mcp__plugin____`). The skill instructs Claude to call it; the call fails at runtime because no such tool is registered. + +**Detection.** Read the skill's declared MCP servers and `allowed-tools` list, compare the named tool against the documented tool surface for each server. Check whether the name is the correct fully-qualified form. + +**Severity.** Major. + +**Deterministic.** Yes in principle — the registered tool names for a server are enumerable, so the match is a boolean once the server is known. Judgment is needed to resolve "which server backs this skill" and the short-vs-fully-qualified mapping. + +**Fix.** Use the exact registered tool name (fully-qualified `mcp__plugin____` form where the skill receives it), or correct the stale name. If the skill genuinely doesn't depend on that tool, remove the reference. + +### Internal slash-command or skill reference doesn't resolve + +**Pattern.** The skill names a `/slash-command` or a `Skill(skill: ":")` / skill invocation that has no backing skill or command in the repo under review — a dead reference (`/quality-check` with no such skill), or a bare `/create-pr` where the correct invocation is `Skill(skill: ":create-pr")` and the unqualified form won't resolve as written. + +**Severity.** Major. + +**Deterministic.** Yes — same-repo existence check, identical mechanism to the cross-plugin reference check. + +**Fix.** Point at a command/skill that exists and invoke it in the resolvable form, or remove the claim. Apply the same out-of-blast-radius exclusions below (a runtime or third-party-marketplace command is not flagged). + +### Instructed tool is missing from `allowed-tools` + +**Pattern.** The skill body (or a reference file) tells Claude to invoke a tool — `Skill(...)`, an `Agent` / `Task` subagent dispatch, `WebFetch`, `WebSearch`, `Bash` to run a bundled script, or a fully-qualified MCP tool (`mcp__plugin____`) — but that tool is **absent from the skill's declared `allowed-tools`**. When `allowed-tools` is set, Claude Code restricts the skill to exactly that surface, so the instructed call is denied at runtime: the subagent never launches, the bundled script is unreachable dead code, the web fetch is blocked. The skill claims a capability its own declared surface can't deliver — a broken claim, the same shape as a reference that doesn't resolve. + +**Detection.** Read the `allowed-tools` frontmatter, then scan the body and reference files for tool invocations the skill *instructs*: `Skill(skill: "...")`, "dispatch the Agent tool", "use `WebFetch`", `bash`/`python` blocks the body says to run (these need `Bash`), and named MCP tools. For each instructed tool, check it's present in `allowed-tools` directly or via a wildcard (`mcp__plugin____*` covers that server's tools). Flag any instructed tool not covered. + +**Severity.** Major. + +**Deterministic.** Yes — set-difference between the tools the body instructs and the `allowed-tools` list. Judgment is only needed to recognise an *instruction to call* a tool versus a passing mention; the membership check itself is mechanical. + +**Fix.** Add the missing tool to `allowed-tools` (use the wildcard or fully-qualified form for MCP tools), or stop instructing it if the skill genuinely doesn't need it. + +**Direction.** This finding fires in **one direction only — instructed-but-undeclared.** The inverse (a tool *declared* in `allowed-tools` but never invoked in the body) is **not** flagged: `allowed-tools` is a superset policy, an unused declaration makes no false claim, and flagging it adds noise with no runtime consequence. See the false-positive guardrails for the `allowed-tools`-absent case. + +### Out-of-blast-radius prefix flagged as broken + +**Pattern.** Reference uses a prefix that resolves outside the repo under review and the referenced item isn't in this repo. + +**Action.** **Do not flag.** These prefixes resolve outside this reviewer's blast radius: + +- Claude Code runtime namespaces (e.g. `plugin-dev:*`) — these ship with Claude Code itself, not from this repo. +- Anthropic's official marketplace (e.g. `superpowers:*`) — auto-installed plugins whose files live in the user's plugin cache, not in this repo. +- Any third-party / external plugin not present in the repo under review. + +Graceful-degradation phrasing ("if installed", "or the equivalent fallback") is correct usage, not a broken-reference signal. + +## Equivalence Sub-Check + +### Paired files declare "must stay identical" but diverge + +**Pattern.** Two files both declare they're supposed to match (a rubric, a list, a table) but the actual content has drifted. The classic shape: a SKILL.md and a companion agent file both declare "this rubric must stay identical" but one side has silently diverged on a predicate, a parenthetical clarification, or an edge-case sentence. + +**Severity.** Major. + +**Deterministic.** Yes — once the AI identifies the declared-paired section pair, the match check is a byte-diff. (The pair declaration itself is structural — "must stay identical" / "must match" text in the file.) + +**Fix.** Either bring the diverged file back to match, or remove the "must stay identical" declaration if drift is intentional. The cleanest structural fix is to eliminate one of the duplicated copies entirely — make one file the source of truth and have the other reference it. + +### Prose count doesn't match referenced table + +**Pattern.** SKILL.md says "the table has 7 columns" or "we cover 6 patterns" but the referenced file has a different count. + +**Severity.** Major. + +**Deterministic.** Yes — integer comparison between the claimed count and the actual table row/column count. + +**Fix.** Either update the prose or update the table — whichever was meant. + +### Two instructions contradict each other + +**Pattern.** Two instructions in the skill's files cannot both be followed — the skill says X in one place and not-X in another, applying to the *same* condition. Shapes seen in practice: + +- A stated invariant the body later violates — frontmatter / Hard Rule declares "Read-only — no mutations", then a later step instructs "enable the `bulk_delete_killswitch`". +- A body↔reference conflict on the same step — the body says "attempt the fix if it's a single file"; the reference for that bucket says "do NOT attempt to implement — just describe". +- A control-flow contradiction — "Stage 1's verdict is ignored here" one sentence after "run only if Stage 1's verdict = INVESTIGATE". +- A directional pointer that points the wrong way — "see the fallback section **above**" when that section is below. + +Whichever instruction Claude reads first wins, so behaviour is unpredictable at exactly the decision point that matters. This is the general semantic case of Equivalence; the prose-count check above is its integer special case. + +**Detection — enumerate same-condition instruction pairs across files.** This finding is under-fired because the two halves of the contradiction usually live in *different files* (body vs reference, or one reference vs another), so neither reads as wrong in isolation. Don't wait for a contradiction to jump out. Build a short list of the directives that govern each key decision point or action the skill performs (which tool to call, which order, which URL/value to use, whether to attempt vs describe, read-only vs mutate), drawing from SKILL.md *and* every reference file, then check each directive against the others that govern the *same* condition. The miss pattern is a body rule and a reference snippet that quietly disagree (e.g. "the conversations table is blocked" in one place, three `Conversation.find` snippets in another) — only visible if you put the same-condition directives side by side. + +**Severity.** Major. + +**Deterministic.** No — recognising that two instructions conflict requires reading both and reasoning about whether they can co-hold under the same condition. Unlike the prose-count check (integer comparison), there's no mechanical match. + +**Fix.** Resolve the conflict: pick the correct instruction and remove or rewrite the other, or scope each to its actual condition if they were meant for different cases. Describe the resolution in prose — do not rewrite the section. + +## Behaviour Sub-Check + +This sub-check requires **reading the actual script files** the skill ships or invokes. That includes scripts under the skill's own `scripts/` **and** shared scripts at the plugin root (e.g. `${CLAUDE_PLUGIN_ROOT}/scripts/...`) that the SKILL.md references and tells Claude to run — a skill folder with no `scripts/` dir of its own is **not** evidence that there are no scripts to review. Glob for the script paths the SKILL.md names and read them wherever they live. Never raise a Behaviour finding from SKILL.md prose alone — if the skill bundles or invokes scripts (or runnable `bash`/`python` blocks the body tells Claude to execute) and they're behaviourally relevant, read them. + +**Mandatory read step — and it cuts both ways.** Before emitting *any* Integrity status, enumerate every script the SKILL.md and reference files name or instruct Claude to run (Glob the referenced paths under the skill's `scripts/`, the plugin root, and any `bash`/`python` block the body says to execute), and **Read each one in full.** This is the most under-fired part of Integrity: the bug is real and readable, but the reviewer never opens the file and defaults to a clean pass. The read requirement is therefore *symmetric* — just as a Behaviour finding requires having read the script, an Integrity **`pass` requires having read every referenced script**. You cannot pass what you did not open. If a named script is for some reason unreadable, say so explicitly rather than passing silently; never infer a script works from its filename, its surrounding prose, or the skill merely having evals. + +### Script crashes on a documented-valid input + +**Pattern.** A bundled script raises an unhandled exception on an input the skill documents as supported — an unmapped `dict`/enum key, an unguarded `None`, an index that runs past the end, a type the code didn't anticipate. The skill claims to handle the input; the code doesn't. + +**Severity.** Major (fails loudly — the author sees the stack trace). + +**Deterministic.** No — requires understanding which inputs the skill treats as valid and whether the code handles them. + +**Fix.** Handle the documented input explicitly — map the missing key, guard the `None`, validate before indexing. Show the corrected code. The classic shape is `MAPPING[value]` where `value` comes from user/Claude input but `MAPPING` doesn't cover every documented case — a `KeyError` waiting on the first unlisted value. + +### Hardcoded environment assumption + +**Pattern.** A bundled script embeds something tied to one machine: an absolute home path (`/Users//...`, `/home//...`), a fixed directory that only exists on the author's box, or a missing `if __name__ == "__main__":` / dependency guard that prevents the script from running as the skill documents. Works for the author, breaks for everyone else and in CI. + +**Severity.** Major (fails loudly — the script errors on first use elsewhere). + +**Deterministic.** No — the `/Users/` / `/home/` literal is regex-detectable, but distinguishing a hardcoded breakage from a documented, overridable default requires judgment. + +**Fix.** Derive the path at runtime (`Path.home()`, `os.environ`, `${CLAUDE_PLUGIN_ROOT}`, an argument with a sensible default), or document the required setup explicitly. Add the missing `__main__` guard. Show the corrected snippet. + +### Logic bug produces wrong output + +**Pattern.** The code runs cleanly and returns a result, but the result is wrong on normal inputs. Over-broad regex that matches more than intended (`#?(\d+)` capturing any digit run, not just PR numbers), an off-by-one in a slice or range, the wrong field read from a payload, a comparison that inverts under an expected value. + +**Severity.** Critical — silent wrongness has no runtime signal and tends to be trusted. This is the only Critical tier in Integrity. + +**Deterministic.** No — requires reasoning about what the correct output should be for representative inputs. + +**Fix.** Tighten the logic to the intended domain (anchor the regex, fix the bound, read the right field). Show the corrected code; where the skill has evals, note the regression case that would have caught it (the missing eval is a separate Test Coverage finding — the bug itself is the Integrity finding). + +## Out of Scope / False-Positive Guardrails + +- **Out-of-blast-radius prefixes never get flagged.** This is the single most common Integrity false positive. The full prefix exclusion list is above — treat absence of any reference that resolves outside the repo under review as valid by default. +- **Graceful-degradation phrasing is correct usage.** "If `:foo` is installed…" or "fall back to manual review if the script isn't available" — these are NOT broken-reference signals, they're correct depend-but-degrade patterns. +- **No `allowed-tools` block → no instructed-tool finding.** When the frontmatter omits `allowed-tools` entirely, the skill inherits the session's full toolset, so nothing is blocked — never raise the instructed-tool finding against a skill that declares no `allowed-tools`. The finding applies only when `allowed-tools` is present *and* an instructed tool falls outside it. Likewise, do not flag the inverse (declared-but-uninvoked tool) — that's the superset-policy case, not a broken claim. +- **Conditional branches are not contradictory instructions.** "If the issue is single-file, attempt the fix; otherwise just describe it" is correct branching, not a contradiction — the two directives apply to *different* conditions. Only raise the contradictory-instructions finding when both directives govern the *same* condition and cannot both hold. Graceful-degradation/fallback phrasing and a "don't do this" anti-pattern shown beside the real instruction are likewise not contradictions. +- **Behaviour findings require reading the script — never speculate.** No crash / hardcoded-path / wrong-output finding may be raised from SKILL.md prose alone. If the relevant script isn't read, there's no Behaviour finding. +- **Anti-pattern examples are not Behaviour findings.** A skill (like this one) that *shows* a buggy snippet as a "don't do this" example is teaching, not shipping a bug. Use surrounding context — is the code framed as the skill's tool, or as a cautionary example? Likewise, illustrative/pseudo-code blocks that aren't wired to run are not Behaviour findings. +- **Safety defects are Security, not Integrity.** Command injection, unquoted expansion enabling exploits, credential leaks, and path traversal live in [`security.md`](./security.md). Integrity's Behaviour sub-check is only for code that *doesn't work* (crash / non-portable / wrong output). A defect that is both → file the more severe. + +## Rewrite Policy + +**Produce a suggested rewrite for every Behaviour finding (crash, hardcoded environment, wrong output).** These are about executable code, so the fix is concrete code — show the corrected branch, the runtime-derived path, or the anchored regex inline in the finding's details block, per [`suggested-rewrites.md`](./suggested-rewrites.md). Keep it minimal — patch the defect, don't refactor the surrounding script. + +For all other Integrity findings (broken cross-plugin / MCP-tool / command reference, instructed-tool-not-in-`allowed-tools`, paired-file divergence, prose-count mismatch, contradictory instructions), describe the fix in prose. Two paths exist for paired-file divergence — bringing the diverged side back to match, or eliminating the duplicated copy entirely so one file becomes the source of truth — pick the cheaper one and explain why. Do not write the diff or the merged file. + +## Notes for Implementers + +- Most Existence and Equivalence findings are deterministically detectable for the repo under review and same-repo paired files: cross-plugin refs, MCP-tool / command resolution, the instructed-tool-vs-`allowed-tools` set-difference, prose-vs-table counts, and paired-file diffs are all boolean checks once the relevant files are read (`deterministic: true`). The **one Equivalence exception is `contradictory-instructions`** — deciding two directives conflict requires semantic judgment, so it is `deterministic: false`. The **Behaviour** sub-check is also judgment-bound — crash / portability / wrong-output detection requires reading the code and reasoning about it, so `deterministic: false` for all three Behaviour finding types. The determinism eval must filter the judgment-bound findings (`contradictory-instructions` + the three Behaviour types) out of its tuple-equality assertion (same treatment as Content Quality), while keeping the boolean Existence/Equivalence findings in scope. +- The reason Integrity has no Minor tier: a reference either resolves or it doesn't, and code either works or it doesn't — there's no "mostly resolves" or "kind of works". The Critical tier is the deliberate exception, scoped to exactly one finding (`logic-bug-produces-wrong-output`): silent wrong output is worse than a loud missing reference. Keep both properties when adding finding types — no Minor, and Critical only for silent-wrongness. diff --git a/skill-review/references/security.md b/skill-review/references/security.md new file mode 100644 index 0000000..2adf5a7 --- /dev/null +++ b/skill-review/references/security.md @@ -0,0 +1,125 @@ +# Security — Detailed Criteria + +## Scope + +No credential exposure in skill instructions. No instructions to paste secrets into the conversation. No instructions that route secrets through the model or to disk in plaintext. No unsafe shell idioms in executable scripts. + +Security findings always escalate to **Critical** or **Major** — there is no "polish" tier. Credential-paste isn't style; shell injection isn't a nit. + +## When This Applies + +Severity tiers in scope: **Critical**, **Major**. + +- **Critical** — credential exposure in instructions, plaintext credential storage, an auth flow that surfaces secrets to the model as text. +- **Major** — security bug in an executable script under `scripts/` (command injection, unquoted expansion, credential leak, path traversal, disabled transport security). +- **Minor** — not in scope. Security findings are not polish. + +## Credential Exposure Patterns (Critical) + +### Asking the user to paste secrets into the conversation + +**Pattern.** Skill body or reference file instructs the user to paste an `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, an API key, a session token, a password, or any other credential as chat input. + +**Severity.** Critical. + +**Deterministic.** No — credential strings appear in this skill's own body as anti-pattern examples. The match decision requires context heuristics ("is this in an instruction or a warning?"), which an AI rerun can resolve differently on borderline cases. + +**Why it's bad.** Credentials in the conversation transcript are stored, indexed, and potentially shared. They also typically circumvent a secure auth flow the user could have used instead. + +**Fix.** Use a non-interactive auth flow that never surfaces credentials as text — one that injects them directly into the command's environment (a subshell, an env var sourced from a secret manager, or an MCP server that handles auth itself), so the secret never appears in the conversation. + +### Writing credentials to plaintext temp files + +**Pattern.** Skill instructs the user (or Claude) to write credentials to a file under `/tmp/` (or any unprotected path) and source it. Detectable by the combination of `/tmp/*.sh` and `export AWS_*=` / `export =` patterns. + +**Severity.** Critical. + +**Deterministic.** No — same context-heuristic concern. The `/tmp/*.sh` + `export` co-occurrence is regex-friendly, but anti-pattern examples in skill bodies cause false positives. + +**Why it's bad.** Plaintext files in `/tmp/` may be world-readable, may survive reboots on some configurations, and aren't cleaned up reliably. + +**Fix.** Use an auth flow that injects credentials directly into the process environment without ever serialising them to disk. + +### Auth flow that surfaces secrets to the model + +**Pattern.** The skill instructs an interactive or human-only auth flow and then captures its output so the model can read the resulting credentials — e.g. "run `` in a separate terminal, then echo the resulting tokens and paste them back", or piping a credential-printing command into the conversation. The skill claims the model "can't access" the secure flow and routes around it by exposing the secret instead. + +This also fires on the narrower trigger **even without an explicit echo-and-paste step**: the skill invokes an *interactive or human-only* auth command — one designed for a person at a terminal (browser-based confirmation, an interactive prompt), not for an automated agent — from inside its own automated flow. Such a command either hangs waiting for interactive input or emits credentials into the session output the model then reads. Naming the wrong (human) auth mode is the defect; the skill does not have to spell out the paste step for the exposure to occur. + +**Severity.** Critical. + +**Deterministic.** No — recognising that a described flow ends with the model reading a secret requires semantic understanding, not a single regex. + +**Fix.** Use the tool's non-interactive / machine auth mode (the one designed for automated agents) that injects credentials into the environment directly, and drop any "echo the token and paste it" step. If no such mode exists, the skill should hand the privileged action to the user rather than capturing their secret. + +## Correct Patterns to Recognise as Safe + +These are NOT findings — recognise them as the right pattern: + +- A non-interactive auth invocation that injects credentials into the command's subshell/environment and never prints them — e.g. `eval "$(some-auth --machine )" && `. +- MCP tool calls where authentication is handled by the MCP server, not the skill (the server holds the token; the skill never sees it). +- Reconnecting an expired MCP session via the documented reconnect flow rather than capturing a token by hand. + +## Security Bugs in Executable Scripts (Major) + +All sub-patterns below are **not deterministic** — flagging command injection, unquoted expansion, credential leaks, path traversal, or disabled transport security requires reading the script and understanding its data-flow semantics. + +### Command injection in shell scripts + +**Pattern.** Script under `scripts/` interpolates user-controlled input into a shell command without quoting. Detectable by reading the script files in the skill folder. + +**Severity.** Major. + +**Fix.** Quote variable expansions: `"$var"` not `$var`. Use `printf '%s' "$var"` for stricter cases. Prefer arrays for argument lists. + +### Unquoted variable expansion + +**Pattern.** Shell script has `cmd $var` where `$var` could contain spaces or special characters. Same root cause as command injection but lower exploit surface. + +**Severity.** Major. + +**Fix.** Quote: `cmd "$var"`. + +### Credential leak in script output + +**Pattern.** Shell script prints `$AWS_SECRET_ACCESS_KEY` or a similar secret to stdout/stderr, or writes it to a log file. + +**Severity.** Major. + +**Fix.** Never print credentials. Mask if you must reference them: `echo "Using key ${AWS_ACCESS_KEY_ID:0:4}…"`. + +### Path traversal + +**Pattern.** Script accepts a path argument and uses it without validating it stays within the expected directory. `rm -rf "$user_path"` is the worst case. + +**Severity.** Major. + +**Fix.** Validate the path with `realpath` and check it has the expected prefix before any destructive operation. + +### Transport security disabled + +**Pattern.** A bundled script turns off TLS / certificate verification on a network call: `verify=False` (Python `requests`), `ssl_verify_peer: false`, `curl -k` / `curl --insecure`, `rejectUnauthorized: false` (Node), `InsecureSkipVerify: true` (Go), or an equivalent flag that suppresses cert checking against a remote host. The connection is then open to a man-in-the-middle: any party on the path can impersonate the endpoint and read or tamper with the traffic, including credentials and production data in the request/response. + +**Severity.** Major. + +**Deterministic.** No — the literal flag is regex-detectable, but distinguishing a real production MITM exposure from a deliberate localhost / self-signed-dev-cert context, or from an anti-pattern example, requires reading the surrounding code and its target host. + +**Fix.** Leave verification on (`verify=True` / drop the `-k` / drop `rejectUnauthorized: false`). If the target is an internal host with a private CA, trust that CA explicitly (`verify="/path/to/ca-bundle.pem"`, `--cacert`, `NODE_EXTRA_CA_CERTS`) rather than disabling verification globally. Show the corrected call. + +## Out of Scope / False-Positive Guardrails + +- **Anti-pattern examples in skill bodies are not credential exposure.** A skill that contains the strings `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` as **descriptions of what NOT to do** is teaching, not instructing. Detection must use context: is the string in an instruction telling the user to do something, or in a "do not" warning? If the surrounding text frames it as wrong, it's not a finding. +- **Plain mention of "paste" is not a finding.** Skills often say "paste the URL" or "paste the build ID" — only flag when "paste" is associated with credential strings. +- **`scripts/` security review requires reading the actual scripts.** Don't speculate about script content from SKILL.md alone. If the skill folder has executable scripts and they're security-relevant, read them. +- **A documented localhost / dev-only TLS-disable is not the transport-security finding.** A `verify=False` scoped to `https://localhost` or a self-signed dev cert, clearly framed as dev-only, is not a production MITM exposure — and an anti-pattern example (this file names the disabling flags as things NOT to do) is teaching, not a finding. Flag transport-security-disabled only when a real remote/production call has verification suppressed. + +## Rewrite Policy + +**Produce a suggested rewrite for executable-script bugs (the Major-tier finding type).** Show the fixed code inline — quoted expansions, masked credential output, `realpath` validation, re-enabled TLS verification (or an explicit private-CA bundle), etc. The rewrite lives inside the finding it addresses (collapsible details block per [`suggested-rewrites.md`](./suggested-rewrites.md)). + +**For credential-exposure Critical findings, describe the fix in prose.** Name the secure replacement explicitly — a non-interactive auth flow that injects credentials into the command environment (so they live only in the process/subshell, never in the conversation transcript or on disk) — and explain why. Do not generate a full rewrite of the surrounding skill section; the author needs to choose where the auth invocation belongs. + +## Notes for Implementers + +- For the credential-paste patterns, detection is FP-prone: anti-pattern examples in skill bodies (showing what NOT to do) fire false positives. Use context to distinguish instructions from warnings before flagging. +- The safe pattern is always the same shape regardless of tool: credentials enter the process environment through a machine/non-interactive flow and are never serialised to the conversation or to disk. Recognise that shape and pass it. diff --git a/skill-review/references/structural.md b/skill-review/references/structural.md new file mode 100644 index 0000000..eae10ef --- /dev/null +++ b/skill-review/references/structural.md @@ -0,0 +1,56 @@ +# Structural Discipline — Detailed Criteria + +## Scope + +Body shape and progressive-disclosure hygiene: section organisation, conditional reference loading, and body↔references duplication. Detection is judgment-bound — paraphrased duplication and missing scope hints can't be matched mechanically. + +## When This Applies + +Severity tiers in scope: **Major**, **Minor**. + +- **Major** — large body↔references duplication in a widely-shared skill (the escalation predicate below). +- **Minor** — duplication and polish (body↔references duplication, flat reference list missing scope hints). + +## Finding Types + +### Body↔references duplication (the duplication pattern) + +**Pattern.** Same rule, code block, or instruction text present in both `SKILL.md` body and a file under `references/`. Claude reads both and pays input tokens twice. Includes paraphrased duplication (same content reworded), not just verbatim copies. + +**Detection.** Read the body and the reference files and compare — paraphrased duplication requires judgment, so this is not a mechanical match. + +**Severity.** Minor by default. **Escalate to Major when both:** +- ≥50 duplicated lines between body and references (mechanically: byte-overlap or paraphrase span flagged by AI), AND +- the skill is widely shared (published in a plugin or marketplace, loaded by many sessions) rather than personal or project-local — the tier where per-session waste compounds across thousands of sessions. + +**Deterministic.** No — paraphrased duplication detection requires judgment; intentional partial summarisation looks the same as accidental duplication at the surface level. + +**Fix.** Move every rule to exactly one place: body for orchestration flow, references for detailed lookup tables. Cross-reference; don't duplicate. + +**How to spot it.** Read the body. For each paragraph, ask: does this same content (or a paraphrased version) exist in a referenced file? If yes, decide which side keeps it (usually references) and replace the body content with a one-line pointer. + +### Flat reference list without per-entry scope hints (the flat-reference pattern) + +**Pattern.** SKILL.md ends with a flat bullet list of every reference file — Claude proactively reads them all because the list invites it to. The "## Reference Files" or "## References" section has 5+ entries and lacks both per-entry scope hints ("**Load when investigating DB latency**") and a guard phrase ("Do NOT pre-load all references"). + +**Severity.** Minor. + +**Deterministic.** No — "missing scope hint" requires judgment about whether the existing prose adequately scopes the entry. + +**Fix.** Each reference entry needs an explicit load trigger ("load when investigating DB latency", "consult for cross-shard analysis"). Open the section with a guard phrase like "Do NOT pre-load all references. Read only those relevant to the task at hand." + +**How to spot it.** Find the reference list (usually near the bottom). If 5+ files are listed without per-entry scope hints, that's the anti-pattern. The reference implementation gives each entry a bolded scope phrase plus an arrow-pointer to when it should be loaded. + +## Out of Scope / False-Positive Guardrails + +- **Worked examples are not duplication.** A single bash block in the body showing the expected shape of one call, with the detailed walkthrough in `references/examples.md`, is the correct pattern. The anti-pattern is the entire walkthrough being in both places. +- **Tables intentionally summarising a fuller reference are not duplication.** A 5-row inline table in the body that points to a 30-row reference table is summarisation, not duplication. Flag only when the inline content is comprehensive enough to replace reading the reference. + +## Rewrite Policy + +**Do not produce a suggested rewrite for Structural findings.** The fixes are mechanical or structural (split body into `references/`, deduplicate a section, add per-entry scope hints). Describe the fix in prose — e.g. "Move the 'Common Queries' section from SKILL.md into `references/common-queries.md` and replace the body with a one-line pointer." The author owns the structural change. Format spec for the (unused-here) rewrite block lives in [`suggested-rewrites.md`](./suggested-rewrites.md). + +## Notes for Implementers + +- Body↔references duplication is judgment-bound: intentional partial summarisation looks the same as accidental duplication at the surface level. Weigh whether the inline content is comprehensive enough to replace reading the reference before flagging. +- Progressive disclosure is the goal, not brevity for its own sake. A long body backed by a well-organised `references/` directory, with the body kept to routing, is healthy structure — flag duplication and flat reference lists, not size alone. diff --git a/skill-review/references/suggested-rewrites.md b/skill-review/references/suggested-rewrites.md new file mode 100644 index 0000000..b60abfd --- /dev/null +++ b/skill-review/references/suggested-rewrites.md @@ -0,0 +1,47 @@ +# Suggested Rewrites — Format Spec + +This file is the **cross-cutting format spec** for the rewrite block — placement, structure, authoring constraints. It does NOT decide *whether* a given finding gets a rewrite. + +**The decision to rewrite (or not) for a finding lives in that finding's category reference**, under the "Rewrite Policy" subsection — see [`structural.md`](./structural.md), [`integrity.md`](./integrity.md), [`test-coverage.md`](./test-coverage.md), [`security.md`](./security.md), [`content-quality.md`](./content-quality.md), [`convention.md`](./convention.md), or [`cost.md`](./cost.md) for the policy that applies to its findings. + +Quick reference — which categories produce rewrites: + +| Category | Rewrites produced? | +|----------|--------------------| +| Structural Discipline | No (describe structural change in prose) | +| Integrity | **Yes** for Behaviour findings (concrete code fix); prose for others | +| Test Coverage | No (describe the eval scenario in prose) | +| Security | **Yes** for executable-script bugs; prose for credential-paste and auth-flow findings | +| Content Quality | **Yes** for procedure smell / vague context, `weak-completion-criterion`, and `temporal-self-reference`; prose for `no-op-instruction` (unless the fix is a strong-leading-word replacement) | +| Convention | **Yes** for similar-skill "differentiate" verdict, `description-as-routing-signal`, and `invocation-mode-mismatch`; prose for placement / hook integration / repo-convention | +| Cost | No (point at the anti-pattern and name the lever; author applies the fix) | + +The rest of this file is the format spec the rewrite block follows when a category does call for one. + +## Format + +Place the rewrite inside the finding it addresses, in a collapsible details block so reviewers can scan findings without scrolling through replacement text: + +```markdown +**Major:** Section "## Querying Data" is procedural — 6 numbered steps teaching +generic telemetry-tool usage Claude already knows. The project-specific facts (dataset +name, environment filter, column availability) are valuable but buried in choreography. + +
+Suggested rewrite + +[Complete replacement section here — ready to copy into SKILL.md] + +
+``` + +## Authoring Constraints + +When writing a rewrite under rules 1–3: + +1. **Preserve all project-specific facts** from the original — don't lose real context when removing procedure. +2. **Make it copy-pasteable** — the author should be able to drop it in as a direct replacement. +3. **Be shorter than the original** — removing choreography naturally reduces length. +4. **Use declarative structure** — tables, constraint lists, "when X, Y applies" patterns beat numbered steps. +5. **Don't invent new content** — only restructure what's already in the skill or its references. +6. **For reference files**: include any expected frontmatter or headers; produce the full file, not a fragment. diff --git a/skill-review/references/test-coverage.md b/skill-review/references/test-coverage.md new file mode 100644 index 0000000..7957eaa --- /dev/null +++ b/skill-review/references/test-coverage.md @@ -0,0 +1,126 @@ +# Test Coverage — Detailed Criteria + +## Scope + +Required evals exist for skills with broad reach. Behavioral and structural coverage match the skill's claimed scope. Operational guardrails declared anywhere in the skill (SKILL.md or any reference file) are exercised by at least one eval. + +## When This Applies + +Severity tiers in scope: **Major**, **Minor**. + +- **Major** — required evals missing entirely on a widely-shared skill, OR an operational guardrail declared anywhere in the skill (SKILL.md or any reference file) is not exercised by any eval, OR an eval asserts behaviour the skill no longer implements (a stale eval that now validates *incorrect* output — false confidence), OR an eval that runs green without actually exercising the behaviour it claims to test (a false-coverage eval). The stale-eval and false-coverage cases are Major regardless of reach, because the harm (a green check on wrong or untested behaviour) doesn't depend on adoption. The operational-guardrail-untested case is likewise Major regardless of reach when the guardrail governs an **irreversible or destructive action** (purge, delete, kill-switch enable, force-merge, any mutation) — the personal/project-local carve-out below does not shield those. +- **Minor** — missing evals on a personal or project-local skill (the floor for low-reach skills), OR eval-quality gaps (eval IDs out of sequence, missing structural mirror for a behavioral guardrail, wishlist coverage). + +## When Evals Are Required + +Eval requirements scale with **reach** — how many people and sessions depend on the skill. The reviewer must apply this table verbatim — flagging missing evals as Major on a low-reach skill is a false positive. + +| Reach | Evals | Reason | +|--------|-------|--------| +| Widely shared — published in a plugin or marketplace, depended on by many engineers | **Required** (Major if missing) | Broad adoption, low tolerance for noise | +| Team-scoped — shared within one team | **Highly recommended** (Minor if missing) | Reduces regression risk; daily use provides some feedback but doesn't catch quality drift | +| Experimental / still proving value | Highly recommended | Evals are the cheapest signal that a skill works | +| Personal / project-local | Optional | Owned by one person or one repo; issues surface through use | + +**Why "highly recommended" is the floor for lower-reach skills.** Evals are the only mechanism that catches behavioral regressions when a skill is modified. A shared skill without evals is one careless prompt edit away from breaking silently. Flag the absence as **Minor** to surface it without escalating beyond the rubric — the owner makes the call, but the absence should be visible in every review. + +## Finding Types + +### New widely-shared skill lacks evals + +**Pattern.** A newly-added SKILL.md that is widely shared (published in a plugin/marketplace) has no evals in either supported location (skill-local `evals/` or a repo-root test suite). + +**Detection.** Read the diff status provided for the review. When a SKILL.md entry has status `A` (added) or `R` (renamed into scope), glob both eval locations: the skill-local `evals/` directory and the repo-root test suite for that skill (e.g. `evals//`, mapping kebab→snake: `name.replace('-', '_')`). If neither exists, flag this finding. Modifications to existing skills (`M`) are grandfathered under the separate finding below. + +**Severity.** Major. + +**Deterministic.** Yes — directory existence + diff-status classification (`A` / `R` vs `M`). + +**Fix.** Add either: +- a skill-local `evals/evals.json` with at least 3 cases (golden + edge + negative), or +- a structural test suite (e.g. a pytest suite) with assertions on tool-call shape. + +### Existing widely-shared skill lacks evals + +**Pattern.** A widely-shared skill predates the evals-required expectation and has no evals in either location. Should still be surfaced even though it was not caught when it was added. + +**Severity.** Major. + +**Deterministic.** Yes — directory-existence check (both eval locations absent). + +**Fix.** Same as the net-new case — add evals. Use the skill's documented behaviors to derive eval scenarios. + +### Operational guardrail untested + +**Pattern.** The skill declares — in SKILL.md *or any reference file* — a "never X" / "always Y" rule that governs the skill's *output correctness on real inputs* (e.g. "do not flag runtime-namespace agents as broken references", "reject code-only analysis when logs are available") AND no eval anywhere exercises it. The predicate is not scoped to the SKILL.md body: a guardrail declared only in a reference file is fully in scope, which is exactly why the Detection step below enumerates across every file. + +**Detection — enumerate, then cross-check; do not sample.** This is the single most under-fired finding in the rubric, and the cause is always the same: the reviewer spot-checks a couple of obvious rules instead of enumerating all of them. Work in two explicit steps: + +1. **Enumerate every guardrail.** Scan SKILL.md *and every reference file* for each "never X" / "always Y" / "must Y" / "do not X" rule that governs output correctness on real inputs. Build the full list — a guardrail you never enumerated is a guardrail you cannot check. Guardrails hide in reference files and bundled-script comments, not just the SKILL.md body. +2. **Cross-check each against the evals.** For *each* enumerated guardrail, look for an eval (in `evals/evals.json` or the repo-root test suite) whose case would **fail if that specific rule were violated**. An eval that merely operates in the same area does not count — the assertion has to be sensitive to the rule. Flag every guardrail with no such eval. + +Passing Test Coverage is a claim that you enumerated the guardrails and found each one covered — not that nothing looked wrong. A skill with N guardrails and an eval suite that happens to be green is the *typical* shape of this miss, not evidence against it. + +**Severity.** Major. + +**Deterministic.** No — distinguishing "operational guardrail governing correctness" from "style rule" requires judgment about the skill's intent. The boundary below names the test but doesn't make it mechanical. + +**Fix.** Add a behavioral eval in `evals.json` that gives Claude a prompt where violating the rule would produce a wrong answer, and assert Claude follows the rule. + +**Boundary.** Rules governing output format, tone, writing style, or rewrite mechanics ("be concise", "describe the hook, don't write it", "keep rewrites copy-pasteable", "don't invent new content") are NOT the operational-guardrail-untested predicate — they're Minor. Ask: would a reviewer following this rule produce a different *correctness verdict* than one who ignored it? If no, it's style, not an operational guardrail. + +**Reach.** This finding is **not** the whole-skill missing-evals finding and is **not** shielded by the low-reach carve-out below. It is especially Major-regardless-of-reach when the untested guardrail governs an **irreversible or destructive action** — a queue purge, a delete, a kill-switch enable, a force-merge, any mutation, a "refuse the dangerous request" gate. A low-reach skill that ships a destructive guardrail with no eval gets the Major regardless: the cost of a silent regression there is a real production action, not a noisy review. (Ordinary, non-destructive guardrails on low-reach skills still warrant the finding, but the destructive case is the one the carve-out must never swallow.) + +### Eval asserts stale behaviour (Major) + +**Pattern.** An eval's expectations describe behaviour the skill no longer implements — the skill was changed (a flow rewritten, an output format swapped, a tool migrated) but its evals weren't updated. The eval now codifies the *old* behaviour, so it passes when Claude does the wrong thing and fails when Claude does the right thing. Example: a skill switched from a remote-doc export to a local-HTML export, but an eval still asserted the remote-doc flow. + +**Detection.** Read each eval's expectation against the skill's current documented behaviour and check whether they agree. This requires judgment — the reviewer reads the eval file and the current SKILL.md body and recognises when they disagree. + +**Severity.** Major — regardless of reach. This is NOT an eval-quality nit; a stale eval is worse than a missing one, because a missing eval is honestly silent while a stale eval gives a false green check on incorrect output. Do not file it under the Minor eval-quality bucket below. + +**Deterministic.** No — judging "the eval expects behaviour the skill no longer does" requires understanding both the eval and the current skill body. + +**Fix.** Update the eval's expectation to match the skill's current behaviour, and confirm the assertion would now fail on the *old* behaviour (otherwise it isn't testing the change). Describe the corrected expectation in prose; do not regenerate the eval JSON wholesale. + +**When it fires.** Stale evals arise from *modifying* a skill without updating its evals, so this finding is most relevant when the skill is being changed in the current PR (diff status `M`). The single-pass review always reads the eval files against the current SKILL.md, so the finding is reachable whenever the skill ships evals — there is no triage gate that could pass a modified-with-evals skill before its evals are read. + +### Eval proves nothing (false-coverage eval) (Major) + +**Pattern.** An eval is present and passes, but it doesn't actually exercise the behaviour it claims to test — so its green check is false confidence, the same harm as a stale eval. Two shapes seen in practice: + +- **Answer scaffolded into the prompt.** The eval's prompt preamble already states the rule or hands Claude the resolved answer, so the case tests whether Claude can *read the prompt*, not whether the *skill* teaches the behaviour. Example: a "detect the self-contradiction" eval whose prompt pre-states which instruction is correct; or a guardrail eval that scaffolds "(remember: never create labels)" into the prompt that the skill body is supposed to supply. +- **Tests the wrong component.** The eval asserts behaviour of a *different* unit than the skill under test — e.g. an orchestrator skill's eval that asserts what the dispatched *worker* does internally, rewarding a hallucinated worker contract and passing even when the orchestrator itself is wrong. + +**Detection.** Read each eval's prompt and expectation against the skill body. Ask: if the skill body were blanked out, would this eval still pass on prompt-content alone? If yes, the prompt is carrying the answer. And: does the assertion target the skill being reviewed, or some other unit it merely dispatches? + +**Severity.** Major — regardless of reach. A false-coverage eval is worse than a missing one for the same reason a stale eval is: it shows green while proving nothing, so a real regression slips through silently. Do not file it under the Minor eval-quality bucket below. + +**Deterministic.** No — judging "the prompt already contains the answer" or "this asserts the wrong unit" requires reading the eval and the skill body together and reasoning about what the case actually exercises. + +**Fix.** Move the behaviour-defining content out of the prompt and into reliance on the skill (the prompt should pose the situation, not pre-resolve it), and re-target the assertion at the skill under review. Confirm the case would now *fail* if the skill's rule were removed — that's the test that it tests anything. Describe the corrected case in prose; do not regenerate the eval JSON wholesale. + +### Eval quality issues (Minor) + +- Behavioral eval IDs non-sequential — **deterministic** (numeric sequence comparison) +- Missing structural mirror for a behavioral guardrail — **not deterministic** (judgment about which behavioral evals merit a structural regression test) +- `trigger-evals.json` missing negative cases for adjacent queries that shouldn't trigger this skill — **not deterministic** (judgment about which adjacent queries warrant a negative case) + +## How to Write Good Evals (out of rubric scope) + +Tutorial content on eval file types, eval archetypes, what makes an eval good vs bad, and the hook trick for eval-trigger reliability lives in your project's eval-authoring guide and the skill-creation workflow. This rubric reference does NOT teach how to write evals — it only enumerates the finding types a reviewer flags. If the reviewer is asked "how should I write this eval?", redirect to that guide. + +## Out of Scope / False-Positive Guardrails + +- **Eval requirements vary by reach — but this carve-out is about *whole-skill* missing evals only.** Don't flag a personal / project-local / experimental skill for having *no eval suite* — only widely-shared skills are gate-enforced for that. The carve-out does **not** extend to: an untested **destructive/irreversible** operational guardrail (Major regardless of reach), a **stale** eval, or a **false-coverage** eval (both Major regardless of reach). Those harms don't depend on adoption, so reach doesn't excuse them. +- **The operational-guardrail-untested predicate has a tight boundary.** Style rules ("be concise", "don't paraphrase") are not operational guardrails. Only flag it when violating the rule would change a *correctness verdict*, not the format of the output. +- **One eval location is enough.** A skill that has `evals/evals.json` but no repo-root test suite (or vice versa) is fine. Both is ideal but not required. + +## Rewrite Policy + +**Do not produce a suggested rewrite for Test Coverage findings.** Eval scenarios depend on the skill's actual operational guardrails — the reviewer can't generate eval JSON without knowing the skill's failure modes deeply. Describe the eval the author should add in prose: "Add a behavioral case where Claude is asked X; assert the response Y, because the skill's rule Z would otherwise be violated." That's enough for the author to write the case themselves. Format spec for the (unused-here) rewrite block lives in [`suggested-rewrites.md`](./suggested-rewrites.md). + +## Notes for Implementers + +- Diff-status classification for the net-new finding: `A` means the file was added, `R` means it was renamed into scope (e.g. renamed from another plugin). `M` (modified) means the skill already existed — route to the grandfathered finding instead, not the net-new one. This distinction matters: flagging a modified skill as "new skill lacking evals" is a false positive. +- The kebab→snake mapping for repo-root eval directories is `name.replace('-', '_')` — `acme-tools` → `evals/acme_tools/`.