Level 2 Agentic Coding · Agentic Coding
From Prototype to Production
An agent can build a working demo in an afternoon, but software other people rely on needs much more. This chapter covers the gap, with a concrete checklist: secrets, logins and access control, input validation, dependencies (including package names the AI made up), deployment, monitoring, costs and maintainability.
- Level
- ●●●●● Easy
- Reading
- 21 min
- To learn it well
- 1 hour to read, an afternoon to run the checklist on your own project
- Builds on
- 16 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 16 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Setting Up Your Environment
- Large Language Models, Explained Simply
- AI Fluency: Working Well with AI
- Using LLM APIs
- Asking Well: Everyday Prompting
- Structured Output and JSON
- What Is Agentic Coding?
- Tool Use and Function Calling
- Setting Up a Coding Agent
- Prompt Injection and LLM Security
- Tests as Guardrails
- Git for Agent Work
- Reviewing and Debugging AI-Written Code
- From Prototype to Production
Read them roughly in this order. See it on the concept map →
Why it matters
A coding agent can take you from an idea to a working demo astonishingly fast. The screens appear, the buttons work, the data saves. It feels finished. Addy Osmani called what comes next "the 70% problem": AI gets you most of the way very quickly, and the last 30%, the part that makes software safe to rely on, turns out to be most of the work. Beginners hit a wall there, because they can't see what is missing.
What is missing is invisible in a demo. A demo runs on your laptop, for you, with friendly input. Production means the software runs where other people can reach it, with real data, for an indefinite time, and you are responsible for what happens. Bots will send inputs you never imagined, someone will change the ID in a URL to see whose data appears, and a bug in a loop can spend a month's budget in an hour.
None of this is new: OWASP (the Open Worldwide Application Security Project, a non-profit) has published its Top 10 web security risks for over twenty years. What is new is that agents let people ship faster than they learn the lessons, and bring failure modes of their own, such as installing packages that don't exist. This chapter assumes you can review an agent's diff and know what Prompt Injection and LLM Security is.
Key idea A working demo proves the happy path. Production is about everything else: hostile input, leaked keys, other users' data, outages, bills and future changes. Agents won't handle these unless you ask, and "it works" tells you nothing about them, so check each one on purpose.
The idea
Think of an iceberg. Above the water is what a demo shows: pages, features, the path where everything goes right. Agents build that part well, because it is what you asked for and can see. Below the water is what decides whether the project survives contact with the world, and it gets built only if you ask for it and check it.
The rest of the chapter takes the eight areas in turn, then runs them as a checklist on an example.
Secrets
A secret is any value that grants access: an API key, a database password, the key that signs login cookies. The rule: secrets live in the environment, never in the code. Code reads them from environment variables at start-up; on your machine they come from a .env file that git ignores, on the server from the host's secret settings. The Twelve-Factor App guidelines give a neat test: could you make your code public right now without leaking a single credential?
Agents break this rule predictably: a key pasted into the source to get the demo working, a real token in a test, .env committed before .gitignore existed. Ask for this pattern instead: read every setting from the environment, stop immediately if one is missing, and never print a secret whole.
import os
import sys
def require(name: str) -> str:
"""Read a required setting from the environment, or stop with a clear error."""
value = os.environ.get(name, "").strip()
if not value:
sys.exit(f"Config error: {name} is not set. Add it to .env or the host's secret settings.")
return value
def masked(secret: str) -> str:
return "*" * 8 + secret[-4:] # safe to log: only the last 4 characters
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-demo-123456789abcd" # demo only: never in real code
print("api key:", masked(require("ANTHROPIC_API_KEY")))
session_secret = require("TALLY_SESSION_SECRET") # not set: stop here
# api key: ********abcd
# Config error: TALLY_SESSION_SECRET is not set. Add it to .env or the host's secret settings.
Failing loudly matters. An app that starts without its signing key and quietly falls back to "dev-secret" has login cookies anyone can forge. Generate real secrets with python -c "import secrets; print(secrets.token_urlsafe(32))".
Three habits close the usual leaks. Ignore first: add .env to .gitignore before the file exists, and commit a .env.example with the names and fake values. Scan: secret scanning means automatically searching code and its history for strings that look like credentials. GitHub does it free on public repositories, and as of late 2026 its push protection blocks individual users from pushing recognised secrets to public repositories by default; open-source scanners such as gitleaks do the same locally or in CI. Rotate on leak: deleting a committed key in the next commit doesn't help, because it is still in the history (Git for Agent Work). Revoke it in the provider's console and issue a new one.
The agent itself is the other half. It can read every file in your project, including .env, and text it reads can try to steer it (Prompt Injection and LLM Security). Never give a coding agent production credentials: give it a development database and a separate, low-limit API key. In Claude Code you can also add deny rules such as Read(./.env) to the project's permissions (Setting Up a Coding Agent).
Authentication and authorization
Authentication checks who you are: logging in. Authorization checks what you may do: may this logged-in user see this record, or delete that one?
Don't build authentication yourself, and don't let the agent improvise it. Password storage, reset emails, session cookies and login rate limits are each easy to get subtly wrong. Use your framework's built-in auth or a hosted identity provider, say so in the spec (Planning and Specs: Telling an Agent What to Build), and add "no custom password handling".
Authorization is where agent-built apps fail most often, and it tops OWASP's list (as of the 2025 edition, A01: Broken Access Control). The classic bug: the page /expenses/42/delete checks that you are logged in, but not that expense 42 is yours. Change 42 to 43 and you delete a stranger's data. Agents write this constantly, because the demo has one user and works perfectly. The same goes for databases the browser talks to directly, common in AI app builders: their access rules (Supabase's row-level security, for example) are all that stands between any visitor and every row, and Building Apps Without Coding describes apps that went live with them switched off.
The fix is to make ownership part of every query, as in the next section's code. The test that matters is not "can Alice delete her expense?" but "can Bob delete Alice's?".
Input validation
Everything that crosses into your program from outside is untrusted: form fields, URL parameters, uploads, webhooks, and the text a language model sends back. Input validation means checking each value's type, range and shape before using it, and rejecting it clearly if it is wrong. The safest form is an allow-list: describe what is allowed ("a category is 1 to 30 lower-case letters, digits, spaces, dashes or underscores") rather than trying to list everything forbidden.
The second rule is keep data as data. The worst bugs happen when input is pasted into something that gets executed: an SQL query, a shell command, an HTML page. OWASP calls this family injection (A05 in 2025). Use the safe interface every language provides. For SQL that is a parameterised query: the command has placeholders (?) and the values travel separately, so the database can never mistake a value for part of the command. For HTML it is a template engine that escapes text by default.
import re
import sqlite3
from decimal import Decimal, InvalidOperation
CATEGORY = re.compile(r"[a-z][a-z0-9 _-]{0,29}") # allow-list
def parse_expense(amount: str, category: str) -> tuple[Decimal, str]:
"""Turn untrusted form input into clean values, or raise ValueError."""
try:
value = Decimal(amount)
except InvalidOperation:
raise ValueError(f"amount {amount!r} is not a number")
if not value.is_finite() or not (0 < value <= 100_000):
raise ValueError(f"amount {amount!r} must be between 0 and 100000")
if value != value.quantize(Decimal("0.01")):
raise ValueError(f"amount {amount!r} has more than 2 decimals")
category = category.strip().lower()
if not CATEGORY.fullmatch(category):
raise ValueError(f"category {category!r} is not allowed")
return value, category
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE expenses (id INTEGER PRIMARY KEY, user_id INT, amount TEXT, category TEXT)")
def add_expense(user_id: int, amount: str, category: str) -> None:
value, cat = parse_expense(amount, category)
db.execute("INSERT INTO expenses (user_id, amount, category) VALUES (?, ?, ?)", # placeholders
(user_id, str(value), cat))
def delete_expense(user_id: int, expense_id: int) -> bool:
cur = db.execute("DELETE FROM expenses WHERE id = ? AND user_id = ?", # ownership check
(expense_id, user_id))
return cur.rowcount == 1
for amount, category in [("12.50", "Lunch"), ("1e9", "rent"), ("NaN", "food"),
("3.333", "coffee"), ("4.20", "x'); DROP TABLE expenses;--")]:
try:
add_expense(1, amount, category)
print("ok ", amount, category)
except ValueError as e:
print("rejected", e)
print("user 2 deletes expense 1:", delete_expense(2, 1))
print("user 1 deletes expense 1:", delete_expense(1, 1))
# ok 12.50 Lunch
# rejected amount '1e9' must be between 0 and 100000
# rejected amount 'NaN' must be between 0 and 100000
# rejected amount '3.333' has more than 2 decimals
# rejected category "x'); drop table expenses;--" is not allowed
# user 2 deletes expense 1: False
# user 1 deletes expense 1: True
NaN ("not a number") and 1e9 are both valid to Python's Decimal, and an agent's first draft will often accept them. Demos never try such inputs. Ask the agent to list the nasty inputs for every field and write a test for each, then add your own.
If your app has an AI feature, the model's output is untrusted input too. Escape it before showing it as HTML, never pass it to a shell or a query unchecked (OWASP's LLM list calls this improper output handling), and remember that whatever users feed into the model can carry instructions (Prompt Injection and LLM Security).
Dependencies
Most of any app is other people's code: the framework, the database driver and everything they depend on. Each dependency runs with full trust, which makes the chain a target. A supply-chain attack plants malicious code in something your software depends on rather than attacking it directly. OWASP's 2025 list ranks it third (A03: Software Supply Chain Failures).
Agents add a twist: language models sometimes recommend packages that don't exist, plausible names the model made up. A 2024 study by Spracklen and colleagues (published at USENIX Security 2025) generated 576,000 code samples with 16 models and found that 19.7% of the packages they referenced did not exist: at least 5.2% for commercial models and 21.7% for open-source ones. The inventions were repeatable. Re-running the same prompt ten times, 43% of the made-up names came back every time. Newer models do this less often, but not never.
Repeatable inventions can be exploited. An attacker collects names that models keep inventing, registers them on the package index (PyPI for Python, npm for JavaScript) with malware inside, and waits for an agent to suggest the name and run pip install. Seth Larson of the Python Software Foundation named this slopsquatting in 2025, after typosquatting (registering misspellings of popular packages). To be precise about the evidence: researchers have shown that it works, and large-scale malicious use is harder to confirm. In 2024 Bar Lanyado of Lasso Security registered a harmless empty package under a name chatbots kept suggesting, huggingface-cli. It was downloaded tens of thousands of times in three months, including through the install instructions in a public repository of a large company.
The defence is a habit: every new dependency is a decision, made by you. Put "no new dependencies without asking" in your memory file, keep package installs on the agent's ask-first list, and check each proposal. A small script does the first check against PyPI's public JSON API:
import json
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
def pypi_info(name: str) -> str:
try:
with urllib.request.urlopen(f"https://pypi.org/pypi/{name}/json", timeout=10) as r:
data = json.load(r)
except urllib.error.HTTPError as e:
if e.code == 404:
return "NOT ON PYPI - a hallucinated name? Do not install."
raise
uploads = [f["upload_time_iso_8601"] for files in data["releases"].values() for f in files]
if not uploads:
return "exists but has no files - suspicious"
first = min(datetime.fromisoformat(u.replace("Z", "+00:00")) for u in uploads)
new = (datetime.now(timezone.utc) - first).days < 90
return f"first release {first:%Y-%m-%d}, {len(data['releases'])} versions" + (
" <- new: check who publishes it" if new else "")
for name in sys.argv[1:]:
print(f"{name:18} {pypi_info(name)}")
# $ python check_deps.py requests python-dotenv flask-csv-guard
# requests first release 2011-02-14, 163 versions
# python-dotenv first release 2014-09-08, 52 versions
# flask-csv-guard NOT ON PYPI - a hallucinated name? Do not install.
(flask-csv-guard is a made-up name for this example.) Existence is not safety: a slopsquatted package does exist, which is why the script flags new ones. Look at the package page too: who publishes it, whether it links to a real source repository, how widely it is used. Then keep the whole set healthy. Pin versions in a lockfile so every install gets what you tested. Audit with pip-audit or npm audit, which compare your dependencies with public vulnerability databases; GitHub's Dependabot does it continuously and opens pull requests with fixes. And prefer fewer: agents reach for a package where the standard library needs five lines.
Deployment
Deployment is getting the app onto a computer that is always on and reachable, and doing it again, safely, after every change. As of late 2026 a small project has three broad options: a platform-as-a-service (Render, Fly.io and Railway, or Vercel and Netlify for front-ends), which builds from your git repository and gives you HTTPS and a place for secrets, the easiest start; a container on a cloud service, with more control (Deploying Models walks through one); or a virtual server you manage yourself, which makes you responsible for updates, firewalls and certificates.
Whatever you pick, the essentials are the same:
- Production settings. Debug mode off: framework debug pages reveal code and settings, and Flask's interactive debugger can run code. HTTPS only.
- Deploy from git, a known commit that passed your tests in CI, never from files on your laptop.
- A way back. Know the one-step rollback before you need it.
- Backups, tested. A redeploy can recreate everything except the data. Turn on automatic backups and restore one once.
- Least privilege. The app's database user can't drop the database; the deploy token can't delete the account.
"Write the Render config with the start command, a health check and the variable names from .env.example" is a good agent task. But keep the production deploy itself behind a human, and never paste production secrets into the chat.
Monitoring
You need to know the app is broken before a user tells you. For a small app that means four things:
- A health check: a URL like
/healththat answers "ok" when the app and database work, polled every minute by an uptime service that alerts you. - Error tracking: a service such as Sentry (free tier as of 2026) or your host's logs, recording every unhandled error with its stack trace.
- Logs: one line per event with a timestamp, and without secrets, passwords or more personal data than needed. Logging whole request bodies "for debugging" is a classic way to leak passwords.
- Usage and cost numbers: requests, model tokens and money per day, so a jump stands out.
Keep alerts few and meaningful, or you will learn to ignore them (alert fatigue). For AI features, monitoring also means watching answer quality (Evaluating LLM Applications).
Costs
Three bills grow with agent-built software: hosting, usually small but check what automatic scaling costs in a spike; your app's model calls, billed by tokens (Using LLM APIs); and the agent's own usage while you develop, which Running Agents in Parallel and in the Background covers.
A worked example shows why limits matter. Suppose (illustrative prices; check current ones) a model costs $3 per million input tokens and $15 per million output tokens, and your app's "ask about my spending" button sends about 2,000 tokens and gets back about 300:
Two users asking 20 questions a day for 30 days is 1,200 questions: about $12.60 a month. Now a front-end bug retries in a loop, or a bot finds the endpoint, at ten requests a second: 864,000 calls a day, about $9,000 a day. Same formula, different input. OWASP's LLM list calls this unbounded consumption, and the defences are limits enforced by code and by the provider:
- A spending limit: a hard monthly cap in the provider's console, with an alert well below it, on a separate API key for each app.
- A
max_tokenscap and a timeout on every call. - A per-user rate limit, and AI features only for logged-in users.
- Cheaper models for simple jobs, and caching (Building AI Products).
Docs and maintainability
Code nobody understands can't be changed safely, by you or by an agent. Agent-written code arrives fast and in bulk, and parts of it you may never have read. That technical debt comes due the first time something breaks in a part you don't understand. Habits that keep it payable:
- Understand what you ship. You should be able to say in two sentences what each module does. If you can't, ask the agent to explain it, then to simplify it. Agents over-engineer, and simplifying is a task they do well when asked.
- A README for humans (how to run, test and deploy it, which variables it needs) and a memory file for agents (Project Context and Memory Files) with this chapter's rules written in.
- A runbook: a short document saying what to do when things go wrong: how to roll back, restore a backup, rotate each key, find the logs. Write it calmly, before the panic.
- Tests for every production bug (Tests as Guardrails), so it can't return, and small, regular dependency updates rather than a frightening yearly one.
Worked example: taking tally online
So far tally has been a command-line tool on your laptop. You and your partner want to log shared expenses from your phones, so an agent built tally-web: a small Flask app with logins, an SQLite database, and an "ask about my spending" button that sends a month's expenses to a model API. It works and the tests pass. Before it goes online, you run the checklist.
1. A review in a fresh session. A clean context hasn't talked itself into the code's correctness. Some agents have a built-in command (Claude Code's /security-review, as of 2026), but a plain prompt works anywhere:
> You are reviewing tally-web before it goes on the public internet. Don't
change any code. Check: secrets in code or git history; every route for
login and ownership checks; input validation; HTML escaping of user and
model text; every package in requirements.txt; debug settings; limits on
the model call. Report each finding with file, line, severity and a fix.
It reports seven findings. You verify each yourself, because review agents also err and miss things.
2. Secrets. git log --all --oneline -- .env shows an early commit, from before .gitignore existed, that contains .env. The repository is private, but you treat the key as leaked: revoke, replace, set the new one only on the host. And app.secret_key falls back to "dev"; replace it with require().
3. Authorization. POST /expense/<id>/delete checks login but not ownership. You have the agent write the failing test first (log in as user 2, delete user 1's expense, expect 404), then the fix, then search for the same pattern elsewhere. The edit route had it too.
4. Dependencies. requirements.txt lists flask-csv-guard, from a session about CSV export. The checker says it isn't on PyPI; the import was never used, which is why nothing crashed. Delete it. pip-audit flags one outdated package; update it and rerun the tests.
5. Output. The summary page shows the model's answer with Jinja's |safe filter, which turns escaping off. The prompt includes categories typed by users, so a crafted category could make the model emit a <script> tag that runs in your browser. Remove |safe and render Markdown with a library that sanitises HTML.
6. Deployment. app.run(debug=True) goes; production runs gunicorn with debug off. Daily backups go on, and you restore one into a scratch copy.
7. Monitoring and costs. /health, an uptime check and error tracking. The model call gets max_tokens=500, 20 questions per user per hour, and its own key with a $20 monthly cap.
8. Docs. The agent updates README.md and writes RUNBOOK.md; you add three lines to AGENTS.md: secrets only from the environment, an ownership check on every route that takes an ID, no |safe on user or model text.
None of these took long. Every one was invisible in the demo.
The checklist
Copy it into your project. Ask the agent to report against it before every launch and after large changes, then check its answers.
Tip
- Secrets: none in code, tests, logs or git history;
.envignored,.env.examplecommitted; the app stops if one is missing; secret scanning on; leaked keys rotated; the agent has no production credentials.- Auth: framework or hosted login, no custom password code; every route and query that takes an ID checks ownership, proven by a two-user test.
- Input and output: allow-list validation with tests for nasty inputs; placeholders in queries; no input in shell commands; templates escape by default; model output treated as untrusted.
- Dependencies: each one chosen by a human, real and established; versions locked;
pip-audit/npm auditclean; Dependabot or similar on.- Deployment: debug off, HTTPS, deployed from a tested commit; rollback known; backups restored at least once.
- Monitoring: health check with alerts; error tracking; logs without secrets or passwords.
- Costs: provider spending limit and alert;
max_tokens, timeouts and per-user rate limits on model calls.- Maintainability: README, runbook and memory file current; you can explain every module; tests run in CI.
For anything handling money, health data or other people's personal data at scale, this is a minimum. Get a human security review and check the law that applies (Privacy, Data and Copyright, AI Regulation and Governance).
Common mistakes
- Asking "is this secure?" The agent will usually say yes, or list generic advice. Ask checkable questions ("for each route, which line checks the user owns the record?") and verify the answers.
- Fixing one instance. Bugs come in families. When you find a missing ownership check, have the agent find every other one.
- Installing whatever the agent suggests. Check that a new package exists and who publishes it.
- Deleting a leaked key and moving on. It is still in the history. Rotate it.
- Setting spending limits after the bill. Set them before launch.
- Letting the agent touch production. Deploys, migrations and production credentials stay behind a human.
Watch out "The agent wrote it and the tests pass" is not evidence of security. Tests check what someone thought to test, and agents test the happy path. Security bugs live in cases nobody wrote down: the other user's ID, the strange input, the key in an old commit. Look for them on purpose.
Where it leads
- Tests as Guardrails: turn each checklist item into a test that runs on every change.
- Extending Your Agent: Skills, Hooks, MCP and Subagents: hooks that stop an agent reading
.envor installing packages without asking, and a reviewer subagent with this checklist built in. - Running Agents in Parallel and in the Background: review agents in CI, and keeping several agents' costs in check.
- Prompt Injection and LLM Security: the security problem specific to AI features, and to the agent itself.
- Deploying Models and Monitoring and Data Drift: deployment and monitoring in more depth.
- Building AI Products: guardrails, cost control and iteration for products built around a model.
Try it
- Run the checklist on a project an agent built for you, marking each item pass, fail or "don't know". Every "don't know" is a task.
- Run
git log --all --oneline -- .envand a secret scanner (for examplegitleaks git .) on your repository. Did anything ever leak?- In three fresh sessions, ask an agent for "a Python script that does X with the best library" for some niche X. Run the checker script on every package it names. Did any not exist? Did the same names recur?
Hint for 1: the quickest failure to find is usually authorization. Make two accounts, log in as the second, and try the first account's IDs in every URL.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
OWASP Top 10
The standard awareness list of the ten most critical web application security risks, from broken access control to supply-chain failures, each with examples and prevention advice. The 2025 edition is the current one as of late 2026.
The 70% problem: Hard truths about AI-assisted coding
Why AI gets non-experts most of the way to a working app quickly and then stalls, and what the remaining 30% (edge cases, security, maintainability) demands of you.
OWASP Cheat Sheet Series
Short, practical guides by security practitioners on specific topics: authentication, authorization, input validation, SQL injection, secrets management, logging. Ideal to hand to an agent as a spec.
GitHub Docs: secret scanning
How GitHub detects API keys and passwords committed to repositories (free for public ones), how push protection blocks them before they land, and what to do when an alert fires.
We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs
Measures how often 16 code models recommend software packages that don't exist (at least 5.2% of packages for commercial models, 21.7% for open ones) and why attackers can exploit it.
The Twelve-Factor App
A short, durable set of principles for software that runs as a service: config and secrets in the environment, explicit dependencies, logs as event streams, and identical development and production setups.
Claude Code security
How Claude Code's permission system, sandboxing and prompt-injection protections work, and the practices Anthropic recommends when working with untrusted content.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/shipping-with-agents.md