06 - Prompt Engineering for IDEs and Code Generation
A prompt for a coding assistant works when it contains what the model cannot work out on its own and when it says how to tell that the job is finished. Magic formulas, roles to play ("you are a senior developer") and section-based structures matter less than you read around, and the few thresholds that circulate about the ideal length of a prompt have no source I was able to open: you will not find them in this article.
What you will find is what the official documentation of Claude Code, Cursor, GitHub Copilot and Windsurf says about how to write instructions, and an experiment I ran: an "optimised" function that on a quick read is correct and yet changes the result, discovered only by a check that the prompt should have asked for.
Then we move on to
persistent instruction files (CLAUDE.md, AGENTS.md, Cursor rules, Copilot
instructions), with a script that checks how well they match the repository. This is the sixth article in the series: the criterion
"who reads the diff" is in the first article, and here
it is taken for granted.
What to put in a prompt: what the model cannot read
The Claude Code documentation, in its page on best practices, starts from a fact: the assistant begins every task by reading your code, and finds the file structure, the conventions and the test framework on its own. The advice it draws is to write only what cannot be found by reading the repository, or what would have to be rediscovered in every session.
The test it proposes is two questions: could it find this by reading the code? would it actually go and look?
If both answers are yes, that line is noise. It follows that the classic prompt, which opens with
"Stack: TypeScript, Node 22, Express", largely repeats the package.json.
What is really needed is shown by the examples on the same page. Instead of "fix the login bug" you write
(quoting) that users report login fails after the session times out, that the place to look is the token
refresh in src/auth/, and that you should write a failing test that reproduces it first and then fix it. Instead of
"add a calendar widget" you ask to follow the pattern of an existing widget, with no new libraries. Inside
those examples there are three things that cannot be read in the repository:
- Missing information: the decision taken in a meeting, the environment variable the integration tests need, the choice between two equally reasonable approaches.
- A perimeter: which function or which folder, and what must not be touched (the public signature, the dependencies).
- A check with a yes or no outcome: a test, the exit code of a build, a linter, a script that compares the output with a known result.
The third item is the one most often skipped, and it is the one the documentation weighs most. Among the causes of a session that goes wrong it lists the case in which the assistant declares it has finished and it is not true, usually because it had nothing to run that would tell it: it stops when the job "looks finished", and you end up being the test suite.
With a check that returns pass or fail, the assistant can reread the output, correct and try again on its own. The same page adds a useful warning for whoever reviews: ask for the evidence (the command that was run and its output), because "all tests pass" said on its own tells you little.
A worked example: the "optimised" function that changes the result
I take a scenario from a prompt manual: a function that looks for duplicate transactions with a double loop and that you want to make fast. The prompt below applies the three things just seen, and in particular asks for the verification in the right terms: a comparison with the original, on data chosen to put a rewrite in difficulty. It is a text template, not a runnable listing: you adapt it to your function.
Context: Python 3.11, standard library only. I am attaching find_duplicates(transactions),
which returns the records that have at least one other record with the same amount, merchant and date.
Problem: with a few thousand records it takes tens of seconds.
Constraints: same signature, same result (same order, a single record for each
identical dictionary), no new dependency, no other file touched.
Verification: write a test that compares your function with the original on a sample with
nearly equal records (same key, different id) and on identical records. Run it and show me
the command and the output, not a sentence saying that it passes.
Note two choices. The constraint "a single record for each identical dictionary" is not a whim: it is a behaviour
of the original, which comes from the instruction t1 not in duplicates and which no function name lets you guess. Whoever
writes the prompt finds it by reading the code, and it must be said, because a rewrite can lose it without anything signalling it.
The final request, the command and the output, is there so that you do not settle for a sentence of confirmation.
The listing contains three functions, all written by me by hand and none generated by a model: I state that the purpose is to show a realistic defect, not to attribute it to a tool.
find_duplicates is the quadratic
original. find_duplicates_fast counts the keys in one pass and collects the records in a second, using
a fingerprint of the dictionary so as not to repeat identical records. find_duplicates_naive is the one that looks right:
it flags every record whose key has already been seen. The program compares them with the original on two samples: one
random but with a fixed seed (300 records over 45 possible combinations), and one built with three identical records plus one nearly equal.
import random
def find_duplicates(transactions):
"""Quadratic version: compares every record with all the others."""
duplicates = []
for i, t1 in enumerate(transactions):
for j, t2 in enumerate(transactions):
if i != j:
if (t1["amount"] == t2["amount"]
and t1["merchant"] == t2["merchant"]
and t1["date"] == t2["date"]):
if t1 not in duplicates:
duplicates.append(t1)
return duplicates
def find_duplicates_fast(transactions):
"""One pass to count the keys, a second one to collect."""
def key(t):
return (t["amount"], t["merchant"], t["date"])
count = {}
for t in transactions:
count[key(t)] = count.get(key(t), 0) + 1
seen, result = set(), []
for t in transactions:
fingerprint = tuple(sorted(t.items()))
if count[key(t)] > 1 and fingerprint not in seen:
seen.add(fingerprint)
result.append(t)
return result
def find_duplicates_naive(transactions):
"""Looks right: flags the records whose key has already been seen."""
seen, result = {}, []
for t in transactions:
k = (t["amount"], t["merchant"], t["date"])
if k in seen:
result.append(t)
else:
seen[k] = t
return result
def sample(n, seed=7):
rnd = random.Random(seed)
shops = ["cafe", "newsstand", "train", "bookshop", "pharmacy"]
return [{"id": i, "amount": rnd.choice([5, 10, 20]),
"merchant": rnd.choice(shops),
"date": f"2026-01-{rnd.randint(1, 3):02d}"} for i in range(n)]
def sample_with_identical_copies():
# three IDENTICAL records (id included): the original returns only one of them
base = {"id": 1, "amount": 5, "merchant": "cafe", "date": "2026-01-01"}
return [base, dict(base), dict(base),
{"id": 2, "amount": 5, "merchant": "cafe", "date": "2026-01-01"},
{"id": 3, "amount": 9, "merchant": "cafe", "date": "2026-01-01"}]
if __name__ == "__main__":
for name, data in (("sample n=300", sample(300)),
("identical copies", sample_with_identical_copies())):
expected = find_duplicates(data)
for f in (find_duplicates_fast, find_duplicates_naive):
obtained = f(data)
print(f"{name:18} {f.__name__:26} "
f"{'SAME' if obtained == expected else 'DIFFERENT'} "
f"({len(obtained)} against {len(expected)} records)")
for n in (1000, 2000, 4000):
print(f"n={n}: double-loop comparisons = {n * (n - 1)}")
# sample n=300 find_duplicates_fast SAME (300 against 300 records)
# sample n=300 find_duplicates_naive DIFFERENT (255 against 300 records)
# identical copies find_duplicates_fast SAME (2 against 2 records)
# identical copies find_duplicates_naive DIFFERENT (3 against 2 records)
# n=1000: double-loop comparisons = 999000
# n=2000: double-loop comparisons = 3998000
# n=4000: double-loop comparisons = 15996000
The output says two things. The fast rewrite returns the same records as the original in both samples. The naive one loses 45 on the first, one for each group of records with the same key, because it flags only the appearances after the first, and on the second it returns 3 where the original gives 2, because it does not know the rule about identical dictionaries.
Read once, the naive version is more elegant than the correct one: it is the kind of difference that a reading of the diff does not catch and a comparison with the original catches at once. That is why the comparison goes into the prompt as a request, not into your head as an intention.
On timings I measured separately, because they vary from one machine to another and are not part of an output to reproduce identically. With the sample from the listing, on an AMD Ryzen 5 5600H with Python 3.14.4 and 5 runs per measurement, the quadratic version takes 0.23-0.24 s with 1,000 records, 1.8-2.2 s with 2,000 and 17-20 s with 4,000; the fast one stays at around 6 milliseconds at most in the three cases.
Doubling the records multiplies the time by about 8-9 and not by 4: the double loop
is quadratic, but t1 not in duplicates scans a list that itself grows with the data. It follows that a figure such as
"50,000 records in 40 seconds", typical of example prompts, cannot be deduced from anything: it depends on how many records are
duplicates, and in the prompt you should put a measurement of your own, not an estimate.
Zero-shot, few-shot, step-by-step reasoning: what the sources say
For few-shot, that is showing examples in the prompt, the source is the GPT-3 paper by Brown and colleagues (2020): tasks and
demonstrations are given to the model purely as text, without updating the weights. In an assistant that reads the repository
the practical equivalent is not pasting three examples into the prompt, but pointing to one that exists: the documentation's example
is asking to follow the pattern of HotDogWidget.php. The Cursor rules guide goes in the same direction, advising to
reference files instead of copying their content, because the copy goes stale.
On step-by-step reasoning the original source is Wei and colleagues (2022): demonstrations with intermediate steps improve results on arithmetic, commonsense and symbolic tasks, in sufficiently large models; it does not talk about coding assistants.
For code there is a variant, the Structured CoT by Li and colleagues, which asks for steps in the form of sequence, branch and loop: according to their abstract it outperforms normal CoT by up to 13.79% in Pass@1 on HumanEval, MBPP and MBCPP, with ChatGPT and Codex, that is 2023 models and single-function problems.
These are research results, not a promise for your editor today: the Claude Code documentation says "think step by step" is ordinary text, and that the main lever for making the model reason more is the effort level that is set, not the phrase. Ask for a plan when you want a text to read and approve before the code, not as a formula.
For "meta-prompting", that is asking the assistant to improve your prompt, I found no primary source, and I do not
present it as a proven technique. The documentation describes instead a nearby, verifiable flow: you say what you want, ask to
be interviewed until the assistant can write the specification, and have the result written to a file (SPEC.md) that you read.
The value lies in the file produced, which you can correct, and not in the promise that the prompt improves by itself.
One last research indication remains, from Liu and colleagues (2023): on multi-document questions and on key-value retrieval, performance is often better when the relevant information sits at the beginning or the end of the context and gets worse in the middle. It is not a measurement on code prompts, but it suggests putting the most important constraint at the end when you paste a lot of material, or not pasting it and giving the path of the file.
Persistent instruction files: where they live in each tool
If you repeat the same constraints every time, you have an instruction file you have not written yet. The four documentations I read describe different locations, and the table reports what I found written, not what I remembered.
| Tool | File it reads | What the documentation says |
|---|---|---|
| Claude Code | CLAUDE.md or .claude/CLAUDE.md in the project, ~/.claude/CLAUDE.md personal; AGENTS.md if there is no CLAUDE.md at all | Context, not enforced configuration; reads AGENTS.md directly from version 2.1.277; per-path rules in .claude/rules/ |
| Cursor | .cursor/rules/*.mdc with frontmatter description, globs, alwaysApply; AGENTS.md in the root and in subfolders | A .md inside .cursor/rules is ignored; the page does not mention .cursorrules |
| GitHub Copilot | .github/copilot-instructions.md for the whole repository; .github/instructions/NAME.instructions.md with applyTo; AGENTS.md; CLAUDE.md or GEMINI.md in the root for the agents | Per-path instructions apply, according to the GitHub.com documentation, only to the cloud agent and to code review |
| Windsurf | AGENTS.md always on; .devin/rules/*.md with trigger; the old .windsurf/rules and .windsurfrules imported | The documentation is now hosted on the Devin site |
The fact that matters is another: all four documentations name AGENTS.md, the open format
described on agents.md as a "README for agents". If you work with several tools, a single AGENTS.md in the root
is the cheapest starting point, and the tool-specific files are only for what the format does not express, such as rules tied to a path.
For Claude Code there is a detail not to miss: it reads AGENTS.md on its own only if no CLAUDE.md exists above the working folder; if
you have both, the CLAUDE.md wins, unless it imports the other with @AGENTS.md. Imports use
the @path syntax, have a maximum depth of four levels and do not reduce the context cost, because the imported file is loaded together with the one that imports it.
What to write in them: concrete, short, verifiable
The Claude Code page on memory gives three indications that also hold for the other tools. The first is to write instructions
concrete enough to be verified: "use 2-space indentation" instead of "format the code properly", "run npm test before
committing" instead of "test your changes". The second is length: fewer than 200 lines per file, because long files consume context and reduce
adherence; Cursor indicates 500 lines for a single rule. The third is consistency: if two instructions contradict each other, the assistant may choose at random,
and a file nobody rereads accumulates exactly these contradictions.
Then there is a limit not to forget, written in the same documentation: Claude treats these files as context and not as configuration. If a rule admits no exceptions (do not touch the generated client, always run the licence-header script), the guide suggests that adding capitals and emphasis is not enough and that the line should be moved into a hook, that is into a check the program runs every time.
How to write a hook is in Claude Code: agentic development from the terminal. The practical rule is that an instruction file steers, and what must always hold is enforced by a mechanism.
A free check: do the instructions cite things that still exist?
An instruction file ages silently. After a month it cites a script you renamed, a folder you moved,
a document that is no longer there, and the assistant follows it with the same confidence as before. Claude Code has a command, /doctor prompt-audit
(from 2.1.283), which looks among other things for references to nonexistent files or commands; however it goes through a model and proposes changes.
The check that follows does only the deterministic part, and it is free to run in CI or before a commit: it reads the file, extracts the npm run commands, the paths between
backticks and the @path imports, and verifies that they exist.
import json
import re
import sys
import tempfile
from pathlib import Path
LINE_LIMIT = 200 # guideline from the Claude Code documentation for CLAUDE.md
def without_code(text):
"""Removes fenced blocks and inline code: there the @ signs are not imports."""
text = re.sub(r"```.*?```", "", text, flags=re.S)
return re.sub(r"`[^`\n]*`", "", text)
def check(instructions_file: Path, root: Path):
text = instructions_file.read_text(encoding="utf-8")
problems = []
scripts = json.loads((root / "package.json").read_text())["scripts"]
commands = set(re.findall(r"npm run ([\w:.-]+)", text))
commands |= {m for m in ("test", "start") if re.search(rf"\bnpm {m}\b", text)}
for name in sorted(commands):
if name not in scripts:
problems.append(f"nonexistent command: npm run {name}")
for path in sorted(set(re.findall(r"`([\w./-]+(?:/|\.\w+))`", text))):
if not (root / path).exists():
problems.append(f"nonexistent path: {path}")
for ref in sorted(set(re.findall(r"(?<!\S)@([\w./-]+)", without_code(text)))):
ref = ref.rstrip(".") # the full stop that ends the sentence is not part of the path
if not (instructions_file.parent / ref).exists():
problems.append(f"import that does not resolve: @{ref}")
lines = len(text.splitlines())
if lines > LINE_LIMIT:
problems.append(f"{lines} lines: over the {LINE_LIMIT} recommended")
return problems
INSTRUCTIONS = """# Project
Before closing a job run `npm run lint` and `npm test`.
For the test database: `npm run seed`.
The API handlers live in `src/api/handlers/`; the old one in `src/legacy/old.ts`.
Architecture: @docs/architecture.md. The file `@README` stays text, it is not imported.
```bash
npm run build
```
"""
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "package.json").write_text(json.dumps(
{"scripts": {"start": "node .", "build": "tsc", "test": "node --test"}}))
(root / "src/api/handlers").mkdir(parents=True)
(root / "CLAUDE.md").write_text(INSTRUCTIONS, encoding="utf-8")
problems = check(root / "CLAUDE.md", root)
for p in problems:
print(p)
print(f"{len(problems)} problems")
sys.exit(1 if problems else 0)
# nonexistent command: npm run lint
# nonexistent command: npm run seed
# nonexistent path: src/legacy/old.ts
# import that does not resolve: @docs/architecture.md
# 4 problems
Two choices in the code come from the documentation. The @path imports are searched for after removing code blocks and inline code,
because the documentation says the import analysis skips those zones: that is why @README between backticks stays text and raises no problem.
The commands, instead, are searched for right inside the code, because that is where they live. The program builds a fake project on its own in a temporary folder, with three scripts
(start, build, test), and finds four problems: two commands that do not exist, a vanished path and an import that does not resolve.
It exits with code 1, so in a pipeline it blocks the commit.
The first time I ran it, it showed a defect of mine: the import was reported as architecture.md., with the full stop of the sentence attached, and the
check declared it nonexistent even though the file was there. The rstrip(".") line is the fix, and the lesson is that a check of this kind is always tried on a case
you know to be wrong and on one you know to be right. The limits remain: it verifies existence, not the truth of what the file says; it knows only npm; it does not read paths with spaces
or with wildcards. It does not replace rereading, it makes it less tiring.
Three prompts that fail for the same reason
The prompts that disappoint most have recurring shapes, and it pays to recognise them before looking for more sophisticated techniques:
- The vague prompt ("improve this function"): it does not say what "better" means, nor when to stop. It is fixed by stating the direction (faster, more readable, fewer dependencies) and the check.
- The implicit context ("use our standard pattern"): the pattern is not in the prompt and not necessarily in the repository. It is fixed by pointing to the file that shows it.
- Everything in one go (a whole feature in one request): every detail left unsaid becomes a choice of the model, and you review an enormous diff. It is fixed by decomposing, as in Agentic workflows: decomposing problems for AI.
The three shapes lack the same thing the experiment showed us: an item of information, a perimeter or a check. It is not length that makes a prompt fail, it is what is missing. A short prompt that names the file, the behaviour to preserve and the command to run is better than a page of labelled sections that does not say how the result is verified. That is why I do not propose a threshold in tokens: I found none with a source, and the right question remains whether the prompt contains what the model does not see.
What a prompt does not guarantee, and how to measure yourself
A prompt gives no certainties: it steers a model, which can still do something else. That is why verification sits outside the prompt: tests, types, diff review, and for what admits no exceptions a mechanism the program runs. The rest of the series deals with the two points where this weighs most, that is how to test generated code and how to reduce the security risks.
On measuring prompts there are no published thresholds that I can cite, and the ones you find (how many iterations "should" be enough, what acceptance rate is "good") are numbers without a sample. Measure them yourself, comparing yourself with yourself.
The METR study described in the first article found experienced developers 19% slower while they believed they were 20% faster: your impression is not enough. Three simple counters, kept on your own work for a couple of weeks, are enough to see whether an instruction file changes anything: how many corrections are needed before the check passes, how many times the check fails at the first attempt, how many assisted commits you then have to revert.
Frequently asked questions
Do I have to write "think step by step" in the prompt?
Not as a formula. The Claude Code documentation says that phrases of this kind are ordinary text and that the main control over reasoning is the effort level. The research on chain-of-thought concerns examples with intermediate steps on specific models and benchmarks. If you want to see the reasoning, ask for a plan to approve before the code.
Better one long instruction file or several short ones?
Short ones, split by scope. Claude Code indicates fewer than 200 lines per file and suggests per-path rules for what concerns only part of the code; Cursor indicates 500 lines per rule and invites you to reference files instead of copying them. Imports do not reduce the context cost, so they serve to organise, not to lighten.
Better CLAUDE.md or AGENTS.md?
If you use several tools, AGENTS.md is the format that all four documentations cite. If you work only with Claude Code you can keep CLAUDE.md and, when you need to
share, import AGENTS.md with @AGENTS.md. Avoid maintaining two different texts with the same content: they will diverge.
Does a well-written prompt save me from reviewing the code?
No. In the experiment above the naive function was readable, plausible and wrong: the only thing that exposed it was a comparison run against the original. The prompt can ask for that comparison, but somebody has to read its output.
What you can do now
You can write a prompt that says what the repository does not say (decisions, perimeter, check) and you can ask for a check with a yes or no outcome, with the command and its output as
proof. You know where each of the four tools reads persistent instructions, why AGENTS.md is the common denominator and how to prevent an instruction file from
starting to cite things that no longer exist. The next article in the series is about the security risks of what the assistant writes:
Security in vibe coding.
Sources
- Claude Code Docs: Best practices - what to write (what cannot be read in the repository), specific prompts, a check with a yes or no outcome, deterministic and non-deterministic instructions, "think step by step" as ordinary text, consulted on 2026-11-13
- Claude Code Docs: How Claude remembers your project - locations of CLAUDE.md, reading of AGENTS.md from 2.1.277, imports with @, the 200-line guideline,
/doctor prompt-audit, consulted on 2026-11-13 - Cursor Docs: Rules - rules in
.cursor/ruleswith the.mdcextension and the fields description, globs, alwaysApply; support for AGENTS.md; 500 lines per rule; referencing files instead of copying them, consulted on 2026-11-13 - GitHub Docs: Adding repository custom instructions for GitHub Copilot - copilot-instructions.md,
.instructions.mdfiles with applyTo, AGENTS.md, CLAUDE.md and GEMINI.md, consulted on 2026-11-13 - Windsurf Docs: Rules (hosted on the Devin site) - AGENTS.md always on,
.devin/ruleswith trigger, legacy files imported, consulted on 2026-11-13 - AGENTS.md - description of the format as a "README for agents" and nested files per sub-project, consulted on 2026-11-13
- Brown et al., Language Models are Few-Shot Learners (arXiv 2005.14165) - few-shot specified purely via text, without weight updates, consulted on 2026-11-13
- Wei et al., Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (arXiv 2201.11903) - improvement on arithmetic, commonsense and symbolic tasks, consulted on 2026-11-13
- Li et al., Structured Chain-of-Thought Prompting for Code Generation (arXiv 2305.06599) - up to 13.79% more Pass@1 than CoT on HumanEval, MBPP and MBCPP (abstract), consulted on 2026-11-13
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts (arXiv 2307.03172) - better performance with the relevant information at the beginning or end of the context, on two tasks, consulted on 2026-11-13
The two listings were run with Python 3.14.4, twice each, with identical output (cmp on the output files); the timings are measured separately, with 5 runs per size. The three comparison functions and the test instruction file are written by hand for the article, not generated by a model. No model was called. The prompt is a template to adapt and was not run.

Commenti
Caricamento commenti...
Sign in to comment