Engineering Skills for AI Coding Agents: Refactoring, Debugging, Code Review, Tests and Migrations
Engineering skills packaged as Agent Skills (SKILL.md folders) that make AI coding agents like Claude Code and Codex work the way a careful senior engineer does: refactor in small verified steps, debug with evidence instead of guesses, review code with prioritized findings, design tests that can actually fail, pin down legacy behavior before changing it, write zero-downtime database migrations, upgrade dependencies without drama, and optimize performance with measurements.
Each skill is short, opinionated and practical. Two of them ship tested, dependency-free scripts: a PostgreSQL migration linter and a flaky test checker.
Last reviewed: December 2026. Tool versions and database behavior notes were checked against official documentation; see Where to go next for sources.
Contents
- The skills at a glance
- Install
- Why skills for engineering practice
- Skill: refactor-safely
- Skill: debug-systematically
- Skill: code-review
- Skill: write-tests
- Skill: characterization-tests
- Skill: database-migration
- Skill: dependency-upgrade
- Skill: performance-investigation
- Cheat sheets
- Comparison tables
- Best picks: tools these skills pair well with
- FAQ
- Where to go next
- Repository layout and tests
- Contributing
- More free resources
The skills at a glance
| Skill | Use it when | Key idea | Script |
|---|---|---|---|
| refactor-safely | “Clean this up”, “split this class”, before adding a feature to messy code | Structure changes only; tests green after every step; never mix with behavior changes | |
| debug-systematically | A bug, stack trace, flaky or failing test | Reproduce, isolate, one hypothesis at a time, git bisect, fix root cause with a regression test |
flake_check.py |
| code-review | “Review this PR”, “is this ready?” | Passes from intent to correctness to security to tests to style; every finding has file:line, reason, fix | |
| write-tests | “Add tests”, new code without tests | Right level (unit/integration/e2e), boundaries and equivalence classes, deterministic, prove the test can fail | |
| characterization-tests | Changing legacy or untested code | Record what the code does (golden master) before changing it | |
| database-migration | Schema changes on live data | Old and new app versions run together: expand/contract, non-blocking DDL, batched backfills | migration_lint.py |
| dependency-upgrade | Bumps, majors, security advisories | Read the migration guide, one major at a time, package manager not hand edits, verify | |
| performance-investigation | Slow, timeouts, memory | Target number, baseline, profile, fix the biggest cost, re-measure |
Install
Claude Code: plugin (all skills)
claude plugin marketplace add Ralpberry-Labs/engineering-skills
claude plugin install engineering-skills@ralpberry-engineering-skills
Run them as /engineering-skills:code-review, /engineering-skills:database-migration and so on, or just describe the task (“review my branch”, “this test is flaky”) and Claude loads the matching skill.
Claude Code: copy individual skills
git clone https://github.com/Ralpberry-Labs/engineering-skills
cp -r engineering-skills/skills/code-review ~/.claude/skills/ # personal
mkdir -p .claude/skills && cp -r engineering-skills/skills/database-migration .claude/skills/ # team, via git
Run /skills to confirm they loaded, or /reload-skills if you copied them mid-session.
OpenAI Codex
mkdir -p .agents/skills && cp -r engineering-skills/skills/* .agents/skills/
Codex scans .agents/skills/ from your working directory up to the repository root, and ~/.agents/skills/ for personal skills.
Any other agent
The skills use only the standard name, description and compatibility frontmatter from the Agent Skills specification, so any skills-compatible agent can load them. If your agent has no skills support, reference the file from your AGENTS.md (“For database migrations, follow skills/database-migration/SKILL.md”).
Why skills for engineering practice
Coding agents know a lot of facts about refactoring, testing and SQL. What they lack is discipline under pressure: in the middle of a task they skip the baseline measurement, change behavior during a refactor, add a sleep() to make a flaky test pass, or write CREATE INDEX without CONCURRENTLY on a 200-million-row table. A skill puts the checklist in front of the agent at exactly the moment it is needed, and costs almost nothing when it is not (only the one-line description is loaded until the skill is used).
| Put it in… | When |
|---|---|
CLAUDE.md / AGENTS.md |
Facts and rules for every task: build commands, project conventions |
| A skill (this repo) | A procedure for some tasks: how to review, how to migrate, how to debug |
| A hook | Something that must happen every time, enforced by code: block DROP TABLE, run the formatter |
| A subagent | Work that should run in a separate context with limited tools: a read-only reviewer |
These combine well: for example, run code-review inside a read-only subagent, and back database-migration with a pre-commit hook that runs migration_lint.py.
Skill: refactor-safely
What the agent does
- States the goal of the refactor in one sentence.
- Finds the safety net: runs the tests for the code, checks coverage of the specific functions, and writes characterization tests if coverage is missing.
- Finds every caller, including string references (DI containers, templates, serialized names, SQL).
- Applies one named refactoring at a time (extract function, rename, move method, guard clauses, parameter object, replace conditional with polymorphism, inject dependency), running tests after each and reverting any step that breaks them.
- Reports the change as a list of named refactorings and lists behavior that looked buggy but was preserved on purpose.
Example prompt: “Refactor billing/invoice.py so tax calculation can be unit tested without a database. No behavior changes.”
Smell to refactoring map (from the skill)
| Smell | Refactoring |
|---|---|
| Long function | Extract function |
| Unclear name | Rename (prefer IDE/LSP rename) |
| Duplicated logic | Extract shared part, only if copies change for the same reasons |
| Function doing two things | Split, then move each part |
| Deep nesting | Guard clauses |
| Long parameter list | Parameter object |
| Feature envy | Move method |
| Repeated type switch | Polymorphism or lookup table |
| Hidden global dependency | Dependency injection |
For risky structural changes the skill uses parallel change: build the new structure next to the old one, migrate callers one by one, delete the old one last.
Skill: debug-systematically
The core loop is: exact failure, reliable reproduction, isolation, one hypothesis at a time, root-cause fix with a regression test, then search for siblings of the bug.
Playbooks by symptom in the skill cover exceptions, wrong output without errors, flaky tests, slowness, “works locally but not in CI”, and heisenbugs. For example, the “works locally, fails in CI” playbook tells the agent to diff runtime and dependency versions, environment variables, file-system case sensitivity, time zone and locale, CPU count and network access, and to reproduce in the CI container image before touching code.
Flake checker
python3 skills/debug-systematically/scripts/flake_check.py --runs 20 -- pytest tests/test_orders.py -k refund
runs: 20 passed: 17 failed: 3 pass rate: 85.0%
failure signatures:
3x AssertionError: expected 3 got 2
failed runs: 4, 11, 17
duration: min 1.84s max 2.31s
Failure output is normalized (memory addresses and durations replaced) so identical failures group together. --stop-after-fails 1 stops at the first failure, handy for long suites.
Example prompt: “test_refund_partial fails about 1 in 10 runs in CI. Find out why.”
Rules the agent follows: never change two things at once; never “fix” with retries, sleeps, broad exception handlers or looser assertions without explaining why that is correct; remove debug output; if the cause is still unknown, report what was ruled out and the next experiment.
Skill: code-review
The review happens in passes, most important first:
- Does it do what the PR/issue says?
- Correctness (logic, null/empty, error paths, concurrency, time zones, money as floats, resource leaks, non-idempotent retries)
- Security (injection into SQL/shell/paths/HTML/URLs, deserialization, ReDoS, missing authorization, secrets in logs, broad CORS)
- Tests (would they fail if the change were reverted?)
- Design (right layer, new dependencies, backward compatibility)
- Readability
- Operations (logs and metrics for new failure modes, safe migrations, documented config, feature flags)
Output format
Summary: Adds partial refunds to the payments service. Close; two blocking issues.
Blocking
1. payments/refund.py:88 - Refund amount is not checked against the remaining captured amount,
so two concurrent partial refunds can exceed the charge. Suggest: SELECT ... FOR UPDATE on the
charge row and compare against captured - refunded inside the transaction.
2. api/routes/refunds.py:31 - Endpoint checks the user is logged in but not that the charge belongs
to their account (IDOR). Suggest: filter by account_id from the session.
Non-blocking
3. payments/refund.py:120 - Amount uses float; store and compute in integer cents.
Questions
- Should refunds on disputed charges be blocked?
Example prompt: “Review PR 482 against its linked issue. Blocking issues first.”
The skill also tells the agent to say when a change is too big to review well and suggest how to split it. Large PRs are where reviewers (human or AI) miss the most.
Skill: write-tests
The agent first learns the house style (framework, fixtures, how to run one test) and never introduces a new framework. Then it chooses the level, lists cases before writing any code, and writes them.
Case checklist: happy path; one representative per equivalence class; boundaries (0, 1, many, empty, max length, just below/at/above limits, month ends, leap day, DST); invalid input with specific error assertions; dependency failures (timeouts, 500s, constraint violations); a regression test per bug fix.
Quality rules: names describe behavior; arrange/act/assert; assert outcomes, not internal calls; deterministic (inject time, seed randomness, no sleeps, no order dependence); mocks only at system boundaries; factories with defaults.
Prove the test can fail: for key tests, the agent temporarily breaks the code (inverts a condition) and confirms the test fails, then restores it. A test that cannot fail is noise. For a systematic version of this, see mutation testing tools in Best picks.
Example prompt: “Add tests for parse_duration(); it accepts strings like ‘1h30m’ and ’90s’.”
Skill: characterization-tests
Before changing code nobody fully understands, record what it does today:
- Pick the narrowest public seam (function, CLI, endpoint, report).
- Generate inputs that hit each branch, plus real anonymized samples.
- Capture outputs, normalizing timestamps, IDs, ordering and paths.
- Assert against the recorded outputs (snapshot tools or plain golden files with an
UPDATE_GOLDEN=1switch). - Break the code on purpose to confirm the tests bite.
- Mark surprising behavior as “looks like a bug” in a comment, but keep it pinned. Fixing it is a separate, explicit change.
Golden file pattern (Python):
import json, os, pathlib, pytest
from legacy.pricing import quote
GOLDEN = pathlib.Path(__file__).parent / "golden"
CASES = {
"single_item": {"items": [{"sku": "A", "qty": 1}], "country": "US"},
"bulk_discount": {"items": [{"sku": "A", "qty": 120}], "country": "US"},
"eu_vat": {"items": [{"sku": "B", "qty": 2}], "country": "DE"},
}
@pytest.mark.parametrize("name", sorted(CASES))
def test_quote_matches_golden(name):
result = quote(**CASES[name])
path = GOLDEN / f"{name}.json"
if os.environ.get("UPDATE_GOLDEN") == "1":
path.write_text(json.dumps(result, indent=2, sort_keys=True))
assert result == json.loads(path.read_text())
Example prompt: “We need to change legacy/pricing.py. It has no tests. Pin its current behavior first.”
Skill: database-migration
The skill is built on one rule: during a rolling deploy, the old and the new version of the app run at the same time, so every migration must work with both.
Expand / contract (also called parallel change) for renames and type changes:
| Step | Ships as | Rename users.fullname to display_name |
|---|---|---|
| Expand | migration | add nullable display_name |
| Dual write | app deploy | write both, read old |
| Backfill | job | copy in batches |
| Switch reads | app deploy | read new, write both |
| Stop old writes | app deploy | write new only |
| Contract | migration | drop fullname |
PostgreSQL lock and rewrite table (PostgreSQL 12+; check the ALTER TABLE and CREATE INDEX docs for your version):
| Operation | What happens | Safer way |
|---|---|---|
| Add nullable column, no default | Metadata only | Fine |
| Add column with constant default | Metadata only on 11+ | Fine |
| Add column with volatile default | Full rewrite under exclusive lock | Add nullable, backfill, set default |
Add NOT NULL column without default |
Fails on non-empty table | Nullable, backfill, enforce |
SET NOT NULL |
Full scan under exclusive lock | CHECK (...) NOT VALID, VALIDATE, then SET NOT NULL |
| Change column type | Usually rewrite of table and indexes | New column and backfill |
CREATE INDEX |
Blocks writes for the build | CREATE INDEX CONCURRENTLY outside a transaction |
| Add foreign key | Validates all rows under lock | NOT VALID, then VALIDATE CONSTRAINT |
| Add unique constraint | Builds index under lock | Unique index concurrently, then USING INDEX |
| Rename | Instant, breaks running code | Expand/contract or compatibility view |
| Any DDL | Waits behind long queries and blocks the queue behind it | SET lock_timeout and retry |
Migration linter
python3 skills/database-migration/scripts/migration_lint.py migrations/
migrations/20261201_orders.sql:2: error: [create-index-not-concurrent] CREATE INDEX blocks writes for the whole build. Use CREATE INDEX CONCURRENTLY.
migrations/20261201_orders.sql:4: warning: [foreign-key-without-not-valid] Adding a foreign key validates every row while locking both tables. Add it NOT VALID, then VALIDATE CONSTRAINT.
migrations/20261201_orders.sql:1: warning: [missing-lock-timeout] DDL without SET lock_timeout can queue behind long queries and block all traffic.
3 finding(s), 1 error(s)
Rules: create-index-not-concurrent, drop-index-not-concurrent, concurrent-in-transaction, set-not-null, add-column-not-null-no-default, volatile-default, alter-column-type, foreign-key-without-not-valid, check-without-not-valid, unique-constraint-without-index, rename, drop-column, drop-table, missing-lock-timeout. Comments and string literals are ignored; dollar-quoted function bodies are not split. Silence a rule on one statement with -- lint: ignore <rule-id>. Exit code 1 on errors, so it fits pre-commit and CI.
It works on SQL files. For ORM migrations, lint the generated SQL: Django manage.py sqlmigrate app 0042, Rails rails db:migrate with a SQL schema dump or strong_migrations, Alembic alembic upgrade head --sql, Prisma prisma migrate diff --script.
Every migration PR includes the SQL that will run, table size and expected lock time, deploy order, rollback plan, and backfill plan.
Example prompt: “Make orders.customer_email NOT NULL. The table has 80 million rows and we deploy with zero downtime.”
Skill: dependency-upgrade
- Inventory: outdated packages and known vulnerabilities (
npm outdated,pip list --outdated,go list -m -u all;npm audit,pip-audit,govulncheck,cargo audit), plus runtime support status. - Plan: security patches first with the smallest fixing version, then minor/patch batches, then each major on its own, one major at a time, reading the official migration guide for each.
- Upgrade with the package manager so the lockfile stays consistent; run official codemods and review their diff.
- Verify: tests, types, lint, production build, smoke test of changelog-mentioned areas, lockfile diff review for surprising new transitive packages.
- Report: from/to, why, breakages and fixes, deferred items, and the guide used.
Example prompt: “Upgrade this app from React Router 6 to 7. Follow the official upgrade guide and keep the diff reviewable.”
The skill forbids regenerating the whole lockfile unasked (it silently upgrades every transitive dependency) and ignoring audit findings without a written reason.
Skill: performance-investigation
- Target: a number (p95 latency, throughput, memory, LCP).
- Baseline: production-like data, several runs, median and p95.
- Profile: find where time actually goes.
- Usual suspects, in order: I/O in loops (N+1), missing indexes, work that is thrown away, wrong data structures, missing caches, serialization/logging in hot paths, concurrency mistakes.
- Fix one thing, re-measure, stop at the target, keep the benchmark.
Profilers by stack (from the skill)
| Stack | CPU | Memory |
|---|---|---|
| Python | py-spy, cProfile | tracemalloc, memray |
| Node.js | node --cpu-prof, 0x, Clinic.js |
heap snapshots |
| Go | pprof | pprof alloc profiles |
| JVM | async-profiler, JFR | JFR, heap dumps |
| Browser | DevTools Performance, Lighthouse | DevTools Memory |
| PostgreSQL | EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements |
- |
Example prompt: “GET /api/orders takes 2-4 seconds for big accounts. Target p95 under 300 ms.”
Cheat sheets
git for debugging
git bisect start; git bisect bad; git bisect good v2.3.0
git bisect run ./repro.sh # 0 = good, 125 = skip, other 1-127 = bad
git bisect reset
git log -S 'calculateTax' --oneline # commits that added/removed a string
git log -G 'retry\(.*\)' --oneline # commits whose diff matches a regex
git log -p --follow -- src/tax.py # history of a file across renames
git blame -w -C -L 40,60 src/tax.py # who changed lines 40-60, ignoring whitespace and moves
PostgreSQL query investigation
EXPLAIN (ANALYZE, BUFFERS) SELECT ...; -- real timings and I/O; runs the query!
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10; -- needs the extension
SELECT relname, n_live_tup FROM pg_stat_user_tables ORDER BY n_live_tup DESC LIMIT 10;
SET lock_timeout = '5s'; SET statement_timeout = '15min'; -- before DDL / backfills
In EXPLAIN output, look for Seq Scan on large tables with a selective filter, row estimates far from actual rows (stale statistics: ANALYZE table), and nested loops over many rows. Wrap EXPLAIN ANALYZE of writes in BEGIN; ... ROLLBACK; because it executes the statement.
Zero-downtime NOT NULL (PostgreSQL 12+)
SET lock_timeout = '5s';
ALTER TABLE orders ADD CONSTRAINT orders_email_not_null CHECK (customer_email IS NOT NULL) NOT VALID;
-- backfill NULLs in batches first, then:
ALTER TABLE orders VALIDATE CONSTRAINT orders_email_not_null; -- scans without blocking writes
ALTER TABLE orders ALTER COLUMN customer_email SET NOT NULL; -- uses the valid CHECK, no scan
ALTER TABLE orders DROP CONSTRAINT orders_email_not_null;
Unique constraint without blocking writes
CREATE UNIQUE INDEX CONCURRENTLY users_email_key_idx ON users (email); -- not inside BEGIN
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE USING INDEX users_email_key_idx;
Benchmark commands
hyperfine --warmup 3 'python old.py' 'python new.py' # compare two commands
oha -z 30s -q 50 http://localhost:8000/api/orders # 30 s at 50 requests/s
py-spy record -o profile.svg --pid 12345 # flame graph of a running process
node --cpu-prof server.js # writes a .cpuprofile for DevTools
go test -bench=. -cpuprofile cpu.out ./pkg/... && go tool pprof -http=:0 cpu.out
Comparison tables
Test levels
| Unit | Integration | End-to-end | |
|---|---|---|---|
| Scope | One function/class | Code + real DB/queue/framework | Whole system through UI or API |
| Speed | ms | ms to s | s to min |
| Flakiness risk | Low | Medium | High |
| Finds | Logic bugs | Wiring, queries, serialization | Broken user journeys |
| How many | Most | Many | Few, critical paths only |
Snapshot/golden testing options
| Option | Stack | Notes |
|---|---|---|
Jest / Vitest toMatchSnapshot |
JavaScript/TypeScript | Built in; review snapshot diffs like code |
| syrupy | Python (pytest) | Snapshot plugin with --snapshot-update |
| ApprovalTests | Python and many other languages | Approval workflow with diff tools |
| Plain golden files | Any | Zero dependencies; the pattern shown above |
PostgreSQL migration safety tools
| Tool | What it is | Best for |
|---|---|---|
migration_lint.py (this repo) |
Single-file, stdlib Python linter over SQL | Quick checks in any stack, pre-commit, agents |
| squawk | Dedicated PostgreSQL migration linter with many rules and CI integration | Teams that want a maintained, comprehensive linter |
| strong_migrations | Rails gem that catches unsafe migrations at run time | Rails apps |
| pgroll | Tool that runs expand/contract migrations for you with versioned schemas | Automating zero-downtime schema changes |
For MySQL, online schema change tools such as gh-ost and pt-online-schema-change play the role that CONCURRENTLY and NOT VALID play in PostgreSQL.
Vulnerability audit commands
| Ecosystem | Command |
|---|---|
| npm | npm audit |
| Python | pip-audit (pypa/pip-audit) |
| Go | govulncheck ./... (docs) |
| Rust | cargo audit (RustSec) |
| Ruby | bundle audit (bundler-audit gem) |
Best picks: tools these skills pair well with
| Need | Pick | Why |
|---|---|---|
| Benchmark CLI commands | hyperfine | Warmups, statistics and comparisons in one command |
| Python CPU profiling | py-spy | Sampling profiler that attaches to running processes without code changes |
| Python memory profiling | memray | Tracks native and Python allocations with flame graphs |
| Node.js profiling | Clinic.js or 0x | Flame graphs and diagnosis for Node processes |
| Go / general profiles | pprof | Standard Go profiler with a web UI |
| JVM profiling | async-profiler | Low-overhead CPU and allocation profiling |
| HTTP load tests | k6, oha, hey | Scriptable scenarios (k6) or quick one-liners (oha, hey) |
| Read PostgreSQL plans | explain.dalibo.com | Paste EXPLAIN output to visualize it |
| Learn indexing | Use The Index, Luke | Free, vendor-neutral guide to SQL indexing |
| Property-based tests | Hypothesis (Python), fast-check (JS/TS) | Generates edge cases you did not think of |
| Mutation testing | Stryker (JS/TS, C#, Scala), mutmut (Python) | Checks that tests fail when code is broken |
| Automated dependency PRs | Dependabot, Renovate | Small, regular upgrade PRs instead of big bang upgrades |
| Runtime end-of-life dates | endoflife.date | One place to check support windows |
FAQ
Do these skills replace linters, type checkers or CI? No. They make the agent use those tools at the right moments and interpret results well. Deterministic checks belong in CI and hooks.
Why are the skills so short?
Every line of a loaded skill costs context and attention. The skills contain only what changes behavior: steps, rules, tables and “never do” lists. The Agent Skills spec recommends keeping SKILL.md under 500 lines; these are far below that.
Is the migration linter a replacement for squawk or strong_migrations? No. It is a small, dependency-free first line of defense that an agent can run anywhere. For production teams, a maintained tool such as squawk (PostgreSQL) or strong_migrations (Rails) is a better long-term choice, and the skill’s table explains the reasoning so the agent fixes issues correctly either way.
Does the migration advice apply to MySQL? The expand/contract pattern, batched backfills and deploy ordering apply to any database. The lock table is PostgreSQL-specific; MySQL’s online DDL behaves differently by version and storage engine, and large tables are often changed with gh-ost or pt-online-schema-change.
How do I make an agent review code without editing it?
Run the code-review skill inside a subagent whose tools exclude Edit and Write, or in Claude Code’s plan mode. The skill itself also instructs the agent not to rewrite the change.
Can I use these with Cursor, Copilot, Gemini/Antigravity or other tools?
Any tool that supports Agent Skills can load them directly. Others can read them as referenced documentation from AGENTS.md or their own rules files.
What does “test can fail” mean in practice? After writing a test, the agent briefly breaks the code under test (for example flips a comparison) and runs the test to see it fail, then restores the code. Mutation testing tools automate the same idea across a whole codebase.
Why does the debugging skill forbid adding retries to fix flaky tests? Because a retry hides the cause. Flaky tests usually point to real problems: shared state, time dependence, unawaited async work or races, which can also hit production. Retries are acceptable only around genuinely unreliable external systems, and then in production code with backoff, not in the test.
Where to go next
- Agent Skills specification: the format these skills follow
- Google Engineering Practices: code review: a widely used public guide to reviewing and authoring changes
- Refactoring catalog: names and mechanics for common refactorings
- Parallel change and Strangler fig: patterns behind expand/contract and incremental rewrites
- The practical test pyramid: choosing test levels
- git bisect documentation
- PostgreSQL: Using EXPLAIN and pg_stat_statements
- Flame graphs: how to read the most useful profiling visualization
- Semantic Versioning and Conventional Commits
- Books worth owning: Refactoring (2nd edition), Working Effectively with Legacy Code, Test Driven Development: By Example, Debugging: The 9 Indispensable Rules
- Sister repos: agent-skills-library (docs, data and DevOps skills) and agent-skills-frontend (accessibility, Core Web Vitals, responsive layout)
Repository layout and tests
.claude-plugin/ plugin.json, marketplace.json
skills/
refactor-safely/
debug-systematically/ scripts/flake_check.py
code-review/
write-tests/
characterization-tests/
database-migration/ scripts/migration_lint.py
dependency-upgrade/
performance-investigation/
tests/test_scripts.py linter, flake checker and frontmatter tests (stdlib only)
python3 -m unittest discover -s tests -v
claude plugin validate . # optional, if Claude Code is installed
Contributing
PRs are welcome: new linter rules with tests, playbooks for more symptoms, stack-specific tables, or corrections. Keep skills short and concrete, verify any database or tool behavior against official documentation (and say which version it applies to), and run the tests before opening a PR.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.