By role · Free prompt pack

ChatGPT, Claude & Gemini Prompts for Coding and Developers

52 free coding prompts for ChatGPT, Claude and Gemini: debugging, code review, tests, SQL, refactoring and AGENTS.md files for coding agents.

Prompts
52
Works with
ChatGPT, Claude & Gemini
Updated
Price
Free to copy

Most lists of coding prompts are one-liners like "write a function in [language] that does X". They produce code that looks right, and nobody can tell whether it is. These 52 prompts work the way a senior engineer does. They read the code before changing it, pin down behavior with tests, debug from evidence instead of guesses, and say UNKNOWN rather than invent an API or a file name.

The pack covers the work developers actually do each week, in eight sections: understanding unfamiliar code, debugging, design and building from a spec, code review and pull requests, refactoring and upgrades, testing, SQL and data, and working with AI coding agents. Each prompt sets a role, asks for your specifics as {{VARIABLES}} such as {{LANGUAGE}} and {{FRAMEWORK}}, and fixes the output format, so it behaves the same in ChatGPT, Claude and Gemini.

The prompts also work alongside agentic tools like Claude Code, Codex and Cursor without depending on any of them. You can write an AGENTS.md or CLAUDE.md from your real repo, brief an agent on one task, and review the diff it hands back. Four prompts include a worked example. The code in the three code examples was run locally: the tests fail on the buggy version and pass on the fix, and the SQL was run against sample data.

Understand & Document Unfamiliar Code

Most bugs come from changing code before understanding it. These prompts map a repository from its file tree, explain what a function promises and what it quietly depends on, and trace a single request end to end. Others dig the undocumented business rules out of legacy code, write a README that works on a clean machine, and help you learn a second language by contrast with one you know. Every one of them separates what the code shows from what the model is guessing.

Map an Unfamiliar Repository From Its File Tree

Best for: Getting oriented in a new codebase before you change anything

You are a staff engineer onboarding onto a codebase you have never seen. Build me a working map of it from the material below, and be explicit about what you are inferring versus what you can see.

Language and framework: {{LANGUAGE}} / {{FRAMEWORK}}
File tree (output of `tree -L 3` or `git ls-files`, trimmed): {{FILE_TREE}}
Key files pasted in full (entry point, config, build/manifest file, one representative module): {{KEY_FILES}}
What I need to do first in this repo: {{FIRST_TASK}}

Give me:
1. One paragraph: what this system does and how it runs (process type, entry point, how requests or jobs arrive).
2. A table of the top-level directories: purpose, and "Seen" or "Inferred" for each.
3. The likely request or data path for my first task, as a numbered list of files and functions. Mark guesses with (?).
4. Where the tests live, how they are probably run, and the command you would try first.
5. Five questions I should ask a teammate, ranked by how much time each answer would save me.
6. The three files I should read next, and why.

Don't invent file names that are not in the tree. If the tree is too thin to answer a point, say so.

Fill in: LANGUAGE FRAMEWORK FILE_TREE KEY_FILES FIRST_TASK

Run this in your first hour on a new repo. Strip secrets from config files before pasting (replace values with REDACTED).

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Explain a Function's Contract, Invariants and Side Effects

Best for: Understanding exactly what a function promises before you modify it

Act as a senior {{LANGUAGE}} engineer doing a careful code reading for a colleague who has to modify this function tomorrow.

Code (the function plus anything it calls that I could find): {{CODE}}
Where it is called from, if known: {{CALL_SITES}}

Explain it in this order:
1. Purpose in one sentence, in business terms if you can tell them.
2. The contract: inputs and their assumed types and ranges, return value, and every way it can fail (exceptions, error returns, null or empty results).
3. Invariants: what must be true before and after it runs. Point to the exact lines that rely on each one.
4. Side effects: I/O, mutation of arguments or shared state, logging, caching, time or randomness.
5. A walk-through of the non-obvious lines only (quote each line, then explain it). Skip the boilerplate.
6. Traps for the person changing it: hidden coupling, ordering dependencies, performance cliffs, and behavior that looks like a bug but might be deliberate.

Cite line numbers or quoted code for every claim. If you can't tell something from the code shown, write "Not visible in the snippet" instead of guessing.

Fill in: LANGUAGE CODE CALL_SITES

Paste the callees too where you can; most surprises live one call deeper. Use the trap list as your review checklist when you make the change.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Trace One Request Through the Codebase

Best for: Answering 'where does this value come from?' or 'why did this request do that?'

You are a senior engineer helping me follow a single request or event all the way through a system I didn't write.

Stack: {{FRAMEWORK}}
The trigger (route, CLI command, queue message or UI action): {{TRIGGER}}
Code along the path (handlers, middleware, services, data access, in call order if I know it): {{CODE_PATH}}
The question I'm trying to answer: {{QUESTION}}

Produce:
1. A numbered trace: each step names the file and function, what it receives, what it does, and what it passes on. Note where the data changes shape.
2. Every branch point that changes the outcome (auth checks, feature flags, validation, cache hits, retries), with the condition quoted.
3. Every place the request leaves the process: database queries, network calls, file writes, messages published.
4. A short sequence diagram in Mermaid syntax.
5. The direct answer to my question, citing the steps that prove it.
6. Gaps: any step where the code I pasted stops and you'd need another file to be sure. Name the file or symbol you'd need.

Do not fill gaps with plausible framework behavior unless you label it "framework default, verify".

Fill in: FRAMEWORK TRIGGER CODE_PATH QUESTION

Works best when you paste the code in call order. Add the missing files it lists and run it again until the gaps section is empty.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Dig Out the Hidden Business Rules in Legacy Code

Best for: Making the implicit rules in old code explicit before a rewrite

Act as an engineer preparing to rewrite or heavily change legacy code. Before anyone touches it, I need every business rule it quietly enforces written down, because nobody has documented them.

Language: {{LANGUAGE}}
Legacy code: {{LEGACY_CODE}}
What the business thinks this code does: {{STATED_PURPOSE}}

Do this:
1. List every rule the code enforces, one per row: the rule in plain English, the line(s) that enforce it, and the input that triggers it. Include magic numbers, date or timezone handling, rounding, special-cased customer IDs or codes, and default values.
2. Mark each rule: Matches stated purpose / Not mentioned in stated purpose / Contradicts stated purpose.
3. For each "Not mentioned" or "Contradicts" row, write the question I should ask the business owner.
4. Suggest one characterization test per rule (input and the output the code currently produces), so a rewrite can prove it kept or deliberately changed each one.
5. Flag code that looks dead, but say what would prove it dead (logs, metrics, a search for callers) rather than assuming.

Report what the code does, not what it should do. Don't fix anything yet.

Fill in: LANGUAGE LEGACY_CODE STATED_PURPOSE

Pair this with the characterization-test prompt in the Testing section before you refactor. Take the questions list to whoever owns the process.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Write a README for an Existing Project

Best for: Turning tribal setup knowledge into a README that works on a clean machine

You are a developer-experience engineer writing the README a new teammate will actually use on their first day. Base it only on the material I give you.

Project name: {{PROJECT_NAME}}
Build, manifest and config files (package.json, pyproject.toml, Makefile, Dockerfile, CI config, .env.example; with secrets removed): {{BUILD_FILES}}
File tree: {{FILE_TREE}}
Notes from me (what it's for, who uses it, known quirks): {{MY_NOTES}}

Write a README with these sections:
1. What it is: two sentences, no marketing.
2. Prerequisites with versions, taken from the files (runtime, package manager, database, services).
3. Setup: copy-paste commands from clone to running locally. Use only commands the files support.
4. Running tests, linting and formatting.
5. Configuration: a table of environment variables from .env.example with a description and whether each is required. Never put real values in it.
6. Project layout: the five most important directories.
7. Common problems and fixes, from my notes.
8. How to contribute (branching, PR checks), if the CI config shows it.

Where a step can't be confirmed from the files, write it with a TODO comment (an HTML comment, <!-- TODO: confirm -->) rather than guessing. Output Markdown only.

Fill in: PROJECT_NAME BUILD_FILES FILE_TREE MY_NOTES

Run the setup commands yourself in a clean checkout before you commit the README; that's the test. Remove secrets from .env files first.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Learn a New Language by Mapping From One You Know

Best for: Getting productive in a second language fast without a beginner course

Act as a senior engineer who writes both {{KNOWN_LANGUAGE}} and {{LANGUAGE}} professionally. I'm fluent in {{KNOWN_LANGUAGE}} and need to become productive in {{LANGUAGE}} quickly for this job: {{GOAL}}.

Teach me by contrast, not from zero:
1. The ten idioms I'll use every day, each as a side-by-side pair: a short {{KNOWN_LANGUAGE}} snippet and the idiomatic {{LANGUAGE}} equivalent. Pick ones relevant to my goal.
2. Five false friends: things that look the same in both languages but behave differently (equality, copying, integer division, string handling, scoping, error handling, async). Show the surprising output for each.
3. The error-handling and null or optional story in {{LANGUAGE}}, compared with mine.
4. Tooling: the standard package manager, formatter, linter and test runner, with the one command for each.
5. One small exercise tied to my goal, with a reference solution hidden under a "Solution" heading so I can try it first.

Use only the standard library unless my goal needs a specific package; if it does, say which and why. Flag anything that changed in recent major versions of {{LANGUAGE}}, and tell me to check the official docs for my version.

Fill in: KNOWN_LANGUAGE LANGUAGE GOAL

Run every snippet; that's how the false friends stick. Ask follow-ups in the same chat, such as 'show me the idiomatic way to do X'.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Debugging From Evidence

Good debugging is a loop: reproduce, form hypotheses, run the cheapest experiment, repeat. These prompts triage a pasted stack trace, rank hypotheses for a bug you can't explain, shrink a bug to a minimal reproduction, and automate git bisect to find the breaking commit. They also cover intermittent bugs and race conditions, works-on-my-machine differences, and a blameless postmortem built from real logs. None of them jumps to a fix before the evidence points to one.

Stack Trace Triage: From Error to Likely Cause

Best for: Getting from a pasted error to a tested fix without guessing

You are a senior {{LANGUAGE}} engineer on call. Triage this error for me the way you would before touching any code.

Full stack trace or error output (with secrets, tokens and personal data removed): {{STACK_TRACE}}
The code at the frames that are in my codebase: {{RELEVANT_CODE}}
What I was doing when it happened, and what I expected: {{CONTEXT}}

Respond with:
1. Plain-English reading of the error: what the runtime is actually complaining about.
2. The frame that matters: the deepest frame in my own code (not the library's) and why the error surfaces there.
3. Up to three candidate causes, most likely first. For each: the evidence in the trace or code that supports it, and the evidence that would rule it out.
4. The quickest check for each cause (a print/log line, a debugger breakpoint, a one-line REPL experiment, or an input to try).
5. Only after that: the most likely fix as a minimal diff, and a regression test that fails before the fix and passes after.

If the trace is truncated or the key frame is in code I didn't paste, stop at step 3 and tell me exactly which file and function to paste next.

Fill in: LANGUAGE STACK_TRACE RELEVANT_CODE CONTEXT

Paste the whole trace, not just the last line; the cause is often in the first frame of your own code. Review and run the fix and its test yourself.

Run in ChatGPT Run in Claude Run in Gemini Prompt page
Example output · Claude (example written by The Prompt Index)
Sample inputs
- STACK_TRACE:
Traceback (most recent call last):
File "/srv/app/repro.py", line 3, in <module>
print(require_fresh_token({"sub": "user_42", "expires_at": "2026-10-28T09:15:00+00:00"}))
File "/srv/app/api/auth/middleware.py", line 9, in require_fresh_token
if is_expired(token):
File "/srv/app/api/auth/tokens.py", line 8, in is_expired
return expires_at <= now
TypeError: can't compare offset-naive and offset-aware datetimes
- RELEVANT_CODE (api/auth/tokens.py):
from datetime import datetime


def is_expired(token, now=None):
"""Return True if the token's expiry time has passed."""
now = now or datetime.utcnow()
expires_at = datetime.fromisoformat(token["expires_at"])
return expires_at <= now
- CONTEXT: Python 3.9 API. Since this morning every authenticated request returns 500. Our identity provider says they "standardized timestamp formats" yesterday. Unit tests still pass.
- LANGUAGE: Python

1. What the error means
Python refuses to compare a datetime that has a time zone attached ("offset-aware") with one that doesn't ("offset-naive"), because it can't know which instant the naive one refers to. Line 8 compares two such values.

2. The frame that matters
tokens.py line 8, `return expires_at <= now`. It's the deepest frame and it's your code. `expires_at` comes from `datetime.fromisoformat("2026-10-28T09:15:00+00:00")`, which is aware because the string ends in +00:00. `now` comes from `datetime.utcnow()`, which is always naive.

3. Candidate causes
a) Most likely: the token issuer started sending an offset ("+00:00") on `expires_at`. Supporting evidence: the provider's format change yesterday, and the failure started on every request at once. Rules it out: an old token payload with no offset that fails the same way (I'd expect it to pass).
b) Your tests pass `now` explicitly, or use offset-less strings, so they never hit the naive `utcnow()` path. That isn't a cause by itself, but it explains why CI is green. Rules it out: a test that calls `is_expired(token)` with no `now`.
c) Unlikely: a caller passes an aware `now` while old tokens are naive. That would fail the other way round, and the trace shows the default path.

4. Quickest checks
- Log `repr(token["expires_at"])` for one request. An offset at the end confirms (a).
- REPL: `datetime.fromisoformat("2026-10-28T09:15:00+00:00").tzinfo` returns UTC, and `datetime.utcnow().tzinfo` returns None.
- Ask the provider whether they may send "Z" instead of "+00:00". `fromisoformat` only accepts "Z" from Python 3.11, so on 3.9 that would fail with a ValueError.

5. Minimal fix and regression tests
```diff
-from datetime import datetime
+from datetime import datetime, timezone
@@
- """Return True if the token's expiry time has passed."""
- now = now or datetime.utcnow()
+ """Return True if the token's expiry time has passed. `now` must be timezone-aware."""
+ now = now or datetime.now(timezone.utc)
expires_at = datetime.fromisoformat(token["expires_at"])
+ if expires_at.tzinfo is None:
+ # ASSUMPTION: timestamps without an offset are UTC. Confirm with the token issuer.
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
return expires_at <= now
```
This also moves you off `utcnow()`, which is deprecated from Python 3.12.

```python
from datetime import datetime, timezone

from api.auth.tokens import is_expired

NOW = datetime(2026, 10, 28, 9, 0, tzinfo=timezone.utc)


def test_default_clock_handles_offset_aware_expiry():
# Regression: the production path (no `now` passed) raised TypeError before the fix.
assert is_expired({"expires_at": "2999-01-01T00:00:00+00:00"}) is False


def test_offset_aware_expiry_in_future_is_not_expired():
assert is_expired({"expires_at": "2026-10-28T09:15:00+00:00"}, now=NOW) is False


def test_offset_aware_expiry_in_past_is_expired():
assert is_expired({"expires_at": "2026-10-28T08:59:59+00:00"}, now=NOW) is True


def test_non_utc_offset_is_compared_correctly():
# 10:30 at +02:00 is 08:30 UTC, so already expired at 09:00 UTC.
assert is_expired({"expires_at": "2026-10-28T10:30:00+02:00"}, now=NOW) is True


def test_timestamp_without_offset_is_treated_as_utc():
assert is_expired({"expires_at": "2026-10-28T09:15:00"}, now=NOW) is False


def test_expiry_exactly_now_counts_as_expired():
assert is_expired({"expires_at": "2026-10-28T09:00:00+00:00"}, now=NOW) is True
```
Run against the old code, `test_default_clock_handles_offset_aware_expiry` and `test_timestamp_without_offset_is_treated_as_utc` fail with the same TypeError. Against the fix, all six pass. The first test is the one that matters: tests that always pass `now` would have stayed green with the bug in place.
Confirm the UTC assumption for offset-less timestamps before shipping. If the issuer never sends them, raise an error instead of guessing.

Hypothesis-Driven Debugging for a Bug You Can't Explain

Best for: Breaking out of guess-and-check on a stubborn bug

Act as a principal engineer coaching me through a bug using the scientific method. I've been staring at it too long and my guesses have stopped working.

System and stack: {{FRAMEWORK}}
Symptom (expected vs actual, exact messages, how often): {{SYMPTOM}}
What I've already tried and what happened each time: {{ALREADY_TRIED}}
What changed recently (deploys, dependencies, config, data, traffic): {{RECENT_CHANGES}}
Relevant code or logs: {{EVIDENCE}}

Do this:
1. Restate the bug as a precise, testable statement.
2. List five or more hypotheses across different layers (code, data, config, environment, concurrency, dependencies). For each, say what it predicts I would observe.
3. Use my "already tried" results to strike out hypotheses they've ruled out, and say why.
4. Rank the rest by likelihood × cheapness to test.
5. For the top three, design one experiment each: the exact change or command, and the result that would confirm it versus kill it.
6. Tell me what to log or capture before the next occurrence if the bug is intermittent.

Don't propose a fix yet. I'll come back with results and we'll iterate.

Fill in: FRAMEWORK SYMPTOM ALREADY_TRIED RECENT_CHANGES EVIDENCE

Reply with each experiment's result in the same chat. Most bugs fall within two or three rounds once the guesses are written down.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Build a Minimal Reproduction Case

Best for: Shrinking a bug to something you (or a library maintainer) can actually fix

You are a senior engineer who files excellent bug reports. Help me shrink this bug to the smallest self-contained reproduction, so I can debug it in isolation or report it upstream.

Language / framework and versions: {{LANGUAGE}} / {{FRAMEWORK}}
The code where it happens (as much as needed): {{CODE}}
How I trigger it now: {{CURRENT_STEPS}}
Expected vs actual: {{EXPECTED_VS_ACTUAL}}

Do this:
1. Identify what is probably essential to the bug and what is probably incidental (database, network, framework setup, unrelated fields).
2. Propose a reduction plan: the order in which to remove pieces, and after each removal check that the bug still happens. If it stops, the last piece removed matters.
3. Write a first-draft minimal reproduction: a single file using only the standard library plus the one library involved, with hard-coded inputs, under about 40 lines, that prints or asserts the wrong result.
4. List the exact versions I should record and the command to capture them.
5. Draft the issue text: title, environment, steps, expected, actual, and the reproduction.

Mark anything in your draft reproduction that you couldn't confirm from my code with a comment like `# ASSUMPTION:`. I'll run it and tell you whether it reproduces.

Fill in: LANGUAGE FRAMEWORK CODE CURRENT_STEPS EXPECTED_VS_ACTUAL

Run the draft repro before you trust it. If the bug disappears when isolated, that's a clue: the cause is in something you removed.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Find the Breaking Commit With git bisect

Best for: Finding which change caused a regression in a long history

Act as a senior engineer who uses `git bisect` routinely. Help me find the commit that introduced a regression, automated if possible.

Language and test tooling: {{LANGUAGE}}
The regression (what used to work, what happens now): {{REGRESSION}}
A commit or tag I know was good, and one I know is bad: {{GOOD_AND_BAD}}
How I currently check for the bug (manual steps or a command): {{CHECK_METHOD}}

Give me:
1. The exact bisect commands to start, mark good and bad, and finish (including `git bisect reset`).
2. A check script for `git bisect run`: exit 0 when the commit is good, 1 when bad, and 125 to skip commits that can't be built or tested. Reinstall dependencies only if needed.
3. An estimate of how many steps the bisect will take, from the commit count (I'll paste `git rev-list --count GOOD..BAD` if you ask).
4. Pitfalls: flaky checks giving wrong answers, merge commits, database migrations or generated files that differ between commits, and how to handle each.
5. What to do once it names a commit: how to read the diff for the cause, and how to confirm by reverting that commit alone on the bad version.

Keep the check script short and safe: no pushing, no destructive commands, and nothing that touches shared environments.

Fill in: LANGUAGE REGRESSION GOOD_AND_BAD CHECK_METHOD

Run the check script by hand on the known-good and known-bad commits first. If it doesn't give 0 and 1 there, bisect will mislead you.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Diagnose an Intermittent Bug or Race Condition

Best for: Flaky behavior, race conditions and 'only in production' bugs

You are a senior engineer experienced with concurrency, async code and distributed systems. Help me pin down a bug that happens only sometimes.

Language / framework: {{LANGUAGE}} / {{FRAMEWORK}}
Symptom and frequency (e.g. 1 in 50 runs, only under load, only in CI): {{SYMPTOM}}
Code involved (shared state, async/await, threads, locks, queues, caches, timers): {{CODE}}
Environment differences where it does and doesn't happen: {{ENVIRONMENTS}}

Do this:
1. List the sources of non-determinism visible in this code: shared mutable state, check-then-act sequences, ordering assumptions, timeouts and retries, unawaited tasks, test order dependence, clock and timezone use, random seeds.
2. For each, describe a concrete interleaving or timeline that would produce my symptom, step by step.
3. Rank them by how well they explain the frequency and environments I described.
4. For the top two, show how to make the bug reproduce reliably (forced delays, a stress loop, fixed seeds, running tests in random or reversed order) so it can be fixed with confidence.
5. Then the fix options, with trade-offs (lock, atomic operation, idempotency key, redesign), and a test that would have caught it.

Don't suggest "add a sleep" or "increase the timeout" as a fix. If it hides the symptom only, say so.

Fill in: LANGUAGE FRAMEWORK SYMPTOM CODE ENVIRONMENTS

Making the bug reproducible on demand is the real win here; fix it only once you can trigger it at will.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Works on My Machine: Diff the Two Environments

Best for: Bugs that only appear in CI, staging or a colleague's laptop

Act as a senior DevOps-minded engineer. The same code behaves differently in two environments, and I need a systematic comparison rather than guesswork.

Stack: {{FRAMEWORK}}
Environment A (works) details: {{ENV_A}}
Environment B (fails) details: {{ENV_B}}
Failure in B (error, logs, behavior): {{FAILURE}}

The details for A and B can include OS and architecture, runtime and package versions (lockfile or `pip freeze`/`npm ls` output), environment variable names (values redacted), config files, container base image, locale and timezone, file system case sensitivity, network access, and data.

Do this:
1. Build a comparison table of every dimension above, marking Same / Different / Unknown.
2. For each "Different", say whether it could plausibly cause this specific failure and how.
3. Give me commands to fill in the "Unknown" rows on both machines.
4. Rank the top three suspects and give a quick experiment for each (e.g. pin the version, set the variable, run B's container locally).
5. Recommend one change that would stop this class of drift recurring: pinned lockfile, dev container, version file, or a CI check.

Never ask me to paste secret values; variable names are enough.

Fill in: FRAMEWORK ENV_A ENV_B FAILURE

Paste lockfile diffs rather than whole lockfiles where you can. Redact every secret value before pasting environment details.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Incident Timeline and Blameless Postmortem From Logs

Best for: Writing up an outage quickly without blame or invented causes

You are an SRE writing a blameless postmortem. Turn my raw notes and logs into a clear timeline and a write-up the team can learn from.

Service: {{SERVICE}}
Raw logs, alerts and chat excerpts with timestamps (personal data and secrets removed): {{RAW_EVIDENCE}}
What we know about impact (users, duration, data, money): {{IMPACT}}
What we did to mitigate and fix: {{ACTIONS}}

Produce:
1. A timeline table in UTC: time, event, source (which log or message). Mark detection, escalation, mitigation and resolution moments. Where timestamps conflict or are missing, say so; don't smooth them over.
2. Time to detect and time to mitigate, calculated from the table, with the calculation shown.
3. Root cause and contributing factors, phrased about systems and processes, never about individuals.
4. What went well, and where we got lucky.
5. Action items: a table with action, type (prevent / detect / mitigate), and a suggested owner role, kept to the five that matter most.
6. Open questions the evidence doesn't answer.

Only state causes the evidence supports. Label anything else "suspected" and list what would confirm it.

Fill in: SERVICE RAW_EVIDENCE IMPACT ACTIONS

Paste log lines with their original timestamps and time zones. Review the root-cause wording with the people involved before you publish.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Design & Build From a Spec

Code written from a vague ticket gets rewritten. These prompts turn a ticket into acceptance criteria and open questions, compare design options with a trade-off table, record the decision in an ADR, and design an HTTP API contract before the handlers exist. For the build itself, there's a tests-first implementation prompt and one for a single function written to a strict contract. A lightweight threat model catches security flaws while they are still cheap to fix.

Turn a Vague Ticket Into a Buildable Spec

Best for: Refining a one-line ticket before you estimate or build

Act as a senior engineer in a refinement session. This ticket is too vague to build safely. Turn it into a spec I can implement and test, and surface every decision someone has to make first.

Ticket text: {{TICKET}}
System context (stack, relevant existing features, constraints): {{SYSTEM_CONTEXT}}
Who asked for it and why, if known: {{REQUESTER_GOAL}}

Produce:
1. The problem in one sentence, and the user-visible outcome.
2. In scope and explicitly out of scope.
3. Acceptance criteria as Given/When/Then scenarios, including at least two edge cases and one failure case (invalid input, permission denied, dependency down).
4. Open questions, each with a recommended default answer so work isn't blocked, and who should decide.
5. Non-functional requirements this ticket implies: performance, security and privacy, accessibility, observability, migration of existing data.
6. A rough breakdown into small tasks that can each be merged on their own.
7. Risks: what could make this take three times longer than it looks.

Don't invent requirements the ticket doesn't support. Put any you think are likely under "Open questions" instead.

Fill in: TICKET SYSTEM_CONTEXT REQUESTER_GOAL

Send the open questions to the requester before you start; the defaults let you begin while you wait.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Compare Two Design Options With a Trade-off Table

Best for: Making a design decision you can defend later

You are a staff engineer helping me choose between design options. I want an honest comparison, not a sales pitch for either.

The problem we're solving: {{PROBLEM}}
Option A: {{OPTION_A}}
Option B: {{OPTION_B}}
Constraints (team size and skills, deadline, budget, scale, existing stack, compliance): {{CONSTRAINTS}}

Do this:
1. Restate the decision and the criteria that should drive it, given my constraints. Weight the criteria and explain the weights.
2. A trade-off table scoring each option on each criterion (1–5) with a one-line reason per cell. Include complexity to build, operational burden, failure modes, performance at our scale, cost, ease of change later, and fit with the team's skills.
3. Reversibility: how expensive would it be to switch later if we chose wrong? This often matters more than the scores.
4. A third option if one is clearly better than both (including "do the simplest thing now").
5. A recommendation, and the specific evidence that would change my mind.
6. The cheapest spike or prototype that would reduce the biggest uncertainty, scoped to a day or two.

Avoid generic claims ("X scales better") unless you tie them to our numbers. Where you lack data, name the measurement I should take.

Fill in: PROBLEM OPTION_A OPTION_B CONSTRAINTS

Give real numbers in the constraints (requests per second, data size, team size); without them every comparison turns generic.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Write an Architecture Decision Record (ADR)

Best for: Recording why a technical decision was made, for future teammates

Act as a senior engineer who keeps clean decision records. Write an Architecture Decision Record from my notes, in the widely used Context / Decision / Consequences format.

Title of the decision: {{DECISION_TITLE}}
Context and forces (what prompted it, constraints, who is affected): {{CONTEXT}}
Options considered, with notes on each: {{OPTIONS}}
What we decided and the main reasons: {{DECISION}}

Write the ADR with:
1. Title, status (Proposed), and date placeholder.
2. Context: the situation and forces in neutral language, so a reader in two years understands why this was hard.
3. Considered options: each with its main pros and cons, fairly stated.
4. Decision: what we will do, in active voice ("We will…").
5. Consequences: positive, negative, and the new risks or work this creates. Be specific; every real decision has a downside.
6. Revisit triggers: the conditions under which this decision should be reopened.

Keep it under about 600 words. Use only facts from my notes; where the reasoning has a gap, insert a bracketed question like [Why was option C rejected?] rather than inventing a reason. Output Markdown.

Fill in: DECISION_TITLE CONTEXT OPTIONS DECISION

Store ADRs in the repo (for example docs/adr/0007-title.md) so they're reviewed like code. Answer the bracketed questions before marking it Accepted.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Design an HTTP API Contract Before Writing Code

Best for: Agreeing an API shape with frontend or partner teams before building

You are a senior API designer. Design the HTTP API contract for this feature before anyone writes the handlers.

Feature and its users: {{FEATURE}}
Resources and data involved (fields, relationships): {{DATA_MODEL}}
Existing API conventions to follow (naming, auth, error format, versioning), or "none": {{CONVENTIONS}}
Expected scale and clients (web, mobile, third parties): {{CLIENTS}}

Produce:
1. A table of endpoints: method, path, purpose, auth required, idempotent (yes/no).
2. Request and response bodies for each, as JSON examples with field types and which fields are required.
3. Error responses: status codes per endpoint and one consistent error body shape.
4. Pagination, filtering and sorting for list endpoints, with the reasoning for cursor versus offset.
5. Safe retries: which writes need idempotency keys, and how duplicates are detected.
6. Versioning and how a breaking change would be rolled out.
7. Security notes: authorization per endpoint (who may act on whose resources), rate limits, and fields that must never be returned.
8. An OpenAPI 3 YAML skeleton for the two most important endpoints.

Follow my conventions where they exist, even if you would choose differently, and note the disagreement separately.

Fill in: FEATURE DATA_MODEL CONVENTIONS CLIENTS

Review the authorization notes line by line; broken object-level authorization is the most common API security bug. Validate the YAML with an OpenAPI linter.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Tests-First Implementation From a Spec

Best for: Building a feature with tests that actually pin down the behavior

Act as a senior {{LANGUAGE}} engineer who practices test-driven development. Implement this feature tests-first, and show your work in that order.

Spec or acceptance criteria: {{SPEC}}
Test framework and conventions: {{TEST_FRAMEWORK}}
Existing code it must fit into (signatures, types, nearby modules): {{EXISTING_CODE}}

Work in this order:
1. Restate the behavior as a numbered list of test cases: the happy path, boundaries, invalid input, and failure of dependencies. Ask me about any behavior the spec leaves ambiguous before writing code, or state the assumption you're making.
2. Write the tests first, complete and runnable, with clear names that describe behavior.
3. Explain which tests would fail against an empty implementation, and why.
4. Write the simplest implementation that makes the tests pass. No speculative features, no new dependencies.
5. Refactor once for clarity, keeping the tests unchanged.
6. List what the tests do not cover and why.

Use only APIs that exist in the standard library or the code I pasted. If you need something else, stop and ask. I will run the tests myself; mark anything you're unsure would pass.

Fill in: LANGUAGE SPEC TEST_FRAMEWORK EXISTING_CODE

Run the tests before reading the implementation; if they pass against a stub, they're too weak. Review every line before merging.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Implement a Function to a Strict Contract

Best for: Getting one well-specified function written correctly, not a whole module

You are a careful senior {{LANGUAGE}} engineer. Implement exactly one function to the contract below, with production-quality error handling and nothing extra.

Function signature (name, parameters, return type): {{SIGNATURE}}
Behavior, including examples of input and expected output: {{BEHAVIOR}}
Constraints (performance limits, memory, allowed dependencies, language version, style guide): {{CONSTRAINTS}}

Requirements:
1. Validate inputs at the boundary, and fail with clear, specific errors that use the language's idiomatic mechanism.
2. Handle these edge cases explicitly: empty input, a single element, very large input, duplicates, and Unicode or locale issues where text is involved. Say how each is handled.
3. State the time and space complexity and why.
4. Add a short docstring or comment describing the contract, not the obvious mechanics.
5. Provide 6–10 example-based tests covering the examples above plus the edge cases.
6. After the code, list any assumption you made that the contract didn't settle.

Do not change the signature. Do not add logging, configuration, classes or helper modules unless the constraints require them. If the behavior examples contradict each other, point out the contradiction instead of picking one silently.

Fill in: LANGUAGE SIGNATURE BEHAVIOR CONSTRAINTS

Good for utility functions, parsers and calculations. Run the tests, then add your own case from production data before merging.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Threat Model a Feature Before You Build It

Best for: Catching security design flaws before the code exists

Act as an application security engineer running a lightweight threat model on a feature during design, when fixes are cheap.

Feature description and user flow: {{FEATURE}}
Architecture (components, data stores, third-party services, trust boundaries): {{ARCHITECTURE}}
Data handled and its sensitivity (personal data, payments, credentials, files): {{DATA}}

Do this:
1. Draw the data flow as a numbered list: who sends what to which component, and mark each trust boundary crossing.
2. For each boundary, walk through the STRIDE categories (spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege) and list only the threats that genuinely apply.
3. For each threat: a concrete attack scenario, likelihood and impact (low/medium/high) with a reason, and the mitigation to build in.
4. Check specifically for: broken access control between users, injection into queries or shell commands, unsafe file upload, server-side request forgery, secrets in code or logs, and missing rate limits.
5. A short list of security test cases to add to the test suite.
6. Residual risks to accept and write down.

Stay concrete to this feature. Skip generic advice that applies to every web app unless it is missing from my design.

Fill in: FEATURE ARCHITECTURE DATA

Run it at design review, then again with the actual diff using the security review prompt in the Code Review section.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Code Review, Security & Pull Requests

Review is where quality is won or lost. These prompts give a diff a senior-level review with severity labels, then run focused passes for security vulnerabilities and performance at your real scale. Others vet a new package for supply-chain risk and review CI pipelines and Dockerfiles. For your own work, there are prompts to self-review a PR before anyone else sees it, and to write the commit message and PR description that get it approved quickly.

Senior Code Review of a Diff With Severity Labels

Best for: Getting a thorough first-pass review before a human reviewer looks

You are a senior {{LANGUAGE}} engineer reviewing a pull request. Review it the way a respected colleague would: specific, prioritized and kind.

What the change is meant to do: {{PR_PURPOSE}}
The diff (unified format, with enough surrounding context): {{DIFF}}
Team conventions or style guide notes: {{CONVENTIONS}}

Review for, in priority order:
1. Correctness: logic errors, unhandled cases, off-by-one, null handling, error paths, concurrency.
2. Does it do what the stated purpose says, and nothing unrelated?
3. Tests: are the important behaviors tested, and could the tests pass with the bug present?
4. Readability: names, function size, comments that explain why, consistency with the codebase.
5. Maintainability: duplication, coupling, hidden assumptions.

For each finding, give: severity (Blocker / Should fix / Nit), file and line, the quoted code, what's wrong, and a concrete suggested change. Group the findings by severity, Blockers first.

End with a two-line summary: approve, approve with changes, or request changes, and the single most important thing to fix. If the diff is too large to review well, say so and suggest how to split it. Only comment on code in the diff.

Fill in: LANGUAGE PR_PURPOSE DIFF CONVENTIONS

Treat the review as a second opinion, not a gate: you're still accountable for the merge. Never paste diffs that contain secrets.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Security Review of a Code Change

Best for: A focused security pass on risky changes before merge

Act as an application security engineer reviewing a code change for exploitable vulnerabilities. Be precise; false alarms waste the team's trust.

Language / framework: {{LANGUAGE}} / {{FRAMEWORK}}
The diff or code: {{CODE}}
Context: who can reach this code (anonymous users, logged-in users, admins, internal services) and what data it touches: {{CONTEXT}}

Check specifically for:
1. Injection: SQL, NoSQL, shell commands, template injection, path traversal, unsafe deserialization.
2. Broken access control: can user A read or change user B's data? Are authorization checks done on the server, for every object?
3. Authentication and session issues, CSRF on state-changing requests.
4. Cross-site scripting: output encoding in HTML, attributes, URLs and JavaScript contexts.
5. Server-side request forgery and unvalidated redirects.
6. Secrets: hard-coded keys, tokens or passwords; secrets or personal data written to logs or error messages.
7. Unsafe defaults: debug mode, permissive CORS, weak crypto, missing rate limits on sensitive endpoints.

For each real finding: severity (Critical / High / Medium / Low), the quoted line, an example attack input or request, the impact, and the fixed code. Separately, list "Worth checking" items you can't confirm from this code, with what to check. If you find nothing serious, say so plainly.

Fill in: LANGUAGE FRAMEWORK CODE CONTEXT

Use on any change that touches auth, payments, file handling, user input or outbound requests. If a real key appears in the code, rotate it; deleting it isn't enough.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Performance Review: Find the Expensive Lines

Best for: Spotting the slow parts of a change before they reach production

You are a senior engineer who specializes in performance. Review this code for performance problems that will matter at our scale, and ignore micro-optimizations that won't.

Language / framework: {{LANGUAGE}} / {{FRAMEWORK}}
Code: {{CODE}}
Realistic scale (rows, requests per second, payload sizes, how often this runs): {{SCALE}}

Look for:
1. Algorithmic complexity: nested loops over large collections, repeated linear searches, sorting inside loops. State the complexity before and after any fix.
2. N+1 queries and chatty I/O: queries or network calls inside loops, missing batching, missing pagination.
3. Unbounded memory: loading whole tables or files, growing caches with no eviction, large string concatenation in loops.
4. Blocking calls on async or request threads.
5. Repeated work that could be cached or computed once, with the invalidation risk stated.
6. Database: missing indexes implied by the queries, SELECT *, functions on indexed columns.

For each finding: the quoted code, why it's slow at the stated scale (rough numbers), the fix, and how to measure the improvement (benchmark or profiler command). Rank by expected impact.

Don't recommend a change without saying how to verify it. If the code is fine at this scale, say so.

Fill in: LANGUAGE FRAMEWORK CODE SCALE

Profile before and after; an estimate is a hypothesis, not a result. Give honest scale numbers or the review will chase the wrong lines.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Vet a New Dependency Before You Add It

Best for: Deciding whether a new library is worth the long-term risk

Act as a senior engineer responsible for supply-chain hygiene. I want to add a third-party package. Help me decide whether it's worth the risk and cost, using evidence I gather, not your memory of the package.

Package name and the version I'd install: {{PACKAGE}}
What I need it for: {{NEED}}
Information I gathered (repository page, release history, open issues, license, download stats, maintainers, dependency tree output): {{GATHERED_INFO}}

Do this:
1. Could the need be met with the standard library or a dependency we already have? Show roughly how much code that would be.
2. Assess from my info: maintenance activity, number of maintainers, release cadence, open security advisories, license compatibility with commercial use, and size of its transitive dependency tree.
3. Red flags: a recently changed maintainer, install scripts, a name that's one character away from a popular package, very new package with sudden popularity, or abandoned repository.
4. A verdict: Adopt / Adopt with pinning and monitoring / Avoid, with reasons.
5. If adopting: how to pin it, which automated audit to run, and how to wrap it so it's easy to replace.

If my gathered info doesn't cover a point, say "Not provided" and tell me where to look. Don't rely on what you remember about this package; it may be out of date.

Fill in: PACKAGE NEED GATHERED_INFO

Check that the package name is spelled exactly right before installing; AI assistants sometimes suggest packages that don't exist, and attackers register those names.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Self-Review Your Own Pull Request Before Asking Others

Best for: Cleaning up your PR before a teammate sees it

You are a senior engineer helping me get my pull request ready so reviewers can approve it quickly. Act as the tough first reviewer I'd rather hear from privately.

What my change does and why: {{PR_PURPOSE}}
The full diff: {{DIFF}}
How I tested it: {{HOW_TESTED}}

Check and report:
1. Leftovers: debug prints, commented-out code, TODOs without a ticket, temporary hacks, console logs, focused or skipped tests, and secrets or local paths.
2. Scope creep: changes unrelated to the stated purpose that should be a separate PR.
3. Missing pieces: tests for new branches, docs or changelog updates, migrations, config or feature-flag entries, and error handling on new I/O.
4. Risky spots a reviewer will ask about, with the answer I should pre-empt in the PR description.
5. Whether my testing actually exercises the change, and one more test or manual check to run.
6. Whether the diff should be split, and how.

Output a checklist I can tick through, ordered by what would most likely block approval. Quote the line for every item. Don't rewrite my code; just tell me what to fix.

Fill in: PR_PURPOSE DIFF HOW_TESTED

Run it right before you open the PR. Fixing these yourself is faster than a review round-trip.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Write a Commit Message From a Diff

Best for: Clear commit history without spending ten minutes per message

Act as a senior engineer who writes commit messages that future maintainers thank them for. Write the message for this change.

The staged diff (output of `git diff --staged`): {{DIFF}}
Why I made the change (ticket, bug, motivation): {{WHY}}
Convention to follow, e.g. Conventional Commits, or "plain": {{CONVENTION}}

Rules:
1. Subject line: imperative mood, at most 50 characters where possible and never over 72, no trailing period. Use the type and scope prefix only if my convention calls for it.
2. Blank line, then a body wrapped at 72 characters that explains why the change was needed and what approach was taken. Don't narrate the diff line by line.
3. Mention any behavior change, migration, or breaking change explicitly (with a BREAKING CHANGE footer if using Conventional Commits).
4. Add a footer for the issue reference if I gave one.
5. If the diff contains several unrelated changes, say so and propose how to split it into separate commits, with a message for each.

Give the final message in a code block, ready to paste. Base the "why" only on what I told you; if I gave no reason, write the body around the observable change and add [reason?] where the motivation belongs.

Fill in: DIFF WHY CONVENTION

Read the message against the diff before committing; the AI can misread what changed. Strip secrets from the diff before pasting.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Write a Pull Request Description Reviewers Can Act On

Best for: Getting a PR reviewed quickly and correctly

You are a senior engineer writing a pull request description that gets a fast, focused review.

The diff or a summary of changed files: {{DIFF}}
The ticket or problem being solved: {{TICKET}}
How I tested it, including commands and screenshots I can attach: {{TESTING}}
Anything risky or that I want specific feedback on: {{CONCERNS}}

Write the description with these headings:
1. Summary: two or three sentences on what changes for users or the system, and why.
2. Changes: a short bullet list grouped by area, focused on decisions rather than file names.
3. How to review: the order to read files in, and what to look at closely.
4. Testing: what was tested and how; what wasn't, and why.
5. Risk and rollout: blast radius, feature flags, migrations, backward compatibility, and how to roll back.
6. Questions for reviewers, from my concerns.

Keep it under about 300 words. Don't claim tests or checks I didn't list. If the diff includes changes the ticket doesn't explain, list them under "Also in this PR" so reviewers aren't surprised.

Fill in: DIFF TICKET TESTING CONCERNS

Paste the ticket text, not just its number, so the summary explains the why. Attach screenshots for UI changes yourself.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Review a CI Pipeline or Dockerfile for Speed and Safety

Best for: Faster, safer builds and smaller, more secure container images

Act as a senior platform engineer reviewing build and delivery configuration. Review this file for correctness, security, speed and reproducibility.

File type and platform (GitHub Actions, GitLab CI, Jenkinsfile, Dockerfile, docker-compose): {{CONFIG_TYPE}}
The file (secrets already replaced with REDACTED): {{CONFIG_FILE}}
What it is supposed to do and what currently annoys us (slow builds, flaky steps, huge images): {{GOALS_AND_PAINS}}

Check for:
1. Security: secrets echoed into logs or baked into image layers, third-party actions or base images referenced by a moving tag instead of a pinned version or digest, overly broad token permissions, containers running as root, untrusted pull-request code running with access to secrets.
2. Reproducibility: unpinned tool and base-image versions, installs without a lockfile, steps that depend on the network at run time.
3. Speed: missing dependency caches, Docker layer order that busts the cache on every change, jobs that could run in parallel, oversized build contexts (a missing .dockerignore).
4. Correctness: steps that can fail silently, missing failure conditions, and deploy steps without a branch or environment guard.

For each finding: severity, the quoted line, why it matters, and the corrected snippet. Then show the full revised file. Only use syntax valid for the platform named; if unsure whether an option exists, say "check the docs".

Fill in: CONFIG_TYPE CONFIG_FILE GOALS_AND_PAINS

Test the revised pipeline on a branch before merging it. If a secret was ever printed in a CI log, rotate it.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Refactoring, Performance & Upgrades

Refactoring is safe when behavior is pinned by tests and the steps are small. These prompts plan a refactor as separately mergeable steps, split a long function without changing what it does, and remove dead code and stale feature flags on evidence rather than hunches. They also cover optimizing from profiler output, planning a major framework upgrade from the real migration guide, and porting code to another language without losing behavior.

Plan a Behavior-Preserving Refactor in Small Steps

Best for: Cleaning up risky code without a big-bang rewrite

Act as a senior {{LANGUAGE}} engineer who refactors production code without breaking it. Plan this refactor as small, safe, separately mergeable steps.

The code to refactor: {{CODE}}
What's wrong with it today (hard to test, duplicated, slow to change, confusing): {{PROBLEMS}}
The target shape, if I have one in mind: {{TARGET}}
Current test coverage of this code: {{TEST_COVERAGE}}

Produce:
1. A safety net first: which behaviors must be pinned by tests before any change, and the tests to add if coverage is thin.
2. A numbered sequence of refactoring steps. Each step must keep behavior identical, be small enough to review in a few minutes, and name the refactoring (extract function, introduce parameter object, replace conditional with polymorphism, move method, inline variable, and so on).
3. For each step: what to change, how to verify it, and whether it can merge on its own.
4. Points where behavior might change by accident (error messages, ordering, rounding, logging, performance), and how to check each.
5. Where to stop: the point where further refactoring isn't worth it for my stated problems.

Show code only for the first two steps, so I can check the approach before you go further. Do not mix refactoring with bug fixes or new features; list any bugs you notice separately.

Fill in: LANGUAGE CODE PROBLEMS TARGET TEST_COVERAGE

Merge each step separately where you can. If a test changes during a refactor step, stop: behavior has changed.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Split a Long Function Without Changing Its Behavior

Best for: Taming a 200-line function so it can be read and tested

You are a senior {{LANGUAGE}} engineer. This function is too long to understand or test. Break it up while keeping its observable behavior exactly the same.

The function and any helpers it uses: {{LONG_FUNCTION}}
How it's called and what callers rely on: {{CALLERS}}
Style constraints (max function length, naming conventions, typing): {{STYLE}}

Do this:
1. Read it and list the distinct responsibilities it currently has, with the line ranges for each.
2. Propose new functions: a name, its parameters, its return value, and the lines it takes over. Prefer pure functions that take inputs and return outputs over ones that mutate shared state.
3. Write the refactored code: the original function becomes a short, readable sequence of calls.
4. Keep the public signature, return values, exceptions raised, and side-effect order identical. Call out anything you couldn't keep identical.
5. Show a before/after comparison of which parts are now unit-testable on their own.
6. Suggest three tests for the newly extracted pieces.

Don't rename public functions, change error messages, or "improve" logic along the way. If you see a bug, report it under "Noticed, not changed" with the line.

Fill in: LANGUAGE LONG_FUNCTION CALLERS STYLE

Run the existing tests before and after; if there aren't any, write characterization tests first (see the Testing section).

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Remove Dead Code and Stale Feature Flags Safely

Best for: Shrinking a codebase without breaking an unknown caller

Act as a senior engineer cleaning up a codebase. I want to delete code that's no longer used, without deleting anything that's quietly still needed.

Language / framework: {{FRAMEWORK}}
The code, flags or endpoints I suspect are dead: {{SUSPECTS}}
Evidence I have (search results for callers, logs, metrics, flag rollout state, git history): {{EVIDENCE}}

Do this:
1. For each suspect, list every way it could still be reached that a plain text search would miss: reflection or dynamic dispatch, string-built names, config files, templates, scheduled jobs, external callers of public APIs, database-stored references, tests.
2. Rate each suspect: Safe to delete / Probably dead, verify first / Still live, with the evidence.
3. For "verify first" items, the cheapest check (a log line or metric for two weeks, a search in other repos, asking a named team role).
4. For feature flags that are fully rolled out, the clean-up: which branch of each conditional to keep, and the flag configuration to remove afterwards.
5. A deletion order with small separate PRs, and what to monitor after each one ships.

Never recommend deleting something because it "looks unused". Tie each verdict to evidence from what I pasted.

Fill in: FRAMEWORK SUSPECTS EVIDENCE

Search every repo and config store you own, not just this one. Watch logs for a release cycle after deleting anything public.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Profile-Led Optimization From Real Measurements

Best for: Making code faster where it actually matters

You are a performance engineer. Optimize this code based on profiler data, not intuition.

Language / runtime: {{LANGUAGE}}
Profiler output (cProfile, py-spy, Chrome DevTools, pprof, perf, or similar), top entries: {{PROFILE}}
The code for the hot paths: {{CODE}}
The goal (latency target, throughput, memory ceiling) and how I'm measuring it: {{GOAL}}

Do this:
1. Read the profile: where is the time or memory actually going? Separate self time from cumulative time. Note anything surprising.
2. Identify the top three opportunities ranked by expected gain against the share of total time, using Amdahl's law to cap the possible speedup for each.
3. For each: the change, why it should help, the risk to correctness, and the trade-off (memory, readability, cache staleness).
4. Write the code for the best opportunity only.
5. A benchmark plan: how to measure before and after with repeated runs and realistic data, and what result would mean the change isn't worth keeping.
6. What not to optimize, and why.

Keep behavior identical and say how to verify that. Don't claim a specific speedup; predict a range and tell me to measure.

Fill in: LANGUAGE PROFILE CODE GOAL

Benchmark with production-like data; optimizing for toy inputs often makes real inputs slower. Keep the change only if the measurement says so.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Plan a Major Version Upgrade of a Framework or Library

Best for: Upgrading React, Django, Spring, Rails, Node or similar without a lost week

Act as a senior engineer leading a major-version upgrade. Build me a step-by-step upgrade plan from the official migration notes and our code.

Package or framework, current version and target version: {{UPGRADE}}
The official changelog or migration guide sections (pasted, since your knowledge may be out of date): {{MIGRATION_NOTES}}
How our code uses it (grep results for imports and key APIs, config files): {{OUR_USAGE}}
Test suite and CI situation: {{TEST_SITUATION}}

Produce:
1. A table of breaking changes from the notes that actually affect us, each with the files affected (from our usage) and the fix.
2. Breaking changes that don't affect us, listed briefly so I know they were checked.
3. Whether to go straight to the target or step through intermediate versions, with reasoning.
4. An order of work: prerequisite upgrades (runtime, peer dependencies), automated codemods if the notes mention them, manual fixes, deprecation warnings to clear first.
5. A verification plan: tests, manual smoke checks, and a canary or staged rollout.
6. A rollback plan.

Base everything on the notes I pasted. If our usage includes an API the notes don't mention, flag it as "check docs" rather than assuming it's unchanged.

Fill in: UPGRADE MIGRATION_NOTES OUR_USAGE TEST_SITUATION

Paste the real migration guide; don't rely on the model's memory of version changes. Clear deprecation warnings on the old version first.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Port Code to Another Language Without Losing Behavior

Best for: Migrating a module or script between languages

You are a senior engineer fluent in both {{SOURCE_LANGUAGE}} and {{LANGUAGE}}. Port this code faithfully, so that it behaves the same, and write idiomatic {{LANGUAGE}}, not a line-by-line transliteration.

Source code: {{SOURCE_CODE}}
Target environment (runtime version, frameworks, libraries allowed): {{TARGET_ENV}}
Known test cases or sample inputs and outputs: {{SAMPLES}}

Do this:
1. Before writing code, list the semantic differences that could change behavior: integer overflow and division, floating-point formatting, string encoding and Unicode, null handling, default sorting stability, date and time zone handling, regex dialect, error handling, and mutability.
2. For each one that applies to this code, say how the port handles it.
3. Write the {{LANGUAGE}} code using its idioms and standard library.
4. Write tests in {{LANGUAGE}} that check the same inputs give the same outputs, using my samples plus edge cases from step 1.
5. List any behavior you deliberately changed (for example, a bug in the original) and any you couldn't reproduce exactly.

Don't add features. If the source relies on a library with no direct equivalent, propose the closest option and explain the differences.

Fill in: SOURCE_LANGUAGE LANGUAGE SOURCE_CODE TARGET_ENV SAMPLES

Run the same inputs through both versions and diff the outputs; that comparison is your real test.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Testing: Unit, Property-Based & Legacy

A test is only useful if it fails when the code is wrong. These prompts write unit tests by equivalence class and boundary, hunt for the inputs most likely to break your code, and generate property-based tests that check rules against many randomly generated inputs (Hypothesis runs 100 per test by default). They also cover characterization tests that pin down legacy code before you change it, fakes and mocks for clocks, APIs and databases, and an audit for tests that can never fail.

Unit Tests by Equivalence Class and Boundary

Best for: Thorough unit tests for a function or class

Act as a senior test engineer. Write unit tests for this code by systematically choosing inputs, not by guessing a few happy paths.

Language and test framework: {{LANGUAGE}} / {{TEST_FRAMEWORK}}
Code under test: {{CODE}}
What it's supposed to do, if different from what the code says: {{INTENDED_BEHAVIOR}}

Do this:
1. List the input equivalence classes (groups of inputs the code should treat the same way), including invalid ones.
2. For each class, identify the boundaries: just below, at and just above each limit, plus empty, single-item and maximum-size cases.
3. Present a test table: case name, input, expected output or error, and which class and boundary it covers.
4. Write the tests in my framework: one behavior per test, descriptive names, arrange-act-assert layout, and parameterized tests where the framework supports them.
5. Flag any case where the code's actual behavior differs from the intended behavior. Write those tests to the intended behavior and mark them as expected to fail now.

Don't mock what you don't need to. Don't test private implementation details; test behavior through the public interface. If expected outputs require calculation, show the calculation so I can check it.

Fill in: LANGUAGE TEST_FRAMEWORK CODE INTENDED_BEHAVIOR

Run the tests and read every expected value; a test with a wrong expectation is worse than none.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Edge-Case Hunt: Inputs Most Likely to Break This Code

Best for: Finding the inputs your happy-path tests missed

You are an adversarial tester whose job is to break code. Find the inputs most likely to make this code crash, hang or quietly return the wrong answer.

Language: {{LANGUAGE}}
Code: {{CODE}}
Where its input comes from (user form, API, file upload, another service, database): {{INPUT_SOURCE}}

Hunt through these categories and list only the ones relevant to this code:
- Empty, null, missing fields, wrong types
- Zero, negative, very large numbers, NaN and infinity, floating-point rounding
- Very long strings, Unicode (emoji, combining characters, right-to-left text), leading and trailing whitespace, case differences
- Dates: time zones, daylight-saving transitions, leap days, end of month, epoch values
- Collections: duplicates, unsorted input, a single element, huge sizes
- Concurrency and repeated calls, partial failures of dependencies
- Malicious input: injection strings, path traversal, oversized payloads

For each edge case: the exact input, what you predict the code does by reading it (quote the line), and the correct behavior. Rank by likelihood × damage. Then write runnable tests for the top eight.

Predictions are hypotheses; label them "predicted" and let the tests decide.

Fill in: LANGUAGE CODE INPUT_SOURCE

Run the tests; some predictions will be wrong, and that's the point. Keep the ones that fail as regression tests after you fix the code.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Property-Based Tests for a Function

Best for: Catching edge cases no one thought to write down

Act as a senior engineer experienced with property-based testing (Hypothesis for Python, fast-check for JavaScript and TypeScript, or the equivalent for {{LANGUAGE}}). Write property tests that check rules which must hold for every valid input, not just a few examples.

Language and property-testing library: {{LANGUAGE}} / {{PBT_LIBRARY}}
Code under test: {{CODE}}
What the function guarantees, in my words: {{GUARANTEES}}

Do this:
1. Identify candidate properties and explain each: round-trips (decode(encode(x)) == x), invariants (output is sorted, length preserved, total unchanged), idempotence (f(f(x)) == f(x)), comparison with a simpler but slower reference implementation, and "never crashes on valid input".
2. Pick the three to five strongest. Avoid properties that merely re-implement the function.
3. Write input generators that cover the real input space, including the awkward parts (empty, duplicates, extreme values, Unicode), with any constraints the function requires.
4. Write the property tests, runnable as-is with the stated library.
5. Explain how the library shrinks a failure to a minimal counterexample, and how to save it as a regular regression test.

If a property you'd expect doesn't hold for this code, say so and show the counterexample you suspect.

Fill in: LANGUAGE PBT_LIBRARY CODE GUARANTEES

Run the tests several times; property tests use random inputs, so a pass is evidence, not proof. Turn every counterexample into a fixed regression test.

Run in ChatGPT Run in Claude Run in Gemini Prompt page
Example output · Claude (example written by The Prompt Index)
Sample inputs
- LANGUAGE / PBT_LIBRARY: Python 3.9 / Hypothesis
- CODE (intervals.py):
def merge_intervals(intervals):
"""Merge overlapping or touching closed intervals [start, end]. Returns a sorted list."""
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
merged[-1][1] = end
else:
merged.append([start, end])
return [tuple(iv) for iv in merged]
- GUARANTEES: "Takes closed integer intervals in any order and returns them merged, sorted, with no overlaps. It shouldn't lose or add any coverage."

1. Candidate properties
- Coverage is preserved: the merged output covers exactly the same points as the input. This is the core promise, and it can be checked against a brute-force reference model (expand each interval to its integer points) that is obviously correct for small ranges.
- Sorted and separated: each output interval ends before the next one starts. If two touched or overlapped, they should have been merged.
- Well-formed: start <= end for every output interval.
- Idempotent: merging an already-merged list changes nothing.
- Order-independent: shuffling the input doesn't change the output.
Rejected: "the output has no more intervals than the input". It's true but weak, since it would pass if the function returned [].

2. Chosen: all five above. The reference-model property does most of the work; the others pin down the shape of the output.

3–4. Generators and tests
```python
from hypothesis import given, strategies as st

from intervals import merge_intervals

# Closed intervals on a small integer range, so overlaps and touching ends are common.
interval = st.tuples(st.integers(-50, 50), st.integers(0, 20)).map(lambda t: (t[0], t[0] + t[1]))
interval_lists = st.lists(interval, max_size=30)


def covered_points(intervals):
"""Reference model: the set of integer points the intervals cover (brute force)."""
return {x for start, end in intervals for x in range(start, end + 1)}


@given(interval_lists)
def test_output_is_sorted_and_strictly_separated(intervals):
result = merge_intervals(intervals)
for (s1, e1), (s2, e2) in zip(result, result[1:]):
assert e1 < s2 # touching or overlapping intervals must have been merged


@given(interval_lists)
def test_every_output_interval_is_well_formed(intervals):
assert all(start <= end for start, end in merge_intervals(intervals))


@given(interval_lists)
def test_covers_exactly_the_same_points_as_the_input(intervals):
assert covered_points(merge_intervals(intervals)) == covered_points(intervals)


@given(interval_lists)
def test_merging_is_idempotent(intervals):
once = merge_intervals(intervals)
assert merge_intervals(once) == once


@given(interval_lists)
def test_input_order_does_not_matter(intervals):
assert merge_intervals(intervals) == merge_intervals(list(reversed(intervals)))
```
The generator builds each interval from a start and a non-negative length, so start <= end always holds (the function's precondition). The small range of -50 to 50 makes overlaps, containment and shared endpoints common.

Suspected counterexample: I expect the coverage property to fail. When a later interval sits entirely inside an earlier one, `merged[-1][1] = end` shrinks the merged interval instead of keeping the larger end. Running the tests confirmed it. Hypothesis reported:
Falsifying example: test_covers_exactly_the_same_points_as_the_input(intervals=[(0, 0), (-1, 1)])
Sorted, that's (-1, 1) then (0, 0). The second interval sets the end to 0, so point 1 is lost. Only the reference-model test caught it: the sort, idempotence and order tests all passed on the buggy code. The fix is one line:
```python
merged[-1][1] = max(merged[-1][1], end)
```
With the fix, all five tests pass.

5. Shrinking and regression
When a property fails, Hypothesis searches for a simpler input that still fails (shorter list, smaller numbers) and reports the smallest one it finds. It may report a different but equivalent example on another run; a second run here gave [(0, 2), (1, 1)]. Save it as a fixed test so it runs every time:
```python
def test_contained_interval_does_not_shrink_coverage():
assert merge_intervals([(0, 0), (-1, 1)]) == [(-1, 1)]
```

Characterization Tests for Untested Legacy Code

Best for: Building a safety net before touching code nobody understands

You are a senior engineer about to change legacy code that has no tests. Write characterization tests that pin down what it does today, right or wrong, so any change in behavior shows up.

Language and test framework: {{LANGUAGE}} / {{TEST_FRAMEWORK}}
Legacy code: {{LEGACY_CODE}}
Its dependencies (database, network, clock, files, globals): {{DEPENDENCIES}}

Do this:
1. Find the seams: places where you can control inputs and observe outputs without changing behavior (parameters, injectable dependencies, overridable methods, environment variables). If there are none, suggest the smallest safe change that creates one, and label it clearly as a code change.
2. Choose inputs that exercise each branch. List them in a table with the branch each one reaches.
3. Write the tests so they record current behavior. Where you can't determine the output by reading the code, leave a clear placeholder and tell me to fill it by running the code once (the "golden master" approach).
4. Control non-determinism: freeze the clock, seed randomness, and stub network calls.
5. Mark any behavior that looks like a bug with a comment, but test the current behavior anyway.

Don't refactor the code under test. The point is to capture it as it is.

Fill in: LANGUAGE TEST_FRAMEWORK LEGACY_CODE DEPENDENCIES

Fill the placeholders by running the real code, never by trusting the AI's prediction. Then refactor with the tests green.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Test Code With External Dependencies Using Fakes and Mocks

Best for: Testing code that calls APIs, databases or the clock

Act as a senior {{LANGUAGE}} engineer who writes fast, reliable tests. Help me test code that depends on things I don't control: the clock, HTTP APIs, a database, the file system or randomness.

Test framework: {{TEST_FRAMEWORK}}
Code under test: {{CODE}}
The behaviors I most need to verify, including failures (timeouts, 500 errors, empty results): {{BEHAVIORS}}

Do this:
1. List each external dependency in the code and recommend how to handle it in tests: a real instance (such as an in-memory or containerized database), a fake (a simple working implementation), a stub (canned answers), or a mock (checks calls). Explain the choice for each.
2. If the code is hard to test because a dependency is created inside it, show the smallest refactor that allows it to be injected.
3. Write tests for my behaviors, including at least two failure modes of each dependency.
4. Avoid over-mocking: don't assert on internal call sequences unless the call itself is the behavior (for example, "an email was sent once").
5. Say which risks these tests don't cover and should be covered by an integration or contract test instead.

Use only my framework and the standard library's test helpers unless I approve a new dependency.

Fill in: LANGUAGE TEST_FRAMEWORK CODE BEHAVIORS

Prefer fakes over mocks for anything with logic; tests built on mocks can pass while production breaks.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Audit a Test Suite for Tests That Can't Fail

Best for: Finding out whether your tests actually protect you

You are a senior engineer reviewing a test suite with a mutation-testing mindset: for each test, would it fail if the code were wrong?

Language and framework: {{LANGUAGE}} / {{TEST_FRAMEWORK}}
The tests: {{TESTS}}
The code they test: {{CODE}}

Do this:
1. Flag weak tests: no assertions, assertions only on "not null" or "no exception", asserting what a mock returned, snapshot tests nobody reads, or expected values copied from the code's own output without independent reasoning.
2. Mentally mutate the code: for the five most important lines, describe a plausible bug (flip a comparison, drop a condition, off-by-one, swap arguments, return early) and state which test, if any, would catch it.
3. Find important behaviors with no test at all.
4. Find brittle tests: tests that would break on a harmless refactor because they check implementation details, depend on order, sleep, or share state.
5. Give a prioritized fix list, with rewritten versions of the three weakest tests.

Quote each test by name. Base the mutation analysis on the code shown; if a mutation tool exists for my language (for example mutmut, Stryker or PIT), suggest running it to confirm.

Fill in: LANGUAGE TEST_FRAMEWORK TESTS CODE

Use the mutation list as a to-do list; each uncaught mutation is a bug your suite would let through.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

SQL, Data & Regex

Data code fails quietly: a wrong join returns plausible numbers. These prompts write SQL for a stated dialect with explicit assumptions and sanity checks, read an EXPLAIN plan to fix a slow query, and design a schema around real access patterns. Others plan zero-downtime migrations with expand and contract, write regular expressions with tests and backtracking checks, and build a cleaning script that reports every row it rejects.

Write SQL From a Plain-English Question

Best for: Getting a correct query for a reporting or product question

Act as a senior data engineer who writes correct, readable SQL. Write a query that answers my question against this schema.

SQL dialect and version (PostgreSQL 16, MySQL 8, SQLite, SQL Server, BigQuery, Snowflake…): {{DIALECT}}
Schema (CREATE TABLE statements or a column list with types and keys): {{SCHEMA}}
The question in plain English: {{QUESTION}}
Notes on the data (soft deletes, time zones, test accounts to exclude, known duplicates): {{DATA_NOTES}}

Do this:
1. Restate the question precisely, resolving ambiguity: what counts as a customer, an order or "active"? Which date range, and in which time zone? State each assumption.
2. Write the query using CTEs with meaningful names, explicit JOIN types, and comments on non-obvious lines. Use only tables and columns from the schema.
3. Explain how it handles NULLs, duplicates from joins, ties, and empty groups.
4. Give two sanity-check queries I can run to verify the result (for example, totals that should reconcile, or a count of rows excluded by each filter).
5. Note indexes that would help if this runs often.

If the schema can't answer the question, say exactly which column or table is missing rather than inventing one.

Fill in: DIALECT SCHEMA QUESTION DATA_NOTES

Run the sanity checks before you trust the numbers. Never paste production data containing personal information; the schema and a few fake rows are enough.

Run in ChatGPT Run in Claude Run in Gemini Prompt page
Example output · Claude (example written by The Prompt Index)
Sample inputs
- DIALECT: SQLite 3 (timestamps stored as ISO 8601 text in UTC)
- SCHEMA:
customers(id INTEGER PK, email TEXT UNIQUE, is_test INTEGER 0/1, created_at TEXT)
orders(id INTEGER PK, customer_id INTEGER FK -> customers.id, status TEXT in pending/completed/cancelled/refunded, total_cents INTEGER, created_at TEXT)
- QUESTION: "How many new customers did we get each month in Q3 2026, and what was their average first order?"
- DATA_NOTES: Exclude test accounts (is_test = 1). Only completed orders count as purchases. Report in UTC.

1. The question, made precise
- "New customer" = a non-test customer whose first completed order, across all history, falls in the month. A customer who signed up in Q3 but never completed an order doesn't count. Assumption: you mean buyers, not sign-ups. If you mean sign-ups, group customers.created_at instead.
- "First order" = their earliest completed order. A cancelled or refunded order before it is ignored.
- Q3 2026 = 2026-07-01 00:00 up to but not including 2026-10-01 00:00, UTC.
- Average first order = mean of total_cents for those first orders, shown in currency units with 2 decimals.

2. Query
```sql
-- New customers by month of their first completed order, Q3 2026 (UTC), excluding test accounts.
WITH completed_orders AS (
SELECT o.id, o.customer_id, o.total_cents, o.created_at
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'completed'
AND c.is_test = 0
),
ranked AS (
SELECT
customer_id,
total_cents,
created_at,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY created_at, id -- id breaks ties between orders placed in the same second
) AS order_rank
FROM completed_orders -- rank across ALL history, not just Q3
),
first_orders AS (
SELECT customer_id, total_cents, created_at
FROM ranked
WHERE order_rank = 1
)
SELECT
strftime('%Y-%m', created_at) AS first_order_month,
COUNT(*) AS new_customers,
ROUND(AVG(total_cents) / 100.0, 2) AS avg_first_order_value
FROM first_orders
WHERE created_at >= '2026-07-01' AND created_at < '2026-10-01'
GROUP BY first_order_month
ORDER BY first_order_month;
```

3. NULLs, duplicates and ties
- The schema declares every column used as NOT NULL, so no NULL handling is needed.
- The join to customers is many-to-one, so it can't duplicate orders.
- Ties: two completed orders in the same second would both rank 1 with RANK(). ROW_NUMBER() with `id` as a tiebreaker picks exactly one.
- Empty months simply don't appear. If you need a 0 row, join to a list of the three months.
- The text comparison on created_at only works because every timestamp uses the same ISO format. A value with a "Z" or an offset would compare incorrectly, so check that first.
- The key trap: ranking must happen before the Q3 filter. Filter first and a returning customer's first Q3 order looks like a first-ever order.

4. Sanity checks
```sql
-- Check 1: how many rows each filter removes.
SELECT
COUNT(*) AS all_orders,
SUM(o.status <> 'completed') AS not_completed,
SUM(o.status = 'completed' AND c.is_test = 1) AS completed_by_test_accounts
FROM orders o JOIN customers c ON c.id = o.customer_id;
-- Check 2: customers with a completed order in Q3 whose FIRST completed order was earlier (must not be counted).
SELECT customer_id, MIN(o.created_at) AS first_completed
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'completed' AND c.is_test = 0
GROUP BY customer_id
HAVING MIN(o.created_at) < '2026-07-01'
AND MAX(o.created_at) >= '2026-07-01';
```
On a small test dataset (7 customers, 11 orders), check 1 returned 11 / 2 / 1. Check 2 returned customer 1, whose first completed order was on 2026-06-10, so they're correctly absent from July. The main query returned:
first_order_month new_customers avg_first_order_value
----------------- ------------- ---------------------
2026-07 1 25.0
2026-08 2 70.0
2026-09 1 35.0
Those numbers come from that test data, not your database. In August there are two new buyers: one whose earlier order was cancelled, and one with two orders in the same second (the tiebreaker kept order 107, worth 80.00), so the average is (60.00 + 80.00) / 2 = 70.00.

5. Indexes
If this runs often, use `CREATE INDEX idx_orders_customer_status_created ON orders(customer_id, status, created_at);`. It serves the per-customer ordering in the window function.

Read an EXPLAIN Plan and Fix a Slow Query

Best for: Fixing a query that got slow as the data grew

You are a database performance specialist. Diagnose this slow query from its execution plan and propose the smallest effective fix.

Database and version: {{DIALECT}}
The query: {{QUERY}}
EXPLAIN (ANALYZE if possible) output: {{EXPLAIN_OUTPUT}}
Table sizes, existing indexes, and how often the query runs: {{TABLE_FACTS}}

Do this:
1. Walk the plan from the most expensive node outward. For each costly node, explain in plain English what the database is doing and why: sequential scan, nested loop over many rows, sort spilling to disk, misestimated row counts.
2. Point out mismatches between estimated and actual rows, and what they suggest (stale statistics, correlated columns, functions on columns).
3. Propose fixes in order of least invasive first: rewrite the query, add or change an index (give the exact CREATE INDEX statement and its column order reasoning), update statistics, then schema changes.
4. For each index, state the cost: slower writes, disk space, and lock behavior while it's being created on a live table (and the concurrent-build option if my database has one).
5. Tell me what the new plan should look like if the fix works, so I can confirm it.

Only reference indexes and columns that exist in what I pasted, unless you're proposing a new one.

Fill in: DIALECT QUERY EXPLAIN_OUTPUT TABLE_FACTS

Test index changes on a copy of production-sized data, not an empty dev database; plans change completely with table size.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Design a Database Schema for a New Feature

Best for: Getting a schema right before data makes it hard to change

Act as a senior engineer designing a relational schema. Design the tables for this feature, and show me the decisions you're making so I can challenge them.

Database: {{DIALECT}}
Feature and the main things users do with it: {{FEATURE}}
Existing related tables: {{EXISTING_SCHEMA}}
Expected volumes and the most frequent queries: {{ACCESS_PATTERNS}}

Produce:
1. Entities and relationships in plain English, including cardinality (one-to-many, many-to-many).
2. CREATE TABLE statements with types, primary keys, foreign keys with ON DELETE behavior, NOT NULL and CHECK constraints, unique constraints, and defaults.
3. Indexes driven by the access patterns, with the query each one serves.
4. The decisions, each with the alternative and why you chose this: surrogate versus natural keys, soft versus hard delete, how money and time are stored (integer minor units or decimal; UTC timestamps), enums versus lookup tables, JSON columns versus normalized tables.
5. Data integrity risks the schema can't prevent on its own, and where the application must enforce them.
6. Three sample queries for the main access patterns.

Keep it as simple as the feature allows. If my access patterns are unclear, list the questions that would change the design.

Fill in: DIALECT FEATURE EXISTING_SCHEMA ACCESS_PATTERNS

Load some realistic fake data and run the sample queries before writing the migration.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Zero-Downtime Database Migration Plan

Best for: Changing a busy table's schema without an outage

You are a senior engineer who ships schema changes to live systems without downtime. Plan this migration using the expand-and-contract approach.

Database and how migrations are run (tool, deploy process): {{DIALECT}}
The change I need (rename, split a column, change a type, add a NOT NULL column, move data between tables): {{CHANGE}}
Table size and write traffic: {{TABLE_FACTS}}
How the application is deployed (rolling deploys, several app versions live at once?): {{DEPLOY_SETUP}}

Produce:
1. A phased plan: expand (add new structures, backward-compatible), dual-write or sync, backfill, switch reads, stop writing to the old structure, contract (remove the old structure). For each phase: the SQL, the application change, and what must be true before moving on.
2. Lock risk for each statement on my database at this table size, and the safer variant (online DDL options, building indexes concurrently, batching).
3. A backfill script in batches, with throttling, that can be resumed and run again safely.
4. Verification queries that prove old and new data match before switching reads.
5. A rollback path from each phase.

State which steps are irreversible. Don't assume a statement is non-locking; say "check your version's documentation" where behavior differs between versions.

Fill in: DIALECT CHANGE TABLE_FACTS DEPLOY_SETUP

Rehearse the plan on a production-sized copy. Take a backup and confirm you can restore it before the contract phase.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Write and Test a Regular Expression

Best for: Getting a regex that works, is readable, and won't hang on bad input

Act as a senior engineer who writes readable, safe regular expressions. Build a regex for my matching task and prove it with tests.

Regex flavor or language (Python re, JavaScript, PCRE, Go RE2, POSIX grep): {{REGEX_FLAVOR}}
What to match or extract: {{MATCH_GOAL}}
Examples that must match: {{SHOULD_MATCH}}
Examples that must not match: {{SHOULD_NOT_MATCH}}

Do this:
1. Ask yourself whether a regex is the right tool; if a parser or standard library function is safer (for URLs, email, HTML, JSON, dates), say so first.
2. Write the regex, then a verbose or commented version that explains each part.
3. Explain the anchoring, greediness and flags used, and how it handles Unicode and line breaks in my flavor.
4. Check for catastrophic backtracking (nested quantifiers such as (a+)+) and say whether this pattern is at risk on long input.
5. Write a runnable test in my language that asserts every "should match" and "should not match" example, plus five edge cases you add.
6. List inputs it will still get wrong, honestly.

Use only features my flavor supports. Go's RE2, for example, has no lookbehind.

Fill in: REGEX_FLAVOR MATCH_GOAL SHOULD_MATCH SHOULD_NOT_MATCH

Run the tests; regex behavior differs between flavors in ways that are easy to miss. Add a failing real-world input to the test list whenever you find one.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Clean and Validate a Messy Data File With a Script

Best for: Turning a messy CSV or export into reliable data

You are a senior data engineer. Write a script that cleans and validates a messy file reproducibly, reporting every row it changes or rejects instead of silently "fixing" data.

Language and allowed libraries (e.g. Python with pandas, or the standard library only): {{LANGUAGE}}
File format and a sample of the first 20 rows, with personal data replaced by fake values: {{SAMPLE_ROWS}}
The target format (columns, types, allowed values): {{TARGET_SCHEMA}}
Known problems (mixed date formats, currency symbols, duplicates, encoding, blank rows): {{KNOWN_PROBLEMS}}

The script must:
1. Read with an explicit encoding and delimiter, and never guess silently.
2. Apply each cleaning rule as a named, separate step, with a comment on why.
3. Validate every row against the target schema, writing rejected rows to a separate file with the reason for each.
4. Report counts: rows read, cleaned, rejected per reason, and duplicates removed.
5. Be idempotent: running it on its own output changes nothing.
6. Take input and output paths as arguments, with no hard-coded paths.

After the script, list the assumptions you made about ambiguous values (for example, is 03/04 the 3rd of April or March 4th?) and how to change each one. Include three test rows that exercise the trickiest rules.

Fill in: LANGUAGE SAMPLE_ROWS TARGET_SCHEMA KNOWN_PROBLEMS

Check the rejected-rows file by hand before trusting the clean output. Use fake sample rows; never paste real customer data into a chat.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

AI Coding Agents & Instruction Files

Agentic tools such as Claude Code, Codex and Cursor do their best work with clear instructions and a human reviewing the result. These prompts write an AGENTS.md or CLAUDE.md from your real repository, brief an agent on one task with scope and a definition of done, and review an agent's diff for its typical failure modes. Others turn a repeated workflow into a reusable skill and restart a stalled session cleanly. A short community planning prompt from our library rounds the section off.

Write an AGENTS.md or CLAUDE.md for Your Repository

Best for: Giving Claude Code, Codex, Cursor and similar agents the context they keep missing

Act as a staff engineer writing the instruction file that AI coding agents read before working in a repository: AGENTS.md (read by many tools) or CLAUDE.md (Claude Code). Write it from facts about this repo, not generic advice.

File tree (top levels): {{FILE_TREE}}
Build, test, lint and run commands (from package.json, Makefile, CI config): {{COMMANDS}}
Conventions, architecture rules and things that have gone wrong before: {{CONVENTIONS}}
Areas agents must not touch, and actions that need human approval: {{BOUNDARIES}}

Write the file with these sections:
1. Project overview: three sentences on what this is and how it's laid out.
2. Commands: exact commands to install, build, run a single test, run the full suite, lint and format. Only commands from the material I gave.
3. Code conventions that a linter doesn't already enforce.
4. Architecture rules: what lives where, and dependency directions to respect.
5. Testing expectations: when to add tests and how to run only the relevant ones.
6. Boundaries: files and directories off-limits, no new dependencies without asking, never commit secrets, never run destructive commands (database drops, force pushes, deploys).
7. Definition of done for any task.

Keep it under about 150 lines. Write rules as short imperatives. Leave out anything the agent can learn by reading the code.

Fill in: FILE_TREE COMMANDS CONVENTIONS BOUNDARIES

Commit the file at the repo root and edit it whenever an agent makes the same mistake twice. Keep secrets out of it; it's read into every session.

Run in ChatGPT Run in Claude Run in Gemini Prompt page
Example output · Claude (example written by The Prompt Index)
Sample inputs
- FILE_TREE: tidepool/ (app/api/, app/services/, app/models/, app/db/), migrations/ (Alembic), tests/unit/, tests/integration/, scripts/, Makefile, pyproject.toml, docker-compose.yml, .env.example, .github/workflows/ci.yml
- COMMANDS: Makefile targets: `make setup` (uv sync), `make db-up` (docker compose up -d postgres), `make test` (pytest), `make test-unit` (pytest tests/unit), `make lint` (ruff check . && mypy app), `make fmt` (ruff format .), `make migrate` (alembic upgrade head). CI runs lint, then unit tests, then integration tests against Postgres 16.
- CONVENTIONS: FastAPI + SQLAlchemy 2.0. Route handlers stay thin and call app/services; services never import from app/api. Money is integer cents. All timestamps are timezone-aware UTC. Last month an agent "fixed" a failing integration test by deleting its assertion; another added `requests` when we already use `httpx`.
- BOUNDARIES: Don't edit existing files in migrations/ (add new ones only). scripts/prod_*.py are run by humans only. Never touch .env or anything under infra/. Ask before adding any dependency.

# AGENTS.md

## Project overview
Tidepool is a FastAPI service backed by PostgreSQL 16, using SQLAlchemy 2.0 and Alembic.
HTTP routes live in `app/api/`, business logic in `app/services/`, ORM models in `app/models/`, and database setup in `app/db/`.
Tests are split into `tests/unit/` (no database) and `tests/integration/` (real Postgres via docker compose).

## Commands
- Install: `make setup`
- Start the database: `make db-up`
- Run one test: `uv run pytest tests/unit/test_invoices.py::test_name -q`
- Unit tests: `make test-unit`
- Full suite (needs `make db-up`): `make test`
- Lint and type-check: `make lint`
- Format: `make fmt`
- Apply migrations locally: `make migrate`

## Code conventions
- Keep route handlers thin: validate input, call a service, return the result.
- Store money as integer cents. Never use floats for money.
- Use timezone-aware UTC datetimes only (`datetime.now(timezone.utc)`).
- Use `httpx` for HTTP calls. Do not add `requests` or another HTTP client.

## Architecture rules
- `app/services` must never import from `app/api`.
- Schema changes go in a NEW Alembic migration. Never edit an existing file in `migrations/`.

## Testing
- Add or update a unit test for every behavior change.
- Run the unit tests for the files you touched, then `make lint`, before saying you're done.
- Never delete, skip or weaken an assertion to make a test pass. If a test looks wrong, stop and explain why.

## Boundaries
- Do not touch `.env`, `infra/` or `scripts/prod_*.py`.
- Ask before adding, removing or upgrading any dependency.
- Never commit secrets, tokens or real customer data.
- Never run destructive commands: dropping databases, `git push --force`, deploying, or running anything against non-local hosts.

## Definition of done
- [ ] The change does only what the task asked
- [ ] Tests added or updated, and `make test-unit` and `make lint` pass
- [ ] New migrations, if any, are new files that apply cleanly with `make migrate`
- [ ] Summary lists what changed, what was run, and anything you could not verify

Note: the `uv run pytest` single-test line is inferred from `make setup` calling uv. Confirm it works in your checkout before committing.

Brief a Coding Agent on One Task

Best for: Getting a coding agent to do exactly one task, well

You are a tech lead writing a task brief for an AI coding agent that will work in my repository with file and terminal access. Turn my rough request into a brief the agent can execute without guessing, and that I can check against afterwards.

My rough request: {{REQUEST}}
Relevant files, modules or symbols I know about: {{RELEVANT_FILES}}
Constraints (no new dependencies, keep the public API, performance limits, deadline): {{CONSTRAINTS}}
How I'll judge it done: {{DONE_CRITERIA}}

Write the brief with:
1. Goal: one sentence on the outcome, not the implementation.
2. Context: why this is needed, and the files to read first.
3. Scope: what to change, and an explicit "Do not" list (unrelated refactors, formatting churn, touching tests to make them pass, editing generated files, adding dependencies).
4. Approach: steps, starting with "read and summarize the relevant code, then propose a plan and wait for approval" if the task is risky.
5. Verification: the exact test, lint and build commands that must pass, and any new tests required.
6. Done means: a checklist matching my criteria, plus "report anything you could not verify".
7. Stop and ask if: conditions under which the agent should pause rather than improvise.

Keep the brief under about 300 words, in plain Markdown that any agent or tool will understand.

Fill in: REQUEST RELEVANT_FILES CONSTRAINTS DONE_CRITERIA

Paste the brief as the agent's first message. Review its plan before letting it edit, and review the diff yourself before merging.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Review an AI-Generated Diff Before You Merge It

Best for: Catching the mistakes coding agents make most often

Act as a skeptical senior engineer reviewing a change written by an AI coding agent. Agent-written code has characteristic failure modes; check for those specifically, in addition to normal review.

The task the agent was given: {{TASK_BRIEF}}
The diff it produced: {{DIFF}}
Test and lint output from the agent's run, if any: {{RUN_OUTPUT}}

Check for:
1. Scope: changes outside the task, reformatting churn, renamed things nobody asked to rename.
2. Tests weakened to pass: deleted or skipped tests, loosened assertions, broadened exception catches, mocks that bypass the code under test.
3. Invented APIs: calls to functions, methods, config options or packages that may not exist. List each external call so I can verify it against the real docs or source.
4. Silent failure: errors swallowed, fallback values that hide problems, TODOs left in critical paths.
5. Security: secrets or tokens added, input validation removed, permissions widened, unsafe shell or SQL construction.
6. Claims versus evidence: does the run output support what the agent says it did? Did it actually run the tests?
7. Normal correctness and readability issues.

Give a verdict (merge / fix first / discard and re-brief) and a numbered list of issues with the quoted lines. If you'd re-brief, write the corrected instruction.

Fill in: TASK_BRIEF DIFF RUN_OUTPUT

Re-run the tests yourself rather than trusting the agent's report. Agents can claim success they didn't achieve.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Turn a Repeated Workflow Into a Reusable Agent Skill

Best for: Writing down a team workflow once so every agent follows it

You are an engineer who packages team know-how for AI agents. Turn a workflow I keep explaining into a reusable skill: a SKILL.md file with a name, a short description of when to use it, and step-by-step instructions an agent can follow.

The workflow, as I'd explain it to a new teammate: {{WORKFLOW}}
When it should be used (and when it shouldn't): {{TRIGGERS}}
Commands, scripts, templates or checklists involved: {{ASSETS}}
Mistakes people or agents make when doing it: {{COMMON_MISTAKES}}

Write:
1. YAML front matter with `name` (lowercase, hyphenated) and `description` (one or two sentences that say what it does and when to use it, so the agent can decide when to load it).
2. A short purpose section.
3. Numbered steps, each a concrete action with the exact command or file to use. Put checks after risky steps.
4. A "Pitfalls" section built from the common mistakes.
5. A "Done when" checklist.
6. A list of supporting files the skill should ship with (scripts, templates), with what each contains. Don't invent their contents beyond what I provided.

Keep the main file focused and under about 150 lines. Write instructions an agent can follow without asking me questions.

Fill in: WORKFLOW TRIGGERS ASSETS COMMON_MISTAKES

Keep supporting scripts small and readable, and review them like any code an agent will run on your machine.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

Reset a Coding Agent That's Going in Circles

Best for: Recovering from an agent loop without losing the progress made

Act as a senior engineer rescuing an AI coding session that has stalled: the agent keeps trying similar fixes, the context is cluttered, and it has started undoing its own work. Help me write a clean restart brief for a fresh session.

The original goal: {{GOAL}}
A summary or excerpt of the session (what it tried, errors it hit, files it changed): {{SESSION_EXCERPT}}
Current state of the code (git status / diff summary, which tests pass and fail): {{CURRENT_STATE}}

Do this:
1. Diagnose why it stalled: wrong assumption repeated, missing information, a misleading error, task too big, or conflicting instructions. Quote the evidence from the excerpt.
2. Separate what's been established (facts confirmed by running something) from what was only assumed.
3. Recommend whether to keep the current changes, keep some (name the files), or reset to the last good commit.
4. Write a restart brief for a fresh session: the goal, the established facts, approaches already tried that failed and why, the next approach to try, a smaller first step, and the exact check that proves progress.
5. Tell me what I should investigate or decide myself before restarting, if anything.

Keep the restart brief under about 250 words so it doesn't recreate the clutter.

Fill in: GOAL SESSION_EXCERPT CURRENT_STATE

Start a fresh session with the brief rather than adding it to the stalled one. A clean context often matters more than a better prompt.

Run in ChatGPT Run in Claude Run in Gemini Prompt page

VibeCode Planning — concise version

Best for: Making any coding agent read the code and plan before it edits anything

My goal is to complete the task. First, think it through. Read the relevant files in the codebase intelligently until you have enough context to write a solid plan. When you're sure you know what you need, write a comprehensive plan for how you will tackle it. Don't DO the task, just plan it. Ensure you do not add any scope beyond what I requested.

Vibe code more accurately by asking the LLM to plan what it will do before writing any code. After you run this prompt and it returns a plan, respond with "Implement."

Run in ChatGPT Run in Claude Run in Gemini Prompt page

How to get the best results

  1. Pick the prompt for the job in front of you. Debugging a crash? Start with Stack Trace Triage. About to change code you didn't write? Explain a Function's Contract first.
  2. Fill every {{VARIABLE}} with real material. Paste the actual code, diff, error or schema, and name your language, framework and versions. A prompt without real code in it gets a generic answer.
  3. Never paste secrets. Replace API keys, passwords, tokens, connection strings and customer data with placeholders like REDACTED. Check your employer's policy before you paste proprietary code into any AI tool. If a real key ever ends up in a prompt or a commit, rotate it.
  4. Review and test everything it gives you. Treat AI output as a pull request from a fast but unreliable colleague. Run the tests, read every line, check any API or package it mentions against the official docs, and never merge code you can't explain.
  5. Iterate in the same chat. Many prompts ask questions or list gaps. Answer them, paste the next file they ask for, and run the experiments they suggest.

Using a coding agent? Start with the AGENTS.md prompt, brief each task with Brief a Coding Agent on One Task, and check what comes back with Review an AI-Generated Diff Before You Merge It. To package a workflow you repeat into a reusable agent skill, our Skill Generator turns a description into a spec-valid SKILL.md bundle for Claude Code, Codex CLI and Cursor. You can also browse ready-made skills in the Skills Database.

Take the whole pack with you

Download all 52 prompts as a tidy PDF, or as Markdown you can paste straight into Notion. It needs a free account: no card, and the prompts above stay free to copy either way.

Sign up free to download

Frequently asked questions

What is the best ChatGPT prompt for coding?

There isn't one best prompt. The best results come from prompts that give the model your real code, your language and framework versions, a clear task, and a required output format. Prompts that ask for tests alongside the code, or for hypotheses before a fix, also tend to give answers you can check. Start with the prompt for the task you have, such as Stack Trace Triage for an error or Senior Code Review for a diff, and fill every variable with real material.

Do these prompts work with Claude, Gemini and coding agents like Claude Code, Codex or Cursor?

Yes. The prompts use plain language and Markdown with no model-specific syntax, so they work in ChatGPT, Claude and Gemini chats. They also work as instructions for coding agents. The agents section includes prompts for writing an AGENTS.md or CLAUDE.md file, briefing an agent on a single task, and reviewing the diff an agent produces.

Is it safe to paste my code into ChatGPT or Claude?

Never paste secrets: replace API keys, passwords, tokens, connection strings and personal data with placeholders. For proprietary code, follow your employer's policy and the AI provider's data settings, since some plans and settings use conversations for training and others don't. When in doubt, paste a minimal reproduction instead of the real code.

Can I trust code that AI writes?

Treat it like code from a new teammate: review it, run it, and test it before it ships. AI models can invent functions or packages that don't exist, miss edge cases, or write tests that can't fail. That's why these prompts ask for tests, say UNKNOWN instead of guessing, and include a checklist for reviewing AI-generated diffs. Always check any package name before installing it.

What is an AGENTS.md or CLAUDE.md file?

It's a Markdown file at the root of a repository that tells AI coding agents how to work in it: the commands to build and test, coding conventions, architecture rules, and what they must not touch. AGENTS.md is read by many agent tools, and CLAUDE.md is the equivalent file for Claude Code. The Write an AGENTS.md or CLAUDE.md prompt drafts one from your real repo, and it includes a worked example.

← All prompt packs