# SkillPatch skill: skill-writer

A comprehensive meta-skill for creating, synthesizing, and iteratively improving agent skills following the Agent Skills specification. It provides a structured canonical workflow covering source discovery, synthesis, authoring, registration, and validation. The skill uses a reference-backed layout with a routing table to guide agents through the correct workflow path depending on the task.

You (the agent) were given this URL and asked to use this skill. This is a **public** skill — no SkillPatch account, API key, or prior setup is required. Two ways to use it:

**1. Use it right now** — the skill's complete file tree (SKILL.md + all reference files) is inlined below; read `SKILL.md` first, then follow it, consulting the other files as it directs.

**2. Install the exact package onto disk** (recommended if you can run a shell — this reproduces the skill byte-for-byte, including any binary assets that can't be inlined):

```bash
mkdir -p .claude/skills/skill-writer
curl -sSL https://skillpatch.dev/install_skill/skill-writer | tar -xz -C .claude/skills/
```

(`.claude/skills/` is Claude Code's convention; use whatever directory your agent loads skills from.)


---

## Skill files (40)

- `SKILL.md`
- `references/authoring-path.md`
- `references/claude-argument-substitutions.md`
- `references/claude-dynamic-context.md`
- `references/claude-frontmatter-invocation.md`
- `references/claude-hook-backed.md`
- `references/claude-subagent-fork.md`
- `references/description-optimization.md`
- `references/design-principles.md`
- `references/example-documentation-skill.md`
- `references/example-hook-backed-skill.md`
- `references/example-router-skill.md`
- `references/example-subagent-fork-skill.md`
- `references/example-workflow-process-skill.md`
- `references/execution-shapes.md`
- `references/iteration-evidence.md`
- `references/iteration-path.md`
- `references/layout-argument-driven-skill.md`
- `references/layout-asset-template-skill.md`
- `references/layout-inline-skill.md`
- `references/layout-reference-backed-skill.md`
- `references/layout-script-backed-workflow.md`
- `references/mode-selection.md`
- `references/output-contracts.md`
- `references/reference-architecture.md`
- `references/registration-validation.md`
- `references/source-adaptation.md`
- `references/source-discovery.md`
- `references/spec-template.md`
- `references/structure-troubleshooting.md`
- `references/synthesis-path.md`
- `references/workflow-orchestrator-workers.md`
- `references/workflow-parallel.md`
- `references/workflow-plan-validate-execute.md`
- `references/workflow-prompt-chaining.md`
- `references/workflow-routing.md`
- `references/workflow-validation-loops.md`
- `scripts/quick_validate.py`
- `SOURCES.md`
- `SPEC.md`


### `SKILL.md`

```markdown
---
name: skill-writer
description: Create, synthesize, and iteratively improve agent skills following the Agent Skills specification. Use when asked to "create a skill", "write a skill", "synthesize sources into a skill", "improve a skill from positive/negative examples", "update a skill", or "maintain skill docs and registration". Handles source capture, precision passes, authoring, registration, and validation.
---

# Skill Writer

Use this as the single canonical workflow for skill creation and improvement.
Primary success condition: maximize high-value input coverage before authoring while minimizing wasted runtime tokens.

Follow the workflow steps in order. Load only the reference files required for the step you are on.
`SKILL.md` is the primary router: every bundled reference file should be flat under `references/` and listed here with a direct "open when..." reason.

## Core Workflow References

| Open when you need to... | Read |
|--------------------------|------|
| choose the minimum workflow path for create, update, iterate, or research-first work | `references/mode-selection.md` |
| choose the simplest adequate execution shape before deciding files | `references/execution-shapes.md` |
| apply writing constraints for depth, concision, and portability | `references/design-principles.md` |
| decide what belongs in `SKILL.md`, `references/`, `SPEC.md`, or supporting files | `references/reference-architecture.md` |
| create or update the maintenance contract for a skill | `references/spec-template.md` |
| find missing high-signal sources, including history and regressions | `references/source-discovery.md` |
| adapt an upstream prompt, workflow, rubric, benchmark, or docs into a skill | `references/source-adaptation.md` |
| run the full synthesis pass with coverage checks and source capture | `references/synthesis-path.md` |
| author or update `SKILL.md`, `SPEC.md`, and supporting files | `references/authoring-path.md` |
| improve trigger language and false-positive/false-negative behavior | `references/description-optimization.md` |
| iterate from positive, negative, or fix examples | `references/iteration-path.md` |
| store persistent working and holdout examples for future revisions | `references/iteration-evidence.md` |
| choose a response template, schema, or output contract | `references/output-contracts.md` |
| troubleshoot overloaded layouts, hidden refs, or other structure failures | `references/structure-troubleshooting.md` |
| register the skill and run final validation checks | `references/registration-validation.md` |

## Artifact Layout References

| Open when you need to... | Read |
|--------------------------|------|
| keep the whole skill inline in one coherent `SKILL.md` | `references/layout-inline-skill.md` |
| split optional deep knowledge into focused routed references | `references/layout-reference-backed-skill.md` |
| add scripts for deterministic automation or validation | `references/layout-script-backed-workflow.md` |
| define a skill that is usually invoked with explicit arguments | `references/layout-argument-driven-skill.md` |
| ship reusable templates, schemas, or other static assets | `references/layout-asset-template-skill.md` |

## Workflow Mechanic References

| Open when you need to... | Read |
|--------------------------|------|
| break a task into fixed ordered steps | `references/workflow-prompt-chaining.md` |
| classify requests and route them to different downstream paths | `references/workflow-routing.md` |
| split independent work into parallel units or votes | `references/workflow-parallel.md` |
| discover work units dynamically and coordinate worker outputs | `references/workflow-orchestrator-workers.md` |
| run validate-fix-repeat checks during authoring or execution | `references/workflow-validation-loops.md` |
| validate a plan before executing a risky action | `references/workflow-plan-validate-execute.md` |

## Claude Code References

| Open when you need to... | Read |
|--------------------------|------|
| use Claude-specific frontmatter or invocation controls | `references/claude-frontmatter-invocation.md` |
| use Claude argument fields or substitution variables | `references/claude-argument-substitutions.md` |
| build a skill that runs in isolated `context: fork` | `references/claude-subagent-fork.md` |
| build a skill that uses Claude hooks for deterministic enforcement | `references/claude-hook-backed.md` |
| use Claude shell preprocessing for dynamic context injection | `references/claude-dynamic-context.md` |

## Example Profiles

| Open when you need to... | Read |
|--------------------------|------|
| see the expected depth for a documentation-heavy skill | `references/example-documentation-skill.md` |
| see the expected depth for a workflow-process skill | `references/example-workflow-process-skill.md` |
| see what a good routed skill looks like | `references/example-router-skill.md` |
| see what a good subagent-fork skill looks like | `references/example-subagent-fork-skill.md` |
| see what a good hook-backed skill looks like | `references/example-hook-backed-skill.md` |

## Step 1: Resolve target, path, and shape

1. Resolve the intended operation (`create`, `update`, `synthesize`, `iterate`) and inspect workspace prior art before choosing where files belong.
2. Choose the target skill root from observed conventions. If the canonical location is still unclear after inspection, ask one direct question before editing files.
3. Read `references/mode-selection.md` to choose the minimum required workflow paths.
4. Read `references/execution-shapes.md` to choose the primary execution shape.
5. Default to the simplest adequate shape. If selecting a more complex shape, record why simpler shapes were rejected.
6. Load only the exact artifact-layout, workflow-mechanic, and provider-specific leaf files required by that shape.
7. Before adding guidance, identify what existing rule, section, or file should be narrowed, replaced, or removed.
8. Record portability implications before using provider-specific mechanics.

## Step 2: Run synthesis when needed

Read `references/synthesis-path.md`.

1. Use this path for new skills, material changes, and research-first planning.
2. Collect and score relevant sources with provenance.
3. Read `references/source-discovery.md` when source material is thin, stale, or ambiguous.
4. Read `references/source-adaptation.md` when adapting an upstream prompt, workflow, rubric, benchmark, or docs.
5. Produce source-backed decisions and coverage/gap status, including the class and execution-shape choice.
6. Load example profiles only when they add concrete depth for the selected class or shape.
7. If the skill uses provider-specific mechanics, include current official provider docs and capture usage constraints.
8. Do not move to authoring until required coverage is understood or gaps are explicit.

## Step 3: Run iteration first when improving from outcomes/examples

Read `references/iteration-path.md` first when selected path includes `iteration` (for example operation `iterate`).

1. Capture and anonymize examples with provenance.
2. Read `references/iteration-evidence.md` when examples should persist beyond the current turn.
3. Review skill behavior against working and holdout slices.
4. Propose improvements from positive/negative/fix evidence.
5. Carry concrete behavior deltas into authoring.

Skip this step when selected path does not include `iteration`.

## Step 4: Author or update skill artifacts

Read `references/authoring-path.md`.

1. Write or update `SKILL.md` in imperative voice with trigger-rich description.
2. Keep `SKILL.md` as the runtime router, not an encyclopedia.
3. Run the pre-edit precision check in `references/authoring-path.md` before creating new sections or files.
4. Read `references/reference-architecture.md` before adding bulk instructions or new reference files.
5. Create or update `SPEC.md` using `references/spec-template.md` when creating a new skill or materially changing its contract.
6. Create focused reference files, scripts, and assets only when each one has a clear "open when..." reason and cannot be handled by tightening an existing file.
7. If you add a bundled reference file, add a direct routing entry for it in this `SKILL.md`.
8. Prefer checklists, tables, templates, and input/output examples over explanatory prose.
9. Follow only the specific artifact-layout, workflow-mechanic, Claude-specific, and output-contract references selected for this skill.
10. For advanced execution shapes, add the required routing, delegation, or safety contracts before considering the skill complete.
11. For authoring/generator skills, include transformed examples in references:
   - happy-path
   - secure/robust variant
   - anti-pattern + corrected version
12. After any skill artifact changes, run the post-change precision pass in `references/authoring-path.md` before description optimization or validation.

## Step 5: Optimize description quality

Read `references/description-optimization.md`.

1. Validate should-trigger and should-not-trigger query sets.
2. Reduce false positives and false negatives with targeted description edits.
3. Keep trigger language generic across providers unless the skill is intentionally provider-specific.

## Step 6: Register and validate

Read `references/registration-validation.md`.

1. Apply repository registration steps for the active layout you verified in the workspace.
2. Run quick validation for structural checks.
3. Review validator warnings, precision-pass results, and coverage gaps with judgment before completion.

## Output format

Return:

1. `Summary`
2. `Changes Made`
3. `Validation Results`
4. `Open Gaps`

```


### `references/authoring-path.md`

```markdown
# Authoring Path

Use this path to create or update skill files.

## Runtime Writing Rules

1. Frontmatter must be first line.
2. `name` must match the directory.
3. `description` must contain realistic trigger language.
4. Keep runtime guidance imperative and compact.
5. Prefer tables, checklists, templates, and examples over prose.
6. Use `SKILL.md` as the runtime decision layer for complex skills.

## Precision Pass

Run the pre-edit check before creating new sections, references, scripts, or assets.

| Question | Required answer |
|----------|-----------------|
| What behavior should change? | one concrete behavior delta |
| What existing rule can be narrowed or replaced? | file and section, or `none` with reason |
| What can be removed or moved out of runtime? | obsolete, duplicate, provenance, or maintenance-only content |
| Why is any new artifact necessary? | branch, lookup, automation, template, or validation need |

Prefer editing existing guidance when it can express the behavior without making that guidance broader.

After any skill artifact changes, run the post-change pass:

1. Re-read changed `SKILL.md` and routed references as a user of the skill would.
2. Remove or narrow any rule made redundant by the change.
3. Move provenance, rationale, or maintenance-only notes out of runtime files.
4. Confirm every added line changes an agent decision, action, or verification step.
5. Record the precision result in the final output as `replaced`, `narrowed`, `moved`, `deleted`, or `added with reason`.

This is a judgment pass. Do not add validators or rigid checklists solely to make the precision pass machine-checkable.

## Path Rules

1. Treat the skill directory as the root for bundled files.
2. Use `references/...`, `scripts/...`, and `assets/...` paths by default.
3. Reserve repo-root paths for registration instructions only.
4. Follow repo prior art if the workspace already standardizes on a provider-specific path variable.
5. Avoid host-specific absolute filesystem paths.

## Supporting Files

Create only what the skill needs:

| File or dir | Use |
|-------------|-----|
| `SPEC.md` | maintenance contract |
| `references/` | optional depth loaded by route |
| `references/evidence/` | persistent iteration examples |
| `scripts/` | repeatable automation or validation |
| `assets/` | reusable templates or static artifacts |

Keep runtime references as direct children of `references/`. Use clear filename prefixes instead of nested folders when references are related.

## File Creation Rules

1. Read `references/reference-architecture.md` before adding bundled files.
2. Create a new reference only when it has a clear "open when..." reason and cannot be handled by tightening an existing reference.
3. If you add a bundled reference, add a direct routing entry for it in `SKILL.md`.
4. Do not create catch-all docs that mix workflow, source notes, examples, and validation results.
5. Keep provenance in `SOURCES.md`, not in runtime files.
6. Update `SPEC.md` when the skill contract changes materially.
7. Do not add nested runtime reference folders unless the content is non-runtime evidence or static assets.

## Class-Specific Requirements

### `integration-documentation`

Require focused coverage for:

1. API surface and behavior contracts
2. config/runtime options
3. common downstream use cases
4. known issues and workarounds
5. version or migration variance

Default minimum depth:

1. at least 6 concrete downstream use cases
2. at least 8 issue/fix or failure/workaround entries

## Shape-Specific Requirements

| Shape | Require |
|-------|---------|
| `router` | route criteria, fallback, per-route contract, misroute recovery |
| `script-backed-workflow` | documented scripts, non-interactive execution, structured output, fallback |
| `parallelization` / `orchestrator-workers` | unit of work, worker output schema, merge rule, stop condition |
| `subagent-fork` | actionable task, return contract, isolation reason, portability note |
| `hook-backed` | event scope, side-effect boundary, fallback, safety note |
| `asset-template` | asset routing, placeholder guidance, validation checklist when needed |
| `argument-driven` | expected arguments, empty-input behavior, manual-only use when risky |

## Example Requirements

Authoring or generator skills should include:

1. happy-path example
2. secure or robust variant
3. anti-pattern plus correction

Do not accept abstract-only guidance when a concrete example is needed.

## Required Output

- updated `SKILL.md`
- updated `SPEC.md` when required
- updated or added supporting files
- precision-pass decision: replaced, narrowed, moved, deleted, or added with reason
- explanation of major authoring decisions
- description-optimization handoff

```


### `references/claude-argument-substitutions.md`

```markdown
# Claude Argument Substitutions

Load this when the skill uses Claude Code argument fields or substitution variables.

## Supported substitutions

- `$ARGUMENTS`
- `$ARGUMENTS[N]`
- `$N`
- named arguments such as `$issue` when `arguments` is declared
- `${CLAUDE_SESSION_ID}`
- `${CLAUDE_EFFORT}`
- `${CLAUDE_SKILL_DIR}`

## Required contract

1. Document expected arguments and empty-input behavior.
2. Add quoting-aware examples for multi-word input when ambiguity is likely.
3. Use manual-only invocation for side-effect-heavy argument-driven skills.
4. Add portability notes because this syntax is Claude Code-specific.

```


### `references/claude-dynamic-context.md`

`````markdown
# Claude Dynamic Context Injection

Load this when the skill uses Claude Code shell preprocessing with ``!`command` `` or fenced ````!` blocks.

## Use this file for

- stable, high-signal preprocessing
- small dynamic snippets that are cheaper than adding a full script

## Use sparingly

1. Only inject output that is stable, high-signal, and cheap.
2. Never inject large or noisy output.
3. Prefer a normal script or tool call when that is easier to reason about.

Treat this as preprocessing, not model behavior, and add portability notes because it is Claude Code-specific.

`````


### `references/claude-frontmatter-invocation.md`

```markdown
# Claude Frontmatter And Invocation

Load this when the skill needs Claude Code-specific frontmatter or invocation control.

## Use this file for

- extra trigger metadata
- invocation visibility rules
- skill-scoped model or effort overrides
- path or shell activation controls

## Relevant fields

| Field | Purpose | Notes |
|-------|---------|-------|
| `when_to_use` | extra trigger context for Claude | additive only; keep trigger-rich language in `description` |
| `disable-model-invocation` | only the user can invoke | good for side-effect-heavy workflows |
| `user-invocable` | hide from `/` menu and let Claude invoke | good for passive background knowledge |
| `allowed-tools` | pre-approve tools while skill is active | provider-specific |
| `model` | skill-scoped model override | provider-specific |
| `effort` | skill-scoped effort override | provider-specific |
| `paths` | glob-based activation limits | provider-specific |
| `shell` | shell for `!` preprocessing | provider-specific |

## Invocation rules

1. If Claude should not decide when to run the skill, set `disable-model-invocation: true`.
2. If the skill is not a meaningful command for humans, consider `user-invocable: false`.
3. Keep trigger-rich language in `description` even if `when_to_use` is present.

## Portability rule

When using any Claude-specific field, say why it is necessary and note that it is not portable Agent Skills behavior.

```


### `references/claude-hook-backed.md`

```markdown
# Claude Hook-Backed Skills

Load this when the skill uses Claude Code hooks for deterministic enforcement around tool or lifecycle events.

## Use this file for

- pre-tool validation for risky commands
- post-edit formatting or linting
- scoped guardrails around specific tool events

## Required contract

1. Narrow event and matcher scope.
2. Explicit side-effect boundaries.
3. Fallback behavior when hooks are unavailable.
4. Security note for shell execution, path handling, and sensitive files.

## Security rules

1. Command hooks run with full user permissions.
2. Validate and sanitize inputs.
3. Use absolute paths for scripts inside the hook definition.
4. Avoid sensitive files such as `.env`, `.git/`, and keys.
5. Test hooks before treating them as trusted enforcement.

## Async note

Async hooks cannot block the action that triggered them; they are not a substitute for synchronous validation.

```


### `references/claude-subagent-fork.md`

```markdown
# Claude Subagent-Fork Skills

Load this when the skill should run in isolated context with `context: fork`.

## Use this file for

- self-contained delegated investigations
- isolated context for focus or permission boundaries
- model or tool specialization where the main thread only needs a summary

## Required contract

1. An actionable task in the skill body.
2. Expected return or summary contract.
3. Explicit reason isolation is useful.
4. Portability note because this is Claude Code-specific.

## Avoid when

1. The skill is passive conventions or reference material.
2. The task depends heavily on the current conversation history.
3. The main value comes from inline collaboration rather than delegation.

```


### `references/description-optimization.md`

```markdown
# Description Optimization

Use this path to improve skill triggering quality and reduce false matches.

## Trigger quality loop

1. Draft a description with realistic user language and concrete trigger phrases.
2. Build two query sets:
- should-trigger queries
- should-not-trigger queries
3. Check the current description against both sets.
4. Edit description wording to improve precision/recall.
5. Repeat until false positives and false negatives are reduced to acceptable levels.

## Authoring rules

1. Keep the description in third person.
2. Include what the skill does and when to use it.
3. Avoid implementation details that do not help triggering.
4. Avoid provider-specific phrasing unless the skill is intentionally provider-specific.
5. For provider-agnostic skills, avoid naming Claude, Codex, or any provider in ways that would narrow portability expectations.

## Required output

- Final description text
- should-trigger query set
- should-not-trigger query set
- Summary of edits made to improve trigger behavior

```


### `references/design-principles.md`

```markdown
# Skill Design Principles

Use this guide to keep skill instructions dense, scannable, and worth their token cost.

## Core Rule

- Every line should help the agent decide, do, or verify something.
- Prefer tables, checklists, templates, and input/output examples over explanatory prose.
- Keep rationale to one short sentence unless the agent is likely to make the wrong choice without it.

## Precision Before Addition

Before adding instructions, choose one:

| Action | Use when |
|--------|----------|
| replace | an existing rule is vague, stale, or pointing at the wrong behavior |
| narrow | the current rule is mostly right but over-triggers or invites extra work |
| move | the content belongs in `SOURCES.md`, `SPEC.md`, or a routed reference |
| delete | the content repeats another rule or no longer changes behavior |
| add | no existing rule can cover the new behavior without becoming less precise |

Do not add a new section, reference, or checklist until replacement, narrowing, moving, and deletion have been considered.

## Keep Vs Cut

| Keep | Cut |
|------|-----|
| project-specific conventions | generic background the agent already knows |
| non-obvious gotchas | motivational filler |
| exact commands, schemas, and templates | repeated restatements of the same rule |
| branch logic and defaults | long essays where a table would work |
| one strong example | multiple weak examples saying the same thing |
| behavior-changing constraints | source notes that belong in `SOURCES.md` |

## Match Structure To Fragility

| Fragility | Preferred structure | Avoid |
|-----------|---------------------|-------|
| high | exact steps, strict templates, validation gates | open-ended guidance |
| medium | short checklist plus examples | long rationale-heavy prose |
| low | brief goals and constraints | overspecified playbooks |

## Preferred Instruction Shapes

| Need | Preferred shape |
|------|-----------------|
| choose a path | decision table |
| do a repeatable task | numbered checklist |
| enforce output structure | template or schema |
| show style or tone | input/output examples |
| diagnose failures | symptom/cause/fix matrix |
| communicate exact facts | compact reference table |

## Description Rules

- Keep `description` in third person.
- Put trigger language in `description`, not the body.
- Front-load what the skill does and when to use it.
- Do not spend description space on internals unless they improve triggering.

## Runtime Writing Rules

- Use imperative voice.
- State one default path before mentioning alternatives.
- Use one term per concept; do not rotate synonyms.
- Put universal rules in `SKILL.md`; put optional depth in routed refs.
- If a section is mostly explanation, cut it or replace it with a denser structure.

## Reference Rules

- Reference filenames should predict their contents.
- Each reference should answer one lookup question.
- Keep runtime references flat under `references/`.
- For related variant-specific references, use sibling files with a shared prefix and explicit differentiator.
- Every bundled reference should have a direct "open when..." entry in `SKILL.md`.
- Do not create catch-all files for notes, context, or mixed patterns.

## Independence And Portability

- Do not require another skill by name at runtime.
- Use skill-root-relative paths by default.
- Reuse established repo-specific path variables only when the repo already standardizes on them.
- Label provider-specific mechanics explicitly and add portability notes when they matter.

## Long Files

- Keep `SKILL.md` short enough to scan as a router.
- For references over 100 lines, add `## Contents`.
- If a reference grows because it mixes multiple lookup needs, split it.

```


### `references/example-documentation-skill.md`

```markdown
# Case Study: Documentation Skill Synthesis

## Scenario

Goal: create a skill that helps an agent answer and author code for a library without repeatedly re-reading upstream docs.

## Input collection approach

This case used breadth-first source collection and only stopped when new retrieval yielded mostly duplicates:

1. Official docs landing pages and navigation trees.
2. All API/class/module reference pages.
3. Configuration and environment reference pages.
4. Official examples/tutorials.
5. Troubleshooting/error catalog pages.
6. Migration/deprecation/changelog pages.
7. Upstream repo README plus canonical examples.
8. In-repo usage of the library (`rg` on imports and key APIs).

## Coverage matrix used

Required dimensions tracked during synthesis:

1. Setup and installation.
2. Core primitives and API surface.
3. Configuration and runtime options.
4. Normal usage patterns.
5. Edge cases and failure handling.
6. Version-specific differences.
7. Migration and deprecation guidance.
8. Instructional templates/examples for direct reuse.

## Synthesized artifacts produced

The resulting skill references included:

1. Happy-path implementation template.
2. Production-safe variant with defensive defaults.
3. Anti-pattern and corrected implementation.
4. Intent-to-reference routing guide (which section to load for which user request).
5. Gap log with explicit next retrieval steps.

## Source-to-decision trace (sample)

1. Source class: migration/changelog docs.
   Decision: add a version-compatibility checklist section to the skill.
   Why: multiple API signatures existed across versions; without this, answers were inconsistent.
2. Source class: troubleshooting/error catalog.
   Decision: add an error-to-fix lookup table in references.
   Why: user prompts often start from failures, not idealized setup.
3. Source class: in-repo usage scan (`rg`).
   Decision: prioritize examples matching local project patterns.
   Why: produced outputs became directly usable with fewer edits.

## Concrete artifacts (sample)

1. Prompt and output skeleton:
   Prompt: "Configure <library> client for retries and auth in production."
   Output: a production-safe template with retry/backoff, timeout defaults, and auth placeholders.
2. Anti-pattern transformation:
   Before: single inline config with no timeout/error handling.
   After: structured config with explicit timeout, retry policy, and failure handling notes.
3. Reference routing snippet:
   If request mentions "migration" -> load migration/changelog reference first, then API reference.

## What made this high quality

1. Input retrieval was exhaustive across all doc classes, not just top pages.
2. The skill shipped transformed examples, not citation-only notes.
3. Coverage and gaps were explicit, so iteration could continue safely.

```


### `references/example-hook-backed-skill.md`

```markdown
# Case Study: Hook-Backed Skill Synthesis

## Scenario

Goal: create a skill that enforces a deterministic check at a specific lifecycle or tool boundary.

## Input collection approach

This case collected:

1. official hook lifecycle and schema docs
2. security guidance for shell-executed hooks
3. examples of narrow matchers vs over-broad hooks
4. fallback behavior for environments without hooks

## Coverage matrix used

Required dimensions tracked during synthesis:

1. event and matcher scope
2. decision behavior
3. security boundaries
4. fallback behavior
5. portability constraints

## Synthesized artifacts produced

The resulting skill references included:

1. hook configuration example
2. safety checklist
3. fallback path without hooks
4. anti-pattern showing over-broad or unsafe hook scope

## What made this high quality

1. the hook scope was narrow and auditable
2. security assumptions were explicit
3. the skill still described what to do when hooks were unavailable

```


### `references/example-router-skill.md`

```markdown
# Case Study: Router Skill Synthesis

## Scenario

Goal: create a skill that classifies requests into distinct downstream paths without overloading one prompt.

## Input collection approach

This case collected:

1. examples of request categories
2. known ambiguous cases
3. downstream resources for each route
4. historical misroutes and their fixes

Collection stopped only after route criteria and fallback behavior were explicit.

## Coverage matrix used

Required dimensions tracked during synthesis:

1. route categories and triggers
2. ambiguous or overlapping cases
3. downstream ownership per route
4. default/fallback path
5. misroute recovery behavior

## Synthesized artifacts produced

The resulting skill references included:

1. route-selection table
2. one reference or script per route
3. ambiguous-case examples
4. fallback rule for unclear input

## What made this high quality

1. the route table was explicit
2. every route had one clear downstream owner
3. the skill knew what to do when classification was uncertain

```


### `references/example-subagent-fork-skill.md`

```markdown
# Case Study: Subagent-Fork Skill Synthesis

## Scenario

Goal: create a skill that runs a self-contained task in isolated context and returns a concise summary.

## Input collection approach

This case collected:

1. official provider docs for skill execution in forked context
2. examples of self-contained tasks that benefit from isolation
3. failure cases where passive guidance was incorrectly put into subagents
4. summary expectations for returning results to the main thread

## Coverage matrix used

Required dimensions tracked during synthesis:

1. why isolation helps
2. task prompt clarity
3. output/summary contract
4. tool/model assumptions
5. portability constraints

## Synthesized artifacts produced

The resulting skill references included:

1. actionable task body
2. expected summary schema
3. portability note
4. anti-pattern showing passive guidance that should stay inline

## What made this high quality

1. the skill body was a task, not a convention list
2. the isolation benefit was concrete
3. the result expected back in the main thread was explicit

```


### `references/example-workflow-process-skill.md`

```markdown
# Case Study: Workflow/Process Skill Synthesis

## Scenario

Goal: create a skill for repeatable operational workflows (for example PR prep, CI triage, branching, settings audit).

## Input collection approach

This case collected process truth from all authoritative locations:

1. Official tool docs and syntax references.
2. Repository workflow conventions and policy docs.
3. Existing local skills with adjacent process logic.
4. CI logs, failure patterns, and known operational pitfalls.
5. Positive and negative historical examples from prior runs.

Collection stopped only after failure and recovery paths were well represented.

## Coverage matrix used

Required dimensions tracked during synthesis:

1. Preconditions and required context.
2. Ordered execution flow.
3. Safety/permission boundaries.
4. Expected outputs and acceptance checks.
5. Failure handling and retry behavior.
6. Escalation and handoff behavior.

## Synthesized artifacts produced

The resulting skill references included:

1. Happy-path execution transcript.
2. Guarded variant with stricter safety constraints.
3. Failure-recovery transcript for a critical broken step.
4. Output template for deterministic reporting.
5. Changelog rules for iterative improvement from examples.

## Source-to-decision trace (sample)

1. Source class: repo policy docs.
   Decision: add explicit precondition checks before running side-effecting steps.
   Why: prevented invalid execution in partially configured environments.
2. Source class: CI failure logs.
   Decision: add a mandatory failure triage branch with retry vs escalate criteria.
   Why: reduced dead-end loops during workflow execution.
3. Source class: historical positive/negative examples.
   Decision: standardize output format for easier review and iteration.
   Why: made regressions and improvements comparable across runs.

## Concrete artifacts (sample)

1. Happy-path transcript snippet:
   Preconditions pass -> execute steps 1..N -> emit structured summary with status per step.
2. Failure-recovery transcript snippet:
   Step fails -> classify transient/permanent -> retry once or escalate with captured evidence.
3. Deterministic report template:
   Sections: Preconditions, Actions Taken, Validation Results, Failures/Recoveries, Next Actions.

## What made this high quality

1. The workflow was executable without rediscovering steps.
2. Non-happy paths were first-class, not afterthoughts.
3. Outputs were structured for consistent review and iteration.

```


### `references/execution-shapes.md`

```markdown
# Execution Shapes

Use this guide to choose the runtime shape of a skill before you decide its files.
Default rule: choose the simplest adequate shape, then add complexity only when it clearly improves outcomes.
Once you pick a shape, load only the concrete leaf references it needs.

## Defaulting To The Simplest Shape

Start from these questions, in order:

1. Can one coherent set of instructions handle most requests?
   If yes, prefer `inline-guidance`.
2. Is the main complexity optional knowledge rather than control flow?
   If yes, prefer `reference-backed-expert`.
3. Is the hard part data extraction, validation, or repeatable automation?
   If yes, prefer `script-backed-workflow`.
4. Does the user usually invoke the skill with explicit parameters?
   If yes, add `argument-driven`.
5. Only then consider routing, worker delegation, subagent execution, hooks, or templates.

Do not jump to advanced mechanics because they sound powerful.

## Complexity Budget

Adding shape complexity should usually replace ambiguity, not add ceremony.

| Addition | Require |
|----------|---------|
| new reference | a routed lookup need that existing files cannot satisfy precisely |
| new script | a repeated operation that is fragile or error-prone in plain instructions |
| new route | distinct inputs that require different tools, references, or output contracts |
| provider-specific mechanic | a capability that portable prompt guidance cannot provide |

If the benefit is only "more thorough", keep the simpler shape and tighten the existing instructions.

## Shape Decision Table

| Shape | Use when | Open next | Portability notes |
|-------|----------|-----------|-------------------|
| `inline-guidance` | one coherent policy, checklist, or procedure is enough | `references/layout-inline-skill.md` | most portable default |
| `reference-backed-expert` | optional deep knowledge is the main complexity | `references/layout-reference-backed-skill.md` | portable if file references stay relative |
| `script-backed-workflow` | repeated parsing, validation, APIs, or transformations are fragile in plain shell | `references/layout-script-backed-workflow.md` | portable if dependencies are explicit |
| `argument-driven` | the skill is usually invoked with issue numbers, paths, targets, or modes | `references/layout-argument-driven-skill.md` | often provider-specific beyond basic manual invocation |
| `router` | distinct categories need different downstream prompts, tools, or references | `references/workflow-routing.md` | portable if routing stays in prompt logic |
| `parallelization` | independent subtasks or multiple votes improve speed or confidence | `references/workflow-parallel.md` | often implemented with tools or agents |
| `orchestrator-workers` | the number or type of subtasks is discovered at runtime | `references/workflow-orchestrator-workers.md` | usually higher-latency and provider-sensitive |
| `subagent-fork` | the skill needs isolated context, tools, or model defaults | `references/claude-subagent-fork.md` | Claude Code-specific |
| `hook-backed` | deterministic enforcement is required beyond prompt guidance | `references/claude-hook-backed.md` | highly provider-specific and security-sensitive |
| `asset-template` | reusable templates, schemas, or static artifacts carry most of the value | `references/layout-asset-template-skill.md` | portable if assets are generic files |

If the chosen shape also uses explicit arguments, Claude-specific frontmatter, or shell preprocessing, load the matching flat `references/claude-*` file listed in `SKILL.md`.

## Secondary Workflow Mechanics

These are not usually primary execution shapes, but they often refine one:

- fixed ordered steps -> `references/workflow-prompt-chaining.md`
- validate-fix-repeat loops -> `references/workflow-validation-loops.md`
- plan-before-execute flows -> `references/workflow-plan-validate-execute.md`

## Hybrid Shapes

Use a hybrid only when one primary shape is insufficient.

1. Declare one primary shape.
2. Add only the minimum secondary shapes needed.
3. Keep each secondary shape scoped to one concrete need.
4. Remove or narrow any older shape guidance that the secondary shape replaces.
5. Avoid stacking multiple advanced shapes without a clear base path.

## Advanced-Shape Hard Stops

Do not finalize a skill when any of these are true:

1. The chosen shape is implied but not named.
2. A simpler shape was not considered.
3. A router has no fallback or default path.
4. A subagent-fork skill contains only passive guidance.
5. A hook-backed skill lacks a security note or fallback behavior.
6. Provider-specific mechanics are used without portability notes.

```


### `references/iteration-evidence.md`

````markdown
# Iteration Evidence

Use this guide when improving a skill from positive examples, negative examples, review feedback, validation results, or observed agent behavior.

## Storage Layout

Store persistent improvement evidence under:

```text
references/evidence/
├── findings-log.md
├── working-set.md
└── holdout-set.md
```

Use this directory only when examples should outlive the current task. For a one-off small fix, summarize the examples in `SOURCES.md` instead.

## File Roles

`references/evidence/findings-log.md` records interpreted findings:

- repeated failure patterns
- preserved success patterns
- suspected root causes
- instruction changes made in response
- unresolved risks

`references/evidence/working-set.md` stores examples used while editing the skill.

`references/evidence/holdout-set.md` stores examples reserved for validation after edits. Do not tune directly against holdout examples unless the user explicitly moves them into the working set.

## Example Record Schema

Use one record per example:

```markdown
## EX-001: Short label

- Label: positive | negative
- Kind: true-positive | false-positive | false-negative | fix | regression | edge-case
- Origin: human-verified | mixed | synthetic
- Source: issue/PR/commit/log/user note/local validation pointer
- Status: working | holdout | resolved | deferred
- Expected behavior: concise statement
- Observed behavior: concise statement
- Skill delta: instruction, reference, description, or validation change
- Anonymization: what was removed or generalized

### Content

Summarized or redacted example content.
```

Keep records concise. Preserve enough detail to reproduce the behavior, but redact secrets, customer data, private URLs, and unnecessary user content.

## Positive And Negative Findings

Positive findings are not just success stories. Use them to protect behaviors that must not regress.

Negative findings should identify the smallest failing decision:

- wrong trigger behavior
- missing source type
- skipped reference file
- overloaded or hidden instruction
- weak output contract
- missing validation step
- unsafe or non-portable path assumption

Each negative finding should map to a concrete skill delta or an explicit deferred reason.

## Promotion Rules

Promote evidence into the skill artifacts only when it changes future behavior:

- Put universal behavioral rules in `SKILL.md`.
- Put domain-specific examples in a focused reference.
- Put source provenance and decisions in `SOURCES.md`.
- Keep raw or semi-raw examples in `references/evidence/`.

Do not turn `references/evidence/` into a changelog. The changelog belongs in `SOURCES.md`.

````


### `references/iteration-path.md`

```markdown
# Iteration Path

Use this path when improving a skill based on outcomes and examples.

## Example intake

Read `references/iteration-evidence.md` when examples should be persisted across future skill revisions.

Capture example records with:

- label (`positive` or `negative`)
- example kind (`true-positive`, `false-positive`, `fix`, `regression`, `edge-case`)
- evidence origin (`human-verified`, `mixed`, `synthetic`)
- anonymized content
- source provenance pointer (where the example came from)

## Replay and Review

1. Review behavior against working set.
2. Review behavior against holdout set.
3. Record improved/unchanged/regressed outcomes.
4. Confirm both positive and negative behavior changed in the expected direction.

## Improvement rules

1. Prioritize fixes for repeated negative patterns.
2. Preserve behavior that consistently succeeds on positives.
3. Update transformed examples when guidance changes.
4. Record deltas in `SOURCES.md` changelog.
5. Expand input collection when failures indicate coverage gaps.
6. Store durable positive/negative examples in `references/evidence/` instead of overloading `SKILL.md`, `SOURCES.md`, or a generic reference file.
7. Keep holdout examples separate from working examples until validation is complete.
8. Update `SPEC.md` when iteration changes the skill's intended scope, evidence model, validation expectations, or known limitations.

## Required output

- Example intake summary
- Behavior deltas
- Updated artifacts
- Replay summary

```


### `references/layout-argument-driven-skill.md`

````markdown
# Argument-Driven Skill Layout

Use this layout when the skill is normally invoked with explicit inputs such as issue numbers, paths, modes, or targets.

## Choose this layout when

- the user supplies parameters directly
- empty-input behavior needs to be defined
- manual invocation is safer than automatic activation

## Common layout

```yaml
---
name: fix-issue
description: Fix a GitHub issue by number. Use when asked to fix or resolve a specific issue.
argument-hint: "[issue-number]"
disable-model-invocation: true
---
```

## Required contract

1. Document expected arguments and empty-input behavior.
2. Use manual-only invocation when side effects are substantial.
3. Use named or positional arguments only when they improve clarity.
4. Add portability notes if the argument syntax depends on provider-specific mechanics.

## Also load

- `references/claude-argument-substitutions.md` when using Claude Code substitutions or named arguments
- `references/claude-frontmatter-invocation.md` when invocation control needs provider-specific fields

````


### `references/layout-asset-template-skill.md`

````markdown
# Asset-Template Skill Layout

Use this layout when reusable templates, schemas, or static artifacts carry most of the skill's value.

## Choose this layout when

- the skill fills in or adapts reusable artifacts
- the runtime procedure is small compared to the bundled assets
- output quality depends on stable templates or schemas

## File layout

```text
my-skill/
├── SKILL.md
└── assets/
    ├── template.md
    └── schema.json
```

## Required contract

1. `SKILL.md` tells the agent when to load each asset.
2. The skill explains how to adapt placeholders or fields.
3. Add a validation checklist when filled-in output can silently drift.

## Avoid this layout when

- the template is small enough to stay inline
- the asset is just an attachment with no routing or reuse value

````


### `references/layout-inline-skill.md`

````markdown
# Inline Skill Layout

Use this layout when one coherent policy, checklist, or procedure fits directly in `SKILL.md`.

## Choose this layout when

- the skill has one dominant path
- every invocation needs roughly the same instructions
- deep optional knowledge is not the main problem

## File layout

```text
my-skill/
└── SKILL.md
```

## Required contract

1. Keep the body small enough to scan in one read.
2. Put all universal steps in `SKILL.md`.
3. Add references only if a real branch or lookup need appears.

## Avoid this layout when

- most invocations need only a subset of a large knowledge base
- scripts or validators carry important runtime behavior
- routing or iterative validation is central to the skill

````


### `references/layout-reference-backed-skill.md`

````markdown
# Reference-Backed Skill Layout

Use this layout when the skill needs deep knowledge, but most runs only need one branch or subset of that knowledge.

## Choose this layout when

- `SKILL.md` can act as a router
- bundled references can stay focused by lookup need
- the complexity is optional knowledge, not heavy automation

## File layout

```text
my-skill/
├── SKILL.md
└── references/
    ├── focused-topic-a.md
    ├── focused-topic-b.md
    └── troubleshooting.md
```

Keep reference files as direct children of `references/`. For related variant-specific leaves, use a shared filename prefix and list each file directly from `SKILL.md`.

## Required contract

1. `SKILL.md` tells the agent exactly when to open each reference.
2. Reference filenames predict their contents.
3. No reference mixes routing, troubleshooting, examples, and source notes without a clear reason.
4. Large references include navigation or are split further.
5. Runtime references stay flat unless there is a non-runtime evidence or asset reason to use a subfolder.

## Avoid this layout when

- the skill is small enough to stay inline
- scripts or validators are central to execution
- the references would only exist as vague topic buckets

````


### `references/layout-script-backed-workflow.md`

````markdown
# Script-Backed Skill Layout

Use this layout when parsing, validation, APIs, or repeatable transformations are fragile in plain shell or prose alone.

## Choose this layout when

- the skill benefits from deterministic automation
- repeated shell snippets would be brittle
- validation or data extraction should be reusable

## File layout

```text
my-skill/
├── SKILL.md
└── scripts/
    ├── fetch.py
    └── validate.py
```

## Required contract

1. Every script is named in `SKILL.md` with arguments, outputs, and fallback behavior.
2. Scripts are non-interactive.
3. Standard output is structured when practical.
4. The skill explains what to do if a script fails or is unavailable.

## Avoid this layout when

- one simple shell command is enough
- the "script" would only wrap trivial shell for no reliability gain

````


### `references/mode-selection.md`

```markdown
# Mode Selection

Choose the minimal set of paths needed for the request.
Regardless of path, prioritize input quality and coverage depth before finalizing outputs.

## Path mapping

| Request shape | Required paths |
|---------------|----------------|
| New skill from scratch | synthesis + authoring + description optimization + registration/validation |
| Update existing skill wording/structure | authoring + description optimization + registration/validation |
| Improve skill from outcomes/examples | iteration + authoring + description optimization + registration/validation |
| Research-first skill planning | synthesis only, then authoring if requested |

## Skill class selection

Classify the target skill before synthesis. This determines the coverage dimensions that must be represented in sources, references, and validation.

| Skill class | Typical request shape | Required dimensions |
|-------------|-----------------------|---------------------|
| `workflow-process` | repeatable operations, CI/task orchestration | preconditions, ordered flow, failure handling, safety boundaries |
| `integration-documentation` | library/framework integration, SDK usage, API correctness | API surface, config/runtime options, common use cases, known issues/workarounds, version/migration variance |
| `skill-authoring` | creating/updating/reviewing other skills | source provenance, precision pass, transformed examples, registration/validation |
| `generic` | does not match above | explicit dimensions chosen and justified in synthesis |

When the class is ambiguous, ask one direct clarification question before synthesis.

## Execution shape selection

Choose the skill's primary execution shape separately from the skill class.
Class answers "what domain/problem is this skill for?"
Shape answers "how should this skill run?"

Use `references/execution-shapes.md` for the full decision table and the next leaf reference to load.

Record:

1. primary execution shape
2. simpler-shape rejection when the chosen shape is advanced
3. exact leaf references opened because of that choice

## Required outputs by path

- `synthesis`: source inventory, decisions, coverage matrix, gaps.
- `synthesis`: selected class, selected execution shape, and selected example profile path(s), including profile-requirement coverage.
- `synthesis`: simplicity rationale showing why the chosen shape is necessary and which simpler shapes were rejected.
- `synthesis`: portability note when provider-specific mechanics are used.
- `synthesis`: explicit retrieval stopping rationale showing why further collection is currently low-yield.
- `authoring`: updated `SKILL.md` and required supporting files.
- `description optimization`: should/should-not trigger sets and final description.
- `iteration`: example intake summary and behavior deltas.
- `registration/validation`: registration edits and validator results.

## Completion Checks

Do not claim completion when any required path output is missing.

For authoring/generator skills, report missing transformed examples, selected-profile requirements, required class dimensions, or execution-shape choices as open gaps instead of hiding them.
When advanced mechanics are used, include justification and portability notes or report the missing decision as an open gap.

```


### `references/output-contracts.md`

`````markdown
# Output Contracts

Use this guide when the skill needs a predictable response shape.

## Choose The Contract

| Need | Use |
|------|-----|
| exact sections or headings | strict template |
| default structure with adaptation | flexible template |
| style is easier to imitate than describe | input/output examples |
| format depends on task type | decision table |
| scripts or tools parse the output | structured schema |

## Strict Template

```markdown
# [Title]

## Summary
[Required summary]

## Findings
- ...
```

## Flexible Template

```markdown
# [Title]

## Summary
[Default summary section; adapt if needed]

## Findings
[Adapt based on context]
```

## Input/Output Example

````markdown
Input: fix date formatting bug
Output:
```text
fix(reports): correct timezone date formatting
```
````

## Decision Table

```markdown
| Input Type | Output Format |
|------------|---------------|
| single file | inline summary |
| many files | grouped report |
```

## Structured Schema

````markdown
```json
{
  "status": "success",
  "summary": "One-line result",
  "findings": []
}
```
````

`````


### `references/reference-architecture.md`

```markdown
# Reference Architecture

Use this guide before adding bundled files or long sections to `SKILL.md`.

## Router Rule

- `SKILL.md` is the router.
- References are flat lookup leaves under `references/`.
- `SPEC.md` is the maintenance contract.
- `SOURCES.md` stores provenance and decisions.

## Lookup Test

Before creating a reference, finish this sentence:

- "I need to decide X, so read `...`."
- "I need to do Y, so read `...`."
- "I need to diagnose Z, so read `...`."

If the sentence sounds like "I need context" or "I need patterns", the file is too vague.

## Placement Table

| Put it in... | When it belongs there |
|--------------|-----------------------|
| `SKILL.md` | every run needs it |
| `references/` | only some branches need it; keep runtime references as direct children |
| `SPEC.md` | it explains maintenance, scope, or evidence policy |
| `SOURCES.md` | it is provenance, a decision record, or a gap |

## Reference Types

| Need | Shape |
|------|-------|
| choose a path | decision guide |
| execute a procedure | task guide |
| look up exact facts | reference table |
| diagnose a failure | troubleshooting matrix |
| imitate quality | example set |
| judge completeness | validation checklist |

## Naming Rules

- Name files for the question or action they answer.
- Good: `mode-selection.md`, `output-contracts.md`, `routing-workflows.md`
- Bad: `notes.md`, `context.md`, `patterns.md`, `research.md`
- Prefer flat filenames over nested reference folders.
- When related references cover parallel variants of one lookup need, keep them as sibling files with a shared prefix plus an explicit differentiator.
- List every runtime reference directly in `SKILL.md`.

## Split Rules

Create a new reference when:

- the content is only needed after a branch decision
- the content has one dominant type
- the section would make `SKILL.md` harder to scan
- the file is approaching 100 lines and contains multiple lookup needs
- the resulting file can be named as a direct child of `references/` with a clear lookup reason

Keep content in `SKILL.md` when:

- every invocation needs it
- it is short
- moving it would force unnecessary file loads

## Final Checks

1. Every runtime reference has a direct "open when..." reason in `SKILL.md`.
2. The filename tells the agent why to open it.
3. No required instruction is hidden only in an optional reference.
4. No reference has become a second `SKILL.md`.
5. No nested reference folder is introduced unless the content is non-runtime evidence or static assets.

```


### `references/registration-validation.md`

````markdown
# Registration and Validation

Apply registration and lightweight validation before completion.

## Registration checklist

1. Inspect the workspace and identify the active skill layout before editing files.
2. Create/update `<skill-root>/SKILL.md`, `<skill-root>/SPEC.md` when required by change scope, and any bundled `references/`, `scripts/`, or `assets/` beneath that root.
3. Default to `.agents/skills/<name>/` when there is no stronger prior art.
4. If the workspace clearly uses a different canonical layout, follow that layout instead of forcing `.agents/skills/`.
5. Common established alternatives include:
   - `skills/<name>/` when the workspace uses a canonical root skill tree
   - `.claude/skills/<name>/` for project-scoped Claude skills
   - `plugins/<plugin>/skills/<name>/` for plugin-scoped skills
   - another repository-managed skill root that is already established by neighboring skills or docs
6. If multiple plausible locations exist and inspection does not make the canonical target clear, ask the user before editing files.
7. Only apply repository-specific registration steps when the workspace conventions explicitly require them.

When a repository does maintain its own skill catalog, verify and update any required registration files such as:

- public skill inventories or tables
- project or plugin settings files
- allowlists used by other skills or automation

## Validation checklist

The validator is a structural check. It should fail only for invalid skill format or missing referenced files. The size warning requires author judgment, not a machine gate.

1. Run:

```bash
uv run scripts/quick_validate.py <path/to/skill-directory>
```

Use the skill-root-relative form above when running from the `skill-writer` directory.
If you must run the validator from another working directory, convert both paths to the correct relative path from that directory instead of introducing absolute or host-specific paths into the skill docs.

2. Confirm manually for authoring/generator skills:
- transformed examples exist in references (happy-path, secure/robust, anti-pattern+fix)
- synthesis coverage was considered and any gaps are explicit
- selected example profile requirements are satisfied and reported
- `SPEC.md` exists or was updated when the change creates a skill or materially changes intent, scope, evidence model, validation, or maintenance expectations
- every bundled reference file is directly discoverable from `SKILL.md`

3. Confirm manually for integration/documentation skills:
- focused references cover API surface, common use cases, known issues/workarounds, and version variance
- reference file names fit the skill's domain rather than a fixed template
- `SKILL.md` and `references/*.md` avoid host-specific absolute filesystem paths

4. Confirm manually for skills that are expected to be portable by default:
- bundled file references use skill-root-relative paths such as `references/...`, `scripts/...`, or `assets/...`
- provider-specific path variables (for example `${CLAUDE_SKILL_ROOT}`) should not be used; use skill-root-relative paths instead (e.g. `scripts/foo.py`, `references/bar.md`)
- provider-specific behavior, if any, is labeled as compatibility guidance rather than the primary workflow

5. Review validator warnings for oversized `SKILL.md` files.
6. Do not add validators for skill class, coverage quality, SPEC shape, trigger quality, or other qualitative guidance.

## Required output

- Registration changes summary
- Selected skill root and why it was chosen
- Validator output
- Any residual risks or open gaps

````


### `references/source-adaptation.md`

```markdown
# Source Adaptation

Use this when turning an upstream prompt, workflow, rubric, benchmark, guide, or docs set into a reusable skill.

## Goal

Preserve the source's useful intent while rewriting the runtime shape for this repository, the Agent Skills format, and the selected execution shape.

## Adaptation Checklist

Use the rows that affect runtime behavior, maintenance, or legal/attribution handling. Do not fill every row mechanically for trivial sources.

| Decision | Record |
|----------|--------|
| source intent | what behavior the source is trying to cause |
| local target | what the generated skill should cause in this repo or agent environment |
| fidelity boundary | what must stay equivalent to the source |
| local replacement | what should be rewritten to match local conventions |
| omitted material | what was not carried forward and why |
| provenance | source URL/path, version or commit when available, trust tier, confidence, and usage constraints |
| rights and attribution | license, notice, attribution, or excerpt limits that affect bundled files |

## Rewrite Rules

1. Do not copy the source's section structure unless that structure improves runtime behavior.
2. Convert narrative instructions into decisions, checklists, examples, or output contracts.
3. Replace source-specific tool names, paths, severity labels, or provider assumptions with local equivalents unless fidelity requires them.
4. Keep provenance, rights notes, source versions, and fidelity tradeoffs in `SOURCES.md`.
5. Keep only instructions that help the agent decide, do, or verify the task at runtime.
6. If preserving benchmark or comparison behavior, state the invariant criteria and avoid tuning to expected answers.

## Precision Check

Before authoring, answer:

1. Which existing local rule should replace a source rule?
2. Which source rule is too broad, stale, provider-specific, or non-runtime?
3. Which added instruction prevents a concrete mistake that existing guidance does not cover?
4. Which source detail belongs in `SOURCES.md`, `SPEC.md`, or a focused reference instead of `SKILL.md`?

If these answers are weak, tighten an existing file instead of adding new guidance.

```


### `references/source-discovery.md`

````markdown
# Source Discovery

Use this guide during synthesis when obvious docs are shallow, stale, incomplete, or too polished to reveal real behavior.

## Source Priority

Prefer sources in this order:

1. Local repository authority: `AGENTS.md`, `README.md`, `CONTRIBUTING.md`, manifests, validators, scripts, tests, and existing neighboring skills.
2. Primary upstream material: official specifications, product docs, API references, release notes, changelogs, and source code.
3. Operational evidence: issue threads, PR discussions, CI failures, incident notes, support patterns, and migration notes.
4. Historical evidence: commit logs, blame, reverted changes, and changelog diffs.
5. Secondary summaries: blog posts, tutorials, and community examples.

Treat secondary and generated content as leads, not authority.

## High-Signal Retrieval Passes

Run the passes that match the skill's risk:

- Core behavior: official docs, source exports, public interfaces, happy-path examples.
- Edge behavior: tests, fixtures, error handling, retries, permissions, validation, and cleanup paths.
- Negative behavior: bug fixes, reverted commits, issue reports, support threads, review comments, and skipped tests.
- Usage behavior: in-repo callers, downstream examples, configuration samples, and migration guides.
- Maintenance behavior: changelog entries, release notes, deprecations, and commits touching the same files repeatedly.

## Commit Log Mining

Use commit history when the task depends on lived behavior rather than only intended behavior.

Good candidates:

- Security, access-control, CI, deployment, or migration skills.
- Skills for internal systems with sparse public docs.
- Skills being improved after repeated failures.
- Areas with many regressions, reversions, or subtle edge cases.

Useful commands:

```bash
git log --oneline -- <path>
git log --stat -- <path>
git log -G '<behavior|symbol|error>' -- <path>
git blame <path>
```

Capture findings as source records with commit SHA, date, affected path, observed behavior, and whether the finding is adopted, rejected, or deferred.

Do not copy large commit messages or diffs into `SKILL.md`. Summarize the behavior and keep provenance in `SOURCES.md` or an evidence file.

## Stop Conditions

Stop collecting when:

- Required coverage dimensions are complete or have explicit next retrieval actions.
- New retrieval mostly repeats known facts.
- Remaining unknowns are low impact or require access the agent does not have.
- The source mix includes both intended behavior and observed behavior for high-risk workflows.

Record the stopping rationale in `SOURCES.md`.

````


### `references/spec-template.md`

````markdown
# SPEC.md Template

Use this guide to create or update a root-level `SPEC.md`.

## Use `SPEC.md` For

- intent
- scope
- trigger context
- evidence model
- validation expectations
- limitations
- maintenance rules

Do not put runtime instructions or full provenance tables here.

## Update `SPEC.md` When

- intent or scope changes
- trigger strategy changes
- evidence sources or storage policy changes
- reference architecture changes
- validation gates change
- privacy, security, or data-handling assumptions change

For tiny wording-only fixes, update `SOURCES.md` changelog instead.

## Relationship To Other Files

| File | Purpose |
|------|---------|
| `SKILL.md` | runtime activation and execution |
| `SPEC.md` | maintenance contract |
| `SOURCES.md` | source inventory, decisions, gaps, changelog |
| `references/` | runtime-loadable depth |
| `references/evidence/` | persistent iteration examples |

## Template

```markdown
# <Skill Name> Specification

## Intent

<1-2 short paragraphs>

## Scope

In scope:
- ...

Out of scope:
- ...

## Users And Trigger Context

- Primary users:
- Common user requests:
- Should not trigger for:

## Runtime Contract

- Required first actions:
- Required outputs:
- Non-negotiable constraints:
- Expected bundled files loaded at runtime:

## Source And Evidence Model

Authoritative sources:
- ...

Useful improvement sources:
- positive examples:
- negative examples:
- commit logs/changelogs:
- issue or PR feedback:
- validation results:

Data that must not be stored:
- secrets
- customer data
- private URLs or identifiers not needed for reproduction

## Reference Architecture

- `SKILL.md` contains:
- `references/` contains:
- `references/evidence/` contains:
- `scripts/` contains:
- `assets/` contains:

## Validation

- Lightweight validation:
- Deeper validation:
- Holdout examples:
- Acceptance gates:

## Known Limitations

- ...

## Maintenance Notes

- When to update `SKILL.md`:
- When to update `SOURCES.md`:
- When to update `references/evidence/`:
```

## Design Rules

1. Keep `SPEC.md` concise.
2. Link to `SOURCES.md` or refs instead of duplicating them.
3. Keep raw examples in `references/evidence/`.
4. Keep sensitive data redacted.

````


### `references/structure-troubleshooting.md`

```markdown
# Structure Troubleshooting

Load this when the skill layout is unclear, overloaded, or drifting away from focused routing.

## Over-long SKILL.md

Problem: `SKILL.md` exceeds 500 lines and becomes a second encyclopedia.

Fix: extract detailed material into focused `references/` files and keep `SKILL.md` as the router.

## Additive Drift

Problem: each update adds another rule, section, or reference without removing or tightening the old one.

Fix: run the precision pass before editing and again after skill artifacts change. Replace, narrow, move, or delete existing guidance before adding new guidance.

## Missing Trigger Keywords

Problem: the description is too vague to match user language.

Fix: include the phrases users actually say.

## Trigger Info In Body Instead Of Description

Problem: "when to use" guidance appears only in the body, after triggering has already happened.

Fix: move trigger language into `description`.

## Duplicating CLAUDE.md Or AGENTS.md

Problem: the skill repeats repo-wide conventions instead of adding net-new value.

Fix: reference existing project docs and keep the skill focused on domain-specific behavior.

## Unconditional Reference Loading

Problem: the skill tells the agent to read every reference up front.

Fix: add a decision table so references load only when needed.

## Large References Without Navigation

Problem: long reference files are hard to preview and easy to misuse.

Fix: add a table of contents or split by lookup need.

## Extraneous Files

Problem: the skill directory accumulates user-facing docs or miscellaneous notes that do not help runtime, validation, or maintenance.

Fix: keep only `SKILL.md`, `SPEC.md`, `SOURCES.md`, `references/`, `scripts/`, `assets/`, and `LICENSE` when needed.

## Scripts Without Documentation

Problem: `SKILL.md` names a script but does not document arguments, output, or fallback behavior.

Fix: document the script interface and expected output shape in `SKILL.md`.

## Hardcoded Paths

Problem: the skill embeds host-specific or repo-hardcoded paths.

Fix: use skill-root-relative paths or established portable placeholders.

## First/Second Person Descriptions

Problem: the description says "I can..." or "You can use this..."

Fix: write in third person so skill discovery stays consistent.

## Time-Sensitive Information

Problem: the skill bakes in dates or transitional logic that will quietly rot.

Fix: move legacy behavior into a clearly labeled deprecated section or remove it.

## Advanced Mechanics Without Justification

Problem: the skill uses routing, `context: fork`, or hooks because they seem sophisticated.

Fix: name the shape, explain why simpler shapes were rejected, and add portability/safety notes.

## Router Without Fallback

Problem: the skill has multiple downstream paths but no default route or clarification step.

Fix: add a fallback branch that asks one clarifying question or picks a documented safe default.

## Evaluator Loop Without Stop Condition

Problem: the skill says "iterate until good" with no rubric or cap.

Fix: add a rubric plus a max-loop or plateau rule.

## Passive Guidance In Forked Context

Problem: `context: fork` is used for conventions or reference material instead of a concrete delegated task.

Fix: keep passive guidance inline; use forked execution only for actionable isolated tasks.

## Hook-Backed Enforcement Without Safety Notes

Problem: the skill uses hooks but does not explain event scope, fallback behavior, or shell risk.

Fix: add hook event scope, fallback path, and explicit security notes.

## Hidden Reference File

Problem: a bundled reference exists, but `SKILL.md` never tells the agent when to open it.

Fix: add the file to the main router with a one-line "open when..." reason, or remove/split the file if no clear reason exists.

## Generic Bucket Reference

Problem: a file groups unrelated techniques under a vague name such as "patterns", "notes", or "context".

Fix: split the file by lookup need and rename each leaf so the filename predicts why it should be opened.

```


### `references/synthesis-path.md`

```markdown
# Synthesis Path

Use this path when creating or materially changing a skill.

## Output Style

- Keep synthesis notes terse.
- Prefer tables, status lists, and gap lists over narrative summaries.
- Record decisions as `adopted`, `rejected`, or `deferred`.

## Step 0: Classify

Record the parts that affect the skill's behavior or maintenance:

1. skill class
2. primary execution shape
3. secondary shapes, if any
4. why simpler shapes were not enough

For `integration-documentation`, cover:

1. API surface and behavior contracts
2. config/runtime options
3. downstream use cases
4. issues/failure modes with workarounds
5. version or migration variance

## Step 1: Collect Sources

Collect from:

1. Agent Skills spec and best practices
2. similar in-repo skills
3. upstream implementations and orchestration docs
4. domain or library docs
5. repo conventions and validators
6. tests, fixtures, changelogs, and issue or PR history
7. commit history and blame for regressions or edge cases
8. prior `SPEC.md`, `SOURCES.md`, and `references/evidence/`

If the shape uses provider-specific mechanics, include current provider docs.

## Step 1.2: Adapt Source Material When Needed

Read `references/source-adaptation.md` when the primary input is an upstream prompt, workflow, rubric, benchmark, guide, or docs set.

Record:

1. source intent
2. local target behavior
3. fidelity boundary
4. local replacements
5. omitted material
6. license, notice, attribution, or excerpt constraints

## Baseline Source Pack For Skill-Authoring

Require at minimum:

1. local `skill-writer` runtime files
2. Agent Skills spec and repo conventions
3. provider docs for any provider-specific mechanic being recommended

## Step 1.5: Load Example Profiles

Load only the flat example profile files you need from the reference index in `SKILL.md`.

## Step 1.6: Expand Coverage

Run targeted passes for:

| Pass | Retrieve |
|------|----------|
| core behavior | happy path and main workflow |
| edge behavior | failures, retries, permissions, cleanup |
| negative behavior | false positives, reviewer concerns, bad outputs |
| repair patterns | fixes and corrected outputs |
| version variance | platform or release differences |
| shape mechanics | routing, delegation, loop stops, hook constraints |

Extra retrieval for advanced shapes:

1. route or delegation criteria
2. worker or handoff contracts
3. loop stopping rules
4. provider-specific lifecycle or security constraints

## Step 2: Capture Provenance

For each source, record:

- source URL or path
- trust tier
- confidence
- contribution
- usage constraints

Store provenance in `SOURCES.md`, not long runtime prose.

## Step 3: Synthesize Decisions

Map each major decision to source evidence, including:

- class choice
- shape choice
- provider-specific mechanics
- deferred gaps

## Step 4: Check Synthesis Completeness

Address these before authoring, or report the unresolved item as an explicit gap:

1. no missing high-impact coverage dimensions
2. partial dimensions have explicit next retrieval actions
3. authoring or generator skills include transformed examples
4. selected profile requirements are satisfied
5. coverage passes are reflected in the coverage matrix
6. stopping rationale is explicit
7. supporting refs stay focused and directly discoverable from `SKILL.md`
8. `SPEC.md` exists or is updated when the contract changed
9. advanced mechanics include required contracts and justification
10. provider-specific mechanics include portability notes

## Required Output

- synthesis summary
- source inventory in `SOURCES.md`
- decisions and rationale
- coverage matrix
- gaps and next retrieval actions
- selected class and shape
- source-adaptation notes when an upstream source materially shapes the skill
- `SPEC.md` update summary when applicable

```


### `references/workflow-orchestrator-workers.md`

````markdown
# Orchestrator-Workers

Use this workflow when the subtasks are not known ahead of time and must be discovered from the input.

## Choose this workflow when

- the orchestrator must discover work units dynamically
- each unit can be delegated to a stable worker contract
- a final synthesis step can merge the results

## Required contract

1. Worker-task schema.
2. Worker output schema.
3. Expansion limit or stopping rule.
4. Final synthesis rule.

## Example

```markdown
1. Inspect the request and identify work units dynamically
2. Assign each work unit to a worker path
3. Collect worker summaries in a fixed schema
4. Synthesize the result
```

````


### `references/workflow-parallel.md`

```markdown
# Parallel Workflows

Use this workflow when independent subtasks can run side-by-side, or when multiple judgments improve confidence.

## Choose this workflow when

- work units are independent
- latency or coverage improves with parallel execution
- aggregation can be described clearly

## Common forms

1. `sectioning`: split a task into independent work units.
2. `voting`: run multiple judgments and aggregate them.

## Required contract

1. Unit of parallel work.
2. Merge or vote rule.
3. Conflict handling.
4. Cost or latency cap.

```


### `references/workflow-plan-validate-execute.md`

````markdown
# Plan-Validate-Execute

Use this workflow when a destructive or high-stakes action should be preceded by a machine-checkable plan.

## Choose this workflow when

- validating the plan is safer than validating the final action
- the task changes many files or records
- rollback would be expensive

## Required contract

1. The plan artifact and schema.
2. The validation step and source of truth.
3. Rework rules when validation fails.
4. Final execution and verification steps.

## Example

```markdown
1. Analyze the input and generate `changes.json`
2. Validate the plan against source of truth
3. Revise until validation passes
4. Execute the plan
5. Verify the result
```

````


### `references/workflow-prompt-chaining.md`

````markdown
# Prompt Chaining

Use this workflow when the task should move through fixed ordered steps and each step makes the next one easier.

## Choose this workflow when

- the decomposition is known in advance
- step order matters
- validation between steps improves quality

## Required contract

1. Step order.
2. Inputs and outputs for each step.
3. Validation or gate points between steps.

## Example

```markdown
1. Summarize the current state
2. Propose the target state
3. Validate the proposal against constraints
4. Write the final document
```

````


### `references/workflow-routing.md`

````markdown
# Routing Workflows

Use this workflow when the incoming request must be classified and sent to different downstream prompts, references, scripts, or tools.

## Choose this workflow when

- distinct request classes benefit from specialized downstream handling
- one broad prompt would create conflicts or false positives
- misroutes can be detected and recovered

## Required contract

1. Route-selection criteria.
2. Default route or clarification fallback.
3. Misroute recovery.
4. Downstream contract for each route.

## Example

```markdown
1. Classify the request:

   **Billing question?** -> Load `references/billing.md`
   **Refund request?** -> Run `scripts/refund_intake.py`
   **Technical bug?** -> Load `references/triage.md`

2. If classification is uncertain, ask one clarification question before continuing.
```

````


### `references/workflow-validation-loops.md`

````markdown
# Validation Loops

Use this workflow when a validator can reliably catch mistakes before the skill should claim completion.

## Choose this workflow when

- a script, schema, test, or parser can catch important failures
- the agent should fix issues immediately after each change
- the main risk is silent drift or invalid output

## Required contract

1. The validator or check to run.
2. When it runs in the workflow.
3. What to fix before retrying.
4. What counts as a passing state.

## Example

```markdown
1. Make the change
2. Validate immediately
3. If validation fails, fix the issue
4. Re-run validation
5. Only proceed when validation passes
```

````


### `scripts/quick_validate.py`

```
# /// script
# requires-python = ">=3.12"
# dependencies = ["pyyaml"]
# ///
"""
Quick structural validation for Agent Skills.

Validates that SKILL.md exists, has valid frontmatter, declares the required
fields, and references bundled files that exist. Size checks are advisory
warnings.

Usage:
    uv run quick_validate.py <skill_directory>

Returns exit code 0 on success, 1 on failure. Outputs JSON with validation
results.
"""

import argparse
import json
import re
import sys
from pathlib import Path

import yaml

MAX_SKILL_CHARS = 20000

LOCAL_FILE_REFERENCE_RE = re.compile(
    r"(?<![A-Za-z0-9_./-])"
    r"((?:references|scripts|assets)/[A-Za-z0-9][A-Za-z0-9._/-]*\.[A-Za-z0-9]+|"
    r"(?:SPEC|SOURCES)\.md)"
    r"(?![A-Za-z0-9_./-])"
)


def parse_args(argv: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Validate the structural requirements for an agent skill.",
    )
    parser.add_argument("skill_directory")
    return parser.parse_args(argv)


def find_local_file_references(text: str) -> list[str]:
    refs: list[str] = []
    for match in LOCAL_FILE_REFERENCE_RE.finditer(text):
        ref = match.group(1)
        if ref not in refs:
            refs.append(ref)
    return refs


def validate_local_file_references(
    skill_path: Path,
    skill_content: str,
    errors: list[str],
) -> None:
    for rel_path in find_local_file_references(skill_content):
        target = skill_path / rel_path
        if not target.exists():
            errors.append(f"Referenced file not found: {rel_path}")
        elif not target.is_file():
            errors.append(f"Referenced path is not a file: {rel_path}")


def validate_skill(
    skill_path: Path,
) -> tuple[bool, list[str], list[str]]:
    """Validate a skill directory. Returns (valid, errors, warnings)."""
    errors: list[str] = []
    warnings: list[str] = []

    skill_md = skill_path / "SKILL.md"
    if not skill_md.exists():
        return False, ["SKILL.md not found"], []

    content = skill_md.read_text()

    if not content.startswith("---"):
        errors.append("No YAML frontmatter found (file must start with ---)")
        return False, errors, warnings

    match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
    if not match:
        errors.append("Invalid frontmatter format (missing closing ---)")
        return False, errors, warnings

    frontmatter_text = match.group(1)
    try:
        frontmatter = yaml.safe_load(frontmatter_text)
        if not isinstance(frontmatter, dict):
            errors.append("Frontmatter must be a YAML mapping")
            return False, errors, warnings
    except yaml.YAMLError as exc:
        errors.append(f"Invalid YAML in frontmatter: {exc}")
        return False, errors, warnings

    invalid_keys = [key for key in frontmatter.keys() if not isinstance(key, str) or not key.strip()]
    if invalid_keys:
        errors.append("Frontmatter keys must be non-empty strings")

    if "name" not in frontmatter:
        errors.append("Missing required field: name")
    else:
        name = frontmatter["name"]
        if not isinstance(name, str):
            errors.append(f"name must be a string, got {type(name).__name__}")
        else:
            name = name.strip()
            if not name:
                errors.append("name must not be empty")
            elif name != skill_path.name:
                errors.append(f"name '{name}' does not match directory name '{skill_path.name}'")

    if "description" not in frontmatter:
        errors.append("Missing required field: description")
    else:
        description = frontmatter["description"]
        if not isinstance(description, str):
            errors.append(f"description must be a string, got {type(description).__name__}")
        elif not description.strip():
            errors.append("description must not be empty")

    if len(content) > MAX_SKILL_CHARS:
        warnings.append(
            f"SKILL.md is {len(content)} characters (recommended max {MAX_SKILL_CHARS}). "
            "Consider moving optional detail to references/."
        )

    validate_local_file_references(skill_path, content, errors)

    return len(errors) == 0, errors, warnings


def main() -> None:
    args = parse_args(sys.argv[1:])
    skill_path = Path(args.skill_directory).resolve()
    if not skill_path.is_dir():
        print(json.dumps({"valid": False, "errors": [f"Not a directory: {skill_path}"]}))
        sys.exit(1)

    valid, errors, warnings = validate_skill(skill_path)
    result = {
        "valid": valid,
        "errors": errors,
        "warnings": warnings,
    }
    print(json.dumps(result, indent=2))
    sys.exit(0 if valid else 1)


if __name__ == "__main__":
    main()

```


### `SOURCES.md`

```markdown
# Sources

This file tracks source material synthesized into `skill-writer`, plus iterative changes over time.

## Current source inventory

| Source | Type | Trust tier | Retrieved | Confidence | Contribution | Usage constraints | Notes |
|---|---|---|---|---|---|---|---|
| `SKILL.md` | local canonical | canonical | 2026-05-01 | high | Baseline orchestration, path model, and runtime contract | local active skill root | Primary source of current behavior |
| `references/*.md` | local canonical | canonical | 2026-05-05 | high | Detailed path guidance, examples, routed leaf references, and validation requirements | local active skill root | Flat runtime reference files listed directly from `SKILL.md` |
| `SPEC.md` | local canonical | canonical | 2026-05-05 | high | Canonical maintenance contract for intent, scope, evidence model, validation, and limitations | local active skill root | Updated to treat `skill-writer` as a meta-router |
| `https://agentskills.io/specification` | external canonical spec | canonical | 2026-05-01 | high | Portable skill structure, frontmatter, progressive disclosure, optional directories, and file-reference rules | spec-level constraints take precedence over local preferences | Cross-agent compatibility baseline |
| `https://agentskills.io/skill-creation/best-practices` | external official docs | canonical | 2026-05-01 | high | Coherent unit design, moderate detail, progressive disclosure, defaults over menus, validation loops, plan-validate-execute | skill-authoring guidance, not provider-specific runtime semantics | Informed shape-selection and workflow guidance |
| `https://agentskills.io/skill-creation/using-scripts` | external official docs | canonical | 2026-05-01 | high | Script bundling, non-interactive requirements, `--help`, structured output, and safe script interfaces | script examples are illustrative, adapt to local tooling | Informed script-backed workflow requirements |
| `https://code.claude.com/docs/en/skills` | external official docs | canonical | 2026-05-01 | high | Current Claude Code skill lifecycle, frontmatter fields, argument features, `context: fork`, `allowed-tools`, and hooks-in-skills support | provider-specific; do not generalize to portable Agent Skills behavior | Replaced stale local assumptions about Claude-specific fields |
| `https://code.claude.com/docs/en/sub-agents` | external official docs | canonical | 2026-05-01 | high | Automatic delegation, focused subagents, explicit invocation modes, and subagent lifecycle integration | provider-specific | Informed `subagent-fork` shape guidance |
| `https://code.claude.com/docs/en/hooks` | external official docs | canonical | 2026-05-01 | high | Hook lifecycle, hooks in skills and agents, async constraints, and security requirements | provider-specific and security-sensitive | Informed `hook-backed` shape guidance and safety notes |
| `https://www.anthropic.com/engineering/building-effective-agents` | external official engineering guidance | canonical | 2026-05-01 | high | Simplicity-first design and workflow taxonomy such as prompt chaining, routing, parallelization, and orchestrator-workers | conceptual guidance; adapt to skill authoring rather than full app orchestration | Core source for execution-shape taxonomy |
| `https://developers.openai.com/api/docs/guides/reasoning-best-practices` | external official docs | canonical | 2026-05-01 | high | Planner/doer distinction, reasoning-vs-GPT model tradeoffs, and avoiding explicit chain-of-thought prompting | provider-specific model guidance; use only as general orchestration input unless exact product syntax matters | Informed reasoning-model notes |
| `https://openai.com/business/guides-and-resources/a-practical-guide-to-building-ai-agents/` | external official guidance | canonical | 2026-05-01 | high | Maximize a single agent first, use multi-agent only when needed, manager-vs-handoff split, layered guardrails | product-level guidance, not a skills standard | Informed simplicity rule and advanced-shape escalation criteria |
| `https://openai.github.io/openai-agents-python/agents/` | external official SDK docs | canonical | 2026-05-01 | medium | Manager-vs-handoff distinction and structured-output support | SDK-specific implementation details | Informed router/orchestrator language and contract expectations |
| `https://openai.github.io/openai-agents-python/handoffs/` | external official SDK docs | canonical | 2026-05-01 | medium | Handoff metadata, input filters, and receiving-agent history control | SDK-specific implementation details | Informed route/handoff contract guidance |
| `https://huggingface.co/docs/hub/model-cards` | external documentation pattern | secondary | 2026-04-26 | high | Model-card sections for intended use, data, limitations, and reproducibility | adapted as documentation prior art, not a skill standard | Inspired `SPEC.md` maintenance contract shape |
| `https://huggingface.co/docs/hub/en/model-card-annotated` | external documentation pattern | secondary | 2026-04-26 | high | Annotated intended-use, out-of-scope, risks, and limitations sections | adapted as documentation prior art, not a skill standard | Informed SPEC scope and limitations sections |
| `https://cacm.acm.org/research/datasheets-for-datasets/` | research/documentation pattern | secondary | 2026-04-26 | high | Data provenance, collection, composition, intended use, and maintenance transparency | adapted from dataset documentation to skill evidence documentation | Informed source/evidence model and privacy rules |
| `https://diataxis.fr/` | documentation framework | secondary | 2026-04-26 | high | User-need-centered documentation types: tutorial, how-to, reference, explanation | adapted as information architecture prior art, not a skill standard | Informed reference files as lookup needs rather than topic buckets |
| `https://dita-lang.org/` | documentation standard | secondary | 2026-04-26 | high | Topic-oriented technical content patterns: task, concept, reference, troubleshooting | adapted as documentation architecture prior art | Informed reference type table and troubleshooting matrix guidance |
| `https://www.writethedocs.org/guide/writing/docs-principles/` | documentation guidance | secondary | 2026-04-26 | medium | Documentation should be structured for findability, reuse, and user participation | general writing guidance | Cross-check for reference architecture usability |
| `AGENTS.md` | repo convention | canonical | 2026-05-01 | high | Repository-specific workflow requirements and registration checklist | repository-local policy | Registration + validator expectations |
| `README.md` | repo convention | canonical | 2026-05-01 | high | Skill table format and authoring conventions | repository-local policy | Registration and discoverability source |

## Decisions

1. `skill-writer` is a meta-router: it must choose both a skill class and an execution shape before authoring.
2. Default to the simplest adequate shape. Advanced mechanics require evidence and an explicit reason simpler shapes were rejected.
3. Skill class and execution shape are independent axes. Class drives coverage requirements; shape drives runtime mechanics and artifact layout.
4. `SKILL.md` remains the orchestration/index layer; references, scripts, assets, hooks, and subagents are leaves selected by that router.
5. Provider-specific Claude Code features are valuable but not default. Use them only when justified and record portability implications.
6. Claude-specific frontmatter guidance should track the current `code.claude.com/docs/en/skills` fields, including `when_to_use`, `arguments`, `effort`, `paths`, `shell`, `context`, `agent`, and `hooks`.
7. Router, parallel/orchestrator, subagent-fork, and hook-backed shapes each require explicit contracts, not just prose.
8. Hooks are deterministic enforcement and need narrow scope plus security notes because command hooks run with full user permissions.
9. Multi-agent guidance should distinguish manager/orchestrator, handoff, and isolated subagent execution instead of collapsing them into one pattern.
10. Reasoning-model guidance is a design option, not a universal default: planner/doer splits are useful when complexity warrants them.
11. Architectural choices are reviewed qualitatively during authoring, not inferred by validator heuristics.
12. Reference files remain split by lookup need rather than topic buckets, even as the set of supported shapes expands.
13. Runtime references stay flat under `references/`; related leaves use filename prefixes, and every bundled reference is directly discoverable from `SKILL.md`.
14. The validator should enforce durable structural guarantees and required fields, but should not hardcode name style, path-portability scans, skill classes, source-coverage schemas, SPEC headings, trigger-quality heuristics, or provider-specific optional frontmatter keys.
15. `skill-writer` should default to dense structures such as tables, checklists, templates, and I/O examples, and should cut explanatory prose unless it prevents a concrete mistake.
16. `SKILL.md` should stay a thin router; repeated policy belongs in routed references rather than always-loaded step prose.
17. Validation stays lightweight and structural; qualitative precision remains an authoring judgment.
18. Missing referenced bundled files are structural failures because they break runtime loading.

## Coverage matrix

| Dimension | Coverage status | Evidence |
|---|---|---|
| SKILL.md vs references placement | complete | Agent Skills spec, local reference architecture |
| Reference splitting heuristics | complete | Agent Skills best practices, Diataxis, DITA, local reference architecture and artifact-layout guidance |
| Long reference navigation | complete | local design principles |
| Source discovery beyond docs | complete | local synthesis coverage checks, repository history practices |
| Commit log as source material | complete | local source-discovery guidance |
| Positive/negative evidence storage | complete | local iteration path, prior validation guidance |
| Skill maintenance specification | complete | model cards, datasheets, local `SPEC.md` reference implementation |
| Shape-selection framework | complete | Anthropic effective agents, OpenAI practical guide, local execution-shapes guidance |
| Router/orchestrator patterns | complete | Anthropic effective agents, OpenAI agent guides, local workflow-mechanics guidance |
| Current Claude skill frontmatter and lifecycle mechanics | complete | Claude Code skills docs |
| Subagent-fork guidance | complete | Claude Code skills docs, subagents docs |
| Hook-backed guidance and security constraints | complete | Claude Code hooks docs |
| Script-backed workflow design | complete | Agent Skills using scripts guide |
| Planner/doer reasoning guidance | complete | OpenAI reasoning best practices |
| Lookup-oriented reference architecture | complete | Diataxis user needs, DITA topic types, local reference architecture |
| Flat reference routing | complete | local reference architecture, user feedback on generator simplicity |

## Open gaps

1. Advanced-shape contracts still rely on author judgment and review rather than deterministic validation.
2. This repository still has few real shipped examples using `hooks`, `context: fork`, `when_to_use`, `arguments`, `paths`, or `effort`.
3. Public repo docs outside `skill-writer` may need follow-up updates to fully reflect the current Claude-specific skill fields.

## Changelog

- 2026-03-05: Initialized `SOURCES.md` with baseline source pack (local canonical, Codex upstream, Claude upstream, spec, and repo conventions).
- 2026-03-19: Clarified path-resolution guidance so bundled skill references stay skill-root-relative while registration steps are resolved from the repository's active layout.
- 2026-03-19: Made portability a default authoring rule and emphasized avoiding host-specific absolute filesystem paths.
- 2026-04-19: Updated path guidance to preserve repository-standard root variables such as `${CLAUDE_SKILL_ROOT}` instead of banning them outright.
- 2026-05-09: Replaced `${CLAUDE_SKILL_ROOT}` guidance with skill-root-relative paths. Environment variable path prefixes cause permission friction and runtime failures in Claude Code.
- 2026-04-19: Restored `.agents/skills` as the default authoring target and kept repository-specific layouts as an inspected override rather than the default.
- 2026-04-19: Added explicit prior-art inspection and user-confirmation guidance when the correct skill root is unclear.
- 2026-04-26: Added reference architecture, source discovery, and iteration evidence guidance; updated synthesis, authoring, and iteration paths to prevent overloaded `SKILL.md` and catch-all reference files.
- 2026-04-26: Added `SPEC.md` as the canonical `skill-writer` maintenance specification and added `references/spec-template.md` for future skills.
- 2026-04-26: Removed fixed integration reference filename validation and added length-based reference warnings.
- 2026-04-26: Reworked reference architecture around concrete lookup needs instead of generic topic buckets.
- 2026-05-01: Reworked `skill-writer` around explicit execution-shape routing, added shape-specific example profiles, refreshed Claude Code provider mechanics from current official docs, and added source guidance for routing, delegation, and hooks.
- 2026-05-01: Replaced generic pattern bucket references with routed leaf files and made `SKILL.md` enumerate every bundled reference file with a direct open-when reason.
- 2026-05-01: Removed the validator's hardcoded optional frontmatter allowlist so provider-specific field drift does not create noisy false warnings.
- 2026-05-01: Reduced prose-heavy guidance in `skill-writer`, rewrote the main runtime refs into denser tables/checklists, and made compact runtime guidance an explicit contract.
- 2026-05-01: Thinned `SKILL.md` back toward a true router and removed duplicated execution-shape detail from `mode-selection.md`.
- 2026-05-05: Flattened runtime reference files under `references/`, kept `SKILL.md` as the complete material index, removed unused runbooks, added source-adaptation guidance, and made precision passes part of every skill create/update flow while keeping validation lightweight.
- 2026-05-05: Removed validator skill-class inference, integration coverage parsing, SPEC heading checks, SOURCES schema checks, and description-style heuristics.
- 2026-05-05: Removed validator name-style checks and machine-specific path scanning; kept only format, required fields, directory-name match, referenced-file existence, and a high-threshold size warning.

```


### `SPEC.md`

```markdown
# Skill Writer Specification

## Intent

`skill-writer` is the canonical workflow for creating, updating, synthesizing, and iteratively improving agent skills in this repository.

Its primary purpose is to prevent shallow skill authoring by forcing high-value source coverage, explicit provenance, focused runtime instructions, and validation before completion.
It is also a meta-router: before authoring, it must choose the simplest adequate execution shape for the target skill and only then decide which artifacts are needed.

## Scope

In scope:

- New skill creation from local, external, or mixed sources.
- Existing skill updates that affect runtime behavior, structure, trigger precision, references, or validation.
- Research-first synthesis for proposed skills.
- Iteration from positive examples, negative examples, review feedback, validation results, and observed agent behavior.
- Registration and validation for this repository's canonical `skills/<skill-name>/` layout and other discovered layouts.
- Choosing between execution shapes such as inline guidance, reference-backed expert, script-backed workflow, router, subagent-fork, hook-backed, asset-template, or hybrids.
- Assessing when provider-specific mechanics are justified and documenting portability constraints.

Out of scope:

- Acting as the runtime instructions for the skills it creates.
- Storing full source inventories, raw examples, or changelog history directly in `SKILL.md`.
- Replacing repository-level instructions in `AGENTS.md`, `README.md`, or `CONTRIBUTING.md`.
- Creating per-skill aliases or symlink skills in this repository.
- Guaranteeing compatibility with provider-specific skill extensions unless they are explicitly scoped and documented.

## Users And Trigger Context

- Primary users: agents and humans authoring or maintaining reusable agent skills.
- Common user requests: "create a skill", "write a skill", "update this skill", "improve from examples", "synthesize a skill from docs", "maintain skill docs", or "validate/register this skill".
- Should not trigger for: ordinary code review, generic documentation edits, PR writing, commit creation, or implementation work that does not create or modify an agent skill.

## Runtime Contract

- Required first actions:
  - Resolve the target skill root and operation.
  - Inspect local repository conventions before deciding where files belong.
  - Classify the skill and select the minimum required workflow paths.
  - Select a primary execution shape and default to the simplest adequate option.
  - Keep validation lightweight and structural unless project conventions require more.
- Required outputs:
  - Summary.
  - Changes Made.
  - Validation Results.
  - Open Gaps.
- Non-negotiable constraints:
  - `SKILL.md` frontmatter is first line and `name` matches the directory.
  - `description` contains realistic trigger language.
  - `SKILL.md` remains an orchestration/index layer for complex skills.
  - Runtime guidance should prefer dense structures such as tables, checklists, templates, and examples over explanatory prose.
  - Material skill changes explicitly name the selected execution shape.
  - Advanced mechanics are justified and include portability notes.
  - Supporting runtime references are focused, flat under `references/`, listed in `SKILL.md`, and loaded conditionally.
  - Source provenance and decisions live in `SOURCES.md`.
  - Durable positive/negative examples live in `references/evidence/`.
  - `SPEC.md` records the maintenance contract for new or materially changed skills.
  - Lightweight structural validation runs before completion.
  - A post-change precision pass runs after any skill artifact change.
- Expected bundled files loaded at runtime:
  - `references/mode-selection.md`
  - `references/execution-shapes.md`
  - `references/synthesis-path.md`
  - `references/iteration-path.md`
  - `references/authoring-path.md`
  - `references/reference-architecture.md`
  - `references/spec-template.md`
  - `references/description-optimization.md`
  - `references/registration-validation.md`
  - `references/source-adaptation.md`
  - flat `references/*.md` files listed in `SKILL.md`
  - `scripts/quick_validate.py`

## Source And Evidence Model

Authoritative sources:

- Local `skill-writer` runtime files: `SKILL.md`, `references/**/*.md`, `scripts/quick_validate.py`.
- Repository policy: `AGENTS.md`, `README.md`, `CONTRIBUTING.md`, plugin manifests, and registration settings.
- Agent Skills specification and official skill authoring guidance.
- Current official provider docs for any provider-specific mechanics being recommended.
- Official orchestration guidance for routing, delegation, and reasoning-model planning patterns.

Useful improvement sources:

- positive examples: successful generated skills, review-approved skill changes, and validation passes that demonstrate desired behavior
- negative examples: shallow generated skills, overloaded `SKILL.md` files, catch-all references, missing provenance, failed validation, false triggers, or review feedback
- commit logs/changelogs: repeated fixes, reversions, migrations, and changes that explain why a rule exists
- issue or PR feedback: reviewer comments about missing coverage, confusing trigger language, poor file placement, or insufficient validation
- validation results: structural checks, review findings, and observed behavior from real skill use

Data that must not be stored:

- secrets, credentials, or tokens
- raw customer data
- private URLs or identifiers that are not needed for reproduction
- large copied source documents or long copyrighted excerpts
- unredacted personal data from examples, logs, issues, or commits

## Reference Architecture

- `SKILL.md` contains the top-level workflow, path-loading table, branch points, universal constraints, and output contract.
- `SKILL.md` acts as a meta-router for the authoring process: class selection, shape selection, and path selection happen before writing.
- `SPEC.md` contains this maintenance specification.
- `SOURCES.md` contains source inventory, decisions, coverage matrix, open gaps, and changelog.
- `references/` contains focused flat workflow guidance, routed leaf references, templates, rubrics, and class-specific authoring requirements.
- Runtime references should be direct children of `references/`; use filename prefixes for related leaves and list every bundled reference directly from `SKILL.md`.
- `references/evidence/` contains durable positive/negative examples when future iterations need them.
- `scripts/` contains validation automation.
- `assets/` is unused unless a future skill-authoring workflow needs static templates or media.

## Validation

- Lightweight validation:
  - Run `uv run skills/skill-writer/scripts/quick_validate.py skills/skill-writer`.
  - Inspect changed references for focused scope, direct discoverability, and absence of host-specific paths.
  - Verify that the selected execution shape is explicit and that advanced mechanics, if any, are justified.
  - Run the post-change precision pass and summarize what was replaced, narrowed, moved, deleted, or added with reason.
- Holdout examples:
  - Keep durable holdout examples in `references/evidence/holdout-set.md` when repeated regressions appear.
  - Do not tune directly against holdout examples until they are intentionally moved to the working set.
- Acceptance gates:
  - Validator passes with no errors.
  - New or changed workflow rules are represented in the correct artifact.
  - `SOURCES.md` records source-backed decisions and any remaining gaps.
  - `SPEC.md` is updated when intent, scope, evidence model, validation, or maintenance expectations change.

## Known Limitations

- The validator checks only structural requirements and a high-threshold advisory size warning; it cannot prove that a generated skill is semantically complete.
- The validator intentionally does not classify skills, parse source coverage, enforce SPEC headings, judge trigger quality, or exhaustively validate provider-specific optional frontmatter fields.
- Prose density, source adaptation quality, advanced-shape contracts, and precision rely on authoring judgment and review.
- Source discovery can still miss private operational knowledge if it is not present in local files, accessible issue/PR history, or supplied context.
- Provider-specific skill extensions may drift; `skill-writer` treats them as compatibility guidance unless a skill is intentionally provider-specific.

## Maintenance Notes

- Update `SKILL.md` when the required runtime workflow, branch conditions, or output contract changes.
- Update `references/execution-shapes.md` when new skill mechanics or orchestration patterns become important.
- Update the relevant flat file under `references/` when a specific routed leaf changes.
- Update `SPEC.md` when intent, scope, user/trigger context, evidence model, validation expectations, limitations, or maintenance rules change.
- Update `SOURCES.md` when source inventory, decisions, coverage, gaps, or changelog entries change.
- Update `references/evidence/` when preserving examples for future iteration or regression tracking.

```
