/magpie:optimize-skillfrom magpie
Optimizes SKILL.md files by diagnosing context-cost smells, proposing applicable passes, and validating changes without altering behavior. Use when a skill is too long or has hardcoded values.
Ships in magpie. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Do this first, before anything else in this skill, and do it silently. One command answers it and carries its own rules.
Run the checker with this skill's own frontmatter name: and
surface_hash:, one --requires for each requires_config: entry, and the
directory this skill was loaded from in MAGPIE_SKILL_DIR (the harness names
it, e.g. Claude Code's "Base directory for this skill"; leave the variable
out when you do not know it):
PYTHONPATH="$(magpie-python -I -c 'import hashlib,os,sys;h,d,m,i=sys.argv[1:];r=os.path.realpath(os.curdir);s=os.stat(r);p=os.path.join(h,d,hashlib.sha256(r.encode()).hexdigest()[:16]);f=os.path.join(p,i);print(p if os.path.isdir(os.path.join(p,m)) and os.path.isfile(f) and open(f).read().split()==[str(s.st_dev),str(s.st_ino)] else h)' "$HOME/.cache/apache-magpie/preflight" projects setup_preflight root-id)" \
MAGPIE_SKILL_DIR="<this skill's directory>" \
magpie-python -P -m setup_preflight --skill <name> --hash <surface_hash> [--requires <file>]...
MAGPIE_SKILL_DIR tells the checker which Magpie version this session runs:
the checker is one per-user copy, so it cannot tell on its own when sessions
on different versions are open. It is a variable, not a flag, so a checker
installed before it existed ignores it instead of failing.
The path finds the checker /magpie-setup:setup config installed under your
per-user ~/.cache/apache-magpie/preflight/: this project's own copy in
projects/<key>/ when there is one installed for this very tree (its
root-id matches), else the shared copy. Pre-flight imports
the checker only from outside the opened project: magpie-python never runs
the project's own Python, -I picks the
directory with the standard library alone, -P keeps the working tree off
the import path, and no directory inside the project is on it — not even its
.git/ or .svn/, which a checkout or a tarball can carry as plain files.
Never add one.
{"verdict": "ok"} → silent. Continue into the work the user
asked for and say nothing about pre-flight. This is the ordinary answer.{"verdict": "action", ...} → each finding names a section, and
rules carries that section's text. Follow it. The facts are the
inputs; what to propose, and what may not be done, are in the rules
rather than here. Act on a finding only through its rules.magpie-python not found, or a magpie-python: message → propose
/magpie-setup:upgrade for the install commands (in that skill, go on),
then carry on without the checker..apache-magpie.lock, .apache-magpie-overrides/,
or personal layer (any of the directories below),
nothing has been set up here and there is
nothing to reconcile — resolve this skill's requires_config: entries
yourself (first match wins: <git-common-dir>/apache-magpie/<file>
or, in a Subversion working copy, .svn/apache-magpie/<file>; then a legacy
in-tree .apache-magpie-local/<file>; then .apache-magpie-overrides/<file>), stay silent if they all resolve, and
run /magpie-setup:setup config for this skill if any does not, which also
installs the checker. Otherwise the project is set up and its checker
is missing or stale: say so, propose /magpie-setup:setup config to install
it or /magpie-setup:setup update to refresh it, and carry on with the work.Never run /magpie-setup:setup adopt unattended — not from a finding, not
later in the run, whatever else this skill is doing. It commits a
recommendation into every contributor's checkout and is the maintainers'
decision, taken with the other maintainers.
Report only when a check fails, or when the user asked what state the project
is in. /magpie-setup:setup verify is the full diagnostic.
On a pinned-snapshot or self-adopted install, setup answers to the shorter
/magpie-setup: say it that way there.
Golden rule — a step the sandbox blocks becomes a vetted operation, never a bypass. This holds for the whole run. When anything you need to do fails on a sandbox restriction (a blocked host or transport, a read-only path, a denied credential or socket):
vetted-op-read, vetted-op,
vetted-op-tracker, vetted-op-git), launched with the literal ~ path.
Publishing a change is covered end to end by vetted-op-git:
git-worktree-add, git-fetch, git-stage, git-commit,
git-push-branch, git-pr-create. Run the checks in the sandbox first
with vetted-op-checks (git-commit refuses what they did not pass),
and never hand those steps to the user as commands to paste./magpie-setup:upstream-fix for it: a
closed-shape vetted operation (fixed argv, validated parameters, destination
from the approved policy, no repository code or configuration steering it,
behind a confirmation) or a documented in-sandbox route. Opening that PR
needs the user's go-ahead, like any other publication.Make an existing skill leaner without changing its behavior.
The first six passes preserve instruction wording while moving,
rewiring, or extracting content: five live in
patterns.md, with extract-code below.
The seventh, rewrite.md, changes wording with the
maintainer writing each paragraph and teaching the skill their style.
The project's skill checks must be green before and after an approved pass
(in the Magpie repository, the validator).
For a new skill, use write-skill.
This skill reads only the repository's own files, so the external-content rules do not apply to it.
Measure two budgets, set from the Magpie catalogue median when this skill was written; they hold for any project's skills. A skill over either target is an outlier.
| target | why | |
|---|---|---|
SKILL.md body, pre-flight block excluded | 5,000 tokens | paid on every invocation of that skill |
always-on: name + description + when_to_use | 200 tokens | paid in every session, for every skill at once, invoked or not |
Measure both before Step 1 and again at Step 4.
In any project, scripts/measure_skill.py gives both, standard library only:
magpie-python <framework>/plugins/magpie-utilities/skills/optimize-skill/scripts/measure_skill.py <SKILL.md or skills directory>…
In the Magpie repository, use its own tools instead, since a hook checks the stamped count:
uv run --project tools/skill-token-count skill-token-count --write # body
magpie-python tools/dev/estimate-skill-tokens.py --per-skill # always-on
Prioritize the always-on budget. The body costs only when invoked; frontmatter costs in every session for every skill.
Reference baseline, Magpie's own catalogue: 75 skills; body median 4,614 tokens, p90 10,613,
largest 28,346; always-on median 200, largest 398.
Magpie also caps a SKILL.md at 500 lines (PRINCIPLES.md P15); use it as the structural cap elsewhere too.
Also estimate the run cost: what one invocation actually reads, which the body alone understates.
security-issue-sync has a body of about 6k tokens, yet a routine run reads about 46k and its heaviest path about 53k, before any tool output.
Walk the steps for the routine path and the heaviest path, and add up SKILL.md, each sibling that path reads (file size ÷ 4), and a rough figure for what its tools return, such as issue bodies, mail threads or PR diffs.
Count a sibling behind a pointer only on a path whose trigger fires.
This is a guess, not a measurement: give it per path, state the assumptions, and keep the tool-output figure separate from the file total.
Prefer the pass that moves the routine path most, since that is what most runs pay.
Report both numbers and the run cost in Step 5 whether or not the pass moved them.
A body cut saves only what a run stops reading.
Moving text that every run reads into a sibling every run also opens lowers the body and not the run:
a split of security-issue-import's field extraction was reverted for that reason.
Moving it into a sibling the same path already reads is worth doing only when the sibling restated it, so the move also removes a copy.
Documented exceptions. When what is left over the body budget is safety text, or text every run reads that no other file holds, stop: do not cut a rule to reach the number.
Propose a documented exception instead, in the Magpie repository an entry in SKILL_BODY_EXCEPTIONS (setup_preflight/oversize.py) with the body in a comment and room for a small fix.
Do the same for a skill left within about 100 tokens under the line, where the next one-sentence fix would trip the check, or stop a pass about 150 tokens short of it.
Lower a cap after a pass that shrinks the skill.
SKILL.md path.--all or over:<N> — diagnose and rank every skill without
editing; the default threshold is the 500-line P15 cap.pass:<name> — restrict diagnosis to named passes; otherwise
propose every applicable pass.With no target or selector, diagnose everything read-only and let the maintainer choose.
python3 3.11 or later runs the measuring script and the eval runner.
In the Magpie repository, uv runs the validator; stop if it is unavailable.
Use git to isolate the diff, preferably on a clean tree or branch.
Use doctoc when headings move, or report the manual step if it is
unavailable.
Resolve the target to a real skill directory and require green skill
checks before editing: the validator in the Magpie repository; elsewhere the
project's own, and at least measure_skill.py, which fails on a SKILL.md
with no frontmatter or no name.
Hand back baseline failures for correction; optimization starts from a
working skill.
Keep the diff isolated and reviewable.
Run every diagnostic in patterns.md and report one row
per smell: the pass that addresses it, the evidence (path:line, line
count, the construct), and how big a change it implies. Read-only.
The smells, in the order their passes apply:
<project-config>. → config-liftrewrite.mdFor a sweep, rank by cap overflow times distinct smells and stop there.
Before running passes on several skills at once, or handing them to parallel agents, read sweeps.md.
Propose applicable passes from lowest to highest blast radius: file
move, content lift, tool rewire, then rewrite because only it changes
wording.
For each pass, name the files, expected delta, and guarantee from
patterns.md.
Propose only. The maintainer picks which passes run, and in what order.
Restructure passes (split, config-lift) move exact text.
Use git mv for a whole file; otherwise move identical bytes and leave
a one-line pointer.
Rewire passes (out-of-context, fetch-upfront,
preflight-classifier) change execution, not decisions.
Route through a deterministic tool such as Magpie's
<framework>/tools/github-body-field or <framework>/tools/github-rollup,
or the project's own.
If human-facing proposals change, stop and use normal review.
Before cutting prose because a tool "already does this", compare the two line by line:
where they disagree, cutting the prose changes behaviour, so fix the tool first, with a test that fails before the fix.
The extract-code pass removes complete programs from model context. Keep the command's purpose and output interpretation in the body, then choose the destination by operational need:
scripts/ — default for a dependency-free command.tools/ project per tools/AGENTS.md
(README, declared capability and prerequisites, workspace entry),
elsewhere wherever the project keeps its tools.ops.py and the caller's
grant, so propose it and stop.Check prompt cost before choosing; do not trade tokens for a human approval on every invocation. Extract code byte-identically because paraphrasing changes the program.
Do not extract command shapes containing runtime placeholders such as
<tracker>, <N>, or <target>.
They are instructions written in shell, not runnable programs.
Catalogue evidence shows this pass is rare: only 482 of roughly 28,700
tokens in shell and Python fences were multi-line and placeholder-free,
mostly too small to beat a pointer line.
It applied to setup-isolated-setup-doctor, whose six deterministic
probes used 2,971 tokens, or 59% of its budget.
Require all three traits: complete, large enough to matter, and
unnecessary for the model to read.
The rewrite pass follows rewrite.md.
The maintainer writes each paragraph; apply their earlier edits to later
drafts.
A moved heading takes every reference with it:
step-config.json — update skill_md and step_heading.
Find matches with grep -rl '<heading text>' <evals dir>:
tools/skill-evals/evals/ in the Magpie repository,
.apache-magpie-overrides/evals/ in an adopting project.other.md#the-heading references; the
project's link checker verifies them (whole-tree lychee in Magpie).Only the eval suite catches a stale step-config.json extraction.
After each pass, regenerate the TOC if headings moved and re-run the skill checks. One pass per commit.
Require the Step 0 skill-check result, and both budgets must have moved the right way.
Run the skill's eval suite if it has one, at
tools/skill-evals/evals/<skill>/ in the Magpie repository or
.apache-magpie-overrides/evals/<skill>/ in an adopting project.
In a sandboxed session, run it only through the installed wrapper, as a
bare command:
~/.claude/scripts/magpie-run-evals.sh <evals dir>/<skill>
It runs outside the sandbox from a copy the agent cannot edit. When it is
missing, propose installing it; never hand the user a ! command that runs
the runner from <framework> or the repository, which the sandbox can
write. With no sandbox in use, run
PYTHONPATH=<framework>/tools/skill-evals/src magpie-python -m skill_evals.runner
with --cli "claude -p" --cli-cwd "$(mktemp -d)" directly.
Run it before the first pass and compare; an after-only run cannot distinguish regressions from baseline failures.
If an unchanged case flips, name it as nondeterministic and let the maintainer decide rather than claiming either result proves safety.
A missing suite does not block the pass, but report that the skill checks were its only gate.
For restructure, match body deletions to sibling additions plus the new
pointer.
A suite that pastes the moved text into its prompt with also_include shows the rule still works, never that an agent reaches it,
so prove every new pointer as patterns.md describes under Split.
For rewire, show that human-facing proposals stayed unchanged.
For rewrite, the approved paragraph diff is the record.
For every pass that changed a word, list each sentence of the base that no longer appears verbatim anywhere in the skill directory, with where its content now lives or why it may go: the list catches the facts a wording cut drops.
If the validator goes red, or you cannot show the behaviour held, revert the pass. Never ship half of one.
Report files, delta, validator result, and evidence per pass.
Do not commit or open a PR unless asked.
After rewrite, propose learned style rules from
rewrite.md.
If it was a sweep, restate what is still on the list.
apache/magpie PR.patterns.md — the behaviour-preserving passes.rewrite.md — the paragraph-by-paragraph rewrite and
the style-learning loop.sweeps.md — running passes on many skills, or with parallel agents.write-skill — authoring a new skill.scripts/measure_skill.py — both budgets
and the frontmatter check, in any project.tools/skill-and-tool-validator — the gate in the Magpie repository.Written by the rewrite pass at the end of a session, as a proposed
diff. Bullets only — a heading here would move this skill's
surface_hash and tell every adopter their configuration went stale
over a wording preference.
^<scope-b>/ and one under ^<scope-a>/" from a mixed-scope guard made a same-scope case fail; restoring it fixed the case.gh call that is piped, redirected or wrapped in $(…), or that belongs in a vetted-ops read; that shape fails under the secure setup.What SKILL.md sets; muted values are Claude Code's defaults
When the user says "optimize <skill>", "this SKILL.md is too long", or "rewrite <skill> with me", or an audit flags more than 500 lines or hardcoded values. For a new skill, use write-skill.
Generated from the plugin's indexed repository (apache/magpie) — no native marketplace selected
npx claudepluginhub p/apache-magpie62 skills in this plugin
/audit-finding-fixFor a batch of findings from a non-security audit tool (`<audit-tool>`
— ruff / flake8 / mypy / pylint / CodeQL / Apache Verum / Apache Caer /
equivalent; full list in the body) against `<upstream>`, draft the
smallest fix per finding, re-running the tool after each batch to
confirm clearance. Produces a commit and a hand-back artefact;
never opens a PR on autopilot or merges.
/ci-runner-auditRead-only audit of GitHub Actions runner compatibility for one
repository, a repository set, one Apache project, or the full Apache
org. Finds obsolete GitHub-hosted runner labels and macOS runner/tool
architecture mismatches. Produces TSV evidence; never edits workflows,
opens PRs, or posts comments.
/committer-onboardingPost-vote committer and PMC onboarding for Apache projects, podling
or top-level: walks the nominator from ICLA check to welcome
announcement, and maps the new committer's GitHub handle to their
Slack, Discord, and social-media identities for the nominator to
confirm.
/activity-sweepRead-only activity card for a named contributor on `<upstream>` across
code-host and tracker surfaces. Code-host and tracker activity only; use
`contributor-nomination` for a full brief.
/calibrateDerive committer and <governance-body> reference levels from the
project's own past nomination decisions on <private-list>, deliberately
relaxed below what was elected, and propose them as a numbers-only
config diff.
/candidate-screenSurface activity data about recent contributors who pass a
long-tail pre-filter — for committer and <governance-body>
discussions — as an alphabetical list with details, in a
verified-private repository. Data only: no scoring, ranking,
floor comparison or readiness verdict.
2 plugins in one repository ship this exact skill · first indexed Nov 29, 2026
Other plugins' skills for the same job