Skip to main content
BuildReviewed Oct 19, 2026

Guarding Destructive Operations

v1.0.1New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, then copy.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install ffmpeg-skill-guarding-destructive-operations

What this does: Add and review preconditions on operations that delete, overwrite, rewrite history, or resolve a caller-supplied name to a filesystem path — refusing instead of warning, placing the guard ahead of the first mutation, structural classification rather than string-prefix matching, name validation plus resolved-path containment as two independent checks, why a guard on the destructive path is invisible to the dry-run, and mutation-testing each half separately. Use when writing or reviewing a `--rebuild`/`--reset`/`--purge` command, a bulk delete, a history rewrite, an `rm -rf`-shaped step, or any code that turns an argument into a file path.

Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/ffmpeg-skill-guarding-destructive-operations/SKILL.md

Setup guide →
0Save

Instructions

Guarding Destructive Operations

Some operations have no undo: an orphan-branch rewrite, a recursive delete of
every tracked file, an overwrite of a stored artifact, a DROP/purge path. The
implementation is usually short and usually correct for the setup its author had
in mind
. The bug is never the deletion itself — it is that nothing checked
whether the target was the thing the author imagined.

Two shapes recur, and they take the same fix:

  • Blast radius. The operation is correct only in a dedicated, single-purpose
    target and is catastrophic in a mixed one.
  • Boundary escape. A caller-supplied name is joined onto a base directory and
    lands outside it.

Refuse; don't warn, and don't add an override

A destructive operation that discovers its precondition is violated should return
an error and change nothing. A warning is read by nobody, and a --force escape
hatch turns the guard into documentation.

// A rebuild that recreates history does `checkout --orphan` then
// `rm -rf --ignore-unmatch .`, keeping only the state files it rewrites.
// That is correct in a dedicated mirror repository whose ONLY tracked content
// is `.state/`. Run it where source code also lives and the new branch loses
// the source code.
func (e *Engine) rebuild() error {
    if err := e.ensureDedicatedRepo(); err != nil {
        return err   // nothing mutated yet
    }
    ...
}

The honest justification for having no override flag: there is no situation where
the operator wants this command to delete unrelated tracked files. If a real one
appears later, that is a separate, differently-named command — not a boolean on
this one.

Put the guard ahead of the first mutation

"Refuses" is only true if the refusal happens before anything has changed.
Walk the function and find the first statement with an effect — it is often not
the obvious deletion. In-memory state clearing, a branch checkout, and a
read-then-rewrite of the very files you are preserving all count.

// Order that makes the refusal safe:
//   1. reject detached HEAD / ambiguous state
//   2. ensureDedicatedRepo()          <-- the new guard, nothing mutated yet
//   3. read the state files to preserve
//   4. CheckoutOrphan()
//   5. RemoveAllTrackedFiles()
//   6. ClearAllProgressCounts()

Steps 3-6 are all mutations of something (3 is not, but it is where the "what to
preserve" snapshot is taken, and a guard after it has already committed you to a
shape). Land the guard at 2 and a rejected run leaves the working tree byte-identical.

Also refuse ambiguous state before rewriting it. A history rewrite that assumes
a named branch should reject detached HEAD up front rather than silently
recreating the wrong ref.

Classify structurally, not by string prefix

The guard needs to answer "is every tracked path inside the directory this
command owns?". A HasPrefix/startswith on the bare directory name is the
wrong answer and looks right in every test you would think to write.

// Bad — admits `.state-backup/notes.md` and `.stateful.txt`, so a repository
// full of unrelated content passes the guard and gets deleted.
func owned(path string) bool {
    return strings.HasPrefix(path, ".state")
}

// Good — the directory itself, or something genuinely under it.
func owned(path string) bool {
    return path == ".state" || strings.HasPrefix(path, ".state/")
}

The same distinction in Python is Path(p) == base or base in Path(p).parents,
not p.startswith(str(base)). Any time a check compares paths as strings, ask
what a sibling with a longer name does to it.

Name validation and resolved containment are two checks, not one

When a public argument selects a file — a baseline name, a template id, a report
slug — do both, in this order:

NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")

def _validate_name(name: str) -> str:
    if ".." in name or not NAME_RE.match(name):
        raise ValueError(f"invalid name: {name!r}")
    return name

def _resolve(name: str, base: Path) -> Path:
    candidate = (base / f"{_validate_name(name)}.json").resolve()
    if not candidate.is_relative_to(base.resolve()):
        raise ValueError(f"name escapes {base}: {name!r}")
    return candidate

The containment half is not redundant with the regex. The regex stops ..
segments and absolute paths; only the resolve() + containment check stops a
symlink placed inside the directory that points out of it — a name matching
^[A-Za-z0-9] all the way through can still resolve anywhere. Route every entry
point through both: the loader, the saver, and any path-building helper a public
method still calls directly. A single unrouted helper reinstates the whole hole.

Without this, an implicit suffix (name + ".json") plus an absolute-path
argument reads any file on disk whose name happens to end in that suffix.

A guard on the destructive path is invisible to the preview

If the real run reaches the guard but --dry-run short-circuits earlier, the
preview cheerfully describes an operation the real run will refuse. That is a
defensible design — the destructive path is the one that must be safe — but be
explicit about it:

  • The preview will show a full rebuild in a repository where the rebuild is
    forbidden. Only the real invocation errors.
  • Anything meant to warn the operator earlier has to live in the preview stage
    or the CLI argument-validation layer, duplicated deliberately, not moved.

Say which one you chose in the PR description; a reviewer cannot tell from the
diff whether the dry-run gap is intentional.

Know what the caller does with your refusal

Tightening validation only helps if the new error reaches somebody. A broad
except Exception two frames up will turn a hard refusal into an ordinary
result shape:

try:
    features = self._load(baseline)
except Exception as e:                       # already there, catches your ValueError
    return {"error": f"Analysis failed: {e}", "features": {}, "flags": {...}}

This is often fine — an API boundary that never raises is a real contract, and
the refusal surfaces as a normal error-shaped response rather than a protocol
error. But check it deliberately: if that shape is what your caller sees, the
integration test asserts on result["error"], not on pytest.raises.

Testing

  • Mutate each half separately. Neuter only the regex and confirm a ..
    fixture fails; neuter only the containment check and confirm a symlink
    fixture fails. One combined test passes with either half deleted and proves
    neither.
  • Write the sibling-name fixture explicitly. A test whose repository tracks
    .state/data.json passes against HasPrefix(path, ".state") too. The test
    that separates the implementations tracks .state-backup/old.json and asserts
    the operation is refused.
  • Assert nothing was mutated on refusal, not just that an error came back:
    the branch is unchanged, the tracked file list is unchanged, the in-memory
    progress counters are unchanged. That is the actual claim.
  • Existing fixtures become the rejected shape. Older tests for the
    destructive path were often built loosely — a repository tracking app.txt
    alongside the state directory, because nothing cared. After the guard, such a
    test no longer reaches the code it was written to cover; it now exercises the
    refusal. Tighten those fixtures to the allowed shape and add the refusal case
    as a new test, or you silently lose coverage of the destructive path.
  • Reproduce the failure with the narrowest hook. When you need one specific
    operation to fail in order to test the recovery path, target it precisely — a
    blanket hook that rejects every operation of that kind aborts the run earlier
    than the path you were trying to reach, and the test proves something else.

Checklist

  • Every irreversible operation states its precondition in code, not in a doc
  • Violation returns an error; no --force, no warn-and-continue
  • The guard runs before the first statement with an effect
  • Ambiguous state (detached HEAD, missing target, multiple candidates) rejected up front
  • Path/ownership classification is structural, never a bare string prefix
  • Caller-supplied names are validated and resolved-path contained
  • Every entry point routes through both checks, including internal helpers
  • The dry-run/preview gap is intentional and stated
  • Tests mutate each half of the guard independently
  • A sibling-name (x-backup/) and a symlink fixture both exist
  • Refusal tests assert the target is unchanged, not just that an error was raised

Note for this repository (ffmpeg-skill)

This repo's actual exposure is much narrower than the examples above — there is
no --rebuild/--purge-shaped command, no history rewriting, and "Keep
originals" is already a stated design principle (README.md design principle
#10: no tool overwrites its input; a test hashes every input after every run,
see tests/test_contract.py's input-hash checks). The
closest analogue is -o/output-path handling: every tool takes a
caller-supplied output path. Since 2.0.0 an existing output is refused before
any ffmpeg runs unless the caller passes --overwrite
(_common._check_existing_output(), kind: input, reason output_exists);
the refusal is that Python guard, not an ffmpeg option (ffmpeg_base() passes
-y either way). With --overwrite, an output that already exists is written
through a hidden sibling temp file that replaces it only on success
(_stage_existing_output()); a new output is written straight to its path, so
a partial file can be seen there while the run is in progress. (Before 2.0 every tool passed -y and replaced an existing file
without a word, which is what this note used to report.) Since this is a local CLI a human or agent
invokes directly (not a server resolving untrusted network input against a
base directory), the "boundary escape" half of this skill is low-stakes here;
the "refuse before the first mutation" and "existing input-hash tests still
prove nothing was touched" halves are the parts that actually apply.

Source: wdm0006/python-skills (MIT).

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
building-python-mcp-serversBuilds robust Python MCP (Model Context Protocol) servers with FastMCP — tool design, error contracts, event-loop-safe blocking work, subprocess/CLI wrapping, single-file vs packaged distribution, global-state-free testing, and prompt-injection awareness. Use when writing an MCP server, exposing a tool or CLI to an LLM client, debugging tool registration/packaging, or testing MCP tools.0 installsreproducing-ci-locallyRun the CI gate on your machine so it agrees with the runner — deriving the exact command, paths, markers, and env from the workflow file instead of the Makefile, unblocking gate steps that short-circuit and hide the next failure, pinning the linter version CI resolves, building the interpreter/toolchain environment the runner builds, and confirming the run is green instead of explaining a red job away. Use when a check passes locally but fails in CI (or the reverse), when a lint/format job goes red on an untouched file, when setting up a local dev loop for an unfamiliar repo, or before pushing a branch you expect to merge.0 installsconcurrent-branchesResolve conflicts and merges when several branches are open against one repo at the same time — the hotspot files every change must touch (registry manifests, a single version field, shared tool config, one aggregated test module, tracked build output), union-vs-recompute-vs-rebuild as three different correct resolutions, generated artifacts that must never be merged, non-deterministic serialization that makes every branch conflict, renumbered identifiers that git cannot show you, and why a clean auto-merge is not a passing test. Use when rebasing or merging a long-lived branch, resolving conflict markers, reviewing a merge commit, deciding what a repo should commit vs generate, or setting up a repo that will take parallel contributions.0 installsprobing-edge-valuesFind the option values an ffmpeg-skill tool accepts without anyone having decided what they mean — zero, a negative number, a value far past any real frame or clip — by running tests/edge_values.py over every numeric option in the contract, then reading each call that ran or hung against the option's help, and checking the few properties a tool should keep (doing it twice changes nothing more, an inverse returns the source's shape, the output is what probe.py says). Use when looking for defects nobody has reported, before a tool moves from beta to stable, after adding a numeric option, or when a report says a tool "hung", "wrote a strange file" or "accepted nonsense".0 installsmanaging-python-releasesManages Python library releases including semantic versioning, changelog maintenance (Keep a Changelog format), release automation with GitHub Actions, and deprecation workflows. Use when planning releases, writing changelogs, automating release pipelines, or communicating breaking changes.0 installsrunning-github-actions-efficientlyCut GitHub Actions minutes and wall-clock time without losing coverage — the OS billing multiplier (macOS 10x / Windows 2x / Linux 1x), trigger hygiene that stops push+pull_request double-firing, concurrency that cancels superseded runs, dependency caching keyed on lockfiles, matrix discipline, and auditing scheduled crons that bill 24/7. Use when CI is burning included minutes, when runs feel slow, when setting up a new repo's workflows, or when reviewing an existing workflow for waste.0 installs

More from ffmpeg-skill

View source →
ffmpeg-skillEdit video and audio with local FFmpeg: cut, join, reframe, speed, captions, overlays, silence removal, sync, loudness, HDR to SDR, platform exports and checks. Use whenever the user mentions a video or audio file (mp4, mov, wav, m4a), footage, captions, a reel or short, YouTube/TikTok delivery, LUFS or ffmpeg, even without saying "edit". Needs FFmpeg 6.1+ and Python 3.10+; stdlib only, no cloud.24 installsreviewing-ffmpeg-skill-changesReview a change to the ffmpeg-skill repository for the failures its own contract makes possible — a claim in a result document that is true at one layer and false at the layer a caller reads, a new flag that reaches the code but not the contract/docs/demo surfaces, a "bug" that docs/design-decisions.md already decided with a pinning test, a fix with no regression test, a new runtime dependency or a raw ffmpeg shell call that breaks the scope boundary, a SKILL.md line added without one trimmed, a review that re-derives findings from a summary instead of the tree at the reviewed commit. Use when asked to review a PR or diff in this repository, when authoring code here and needing a pre-commit check, or when triaging an external review or audit report about this codebase.5 installsffmpeg-skillEdit video and audio with local FFmpeg: cut, join, reframe, speed, captions, overlays, silence removal, sync, loudness, HDR to SDR, platform exports and checks. Use whenever the user mentions a video or audio file (mp4, mov, wav, m4a), footage, captions, a reel or short, YouTube/TikTok delivery, LUFS or ffmpeg, even without saying "edit". Needs FFmpeg 6.1+ and Python 3.10+; stdlib only, no cloud.4 installskeeping-git-repos-cleanPrevents, detects, and remediates files that should never be committed — secrets (.env, API tokens, hardcoded credentials) and dev artifacts (build output, scratch databases, editor/OS files). Covers .gitignore (and why it does not untrack), git rm --cached, auditing tracked files, history scrubbing, and credential rotation. Use when a repo has committed secrets or junk, when setting up a new repo's ignore rules, or when reviewing what a repo actually tracks.1 installsci-pipeline-synthesizerGenerate GitHub Actions CI/CD pipeline configurations for automated building and testing of library and package projects. Use when creating or updating CI workflows for npm packages, Python packages, Go modules, Rust crates, or other library projects that need automated build and test pipelines. Includes templates for common package ecosystems with best practices for dependency caching, matrix testing, and artifact publishing.0 installsbuilding-the-review-pageBuild or change the standalone review page (scripts/_review.py, `npx ffmpeg-skill review`) — the editor-style screen where a person looks at a render project and its result and composes an instruction for their agent. Covers the fixed constraints (one offline HTML file, nothing executed, no new dependency, not a contract tool), the 16:10 three-column layout, the numbering scheme every element carries (S, C, T, A, M, R, P,0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.656 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.561 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.373 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.269 installsfounder-consumerThe consumer panel. Spins up a swarm of buyer sub-agents (default 100, --quick for 20) trained on the user's target customer, each with a different income, age, buying behaviour and objection, shows every one the same pitch, and runs the business through 100 buyer scenarios to see who buys, who doesn't, and why. Tallies the answers into buy rates by segment, the reasons people pass in their own words, what would flip a no, and price answers for founder-pricing. Use when the user says "would people buy this", "test it on customers", "run the consumer panel", "simulate buyers", "who is my customer", or "validate demand".198 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.186 installs

Frequently asked questions about guarding-destructive-operations

What does the guarding-destructive-operations skill do?

Add and review preconditions on operations that delete, overwrite, rewrite history, or resolve a caller-supplied name to a filesystem path — refusing instead of warning, placing the guard ahead of the first mutation, structural classification rather than string-prefix matching, name validation plus resolved-path containment as two independent checks, why a guard on the destructive path is invisible to the dry-run, and mutation-testing each half separately. Use when writing or reviewing a `--rebuild`/`--reset`/`--purge` command, a bulk delete, a history rewrite, an `rm -rf`-shaped step, or any code that turns an argument into a file path. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the guarding-destructive-operations skill?

Run `npx @skills-hub-ai/cli install ffmpeg-skill-guarding-destructive-operations` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/ffmpeg-skill-guarding-destructive-operations/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does guarding-destructive-operations work with?

guarding-destructive-operations runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the guarding-destructive-operations skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use guarding-destructive-operations after installing it?

In Claude Code, type `/ffmpeg-skill-guarding-destructive-operations` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the guarding-destructive-operations skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.

Badge for your README

Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/ffmpeg-skill-guarding-destructive-operations)](https://skills-hub.ai/skills/ffmpeg-skill-guarding-destructive-operations)
HTML
<a href="https://skills-hub.ai/skills/ffmpeg-skill-guarding-destructive-operations"><img src="https://skills-hub.ai/api/badges/skill/ffmpeg-skill-guarding-destructive-operations" alt="Install on Skills Hub"></a>

More options in the badge docs.