Originally published on tamiz.pro.
Vibe coding feels like magic: you describe a feature in plain English, an agent streams back working code, and you accept the diff without a second thought. But the magic has a meter. Every keystroke you save in the prompt is paid for in tokens, context, and — most expensively — in the verification work that separates "it compiles" from "it ships." This article dissects the hidden invoice of AI-assisted development: how token budgets actually accrue, why agent memory degrades as context windows fill, and which engineering checks are non-negotiable before AI-generated code touches production.
- 1. The Token Economy
- 2. Agent Memory and the Context Window
- 3. The Verification Layer
- 4. A Practical Budgeting Framework
- 5. The Production-Readiness Checklist
- Frequently Asked Questions
1. The Token Economy
What a token actually is
Tokens are the atomic unit of LLM billing. A token is roughly 4 characters, or about 0.75 words of text. When you send a prompt to an API, the provider tokenizes both your input and the model's output, and you pay for both. The pricing is asymmetric: output tokens are typically 3–5× more expensive than input tokens, and cached input tokens (prompts the provider has already seen) cost a fraction of fresh input.
Here's a representative pricing table for a mid-tier frontier model (numbers are illustrative, but they reflect the current market):
| Token Type | Price per 1M tokens |
|---|---|
| Input (cache miss) | $3.00 |
| Input (cache hit) | $0.30 |
| Output | $15.00 |
The asymmetry matters more than people think. A single "vibe coding" turn might send 20,000 input tokens and produce 800 output tokens. The output tokens alone cost $0.012, but the input tokens — which you'd assume are cheap — cost $0.06. Input is the bulk of the bill, and it grows.
The compounding conversation problem
Here's the hidden invoice's first line item: conversation history is re-sent on every turn.
When you use an agent like Cursor, Copilot, or Claude Code, each tool call is a fresh API request. The agent can't just send the new instruction; it has to send the entire conversation so far so the model knows what it's doing. That means turn 1 sends 5,000 tokens, turn 2 sends 7,000, turn 3 sends 9,000 — the history keeps growing.
Over a 100-turn session, the total input tokens sent is the sum of every prefix:
Total input = Σ (base_context + Σ(turn_i_tokens))
If your base context (system prompt + open files) is 10,000 tokens and each turn adds an average of 500 tokens of new history, then by turn 100 you're sending ~60,000 tokens per request. The cumulative total across the session is roughly 3.5 million tokens — a bill of ~$10.50 in input alone, before you count a single output token.
The math is quadratic in the number of turns. A 50-turn session costs about a quarter of a 100-turn session, not half.
Tool-call multiplication
The second line item is tool-call fan-out. One "vibe" request is rarely one API call. A typical agent workflow for a single feature looks like this:
- Read the target file (API call #1)
- Generate an edit (API call #2)
- Run the test suite (API call #3)
- See a failing test (API call #4)
- Fix the code (API call #5)
- Re-run tests (API call #6)
Each of those six calls re-sends the entire growing history. So a single "vibe" that you perceive as one interaction is actually 6 API calls, each costing more than the last. The invoice isn't per-feature — it's per-tool-call, and the agent decides how many tool calls to make.
The practical takeaway: turn count and tool-call count are the real cost drivers, not the size of your prompt. A tight, well-scoped prompt that produces one edit and one test run costs a fraction of a vague prompt that triggers six tool calls and three failed attempts.
2. Agent Memory and the Context Window
The anatomy of agent memory
An AI coding agent's "memory" isn't a database. It's a single, fixed-size context window that holds everything the model can see in one forward pass. That window is filled by four competing consumers:
┌─────────────────────────────────────────────────────────────┐
│ CONTEXT WINDOW │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ System Prompt│ │ Conversation │ │ File Contents │ │
│ │ (rules, tools│ │ History │ │ (open files, │ │
│ │ persona) │ │ (user/assist)│ │ diffs, imports)│ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
│ ┌──────────────────┐ │
│ │ Tool Results │ ← test output, lint output, errors │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The system prompt is fixed. File contents are pulled in on demand. Tool results — especially test output and error traces — can be enormous. A single failing test can dump 5,000 tokens of stack trace into the window. Conversation history fills the rest.
Context compaction and the forgetting curve
When the total exceeds the window (say, 128k or 200k tokens), the agent has to compact. It does this by summarizing older turns into a short paragraph, or by truncating them entirely. This is the moment the "memory" breaks.
Here's the failure mode: at turn 5, you told the agent, "Use React 18, don't call hooks inside loops, and keep all API calls in a useEffect." That's a constraint. By turn 40, after a few compactions, that constraint has been summarized into "follow the project's React conventions" — or dropped entirely. The agent then happily generates a hook inside a loop, because it no longer has the original instruction.
This is the forgetting curve of agentic coding: the more turns you take, the more likely the agent is to violate an early constraint, because early constraints are the first to be compacted away.
The memory tax
Compaction isn't free. When the agent forgets a file's contents, it has to re-read that file in a later turn — and re-reading costs tokens. When it forgets a constraint, you have to re-state it — which costs tokens and your attention. When it forgets a test result, it may re-run the same failing test, producing the same 5,000-token stack trace, costing tokens again.
This is the memory tax: you pay once to keep context, you pay again when the agent loses it, and you pay a third time when you have to correct the resulting mistake. Three invoices for one decision.
The trade-off is real:
| Strategy | Token cost | Accuracy cost |
|---|---|---|
| Keep full context | High (linear growth) | High fidelity |
| Compact aggressively | Low | Low (forgets constraints) |
| RAG / file re-injection | Medium (retrieval overhead) | Medium (may miss relevant files) |
There's no free lunch. The only way to win is to reduce the number of turns, which means being deliberate about what you ask for.
3. The Verification Layer
Why AI-generated code is unverified by default
An LLM is a next-token predictor. It optimizes for output that looks like correct code — the statistical shape of a solution — not code that is correct. It has no execution environment, no test runner, and no notion of runtime behavior. When it generates a function, it's producing the most probable continuation, not the one that passes your tests.
This creates a specific failure profile: happy-path bias. AI-generated code tends to handle the common case well and the edge cases poorly. It forgets null checks, off-by-one errors, race conditions, and error propagation. It writes code that works on the demo path and breaks in production.
The checks that matter
The "invoice" here is verification overhead. Every AI-generated diff needs to pass a gate before it's production-ready. Here's the minimum viable gate:
- Static analysis (linting). Catches unused variables, unreachable code, import errors, and style violations. Fast, cheap, non-negotiable. Run ESLint, Ruff, or golangci-lint on every diff.
-
Type checking. Catches the largest class of AI bugs: mismatched types, undefined properties, wrong argument counts.
tsc --noEmitormypyshould be part of the pre-commit hook. - Unit and integration tests. AI code passes the tests you write — not the tests you should write. If you only have happy-path tests, the AI will only be happy. Add property-based tests and edge-case tests.
- Security scanning. SAST tools (Semgrep, CodeQL) catch injection, insecure deserialization, and path traversal. Dependency audit catches vulnerable packages. Secret scanning catches hardcoded credentials — which AI models are notorious for inserting.
- Human code review. The most expensive check, and the one that catches the semantic bugs that no tool can. The reviewer must read the diff as if it were written by a junior dev who was in a hurry.
- Performance profiling. AI often generates O(n²) solutions when O(n) is expected, or leaks memory in event handlers. Profile before merge.
A worked example
Here's the kind of bug that slips through. An AI agent generates this function for a rate limiter:
function rateLimit(requests: number[], limit: number): number[] {
const result: number[] = [];
let count = 0;
for (let i = 0; i < requests.length; i++) {
if (requests[i] === 1) {
count++;
}
if (count > limit) {
result.push(i); // mark as rate-limited
}
}
return result;
}
It looks correct. It passes a happy-path test. But it has two bugs:
- It never resets
countwhen a request isn't1— so it's counting total1s, not consecutive1s. Thecount > limitcheck is wrong for a sliding window. - It pushes the index
ieven when the rate limit was already exceeded on a previous iteration, so the same window gets multiple entries.
A linter won't catch this. A type checker won't catch this. A unit test with a single happy path won't catch this. Only a property-based test — for all arrays, the output should have at mostlimitconsecutive 1s — or a human reviewer will catch it.
This is the core of the hidden invoice: the code is cheap, the verification is expensive. You save 10 minutes of typing and spend 30 minutes debugging a subtle semantic bug that the AI confidently produced.
The vibe debt
The real cost of vibe coding isn't the token bill — it's the debt you accrue in verification. When you accept an AI diff without running the full gate, you're deferring that cost. It comes back as a production incident, a security vulnerability, or a 2 a.m. rollback. The invoice always arrives; the only question is whether you pay it in CI or in production.
4. A Practical Budgeting Framework
Estimating your spend
You can estimate token spend before you start. The inputs are:
-
base_context: system prompt + open files (tokens) -
turns: number of user/assistant exchanges you expect -
tokens_per_turn: average new tokens added per turn (your prompt + the agent's response) -
tool_calls_per_turn: average number of API calls per turn -
prices: input and output token prices
Here's a small script that models the cost:
def estimate_cost(
base_context: int,
turns: int,
tokens_per_turn: int,
tool_calls_per_turn: float = 1.0,
price_input: float = 3.00, # $/1M tokens
price_output: float = 15.00, # $/1M tokens
output_ratio: float = 0.05, # output tokens as fraction of input
) -> dict:
"""Estimate total token spend for an agentic coding session."""
total_input = 0
total_output = 0
for turn in range(1, turns + 1):
# Context grows linearly: base + history accumulated so far
context = base_context + (turn - 1) * tokens_per_turn
calls = tool_calls_per_turn
total_input += context * calls
total_output += context * output_ratio * calls
cost = (
total_input / 1_000_000 * price_input
+ total_output / 1_000_000 * price_output
)
return {
"total_input_tokens": total_input,
"total_output_tokens": total_output,
"estimated_cost_usd": round(cost, 2),
}
# Example: 40 turns, 12k base context, 600 new tokens per turn, 2 tool calls per turn
print(estimate_cost(base_context=12000, turns=40, tokens_per_turn=600, tool_calls_per_turn=2))
Running this with realistic numbers gives you a ballpark. For a 40-turn session with a 12k base context, 600 new tokens per turn, and 2 tool calls per turn, you're looking at roughly 2.5 million input tokens and a cost around $8–$12. That's for one feature.
Cost-control strategies
The invoice is controllable. Here's what actually moves the needle:
- Scope the context. Don't let the agent read the whole repo. Pin the files you care about and use file-scoped context. A 12k-token base context is far cheaper than a 60k-token one.
-
Cap the turns. Set a
max_turnson your agent. If it hasn't solved the problem in 10 turns, stop and rethink your prompt. The quadratic growth means turn 20 costs 4× turn 10. - Use cheaper models for routine edits. Save the frontier model for complex refactors; use a fast, cheap model for boilerplate, comments, and test scaffolding.
- Checkpoint and restore. If the agent goes off the rails, restore the last good state rather than trying to talk it back. Every "let me explain what went wrong" turn is a fresh invoice.
- Batch your edits. One well-specified prompt that produces one correct edit beats ten vague prompts that produce ten broken ones. The agent's tool-call fan-out is the multiplier.
5. The Production-Readiness Checklist
Before any AI-generated diff merges, it should pass this gate. Copy this into your PR template:
- [ ] Lint clean —
eslint ./ruff check .passes with zero errors. - [ ] Types check —
tsc --noEmit/mypy .passes with zero errors. - [ ] Unit tests pass —
npm test/pytestis green, including new tests for the feature. - [ ] Edge-case tests added — at least one test covers a boundary: empty input, null input, max input, concurrent calls.
- [ ] Security scan clean — SAST and dependency audit report no new critical or high findings.
- [ ] No secrets committed — secret scanning confirms no hardcoded credentials or API keys.
- [ ] Human review complete — a human read the diff and verified the logic, not just the syntax.
- [ ] Performance sanity — no obvious O(n²) loops, no memory leaks in event handlers, no unbounded recursion.
This checklist is the invoice. It's the price of turning "the AI wrote it" into "it's shippable." If you skip it, you're not saving time — you're deferring the cost to a more expensive moment. For a deeper look at CI pipelines that enforce this gate, see Tamiz's Insights.
Frequently Asked Questions
Q: Is vibe coding worth it if the verification costs that much?
A: It depends on the ratio of verification time to implementation time. For boilerplate, migrations, and test scaffolding, the ratio is low — the AI saves real time and the checks are fast. For core business logic, concurrency, and security-sensitive code, the ratio is high — you'll spend more time verifying than you saved writing. Use vibe coding for the low-risk 80%, not the high-risk 20%.
Q: How do I stop the agent from forgetting early constraints?
A: You can't fully prevent it, but you can mitigate it. Put non-negotiable constraints in an AGENTS.md or CLAUDE.md file that's loaded into the system prompt on every turn — that way they survive compaction. Keep sessions short. If a constraint is critical, re-state it explicitly in the prompt rather than relying on the conversation history.
Q: What's the single most impactful check for AI-generated code?
A: Human code review, by far. Linters and type checkers catch syntax and type errors, but the failures that actually hurt — semantic bugs, race conditions, security holes — are invisible to static analysis. The reviewer needs to ask "does this logic actually do what the comment says?" not "does this compile?"
Top comments (0)