[
  {
    "id": "vibe-coding",
    "title": "Vibe Coding\nwith Confidence",
    "subtitle": "The Vibecoder's Handbook, from idea to production",
    "tagline": "Build Reliable Apps That Survive Production.",
    "description": "Plan it. Build it. Debug it. Ship it. Scale it. With AI as your engineer.",
    "author": "Mahmoud Zalt",
    "authorRole": "Principal AI Architect",
    "status": "available",
    "url": "https://zalt.me/guides/vibe-coding",
    "premium": {
      "price": 29.99,
      "currency": "USD",
      "displayPrice": "$29.99",
      "access": "lifetime",
      "purchaseUrl": "https://buy.stripe.com/6oUdRa3uzdKOgCN8qPawo01"
    },
    "coverImage": "/images-optimized/books/vibe-coding-cover-medium.webp",
    "edition": "2026 Edition",
    "version": "v2.0",
    "parts": [
      {
        "id": "intro",
        "title": "What this book is & how to read it",
        "chapters": [
          {
            "slug": "start-here",
            "title": "Preface",
            "label": null,
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/intro/start-here",
            "content": "---\ntakeaway: Build the app, and the system that runs it\nshare: \"Anyone can get AI to build an app in a weekend; almost nobody keeps it alive a month later. This handbook hands you the system that closes that gap: idea to live software, the AI building and you in control.\"\nrequires: []\nproduces: []\nteaches: [agent-operating-system, ai-as-junior-developer, agentic-sdlc]\nuses: [ai-coding-agent, codebase, prompt, test, code-review]\n---\n\nWelcome. If you are reading this, you have likely felt both ends of building software with artificial intelligence. First comes the electric rush of spinning up a working application in an afternoon. Then comes the sinking feeling a week later when it breaks, and you cannot trace why.\n\nHere is what you already suspect. Anyone can prompt an AI to generate an app over a weekend. Almost nobody can keep that app alive, structured, and running a month down the line. The difference is not raw coding talent. It is a system, and this handbook hands it to you: from initial vision to live software, the AI executing the build, you in full control.\n\n## Learn while Building: Read, Prompt, Build\n\nThis handbook is designed as an interactive blueprint for your codebase. Every single chapter comes equipped with a production-ready prompt engineered for your AI coding agent.\n\nYou do not simply read theory here. You run these prompts sequentially directly inside your own repository. As you progress through each chapter, you learn essential engineering principles while your AI agent builds out the exact system and foundation in real time. By the time you finish reading, your application and the automated infrastructure behind it are already standing.\n\n## If You Ship it, You Own it\n\nOne truth comes first. Once real users touch your software, every decision is yours. The AI writes the source code, but your name, your product, and your reputation sit on the result.\n\nKeep that in mind at every step. This handbook hands you the framework to move at maximum speed without pretending responsibility vanishes because an agent typed the characters.\n\n## You Build the Factory, Not Just the Car\n\nMost guides end when the application boots up. This book starts there. The real asset is not just the single product you launch today. It is the operating system inside your repository that builds, tests, maintains, and scales your product going forward.\n\n```mermaid\n%% caption: The AI engine runs the loop, pausing only for your approval.\nflowchart LR\n  A[1. AI builds feature] --> B[2. Automated tests run]\n  B --> C[3. AI proposes deploy]\n  C --> D([4. You approve])\n  D --> E[5. Ships to live users]\n  E --> A\n```\n\nYou sit in the driver seat as the executive architect. The AI operates as your tireless engineering department, executing builds, running test suites, and surfacing clear options for your approval. Only the decisions that could cause real damage wait for your explicit command.\n\nThat loop has a name, the **agentic SDLC**, and the fifteen stages of this book are it. The first stage defines the system properly; every stage after hands it one more piece.\n\n## You Direct It, You Do Not Out-Code It\n\nYou do not need every single line of code in your head. No senior engineer operates like that.\n\nYou need the architectural mental model: how pieces connect, where data flows, and where vulnerabilities hide. Think of your AI as an exceptionally fast junior developer: brilliant, tireless, and wrong just often enough to matter. You supply the senior judgment; the AI supplies the execution speed.\n\n## What You Walk Away With\n\nYou gain a modular, clean codebase where adding new features never breaks existing functionality. You step away with a fully configured AI operating system tailored to your exact workflow.\n\nThis framework covers the full lifecycle path from start to finish: set up, plan, architect, build, inspect, amplify, debug, test, automate, harden, secure, protect, ship, operate, and scale.\n\n## Who This Is For\n\n- **Founders and Builders without a coding background.** You can prompt an AI, but you need to know how real software is structured so it does not collapse under real traffic.\n- **Developers building with AI daily.** Speed is no longer your bottleneck. Fragile output and technical debt are. This gives you an AI-native workflow built for modern development.\n\nBoth want the same thing: software that holds up. Not a demo, not a prototype, not a landing page. A real application with a server behind it, real users, real data, and a reason to still be running next year.\n\nWhat that application looks like from the outside is up to you. A website, a phone app, a desktop tool, a browser extension, a plugin inside someone else's platform: the shell changes, the engineering behind it does not. This handbook covers all of them at once, because they all sit on the same backend you are about to build.\n\nIf you already run large-scale production infrastructure for a living, hand this book to the person who keeps asking you how you do it.\n\n## Built for How Software Is Created Now\n\nTraditional software development principles were created for a world where human typing speed and human memory were the main constraints. That world no longer exists.\n\nThis handbook asks one fundamental question: if you designed a software engineering process today with powerful AI agents at your disposal, how would you build? Some legacy rules still hold. Most do not. Knowing the difference is your real competitive edge."
          },
          {
            "slug": "how-to-read",
            "title": "How to Read Me",
            "label": null,
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/intro/how-to-read",
            "content": "---\ntakeaway: Read it in the order you build\nshare: \"How to read this handbook: it runs in the exact order you build real software, each stage producing what the next stage needs, so you are never stuck starting a step without what it takes to finish it.\"\nrequires: []\nproduces: []\nteaches: [defer-vs-invest, over-engineering]\nuses: [ai-coding-agent, operating-system, stack, model, prompt, spec, module, test, ci, database, hosting]\n---\n\nBefore you build anything you need the lay of the land: where to start, what you need, and what order to move in. This book runs in the exact sequence you build real software, each stage producing what the next one requires. Read it in order, run the prompts as you go, and you will never be stuck starting a stage without what it takes to finish it.\n\n## Fifteen Stages, One Path\n\nEvery chapter is a stage of a production lifecycle, ending with something real in your codebase:\n\n1. **Set Up:** A working agent, a chosen stack, and a running foundation app.\n2. **Plan:** A structured spec your AI agent can build from cleanly.\n3. **Architect:** A modular codebase layout that grows without rewrites.\n4. **Build:** Your application features, delivered in reviewable slices.\n5. **Inspect:** The core skill to open files, recognize patterns, and judge quality.\n6. **Amplify:** Real intelligence and agentic workflows integrated into your product.\n7. **Debug:** The systemic skill to unstick your agent when it loops.\n8. **Test:** An automated safety net that catches failures before users do.\n9. **Automate:** The operating system you and your agents run everything from.\n10. **Harden:** The rough edges rounded off into a complete product.\n11. **Secure:** An application that actively defends its data, endpoints, and users.\n12. **Protect:** User data handled responsibly, securely, and legally.\n13. **Ship:** Your software deployed live on real production infrastructure.\n14. **Operate:** A running system you can observe, monitor, and keep healthy.\n15. **Scale:** Growth without bottlenecks, knowing your system limits.\n\nThe first ten stages are free end to end. The final five, Secure through Scale, are the premium operations playbook: each opens with a free chapter, and the full suite unlocks together.\n\n```mermaid\n%% caption: The fifteen stages across five phases, from a fresh computer to production scale.\nflowchart LR\n  subgraph P1[1. Get Ready]\n    SETUP[Set Up] --> PLAN[Plan] --> ARCH[Architect]\n  end\n  subgraph P2[2. Make It Work]\n    BUILD[Build] --> READ[\"Inspect\"] --> AMP[Amplify] --> DEBUG[Debug] --> TEST[Test]\n  end\n  subgraph P3[3. System]\n    AUTO[Automate]\n  end\n  subgraph P4[4. Make It Solid]\n    HARD[Harden] --> SEC[Secure] --> PROT[Protect]\n  end\n  subgraph P5[5. Take It Live]\n    SHIP[Ship] --> OP[Operate] --> SCALE[Scale]\n  end\n  P1 --> P2 --> P3 --> P4 --> P5\n```\n\nEach stage feeds the next, which is why the order is non-negotiable. You have a running application by the end of stage one, and every prompt after that operates on a real, evolving system.\n\n## All You Need Is a Computer and an Agent\n\nThis handbook assumes a completely fresh computer. Editors, keys, and cloud accounts arrive only when you actually need them. You need two things to start:\n\n* A computer running macOS, Linux, or Windows.\n* An AI coding agent. Stage 1 guides you through selecting and setting one up.\n\nYour agent is the execution engine; this book is the supervisory judgment. It teaches what to demand, what prompts to run, and how to verify the output is solid.\n\n**Already have something half-built?** A weekend app, a template, a project you inherited: you are not starting over. Stage 1 has a chapter that surveys what you own, scores it against these fifteen stages, and hands back a shortened reading list.\n\n## Follow the Stages in Order\n\nWork through the handbook sequentially on your first pass. Because every prompt relies on the architecture built in previous steps, jumping ahead leaves your AI agent without necessary context.\n\nOne thing is not a stage at all. Your AI operating system, the rules, records, and agents that keep the app alive, is defined on your first day and gains a piece in almost every stage after:\n\n| Stage | What it adds to your system |\n|---|---|\n| Set Up | Its definition, the standing rules, the work loop |\n| Plan, Architect | The spec, the layout, the reasons |\n| Build, Test | Gates that block bad work unattended |\n| Automate | The crew, the board, the log, the schedule |\n| Ship, Operate | Version stamps, verdicts on what worked |\n\nSo you never skip ahead to get it. Automation is only safe once you have done the work by hand and can judge what comes back.\n\nAfter your first complete build, use this book as an operational manual. When a deploy fails or a database bottlenecks, jump straight to that chapter for the diagnostic prompt.\n\n## What to Build Now vs. What to Defer\n\nOne golden rule decides what to add: defer what is cheap to add later, invest now in what is brutal to retrofit.\n\nIf you could wire a component in an afternoon once users demand it, defer it. Building it early is over-engineering: solving problems you do not yet have. If skipping a practice now forces a painful rewrite later, set a baseline today.\n\n* **Defer:** CI/CD, multi-region clusters, microservices, complex caching, all before real traffic.\n* **Invest now:** Automated testing, modular boundaries, clear specs, version control, basic security defaults.\n\n## The Side-by-Side Workflow\n\nKeep your agent open right next to this handbook. You read on the same screen where it runs, so each prompt goes straight into your repository as you finish a section, and your codebase advances in lockstep with your reading.\n\n```mermaid\n%% caption: Your code and understanding move forward together.\nflowchart LR\n  A[Read Concept] --> B[Copy Prompt] --> C[Agent Executes in Repo] --> D[System Upgraded]\n```\n\n## Prompts Are Starting Points, Not Gospel\n\nEvery prompt is a battle-tested template, not a rigid script. Copy it, then adapt the wording to your product and architecture; the judgment inside it stays constant.\n\nThe same holds for recommended stacks and tools: reliable defaults. When your agent suggests a better fit, trust the judgment taught here and adapt.\n\n## Short by Design, Deep on Demand\n\nThis book is intentionally lean: you no longer need 800 pages of syntax your AI can explain in seconds.\n\nIt concentrates on direction, architecture choices, and supervisory judgment. For deeper context on anything here, feed the chapter to your agent and ask follow-ups until it clicks."
          },
          {
            "slug": "the-author",
            "title": "About the Author",
            "label": null,
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/intro/the-author",
            "content": "---\ntakeaway: Every move has a reason\nshare: \"Every vibecoding guide has the same gap: one narrow slice, vague, or long on what and silent on why. Here is the track record behind a handbook where every move carries its reason.\"\nrequires: []\nproduces: []\nteaches: [vibe-coder]\nuses: [ai-coding-agent, model, open-source]\n---\n{/* KEEP: this page = trust (job 4) + payoff (job 5). Lead-in = vibecoding handbooks are flooding out, author actually surveyed them, they share one gap (too narrow, or vague, or they say what to do but never WHY). This book's edge = the reason behind every move, which the reader has already felt reading this far. Then pivot to the track record. Do NOT regress to narrating the page's three sections. */}\n\nVibecoding handbooks are everywhere now, and more land every week. I read through what is out there, and each one has the same gap: zoomed onto a single slice, or vague, or long on what to do and silent on why. You have read this far, so you can already feel the difference here, every move carries its reason. Here is the track record behind that voice.\n\n{/* KEEP: concrete credentials: 16 years; ~100 projects built from scratch (the phrase itself links to /projects, like the OSS links below); ~another 100 managed, architected, or contributed to; 3 continents; OSS (Laradock, Apiato, Porto); Sista AI = solo-built, guides startups through AI transformation; Sistava = solo-built platform for running an entire business on AI agents. Mention for CREDIBILITY only, keep it factual and understated, not a promo/CTA (user is explicit about this). */}\n\n## I have shipped over a hundred projects\n\nMahmoud Zalt, sixteen years shipping software. Around [100 projects](/projects) built from scratch, and roughly another 100 managed, architected, or contributed to, with top teams across three continents. More on [LinkedIn](https://www.linkedin.com/in/mahmoudzalt).\n\nMore than ten open-source projects, including [Laradock](https://laradock.io), [Apiato](https://apiato.io), and [Porto](https://porto.zalt.me), tools other engineers build their own systems on. Full list on [GitHub](https://github.com/Mahmoudz).\n\nTwo companies built solo: [Sista AI](https://sista.ai), guiding startups through their AI transformation, and [Sistava.com](https://sistava.com), a platform for running an entire business on AI agents.\n\n{/* KEEP: humble + professional, do NOT criticize other teachers. Track record = 16 years building through every shift in the field; early AI adopter who went through every phase as the tools improved; with AI has shipped many products of his own and helped many others do the same (NO numbers, no \"proudest of\" style). This continuity is the credibility. */}\n\n## I adopted AI early, and kept shipping\n\nFor sixteen years I have built software, adapting through every shift the field went through. When AI coding arrived I was among the first to adopt it, and I have stayed with it through every phase, rebuilding how I work as the tools grew more capable.\n\nWith AI I have shipped many products of my own, and helped many others do the same.\n\n{/* KEEP: openly written with AI (best model available), section by section with human ordering and judgment; the onboarding-a-junior frame (if you joined my team, this is what I'd tell you). */}\n\n## AI drafted it, I ordered it\n\nThis book was written with AI, and I will say so plainly: the most capable model available at the time did the drafting. But nothing here was generated in one pass. Each section took hours of back-and-forth, pulling what I know into words and into an order a beginner can actually follow.\n\nThat ordering is the real work, and the part AI still cannot do alone. It is what I would do sitting beside a new junior on their first day: not everything at once, but the right thing next, until they can build on their own.\n\n{/* KEEP: payoff = you become a professional vibe coder (idea to live, maintained software, AI as builder); then it is practice, build real projects with AI guiding you (the thing the author never had), until you can do what a junior engineering role asks for. NO vanity counts (\"three systems\"). */}\n\n## What you walk away with\n\nYou will not write code by hand, and you will not need to. Work through this book and you become a professional vibe coder: someone who takes an idea all the way to live, maintained software, with AI doing the building.\n\nFrom there it is practice. Build real projects this way, with something I never had sixteen years ago, an AI guiding you the whole way, and before long you can do what a junior engineering role actually asks for.\n\n{/* KEEP: contact = the \"How to Contact Us\" convention, folded into the author page instead of a standalone page. Email + contact page + the per-chapter discussion thread. Understated, an open door, not a CTA. */}\n\n## How to reach me\n\nFound an error, have a question, or just want to tell me what worked? Write to me at [mahmoud@zalt.me](mailto:mahmoud@zalt.me), or use the [contact page](/contact). Every chapter also has its own discussion at the bottom, often the fastest way to get an answer where others can see it too."
          },
          {
            "slug": "colophon",
            "title": "Colophon",
            "label": null,
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/intro/colophon",
            "content": "---\ntakeaway: Know what you can do with this book\nshare: \"The fine print behind the handbook: who owns it, what you are free to do with it, and where its advice stops.\"\nrequires: []\nproduces: []\nteaches: [living-book, premium-unlock]\nuses: [license]\n---\n{/* KEEP: the colophon / copyright page, the web equivalent of a published book's front matter. Three jobs: edition + revision history (it is a living book, you always have the current one), copyright + license (what a reader may do, links to /terms), and a plain-English legal disclaimer (education only, not legal advice, follow it at your own risk). Plainer voice than the rest of the book on purpose, this is the fine print. */}\n\nYou are going to build something real with what this book teaches. Sooner or later you need to know who owns these words, what you are free to do with them, and where the advice stops being enough on its own. This page settles all three.\n\n- What is free and what is premium.\n- What you can and cannot reuse from the book.\n- Which parts are guidance, and where you still need professional advice.\n\n## Open to build, premium to run\n\nThe split is simple. The open chapters get you from idea to a real built app. The premium chapters cover running that app safely with real users: deploying it, security, data responsibility, operations, and scale.\n\nIt is one unlock, not a subscription. If the open half does not already prove useful for your project, do not unlock yet.\n\n{/* KEEP: edition + revision line, and the living-book point, because it lives on the web you always read the current edition, no reprint. */}\n\n## Edition and revisions\n\n**Vibe Coding with Confidence**, 2026 Edition (v2.0), first published July 2026.\n\nThis is a living book. It is revised as tools and practice change, so the edition above is the one in front of you now, and later ones may read differently. Because it lives on the web, you always have the current version, no reprint required.\n\n{/* KEEP: copyright + license = what a reader may and may not do, in plain terms, with the full terms one link away. */}\n\n## Copyright and license\n\nCopyright &copy; 2026 Mahmoud Zalt. All rights reserved.\n\nThe words, the structure, and the examples here are the author's work. You are welcome to read the book, link to it, quote short passages with attribution, and use everything you learn in your own projects, commercial or not. You may not republish the book or large parts of it as your own, or resell it, without written permission.\n\nThe full terms live on the [Terms](/terms) page.\n\n{/* KEEP: the legal disclaimer, the \"not legal advice / at your own risk / third-party licenses are your responsibility\" trio a published book carries. Ties back to the Secure and Protect parts: they teach the shape of the problem so you know what to ask, they do not replace a professional. */}\n\n## Disclaimer\n\nThis book is provided for education, as is, with no warranty of any kind. The author is not liable for any loss or damage that comes from following it. The tools, code, and services it mentions carry their own licenses and terms, and making sure your use complies with them is your responsibility.\n\nNothing here is legal, financial, or professional advice. The chapters on security, privacy, and compliance explain the shape of those problems so you know what to ask for. They are not a substitute for a qualified professional. The moment what you build touches real user data, payments, or the law, get proper advice."
          }
        ]
      },
      {
        "id": "setup",
        "title": "Get your tools and a running app ready",
        "chapters": [
          {
            "slug": "set-up-your-workspace",
            "title": "Let's Start Vibe Coding",
            "label": "Workspace",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/set-up-your-workspace",
            "content": "---\ntakeaway: Ready your machine first\nshare: Set up a clean coding workspace, a terminal, and your AI agent on the computer you already own, before you write a single line of code.\nrequires: []\nproduces: [editor, terminal-access, ai-agent, paid-agent-plan, project-folder, readme]\nteaches: [operating-system, ai-coding-agent, model, terminal, command, prompt]\nglosses: []\n---\n{/* KEEP: this is the book's real first working chapter (Set Up ch1, the very first thing the reader does). Before any step makes sense you need two things: a place to write and an AI agent (you won't type code by hand). Sets both up on the computer you already own, introduces the terminal (the one layer every later chapter assumes), and leaves a project folder with a README in it. Do NOT create a specs/ folder here: specs are not explained until the Plan part, and the chapter that first writes one creates it. Absorbs the old dev-environment chapter. */}\n\nBefore any step in this book makes sense, you need two things: a place to write, and something to write with. You will not type code by hand, so that something is an AI agent. This chapter sets both up on the computer you already own, and leaves you a project folder with your first file in it.\n\n{/* KEEP: your existing OS (Windows/macOS/Linux) is the ground floor and enough; any recent laptop works (8GB ok, 16 comfortable); buy nothing, switch nothing. Bold-first: operating system. */}\n\n## Your own computer is enough\n\nYour computer already runs Windows, macOS, or Linux. That is its **operating system**, the ground floor everything else installs onto, and any of the three builds everything in this book.\n\nAny laptop from the last few years is enough: 8 GB of memory works, 16 GB is comfortable. Buy nothing and switch nothing, you start from what you have.\n\n{/* KEEP: the one thing you cannot skip = an AI coding agent (writes and changes your code); it's the engine of the book since you don't hand-write code. Two things decide quality: the agent itself AND the model powering it, watch both. Bold-first: AI coding agent, model. */}\n\n## The agent matters more than the editor\n\nThe one thing you cannot skip is an **AI coding agent**: the program that actually writes and changes your code. Since you never type code by hand, the agent is the engine this whole book runs on.\n\nTwo things decide how good it is: the agent itself, and the **model** powering it, the AI brain it thinks with. Keep an eye on both. A sharp agent on a weak model, or the reverse, will let you down.\n\n```mermaid\n%% caption: Your workspace: the editor and agent work on your code, with a model behind the agent.\nflowchart LR\n  subgraph COMP[Your computer]\n    ED[Your editor] --> AG[AI agent]\n    AG -->|reads and writes| CODE[(Your project code)]\n  end\n  AG -->|runs on a model| M[AI model]\n```\n\n{/* KEEP: CONCRETE install step, no prompt yet (the reader has no agent to paste one into, that was the old circularity). Two named paths: VS Code + agent if more technical, agent-first tool if simplest. Then the three real steps everyone hits: install, sign in, pay for a plan. Do NOT prescribe only VS Code. Keep the paid-plan point, it is the one nobody warns them about. */}\n\n## Install one agent and sign in\n\nWhere you and the agent work together is your choice, and it matters far less than the agent itself. Pick one of these two now:\n\n- **Want the simplest path?** Install an agent-first tool like [Claude Code](https://claude.com/claude-code), [Codex](https://developers.openai.com/codex), [Cursor](https://cursor.com), or [OpenCode](https://opencode.ai), where the agent is the whole interface.\n- **More technical, or want full control?** Install [VS Code](https://code.visualstudio.com), a free editor from Microsoft, and run your agent inside it.\n\nInstalling is a download and a normal install, the same as any other app. Then two steps people are never warned about: you create an account, and you pay for a plan. You will run this agent constantly, so a plan that keeps up matters more than the exact tool you land on.\n\n> **Hint:** In 2026, [Claude Code](https://claude.com/claude-code) is the strongest agent for this, and it is the one this book uses. New options appear all the time, so ask your agent or search for the current best, then pick the one you feel comfortable in.\n\n{/* KEEP: three plugins the author personally uses, named so a reader on Claude Code gets a concrete starting set instead of an empty marketplace. Also install THIS book's own skill (vibe-coding-book), which is free, self-referential, and the natural fourth. Close with \"search for more as you need them\" so the list doesn't read as exhaustive or go stale. */}\n\n## Worth adding on day one\n\nIf you picked Claude Code, a few plugins are worth installing before you write your first prompt:\n\n- **[Superpowers](https://github.com/obra/superpowers)**, a library of skills that keeps the agent from skipping steps like planning and testing.\n- **Ponytail**, which pushes back on over-engineering and keeps the agent's solutions as small as the problem actually is.\n- **chrome-devtools-mcp**, which lets the agent open a real browser and see your app the way a user would, instead of guessing from the code.\n- **[This book's own skill](https://github.com/Mahmoudz/vibe-coding/tree/main/skills/vibe-coding-book)**, so your agent knows what this handbook covers and can point you at the right chapter instead of you hunting for it.\n\nAsk your agent to find and install each one by name. As you hit a specific need later, chapter by chapter, ask it to search for a plugin for that need too, the right set grows with your project instead of being decided all at once here.\n\n{/* KEEP: the money answer nobody gives a beginner, placed right after \"you pay for a plan\" so the first real question gets a real number. Three facts: ~20 a month for a usable plan and 100-200 for heavy daily building; two billing doors (flat plan vs pay-per-use) and why the flat plan is the right default for an agent that reads whole files; free tiers throttle exactly mid-build. Plain prose, no callout, there is already one above. Do NOT use the word token here, it is taught much later. */}\n\n## The agent is your only real cost until you deploy\n\nBudget for this before anything else. A usable plan starts around 20 US dollars a month, and the heavier tiers that survive a full day of building run 100 to 200.\n\nTwo doors reach the same models. One is a flat monthly plan; the other is pay-per-use billing, charged by how much text the agent reads and writes. Take the flat plan, because an agent reads whole files all day, and per-use billing is how people get a shocking bill in week one.\n\nFree tiers exist, and they throttle you exactly when you are mid-build. Fine for an evening of trying a tool out, not something to build on.\n\n{/* KEEP: THE MISSING LAYER (sequencing fix, July 2026). Every later chapter says \"run this command\" and the book never said where. Terminal = the text panel where commands go; it ships with your computer and inside VS Code; your agent runs commands there itself, so you mostly watch and approve. Also covers the permission prompt, which is the first confusing thing a beginner meets. Bold-first: terminal. */}\n\n## Meet the terminal, where commands run\n\nA **command** is one line of text that tells your computer to do something, and it goes in the **terminal**: a plain text panel where you type that line and your computer runs it. The terminal already ships with your operating system, and VS Code has one built in, so there is nothing to install.\n\nYou will barely use it by hand. Your agent runs commands there itself and shows you the output, usually asking permission first. That prompt is not a warning, it is the agent doing what it should: telling you before it touches your machine.\n\n{/* KEEP (corrected July 2026): create ONE project folder and ONE README, nothing else. The old version created a specs/ folder here and glossed \"spec\", ten chapters before the Plan part explains what a spec is or writes one. Every folder is created by the chapter that first puts something in it; do not pre-create empty folders for later parts. */}\n\n## Make a folder and your first file\n\nCreate one new folder on your computer for this project; it will hold everything you build. Inside it, put a single `README.md` saying, in your own words, what you are building. That is your whole workspace today.\n\nThat file is not paperwork. It is the first thing your agent reads to know what this project is, and it keeps growing as the project does. Every other folder gets created by the chapter that first needs it.\n\n{/* KEEP: the prompt runs INSIDE the agent the reader just installed (no longer the old circular \"have your agent pick your agent\"). It verifies the install, sets up the folders, and confirms the terminal works. Senior voice, fixed top + one append slot. Also has it install the 4 plugins from \"Worth adding on day one\" (named, so it doesn't invent substitutes) plus anything else relevant to the stated goal, so the plugin list above isn't just read, it gets acted on. Ends with Do this now. */}\n\n## Have your agent finish the setup\n\nEvery chapter from here ends with a **prompt**: a block of text you copy and paste to your agent as its instructions. This is your first one. With the agent installed, open it and paste this. It checks your machine, builds your folders, and confirms everything works before you go further:\n\n```prompt\nAct as a patient senior engineer setting someone up to\nbuild software with AI for the first time. Assume I have\nnever coded and have just installed you. Do the following,\nexplaining each step in plain words as you go:\n- Confirm what operating system I am on and that you can\n  run commands in my terminal.\n- Create a project folder for me, and inside it one\n  README.md saying what I am building, in my own words\n  from below. We add to that file as the project grows.\n- Open that folder as my working project and show me the\n  file tree so I can see what exists.\n- Tell me anything on this machine that will bite me\n  later, and fix it now if it is safe to.\n- If you are Claude Code, find and install these plugins:\n  Superpowers, Ponytail, chrome-devtools-mcp, and the\n  vibe-coding-book skill from github.com/Mahmoudz/vibe-coding.\n  Then, based on what I want to build below, search for\n  one or two more plugins worth adding now, and tell me\n  what they do before installing them.\n\nMy computer and experience:\n- Computer: (Mac, Windows, or Linux, roughly how old)\n- Coding experience: (none, a little, or comfortable)\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/set-up-your-workspace\n\n- What I want to build, in one sentence:\n```\n\n**Do this now:** install your agent, sign in, pay for a plan, then paste the prompt and let it set up your project folder and write your first README."
          },
          {
            "slug": "meet-your-ai-agent",
            "title": "Meeting Your AI",
            "label": "Agent",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/meet-your-ai-agent",
            "content": "---\ntakeaway: Treat your AI as an agent, not a chatbot\nshare: Your AI agent is not a chatbot that answers questions, it reads your files, runs commands, and changes your code. Knowing what it can and cannot do, and where its limits are, is what separates steering it from hoping.\nrequires: [ai-agent, project-folder]\nproduces: []\nteaches: [context]\nuses: [ai-coding-agent, command]\n---\n{/* KEEP: lead-in = you picked an agent in Workspace; now understand what it actually IS so you can steer it instead of hope. Not tool-picking (that's Plan ch1), this is the mental model of working with an agent. */}\n\nYou already picked an agent back when you set up your workspace. Now you need to understand what it actually is, because the difference between steering it and just hoping comes down to knowing how it works. This chapter gives you that mental model.\n\n{/* KEEP: an agent is NOT a chatbot that just answers; it reads your files, runs commands, writes and changes code, and checks its own results, in a loop, inside your project. It acts, it doesn't just talk. Bold-first: agent. */}\n\n## What an agent actually is\n\nAn **agent** is not a chatbot that answers questions. It reads the files in your project, runs commands, writes and changes code, sees what happened, and goes again, in a loop, until the task is done.\n\n```mermaid\n%% caption: An agent works in a loop: read, run, change, check, then go again.\nflowchart LR\n  R[Reads your files] --> C[Runs commands]\n  C --> W[Writes and changes code]\n  W --> S[Sees what happened]\n  S -->|loop until done| R\n```\n\nThat is the whole shift: a chatbot talks, an agent acts. It works inside your actual project, on your actual files, which is why everything in this book is about directing that action well.\n\n{/* KEEP: what it CAN do (write/refactor/wire features/fix errors/explain code fast) vs what it CAN'T (know your intent, decide what's worth building, judge good-enough, own the consequences). It is astonishing at the how, blind to the whether/why. That gap is the reader's job. */}\n\n## What it can and can't do\n\n| It's brilliant at | It cannot |\n|---|---|\n| writing and refactoring code | know what you actually want |\n| wiring up a feature | decide what's worth building |\n| reading an error and fixing it | judge when it's good enough to ship |\n| explaining a strange file in seconds | own the consequences |\n\nGive it a clear task and it outruns any human at the typing. But it is brilliant at the *how* and blind to the *whether* and the *why*, and that gap is exactly your job.\n\n{/* KEEP: agents work from CONTEXT (what's in front of them right now: open files, your message, what it just read), NOT long-term memory; it forgets between sessions. So you must feed it the right context each time; the rules file and a clear spec are how you make the important context always present (forward-points to the Rules chapter without naming mechanics). Bold-first: context. ALSO KEEP (added July 2026): the first-aid version of the finite-context problem, three sentences max. There is a ceiling on what it holds at once, a long session goes vague, the move is a fresh session, and the Build part owns the real skill. Do NOT name or define \"context window\" here, that term belongs to the context-engineering chapter and must stay its first definition. */}\n\n## It works from context, not memory\n\nAn agent works from **context**: what is in front of it right now, your message, the files it has open, what it just read. It does not carry a memory of your project between sessions the way a teammate would. Close it, reopen it, and it starts fresh.\n\nSo getting good work out of it is mostly getting the right things in front of it at the right moment. Much of this book, the rules you will set next, the written plan you will produce in the next part, exists to keep the context that matters always in view.\n\n```mermaid\n%% caption: The agent works only from what is in front of it now, and starts fresh when reopened.\nflowchart LR\n  subgraph CTX[Context, this session]\n    MSG[Your message]\n    FILES[Open files]\n    READ[What it just read]\n  end\n  CTX --> AG([Agent works])\n  AG -.->|closed and reopened| FRESH[Starts fresh]\n```\n\nThere is also a ceiling on how much it holds at once, so a session that has run for hours goes vague and starts contradicting what you agreed earlier. Do not argue with it when that happens: open a fresh session and point it at the same files again. The build part turns this into a real skill.\n\n{/* KEEP: trust it to TYPE, not to DECIDE. Let it produce code fast, but you own the decisions (what to build, whether the result is right, what ships). Read what it does, don't rubber-stamp. This sets up code review later without naming it. */}\n\n## Trust it to type, not to decide\n\nLet the agent do the typing, all of it, at full speed. That is what it is for, and second-guessing every line wastes the whole advantage.\n\nBut keep the decisions yours: what to build, whether the result is actually right, what is allowed to ship. Read what it produces instead of waving it through. The agent is the fastest pair of hands you will ever have, and you are still the one steering.\n\n```mermaid\n%% caption: The agent does all the typing; you own the decisions and review its work.\nflowchart LR\n  YOU([You]) -->|what to build| AG([Agent])\n  AG -->|all the typing| CODE[Code]\n  CODE -->|you review it| YOU\n  YOU -->|what ships| OUT([Ships])\n```\n\nThis prompt makes the agent show you what it actually is, on your own machine:\n\n```prompt\nAct as a senior engineer introducing yourself to\nsomeone who has never worked with an agent before.\nLook around my machine and my project folder and\ndescribe back to me, in plain words: what you can\nsee, what you can change, what you can run, and\nwhat you cannot do without asking me first. Then\nrun one harmless command and show me the output,\nso I watch the read-run-report loop once. Tell me\nplainly what you will forget when this session\nends, and what I will have to hand you again.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/meet-your-ai-agent\n\nMy machine, and what I am about to build:\n```\n\n**Do this now:** paste the prompt and watch your agent read, run a command, and report back, so you have seen the loop before you start directing it for real."
          },
          {
            "slug": "the-system",
            "title": "What You Are Really Building",
            "label": "The System",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/the-system",
            "content": "---\ntakeaway: Build the system, not just the app\nshare: 'Every project you build has two halves: the app your users touch, and the system that produces it and keeps it alive. Most people only build the first one, which is exactly why their app dies in a month.'\nrequires: [ai-agent, project-folder, readme]\nproduces: [system-map]\nteaches: [ai-operating-system]\nuses: [ai-coding-agent, prompt]\n---\n{/* KEEP (added July 2026, user mandate): this chapter exists because the system was previously DEFINED at chapter 68, and nobody reaches chapter 68 without having used it for sixty chapters. It gets defined HERE, on day one, right after the reader meets their agent and before they write the rules file, so the rules file lands as piece one of something rather than as a loose tip. */}\n\nYou have an agent and an empty project. The obvious next move is to start asking it for features, and that move is exactly how a weekend app gets born and how it dies a month later. What separates the projects that survive is not talent. It is that they build a second thing alongside the app, starting on day one.\n\n{/* KEEP: CONCEPT. Two halves: the app (what users touch) and the AI operating system (what produces it and keeps it alive). The intro already gave the factory metaphor, so REFER to it, do not re-teach it. Bold-first: ai operating system. */}\n\n## Your project has two halves\n\nThe introduction put it as a factory and a car. Here is the same thing without the metaphor.\n\nEvery project has an app: the screens, the features, the thing users touch. It also has an **AI operating system**: the rules, plans, checks, records, and agents that produce that app and keep it alive. One is the output. The other is what makes more output possible.\n\n{/* KEEP (added July 2026, user mandate): the OS is not one thing, it runs TWO departments and they feed each other. Software cycle = the agentic SDLC, the definitional home of that term. Growth cycle = users, behaviour, data, revenue, the evidence that decides what to build next. Be honest about scope: this book builds the software department end to end and only stands up the first pieces of growth, which is consistent with the closing chapter handing the rest to a future book. The word \"departments\" is deliberate, the Automate part later turns folders into an org chart. */}\n\n## The operating system runs two departments\n\nAn operating system is not one thing. Yours runs two cycles, on the same files, feeding each other:\n\n| Department | What it runs | What it produces |\n| --- | --- | --- |\n| The software cycle | Plan, build, test, ship, operate | Software that works and keeps working |\n| The growth cycle | Who your users are, what they do, what it earns | The evidence that decides what to build next |\n\nThe software cycle is the agentic SDLC the preface named: plan, build, test, ship, run, with agents doing the work at each stage. The fifteen stages of this book are that cycle, and the system is the layer underneath it that makes agent-written work trustworthy instead of merely fast.\n\nThis book builds that department end to end. It also stands up the first pieces of the growth one: the screen that shows what real people are doing, and the numbers that say whether any of it worked. Both run on the same files. The rest of growth is a body of work as large as this one, and the last chapter says so plainly.\n\n{/* KEEP: STEP. Kill the expectation that the system is a product you install. It is plain files and folders in your own project, readable by you and your agent, and the first one arrives in the very next chapter. Show the shape it grows into as a folder sketch, marked so the reader knows it is the destination, not today's homework. */}\n\n## It is plain files, and the first one is next\n\nThe system is not a tool you install or a service you pay for. It is plain text files sitting in your own project, which is what makes it readable by you and by every agent you ever point at it.\n\nHere is roughly what it grows into. You are not building this today:\n\n```\nyour-project/\n  <rules file>        how the agent must work        (next chapter)\n  specs/              what you are building and why   (Plan)\n  docs/decisions/     why you chose what you chose    (Architect)\n  tests/              proof it still works            (Test)\n  <system folder>/    the board, the log, the agents  (Automate)\n```\n\nEach arrives in the stage that needs it, as a byproduct of work you were doing anyway. None of it is paperwork you do on the side.\n\n{/* KEEP: STEP, the standing loop in SEED form. This is the user's core point: the flow has to be defined as you start, not two thirds of the way in. Five steps, small enough to run on day one with no board and no log. The full six-stop version with tickets and a ledger arrives in the Automate part, so do NOT teach that here, and do not use the words ticket, board or ledger. */}\n\n## Define the loop before you need it\n\nThe system also has a shape to how work gets done, and it costs nothing to set on day one:\n\n1. **Understand** what is being asked, and read before writing.\n2. **Write down** what will change, and get your yes.\n3. **Build** only that.\n4. **Check** it actually runs before calling it done.\n5. **Record** anything you would otherwise have to remember.\n\nFive lines. Later stages make each one heavier and eventually hand parts of it to machines, but the shape never changes. Setting it now is what stops sixty chapters of habits forming around no shape at all.\n\n{/* KEEP: STEP, the sequencing answer, and the reason the automation part sits late. You run the loop by hand first because you cannot hand over work you have never done and cannot judge. Automation is one component of the system, not the system, and it is switched on after the first release, when trust has been earned. This reframes the whole book's shape for the reader. */}\n\n## You automate last, not first\n\nAutomation is a part of the system, not the system itself, and it is the last part to arrive.\n\nYou run the loop by hand first, for real, on your own project. That is not a hazing ritual: you cannot safely hand over work you have never done, because you would have no way to judge what came back. Once you have shipped a first version and watched the loop hold, you start handing pieces of it to agents that run without you. That is what the Automate stage is for, and it is late in this book on purpose.\n\n> **Rule of thumb:** the app is what you sell. The system is what lets you sell the next one. Build both, always, in the same session.\n\n{/* KEEP: the prompt. Small and honest for day one: no folders to create yet, no machinery. It records the two halves and the five-step loop in the project README, so the very next chapter (the rules file) has somewhere to attach and every later stage appends instead of inventing. One append slot. */}\n\n## Write the shape down before you build\n\n```prompt\nAct as a senior engineer setting the shape of my\nproject. Read my project folder and README first, and\nwork only from what is actually there.\n\nAdd a short section to my README called \"How this\nproject works\". In it, record two things.\n\nFirst, that this project has two halves: the app, and\nthe system that produces it, and that both grow in the\nsame sessions.\n\nSecond, the standing loop for any piece of work:\nunderstand it, write down what will change and wait for\nmy yes, build only that, check it runs, then record\nanything worth remembering.\n\nKeep it under fifteen lines and do not invent a stack,\na folder layout, or any tooling. Nothing has been\nchosen yet, and later chapters add each piece here as\nit is decided.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/the-system\n\nWhat I am building, in one or two sentences:\n```\n\n**Do this now:** paste the prompt so the two halves and the loop are written down before any code exists. Every stage after this adds one piece to the system, and the next chapter adds the first."
          },
          {
            "slug": "agent-rules",
            "title": "How the Agent Should Behave",
            "label": "Rules",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/agent-rules",
            "content": "---\ntakeaway: Give the agent standing rules to follow\nshare: An agent forgets everything between sessions, so it repeats the same mistakes. A rules file is your standing instructions it reads every time, the difference between correcting it forever and telling it once.\nrequires: [ai-agent, project-folder]\nproduces: [rules-file]\nteaches: [rules-file]\nuses: [ai-coding-agent]\n---\n{/* KEEP: lead-in = an agent starts fresh every session (context, not memory, from the last chapter), so it repeats the same mistakes. A rules file = standing instructions read automatically every time. Chapter = write it once instead of correcting forever. */}\n\nYour agent starts every session fresh, so it repeats the same mistakes: wrong folder, wrong style, a tool you already rejected. Correcting it each time is exhausting and it never sticks. This chapter gives you the fix, a rules file the agent reads automatically, every single time.\n\n{/* KEEP [pro]: a rules file = a plain text file of standing instructions the agent reads at the start of every session, on its own. It is how you turn \"context, not memory\" (last chapter) into consistency: the important context is always present without you re-typing it. Bold-first: rules file. */}\n\n## A rules file is your standing instructions\n\nA **rules file** is a plain text file of standing instructions your agent reads at the start of every session, without being asked. It is how you beat the memory problem from the last chapter: the things that matter are in front of the agent every time, so you never re-type them.\n\nThink of it as onboarding a new hire who arrives with amnesia each morning. The rules file is the one-page brief that makes them productive again in seconds.\n\n{/* KEEP [pro]: put the NON-NEGOTIABLES in writing = the decisions you never want re-litigated: the stack, where code goes, the naming style, libraries to prefer or avoid, commit habits, \"always run the app before saying done\". Concrete, testable instructions, not vague vibes. */}\n\n## Put the non-negotiables in writing\n\nFill it with the decisions you never want to explain twice: the tools you build with, and where new code goes. Add your naming style, which ready-made pieces to prefer or avoid, how to save your work, and \"always run the app before telling me it works.\"\n\nWrite them concrete, the way you would tell a person, not as vague vibes.\n\n| Vague | Concrete rule |\n|---|---|\n| \"write clean code\" | \"keep files under 300 lines, one feature per folder\" |\n| \"be careful with passwords and keys\" | \"never hardcode keys, keep them out of the code\" |\n| \"test your work\" | \"run the app and confirm it works before saying done\" |\n\n{/* KEEP: keep it SHORT and LIVING = a bloated rules file gets ignored (by you and the agent); keep it tight. It is living: every time you correct the agent on something it should have known, add that as a rule so you never correct it again. */}\n\n## Keep it short and living\n\nA giant rules file gets skimmed and ignored, by the agent and by you. Keep it tight, only the rules that actually matter.\n\nAnd keep it living. Every time you catch yourself correcting the agent on something it should have known, add that as one line. Over a few weeks the file quietly becomes the exact brief your project needs.\n\n```mermaid\n%% caption: Each correction becomes a one-line rule, so you never fix the same thing twice.\nflowchart TD\n  C[1. You correct the agent] --> ADD[2. Add it as one line]\n  ADD --> RF[(3. Rules file)]\n  RF -->|read next session| A([4. Agent follows it])\n  A -->|one less thing to fix| C\n```\n\n{/* KEEP: where it lives = in the project itself (in the repo, alongside the code), so it travels with the code and every agent on the project reads the same rules. Each tool has its own filename/location, so let the agent set it up for your tool. Ends with Do this now = have the agent create the rules file for your tool + seed it. */}\n\n## Where the file lives\n\nThe rules file lives inside your project folder, next to your code. It travels with the project, so every agent that opens it reads the same rules. Each tool looks for the file under its own name and place. The simplest move is to let your agent create the right one for the tool you chose.\n\nThis prompt has your agent create its own rules file:\n\n```prompt\nAct as a senior engineer configuring my agent. Read my\nproject folder and README first and work from what is\nactually there, not from assumptions.\n\nCreate the rules file for the tool I use, in the right\nfilename and place. Seed it with only what is true\ntoday: what I am building, that I am new to this and\nwant plain explanations, and a few non-negotiables, for\nexample run the app and confirm it works before telling\nme it is done, and never invent a fact you have not\nchecked.\n\nDo not invent a stack, a folder layout or a naming\nstyle: I have not chosen those yet, and the next\nchapters add each one here as it is decided. Keep it\nshort, and state in the file that this is the one place\nmy standing rules live, so everything later appends\nhere instead of starting a new file.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/agent-rules\n\nMy tool, and what I am building:\n```\n\n**Do this now:** paste the prompt so your agent creates the rules file, then read it and add one rule you already know you care about. Add to it every time you correct the same thing twice."
          },
          {
            "slug": "existing-code",
            "title": "If You Already Started",
            "label": "Existing Code",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/existing-code",
            "content": "---\ntakeaway: Point the book at code you already have\nshare: 'Most people arrive with something half-built: a weekend app, a template, a project someone else abandoned. The path in this book still works, you just aim it at what exists instead of at an empty folder.'\nrequires: [ai-agent, project-folder, rules-file]\nproduces: [codebase-survey]\nteaches: []\nuses: [ai-coding-agent, prompt, rules-file]\n---\n{/* KEEP (added July 2026): the on-ramp the book was missing. Its own opening line is \"anyone can build an app in a weekend, almost nobody keeps it alive a month later\", and those readers already HAVE the weekend app; every other chapter assumed an empty folder. Lead-in names the three ways people arrive with code. This chapter is OPTIONAL and says so immediately, the way the Inspect part does. */}\n\nPlenty of people reach this page with something already half-built: an app they vibe-coded over a weekend, a template they downloaded, a project someone else abandoned. Everything so far has assumed an empty folder. It does not have to. This chapter aims the same path at code that already exists.\n\n{/* KEEP: STEP. Say the skip condition in the first line so a greenfield reader loses ten seconds, not ten minutes. Then the reassurance that carries the chapter: the order does not change, only the starting point, and some stages arrive already done. */}\n\n## Skip this if your folder is empty\n\nIf you have nothing yet, you are on the normal path. Go to the next chapter.\n\nIf you do have something, nothing about this book changes except where you start. The stages run in the same order, and a few of them are simply already finished. Your job in this chapter is to find out which ones.\n\n{/* KEEP: STEP, and the one thing beginners get wrong. Survey BEFORE touching anything. The agent reads what is there and writes it down; that written inventory is the missing README and the beginning of the plan at the same time. Hard rule: no refactoring, no cleanup, no improvements during the survey, or you lose the only working version you have. */}\n\n## Survey it before you touch it\n\nThe instinct is to hand the whole thing to your agent and say \"clean this up\". Do not. You would be trading the only working version you have for a version nobody has run.\n\nRead first. Have the agent go through what is there and write down what it finds: what the project is, how to start it, what it is built with, and what the data looks like. Nothing else. No fixes, no tidying, no improvements.\n\nThat written survey is worth more than it sounds. It is the front-door document your project never had, and it is the first honest description of what you actually own.\n\n{/* KEEP: STEP, the payoff that makes the rest of the book usable for this reader. Map what exists onto the fifteen stages: a running app but no written plan, no automated checks, nothing live. The gaps ARE the reading list. Table, one line per stage group, using the stage names from the introduction (already known). Do NOT use \"spec\", \"test suite\" or \"deploy\" as taught terms here, this chapter sits before those chapters; say them in plain English. */}\n\n## Your gaps are your reading list\n\nNow line up what you have against the fifteen stages. A typical weekend project scores something like this:\n\n| Stage | Usually true of an existing project |\n| --- | --- |\n| Set Up | Done. It runs, and something is installed |\n| Plan | Missing. Nobody ever wrote down what it should do |\n| Architect | Partly. There is a layout, but nobody chose it |\n| Build | Partly. Features exist, in whatever shape they landed |\n| Test | Missing, almost always |\n| Ship, Operate | Missing. It runs on your laptop and nowhere else |\n\nThe empty rows are your reading list, and they are usually the same rows for everyone. That is the actual reason a weekend app dies in a month: the parts that were skipped are the parts that keep software alive.\n\n{/* KEEP: STEP. the honest triage, because the reader will want to delete everything and start over, which is usually wrong. Three buckets with a clear test each. The line that must survive: working code you do not understand is still working code. Bound the redo bucket tightly to money and user data so this does not license a rewrite. */}\n\n## Keep, redo, or delete\n\nYou will be tempted to throw it all away and start clean. That is almost always the expensive choice. Sort it into three piles instead:\n\n- **Keep** anything that runs and that you can describe. Working code you do not understand is still working code.\n- **Redo** only what you cannot explain *and* that touches money, passwords, or personal data. Those two conditions together, not either one alone.\n- **Delete** whatever nothing calls: the abandoned file, the half-finished page, the feature you talked yourself out of.\n\n> **Rule of thumb:** rewriting feels like progress and usually is not. Every hour spent replacing code that already worked is an hour not spent on the empty rows above.\n\n{/* KEEP: the prompt. Agent surveys and reports ONLY, explicitly forbidden from changing anything, then scores the project against the fifteen stages and returns the reading list. Also seeds the rules file with what it found, so the later chapters confirm rather than re-decide. One append slot. */}\n\n## Have your agent survey what you own\n\n```prompt\nAct as a senior engineer taking over a codebase I\nalready have. Read the project and report only. Do not\nchange, refactor, tidy, or fix a single file in this\ntask, even if something looks obviously wrong.\n\nTell me: what this project is, the exact command to\nstart it, what it is built with, what the data looks\nlike, and which parts actually work when you run it.\nSay plainly where you are guessing.\n\nThen score it against the fifteen stages of this book,\nfrom Set Up to Scale, and tell me which ones are done,\npartly done, or missing. The missing ones are my\nreading list, so order them.\n\nFinally, list anything that touches money, passwords,\nor personal data and that you could not explain\nconfidently. That list, and only that list, is what I\nshould consider rewriting.\n\nWrite the survey into my project as a README and add\nwhat you found (the language, the framework, the\ndatabase) to my rules file, so later sessions confirm\nthese instead of choosing again.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/existing-code\n\nWhat I already have, and how I got it:\n```\n\n**Do this now:** paste the prompt and read the survey before changing one line. Then carry on through the book, moving faster through the stages it says you already finished."
          },
          {
            "slug": "choosing-your-platform",
            "title": "What You Are Actually Building",
            "label": "Platform",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/choosing-your-platform",
            "content": "---\ntakeaway: Any interface, one backend behind it\nshare: 'Web, mobile, desktop, a browser extension, a plugin inside someone else platform: the shell changes, the engineering does not. Settle what you are building, and where the logic lives, before you pick a single tool.'\nrequires: [ai-agent, project-folder, rules-file]\nproduces: [platform-chosen]\nteaches: [offline-app]\nuses: [ai-coding-agent, prompt, rules-file]\n---\n{/* KEEP: lead-in = agent is set up and knows the rules; the next question sounds obvious until you answer it, what shape does this thing take. \"An app\" means a dozen different things and the answer decides every tool choice after it. This chapter must come BEFORE the stack chapter, which says platform decides everything above it but never lists the options. */}\n\nYour agent is set up and it knows your rules. The next question sounds obvious until you try to answer it: what shape does this thing take? People say \"an app\" and mean a dozen different things, and the answer decides every tool choice after it. This chapter settles it.\n\n{/* KEEP: CONCEPT. the first fork is offline vs online, because it decides whether there is a server at all. Bold-first: offline app. Offline = everything on the device, no accounts, no sync. Online = anything shared, paid, or synced across devices. State plainly that the book assumes online from here. */}\n\n## Offline or online is the first fork\n\nEverything splits on one question: does your app need a server?\n\nAn **offline app** runs entirely on the user's device. No accounts, no syncing, no shared data, and nothing to keep alive at three in the morning. A calculator, a notepad, a single-player game.\n\nEverything else needs a server. The moment two people share data, money changes hands, or a phone and a laptop must show the same thing, you need somewhere neutral that holds the truth. This book assumes that from here on.\n\n{/* KEEP: STEP. the catalog the author asked for. Point = \"an app\" is a much longer list than \"a website\", and the choice is only about what the user touches. Do NOT bold \"interface\": the code sense is taught in the Architect part. Table, one short line each. Link WordPress, Shopify and VS Code officially on first naming (all curl 2xx). End on: you can ship more than one. */}\n\n## Your interface is one of many\n\nWith that settled, the only remaining choice is what the user touches. That is your interface, and the list is longer than \"a website\":\n\n| Interface | What it is |\n| --- | --- |\n| Web app | Runs in a browser, nothing to install, updates instantly |\n| Mobile app | Installed from a store, store review on every update |\n| Desktop app | Installed on a computer, can reach local files |\n| [Browser extension](https://developer.chrome.com/docs/extensions) | Adds itself to pages the user already visits |\n| Platform plugin | Lives inside [WordPress](https://wordpress.org) or [Shopify](https://www.shopify.com), borrows their users |\n| Editor extension | Lives inside a tool like [VS Code](https://code.visualstudio.com), aimed at developers |\n| Assistant app | Called by an AI assistant on the user's behalf |\n| Command line | No screen at all, just typed commands, fastest to build |\n\nYou can ship more than one, and most serious products eventually do.\n\n{/* KEEP: STEP, the core idea and the diagram the author asked for. Every interface is a presentation layer and nothing else; all rules, data and keys sit in the backend behind an API. Do NOT bold presentation layer, backend or api: their real homes are the Architect and Plan parts, this chapter only uses them in plain language. Diagram = many interfaces converging on one backend. Payoff = a second interface costs a shell, not a rebuild; the alternative rewrites every rule per screen and leaks them. */}\n\n## One backend, many faces\n\nHere is the rule that makes that whole list cheap: every interface is a presentation layer, and nothing more.\n\nYour rules, your data, your calculations and your keys all live in the backend, the code running on your server where users cannot reach it. Each interface asks for what it needs through an API, a fixed set of allowed requests, and draws whatever comes back.\n\n```mermaid\n%% caption: Every interface is a face; one backend holds the logic, the data, and the keys.\nflowchart LR\n  W[Web app] --> API{{API}}\n  M[Mobile app] --> API\n  E[Extension or plugin] --> API\n  C[Command line] --> API\n  API --> BE[Backend: all logic and keys]\n  BE --> DB[(Your data)]\n```\n\nBuild it this way and a second interface costs you a shell, not a rebuild. Build it the other way, with logic sitting in the interface, and you write every rule again for every screen while a stranger reads all of them.\n\n> **Rule of thumb:** if a rule would embarrass you when a user reads it, it does not belong in the interface.\n\n{/* KEEP: STEP. reassurance + the reason the book covers all of them at once. What the interface changes is a short, closed list (update delivery, review gatekeeper, offline behaviour, how a user proves identity). What it does not change is everything else in the book. Ends by telling them to just pick the first one and keep moving. */}\n\n## The shell changes, the engineering does not\n\nYour interface changes a handful of things: how updates reach users, whether someone reviews your release, what still works with no signal, and how a user proves who they are.\n\nIt changes nothing about your spec, your architecture, your tests, your security, your deploy, or the way you direct your agent. That is why this book can cover all of them at once. Pick the first interface and keep going.\n\n{/* KEEP: the prompt. Senior engineer picks the FIRST interface and justifies the order, names a likely second one and what to keep out of the first so adding it stays cheap, then hard-confirms the backend-holds-everything shape and calls out anything the reader described that pushes logic into the interface. Writes the decision to the rules file. One append slot. */}\n\n## Let your agent name your first interface\n\n```prompt\nAct as a senior engineer deciding what I am building.\nRead my rules file first and keep anything it already\nsays about platform or stack.\n\nFrom the description below, tell me which interface my\nfirst release should be, and why that one before the\nothers. Name any second interface worth planning for,\nand say what to keep out of the first one so adding\nthe second later stays cheap.\n\nThen confirm in one line that all business rules, data\naccess, and keys will sit behind an API in the backend,\nwith every interface as presentation only. If anything\nI described puts logic into the interface, say so and\ngive me the version that does not.\n\nWrite the decision and the reason into my rules file,\nso every later session builds the right shape.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/choosing-your-platform\n\nWhat I want to build, and who will use it:\n```\n\n**Do this now:** paste the prompt and lock in your first interface, then have your agent record it in your rules file before you pick a single tool."
          },
          {
            "slug": "choosing-your-stack",
            "title": "What to Build It With",
            "label": "Stack",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/choosing-your-stack",
            "content": "---\ntakeaway: Pick boring, popular stack\nshare: Ignore the hundreds of options and the fights about them. Get a solid tech stack to start on today, plus a prompt that picks the right one for your case with a senior engineer judgment.\nrequires: [ai-agent, project-folder]\nproduces: [stack-chosen]\nteaches: [stack, framework, boilerplate, library, reuse-ladder]\nglosses: [frontend, backend, database, hosting, api]\nuses: [ai-coding-agent]\n---\nYour workspace is ready and your agent is waiting. Now you choose what to build the app out of: the language, the framework, the **database** where your data lives, and the place it runs. Ignore the hundreds of options and the fights about them. This chapter hands you a stack to start on today, and a prompt that picks the right one for your case with a senior engineer's judgment.\n\n## A stack is layers, bottom to top\n\nA **stack** is just the layers your app is built from, each sitting on the one below:\n\n- **Platform:** where it runs, web, iPhone, or desktop. This choice decides everything above it.\n- **Language:** the code it is written in, like [TypeScript](https://www.typescriptlang.org) or [Python](https://www.python.org).\n- **Framework:** a proven structure on top of the language, so you do not start from a blank page.\n- **Boilerplate:** a ready-made starter project, so you begin from a working app instead of an empty folder.\n- **Libraries:** open-source pieces you drop in for one specific job instead of building it yourself.\n- **Services:** whole capabilities you rent and call over the internet, like payments or email, instead of running them yourself.\n\nYou pick from the bottom up, and at each layer the popular choice is usually the right one.\n\n{/* KEEP: reuse ladder = start from what exists, build your own LAST. Order: proven framework > starter/boilerplate on top > wire in open-source projects and services via API > build your own only when nothing fits. You integrate proven pieces, you do not reinvent them. This is the counterweight the whole book leans on; the one deliberate exception (building your own agent operating system) is made in the Automate part, do not soften this rule to accommodate it. */}\n\n## Reuse first, build your own last\n\nEvery layer points the same way: start from what already exists. Reach for a proven framework first, then stand a starter on top of it. Wire in open-source projects and paid services through their **APIs**, the doorways programs use to call each other. You write your own version of a piece only when nothing out there fits.\n\nThis is not laziness, it is leverage. A payment flow or a login system has absorbed years of edge cases you have never seen. Rebuild it by hand and you meet every one of them yourself.\n\nYou move fast because you integrate proven parts, not because you type faster. If a solid, maintained option already exists, use it. Building your own is the last resort, not the first move.\n\n```mermaid\n%% caption: Work down the reuse ladder; writing your own is the last resort.\nflowchart TD\n  N[Need a piece] --> Q1{A proven framework fits?}\n  Q1 -->|Yes| U1[Use it]\n  Q1 -->|No| Q2{A starter or library fits?}\n  Q2 -->|Yes| U2[Wire it in]\n  Q2 -->|No| Q3{A paid service fits?}\n  Q3 -->|Yes| U3[Call its API]\n  Q3 -->|No| BUILD[Build your own, last resort]\n```\n\n## Default to the popular choice\n\nPick the most common option unless a hard requirement forces otherwise. Your agent has built it countless times and makes fewer mistakes with it, so popularity is really how much help you get.\n\n## A stack for almost any app\n\nFor a typical web or consumer app, take this as-is:\n\n| Piece | Use | Why |\n|---|---|---|\n| **Frontend**, what the user sees | [React](https://react.dev), via [Next.js](https://nextjs.org) | The default way to build a web interface |\n| **Backend**, the code behind it | [Node](https://nodejs.org) with TypeScript | Same language as the frontend, one stack to run |\n| Database, where the data lives | [PostgreSQL](https://www.postgresql.org) | Proven, free, handles almost anything |\n| **Hosting**, where it runs online | A plain rented server, like [Hetzner](https://www.hetzner.com) | Cheapest and simplest; a plain server suits your agent better than a fancy dashboard |\n\nOne language front to back. Next.js can serve both sides, so it is often the whole stack on its own.\n\nHosting is the one row you do not act on today, since nothing leaves your laptop for a while yet. You pick a host for real in the ship part, where the tiers and their true costs get compared.\n\n## Switch when the job demands it\n\nThe default holds until your app has a real requirement. Then a senior engineer moves deliberately, one line each:\n\n- **AI or heavy data:** a Python backend, its ecosystem is years ahead.\n- **Very low latency or high throughput:** [Go](https://go.dev) or [Rust](https://www.rust-lang.org) on the hot path.\n- **A static or brochure site:** no backend or database at all.\n\n## Let your agent choose for your case\n\nThis prompt already carries the engineering judgment. Paste it in and describe your app in the one slot at the bottom, nothing in the middle to hunt down and replace:\n\n```prompt\nAct as a senior engineer choosing my stack. Read my rules\nfile first, and keep any language, framework, or tool it\nalready names unless my case forces a change. Say why if\nit does.\n\nRecommend a frontend, backend, database, and hosting for\nthe app below. Default to the simplest, most popular,\nagent-friendly option, and override only with real\nengineering judgment:\n\n- Typical web or consumer app: TypeScript everywhere.\n- AI or heavy-data app: Python backend for the ecosystem.\n- Low-latency or high-throughput core: Go or Rust there.\n- Weigh ecosystem maturity, hosting cost, and how easily\n  an agent can maintain it.\n\nFor each choice: one line of reasoning, plus one\nalternative and its tradeoff. Once I confirm, write the\nstack into my rules file, so every later session builds\non it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/choosing-your-stack\n\nMy app:\n```\n\n**Do this now:** take the default stack, or paste the prompt and describe your app at the bottom. Then lock one tool into each piece before the next chapter."
          },
          {
            "slug": "choosing-a-database",
            "title": "Which Database You Need",
            "label": "Database Type",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/choosing-a-database",
            "content": "---\ntakeaway: Pick the kind of database your data needs\nshare: \"Your agent will pick a database for you, but which kind is a real decision. Get the few kinds that exist, when each fits, and a prompt that recommends the right one for your data.\"\nrequires: [stack-chosen, ai-agent]\nproduces: [database-chosen]\nteaches: [relational-database, document-database, key-value-store, vector-database, graph-database, object-storage, cache]\nuses: [database, stack, ai-coding-agent]\n---\n{/* KEEP: Problem = your agent picks a database instantly, but which KIND is the real decision and the wrong kind makes everything after harder. Reader needs the few kinds + when each fits, not expertise. Ends on the payoff: this chapter gets you that call. NOTE (sequencing, July 2026): this chapter now runs BEFORE the Plan part, so it must not assume the data-model sketch exists. A rough idea of what the app stores is all it needs; the detailed sketch comes later and slots into the kind chosen here. */}\nYour stack named a database, and everything you build will sit on it. Your agent will happily pick one the moment you ask, but which kind it should be is a real decision, and the wrong kind makes every feature after it harder. You do not need to be an expert here, only the few kinds that exist and when each one fits. This chapter gets you that call.\n\n{/* KEEP: S1 concept = relational (SQL) is THE default for almost every app: data in tables with clear relationships, described in plain terms since the detailed data model is sketched later in Plan. Right unless a specific reason not to. Bold relational + SQL on first use. Tie to the stack chapter's PostgreSQL default and link it. */}\n## Start with a relational database\n\nThe default for almost every app is a **relational** database, also called **SQL** after the language you query it with. It keeps your data in tables of rows and columns with clear links between them, which is how most apps naturally think about what they store: customers, and the orders belonging to each one.\n\nThis is the right choice unless you have a specific reason it is not, and most apps never do. Your stack already pointed you at [PostgreSQL](https://www.postgresql.org), a proven, free relational database that handles almost anything you give it.\n\n{/* KEEP: S2 = the signature TABLE of database KINDS vs what each is for. Names document (NoSQL)=loose varied shapes, key-value=fast simple lookups, vector=AI similarity search. Bold document (NoSQL), key-value, vector on first use in the table. After-table line refers vector/RAG by TOPIC (AI search over your own content by meaning), never by chapter number. Awareness level: recognize the names, do not deep-teach. */}\n## Know the other kinds and when they fit\n\nA few other kinds exist, each shaped for data that tables handle awkwardly. You will rarely need them, but you should know the names and what each is for.\n\n| Kind | What it holds | Use it when |\n|---|---|---|\n| Relational (SQL) | Tables with clear relationships | Almost anything, your default |\n| **Document (NoSQL)** | Loose records of varied shape | Records differ from one to the next |\n| **Key-value** | One value fetched by its key | Fast, simple, repeated lookups |\n| **Vector** | Data indexed by meaning | AI search by similarity |\n| **Graph database** | Data made of connections | Social graphs, recommendations, fraud rings |\n\nThe last one, vector, only comes up when you add AI search over your own content, matching by meaning instead of exact words. That is a specific, later need, not something a first version carries.\n\nBeyond these sit more specialized kinds still, like time-series stores built for metrics and events over time, each the right tool for one specific job. Knowing the whole menu lets you choose deliberately for a real system, but it is not a reason to run several at once.\n\nOne thing never belongs in a database at all: files and media (user uploads, images, documents, video). Those go in **object storage**, an S3-style store with self-hosted options too, while your database keeps only a link to each file.\n\n{/* KEEP: S3 = start with ONE relational database; it does the whole job far longer than you expect. Add a second kind ONLY when a real felt need appears (a needed cache, an AI vector search), NEVER up front on a guess. Every extra store multiplies the run-and-sync cost of everything on top. Gloss cache on first use. */}\n## One database is usually enough\n\nIt is tempting to reach for several kinds at once, a **cache** for speed (a fast store for repeat answers) and a document store for varied data. Resist it. Every extra database is another moving part to run and keep in sync, and it multiplies the work of everything built on top.\n\nStart with one relational database and let it do the whole job, which it can for far longer than you would guess. Add a second kind only when a real need appears: a page too slow without a cache, or an AI feature needing vector search. Never add one on a hunch that you might want it later.\n\nEven that vector search rarely needs a separate store, because a relational database like Postgres can do it through an extension ([**pgvector**](https://github.com/pgvector/pgvector)), keeping you on one database instead of adding another.\n\n{/* KEEP: S4 = hand the call to your agent: give it your sketched data + needs, have it recommend the KIND, defaulting to ONE relational database and JUSTIFYING any second store. The copy-paste prompt is the signature device: senior voice, expert criteria fixed at top (relational default; second store only for a real need: cache/document/vector; one line reasoning + honest cost each; prefer one DB), ONE append slot \"My app, and what it stores:\" at the bottom, no mid brackets, lines <65. */}\n## Let your agent pick for your data\n\nYou have the default and the handful of exceptions, so hand the real call to your agent. Describe in plain words what your app will store, and have it name the kind, defaulting to one relational database and justifying anything more.\n\nThis prompt already carries the judgment. Paste it in and describe your app in the single slot at the bottom:\n\n```prompt\nAct as a senior engineer choosing my database. Read my\nrules file first: the stack recorded there bounds this\nchoice. If the best answer contradicts it, say so and\nwhy, do not diverge quietly.\n\nRecommend the kind of database for the app below, and\ndefault to one relational database unless my data or\nscale clearly demands otherwise.\n\n- Relational (SQL) is the default: choose it unless\n  there is a specific, concrete reason not to.\n- Propose a second store only for a real need: a cache\n  for speed, a document store for varied shapes, a\n  vector store for AI similarity search.\n- For each, one line of reasoning and the honest cost\n  of running it.\n- Prefer one database doing the whole job over several.\n\nThen record the choice and its reason as one line in my\nrules file, so nothing later re-litigates it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/choosing-a-database\n\nMy app, and what it stores:\n```\n\n**Do this now:** keep the relational default your stack already gave you, or paste the prompt, describe what your app stores, and lock in one kind of database before the next chapter."
          },
          {
            "slug": "scaffolding",
            "title": "Blank Screen to Running App",
            "label": "Scaffolding",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/scaffolding",
            "content": "---\ntakeaway: Get a running app before features\nshare: \"The gap that stalls people is not the features, it is getting an empty folder to run at all. Scaffold from a boilerplate, put one thing on screen, and commit that running skeleton as your known-good baseline before any feature.\"\nrequires: [stack-chosen, project-folder, ai-agent]\nproduces: [running-app, dependency-manifest]\nteaches: [app-skeleton, scaffolder]\nglosses: [dev-server]\nuses: [boilerplate, stack, command]\n---\n\n{/* KEEP: lead-in = reader has a chosen stack + an empty folder; the instinct is to jump to features, but there is nothing running for one to live in. This chapter gets them from empty folder to a running app skeleton they can see in a browser. NOTE (sequencing, July 2026): this chapter sits in Set Up, BEFORE the Plan part and BEFORE version control, so it must not assume a spec exists and must not use commit/repo/branch vocabulary. The baseline commit lives in the version-control chapter that follows. */}\n\nYou have a stack picked and an empty folder. Everything after this asks you to change an app, and you do not have one yet: nothing runs, no page loads. This chapter gets you from that empty folder to a running app skeleton you can see in your browser, before you decide a single thing about what it will do.\n\n{/* KEEP: concept = first goal is NOT a feature, it is a running app that does almost nothing. A skeleton that boots, serves one page, proves the toolchain works end to end. Everything after drops into something already alive. Bold-first: skeleton. */}\n\n## From blank folder to running app\n\nThe gap that stalls people is not writing features, it is the plumbing before the first one: install the tools, wire the build, get a server to boot. Your first goal skips straight past that struggle.\n\nAim for a running app that does almost nothing useful yet, a **skeleton** that boots, serves one page, and proves the whole toolchain works end to end. Once it runs, every feature drops into something already alive, so a broken feature stands out against a baseline you know works.\n\n{/* KEEP: don't hand-assemble the plumbing. boilerplate = ready-made starter project; scaffolder = command that generates one. create-next-app is the fastest path for a typical web app. Show the real command + resulting file tree. Watch out: don't customize before it boots. Bold-first: boilerplate, scaffolder. Link create-next-app official. */}\n\n## Start from a boilerplate\n\nDo not hand-assemble the plumbing. A **boilerplate** is a ready-made starter project with the build, the config, and one working page already wired together. A **scaffolder** is a single command that generates one in seconds. For a typical web app, [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app) is the fastest path from nothing to running:\n\n```bash\nnpx create-next-app@latest my-app\ncd my-app\nnpm run dev\n```\n\nThat last line starts the **dev server**, the small web server that runs your app on your own machine. It boots at http://localhost:3000, with a shape like this:\n\n```\nmy-app/\n  app/\n    page.tsx      (the home page you see)\n    layout.tsx\n  public/\n  package.json\n```\n\n> **Watch out:** get the default booting before you customize anything. If you tweak first and it breaks, you cannot tell whether the boilerplate or your change is at fault.\n\n{/* KEEP: before any feature, put ONE real thing on screen: your app's name. Edit the home page, save, watch the browser update on its own. This proves the change-a-file-see-the-result loop you live in all through building. Show the hello-on-screen snippet. */}\n\n## Get one thing on screen first\n\nBefore a single feature, put one thing on screen that is unmistakably yours. Open the home page the scaffolder made and replace it with your app's name:\n\n```tsx\n// app/page.tsx\nexport default function Home() {\n  return <h1>Ledger is running.</h1>;\n}\n```\n\nSave, and the page in your browser updates on its own. Seeing your own words render proves the loop you will live in all through building: change a file, see the result. That tiny win is the entire point of the skeleton.\n\n```mermaid\n%% caption: The loop you live in while building: change a file, see the result.\nflowchart TD\n  E[1. Edit page.tsx] --> SV[2. Save the file]\n  SV --> UP[3. Browser updates on its own]\n  UP --> SEE[4. See your result]\n  SEE -->|change again| E\n```\n\n{/* KEEP: the skeleton is the most valuable state the project will be in for a while (it works, and nothing added can have broken it), so leave it alone until it is saved. The actual saving is the NEXT chapter's job (version control), do NOT teach commit/repo vocabulary here, this chapter now runs before it. */}\n\n## Stop here, before any feature\n\nA running skeleton is the most valuable state your project will be in for a while: it works, and nothing you have added can have broken it yet. Resist adding a feature to it today.\n\nThat is because you have no way back yet. The next chapter gives you one: a safety net that saves this exact working state so you can always return to it. From then on, every feature is a change against something known good.\n\nThis prompt has your agent scaffold that skeleton for your stack:\n\n```prompt\nAct as a senior engineer scaffolding my project.\nFirst read my rules file, so the stack and the\nnon-negotiables already recorded there decide this.\nIf anything below contradicts it, say so instead of\nquietly picking one. Then use the official\ngenerator for that stack: create-next-app for a\nNext.js web app, Vite for a plain single-page app,\nthe framework's own CLI otherwise. Generate the\nstarter, get it booting locally, and confirm the\ndev server serves one page in the browser. Then\nreplace that page with a single line showing my\napp's name, so I see my own output render.\nDo not add any feature yet. Show me the commands\nand the file tree they produce first, then add the\ngenerator used and the dev command to my rules\nfile so neither of us guesses them later.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/scaffolding\n\nMy app idea and stack:\n```\n\n**Do this now:** paste the prompt, name your app and stack, and let your agent scaffold a running skeleton. Then open it in your browser and see your own app name on the screen."
          },
          {
            "slug": "version-control",
            "title": "Never Losing Work",
            "label": "Version Control",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/version-control",
            "content": "---\ntakeaway: Never lose working code\nshare: You are about to let AI change your code all day. Version control is the safety net so one bad change never buries the version that worked, plus the words to make your AI use it right.\nrequires: [running-app, project-folder, ai-agent]\nproduces: [git-repo, baseline-commit]\nteaches: [git, commit, repo, branch, main-branch, merge, worktree, git-hook, semantic-versioning, deployment, test]\nglosses: [formatter, linter]\nuses: [command]\n---\n{/* KEEP: lead-in = you have a running skeleton and no way back; you're about to let AI change code all day, and without a safety net one bad change buries the working version. Version control is the net; this chapter gives the net + the vocabulary to make sure AI uses it right. */}\n\nYour app skeleton runs, and right now there is no way back to it. You are about to let AI change your code all day long, and without a safety net one bad change buries the version that worked. Version control is that net, and this chapter hands it to you along with the words to make sure your AI uses it right.\n\n{/* KEEP: define git plainly = saves a snapshot (commit) of the whole project every time something works; you can return to any of them; the repo is the folder git watches. Unlike editor undo, git never forgets and never runs out. Bold-first: git, commit, repo. */}\n\n## Git is your undo button\n\n[**Git**](https://git-scm.com) is a tool that saves a snapshot of your whole project every time something works. Each snapshot is a **commit**, and you can jump back to any of them, so a version that ran is never more than one step away. The folder git watches is your **repo**, short for repository.\n\nUnlike the undo in a text editor, git never forgets and never runs out. Months of commits stay there, each one a safe place to return to.\n\n{/* KEEP: reassurance = you do NOT memorize or type git; the agent runs every command. Your job is judgment, knowing what should happen so you can tell it's being done right. That is the whole point of the chapter. */}\n\n## Your AI runs git, not you\n\nHere is the relief: you will not memorize a single git command. Your agent runs every one of them for you.\n\nWhat you need is not the typing, it is the judgment: knowing what should be happening, so you can tell when it is being done right. That is all this chapter is for.\n\n{/* KEEP (added July 2026 when scaffolding moved ahead of this chapter): the reader's very first commit is the running skeleton from the previous chapter. It is the last moment the project is guaranteed to work, so it becomes the baseline every later change is measured against. This is the baseline-commit beat that used to close the scaffolding chapter; do not let it drift back there, scaffolding now runs before git exists. */}\n\n## Save your running skeleton first\n\nYour first commit is the skeleton you just got booting. Nothing you have added can have broken it yet, which makes it the one state you always want a way back to.\n\n```bash\ngit init\ngit add -A\ngit commit -m \"chore: scaffold running skeleton\"\n```\n\nFrom here every change is measured against a version you know ran. When something breaks, and it will, getting back to working is one step, not an afternoon.\n\n{/* KEEP: branch = a private copy split from the main line where AI tries a feature; merge if it works, throw it away if it breaks and main is untouched. Worktrees = one-line mention (several branches at once), AI handles them, reader doesn't. Bold-first: branch, main, worktrees. */}\n\n## Every experiment gets its own branch\n\nWhen AI tries a new feature, it should do it on a **branch**: a private copy of the project split off from the main line. If the feature works, the branch is merged back in. If it breaks, you throw the branch away and the working version, the **main** branch, never felt it.\n\n```mermaid\n%% caption: Each experiment runs on its own branch, merged back only if it works.\nflowchart LR\n  M1[main] --> M2[main]\n  M1 -->|branch off| F[try the feature]\n  F -->|works: merge back| M2\n  F -->|breaks: throw away| D[gone, main untouched]\n```\n\nYou may also hear about [**worktrees**](https://git-scm.com/docs/git-worktree), a way to keep several branches open at once. Same idea, and your agent handles it. You do not need to.\n\n{/* KEEP: the one habit = commit after each small working change, not one giant commit at the end. Small commits = precise undo (undo the one bad step, not an afternoon). Instruction to give the agent: commit often with a short message. */}\n\n## Commit after every working step\n\nOne habit matters more than the rest: have your agent commit after each small change that works, never one giant commit at the end.\n\nSmall commits are precise. When something breaks, you undo the one step that caused it instead of losing an afternoon of work.\n\n> **Rule of thumb:** if it runs and does one new thing, commit it.\n\n{/* KEEP: git hook = a script git runs automatically on commit or push, so quality gates run without anyone remembering. High-level list of what goes there as the project grows: format + lint, scan for secrets, run the tests your change affects. Cross-link Test + guardrails (Build) by topic, no tool names. Bold-first: hook. SEQUENCING (corrected July 2026, do not regress): the reader owns NO formatter, linter, secret scan or tests at this point, so this section must NOT tell them to wire anything up today. It teaches what the slot is and says each check joins the hook in the part that installs it; the conventions chapter sets up the formatter and linter, guardrails wires the gate, the Test part adds tests. */}\n\n## Let git run your checks for you\n\nGit can also run a check for you automatically, the moment you commit. That automatic check is a **hook**: a small script git triggers on its own, so the things you would otherwise forget just happen every time.\n\nAs the project grows you will put a few jobs here: a **formatter** to tidy the code's layout, a **linter** to flag sloppy patterns, and a scan for leaked keys. Your **tests** go here too, the small programs that check your app still does what it should.\n\nYou own none of those yet, so there is nothing for a hook to run today, and that is fine. Each one joins it as it arrives: the formatter and linter when you settle your code conventions, then the secret scan and the tests in the parts that set them up. What you need now is knowing the slot exists, so quality never depends on you remembering.\n\n```mermaid\n%% caption: A git hook runs your quality checks automatically the moment you commit.\nflowchart LR\n  CM([You commit]) --> HK[Git hook runs]\n  HK --> FMT[Format and lint]\n  HK --> SCAN[Scan for secrets]\n  HK --> TST[Run affected tests]\n  FMT --> OK([Commit proceeds])\n  SCAN --> OK\n  TST --> OK\n```\n\n{/* KEEP: semantic versioning = three numbers major.minor.patch (e.g. 2.4.1); major = breaking, minor = new feature, patch = fix. WHY START EARLY (the point of this section): versioning from day one gives you a clear marker for big changes/refactors, lets you control deployments and know exactly which version is live, and makes future debugging easier (you can pinpoint which version introduced a bug). Start now at ~0.1.0. Reader doesn't calculate it, tells AI to follow it. Bold-first: semantic versioning. Table for the three parts. */}\n\n## Version numbers that tell the truth\n\nWhen you share software, its version number tells people what changed. The standard is [**semantic versioning**](https://semver.org): three numbers like 2.4.1, each with a job.\n\n| Number | Goes up when | Example |\n| --- | --- | --- |\n| Major | a change breaks how it worked before | 1.9 to 2.0.0 |\n| Minor | you add a feature, nothing breaks | 2.3 to 2.4.0 |\n| Patch | you fix a bug | 2.4.0 to 2.4.1 |\n\nStart numbering from your very first working version, not once things get serious. With versions in place you always know where you stand: which one is live, what changed since, and, when a bug appears, which version introduced it.\n\nThat one early habit pays off later at every **deployment**. That is the moment you send a version out of your machine and onto real servers where users reach it.\n\nYou do not work the numbers out yourself. Tell your agent to follow semantic versioning from the first release, starting around 0.1.0, and your history stays honest about what changed.\n\n{/* KEEP: the setup prompt (senior-engineer voice, fixed content + one append slot). Sets the agent's git ground rules once: commit per working step with clear messages, branch per feature, semantic versioning. Ends with Do this now = paste it. */}\n\n## Set the git rules once\n\nGive your agent these rules at the start, and it handles version control for the whole project:\n\n```prompt\nAct as a senior engineer setting up version control.\nFirst read my rules file, so your commit style and\nbranch names match what is already written there.\nThen start git here and commit the app skeleton\nexactly as it boots, as my baseline. From then on,\nwithout me asking each time:\n- Commit after every change that works, with a short,\n  clear message saying what changed.\n- Put each new feature on its own branch, and merge it\n  back only once it works.\n- Follow semantic versioning for releases: major for a\n  breaking change, minor for a feature, patch for a fix.\nAdd those three as standing rules in my rules file, so\nevery session follows them. Explain what you are doing\nthe first few times so I can follow along.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/version-control\n\nMy project:\n```\n\n**Do this now:** paste the prompt above to your agent, so your running skeleton is saved and version control is live before you write another line."
          },
          {
            "slug": "secrets-and-config",
            "title": "Handling Keys and Config",
            "label": "Secrets",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/secrets-and-config",
            "content": "---\ntakeaway: Keys out of code\nshare: Put one password or API key in your code, and the day you share that code you hand strangers the keys. Keep every secret out of your codebase from the start with a git-ignored .env file.\nrequires: [git-repo, project-folder, stack-chosen, ai-agent]\nproduces: [env-file, env-example]\nteaches: [secret, config, environment-variable, gitignore, secret-rotation, api-key]\nglosses: [push, secret-manager]\nuses: [commit, repo, git, stack, database]\n---\n{/* KEEP: lead-in = your app needs passwords/keys to reach its database, payments, AI services; put even one in the code and sharing the code hands strangers the keys. Chapter = keep every secret out of the codebase from day one. */}\n\nYour app needs passwords and keys to reach its database, its payment provider, its AI services. Put even one of those in your code and it goes wherever the code goes: shared with someone, **push**ed to a copy online, pasted to your agent. Any of those hands strangers the keys. This chapter keeps every secret out of your codebase from the start.\n\n{/* KEEP: secret = any value that lets someone act as you/your app (db password, API key, payment token, signing key); if leaking it costs money or access, it's a secret. Everything else (titles, feature flags) = plain config, safe to share. Bold-first: secret, config. */}\n\n## What counts as a secret\n\nA **secret** is any value that lets someone act as you or your app: a database password, an **API key** (the password a service hands you so its systems know the request is yours), a payment token, an auth signing key. The test is simple: if leaking it costs you money or access, it is a secret.\n\nEverything else is just **config**, plain settings like a page title or a feature switch. Config is safe to share; secrets never are. This chapter is about the secrets.\n\n```mermaid\n%% caption: One test sorts every value: would leaking it cost you money or access?\nflowchart TD\n  V[A value your app uses] --> Q{Leaking it costs money or access?}\n  Q -->|Yes| SEC[Secret, keep out of code]\n  Q -->|No| CFG[Plain config, safe to share]\n```\n\n{/* KEEP [pro]: the rule pros never break = a secret is NEVER written in the code itself, because code gets shared, pushed, copied, pasted to the agent, and a hardcoded key travels everywhere the code goes. Secrets live OUTSIDE the code, in environment variables the app reads by name. Bold-first: environment variable. */}\n\n## Keys never touch the code\n\nThe rule a professional never breaks: a secret is never written in the code itself. Code gets shared, pushed to your repo, copied between machines, pasted to your agent, and a key sitting inside it travels to every one of those places.\n\nInstead, secrets live outside the code, in **environment variables**: values the app reads from its surroundings at startup, by name. The code says \"give me the database password,\" never the password itself.\n\n{/* KEEP: the .env file = standard home for secrets, KEY=value per line, read at startup; NEVER committed, add it to .gitignore. Commit a .env.example with the same keys but blank/fake values so others know which keys exist without seeing them. version-control already taught (this chapter comes after), so commit/repo/.gitignore are fine here. Bold-first: .env, .gitignore, .env.example. */}\n\n## One .env file, never committed\n\nThe standard home for those values is a file named **.env** in your project, one `KEY=value` per line, that your code reads when it starts. This file never leaves your machine: you add it to your **.gitignore** so version control skips it and it is never committed.\n\nBeside it you commit a **.env.example**: the same key names with blank or fake values. Anyone else, including your future self, can then see which keys exist without seeing their values. The real secrets stay local, the list of what is needed is shared.\n\n```mermaid\n%% caption: Real secrets live in a git-ignored .env; a blank .env.example is shared.\nflowchart LR\n  CODE[Your code] -->|reads a key by name| ENV[.env: real secrets]\n  ENV -->|git-ignored| L[stays on your machine]\n  EX[.env.example: blank keys] -->|committed| R[shared in the repo]\n```\n\n{/* KEEP: if a secret ever leaks (screenshot, commit, pasted log), treat it as burned and ROTATE it: generate a new key at the provider, replace the old one, which instantly makes the leaked one useless. Do it immediately. Watch-out: a secret pushed to a repo stays in git history even after you delete it, rotating is the only real fix. Bold-first: rotate. */}\n\n## Rotate anything that leaks\n\nIf a secret ever slips out, in a screenshot, a commit, a pasted log, treat it as burned. **Rotate** it: generate a fresh key at the provider and replace the old one, which instantly makes the leaked copy useless. Do it the moment you notice, not later.\n\n> **Watch out:** a secret pushed to your repo does not disappear when you delete the line, it stays in the history. Rotating the key is the only real fix.\n\n{/* KEEP: the production door, missing until July 2026. A reader who stops at .env believes it is the whole answer, then reaches deployment with a git-ignored file that by definition never travels. Name the three homes, one line each, and mark clearly that only the first is needed now: local .env for development, environment variables set in the host's own dashboard or CLI for production, a secret manager once several people or machines need the same keys. NO how-to here, the ship part owns that. Do not use \"remote\" or \"push\", the remote chapter comes after this one. */}\n\n## Production keeps its keys somewhere else\n\nYour `.env` never leaves your machine, which is the whole point of it. It is also why nothing you set up today reaches the server your app will eventually run on.\n\nYou do not need to solve that yet. When you deploy, the same key names get set as environment variables in your host's own dashboard or command line. Your code reads them exactly as it does now.\n\nA dedicated secret manager is a service whose only job is holding keys and handing them out. It earns its place later, once several people or machines need the same ones.\n\n{/* KEEP: prompt (senior voice) to wire up secret handling for the reader's stack: create .env, add to .gitignore, create .env.example, move existing keys out of code into .env and read from there. Ends with Do this now. */}\n\n## Wire it up for your stack\n\nThis prompt has your agent set secret handling up correctly for whatever stack you chose:\n\n```prompt\nAct as a senior engineer setting up secret handling for\nmy project. Read my rules file first so this matches how\nthe project already works.\n\nCreate a .env for my stack and add it to .gitignore so it\nis never committed. Create a .env.example with the same\nkeys and empty values. Move any key already sitting in my\ncode into .env and read it there by name. Tell me what\neach key is for.\n\nThen add one standing line to my rules file: no secret\never goes in code, and every new key lands in .env and\n.env.example in the same change.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/secrets-and-config\n\nMy stack:\n```\n\n**Do this now:** create the git-ignored `.env` and the `.env.example` beside it today, before your first key exists, so there is never a moment where a secret has nowhere to go but your code."
          },
          {
            "slug": "remote-repository",
            "title": "Backing Up to a Remote",
            "label": "Remote",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/remote-repository",
            "content": "---\ntakeaway: Push your code somewhere off your machine\nshare: Your commits are safe from bad changes but not from a dead laptop. This chapter backs your code up off-machine, where you can share it and later ship from it.\nrequires: [git-repo, baseline-commit, env-file]\nproduces: [remote-repo]\nteaches: [remote, push]\nuses: [git, repo, commit, secret, deployment]\n---\n{/* KEEP: lead-in = you set up version control, but every commit still lives on one laptop, and a laptop can die, get lost, or be dropped in a lake. \"Never losing work\" is only half true while your only copy is local. Chapter = get your code backed up off your machine, where you can share it and later ship from it. */}\n\nYou set up version control, so no bad change can bury the version that worked. But every commit still lives on one laptop, and a laptop can die, get lost, or land in a lake. \"Never losing work\" is only half true while your only copy sits on that machine. This chapter gets your code backed up somewhere off your laptop, where you can share it and later ship from it.\n\n{/* KEEP: define remote plainly = a remote is a copy of your repo hosted off your laptop (GitHub, GitLab); local git protects you from mistakes but not from the machine itself, so losing the laptop does not lose the work. Bold-first: remote. */}\n\n## Local git isn't a backup\n\nLocal git protects you from your own mistakes, not from the machine. Every commit is safe from a bad change, and every commit still lives on the same disk that can fail.\n\nA **remote** is a copy of your repo hosted off your laptop, on a service like [GitHub](https://github.com) or [GitLab](https://about.gitlab.com). When you send your commits there, losing the laptop stops meaning losing the work. Either one does that job; this book assumes GitHub, because the testing and deployment parts later build on its own automation.\n\n{/* KEEP: the step = create a repo on a host and push your local one to it; after that every commit can be sent up with one command. Show the real artifact (remote add + push) framed as the agent running it. Bold-first: push. ALSO KEEP: the public/private call, which the host forces the moment you create the repo. Default is PRIVATE unless deliberately open-sourcing; private can be flipped public later, a leak cannot be undone. The prompt must ask for a private repo, not just report which one it made. */}\n\n## Push your repo to a host\n\nYou create an empty repo on the host, then link your local one to it and send everything up. That send is a **push**, and after the first one, every future commit goes up with a single command.\n\nThe host asks one question while you create it: public or private. Choose private unless you are deliberately open-sourcing the project. You can make a private repo public any day you like, and you can never un-leak what strangers and code-scanning bots already copied.\n\nYour agent runs this for you. The shape is worth seeing once:\n\n```bash\ngit remote add origin https://github.com/you/your-app.git\ngit push -u origin main\n```\n\nThe first line names the remote, the second pushes your history to it. From then on, a plain `git push` keeps the off-machine copy current.\n\n{/* KEEP: the remote is three things at once = the off-machine backup, the place a collaborator or your other machine pulls from, and the source your automated tests and deploys later run from (refer to CI / deployment by topic, no re-teaching). */}\n\n## It's your backup and your launchpad\n\nThe remote earns its keep three ways at once:\n\n- **Backup:** an off-machine copy of every commit, safe when the laptop is not.\n- **Sharing:** the one place a teammate, or your other machine, pulls the latest from.\n- **Launchpad:** the source your automated tests and deploys will later pull from, when this book gets to shipping.\n\nThat third job is why this matters beyond backup. The habit you set now is the foundation the deployment part builds straight on top of.\n\n{/* KEEP: one caution = a remote is often public or shared, so anything committed is exposed; your git-ignored secrets stay local (refer to the secrets chapter by topic). Watch-out callout. Then the setup prompt (senior voice) = create my remote repo, push my code, make pushing part of my normal flow, keeping secrets out. Ends with Do this now. */}\n\n## Keep secrets out of what you push\n\nA remote is often public, and always shared with anyone who has access. Anything you commit and push is exposed to every one of them, so a pushed secret is a leaked secret.\n\nThis is exactly why the secrets chapter had you git-ignore your `.env`: an ignored file never gets committed, so it never rides a push up to the host.\n\n> **Watch out:** a public repo is readable by strangers and by code-scanning bots. Confirm your secrets are git-ignored before the first push, not after.\n\nThis prompt has your agent create the remote, push your code, and wire pushing into your normal flow, secrets left behind:\n\n```prompt\nAct as a senior engineer setting up a remote\nrepository for my project. Read my rules file and\nmy .gitignore first, so you follow what I already\nset. Then:\n- Create a new private repository on my chosen host\n  and connect my existing local repo to it.\n- Confirm my .env and any secret files are\n  git-ignored, and my .env.example is committed,\n  then push my full history up.\n- Add one standing line to my rules file: push\n  after each set of commits, so the off-machine\n  copy stays current without me asking.\n- Tell me the repo URL and whether it is private\n  or public when you are done.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/remote-repository\n\nMy host and project:\n```\n\n**Do this now:** paste the prompt above so your code is backed up off your machine before you write another line."
          },
          {
            "slug": "dependencies",
            "title": "Living on Others' Code",
            "label": "Dependencies",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/setup/dependencies",
            "content": "---\ntakeaway: Reuse proven code, but vet it first\nshare: Almost everything your app needs, login, payments, dates, file uploads, is already built and battle-tested by millions. Learn to lean on these dependencies without inheriting their problems.\nrequires: [running-app, dependency-manifest, ai-agent]\nproduces: []\nteaches: [dependency, package, manifest, lockfile, license, package-manager]\nuses: [library, semantic-versioning, commit, ai-coding-agent, test]\n---\n{/* KEEP: lead-in = don't build from scratch; almost everything (login, payments, dates, uploads) already exists as dependencies, tested by millions. Chapter = how to lean on them without inheriting their problems. */}\n\nYou could tell your AI to write everything from scratch. You should not. Almost everything your app needs, login, payments, date handling, file uploads, someone has already built and millions have tested. These ready-made pieces are dependencies, and this chapter shows you how to lean on them without inheriting their problems.\n\n{/* KEEP: dependency = code someone else wrote that your app installs and uses (a library / package); the agent installs them and lists them in one manifest file so any machine rebuilds the exact set; reader never installs by hand, their job is deciding which to trust since each is code they can't fully see. Bold-first: dependency, library, package, manifest. */}\n\n## What a dependency actually is\n\nA **dependency** is code someone else wrote that your app installs and uses, usually called a **library** or a **package**. Rather than build a payment flow or a calendar yourself, you pull in one that already works, hardened by everyone who uses it.\n\nYour agent installs them and lists them in one file, the **manifest** (like `package.json`), so any machine can rebuild the exact same set. You never install them by hand. Your job is deciding which are worth trusting, because each one is code you cannot fully see.\n\n```mermaid\n%% caption: Your app leans on ready-made libraries, all recorded in one manifest file.\nflowchart LR\n  APP([Your app]) --> LOGIN[Login]\n  APP --> PAY[Payments]\n  APP --> DATES[Date handling]\n  APP --> UP[File uploads]\n  APP -.->|all listed in| MAN[(Manifest)]\n```\n\n{/* KEEP: choosing = prefer widely-used, recently-updated, still-maintained libraries; popularity means bugs surface fast, recent activity means security holes get patched. And add one only when it saves real work; for a few lines let the agent just write them (fewer deps = smaller surface to trust). Rule-of-thumb callout. */}\n\n## Pick popular, maintained, and alive\n\nNot every library deserves your trust. Before your agent adds one, it should prefer the option that is widely used, recently updated, and still maintained. Popularity means bugs surface fast; recent activity means security holes get patched.\n\nAdd one only when it saves real work, too. For a handful of lines, have your agent just write them, every dependency you skip is one less thing that can break on you.\n\n> **Rule of thumb:** a library with thousands of users and a commit this month beats a slicker one nobody has touched in two years.\n\n```mermaid\n%% caption: Reach for a library only when it is proven and saves real work.\nflowchart TD\n  Q{Saves real work?}\n  Q -->|Just a few lines| WRITE[Let the agent write it]\n  Q -->|Yes, real work| M{Popular and maintained?}\n  M -->|Yes| ADD[Add it]\n  M -->|No| SKIP[Skip it]\n```\n\n{/* KEEP: updating = old deps are where security problems pile up, so keep them current; but an update can change behavior, so update in small batches and check the app still works after each, never update everything at once right before shipping. Do NOT use \"branch\"/\"tests\" here (forward refs to version-control and Harden). */}\n\n## Update often, but never blindly\n\nOld dependencies are where security problems quietly pile up, so keep them current. An update can also change how a library behaves, though, so it pays to update a few at a time and check the app still works after each batch.\n\nRead the changelog before each one, too. That is where maintainers announce the change that will break you, in plain language, and it costs a minute.\n\nWhat you never do is update everything at once the day before you ship. Small, checked steps let you catch the one update that broke something while it is still easy to find.\n\n```mermaid\n%% caption: Update dependencies in small batches, checking the app still works after each.\nflowchart LR\n  U[Update a few] --> CHECK{App still works?}\n  CHECK -->|Yes| NEXT[Next batch]\n  NEXT --> U\n  CHECK -->|No| FIX[Fix the one that broke]\n  FIX --> U\n```\n\n{/* KEEP: version conflicts = two libs can want different versions of a third, or an update silently pulls in a newer piece that breaks yours; the lockfile (agent creates it automatically) records the exact version of everything so the app builds identically everywhere and nothing shifts unseen. Agent resolves conflicts; reader's job = notice when something that worked stops working. Bold-first: lockfile. */}\n\n## Lock versions so builds stay identical\n\nLibraries depend on other libraries, so two of them can want different versions of a third, or a fresh install can pull in a newer piece that breaks yours. Those version numbers follow a shared convention, [semantic versioning](https://semver.org), so a jump in the first number warns you a change may break things. A **lockfile**, which your agent creates automatically, records the exact version of everything, so the app builds the same on every machine and nothing shifts under you unseen.\n\n```mermaid\n%% caption: Libraries depend on other libraries, and the lockfile pins every exact version.\nflowchart TD\n  APP([Your app]) --> LOGIN[Login library]\n  APP --> CAL[Calendar library]\n  LOGIN -->|needs Dates v2| DATES[Date library]\n  CAL -->|needs Dates v1| DATES\n  LOCK[(Lockfile)] -.->|pins exact versions| APP\n```\n\nWhen versions do conflict, your agent sorts it out. Your job is only to notice when something that worked yesterday suddenly does not, and point the agent at it.\n\n{/* KEEP: the package manager, missing until July 2026 (npm was used as a bare command in scaffolding and never introduced). Three beats: what it is (the program that installs packages and writes the manifest and lockfile), the two real choices (npm as the lazy default that ships with Node, pnpm as the one most seniors pick for speed and disk), and the HARD RULE, pick one and never mix, because two lockfiles in one project is the mismatched-install mess beginners hit. Links: npm, Node, pnpm. */}\n\n## Pick one package manager and never mix\n\nThe program that does the installing is your **package manager**. It fetches each package, writes it into the manifest, and keeps the lockfile honest, and its name starts every install command you will ever see.\n\n[npm](https://www.npmjs.com) is the lazy default: it ships with [Node](https://nodejs.org), and every tutorial assumes it. [pnpm](https://pnpm.io) is what most senior engineers reach for instead, same packages, faster installs, far less disk.\n\nEither is fine; using both is not. Each writes its own lockfile, `package-lock.json` for npm and `pnpm-lock.yaml` for pnpm, and a project carrying two of them installs differently on every machine. Tell your agent which one you use and hold it there.\n\n{/* KEEP: license = every library ships with a license (legal terms for using it); most popular ones (MIT, Apache) allow almost anything, a few (some GPL variants) put conditions on how you distribute your own code. Rarely bites a small project, but before building a business on a library have the agent confirm its license is one you can live with. Link: choosealicense.com. Bold-first: license. */}\n\n## Check the license before you build on it\n\nEvery library comes with a **license**, the legal terms for using it. Most popular ones, like MIT and Apache, let you do almost anything. A few, like some GPL variants, put conditions on how you share your own code.\n\nIt rarely bites a small project, but before you build a business on a library, have your agent confirm its license is one you can live with. [choosealicense.com](https://choosealicense.com) explains the common ones in plain language.\n\nThis prompt turns that into a standing check rather than a one-off:\n\n```prompt\nAct as a senior engineer auditing what my project\ndepends on. Read my rules file and my dependency\nmanifest first, so this fits the stack I already\ncommitted to.\n\nList every direct dependency with its popularity,\nlast release date, and license. Flag any that are\nunmaintained, duplicated, or carry a license I\nshould not build a business on, and recommend a\nreplacement with the honest tradeoff. If a swap\ncontradicts a choice in my rules file, say so and\nwhy rather than switching quietly.\n\nThen write my dependency rules into that file: one\npackage manager, popular and maintained only, the\nlicenses I accept. Set the same audit to run\nwhenever a dependency is added.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/setup/dependencies\n\nMy project and how it is set up:\n```\n\n**Do this now:** paste the prompt and let your agent audit what you are standing on, so you know before a dependency becomes a problem instead of after."
          }
        ]
      },
      {
        "id": "plan",
        "title": "Structure your idea into a clear specification",
        "chapters": [
          {
            "slug": "gathering-requirements",
            "title": "Convert Ideas to Specs",
            "label": "Requirements",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/gathering-requirements",
            "content": "---\ntakeaway: Turn the idea into a testable list\nshare: Your AI agent cannot build a feeling, and you cannot check whether a feeling is finished. Turn the idea in your head into a clear, testable list of what the software must do, before any code.\nrequires: [ai-agent, project-folder]\nproduces: [specs-folder, user-stories]\nteaches: [requirement, user-story, must-have]\nuses: [ai-coding-agent, prompt]\n---\nYou have the whole idea in your head. Your agent cannot build a feeling, and you cannot check whether a feeling is finished. Before any code, you turn that idea into a clear, specific list of what the software must do. This chapter gets you that list.\n\n## A requirement is testable, not a wish\n\nA **requirement** is one thing your software must do, written plainly enough that anyone can tell whether it works yet.\n\n| Wish | Requirement |\n|---|---|\n| Users can log in | A person signs in with an email and password, and resets a forgotten one through an email link |\n\nThe difference is that you can test the requirement and point at a clear yes or no. Write every requirement so it passes that test.\n\n## Write each one as a user story\n\nProfessional teams capture requirements as **user stories**, one line each: `As a [type of user], I want to [do something], so that [reason].` The shape forces you to name who the feature is for and why it exists. That quietly kills the features nobody actually needs.\n\n> **Example:** As a shopper, I want to save items to a cart, so that I can pay for them all at once.\n\n## Split must-have from later\n\nList every story you can think of, then mark each one **must-have** or **later**. Be harsh: a must-have is something the product is useless without, not something that would be nice to have. The must-haves are all you build first; everything else waits its turn.\n\n```mermaid\n%% caption: Sort every story by one harsh test: is the product useless without it?\nflowchart TD\n  S[Every user story] --> Q{Useless without it?}\n  Q -->|Yes| MH[Must-have, build first]\n  Q -->|No| LT[Later, it waits]\n```\n\n## Get them from real users, not your head\n\nRequirements come from the people who will actually use the thing, not your imagination. Talk to three to five real potential users and write down what they ask for in their own words.\n\nNever ask \"would you use this?\", which buys you a polite yes and nothing else. Ask about the past instead, where the answers are facts:\n\n- What do you do about this today, step by step?\n- What did the last time cost you, in money or in hours?\n- What have you already tried, and why did you stop?\n\nFind those people where they already complain. Try a community you belong to, a forum about the problem, or the handful of people who have grumbled about it in front of you.\n\n> **Watch out:** if you cannot find one person who wants this, that is the cheapest moment you will ever get to learn it, long before you have built anything. Check before you build; if you build anyway, at least know you skipped it.\n\nThis prompt turns the idea in your head into that list:\n\n```prompt\nAct as a senior product engineer. Before you ask me\nanything, read my rules file and my project folder so you\nknow the stack and what already runs. Then interview me\nabout the app I want, and turn my idea into user stories,\none line each: \"As a [user], I want [action], so that\n[reason].\" Mark each must-have or later, and keep every\none testable, something we can point at and call done. If\nsomething I ask for fights the stack already chosen, say\nso before writing it. Create a specs folder in my\nproject if there is not one, and save the list there.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/gathering-requirements\n\nMy idea:\n```\n\n**Do this now:** paste the prompt, describe your idea, and let your agent draft the user-story list into your `specs` folder. That list is the raw material for every chapter that follows."
          },
          {
            "slug": "scoping-your-mvp",
            "title": "Cutting Scope to the MVP",
            "label": "MVP",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/scoping-your-mvp",
            "content": "---\ntakeaway: Cut to the core\nshare: \"Every item on your must-have list feels essential, which is exactly why it will sink your first version. Cut it down to an MVP: the smallest thing you can ship that actually helps one real person.\"\nrequires: [ai-agent, user-stories]\nproduces: [mvp-scope]\nteaches: [mvp, walking-skeleton, scope-creep]\nuses: [ai-coding-agent, prompt, user-story, must-have]\n---\nYour must-have list is still too big. Every item on it feels essential, which is exactly why the list will sink your first version if you try to build all of it. This chapter cuts that list down to an MVP: the smallest thing you can ship that actually helps one real person.\n\n## An MVP is the smallest version worth shipping\n\n**MVP** stands for **minimum viable product**. It is the leanest version of your idea that still delivers real value to one kind of user and can go live.\n\nTwo words carry the weight. \"Minimum\" means you cut ruthlessly. \"Viable\" means what is left still works for someone, end to end, on its own.\n\n## Apply the one core job test\n\nEvery product exists to do one core job. For everything on your list, ask a single question: does this feature directly serve that one job, or does it just decorate it?\n\n| Product | The one core job |\n|---|---|\n| A note app | Write a note and find it again |\n| A store | Buy one item and pay |\n| A booking tool | Reserve one slot at one time |\n\nIf a feature is not required for that core job to work once, it is not in the MVP. It can be the best idea you have and still wait.\n\n```mermaid\n%% caption: The MVP filter keeps only what the one core job needs to work once.\nflowchart TD\n  F[Every feature on your list] --> Q{Serves the one core job, or decorates it?}\n  Q -->|Serves it| IN[In the MVP]\n  Q -->|Decorates it| OUT[Waits for later]\n```\n\n## Expect to cut some must-haves too\n\nHere is the uncomfortable part: some features you marked must-have in the previous chapter still get pushed to a later version. \"Must-have eventually\" and \"must-have to ship the first slice\" are different bars.\n\n| In the MVP | Pushed to later |\n|---|---|\n| Sign in with email | Sign in with Google, Apple |\n| Post one item for sale | Bulk upload, drafts, scheduling |\n| Pay with one card | Saved cards, refunds, coupons |\n| One language | Translations |\n\n## Build a walking skeleton, not half an app\n\nA **walking skeleton** is one thin path through your whole app that actually works: a user arrives, does the core job once, and gets a result. It is skinny, but every bone connects.\n\n```mermaid\n%% caption: A walking skeleton: one thin path that does the core job end to end.\nflowchart LR\n  A([User arrives]) --> B[Does the core job once] --> C([Gets a result])\n```\n\nThis beats building many features to fifty percent. Ten half-finished features ship nothing a person can use. One complete path, however plain, is a product you can put in front of someone tomorrow.\n\n## Guard the line against scope creep\n\n**Scope creep** is the slow drift of \"while we are at it, let us also...\" that turns a two-week build into a six-month one. Every added feature feels small in the moment and enormous in total.\n\nWrite your MVP list down and treat new ideas as a separate \"later\" pile, not an edit to the plan. The plan is closed; the pile stays open.\n\n```mermaid\n%% caption: New ideas go to a later pile; the MVP plan stays closed.\nflowchart TD\n  I[New idea appears] --> Q{Part of the MVP plan?}\n  Q -->|Yes, already in it| BUILD[Build it]\n  Q -->|No| PILE[Add to the later pile]\n  PILE -.-> CLOSED[Plan stays closed]\n```\n\n> **Example:** An MVP for a food-delivery app: one restaurant, a fixed menu, one delivery address, pay with one card. No search, no ratings, no live tracking. A hungry person can still order dinner, so it is viable.\n\nThis prompt cuts your list to the core for you:\n\n```prompt\nAct as a senior engineer scoping my MVP. Read my rules\nfile and my specs folder first, so the cut fits the stack\nand the app I already run.\n\nFrom my user stories, find the single core job the app\nexists to do, then keep only the stories needed to do\nthat job once, end to end. Challenge every must-have: if\nthe product still works without it, move it to later.\n\nList what ships now and what waits, one line of reasoning\nper cut. If a cut contradicts something I already decided,\nsay so rather than dropping it quietly. Save the result in\nmy specs folder; the spec I write next builds on it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/scoping-your-mvp\n\nMy user stories (paste them, or point to the file):\n```\n\n**Do this now:** paste the prompt with your stories, and let your agent cut them to the smallest version that does the one core job, moving the rest to a \"later\" pile."
          },
          {
            "slug": "the-pieces-of-an-app",
            "title": "The Building Blocks",
            "label": "Components",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/the-pieces-of-an-app",
            "content": "---\ntakeaway: Know the five pieces of every app\nshare: Every web app is a few standard parts, each with its own job. Learn to name the five pieces and follow a single click through them, so you can tell your agent what to change and reason about why things break.\nrequires: [ai-agent]\nproduces: [component-map]\nteaches: [frontend, backend, api, database, hosting]\nuses: [ai-coding-agent, prompt, stack]\n---\nYour idea feels like one thing, but every web app is made of a few standard parts, each with a separate job. If you cannot name those parts, you cannot tell your agent which one to change, and you cannot reason about why something broke. This chapter gives you that map: the five pieces and how a single click travels through them.\n\n## The five pieces\n\nEvery web app is built from the same handful of parts. Learn these names once and the rest of the handbook stops sounding foreign.\n\n| Piece | What it does |\n|---|---|\n| Frontend | What the user sees and clicks in the browser: the pages, buttons, forms |\n| Backend | The server that runs your logic: it decides what happens when a request arrives |\n| Database | Where data is stored so it survives after the browser closes |\n| API | The agreed set of messages the frontend and backend use to talk to each other |\n| Hosting | The computers where all of the above actually run, reachable over the internet |\n\n## Frontend and backend are two programs\n\nThe **frontend** runs on the user's device, inside their browser. The **backend** runs somewhere else, on a server you control, out of the user's reach.\n\nThis split matters because anything secret (passwords, private data, business rules) lives in the backend, never the frontend. The frontend is public by nature: anyone can open it and look.\n\n```mermaid\n%% caption: The frontend is public on the user device; secrets stay in the backend you control.\nflowchart LR\n  subgraph DEV[Public, on the user device]\n    FE[Frontend]\n  end\n  subgraph SRV[Private, on your server]\n    BE[Backend]\n    SEC[Passwords, private data]\n  end\n  FE <-->|API| BE\n  BE --- SEC\n```\n\n## The API is a contract, not a place\n\nThe frontend cannot reach into the database directly. It sends a request to the backend through the **API**, a fixed list of allowed messages like \"give me this user's orders\" or \"save this comment.\"\n\nThink of the API as a menu. The frontend can only order dishes on the menu, and the backend decides how each one is cooked.\n\n## The database remembers, hosting runs it\n\nThe **database** is the app's memory. Close the browser, restart the server, and whatever was saved there is still waiting.\n\n**Hosting** is simply the rented computers where the frontend, backend, and database live so the public can reach them. Which specific tools fill each slot is a later decision, covered when you choose your stack.\n\n## Trace one click through all five\n\nFollow one action, a user saving a comment, and watch it cross every piece in order:\n\n1. **Frontend:** packages the typed comment and sends it off.\n2. **API:** carries that request to the backend as an agreed message.\n3. **Backend:** checks the user is allowed, then writes the comment down.\n4. **Database:** stores it and confirms it is saved.\n5. **Frontend again:** shows the saved comment on screen.\n\nAll of it runs on **hosting**, the rented computers underneath.\n\n```mermaid\n%% caption: One saved comment travels through every piece and back to the screen.\nflowchart LR\n  U([User]) -->|types comment| FE[Frontend]\n  FE -->|API request| BE[Backend]\n  BE -->|write| DB[(Database)]\n  DB -->|saved| BE\n  BE -->|confirmed| FE\n  FE -->|shows comment| U\n```\n\nEvery feature you build is some version of this loop. Once you can see the loop, a bug stops being \"the app is broken\" and becomes \"which piece dropped the message.\"\n\nThis prompt maps your app onto the five pieces:\n\n```prompt\nAct as a senior engineer. Read my user stories, my MVP\nscope, and my rules file first, then map the app they\ndescribe, not a generic one.\n\nMap it onto the five pieces of a web app: frontend,\nbackend, API, database, and hosting. For each, say in\none line what it does for my app specifically, naming\nthe stack and the database I already chose rather than\nproposing new ones. Where my running scaffold already\nfills a piece, say so.\n\nThen trace one must-have story as a round trip through\nall five.\n\nSave it in my specs folder, and flag anything here that\ncontradicts what my stories or rules already say.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/the-pieces-of-an-app\n\nMy app:\n```\n\n**Do this now:** paste the prompt and let your agent map your five pieces, then read the round trip so you can picture where each feature lives."
          },
          {
            "slug": "modeling-your-data",
            "title": "Planning Your App's Data",
            "label": "Data Model",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/modeling-your-data",
            "content": "---\ntakeaway: Sketch your data before any code\nshare: \"Code changes cheaply; the shape of your stored data does not, once real users have filled it. Sketch a plain data model first: the things you store, what each holds, and how they connect.\"\nrequires: [ai-agent]\nproduces: [data-model]\nteaches: [schema, entity, field, relationship, one-to-many, many-to-many]\nuses: [ai-coding-agent, prompt, database]\n---\nYour app stores things: people, their stuff, the records of what they did. Code changes cheaply, but the shape of that stored data does not, because once real users have created it, you cannot rename or reorganize it without touching everything they made. So you sketch that shape first, on paper, before a line of code. This chapter gets you a plain data model: the things you store, what each one holds, and how they connect.\n\n```mermaid\n%% caption: Code stays cheap to change; the shape of stored data locks once real users fill it.\nflowchart LR\n  CODE[Your code] -->|rewrite anytime| CHEAP[Cheap to change]\n  DATA[Your data shape] -->|users fill it| LOCKED[Painful to change]\n```\n\n## The shape of your data is called a schema\n\nA **schema** is the plan for what your app stores, separate from the place it gets stored (an earlier chapter covered what a database is). You are drawing the plan now, not choosing the storage yet.\n\nThe plan has two parts: the things you keep, and the links between them. Get both right on paper and the actual build is mostly transcription.\n\n## List your entities and their key fields\n\nAn **entity** is one kind of thing you store, like a `User` or an `Order`. A **field** is one piece of information an entity holds, like a user's email or an order's total.\n\nName each entity as a singular noun, then list only its key fields: the ones the app genuinely needs, not every detail you can imagine. Write it as a plain table.\n\n| Entity | Key fields |\n|---|---|\n| `User` | `name`, `email` |\n| `Order` | `total`, `status`, `createdAt` |\n\nNotice there is no password field. You are not going to store passwords at all: a login provider holds them for you, which the chapter on adding accounts explains. Leaving the field out of the sketch is how you stop your agent quietly putting one in your database.\n\nIf you cannot name an entity as a single noun, it is probably two entities hiding in one.\n\n## Draw the relationships between them\n\nA **relationship** is how two entities connect. Most connections are **one-to-many**: one entity owns many of another, and each of those belongs to exactly one owner.\n\nA `User` has many `Orders`, and each `Order` belongs to one `User`. That is one-to-many. When both sides have many (a `Post` has many `Tags` and a `Tag` covers many `Posts`), that is **many-to-many**, and you note it as such.\n\n```mermaid\n%% caption: The two relationships you use most: one-to-many and many-to-many.\nflowchart LR\n  U[User] -->|has many| O[Order]\n  O -.->|belongs to one| U\n  P[Post] <-->|many to many| T[Tag]\n```\n\nState every relationship in that plain \"has many\" and \"belongs to\" form. Sketched out, a shop's model nests like this:\n\n```\nUser\n  has many: Order\n    has many: LineItem\n      references: Product\n```\n\nEach indent is a \"belongs to\": a `LineItem` sits under one `Order`, which sits under one `User`. It reads unambiguously to both you and your agent, no diagram tool needed.\n\n## Keep it a sketch, not a database\n\nResist writing database code, picking a product, or adding fields for features you have not scoped. The model is a thinking tool, and every field you add now is one more thing to keep true later.\n\nA later chapter turns this sketch into real tables. Right now you only need it clear enough that someone else could read it and know what your app remembers.\n\nThis prompt drafts the sketch from your app:\n\n```prompt\nAct as a senior engineer sketching my data model.\nFirst read my specs folder: my user stories and my\nMVP scope. Model only what those need, nothing\nspeculative, and stay inside the database I already\nchose in my rules file.\n\nList the entities (the things my app stores), each\nwith its key fields, and state every relationship\nas \"has many\" or \"belongs to.\" Name each entity as\na singular noun; if it takes two nouns, it is two\nentities. Keep it a plain sketch, not SQL and not a\nreal database yet.\n\nThen flag any must-have story this model cannot\nserve, and any entity no story actually uses. Save\nthe sketch in my specs folder beside the rest.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/modeling-your-data\n\nMy app, and what it needs to remember:\n```\n\n**Do this now:** paste the prompt and let your agent draft the entity sketch, then check the relationships match how you picture your app."
          },
          {
            "slug": "non-functional-requirements",
            "title": "The Hidden Requirements",
            "label": "NFRs",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/non-functional-requirements",
            "content": "---\ntakeaway: Set quality targets as numbers\nshare: Your features say what the software does, not how fast, reliable, or safe it must be. Pin down these quality targets early, while changing them is still cheap, because they quietly decide how your app has to be built.\nrequires: [ai-agent, specs-folder, user-stories]\nproduces: [nfr-targets]\nteaches: [functional-requirement, non-functional-requirement, accessibility]\nuses: [ai-coding-agent, prompt, user-story, database, hosting]\n---\n{/* KEEP: lead-in = user stories say WHAT it does, not HOW WELL (fast/reliable/for how many). Those quality bars = non-functional requirements: the part most tutorials and books SKIP, and the part serious engineers pin down EARLY, because they decide architecture and stack before any feature exists. This chapter = a short list of measurable targets set now, while changing them is still cheap. */}\n\nYour user stories say what the software does. They say nothing about how well it has to do it: how fast, how reliably, how safely, for how many people. Those quality bars are non-functional requirements, the part most tutorials skip and serious engineers pin down early. They quietly decide how the app has to be built, long before you write a single feature.\n\nThis chapter gets you a short list of measurable targets, set now, while changing them is still cheap.\n\n{/* KEEP: functional requirement = a thing the software does; non-functional requirement = a standard it must meet while doing it. Table contrasts the two sides. Bold-first: functional requirement, non-functional requirement. */}\n\n## What it does vs. how well it does it\n\nA **functional requirement** is a thing the software does. A **non-functional requirement** is a standard it must meet while doing it.\n\n| Functional | Non-functional |\n|---|---|\n| A shopper can pay for a cart | Checkout completes in under 3 seconds |\n| A user uploads a photo | The site handles 500 people uploading at once |\n| An admin views a report | The report is available 99.9% of the time |\n\nThe functional side is the feature. The non-functional side is the quality bar that feature is held to.\n\n{/* KEEP: targets must be NUMBERS, not adjectives (\"fast\"/\"secure\" can't be tested). Walk seven categories (performance, availability, security, scale, accessibility, cost, privacy and law) and turn each vague wish into a measurable target. Three-column table: category | vague | measurable. COST and PRIVACY were added July 2026 and must stay: a monthly ceiling decides hosting and database as hard as the scale target does, and the personal data you choose to store now is what you are legally on the hook for later. Keep the row count and the prompt's category list in sync. */}\n\n## Set a number, never an adjective\n\n\"Fast\" and \"secure\" cannot be tested. A number can. Every target you write should be something you or your agent can measure and get a clear yes or no on.\n\nWalk these seven categories. For each, turn the vague wish into a number a test can check:\n\n| Category | Vague (won't do) | Measurable target |\n|---|---|---|\n| Performance | \"fast\" | A page loads in under 2 seconds |\n| Availability | \"reliable\" | Up 99.9% of the time |\n| Security | \"secure\" | Passwords never stored as plain text, login enforced on private data |\n| Scale | \"handles growth\" | 10,000 users and 1 GB of data in year one |\n| Accessibility | \"usable by all\" | Works by keyboard and screen reader, meets [WCAG](https://www.w3.org/WAI/standards-guidelines/wcag/) AA |\n| Cost | \"cheap to run\" | Under 50 euro a month at launch, hosting and database included |\n| Privacy and law | \"we respect privacy\" | We store names and emails only, no card details on our servers, and a user can delete their account |\n\n{/* KEEP: THE most important idea of the chapter, hammer it. Your OBJECTIVE (raw speed vs tight accuracy vs a target user count) decides how the whole app is architected. Document these targets and hand them to the AI BEFORE it designs anything, so it builds the structure to hit them; leave them out and it guesses wrong and you pay to redo the foundation. Not built here, a later part covers hitting the bars. */}\n\n## Write them down for your AI before it builds\n\nThese are not paperwork, they are the most important thing you decide in this part. Your objective, whether you need raw speed, tight accuracy, or a set number of users, decides how the whole app is put together.\n\nA \"handle 500 uploads at once\" target changes your database and hosting from day one. Bolt scale or accessibility on after launch and you are usually rewriting the foundation.\n\nThe last two rows earn their place the same way. A cost ceiling rules out the expensive host before you fall for one. And the personal data you choose to store today is exactly what you answer for later, long before this book reaches the law.\n\nHand these targets to your AI before it designs anything, and it builds the structure to hit them. You are not implementing any of it yet, a later part covers how. Here you just set the bars, so every choice downstream has something to aim at.\n\n```mermaid\n%% caption: Give targets to your AI before it designs, or it guesses and you rebuild the foundation.\nflowchart TD\n  T[Your quality targets] --> Q{Given to the AI before it designs?}\n  Q -->|Yes| BUILD[It builds to hit them]\n  Q -->|No| GUESS[It guesses, foundation rebuilt]\n```\n\n> **Example:** 95% of pages load in under 2 seconds on a mobile connection, and the app is available 99.9% of the time.\n\nThis prompt proposes your targets, tuned to your goal:\n\n```prompt\nAct as a senior engineer setting my non-functional\ntargets. First read my specs folder: my user stories, my\nMVP scope, my data model. Targets must fit the app I\nscoped and the stack and database I already picked, not\ngeneric best practice.\n\nPropose one measurable target in each of: performance,\navailability, security, scale, accessibility, cost, and\nprivacy. Each must be a number a test could check.\n\nFor cost, give me a monthly ceiling at launch and say\nwhich hosting and database choices it rules out. For\nprivacy, list the personal data my app would store and\nflag anything that pulls in extra legal duty, such as\npayments, health data, or users under 18.\n\nIf a target my objective needs conflicts with a choice I\nalready made, say so and why instead of quietly picking\none. Save them in my specs folder.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/non-functional-requirements\n\nMy app, and my main objective (speed, accuracy, scale...):\n```\n\n**Do this now:** paste the prompt with your objective, and let your agent propose the seven measurable targets into your `specs` folder. Then adjust any number that does not match your goal."
          },
          {
            "slug": "sketch-your-screens",
            "title": "Sketch Your Screens and Flows",
            "label": "Screens",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/sketch-your-screens",
            "content": "---\ntakeaway: Name your screens before the agent invents them\nshare: Your spec says what the app does and stores, but never what the user sees or how they move between screens. Hand the agent a screen list and a flow so it builds the interface you meant.\nrequires: [ai-agent, user-stories]\nproduces: [screen-map]\nteaches: [interface-map, screen-inventory, user-flow]\nglosses: [spec]\nuses: [ai-coding-agent, prompt, requirement]\n---\n{/* KEEP: Problem, spec covers logic and data but not what the user sees or the path between screens; agent invents its own UI. Payoff: a plain map of screens plus the flow. */}\nYour **spec**, the document your agent builds from, says what the app does and stores, but not what the user sees or how they move between screens. Hand that to an agent and it invents a screen structure of its own. This chapter gets you a plain map of your screens and the path between them, so the agent builds the interface you meant.\n\n{/* KEEP: Concept, the missing piece is the interface map: the screens and the route through them, which the spec so far leaves the agent to guess. */}\n## Your spec describes logic, not screens\n\nA spec that covers requirements, data, and quality targets still says nothing about the surface the user touches. It describes what happens under the hood, not the rooms the user walks through to get there.\n\nThat missing piece is the **interface map**: the set of screens your app has, and the route a user takes across them. Leave it out and the agent fills the gap with its own guess, which is rarely the one in your head.\n\n{/* KEEP: Step, a plain screen inventory, one line per screen the app has; show the fenced list. Bold \"screen inventory\" first use. */}\n## List your screens\n\nStart with a **screen inventory**: one line per distinct screen the app has, nothing more. Name each screen the way a user would think of it, not by its technical route.\n\n```\n- Landing page\n- Sign up / log in\n- Dashboard (list of my items)\n- New item\n- Item detail\n- Settings\n```\n\nThis list is deliberately dumb. Its whole job is to name every place a user can be, so nothing gets invented and nothing gets forgotten.\n\n{/* KEEP: Step, a user flow: arrows showing the path a user takes (land -> sign up -> dashboard -> create). Show a mermaid flow sketch with arrows. Bold \"user flow\" first use. */}\n## Draw the flow between them\n\nThe inventory names the rooms; the **user flow** names the doors. It is the ordered path a real user takes, drawn as arrows from one screen to the next.\n\n```mermaid\n%% caption: The path a new user takes, from landing to a created item.\nflowchart LR\n  L[Landing] --> S[Sign up]\n  S --> D[Dashboard]\n  D --> N[New item]\n  N --> I[Item detail]\n```\n\nOne arrow per move keeps it honest. If two screens have no arrow between them, the user has no way to travel that route, and now you can see it.\n\n{/* KEEP: Step, drop the screen list and flow into the spec so it becomes a build input, not an afterthought; refer to the spec chapter by topic. */}\n## Add it to the spec\n\nThe list and the flow are worth nothing sitting in a side note. Paste both into the spec, the one short document your agent reads before it builds, so the interface is an input, not an afterthought.\n\nGive them their own section, next to the data model and the requirements. Now every part of what to build lives in one place the agent already opens every time.\n\nThis prompt turns your idea into both artifacts, ready to paste in:\n\n```prompt\nAct as a senior product engineer. Read the planning\npieces in my specs folder first: my user stories, my\nMVP scope, and my data model. The screens must cover\nthose stories and nothing outside that scope.\n\nProduce two things I can paste in beside them.\n\nFirst, a screen inventory: one line per distinct\nscreen, named the way a user would think of it, not\nby its route. Cover sign up and log in, the main\nlist, create and detail views, and settings.\n\nSecond, a user flow: arrows showing the path a new\nuser takes across those screens, one arrow per move.\nFlag any screen nothing links to, and any story with\nno screen.\n\nKeep both short and skimmable.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/sketch-your-screens\n\nMy app:\n```\n\n**Do this now:** paste the prompt, describe your app, and drop the screen inventory and flow into your spec as their own section."
          },
          {
            "slug": "writing-the-spec",
            "title": "Writing It All Down",
            "label": "Spec",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/plan/writing-the-spec",
            "content": "---\ntakeaway: Assemble it into one short spec\nshare: Your requirements, scope, parts, data, and quality targets are useless scattered across notes. Assemble them into one short spec, the single document your AI agent actually builds from.\nrequires: [ai-agent, specs-folder, project-folder, user-stories, mvp-scope, component-map, data-model, nfr-targets]\nproduces: [spec-file]\nteaches: [spec, prd, repo]\nglosses: [markdown]\nuses: [ai-coding-agent, prompt, user-story, mvp, entity, non-functional-requirement]\n---\nThe earlier chapters each left you with a piece: user stories, a scope line, the app's parts, its data, its non-functional targets. Scattered across notes and your head, those pieces are useless to an agent that reads before it builds. This chapter assembles them into one short document, the spec, that your agent works from.\n\n## A spec is a document your agent builds from\n\nA **spec** is a single short document describing what the software must be and do. If you have heard the term **PRD**, short for product requirements document, that is the same idea under a heavier name.\n\nYour agent needs it as its single source of truth: the one thing it reads before building, so it does not guess and invent details you never wanted. Without it, every ambiguity becomes a coin flip you did not get to call.\n\n## Short and living, not forty pages\n\nA spec is not an exhaustive contract you write once and freeze. It is a working document you keep tight and update as you learn.\n\n| Forty-page document | Living spec |\n|---|---|\n| Written once, out of date by week two | Edited whenever scope or data changes |\n| Covers every edge case up front | Covers the shape; details emerge in the build |\n| Nobody rereads it | Short enough to reread before each task |\n\nAim for something you and the agent can both hold in your head. A page or two beats a chapter nobody keeps current.\n\n## Assemble the sections you already have\n\nEach section maps to a Plan chapter you already worked through. You are not writing new material here, you are collecting it.\n\n- **Problem and audience:** the problem and who it is for.\n- **Scope:** the MVP as must-have user stories.\n- **Main pieces:** the app's components and how they are kept separate.\n- **Data model:** the entities and how they relate.\n- **Non-functional targets:** speed, security, and scale you committed to.\n\n```mermaid\n%% caption: The planning pieces assemble into one short spec your agent builds from.\nflowchart LR\n  R[Requirements] --> S[spec.md]\n  M[MVP scope] --> S\n  C[Main pieces] --> S\n  D[Data model] --> S\n  N[Non-functional targets] --> S\n```\n\n> **Template:**\n> ```\n> # [Product name]\n> ## Problem & audience\n> ## Scope (MVP user stories)\n> ## Main pieces & structure\n> ## Data model\n> ## Non-functional targets\n> ```\n\n## Keep it in the repo, next to the code\n\nPut the spec in the project itself, its **repo** (the folder that holds all your code). Make it a plain [**markdown**](https://commonmark.org) file, text with light formatting marks, that the agent can open every time. A spec living in a chat window or a separate doc is one your agent cannot reliably read.\n\nKeeping it beside the code means every edit to scope or data lands in the same place the build happens. The spec and the software drift apart the moment they live in different homes.\n\nThis prompt assembles the spec from what you already wrote:\n\n```prompt\nAct as a senior engineer assembling my spec. Read what\nis already in my specs folder (user stories, MVP scope,\nthe five components, the data model, the non-functional\ntargets) and my rules file, then pull it into one short\nspec.md in that folder. Keep it tight and skimmable, a\nliving document, not forty pages. Where two pieces\ncontradict each other, or contradict the stack I already\nchose, say so and ask me. Never quietly pick a side.\nThen add one line to my rules file naming spec.md as the\nthing to read before building.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/plan/writing-the-spec\n\nMy pieces (paste them, or point to the files in specs):\n```\n\n**Do this now:** paste the prompt, point your agent at your `specs` folder, and let it assemble `spec.md`. A later chapter turns this spec into instructions your agent builds from."
          }
        ]
      },
      {
        "id": "architect",
        "title": "Lay out a modular codebase for your AI",
        "chapters": [
          {
            "slug": "modular-foundation",
            "title": "Setup a Modular Foundation",
            "label": "Modularity",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/modular-foundation",
            "content": "---\ntakeaway: Modular monolith first\nshare: \"The one architecture decision that keeps an AI-built app changeable: build it as a modular monolith, clean parts inside one app, from the very first file, so it bends instead of breaks as it grows.\"\nrequires: [ai-agent, running-app, spec-file]\nproduces: [module-boundaries]\nteaches: [separation-of-concerns, modular-monolith, big-ball-of-mud, premature-microservices, module]\nuses: [ai-coding-agent, entity, user-story]\n---\n\n{/* KEEP: lead-in = you are about to have the agent generate the app; left alone it pours every feature into one growing tangle that works Friday and cannot be touched Monday. This chapter gives the one architecture decision that keeps it changeable: build it as separate parts from the first file. */}\n\nYou are about to ask your agent to build the app, and it will happily generate whatever runs. Left alone, it pours every feature into one growing tangle that works on Friday and cannot be safely touched by Monday. This chapter gives you the one architectural decision that keeps the app changeable as it grows: build it as separate parts from the very first file.\n\n{/* KEEP: separation of concerns = each part does one job and knows as little as possible about the others; payments handle payments, users handle users, neither reaches into the other's internals. You do not enforce this by hand, you tell the agent the areas are distinct and hold it to that on every feature. Bold-first: separation of concerns. */}\n\n## Separate concerns from the start\n\nThe oldest rule in software is **separation of concerns**: each part of the app does one job and knows as little as possible about the others. Payments handle payments, accounts handle accounts, and neither reaches into the other's internals.\n\nYou do not enforce this by hand. You tell the agent the app is made of distinct areas that each stay behind their own door. Then you hold it to that every single time it adds a feature.\n\n{/* KEEP: modular monolith = one program you run and deploy as a single thing, split inside into clear modules with clean lines between them; one app outside, many tidy rooms inside. It is the right starting architecture for almost everyone: simplicity of one codebase plus internal boundaries. Bold-first: modular monolith. */}\n\n## Start with a modular monolith\n\nA **module** is one self-contained area of your app, all the code for one job kept together: accounts in one, billing in another. A **modular monolith** is one program you run and deploy as a single thing, split inside into those modules with clean lines between them. One app on the outside, many tidy rooms on the inside.\n\nThis is the right starting architecture for almost everyone. You get the simplicity of one codebase to run, build, and debug, plus the internal boundaries that let you change one area without disturbing the rest.\n\n{/* KEEP: two failure modes on either side. big ball of mud = no boundaries at all, every part reaches into every other, one change ripples everywhere (link laputan.org/mud). premature microservices = splitting into separate deployed services too early, a solo builder trades a problem they have (organizing code) for ones they do not (networks, versioning, distributed failure). Link Fowler MonolithFirst. Bold-first: big ball of mud, premature microservices. */}\n\n## Avoid the mud ball\n\nTwo failure modes sit on either side. The [**big ball of mud**](http://www.laputan.org/mud/) is what you get with no boundaries at all: every part reaches into every other, and one change ripples everywhere at once.\n\nThe opposite mistake is splitting the app into separate deployed services too early, [**premature microservices**](https://martinfowler.com/bliki/MonolithFirst.html). A solo builder who does this trades a problem they have, organizing code, for problems they do not: networks between services, version mismatches, and failures spread across machines.\n\n```mermaid\n%% caption: From no boundaries to too many services, the modular monolith is the sweet spot.\nflowchart LR\n  MUD[Big ball of mud] -.->|add boundaries| MONO([Modular monolith])\n  MONO -.->|split too early| MICRO[Premature microservices]\n```\n\n{/* KEEP: clean modules let the app bend instead of break: a feature drops into the area it belongs to, a bug stays contained to one room, you hand the agent one module at a time without the whole app in its head. And if you truly outgrow the single app, clean boundaries are the seams you cut along, a module lifts out into its own service, a mud ball gets rewritten. Not choosing against scale, earning the right to it later. */}\n\n## A foundation that bends instead of breaks\n\nClean modules are what let the app bend instead of break. A new feature drops into the area it belongs to, and a bug stays contained to one room. You can also hand your agent one module at a time, without it needing the whole app in its head.\n\nIf you ever genuinely outgrow the single app, the boundaries you drew are the seams you cut along. A module with a clean edge lifts out into its own service; a mud ball has to be rewritten. You are not choosing against scale, you are earning the right to it later.\n\n{/* KEEP: the METHOD for drawing the module lines, added July 2026 because this was the hardest call in the part and got one parenthetical. Three beats, keep all three: name modules after what the business talks about and never after technology; the lines are already in the plan, since the entities from the data model and the user stories cluster into the same three or four groups; two tests, a module owns its own data and nothing outside writes to it, and two areas that always change together are one module. */}\n\n## Your data model already shows you the modules\n\nYou do not invent these boundaries, you read them off the plan you already wrote. Name each module after something your business talks about, accounts, billing, notifications, and never after a technology, so nothing ends up called services or helpers.\n\nThe entities you sketched in your data model cluster into three or four groups, and your user stories fall into the same groups. Start there and you are usually right the first time.\n\nTwo tests settle the rest. A module owns its own data and nothing outside it writes to that data, and two areas that always change together were one module all along.\n\nThis prompt draws the boundaries with you rather than for you:\n\n```prompt\nAct as a senior engineer drawing the module\nboundaries for my app. Read my spec first, the whole\nof it: the components I mapped, the screens, and\nwhat I cut from the MVP all move these lines.\n\nPropose three or four modules, each owning one area.\nFor each, name what it owns, what it must never\nreach into, and which entities live inside it. Name\nthem after the business, never after a technology.\nPrefer one modular app over separate services. Where\ntwo modules want the same data, say which one owns\nit and how the other asks.\n\nShow me the split and your reasoning before creating\nanything. Once I agree, record the boundaries in my\nspec and add one line to my rules file saying where\nnew code goes.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/modular-foundation\n\nMy data model and my user stories:\n```\n\n**Do this now:** paste the prompt, hand over your data model and stories, and agree the three or four modules before your agent generates a line of the app."
          },
          {
            "slug": "folder-structure",
            "title": "Where Everything Lives",
            "label": "Structure",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/folder-structure",
            "content": "---\ntakeaway: Organize by feature\nshare: Your agent scatters one feature across five type-folders and nobody can find anything. Give each feature its own folder, keep one home for shared code, and you and your agent navigate the codebase the same way.\nrequires: [ai-agent, project-folder, running-app, module-boundaries]\nproduces: [folder-layout]\nteaches: [file-type-folders, feature-based-structure, shared-code]\nuses: [test, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the scaffolder's default tree is fine for one page and turns into a pile once features land; left alone the agent drops files wherever and both of you lose the code for a feature, so it writes duplicates. This chapter gives a folder shape organized by what the app does, one both of you navigate without a map. NOTE (sequencing, July 2026): the reader has a scaffolded skeleton here, not a messy codebase, so the pain is stated as what happens next, not as something already true. */}\n\nYour scaffolded project has a handful of folders, and they are fine for the one page you have. Start dropping features into them and it becomes a pile: you cannot find the code for one feature without opening ten folders, and neither can your agent, so it writes a second copy instead. This chapter gives you a folder shape organized around what the app does, one both you and your agent navigate without a map.\n\n{/* KEEP: the agent's default is file-type folders (components/, hooks/, services/) which smears one feature across all of them. Feature-based (a.k.a. package by feature) puts everything a feature needs in one folder, so the shape of the folders matches the shape of the app. Bold-first: file-type folders, feature-based. */}\n\n## Organize by feature, not by file type\n\nLeft alone, an agent reaches for **file-type folders**: a `components/` bin, a `hooks/` bin, a `services/` bin, everything of one kind piled together. The trouble is that one feature, billing say, ends up smeared across all of them, so touching it means hunting through five folders.\n\nOrganize the opposite way. A **feature-based** layout (also called package by feature) puts everything a single feature needs in one folder, so the shape of the folders matches the shape of the app.\n\n```mermaid\n%% caption: By type the billing feature splits across three bins; by feature it stays in one.\nflowchart LR\n  B1[Billing feature] --> CO[components/]\n  B1 --> HO[hooks/]\n  B1 --> SE[services/]\n  B2[Billing feature] --> FF[billing/]\n```\n\n{/* KEEP: each feature gets its own folder under src/features/, holding its screen + logic + data access + test side by side. Adding a feature = adding a folder, removing one = deleting a folder. Show the real folder tree. Frame: your agent writes this, here is the shape. */}\n\n## One folder per feature\n\nGive each feature its own folder under `src/features/`, and keep its screen, its logic, its data access, and its test side by side inside it. Your agent writes this, here is the shape:\n\n```\nsrc/\n  features/\n    billing/\n      BillingPage.tsx\n      useInvoices.ts\n      billing.api.ts\n      billing.test.ts\n    auth/\n      LoginForm.tsx\n      useSession.ts\n      auth.api.ts\n  shared/\n    ui/           (buttons, inputs used everywhere)\n    lib/          (dates, money, formatting)\n    types.ts\n```\n\nAdding a feature is now adding a folder, and removing one is deleting a folder. Nothing about billing lives anywhere but `billing/`.\n\n{/* KEEP: some code belongs to no single feature (a button on every screen, a money formatter, a date helper): that is shared code, one home in a shared/ folder next to features/. Be strict: code stays with its feature until a SECOND feature needs it. Rule-of-thumb callout. Bold-first: shared code. */}\n\n## A home for shared code\n\nSome code belongs to no single feature: a button used on every screen, a money formatter, a date helper. That is **shared code**, and it gets one home, a `shared/` folder sitting next to `features/`.\n\nBe strict about what earns a place there, or `shared/` becomes its own junk drawer.\n\n> **Rule of thumb:** keep code inside its feature folder until a second feature actually needs it, then move it to `shared/`.\n\n{/* KEEP (added July 2026, user mandate): the Set Up part promised that a second interface costs a shell and not a rebuild. This section is where that promise is kept. Show the tree that has room for more than one client, name real second clients (phone, watch, TV, extension) so the possibility feels concrete, and give the one-line test. Bound it hard: you build ONE client today, this is about not welding yourself shut. Do not bold \"interface\", the code sense belongs to the coupling chapter. */}\n\n## Leave room for a second front end\n\nThat tree assumes one thing in front of your app. Most products that survive end up with more: a phone app, a watch or TV app, a browser extension, a plugin inside somebody else's platform.\n\nYou are not building those today. You are only avoiding welding yourself shut, which costs nothing now:\n\n```\nyour-project/\n  api/          every rule, calculation, and database call\n    features/\n    shared/\n  web/          the first front end: screens only\n  shared/       types both sides agree on\n```\n\nA second front end then becomes a new folder beside `web/` that talks to the same `api/`, holding screens and nothing else. Put one rule inside `web/` instead, and the phone app has to reimplement it, and the two will disagree within a month.\n\n> **Watch out:** if adding a watch app would mean rewriting a rule rather than drawing a new screen, that rule is in the wrong folder. Move it down to `api/` before you have two copies to keep in sync.\n\n{/* KEEP: payoff = a predictable, uniform structure lets the agent know where to add new code and where to find existing code. Tell it the convention once and it stops scattering files and stops writing duplicates. The structure does the organizing. Do this now = have the agent lay out src/features + shared/ for your app. */}\n\n## Structure the agent can navigate\n\nA predictable structure is a gift to your agent. When every feature looks the same and shared code has one address, the agent knows exactly where to add new code and where to find what already exists.\n\nTell it the convention once and it stops scattering files and stops writing duplicates. The structure does the organizing, so you are not correcting placement on every task.\n\nThis prompt has your agent lay the tree out for you:\n\n```prompt\nAct as a senior engineer laying out my codebase.\nRead my spec and the module boundaries I already\nset, and take the feature list from there rather\nthan inventing one. Organize the code by feature,\nnot by file type. Under src/features, give each\nfeature its own folder, and co-locate its screen,\nits logic, its data access, and its test inside\nthat folder. Put code shared by two or more\nfeatures in a src/shared folder. Keep a feature's\ncode in its own folder until a second feature\nneeds it.\n\nKeep every rule, calculation, and database call\nout of the front end and behind the API, so a\nsecond front end later (a phone or watch app, an\nextension) is a new folder of screens and not a\nrewrite. Do not create that folder now: I have one\nfront end and I want one.\n\nShow me the folder tree first, then create it.\nThen add one line to my rules file saying where\nnew code goes, so this layout holds without me\nrepeating it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/folder-structure\n\nMy app and its features:\n```\n\n**Do this now:** paste the prompt above and list your app's features, so your agent lays out the folder tree for you."
          },
          {
            "slug": "coupling-and-cohesion",
            "title": "Keeping Pieces Independent",
            "label": "Coupling",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/coupling-and-cohesion",
            "content": "---\ntakeaway: Keep modules independent, each doing one job\nshare: When one small change breaks three unrelated things, your modules are too tangled. Loose coupling and tight cohesion keep a change where you made it, and let your agent work on one piece without holding the whole app in its head.\nrequires: [ai-agent, project-folder, folder-layout, module-boundaries]\nproduces: []\nteaches: [coupling, cohesion, circular-dependency, interface, dependency-injection, dependency-inversion]\nuses: [module, dependency, test, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the reader's real pain, one small change breaks unrelated things because modules reach into each other. This chapter gets them to spot that tangle and ask for looser seams. Do NOT teach folders/layers/naming here. */}\n\nYour agent ships fast, and then a one-line change to how orders are priced breaks the invoice screen and the email receipt too. That happens when your modules reach into each other instead of talking at arm's length. This chapter gets you the two words that name the problem, and how to point your agent at looser seams.\n\n{/* KEEP: concept = define BOTH. coupling = how much one module depends on another's insides. cohesion = how focused a module is on one job. Bold-first: coupling, cohesion. Keep it plain, one sentence each. */}\n\n## Coupling and cohesion, defined\n\n**Coupling** is how much one module depends on the inner workings of another. Two modules are tightly coupled when changing one forces you to change the other; loosely coupled when each can change on its own.\n\n**Cohesion** is how focused a single module is. A cohesive module does one clear job and holds only the things that job needs, instead of being a junk drawer of unrelated code.\n\n```mermaid\n%% caption: A cohesive Orders module holds only order work, not a junk drawer of extras.\nflowchart TD\n  subgraph GOOD[Cohesive]\n    O1[Orders] --> O2[Pricing]\n    O1 --> O3[Order totals]\n  end\n  subgraph BAD[Junk drawer]\n    J1[Orders] --> J2[Email templates]\n    J1 --> J3[PDF export]\n  end\n```\n\n{/* KEEP: why low coupling matters = a change stays contained. tight coupling = a change ripples out to places you did not touch; that ripple is the source of \"it broke and I do not know why\". Loose coupling caps the blast radius. */}\n\n## Keep a change from spreading\n\nTight coupling is why a small edit ripples into code you never opened. When one module knows how another stores its data, that knowledge is a wire, and every wire is a path for a change to travel down.\n\nLoose coupling caps the blast radius. Cut the wires and a change stays where you made it, which is the whole reason you can move fast without holding the entire app in your head. The worst wire runs both directions: a **circular dependency**, where A depends on B and B depends back on A, so neither one can change or be understood alone.\n\n```mermaid\n%% caption: With tight coupling, one pricing change ripples into unrelated screens.\nflowchart TD\n  CH[Change to order pricing] --> INV[Invoice screen breaks]\n  CH --> EMAIL[Email receipt breaks]\n```\n\n{/* KEEP: THE artifact. talk through an INTERFACE (a named contract, the promise a module makes) not internals. Bold-first: interface. Show tiny TS/pseudocode: caller reaching into order.items vs calling order.total(). The point = ask, do not reach. */}\n\n## Talk through interfaces, not internals\n\nThe fix is to make each module expose an **interface**, the short list of things it promises to do, and keep everything else private. Callers use the promise; they never reach past it.\n\n```ts\n// Reaching into internals: the caller knows how an Order\n// stores its lines, and breaks the day that changes.\nlet total = 0;\nfor (const line of order.items) {\n  total += line.price * line.qty;\n}\n\n// Talking through the interface: the caller just asks.\n// Order owns how it adds up; change it freely.\nconst total = order.total();\n```\n\nBecause a caller depends on the promise and not the parts behind it, you can hand a module what it needs from the outside instead of letting it reach for its own. That is **dependency injection**, and it is what lets a test pass in a fake service where the real one normally sits. Push it one step further and both sides depend on the interface in the middle rather than on each other's guts, which is **dependency inversion**.\n\n> **Rule of thumb:** if a module reads another's fields to do its work, it is reaching through the wall. Ask for a method that does the job instead.\n\n```mermaid\n%% caption: The caller uses the promise; the internals stay hidden behind it.\nflowchart LR\n  CALLER([Caller]) -->|order total| IFACE[Order interface]\n  IFACE --> INT[(Line items and prices)]\n  CALLER -.->|blocked| INT\n```\n\n{/* KEEP: synthesis = the goal is high cohesion + low coupling together, one job per module, arm's-length between them. Ends with prompt (audit ONE module for tight coupling, propose looser seams) + Do this now. */}\n\n## High cohesion, low coupling\n\nThe target is both at once: each module does one job well, and modules stay at arm's length from each other's insides. Your agent will not aim for this unless you ask, so ask.\n\n```prompt\nAct as a senior engineer auditing one module for\ncoupling and cohesion. Read my spec and the module\nboundaries I already drew, so you judge this module\nagainst the split I chose, not a generic one.\n\nCoupling: list every place this module reaches into\nanother module's internals (reads its fields, knows\nhow it stores data, depends on its private shape).\nFor each, propose a method or interface to call\ninstead, so the two can change independently.\n\nCohesion: name this module's one job, in the words my\nspec uses. Flag anything inside it that belongs to a\ndifferent job and should move out.\n\nIf the honest fix means changing a boundary I already\nset, say so and why. Propose first, rewrite nothing.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/coupling-and-cohesion\n\nThe module I'm worried about:\n```\n\n**Do this now:** paste the prompt, name one module you keep breaking by accident, and have your agent map its wires before you cut them."
          },
          {
            "slug": "boundaries-and-layers",
            "title": "Drawing the Boundaries",
            "label": "Layers",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/boundaries-and-layers",
            "content": "---\ntakeaway: Make dependencies point one way, inward\nshare: 'Inside every piece of your app, code splits into three layers: presentation, business logic, and data. Draw the boundary between them and point every dependency one way, so a change stays local instead of rippling out.'\nrequires: [ai-agent, project-folder, component-map, folder-layout]\nproduces: [layer-map]\nteaches: [layer, presentation-layer, business-logic, data-layer, repository-pattern, clean-architecture, hexagonal-architecture, layer-leak, dto]\nglosses: [import]\nuses: [module, database, framework, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = you named the five pieces, but inside one piece the code is a tangle (a screen running its own query, a rule buried in a button). Payoff: draw boundaries INSIDE a piece, three layers with one rule about which way they depend. Distinct from the-pieces-of-an-app (physical parts) and coupling (independence metrics). */}\n\nYou named the five pieces of your app. Inside any one of them, though, the code is usually a single tangle: a screen that runs its own database query, a pricing rule buried in a button handler. When everything can touch everything, one change ripples everywhere and your agent cannot tell you what a file is for. This chapter draws the boundaries inside a piece: three layers, with one clean rule about which way they depend.\n\n{/* KEEP: define the three layers, each changes for its own reason. Bold-first: layer, presentation layer, business logic, data layer. Presentation = what the user sees/touches. Business logic = the rules that make it YOUR app. Data = storage. */}\n\n## Presentation, logic, data\n\nSlice any part of your app into three **layer**s, each with one job. The **presentation layer** is what the user sees and touches: screens, buttons, the shape of a form. The **business logic** is the rules that make it your app and not a generic one: what a discount is, who may cancel an order, when a booking is valid. The **data layer** is storage: reading and writing rows, talking to the database or a file.\n\nThe point of the split is that each layer changes for its own reason. You redesign the screen without touching a pricing rule, and you swap the database without rewriting what a discount means. Reaching your data through one stable interface is called the **repository pattern**, and it is what lets the underlying database change without business logic ever noticing.\n\n{/* KEEP: a layer offers a short list of calls and hides the rest; the layer above calls one of them and never skips to reach below. Narrow boundary = you can rewrite behind it without opening the caller. Sets up the leak. Keep distinct from coupling's interfaces section: this is specifically the seam BETWEEN layers. */}\n\n## How modules talk\n\nA layer offers the one above it a short list of calls and hides everything else behind them. The presentation layer calls `placeOrder(cart)`, never sees the query the logic runs underneath, and never skips a layer to reach the one below it.\n\nKeep that boundary narrow on purpose. If the screen only ever asks for `placeOrder`, you can rewrite how orders are placed without opening a single screen file.\n\n```mermaid\n%% caption: The screen calls one named method; the query underneath stays hidden.\nflowchart LR\n  PRES([Screen]) -->|placeOrder cart| LOGIC[Logic layer]\n  LOGIC -->|runs query| DB[(Database)]\n  PRES -.->|never reaches| DB\n```\n\n{/* KEEP: dependencies point ONE way, inward toward the stable core (the business logic). Presentation and data depend on it; it depends on neither and must never import a screen or a db driver. Fenced sketch with both edges pointing IN. Reversing an arrow glues the durable core to the parts that change most. */}\n\n## Dependencies point one way\n\nEvery dependency points one direction: inward, toward the stable core. The business logic is that core. The presentation and data layers depend on it, it depends on neither, and it must never **import** (pull in the code of) a screen or a database driver.\n\n```\n  Presentation           Data\n  (screens, forms)   (database, files)\n       |                   |\n       | depends on        | depends on\n       v                   v\n       Business logic  =  the stable core\n       (the rules that make it your app)\n```\n\nBoth edges point in. Screens and storage are swappable details, and the rules at the center stay put. This inward-pointing, framework-independent shape is called **clean architecture** (also known as **hexagonal architecture**). Reverse an arrow, so the core imports the UI, and you glue the two together. The part that should outlive every redesign is now tied to the part that changes most.\n\n{/* KEEP: layer leak = a call that jumps the boundary (UI running a query, a business rule written into a screen). Real artifact: leak vs fixed. The leak works today and rots tomorrow because the rule now lives in a click handler. Bold-first: layer leak. Do this now = paste the audit prompt. */}\n\n## Don't let a layer leak\n\nA **layer leak** is a call that jumps the boundary: the presentation layer running a query straight against the database, or a business rule written into a screen.\n\n```\n# Leak: the screen reaches into the data layer\nbutton.onClick = () =>\n  db.query(\"UPDATE orders SET status='paid' ...\")\n\n# Fixed: the screen calls the logic; logic owns the rule\nbutton.onClick = () => payForOrder(orderId)\n```\n\nThe first line works today and rots tomorrow. The rule for paying an order now lives in a click handler, so the next screen that pays an order either duplicates it or gets it wrong. Route the call through the layer that owns the rule and the leak closes.\n\nSometimes a layer does need to hand data across the boundary. Give the next layer a **DTO** (data transfer object): a small plain shape built for the trip, instead of your internal objects. That keeps the layers decoupled.\n\nThis prompt has your agent sort your code into layers and check the arrows:\n\n```prompt\nAct as a senior engineer auditing my architecture.\nRead my rules file, my spec, and my folder layout\nfirst, so you sort the code I actually have against\nthe boundaries I already chose.\n\nSort my code into three layers: presentation (the UI),\nbusiness logic (the rules), and data (storage), naming\nthe layer of each file or module. Then check the\ndependency direction: the business logic must not\nimport the UI or the database library, and the UI must\nnot run queries or hold business rules. Flag every\nplace a layer reaches past its neighbor or points the\nwrong way, and give the one move that fixes each.\n\nWhere the code contradicts my recorded structure, say\nso rather than quietly picking a side. Then write the\nlayer rule and its allowed import direction into my\nrules file, so new code follows it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/boundaries-and-layers\n\nMy app's layers today:\n```\n\n**Do this now:** paste the prompt so your agent maps your files onto the three layers and flags every leak, then fix the one that points the wrong way."
          },
          {
            "slug": "api-design",
            "title": "Contracts That Last",
            "label": "API Design",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/api-design",
            "content": "---\ntakeaway: Design the contract first\nshare: 'Your frontend and backend agree on a shape: what a request looks like, what comes back, what an error looks like. Fix that agreement once, keep it consistent, and version it carefully, so a change on one side never silently breaks the other.'\nrequires: [ai-agent, project-folder, component-map, spec-file]\nproduces: [api-contract]\nteaches: [api, endpoint, contract, api-first, envelope]\nglosses: [json, http-status-code, pagination, monorepo]\nuses: [frontend, backend, json, http-status-code, semantic-versioning, pagination, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = frontend and backend talk over an agreed shape; the API is that agreement. Design the shape first, keep it consistent, version it so nothing breaks silently. Payoff = a contract that lasts. CODE-FORWARD. */}\n\nYour frontend asks your backend for data, and the backend answers. The exact shape of that exchange, what you send and what comes back, is a promise both sides rely on. Change it carelessly and every screen that read the old shape breaks at once. This chapter gets you a contract that stays stable as the app grows.\n\n{/* KEEP: API = the set of endpoints your app exposes; contract = the agreed request/response shape; endpoint = one URL + method. Decide the shape BEFORE the agent writes handlers, so both sides build to the same agreement. Bold-first: API, contract, endpoint. */}\n\n## Design the contract first\n\nYour **API** is the set of addresses your app exposes for others to call. Each one is an **endpoint**: a single URL plus a method (`GET /posts`, `POST /posts`) that does one job. The **contract** is the agreed shape of every request and response those endpoints exchange.\n\nDecide that shape before the agent writes a single handler. Designing the contract before you build anything is called **API-first** design. When the request and response are pinned down first, the frontend and backend can be built in parallel against the same agreement instead of guessing at each other.\n\n{/* KEEP: answers \"is this one project or two?\", which the reader cannot place otherwise: they hold one scaffolded Next.js project and this chapter suddenly implies two programs. Default for this book's stack = ONE project serving both halves, and the contract still matters inside it because only the backend can be trusted. Split into two packages in one repo (monorepo) or two repos ONLY when the halves deploy separately or a second client calls the same API. Added July 2026. */}\n\n## Your frontend and backend can share one project\n\nTwo programs does not mean two projects. In this book's stack, the single project you scaffolded serves both halves: your pages are the frontend, and the files under its API route folder are the backend. The contract still matters inside one project, because only the backend can be trusted with anything private.\n\nSplit them into two packages in one repo, a **monorepo**, or into two separate repos. Do that only when the halves deploy separately, or when a second client, a mobile app say, calls the same API. Before that the split buys you nothing and costs you a second build to keep working.\n\n{/* KEEP: every response uses ONE consistent envelope: success flag, data, error, meta (pagination). Show the JSON artifact. Then the error shape reuses the same envelope. Errors carry a stable code + message + a real HTTP status. Bold-first: envelope. Link MDN status on first mention. */}\n\n## Consistent shapes and errors\n\nWrap every response in one consistent **envelope**, the same outer shape whether the call succeeds or fails. It carries a success flag, the data, the error, and a `meta` block for **pagination**, serving a long list one page at a time. Here it is in **JSON**, the plain text format APIs use to send data:\n\n```json\n{\n  \"success\": true,\n  \"data\": { \"id\": 42, \"title\": \"First post\" },\n  \"error\": null,\n  \"meta\": { \"page\": 1, \"perPage\": 20, \"total\": 137 }\n}\n```\n\nA failure reuses the same envelope, flips the flag, and fills `error` instead of `data`:\n\n```json\n{\n  \"success\": false,\n  \"data\": null,\n  \"error\": { \"code\": \"not_found\", \"message\": \"No post with id 42\" }\n}\n```\n\nGive each error a stable `code` your frontend can branch on, a human `message`, and a real **HTTP status code**. That is the three-digit number the web uses to report how a request went ([MDN lists them](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status)): `200` for success, `404` for not found, `422` for bad input.\n\n{/* KEEP (added July 2026, user mandate): the API as a PRODUCT surface, not only an internal contract. Customers eventually want to skip your interface and automate, and live data is the pull. This is why the versioning discipline above matters. Then the honest security weight, stated plainly and cross-referenced BY TOPIC: rate limits and auth are taught much later, so no jargon here. */}\n\n## One day your customers will want it too\n\nEverything above treats the API as private wiring between your own two halves. That changes the first time a customer asks to skip your interface entirely, pull their live data on a schedule, and wire your product into theirs.\n\nSay yes when it happens, because it is the cheapest product surface you will ever ship: it already exists. What you are adding is a door, not a feature.\n\nIf customers want to shape their own queries rather than take your fixed responses, [GraphQL](https://graphql.org) is the usual answer. And a written description of your endpoints in a standard format like [OpenAPI](https://www.openapis.org) is what lets their tools, and their agents, use it without asking you anything.\n\nThe versioning discipline above is what makes that survivable. An internal client you can update yourself. A customer's script you cannot, so from the day one outsider depends on you, breaking a shape is something you schedule rather than something you do.\n\nBe clear-eyed about the cost, though. A public API is the largest attack surface you will ever open: every endpoint reachable by anyone with a key, no interface in front of it, and automated traffic that never gets tired. Each customer gets their own key, that key can only reach their own data, and there is a cap on how much any one of them can ask for. The security part of this book builds every one of those, and none of them is optional once the door is open.\n\n{/* KEEP: version so existing clients keep working. Put a version in the path (/v1/). Additive changes (a new optional field) are safe and stay in v1; anything that removes or renames = breaking = a new version (/v2), old one kept alive. Semantic versioning names this rule. Link semver.org. */}\n\n## Versioning without breaking clients\n\nPut a version in the path from day one (`/v1/posts`). Adding a new optional field is safe: old clients ignore it, so it stays in `v1`. Removing or renaming a field breaks anyone reading the old shape, so that goes in a new `/v2` while `v1` keeps running.\n\nThis is exactly the split [semantic versioning](https://semver.org) formalizes: additive is a minor change, breaking is a major one. You do not cut clients off, you give them a version to move to on their own schedule.\n\n```mermaid\n%% caption: Additive changes stay in v1; breaking changes get a new version.\nflowchart TD\n  Q{Removes or renames a field?}\n  Q -->|No, only adds| V1[Stays in v1]\n  Q -->|Yes, breaking| V2[New v2, keep v1 running]\n```\n\nThis prompt hands the whole contract to your agent:\n\n```prompt\nAct as a senior engineer designing my API contract.\nFirst read my spec and my data model. Endpoints must\nserve the stories in that spec and reuse the entity\nand field names from that model, never new ones.\n\nDefine one consistent response envelope for every\nendpoint: a success flag, a data field, an error\nobject, and a meta block for pagination. Give me the\nexact JSON for a success and an error response, a\nsmall set of stable error codes, and the HTTP status\neach maps to. Then propose a versioning scheme (path\nor header) and the rule for what counts as a\nbreaking change versus a safe additive one, so\nexisting clients never break.\n\nKeep to the layer rule and module boundaries I\nalready set. If one has to bend, name it and say why\nrather than diverging quietly. Save the contract\nwith my spec.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/api-design\n\nMy API and what it returns:\n```\n\n**Do this now:** paste the prompt with your endpoints, let your agent define the envelope, error codes, and versioning rule, then hold every new endpoint to that one shape."
          },
          {
            "slug": "third-party-boundaries",
            "title": "Wrap the Services You Depend On",
            "label": "Integrations",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/third-party-boundaries",
            "content": "---\ntakeaway: Put a vendor behind your own door\nshare: 'Stripe, an email service, an LLM API: each outside service should be reachable through one thin adapter you own, so swapping a vendor becomes a one-file change instead of a rewrite.'\nrequires: [ai-agent, project-folder, folder-layout, env-file]\nproduces: [vendor-adapter]\nteaches: [vendor-lock-in, anti-corruption-layer]\nglosses: [adapter, import, sdk, webhook]\nuses: [adapter, interface, library, import, api, coupling, sdk, webhook, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = your agent wires a payment SDK, an email service, an AI API straight into feature code wherever it needs them. Works until the vendor changes prices, you switch providers, or the SDK breaks, and the change is scattered across twenty files. Payoff: get each outside service behind one door you control. Distinct from api-design (the API you EXPOSE); this is services you CONSUME. */}\n\nYour agent wires an email service, an AI API, and a payment **SDK**, the vendor's own ready-made code, straight into feature code, wherever each one is needed. It works, until the vendor changes its prices, you want to switch providers, or the SDK ships a breaking change. Now that one change is scattered across twenty files. This chapter gets each outside service behind one door you control.\n\n{/* KEEP: Concept. When feature code calls a vendor SDK directly, the vendor is glued into the whole app; a swap or a breaking change means editing everywhere it appears. Vendor entanglement is one of the most common rewrite triggers in AI-built apps. Bold-first: vendor lock-in. Note this is a service you CONSUME, distinct from the API you expose (api-design). */}\n\n## A vendor threaded everywhere is a rewrite waiting\n\nWhen feature code calls a vendor's SDK directly, the vendor is glued into your whole app. Every screen that charges a card **imports** the payment library, pulling that vendor's code into its own file. Every place that emails a user does the same with the mail library. This is **vendor lock-in**: the outside service is now welded into dozens of files.\n\nThe day the vendor raises its price, breaks its SDK, or loses your trust, the swap means editing everywhere it appears. Vendor entanglement is one of the most common rewrite triggers in AI-built apps. Note this is a service you consume, distinct from the API you expose.\n\n{/* KEEP: Step. An adapter (glossed in one clause and bolded here on first use, since patterns teaches it properly later; do not re-teach the pattern here) is a thin file you own that wraps the vendor; your code calls YOUR adapter (charge(...)), and only the adapter knows the vendor exists. REAL ARTIFACT: feature code -> your wrapper -> the vendor SDK, imported in exactly one place. Plus the mermaid. */}\n\n## Put each service behind one adapter\n\nGive each outside service one **adapter**, a thin file you own that wraps the vendor and stands between it and your code. Your feature code calls your function (`charge(...)`), and only the adapter file ever imports the vendor. That one file is the whole surface the rest of your app sees. This owned wrapper is sometimes called an **anti-corruption layer**, because it stops the vendor's shape from leaking into, and corrupting, the rest of your code.\n\n```ts\n// features/checkout.ts  (feature code, vendor-free)\nimport { charge } from \"../lib/payments\"\nawait charge({ amountCents, currency, customerId })\n\n// lib/payments.ts  (YOUR adapter: the ONLY file\n// allowed to import the vendor SDK)\nimport Stripe from \"stripe\"\nconst stripe = new Stripe(process.env.STRIPE_KEY)\n\nexport async function charge(p) {\n  const intent = await stripe.paymentIntents.create({\n    amount: p.amountCents,\n    currency: p.currency,\n    customer: p.customerId,\n  })\n  return { id: intent.id, status: intent.status }\n}\n```\n\nSome vendors also call back. A payment provider takes your charge request, then contacts your app minutes later with the outcome, over a webhook, an address on your app the vendor sends to. That handler belongs beside the adapter and not in a feature file, so everything about that vendor still lives in one place.\n\n{/* KEEP: Step. To change providers or absorb a breaking change, you rewrite the ONE adapter, and the rest of the app never notices. This is exactly the \"extend without rewrites\" the architect part is about. */}\n\n## Now you can swap without a rewrite\n\nTo move from one provider to another, or to absorb a breaking SDK change, you rewrite the inside of that one adapter. The `charge` function keeps the same name and the same shape, so every file that calls it stays untouched.\n\nThe rest of your app never notices the vendor changed. That is exactly the \"extend without rewrites\" this part is built around: a swap that could have touched twenty files now touches one.\n\n{/* KEEP: the LIMIT on the rule, added July 2026. Stated without one, the reader wraps their framework, their database library and their UI toolkit too, which no senior would do. Wrap what you could plausibly swap (payments, email, SMS, model APIs, auth); never wrap the platform you have committed to, where the wrapper is a layer to see through with no swap behind it. */}\n\n## Wrap what you could swap, not your framework\n\nThe rule has an edge, and it is worth knowing before you over-apply it. Wrap the services you could plausibly change one day: payments, email and SMS, an AI model API, a login provider.\n\nDo not wrap your framework, your database library, or your UI toolkit. You committed to those when you picked your stack. Swapping one would be a rewrite either way, so the wrapper buys you nothing and costs every reader a layer to see through.\n\n{/* KEEP: Step. Keep the door THIN and in YOUR words: the adapter exposes only what your app needs, in your own terms, not the vendor's full surface. Do not leak vendor-shaped types through it. Refer to talking-through-interfaces / coupling by topic, do not re-teach. Do this now = paste the prompt. */}\n\n## Keep the door thin and in your words\n\nAn adapter is only useful if it stays narrow. Expose the handful of operations your app actually needs, named in your own terms (`charge`, `refund`, `sendEmail`), not the vendor's entire API surface.\n\nDo not let the vendor's own types leak back out through the door. If `charge` returns the vendor's raw response object, every caller is quietly coupled to that vendor again, and you are back where you started. Return a small shape you define, the same narrow-interface idea from the coupling chapter.\n\nThis prompt has your agent pull every vendor behind its own door:\n\n```prompt\nAct as a senior engineer hardening my vendor\nboundaries. Read my rules file and my folder layout\nfirst, so adapters land where my layer rules put\nthem and respect my import direction.\n\nFind every place my code touches an external service\ndirectly: a payment SDK, an email or SMS provider,\nan LLM API, an auth SDK. Move each vendor call\nbehind a single thin adapter I own, so exactly one\nfile imports that vendor's SDK. Expose only the\noperations my app needs, named in my own terms, and\nnever leak the vendor's own types back through the\nadapter. Do not wrap my framework, my database\nlibrary, or my UI toolkit.\n\nList each service, the one file that should own it,\nand the functions the rest of my app calls instead.\nAdd one line to my rules file: only its adapter may\nimport a vendor SDK.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/third-party-boundaries\n\nMy services and where they are called:\n```\n\n**Do this now:** paste the prompt so your agent finds every direct vendor call and moves each behind one adapter you own, then confirm exactly one file imports each SDK."
          },
          {
            "slug": "conventions-and-naming",
            "title": "Naming Things Consistently",
            "label": "Conventions",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/conventions-and-naming",
            "content": "---\ntakeaway: Write the conventions down\nshare: 'Left to itself, an agent writes each new file in a slightly different style, and the codebase turns into a patchwork. Conventions are the one-hand rules you write down once so every file matches.'\nrequires: [ai-agent, project-folder, rules-file]\nproduces: [coding-conventions]\nteaches: [convention, formatter, linter]\nglosses: [function]\nuses: [function, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = an agent left alone writes each file in a slightly different style; the codebase becomes a patchwork nobody can read at a glance. Chapter = pick one style, name things one way, write it in a file the agent follows so consistency is enforced not remembered. */}\n\nLeft to itself, your agent writes each new file in whatever style feels right that session: camelCase here, snake_case there, one file with tabs and the next with spaces. Each piece works, but the codebase reads like five people who never met wrote it. This chapter gets you one consistent hand across the whole project, enforced by a file, not by your memory.\n\n{/* KEEP: a convention = a repeated decision made once and reused everywhere. The specific choice matters less than sticking to it. Mechanical formatting (quotes, spacing, semicolons) is settled by a formatter/linter so nobody argues it. Bold-first: convention. Link Prettier + ESLint official only. */}\n\n## Pick one way and keep it\n\nA **convention** is a decision you make once and then repeat everywhere: quote style, indentation, how files are named, how a boolean reads. Which way you pick matters far less than picking one and never drifting. Two reasonable styles applied consistently beat one perfect style applied half the time.\n\nThe purely mechanical decisions (spacing, quotes, trailing commas) you should not decide by hand at all. A formatter like [Prettier](https://prettier.io) rewrites every file to one layout on save, and a linter like [ESLint](https://eslint.org) flags the rest, so that whole category stops being a discussion.\n\n{/* KEEP: naming is where \"one hand\" is won or lost. Standard buckets: components PascalCase, functions/vars camelCase, files kebab-case, constants UPPER_SNAKE_CASE, booleans is/has/should/can. Three-column table Category|Inconsistent|Consistent. */}\n\n## Names that read as one hand\n\nNaming is where a codebase either reads like one author or like a committee. Variables and **functions**, the named blocks of code you call to do one job, go in `camelCase`. The other standard buckets are worth adopting as-is: types and components in `PascalCase`, filenames in `kebab-case`, constants in `UPPER_SNAKE_CASE`. Booleans start with `is`, `has`, `should`, or `can`, so they read like a yes-or-no question.\n\n| Category | Inconsistent                    | Consistent              |\n| -------- | ------------------------------- | ----------------------- |\n| Function | `GetUser`, `fetch_user`         | `getUser`, `fetchUser`  |\n| Boolean  | `active`, `loaded`              | `isActive`, `hasLoaded` |\n| File     | `UserCard.tsx`, `user_card.tsx` | `user-card.tsx`         |\n\n```mermaid\n%% caption: One rule per kind of name: route each identifier to its casing.\nflowchart TD\n  N{What kind of name?} -->|Type or component| PC[PascalCase]\n  N -->|Variable or function| CC[camelCase]\n  N -->|Filename| KC[kebab-case]\n  N -->|Constant| US[UPPER_SNAKE_CASE]\n  N -->|Boolean| BQ[isActive hasLoaded]\n```\n\n{/* KEEP: write the conventions in a file the agent reads (ties to the rules file from last chapter). Show the real artifact: a short conventions block. Consistency becomes enforced, not remembered. */}\n\n## Write the conventions down\n\nRules you only hold in your head get applied when you remember and skipped when you do not. Put them in the rules file your agent already reads every session, so it writes to them from the first line instead of you correcting them after.\n\nKeep it short and concrete, the kind of block you can paste straight in:\n\n```\n## Conventions\n- Components/types: PascalCase. Vars/functions: camelCase.\n- Filenames: kebab-case. Constants: UPPER_SNAKE_CASE.\n- Booleans read as a question: isActive, hasLoaded.\n- Prettier owns formatting; do not hand-format.\n- One component per file; match the filename to it.\n```\n\n{/* KEEP: consistency > any one person's taste. Don't relitigate a settled style; the win is uniformity, not winning the argument. Let the formatter own mechanical style. Do this now = have the agent write the conventions into the rules file and apply going forward. */}\n\n## Consistency beats personal taste\n\nYour preference for single quotes is not worth a codebase split down the middle. Once a convention is written, treat it as settled and let the agent apply it everywhere, including code you would have styled differently. The value is uniformity, not being right.\n\nThis prompt has your agent record your conventions and follow them from now on:\n\n```prompt\nAct as a senior engineer. Read my rules file, my folder\nlayout, and my layer boundaries first, then infer the\nnaming and style conventions already in use.\n\nWhere they conflict, pick one consistent choice per\ncategory (casing for types, functions, files, constants;\nboolean naming; quote and format style) and tell me the\ncalls you made. Nothing you pick may contradict a decision\nalready written in my rules file. If one must, say so and\nwhy instead of quietly diverging.\n\nWrite the result into my rules file as a short Conventions\nsection, then apply it to any code you touch from now on.\nKeep it tight and concrete.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/conventions-and-naming\n\nMy stack and current style:\n```\n\n**Do this now:** paste the prompt so your agent writes the conventions into your rules file, then read the choices it made and change any single one you disagree with."
          },
          {
            "slug": "configuration",
            "title": "The Knobs You Will Turn",
            "label": "Configuration",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/configuration",
            "content": "---\ntakeaway: Pull every future decision into config\nshare: 'You will never read every line your agent writes, and you should not try. Pull the values you already know will change into one file per module, and that file becomes the small part you do read.'\nrequires: [ai-agent, project-folder, module-boundaries, coding-conventions]\nproduces: [module-config]\nteaches: []\nuses: [config, module, secret, ai-coding-agent, prompt]\n---\n{/* KEEP (added July 2026, user mandate): the honest answer to \"how much of this do I actually have to read\". You cannot read all of it; the move is to make the part that matters small and always in the same place. That part is the config. This chapter is the design discipline, NOT the secrets-vs-config distinction, which the Set Up part already taught. */}\n\nYou are never going to read every line your agent writes, and you should not try. But some of what it writes are decisions rather than instructions, and those you do have to read, every time. This chapter is about making that part small, obvious, and always in the same place.\n\n{/* KEEP: CONCEPT and the mental move that carries the chapter: before building anything, ask what about this will change later WITHOUT the logic changing. Rate limits, model choice, timeouts, retries. Those are decisions wearing implementation's clothes. Show the buried version and the pulled-out version side by side, that pair teaches faster than prose. */}\n\n## Ask what will change, then pull it out\n\nBefore your agent builds anything, ask one question: what about this will I want to change later without touching the logic?\n\nBuild a rate limiter and you already know the number moves. Wire up a model and you know you will swap it, and adjust the timeout, and cap the retries. None of that is implementation. They are decisions wearing implementation's clothes, and buried inside a function they are invisible to you and trivially easy for an agent to duplicate somewhere else.\n\n```\n// buried in the logic: invisible, and copied by Friday\nif (requestsThisMinute > 60) reject()\n\n// billing/config.ts: one place, and you can read it\nexport const billingConfig = {\n  rateLimitPerMinute: 60,\n  invoiceRetryAttempts: 3,\n  currency: 'EUR',\n}\n```\n\n{/* KEEP: STEP. One config file per module, holding every knob that module owns. The payoff is the reading claim: you skip the implementation and still know what the app will do, because every decision is on one screen. Rule-of-thumb callout on the three-files test. Secrets are explicitly NOT this, one clause, cross-referenced by topic. */}\n\n## Give every module one config file\n\nEach module gets a single settings file, and every knob that module owns lives in it: limits, timeouts, retries, which model, which provider, which feature is switched on.\n\nThat file is what you read. You can skip a thousand lines of implementation and still know what your app will do, because every decision that module makes sits on one screen. Keys and passwords are the exception and never belong here; they stay in the **secret** handling you set up earlier.\n\n> **Rule of thumb:** if answering \"what is our rate limit\" means opening three files, the config is not doing its job.\n\n{/* KEEP: STEP, the strongest idea in the chapter and the author's core point. There is usually more than one way to achieve anything and the agent takes whichever it finds first, so you DELETE the other ways on purpose. Good design here is the options you removed, not the flexibility you added. The framing must be about designing the agent into the right path rather than reminding it. */}\n\n## Leave exactly one way to change it\n\nThere is almost always more than one way to achieve something, and your agent will take whichever route it finds first. Say a limit can be set in the config, passed as an argument, or hardcoded in a helper. In a few months it will be set in all three, and they will disagree.\n\nSo remove the other routes deliberately. One name, one file, one way to change it. Good design here is not the flexibility you added, it is the options you took away.\n\nThat is worth more than any instruction you could write. An agent with one available path takes the right one every time, without being reminded, and without you noticing it was ever at risk of doing otherwise.\n\n{/* KEEP: STEP. Consistency across modules: they can be wildly different inside and must still expose settings identically, same filename, same shape, same place. The payoff is answering a question about a module you have never opened. Ties to the conventions chapter by topic, do not re-teach conventions. */}\n\n## The same shape in every module\n\nModules can be completely different inside and should still expose their settings identically: same filename, same location, same style. Plain code, JSON, or YAML all work; picking one and using it everywhere matters more than which.\n\nThat sameness is a convention like any other, and it earns its place faster than most. It pays twice over for anything you run several of: put every model and provider you call in one file and you can compare them side by side, swap one, and see the whole bill in a single read.\n\nThe payoff arrives the first time you need something from a module you have never opened. You know where to look before you look, and so does your agent.\n\n{/* KEEP: the prompt. Creates one config per module from values ALREADY in the code, forbids leaving a copy behind, keeps secrets out, and then the important half: find every setting changeable in more than one place and delete the extra routes. Records the convention so it holds. One append slot. */}\n\n## Have your agent pull the knobs out\n\n```prompt\nAct as a senior engineer setting up configuration for\nmy project. Read my module boundaries and my\nconventions first, and follow what they already say.\n\nFor each module, create one config file holding every\nvalue that module owns: limits, timeouts, retries,\nwhich model or provider, and any feature switch. Move\nthose values out of the logic and leave no copy behind.\nKeys and passwords stay where my secrets setup already\nputs them and never appear here.\n\nThen go through the code and list every setting that\ncan currently be changed in more than one place. For\neach one, make the config file the only home and\ndelete the other routes, so there is one way to change\nit and no second path.\n\nUse the same filename and the same shape in every\nmodule, then record that convention so it holds without\nme repeating it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/configuration\n\nMy modules, and the settings I already know will change:\n```\n\n**Do this now:** paste the prompt, then open one config file and read it end to end. If it does not tell you what that module will do, a knob is still buried in the code."
          },
          {
            "slug": "enforcement",
            "title": "Make the Wrong Thing Impossible",
            "label": "Enforcement",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/enforcement",
            "content": "---\ntakeaway: Make the wrong path impossible to take\nshare: 'Instructions get skipped on a long session. Code cannot skip a required argument. Shape your codebase so the wrong move fails on its own and the agent has only one road left.'\nrequires: [ai-agent, project-folder, module-boundaries, coding-conventions]\nproduces: [enforced-contracts]\nteaches: [make-invalid-states-unrepresentable]\nuses: [ai-coding-agent, prompt, rules-file]\n---\n{/* KEEP (added July 2026, user mandate): the author's strongest architecture idea. Rules and skills are advisory and an agent WILL route around them late in a session; the fix is not a better instruction, it is code that cannot be used wrongly. This chapter is the general form of the one-path idea the configuration chapter applies to settings. */}\n\nYour rules file tells the agent what to do, and most days it listens. Then a long session runs down, the context fills, and it quietly does the thing you forbade in writing three weeks ago. This chapter is about the fix that does not depend on it remembering anything.\n\n{/* KEEP: CONCEPT. Instructions are advisory, structure is not. The move is to design so the wrong thing FAILS rather than trusting it not to be attempted. Bold-first: make invalid states unrepresentable. The line that must survive: you are not writing a better rule, you are removing the ability to break it. */}\n\n## An instruction can be skipped, a required argument cannot\n\nEverything you write in a rules file is advice. It is read, weighted against everything else in the window, and sometimes loses. Nothing enforces it.\n\nStructure is different. If the function that creates a page cannot be called without the thing you require, no amount of tiredness gets around it. Designing so the broken version cannot even be expressed has a name in engineering: **make invalid states unrepresentable**. You stop writing a better rule and remove the ability to break the rule.\n\n{/* KEEP: STEP, the author's own example and the clearest teaching case in the chapter. Every contact form must send a confirmation email; a rule saying so gets forgotten, so the form builder REQUIRES the template as an argument and there is no path to a form without one. Show both versions in code, the pair does the work. */}\n\n## Require the thing you would otherwise forget\n\nSay every form on your site must send a confirmation email. You can write that in the rules and hope. Or you can make the form impossible to build without one:\n\n```\n// advisory: the rule lives in a file, and gets forgotten\ncreateForm({ fields, onSubmit })\n\n// enforced: there is no form without a confirmation\ncreateForm({ fields, onSubmit, confirmationEmail })\n```\n\nThe second version does not need you to remember, review, or notice. A form with no confirmation is not a mistake anyone has to catch, because it will not run.\n\nLook for these wherever a step is easy to omit and expensive to omit: the audit line on a sensitive action, the tenant filter on a query, the permission check before a delete.\n\n{/* KEEP: STEP, the grouping idea. Things of the same family (drawers, forms, jobs, emails, model calls) get registered in ONE place so the whole family can be listed, changed, and reasoned about as a unit. Otherwise the agent adds a twelfth one you never see and it drifts from the other eleven. Show the registry shape. */}\n\n## Register a family in one place\n\nThe second failure is quieter. You have five side drawers, and the agent adds a sixth somewhere new. It works, it looks fine, and it slowly drifts from the other five because nobody could see them side by side.\n\nAnything you have more than three of belongs in one registry: drawers, forms, background jobs, outbound emails, model calls. One file lists the family, and adding to the family means adding a line there.\n\n```\n// ui/drawers/registry.ts\nexport const drawers = {\n  settings: SettingsDrawer,\n  billing: BillingDrawer,\n  invite: InviteDrawer,\n}\n```\n\nNow the family is one thing. You can change all of them at once, count them, and see the odd one out. So can your agent, in a single read instead of a search.\n\n{/* KEEP: STEP. Commands that PRINT things. Two payoffs and both matter: you get an audit without reading code, and the command cannot be written unless the family is grouped, so it forces the previous section to stay true. Show real command names. */}\n\n## Add a command that prints each family\n\nThen put a command in front of every registry:\n\n```\nmake list-forms      # every form, and its confirmation email\nmake list-jobs       # every scheduled job, and its cadence\nmake list-models     # every model call, and which model it uses\n```\n\nTwo things come from this, and the second is the point. You get an honest answer in one second without reading any code, which is how you audit a system you did not type. And the command cannot exist unless the family is genuinely grouped, so writing it keeps the grouping honest.\n\n> **Rule of thumb:** if you cannot list something with one command, your agent cannot see it as one thing either, and it will drift.\n\n{/* KEEP: the prompt. Finds the rules that are currently advisory and converts each into structure where possible, builds registries for families that are scattered, and adds a list command per registry. Must say plainly which rules CANNOT be enforced structurally, so the reader knows what still relies on discipline. One append slot. */}\n\n## Turn your rules into structure\n\n```prompt\nAct as a senior engineer hardening my codebase against\nits own mistakes. Read my rules file, my conventions,\nand my module boundaries first.\n\nGo through every rule I currently rely on the agent to\nremember. For each, tell me whether it can be enforced\nin the code instead: a required argument, a type that\nwill not compile, a single entry point, a check that\nruns on its own. Convert the ones that can be, and say\nplainly which ones cannot, so I know what still depends\non discipline.\n\nThen find anything I have more than three of that is\nnot registered in one place: forms, drawers, jobs,\noutbound emails, model calls. Give each family one\nregistry file, and add a command that prints that\nfamily with the detail I would want to audit.\n\nAdd nothing speculative. Every registry and command\nmust cover something that already exists in my code.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/enforcement\n\nMy project, and the rules I keep having to repeat:\n```\n\n**Do this now:** paste the prompt, then take the one rule you have repeated most often and turn it into something the code refuses to run without."
          },
          {
            "slug": "architecture-handoff",
            "title": "Teaching the AI the Layout",
            "label": "Handoff",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/architecture-handoff",
            "content": "---\ntakeaway: Give the agent a map\nshare: 'Your agent knows your rules but not where things live, so new code lands anywhere. An architecture map in the file it reads every session tells it where each feature goes, so its code extends your structure instead of fighting it.'\nrequires: [ai-agent, project-folder, rules-file, folder-layout, layer-map, coding-conventions]\nproduces: [architecture-map]\nteaches: [architecture-map]\nuses: [layer, database, stack, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the always-read file tells the agent WHAT to do (rules) but not WHERE things live, so new code lands anywhere and fights the structure. This chapter adds the architecture map: a compact picture of the codebase in that same file so new code lands right. Builds on the memory/rules file, folder structure, layers, conventions taught earlier; point, don't re-teach. */}\n\nYour agent already reads a file every session that tells it your stack and your non-negotiables. But that file says what to do, not where anything lives. So new code lands wherever the agent guesses: a feature split across the wrong folders, a database call inside a button, a structure it invents instead of yours. This chapter gives the agent a map of your codebase in that same file, so its code extends your architecture instead of fighting it.\n\n{/* KEEP: concept = the architecture map is a compact picture of the codebase (where features live, the layer rule, the naming rule, where new code goes) added to the always-read file. It turns the agent from guessing to placing. Bold-first: architecture map. */}\n\n## Hand the agent the map\n\nAn **architecture map** is a compact picture of your codebase, added to the file your agent reads first. It says where features live, how the layers stack, what things are named, and where new code goes. It is the same thing a senior would tell a new hire before they touch anything.\n\nWithout it, the agent reverse-engineers your structure from whatever files it happened to open, and gets it wrong half the time. With it, the agent places code instead of guessing at it.\n\n{/* KEEP: the real artifact = show a compact map in the always-read file (AGENTS.md / CLAUDE.md). Rules plus structure in one place. Link agents.md on first mention, verified. Show the fenced example: where features live, layer rule + import direction, naming rule, \"new code goes here\". */}\n\n## Rules plus structure in one file\n\nThe map lives in the same always-read file as your rules, the one most tools share as [AGENTS.md](https://agents.md) or call `CLAUDE.md`. Rules say how to behave; the map says where the code goes. The agent needs both in front of it every session.\n\nKeep it a map, not an essay. A dozen lines that a beginner could not have written but an agent can follow exactly:\n\n```\n## Architecture\n\n- Features live in src/features/<name>/, self-contained.\n- Layers: ui -> hooks -> lib -> db. A layer imports\n  only downward, never up or sideways.\n- Shared code in src/lib/, shared UI in src/ui/.\n- Naming: components PascalCase, hooks use*, files\n  kebab-case.\n- New feature = a new folder under src/features/.\n  Nothing goes in the root. Match the nearest\n  neighbor's structure.\n```\n\n{/* KEEP: payoff = the map's \"new code goes here\" + layer rule + naming rule are what make output land correctly and read like the rest of the code. Not one-off, it holds across every session because the file is always read. */}\n\n## New code lands in the right place\n\nThat last line does the heavy lifting. \"New feature goes under `src/features/`, match the nearest neighbor\" turns a vague instruction into a placement the agent cannot miss. The layer rule then stops it from wiring a database call straight into the UI. The naming line makes the new file look like it was always there.\n\nBecause this lives in the always-read file, it holds on every session, not just the one where you happened to explain it. The agent stops inventing structure and starts filling in yours.\n\n{/* KEEP: keep it current = the map goes stale as the code grows (new layer, new top-level folder), and a stale map misroutes worse than none. Don't hand-maintain: when you add a real structural piece, have the agent update the map in the same change. Old map = old documentation, same discipline as the memory file. */}\n\n## Keep the handoff current\n\nThe map is only as good as its accuracy. Add a new top-level folder or a new layer and forget to update the map, and the agent follows the old one straight into the wrong place. A stale map misroutes worse than no map at all.\n\nDo not maintain it by hand. When you and the agent add a real structural piece, have it update the map in the same change. That is how your memory file grows itself when you correct it. Treat a map written months ago like old documentation: check it against the real folders before you trust it.\n\n```mermaid\n%% caption: Update the map in the same change, or a stale map misroutes worse than none.\nflowchart TD\n  ADD[Add a new layer] --> Q{Update map now?}\n  Q -->|Yes| FRESH[Map matches code]\n  Q -->|No| STALE[Stale map]\n  FRESH --> RIGHT([Agent routes right])\n  STALE --> WRONG([Agent misroutes])\n```\n\n{/* KEEP: prompt = have the agent read the codebase and write a compact, accurate architecture map into the reader's always-read file. Senior voice, expert content fixed, one append slot at bottom, lines <65 chars. Ends with Do this now. */}\n\n## Write the map into your file\n\nThis prompt has your agent read the code and write the map:\n\n```prompt\nAct as a senior engineer documenting my codebase for\nan engineer joining today. Read my project, my spec,\nand the layer, boundary, and naming rules I already\ndecided. Then add an Architecture section to the file\nmy agent reads every session (CLAUDE.md, AGENTS.md, or\nmy rules file). Keep it a compact map, not prose: where\neach feature lives, the layer rule and its allowed\nimport direction, the naming convention, and one line\nsaying where new code goes. Infer the real structure\nfrom the code, do not invent one. Keep it under fifteen\nlines, and list every place the code and my recorded\nrules disagree instead of picking a side for me.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/architecture-handoff\n\nMy structure, layers, and conventions:\n```\n\n**Do this now:** paste the prompt so your agent writes the map, then read it against your real folders and cut any line the code does not actually follow."
          },
          {
            "slug": "documentation",
            "title": "Writing for Humans and AI",
            "label": "Docs",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/architect/documentation",
            "content": "---\ntakeaway: Write down what code cannot say\nshare: 'You will rewrite onboarding, delete features, and redraw the app more than once. A README, a decision record, a changelog, and comments that say why are what make all that survivable instead of guesswork.'\nrequires: [ai-agent, project-folder, git-repo, spec-file, component-map, data-model]\nproduces: [project-docs]\nteaches: [readme, adr, changelog, mermaid, code-comment]\nuses: [git, commit, repo, spec, convention, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the architecture will CHANGE, heavily and repeatedly (onboarding rewritten, features deleted, shape redrawn), and these files are what makes that survivable rather than paperwork. Do not soften the change-is-normal framing, it is the reason the chapter exists. This chapter = the files that make the system legible: README, ADRs, CHANGELOG, and comments that record WHY. Last chapter of the Architect part: docs are what you carry into building. */}\nYou have the whole architecture now: the pieces, the data, the decisions behind them. None of it will survive contact with reality unchanged. You will rewrite onboarding, delete features you shipped, and redraw the shape of the app more than once. This chapter gives you the plain files that let all that happen without anyone having to reconstruct why the project is the way it is.\n\n{/* KEEP: README = the front door. What it is, why it exists, how to run it. First file anyone (and the agent) opens. Keep it plain. */}\n\n## The README is your project's front door\n\nA **README** is the file at the top of your project that answers the first questions anyone asks: what is this, why does it exist, and how do I run it. It is the first file a teammate opens, and the first the agent reads to orient itself.\n\nKeep it to what a newcomer needs on day one: a one-line description, the setup steps, how to start the app, and where the key docs live. Kept current, it takes someone from clone to running without asking you.\n\n{/* KEEP: ADR = record WHY a decision was made, dated, short. Architecture docs describe the shape; ADRs capture the reasoning so it survives. Show a real ADR template. Link adr.github.io. */}\n\n## Architecture docs and ADRs record your choices\n\nAn **ADR**, an [architecture decision record](https://adr.github.io), captures one decision and the reasoning behind it: short, dated, written the moment you choose. Six months on, nobody remembers why you picked Postgres over a document store, and the ADR is the answer.\n\nWrite one when a choice is hard to reverse or easy to question later. The format is deliberately small:\n\n```\n# ADR 0001: Use Postgres, not a document store\n\nDate: 2026-07-20\nStatus: Accepted\n\n## Context\nWe need relational queries across users, orders, and\ninvoices, with strong consistency at checkout.\n\n## Decision\nUse Postgres as the primary database.\n\n## Consequences\nJoins and transactions are easy. We add a search\nindex later if full-text needs grow.\n```\n\n{/* KEEP: CHANGELOG = track what changed over time, human-readable, newest first. Link keepachangelog.com. Optional conventional commits link. */}\n\n## The CHANGELOG tracks what changed\n\nA **CHANGELOG** is a running, human-readable list of notable changes, newest at the top, grouped by version. It answers \"what is different since last time\" without anyone reading the git history. The widely used convention is [Keep a Changelog](https://keepachangelog.com).\n\nYou do not write it from scratch: if your commit messages follow a convention like [Conventional Commits](https://www.conventionalcommits.org), the agent drafts it from them and you edit for clarity.\n\n{/* KEEP (added July 2026, user mandate): the FOURTH thing you write down, and the one this book needs more than a normal codebase does: comments that record WHY. The agent wrote the code, so in three months nobody, human or agent, remembers the reasoning; the code already says what it does. Explicitly counter the \"AI code needs no comments\" assumption. Keep the wrong/right pair, it does the teaching faster than prose. */}\n\n## Comments record why, never what\n\nThe code already says what it does, and your agent can explain any line on demand. What neither can recover is why it is that way, and that is the only thing worth writing in a comment.\n\nThis matters more here than in a codebase you typed yourself. You did not make most of these decisions line by line, so in three months the reasoning is gone unless someone wrote it down.\n\n| Wrong | Right |\n|---|---|\n| `// loop through the users` | `// batches of 50: the payment provider rate-limits above that` |\n\nReach for one when a future reader would reasonably ask \"why is this here\" or \"why not the obvious way\". A workaround for someone else's bug, a limit you hit, a rule that came from the business rather than the code.\n\n{/* KEEP (added July 2026, user mandate): the density reframe. The rule above does not change, but the READER did: your main reader is now an agent that arrives with no memory of any conversation, so the bar for \"worth a comment\" drops a long way and comment density in an agent-first codebase runs far higher than in a human one. Name the three things that earn one. Keep the anti-noise guard: still why, never what. */}\n\nThen adjust for who is actually reading. Your main reader is no longer a colleague who was in the room when you decided things. It is an agent that opens the file cold, every session, knowing nothing that was not written down.\n\nThat drops the bar for what earns a comment, a long way. In a codebase built this way, comments running close to half the file is normal rather than excessive. Three things earn one:\n\n- **Why it is like this**, the workaround, the limit, the business rule.\n- **What must stay true**, the condition the code below quietly depends on.\n- **What not to do here**, the obvious-looking change that would break something elsewhere.\n\nWhat still earns nothing is narration. `// loop through the users` helps no reader, human or otherwise, and your agent will generate it by the hundred if you let it.\n\n{/* KEEP: DIAGRAM = the mind map from the start of the book, drawn as a mermaid block that lives in the repo and renders on GitHub. A picture of how the pieces connect beats a page of prose. Distinct from modeling-your-data's data sketch: this is the whole-system wiring, not entities/fields. Have the agent draw it. Real artifact = a short copyable mermaid block. */}\n\n## Draw the architecture as a diagram\n\nThe mind map you started this book with, the pieces and how they talk, belongs in the repo as a picture. A **[mermaid](https://mermaid.js.org)** diagram is that picture written as plain text, so it renders on GitHub and in most editors and sits beside these docs. Have your agent draw your architecture as a few nodes:\n\n```mermaid\n%% caption: Your whole architecture as a few nodes: the pieces and how they talk.\nflowchart LR\n  user([User]) --> web[Web app]\n  web --> api[API]\n  api --> db[(Database)]\n  api --> pay[Payments]\n```\n\nA newcomer grasps the shape at a glance, and your agent gets a map instead of a page of prose.\n\n{/* KEEP: payoff = these docs are the agent's context. It reads README/ADRs/CHANGELOG the way it reads the memory file, so keeping them current is not admin, it directly makes the agent build correctly. Closing nod: the documented architecture is what you carry into building. */}\n\n## Your agent reads all of this before it builds\n\nThese files are not paperwork for humans alone. Your agent reads the README to orient, the diagram to see the shape, the ADRs to respect decisions you made, and the CHANGELOG to see where things stand. Stale docs mislead it exactly as they mislead a person.\n\nThat is the payoff of this whole part: a documented architecture is a system the agent can hold in its head and build against. It will not stay clean on its own; code decays as it grows, so a later part turns continuous cleanup into a habit. This prompt gives you the starter set:\n\n```prompt\nAct as a senior engineer documenting my project.\nRead my spec first, plus the architecture and\nconventions already recorded in my rules file, and\ndocument what is actually there.\n\nCreate three starter files:\n- README.md: one-line description, setup steps, how\n  to run it, and where key docs live.\n- docs/adr/0001-*.md: one ADR for a real decision I\n  already made (the stack, the database, or the\n  module split), using Context / Decision /\n  Consequences, dated, marked Accepted. Take the\n  reasoning from where I recorded it, not from\n  guesswork.\n- CHANGELOG.md: Keep a Changelog format, an\n  Unreleased section grouped Added/Changed/Fixed.\n\nKeep each file short and skimmable. Where a doc and\nthe code disagree, tell me which one is wrong.\nAsk me before inventing any fact you do not have.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/architect/documentation\n\nMy project:\n```\n\n**Do this now:** paste the prompt, name your project and one real decision you made, and let your agent write the starter README, ADR, and CHANGELOG."
          }
        ]
      },
      {
        "id": "build",
        "title": "Implement the application in working slices",
        "chapters": [
          {
            "slug": "directing-your-agent",
            "title": "Steering Your Agent",
            "label": "Direction",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/directing-your-agent",
            "content": "---\ntakeaway: Give the goal, steer early\nshare: You set the goal and the constraints, then catch the agent at its first wrong turn instead of after it has built the wrong thing. This chapter is the steering discipline that keeps AI fast without letting it run off.\nrequires: [ai-agent, project-folder, running-app]\nproduces: [steering-brief]\nteaches: [slice]\nglosses: [diff]\nuses: [ai-coding-agent, prompt, diff]\n---\n{/* KEEP: lead-in = agent is scaffolded and now runs off faster than you can read; the two failure modes are micromanaging every keystroke (lose the speed) and \"build my app\" then walk away (confident and wrong). This chapter = the middle path, point at the goal and steer before it drifts. */}\n\nYour agent is set up and the app skeleton runs. You type a request and it takes off, writing files faster than you can read them. Dictate every keystroke and you lose the speed you came for; say \"build my app\" and walk away and you get something confident and wrong. This chapter is the middle path: point the agent at the goal, and steer it before it drifts.\n\n{/* KEEP: concept = the agent is strongest given INTENT + boundaries, not a procedure. You own what \"done\" means and what must not break; it knows a thousand paths there. Two-column table contrasts keystroke-level instruction vs goal + constraints. */}\n\n## Give the goal, not the keystrokes\n\nThe agent is strongest when you hand it intent and boundaries, not a step-by-step procedure. You are the one who knows what \"done\" means and what must not break. It knows a thousand ways to get there, so describe the destination and let it pick the road.\n\n| Keystrokes (don't) | Goal + constraints (do) |\n| --- | --- |\n| \"Add a `role` prop to `UserCard`, then map over it\" | \"Show each user's role on their card\" |\n| \"Write a for-loop that sums the items\" | \"Total the cart, and handle an empty cart\" |\n\n```mermaid\n%% caption: You own the goal and the limits; the agent picks among many routes to it.\nflowchart LR\n  GOAL([Goal + constraints]) --> AG[Agent]\n  AG --> R1[Route A]\n  AG --> R2[Route B]\n  R1 --> DONE([Done])\n  R2 --> DONE\n```\n\n{/* KEEP: slice = one small self-contained change; give the agent ONE, not the whole feature. Small enough to check in minutes AND small enough the agent still does it well. Point forward BY TOPIC to working-in-small-steps (save points / rollback), do NOT deep-dive commits here. Bold-first: slice. */}\n\n## Work one slice at a time\n\nHand the agent one **slice**, one small self-contained change that either works or does not, never the whole feature at once. A slice is small enough that you can check it in a couple of minutes, and small enough that the agent still has room to do it well.\n\nTurning each finished slice into a save point you can return to is its own discipline, and the chapter on working in small steps covers it. Here the rule is only about size: keep the task small enough to steer.\n\n```mermaid\n%% caption: Give one slice, verify it, then the next, never the whole feature at once.\nflowchart LR\n  S1[Slice 1] -->|verify| S2[Slice 2]\n  S2 -->|verify| S3[Slice 3]\n  S3 -->|verify| DONE([Feature done])\n```\n\n{/* KEEP: check before accepting = look at what changed and confirm it does what you asked, not merely that it runs. Running != correct. Point forward BY TOPIC to reviewing-the-agents-code for HOW to read a diff; here the rule is just \"never accept a slice you haven't looked at.\" */}\n\n## Check its work before accepting\n\nBefore you accept a slice, read the **diff**, the exact list of lines it added and removed, and confirm it does what you asked. Running without an error is not the same as correct, and the agent will happily report success on the wrong thing.\n\nReading the agent's code closely is a skill of its own, covered when we get to reviewing what it wrote. For now the rule is blunt: never accept a slice you have not looked at.\n\n{/* KEEP: steer early = cost of a wrong turn grows with every line built on top of it; catch it at the first sign (a one-sentence fix) vs after 500 lines (untangling). Watch the FIRST file it touches and the plan it proposes, not the finished result. Rule-of-thumb callout. */}\n\n## Steer early, before it drifts\n\nThe cost of a wrong turn grows with every line built on top of it. Catch it at the first sign and one sentence corrects it. Catch it after five hundred lines and you are untangling. So watch the first file the agent touches and the plan it proposes, not just the finished result.\n\n> **Rule of thumb:** correct the agent on its first wrong turn, not its tenth. A nudge now is a rewrite later.\n\n```mermaid\n%% caption: Steer at the plan and the diff, one slice at a time.\nflowchart TD\n  S([One slice]) --> P[Agent proposes plan]\n  P --> Q{Plan on track?}\n  Q -->|No, correct now| P\n  Q -->|Yes| B[Agent builds slice]\n  B --> R[Read the diff]\n  R --> D{Does what you asked?}\n  D -->|No, steer| B\n  D -->|Yes, accept| S\n```\n\n{/* KEEP: prompt = a reusable steering brief that forces the agent to restate the goal, list constraints, propose the smallest first slice, and STOP before coding. Senior voice, expert content fixed at top, ONE append slot (My next feature:) at bottom, lines <65 chars. Ends with Do this now. */}\n\n## Turn any task into a steering brief\n\nThis prompt makes the agent slow down at the one moment that matters, before it writes code:\n\n```prompt\nAct as a senior engineer. Before writing any code\nfor the task below, do this in order:\n\n1. Read my rules file, my spec, my architecture\n   map, and my conventions, so you build to what\n   is already decided.\n2. Restate the goal in your own words.\n3. List the constraints and what must not break.\n4. Propose the smallest first slice, one change\n   I can verify in a couple of minutes.\n5. Stop and wait for my OK before coding.\n\nIf the slice needs a call that contradicts what\nis already recorded, say so and why instead of\nquietly diverging.\n\nAfter I approve, build only that slice, then show\nme exactly what you changed and why.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/directing-your-agent\n\nMy next feature:\n```\n\n**Do this now:** take the next thing you want built, paste the prompt above, and make the agent restate the goal and propose one slice before it writes a single line."
          },
          {
            "slug": "prompting",
            "title": "Instructing the Agent Well",
            "label": "Prompting",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/prompting",
            "content": "---\ntakeaway: Give one task, ask for a plan first\nshare: \"You reword the same request five times and keep getting the wrong code. The fix is not clever phrasing: it is four habits that make the agent build what you actually meant.\"\nrequires: [ai-agent, project-folder, rules-file]\nproduces: [prompt-template]\nteaches: [prompt-template]\nuses: [prompt, context, ai-coding-agent, model, rules-file]\n---\n{/* KEEP: lead-in = reader rewords a request, agent produces wrong or sprawling code, blames own phrasing. Reframe: not a magic phrase. Chapter delivers the four habits (context, one task, show an example, plan first) that make the agent build the intended thing. */}\n\nYou type a request, the agent writes two hundred lines, and half of it solves a problem you never asked about. You reword it, try again, and get a different wrong answer. The fix is not a magic phrase. This chapter gives you the four habits that make an agent build the thing you actually meant.\n\n{/* KEEP [pro]: an agent is not a keyword box; it writes what your words PLUS everything it can see add up to, so context is the high-leverage move, not clever wording. Show weak vs strong prompt as real artifacts. Cite Anthropic prompt engineering docs on first mention. Tie back to the rules file (auto-context). Soft pointer to the next chapter (the window) without deep-diving. */}\n\n## Context beats clever wording\n\nAn agent is not a search box waiting for the right keyword. It writes what your words plus everything it can see add up to, so the highest-leverage move is handing it context, not hunting for a magic phrase. [Anthropic's prompt engineering guidance](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/overview) says the same thing: be clear and direct, and give the model what it needs.\n\nThese two prompts ask for the same feature. Only one works.\n\n```\nMake the login better.\n```\n\n```\nOur login is in src/auth/. Users sign in with email and\npassword against the users table. Add a \"remember me\"\ncheckbox that keeps them signed in for 30 days. Match\nthe session code already in that folder.\n```\n\nThe rules file you set up earlier is context the agent reads on its own. A good prompt adds the rest: the files, the constraint, the definition of done. Keeping the right context in front of the agent is a skill of its own, and the next chapter is about the window it all has to fit inside.\n\n{/* KEEP: bundling 3 asks makes the agent do each half-well; give it ONE task, let it finish, then the next. Smaller finished steps are easier to check and undo. Rule-of-thumb callout: an \"and\" joining two jobs = two prompts. */}\n\n## One task per prompt\n\nAsk for three things in one message and the agent spreads its attention across all three, doing each one half-well. Give it one task, let it finish, then give the next. A small finished change is easier to check and easier to undo than one sprawling one.\n\n> **Rule of thumb:** If your prompt joins two jobs with an \"and,\" it is two prompts.\n\n```mermaid\n%% caption: Three asks in one prompt split the agent's attention; one task gets finished.\nflowchart TD\n  MULTI[Auth and styling and tests] --> HALF[Each done half-well]\n  ONE[One task] --> FULL[Finished, then the next]\n```\n\n{/* KEEP: fastest way to kill ambiguity = show what \"done\" looks like. Paste one example: an input and expected output, or the shape you want. A pattern the agent can match beats a paragraph describing it. Small artifact showing an example. */}\n\n## Show it an example\n\nThe fastest way to remove ambiguity is to show the agent what \"done\" looks like. Paste one concrete example: an input and the output you expect, or a sample of the shape you want. Something the agent can pattern-match against beats a paragraph describing the same thing.\n\n```\nGiven { \"email\": \"a@b.com\" }, the endpoint should return\n{ \"id\": 42, \"email\": \"a@b.com\" }. Match that shape.\n```\n\n{/* KEEP: make the agent produce a PLAN first (files it will touch, approach, unknowns), you approve, THEN it codes. Reading a 5-line plan is seconds; reviewing 200 lines of wrong code is an hour. Catch the misunderstanding for free. */}\n\n## Ask for a plan before code\n\nBefore the agent writes anything, ask it to lay out a plan: which files it will touch, the approach, and what it is unsure about. Reading a five-line plan takes seconds; reviewing two hundred lines of wrong code takes an hour. If the plan is wrong, you caught the misunderstanding for free, then approve it and let it build.\n\n```mermaid\n%% caption: A five-line plan catches the misunderstanding before the code exists.\nflowchart TD\n  PR([Your prompt]) --> PL[Agent returns a plan]\n  PL --> Q{Plan match your intent?}\n  Q -->|No, fix in one line| PR\n  Q -->|Yes, approve| CODE[Agent writes code]\n```\n\n{/* KEEP: a prompt that worked is an ASSET, not a throwaway. Save it as a prompt template: instructions fixed at top, one blank slot at the bottom for today's specifics. Build a small library your project trusts. Bold-first: prompt template. Ends with the copy-paste template + Do this now. */}\n\n## Keep the prompts that work\n\nA prompt that produced good work is an asset, not a throwaway line. Save it as a **prompt template**: the instructions fixed at the top, one blank slot at the bottom where you drop today's specifics. Over a few weeks you build a small library of prompts your project already trusts, and you stop rewriting the same setup every session.\n\n```mermaid\n%% caption: A saved template keeps the instructions fixed and swaps only today's specifics.\nflowchart LR\n  FIX[Fixed instructions] --> TMPL[Reusable template]\n  SLOT[Blank slot] --> TMPL\n  TODAY[Today's specifics] -->|fill the slot| SLOT\n  TMPL --> REUSE([Paste next session])\n```\n\nThis template bakes all four habits into one block you paste before any feature:\n\n```prompt\nAct as a senior engineer pairing with me. Before you\nwrite any code, do these in order:\n\n1. Restate the one task you think I am asking for. If it\n   is really two tasks, say so and stop.\n2. Read my rules file, the architecture map and\n   conventions in it, my spec, and the files this\n   touches. List what you found that constrains this.\n3. Propose a short plan: the files you will change, the\n   approach, and anything you are unsure about.\n4. Wait for my go-ahead. Only then write the code.\n\nIf the right move contradicts my spec, my map, or my\nconventions, stop and tell me why instead of diverging\nquietly.\n\nAlso show me one example of the result you expect, an\ninput and the output, so we agree on done first.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/prompting\n\nThe feature I want built:\n```\n\n**Do this now:** save the prompt above, paste it before your next feature, and make the agent plan before it writes a single line."
          },
          {
            "slug": "directing-visual-work",
            "title": "Building UI Is Directed Differently",
            "label": "Visual Work",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/directing-visual-work",
            "content": "---\ntakeaway: Show the agent the look, don't describe it\nshare: \"Logic you steer with words and a spec. Appearance you cannot, because the agent never sees the screen it builds. This chapter gives you the different loop that visual work needs: reference, render, adjust.\"\nrequires: [ai-agent, project-folder, running-app]\nproduces: [design-direction, ui-screen]\nteaches: [showing, visual-reference, design-direction]\nuses: [ai-coding-agent, prompt, spec]\n---\n{/* KEEP: lead-in = you can describe logic in words and check it against a spec, but the same approach on appearance returns something technically correct and visually wrong, because the agent is building a screen it cannot see. Chapter delivers the different loop visual work needs. */}\n\nYou can describe logic to your agent in words and check the result against a spec: given this input, return that output. Try the same with how something looks and you get back code that runs, compiles, and is visually wrong. The agent is building a screen it cannot see. This chapter gives you the different loop that visual work needs.\n\n{/* KEEP: concept = the agent writes UI code without ever seeing the rendered result, so a worded description (\"modern and clean\") gives it nothing concrete to match. Visual work is directed by showing, not telling. This is the mental model the rest of the chapter builds on. */}\n\n## The agent builds the screen blind\n\nWhen the agent writes interface code, it never sees what that code paints on the screen. It is arranging pieces by name, not by eye, the way you might wire a lamp you are not allowed to switch on.\n\nSo a worded brief like \"make it modern and clean\" hands it nothing to aim at. Those words map to a thousand different screens, and the agent picks one at random. Logic you steer by telling; appearance you steer by **showing**.\n\n{/* KEEP: step = paste a screenshot, a mockup, or a link to a page whose look you want. The agent matches something concrete far better than an adjective. Show the artifact: a reference-driven prompt vs a vague worded one. Do not duplicate designing-the-interface (that chapter is the design decision; this is the directing method). */}\n\n## Show a reference, not a paragraph\n\nThe fastest way to pin down a look is to hand the agent something it can copy. Paste a screenshot of a screen you like, a mockup, or a link to a page whose style you want, then tell it what to borrow.\n\nCompare the two briefs below. The first leaves the agent guessing; the second gives it a target.\n\n```\nBuild a pricing page. Make it clean and modern\nand professional.\n```\n\n```\nBuild a pricing page. Match the layout and spacing\nin the screenshot I pasted: three cards side by\nside, the middle one raised and highlighted. Use\nour brand colors, not the ones in the image.\n```\n\nA reference collapses a thousand possible screens down to one. An adjective does the opposite.\n\n{/* KEEP: step = UI is judged by eye, so the loop is render, look, adjust. Have the agent build it, view it (or have it screenshot the running page), give specific visual corrections, repeat until it looks right. Mermaid render->screenshot->adjust loop. Point BY TOPIC to visual-and-snapshot-tests (locking the look once right); do not deep-dive it here. */}\n\n## Iterate on the look, not the logic\n\nNo automated test can tell you whether a screen looks right; you judge it by eye. So the loop is short and visual: the agent builds, you look, you correct. Modern agents can screenshot the running page and read their own output, which closes the loop without you.\n\nGive corrections that are specific and visual, not vague: \"the heading is too close to the buttons, double the gap\" beats \"it feels off.\" Repeat until it matches, then lock that look in place so it cannot drift, which the chapter on visual and snapshot tests covers.\n\n```mermaid\n%% caption: Visual work loops build, screenshot, and specific fix until it matches.\nflowchart TD\n  REF[1. Reference] --> BUILD[2. Agent builds the UI]\n  BUILD --> SHOT[3. Screenshot the render]\n  SHOT --> LOOK{4. Matches?}\n  LOOK -->|No, one visual fix| BUILD\n  LOOK -->|Yes| LOCK([5. Lock the look])\n```\n\n{/* KEEP: step = commit to a concrete design direction up front (a reference, a palette, one named style) so the agent is not guessing taste every prompt. Point BY TOPIC to designing-the-interface (the Harden interface chapter) for the actual design decisions; here the rule is just \"decide the direction before you build, not per-prompt.\" Section ends with the copy-paste prompt: a reusable brief that makes the agent direct a screen from a reference (build, screenshot, compare, iterate on specific visual fixes until it matches). Senior frontend voice, expert content fixed at top, ONE append slot (My screen:) at bottom, lines <65 chars. Ends with Do this now. */}\n\n## Give a design direction, not \"make it nice\"\n\nIf every screen starts from \"make it nice,\" the agent guesses your taste fresh each time and nothing matches. Decide the direction once, before you build, and every screen inherits it.\n\nA usable direction is three concrete choices, not a mood:\n\n- One reference the whole app should resemble.\n- A small color palette, your brand colors named.\n- One named style you are committing to, not a shrug.\n\nWhat that direction should actually be, the layout, the flow, the interface decisions, is its own subject, covered when we design the interface. Here the rule is only that you pick it up front and hand it over, rather than let the agent invent taste per prompt.\n\nOnce you have a direction and a reference, this prompt runs the whole visual loop for you, from image to a screen that matches:\n\n```prompt\nAct as a senior frontend engineer. Read my rules file\nfirst: the architecture map says where UI code lives,\nand the conventions say how it is written. Reuse the\ncomponents and styles already in my codebase instead\nof starting a parallel set.\n\nI will paste a reference image and a short brief.\nDo this in order:\n\n1. Describe what you see in the reference: layout,\n   spacing, hierarchy, and color feel. Confirm you\n   have it right before building.\n2. Build the screen to match, using my palette,\n   not the colors in the image.\n3. Screenshot the running page and compare it to\n   the reference. List every visible difference.\n4. Fix the top difference, screenshot again, and\n   repeat until it matches. Stop and show me.\n\nKeep corrections visual and specific, never \"make\nit look better.\"\n\nThen record the direction, my palette, the reference,\nand the named style in my rules file, so every later\nscreen inherits it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/directing-visual-work\n\nMy screen:\n```\n\n**Do this now:** take a screen you want built and paste a reference image with the prompt above. Make the agent build, screenshot, and match it before you touch the words."
          },
          {
            "slug": "context-engineering",
            "title": "Keeping the Agent Smart",
            "label": "Context",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/context-engineering",
            "content": "---\ntakeaway: Feed only what's relevant\nshare: \"The agent goes dull in long sessions, not because the model is weak but because of what you let pile up in front of it. This is the core skill of working with AI: feed only what matters, point to files instead of pasting them, and reset before the thread rots.\"\nrequires: [ai-agent, project-folder, rules-file, spec-file, data-model]\nproduces: [session-summary]\nteaches: [context-window, context-engineering, compaction]\nglosses: [token]\nuses: [context, model, token, ai-coding-agent, prompt, api-key, spec, requirement]\n---\n{/* KEEP: lead-in = the agent starts sharp and goes dull in long sessions; the cause is almost never the model, it is what you let pile up in front of it. This chapter = the core skill: managing what the agent sees. */}\n\nThe agent starts sharp and slowly goes dull in a long session. It forgets what you decided an hour ago, contradicts itself, edits the wrong file.\n\nThe cause is almost never the model. It is what you have let pile up in front of it. This chapter teaches the one skill that most separates people who get real work from AI: managing what the agent sees.\n\n{/* KEEP: concept = the context window is a fixed budget; files, your messages, its replies all count against it; when it fills, detail falls out and answers get fuzzy. More is not better. Name the discipline (context engineering) + Fowler cite on first mention. Cross-ref the memory file as ONE slice, do not re-teach it. Bold-first: context window, context engineering. */}\n\n## The context window is finite\n\nThe **context window** is the fixed amount of text the agent can hold at once. Your files, your messages, and its own replies all count against one budget. When it fills, the oldest details fall out or the whole thing goes fuzzy.\n\nMore is not better. A window stuffed with irrelevant history produces worse answers, not richer ones. Managing that budget on purpose is called **context engineering**, and it is what this whole chapter is about. Martin Fowler has a good primer, [Context Engineering for Coding Agents](https://martinfowler.com/articles/exploring-gen-ai/context-engineering-coding-agents.html).\n\nThe always-loaded memory file you set up earlier is one small, permanent slice of that budget. Everything else is what you hand the agent per task.\n\n{/* KEEP: feed only what's relevant = the takeaway. Give it the two files this task touches, not the whole repo; the one error, not an hour of logs. Real artifact: before/after of a bloated vs focused hand-off. One rule-of-thumb callout. */}\n\n## Feed only what's relevant\n\nHand the agent the two files this task touches, not the whole codebase. Give it the one error message, not the last hour of logs. The narrower the input, the sharper the output.\n\n```\nBLOATED: here is my whole codebase [40 files],\nplus yesterday's full chat and the API docs.\nNow fix the login bug.\n\nFOCUSED: the login bug is in auth/session.ts.\nHere is that file and the error. Fix the\ntoken refresh.\n```\n\n> **Rule of thumb:** if you would not put a document in front of a new hire to solve this exact task, do not paste it to the agent either.\n\n{/* KEEP: the money angle on the same lever. Every token the agent reads and writes is metered: paid per-token on an API key, or counted against the usage cap on a flat plan. So a bloated window is not just duller, it is more expensive and it rate-limits you sooner. Same fix as the rest of the chapter (lean input, reset, summarize), so frame it as a second reason to do what you already should, not a new discipline. Keep short. */}\n\n## A bloated session costs real money\n\nThere is a second reason to keep the window lean, and it is money. Models count text in **tokens**, chunks of roughly four characters. Every token the agent reads or writes is metered: you pay per token on an API key, or burn against the usage cap on a flat plan.\n\nSo a window stuffed with your whole repo and yesterday's chat is not just a duller answer. It is a bigger bill and a cap you hit hours sooner.\n\nThe fix is the one you already have. Lean input, a reset when the thread drifts, a summary before you continue: each of those buys you sharper answers and a smaller bill at the same time. You are not learning a new discipline for cost, you are getting paid twice for the one you already keep.\n\n{/* KEEP: point to the spec, don't repeat it = agents read files themselves, so name the file and let it open what it needs instead of pasting 500 lines. Keeps the window lean AND the agent reads the current version, not a stale paste. Cross-ref the spec chapter by topic. */}\n\n## Point to the spec, don't repeat it\n\nYour agent can open files on its own. So do not paste a 500-line spec into the chat. Tell it where the file lives and which part to read: \"the spec is in docs/spec.md, read the billing section.\"\n\nThis keeps the window lean. It also means the agent reads the current spec every time, instead of a copy that went stale the moment you pasted it. The same holds for the requirements and data model you wrote in the planning part: point, do not repaste.\n\n{/* KEEP: reset when the thread drifts = after a long rabbit hole the window is full of dead ends the agent keeps tripping over; a fresh session with a tight prompt beats fighting a poisoned one. This is hygiene, not failure. */}\n\n## Reset when the thread drifts\n\nWhen a session has wandered through three failed approaches, its window is now full of dead ends the agent keeps tripping over. It will keep re-suggesting the thing that already did not work.\n\nStart a fresh session. A clean window with a tight prompt almost always beats fighting a long one that is carrying every mistake it made. This is hygiene, not failure.\n\n{/* KEEP: the counterweight to the lead-in's \"the cause is almost never the model\", added July 2026 because nothing in Build told the reader that switching models is a lever at all. Two beats: when a clean window does not fix it, change the model before rewriting the prompt again; and models are not interchangeable, cheap and fast for boilerplate, strong reasoning for architecture and hard bugs, switchable in settings mid-project. Keep it to two short paragraphs so it never competes with the reset. */}\n\n## When a fresh window does not help, change the model\n\nA reset fixes most of it. When it does not, when the agent fails the same task again in a clean window, change the model before you rewrite the prompt a fourth time.\n\nModels are not interchangeable. A cheap fast one is right for boilerplate and repetitive edits, and the strong reasoning one earns its price on architecture and the bugs you cannot see. Most agents let you switch in their settings, mid-project.\n\n{/* KEEP: summarize before continuing = when a long task is going WELL but the window fills, don't just reset and lose the thread. Have the agent write a short summary (done/next/decisions), start fresh, paste it. Real artifact: the summary snippet. Name compaction + link Claude Code. */}\n\n## Summarize before continuing\n\nWhen a long task is going well but the window is filling, do not just reset and lose the thread. Ask the agent to write a short summary first, then start fresh and hand that summary back to it.\n\n```\n## Where we are\n- Done: login + session refresh, tests pass.\n- Next: password reset email.\n- Decisions: tokens in httpOnly cookies,\n  15-min expiry. Reset link valid 1 hour.\n```\n\n```mermaid\n%% caption: When the window fills, reset a stuck thread or summarize a good one.\nflowchart TD\n  Q{Window filling. Going well?}\n  Q -->|No, chasing dead ends| RESET[Start fresh session]\n  Q -->|Yes, on track| SUM[Summarize the thread]\n  SUM --> FRESH[Continue in fresh window]\n```\n\nSome tools do this for you: [Claude Code](https://claude.com/claude-code) calls it **compaction**. This prompt produces a clean hand-off you can carry into a new session:\n\n```prompt\nAct as a senior engineer closing out a long\nworking session. Summarize this thread for a\nfresh start so no context is lost. Include:\nwhat we set out to do, what is done and\nverified, what is left, and every decision\nwith its reason. Name the exact files and\nfunctions touched.\n\nPoint at my rules file, my spec, and my\narchitecture map by path instead of repeating\nwhat they already say; the next session can\nopen them. Flag any decision we made here that\ncontradicts one of those, and any that is\ndurable enough to belong in an ADR or the\nchangelog.\n\nKeep it under 20 lines, facts only, no\nnarration. I will paste this into a new session.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/context-engineering\n\nMy task and the files that matter:\n```\n\n**Do this now:** next time a session runs long, stop, ask the agent for that summary, and continue in a fresh window instead of pushing through the bloated one."
          },
          {
            "slug": "working-in-small-steps",
            "title": "Working in Small Steps",
            "label": "Increments",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/working-in-small-steps",
            "content": "---\ntakeaway: Ship in small slices\nshare: \"One big AI-written change breaks in ways you cannot untangle. Work in small slices instead: one change at a time, committed after each, so rollback is trivial and the culprit is obvious.\"\nrequires: [ai-agent, project-folder, running-app, git-repo, baseline-commit]\nproduces: [first-feature]\nteaches: [green, big-bang]\nglosses: [diff]\nuses: [slice, commit, diff, branch, main-branch, merge]\n---\n{/* KEEP: lead-in = you let the agent write a whole feature in one shot, it half-works, and the change is too big to read or undo. This chapter: build in small slices, one working change at a time. */}\n\nYou let your agent write a whole feature in one shot, and it half-works. Now the change is too big to read, and you cannot tell which part broke what. This chapter fixes that at the source: build in small slices, one working change at a time, so nothing ever grows too big to understand or undo.\n\n{/* KEEP: concept = define slice (one thin complete change, does one visible thing, leaves app running); the big-bang is the opposite and loses because a large broken change is ten things braided together. Bold-first: slice. Rule-of-thumb callout distinct from version-control's. */}\n\n## Ship in slices, never big-bang\n\nA **slice** is one thin, complete change: it does a single visible thing and leaves the app running. The opposite is the big-bang, one huge change that adds everything at once and only works if every part is right.\n\nThe big-bang loses every time. When one large change misbehaves, you are untangling ten things braided together. Cut the same work into slices and each piece is small enough to read and trust before the next.\n\n> **Rule of thumb:** if you cannot name the one thing a change does, it is more than one change.\n\n```mermaid\n%% caption: The big-bang is all-or-nothing; slices each work before the next begins.\nflowchart TD\n  subgraph BIG[Big-bang]\n    B1[Ten changes at once] --> B2{All right?}\n    B2 -->|No| B3[Whole thing breaks]\n  end\n  subgraph SLICE[In slices]\n    S1[Slice 1 works] --> S2[Slice 2 works]\n  end\n```\n\n{/* KEEP: step = cut along features not layers; a good slice reaches from what the user sees to where data lives and does one real thing end to end. Artifact = one feature (login) as a sequence of small commits, each runnable. */}\n\n## One working change at a time\n\nCut along features, not layers. A good slice reaches from what the user sees down to where data is stored and does one real thing, so you can run it and watch it work. A bad slice builds half of everything and runs nothing.\n\nTake a login feature. Instead of \"build login,\" your agent works it as a sequence of small changes, each one runnable and each its own commit:\n\n```\nfeat: show the login form (no logic yet)\nfeat: accept email + password, log to console\nfeat: verify credentials against the database\nfeat: start a session on success\nfeat: show an error message on failure\n```\n\n{/* KEEP: step = define green (it works: app runs, slice does its job); commit at exactly that moment, never on red (code that does not run). References the safety net from version control, does not re-teach committing. Bold-first: green. */}\n\n## Commit after each green step\n\n**Green** means it works: the app runs and the new slice does what it should. Commit at exactly that moment, never before. You already set your agent to save a snapshot after every working step; this is the discipline that makes that safety net worth having, one green slice, one commit.\n\nA commit on red, code that does not run, poisons your history. Now a \"saved\" version is broken, and it is useless as a fallback. Only green earns a commit.\n\n```mermaid\n%% caption: Commit only on green; a red commit poisons your history.\nflowchart TD\n  S[Build one slice] --> G{Green?}\n  G -->|No, red| F[Fix it, no commit]\n  F --> S\n  G -->|Yes, green| C[Commit this slice]\n  C --> S\n```\n\n{/* KEEP: the branch beat, added July 2026. Version control already had the reader tell the agent \"put each new feature on its own branch\", and the review chapter talks about merging, but the Build loop never put a feature on a branch, so \"merge\" had no referent in the reader's actual working day. Keep all three: every slice of one feature goes on that one feature branch, it merges back only after the whole feature works and has been read, and main stays runnable the entire time. */}\n\n## Keep the whole feature on one branch\n\nThose slices do not land straight on your working version. All of them go on that feature's own branch, the private copy your agent splits off for it, one commit per green slice.\n\nThe branch merges back into main only when the whole feature works and you have read what it does. Until then main stays exactly as it was: runnable, and untouched by a feature that is half built.\n\n{/* KEEP: step = with every commit one green slice, rollback is surgical (undo one commit, not an afternoon) and the culprit is one small diff, obvious on sight. Cross-ref the later bug-hunting chapter by topic, not number. */}\n\n## Small steps make going back easy\n\nWhen every commit is one green slice, going back is surgical. A slice breaks something, you undo that one commit, and you are on solid ground again instead of unwinding an afternoon.\n\nIt is also how you find the culprit fast. With small steps, the change that caused a bug is one small **diff**, the handful of lines added and removed, obvious on sight. With a big-bang commit, the cause is buried in hundreds of lines. The later chapter on hunting down which change caused a bug turns this into a method.\n\n{/* KEEP: prompt (senior-engineer voice, fixed content + one append slot \"The feature to slice up:\"). Agent breaks a feature into ordered vertical slices, each runnable, commit after each. Do this now = paste with next feature, build slice by slice. */}\n\n## Hand the slicing to your agent\n\nGive it a feature and let it plan the slices for you:\n\n```prompt\nAct as a senior engineer breaking work into small,\nsafe slices. First read my spec and the architecture\nmap in my rules file, so every slice lands where my\nstructure and conventions say it belongs.\n\nTake the feature below and return an ordered list of\nvertical slices. Rules:\n- Each slice does ONE visible thing end to end and\n  leaves the app runnable, never a half-built layer.\n  Too big to read in one sitting means split again.\n- Order them smallest and safest first, each one\n  building on the last.\n- After each slice, stop, confirm it works, and\n  commit it with a short clear message before you\n  start the next.\n- Put the whole feature on its own branch, and\n  merge it back only once every slice is in and\n  working, then add a line to my CHANGELOG.\n- If a slice needs something my spec or my map does\n  not cover, say so first, do not invent it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/working-in-small-steps\n\nThe feature to slice up:\n```\n\n**Do this now:** paste the prompt above with your next feature, and build it slice by slice instead of all at once."
          },
          {
            "slug": "guardrails",
            "title": "Catching Bugs Early",
            "label": "Guardrails",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/guardrails",
            "content": "---\ntakeaway: Automate the quality checks\nshare: 'The agent writes code that looks right and runs, until a typo or a wrong type hides a bug you cannot see by eye. Automated checks catch whole classes of mistakes before they ever reach you.'\nrequires: [ai-agent, project-folder, stack-chosen, rules-file]\nproduces: [quality-gate]\nteaches: [linter, type-checker, static-analysis]\nuses: [formatter, stack, secret, command, rules-file, git-hook, ai-coding-agent]\n---\n{/* KEEP: lead-in = the agent's code looks right and runs, but small mistakes (typo, wrong type, unused variable hiding a bug) slip past because you cannot eye every line. This chapter sets up the automated checks that catch whole classes of mistakes before they reach you. Distinct from conventions-and-naming (that was consistent STYLE); this is bug-catching. */}\n\nThe agent writes code that looks right and runs, right up until a typo, a value of the wrong type, or an unused variable quietly hides a real bug. It generates faster than you can read, and you cannot eye every line. This chapter sets up the automated checks that catch whole classes of mistakes for you, before they ever reach a user.\n\n{/* KEEP: you met the formatter + linter for consistent STYLE; the linter earns its keep again here catching likely BUGS (unused variable, unreachable code, a comparison always true). Machines are tireless and consistent where your eyes glaze over. Bold-first: linter (as bug-catcher). Reference conventions chapter by topic, don't re-teach. */}\n\n## Let the linter catch the small bugs\n\nYou already set up a formatter and a [**linter**](https://eslint.org) to keep the code in one consistent style. The linter does a second job that matters more here: it flags likely mistakes. An unused variable, an unreachable line, a comparison that is always true, the small errors that read as fine but signal a real bug.\n\nThese are exactly the things your eyes glaze over on line four hundred of code you did not write. A machine never glazes over.\n\n{/* KEEP: THE big one. a type checker catches a whole class of errors before the code runs: passing text where a number is expected, calling something that might not exist. Bold-first: type checker. Link TypeScript as the common one. It turns a crash-in-production into a red squiggle now. */}\n\n## Turn on type checking\n\nThe single highest-value check is a **type checker**. It knows what shape each value is meant to be: a number, a name, a user. Then it flags the moment you use one wrong, like passing text where a number belongs, or reading a field that might not exist.\n\nThat catches a whole class of bugs before the code runs at all. The common one is [TypeScript](https://www.typescriptlang.org); most stacks have an equivalent. It turns a crash a user would have hit into a red underline you fix in seconds.\n\n{/* KEEP: static analysis = deeper automated scans for risky patterns, security smells, dead code, beyond style + types. Bold-first: static analysis. Optional-but-worth-it; one tool, runs in CI or on save. Keep short, it is the third layer. */}\n\n## Add static analysis for the deeper risks\n\nPast style and types, **static analysis** reads your code for risky patterns without running it. It finds a secret left in the source, an input used without checking, or a whole file nobody calls anymore.\n\nYou do not need it on day one, but one tool wired in early keeps a class of security and dead-code problems from ever accumulating.\n\n{/* KEEP: the move that makes all of it work = the agent runs the checks EVERY time, before it says done, not you remembering. Show the real artifact: the check commands + the standing rule. A check you run sometimes is a check you do not have. BOTH LAYERS MUST BE NAMED (added July 2026): the rules file is an instruction the agent can skip, the git hook the reader left empty back in version control is the gate it cannot skip. Say which is which, and keep the hook line in the prompt. */}\n\n## Make the agent run them every time\n\nChecks you run when you remember are checks you do not really have. The move is to make the agent run them itself, every time, before it declares a task done:\n\n```\n# The agent runs these before saying \"done\":\nformat   ->  prettier --write .\nlint     ->  eslint .\ntypes    ->  tsc --noEmit\n```\n\n```mermaid\n%% caption: No task is done until format, lint, and type checks all pass.\nflowchart TD\n  W[1. Agent writes code] --> FMT[2. Format]\n  FMT --> LINT[3. Lint]\n  LINT --> TYPES[4. Type check]\n  TYPES --> Q{5. All pass?}\n  Q -->|No, fix| W\n  Q -->|Yes| DONE([6. Task done])\n```\n\nWrite that into the rules file the agent reads every session, as a hard line: no task is finished until format, lint, and type checks pass.\n\nThen back it with the git hook you left empty when you set up version control. A rules file is an instruction your agent can drop under pressure; a hook is a gate that runs whether anyone remembered or not. Put the same commands in both and you are covered twice: the agent runs them before it says done, and nothing lands if it did not.\n\nThis prompt wires the checks and the standing rule for your stack:\n\n```prompt\nAct as a senior engineer setting up my quality gate.\nRead my rules file first, Conventions section\nincluded, and configure tools that enforce what is\nalready written there rather than a different house\nstyle.\n\nFor my stack, set up a formatter, a linter, and a\ntype checker, plus one static-analysis tool if it\nfits. Give me the exact command for each.\n\nThen add a standing rule to my rules file: no task\nis done until all of them pass, and you run them\nyourself before saying so. Wire the same commands\ninto my commit hook, so they still run on anything\nthat slips past you.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/guardrails\n\nMy stack:\n```\n\n**Do this now:** paste the prompt, wire the checks for your stack, and add the \"not done until they pass\" rule so your agent runs them on every change."
          },
          {
            "slug": "reviewing-the-agents-code",
            "title": "Checking the Agent's Work",
            "label": "Code Review",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/build/reviewing-the-agents-code",
            "content": "---\ntakeaway: Never ship unread code\nshare: \"Your agent writes most of the code now, faster than you can read it. This chapter makes review the gate every change passes: read the real diff, run four checks, and never accept a line you cannot explain.\"\nrequires: [ai-agent, project-folder, git-repo, first-feature]\nproduces: [review-habit]\nteaches: [diff, code-review]\nuses: [ai-coding-agent, merge, dependency, package]\n---\n{/* KEEP: lead-in = the Problem. Agent writes most of the code, faster than you can read; the summary is not the code; review is the first time a human truly looks. This chapter makes that look happen every time, before the change lands. */}\n\nYour agent writes most of the code now, and it writes it faster than you can read. The temptation is to skim its summary, see the app still runs, and move on. But that summary is a claim, not the code, and review is the first time a human truly looks at what shipped. This chapter makes that look happen every time, before the change lands.\n\n{/* KEEP: Concept = the agent's summary is a claim, not evidence; open the actual diff and read the changed lines yourself. Bold-first **diff** (glossed: lines added and removed) and **code review**. Read the whole thing; the lines you skip hide the bug you can't explain later. */}\n\n## Read what the agent wrote\n\nThe agent hands you a confident paragraph describing what it did. Open the **diff**, the exact lines added and removed, and read them against what you actually asked for. That is **code review**: you deciding whether this change earns a place in your codebase, from the real evidence and not the sales pitch.\n\nRead the whole change, not just the parts you follow at a glance. The lines you skip are exactly where the bug you cannot explain later is hiding.\n\n{/* KEEP: Step = review even solo. On a team a second engineer reviews before merge; alone that engineer is you, and skipping it doesn't make it safe, it means nobody looked. Fresh eyes catch what the author can't; read it like a stranger wrote it, or hand it to a second reviewer agent (nod to builder/reviewer split, separation of blind spots). Watch out callout on silent extra scope. */}\n\n## Review even when solo\n\nOn a team, a second engineer reads the change before anything merges. Alone with an agent, that second engineer is you, and skipping the step does not make the code safe, it just means nobody looked.\n\nFresh eyes catch what the author cannot see, so give yourself them: read the diff as if a stranger wrote it. Better, hand it to a second agent whose only job is to review, the same builder-and-reviewer split you use elsewhere, so a different mind grades the work.\n\n> **Watch out:** the change that also quietly renamed, restructured, or \"cleaned up\" something you never asked about is the one that breaks a working feature. Extra scope is not a bonus, it is unreviewed risk.\n\n```mermaid\n%% caption: A second set of eyes, yours or an agent's, grades the change before merge.\nflowchart LR\n  BUILD[Builder agent] -->|change| REV[You or reviewer agent]\n  REV -->|passes| MERGE([Merge])\n  REV -->|fails| BUILD\n```\n\n{/* KEEP: Step = the real artifact, a fixed checklist run on every diff. Four checks: Intent, Scope, Security, Bugs. You're not re-deriving the code, you're running it past the same questions each time. Fenced checklist is the copyable thing. The Scope check carries the dependency question (added July 2026) so the count and its diagram stay at four; the paragraph under it must keep the reason: agents add packages you do not need and sometimes name ones that do not exist, which attackers register. */}\n\n## Four checks on every diff\n\nYou are not re-deriving the code from scratch, you are running it past a fixed set of questions. The same four, every diff:\n\n```\nReview checklist, run on every diff:\n[ ] Intent: does it do exactly what I asked,\n    no more and no less?\n[ ] Scope: did it touch files or behavior I\n    never mentioned, or add a package I did\n    not ask for?\n[ ] Security: is every secret, input, and login\n    path handled with care?\n[ ] Bugs: any obvious error, missed edge case,\n    or dead code left behind?\n```\n\nTake the package question seriously. Agents pull in libraries you do not need, and they sometimes name one that does not exist at all. Attackers now exploit that: they register the invented name and fill it with their own code. Before you accept a new dependency, have the agent show you its official page and the date of its last release.\n\n```mermaid\n%% caption: Every diff passes the same four gates before you accept it.\nflowchart TD\n  D([Open the diff]) --> I{Intent right?}\n  I -->|No| FIX[Send back]\n  I -->|Yes| SC{Scope creep?}\n  SC -->|Yes| FIX\n  SC -->|No| SE{Security handled?}\n  SE -->|No| FIX\n  SE -->|Yes| B{Bugs or dead code?}\n  B -->|Yes| FIX\n  B -->|No| A([Accept the change])\n```\n\n{/* KEEP: the \"majority problem\" (Osmani's term, merged into our review lens): an agent predicts the most STATISTICALLY common solution, which is the average of its training, often a solid default, sometimes an outdated pattern, a heavier dependency than needed, or a generic approach blind to your specific case. It passes the four checks because it WORKS; it is just not the BEST fit. The check: ask whether this is the reflex default or the right call here, and when unsure make the agent show alternatives + its reasoning. The reason, not the popularity, is the signal. Rule-of-thumb callout. Keep short. */}\n\n## The common answer is not always the right one\n\nThe four checks catch code that is wrong. They miss code that is merely average. An agent predicts the most common solution, and most common is not the same as most appropriate.\n\nIts answer is the average of everything it read. Sometimes that is a solid default. Sometimes it is an outdated choice, a heavier dependency than you need, or a generic approach blind to what makes your case different.\n\nNone of that trips the checklist, because the code runs. It is just not the best code for you.\n\nSo add one question to the read: is this the choice everyone reaches for by reflex, or the right one here? When you are not sure, ask the agent for two or three alternatives and why it picked this one.\n\n> **Rule of thumb:** \"everyone uses this\" is how the agent defaults, not why it fits you. Judge the reasoning it gives, not the popularity of the answer.\n\n{/* KEEP: COMMENTS = comment the WHY and the non-obvious decision, not the obvious what. Over-commenting is noise the agent loves to add (delete `// increment the counter`); a surprising choice gets a short why. Comments are documentation that lives next to the code, re-read next session. Reconciled: refactoring.mdx only says \"don't add comments\" mid-refactor; the-pieces-of-an-app uses \"comment\" as example data, not code comments. No overlap. */}\n\n## Comments should explain why, not what\n\nWhile you read the diff, watch how it comments. The agent loves to narrate the obvious (`// increment the counter` above `count++`), and that noise buries the lines that matter. What earns its place is a comment where a choice is surprising: why this retry limit, why this workaround, the reason the code itself cannot show. A comment is documentation that lives next to the code, and the agent re-reads it next session, so keep the why and cut the what.\n\n{/* KEEP: Step + Action = never ship what you don't understand. A line you can't explain is a liability with a green checkmark; make the agent teach you until you could defend it. Copy-paste prompt: senior reviewer voice, checks diff against intent + security + bugs, ONE append slot at bottom. Do this now nods to carrying a reviewed running app into hardening, no re-teaching. */}\n\n## Never ship what you don't understand\n\nA change you cannot explain is one you cannot maintain, debug, or trust. If a line does what you asked but you have no idea how, that is not done, it is a liability with a green checkmark.\n\nSo make the agent teach you: have it walk you through anything unclear until you could defend it yourself. Then run the review as one command:\n\n```prompt\nAct as a senior engineer reviewing a colleague's\nchange before it merges. First read my standing\ncontext: my rules file, my architecture map, my\nconventions, and my spec. Then read the actual\ndiff below, not the summary of it, and check it\nagainst three things: intent (does it do exactly\nwhat was asked, nothing extra), security (secrets,\nlogin, and unchecked user input), and bugs (broken\nlogic, missed edge cases, dead or duplicated code).\nName anything that contradicts a decision those\nfiles already record, and say which one.\nList every issue by severity, blockers first.\nExplain anything I would likely not understand in\nplain words. If it is clean, say so plainly, do\nnot pad. Do not rewrite the code, only review it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/build/reviewing-the-agents-code\n\nThe task I asked for and the diff to review:\n```\n\n**Do this now:** take the last change your agent made, open its diff, and run it through the four checks and the prompt before you accept it. A reviewed, running app is what you carry into hardening it for real users."
          }
        ]
      },
      {
        "id": "read",
        "title": "Inspect the Code Your Agent Writes",
        "chapters": [
          {
            "slug": "reading-code",
            "title": "Looking Under the Hood",
            "label": "Reading Code",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/reading-code",
            "content": "---\ntakeaway: Read code only when it pays off\nshare: \"You let your AI write the code, but sometimes you want to look yourself. This chapter reframes reading code as an optional, occasional skill: the few moments it pays, the plain vocabulary, and how to trace one path instead of a whole file.\"\nrequires: [project-folder, ai-agent, editor]\nproduces: []\nteaches: [file, function, variable, class, object]\nuses: [ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = this whole Read part is OPTIONAL, for readers (often juniors, or curious non-technical builders) who want to look under the hood and judge quality; someone who just wants to ship can skip it. Say it plainly here, do not oversell. Reframe reading as an occasional skill, not a job. */}\n\nYou let your AI write the code, and most days you never open a file. But sometimes you want to look yourself: to settle a stubborn bug, to check something sensitive, or to judge whether the work is any good.\n\nThis part is optional. If you just want to ship, skip it with a clear conscience. If you are curious, or newer to this and want to learn, it hands you enough to look under the hood without turning reading code into a second job.\n\n{/* KEEP: three moments reading pays: a bug the agent keeps missing, a sensitive area (payments, auth, user data), and judging quality. Reading is a tool you reach for, not a duty. */}\n\n## You don't have to read code, but you can\n\nReading is a tool you pick up for a reason, not a duty you owe every file. Three moments make it worth the minutes:\n\n- **A bug the agent keeps missing.** When the agent circles the same fix and never lands it, your own eyes on the code break the loop.\n- **A sensitive area.** Payments, login, and anything touching user data are worth reading before you trust them, because the cost of a quiet mistake is high.\n- **Judging quality.** When you want to know if the work is solid or just working, you have to look.\n\nOutside those, let the agent write and move on.\n\n{/* KEEP: plain vocab, bold-first: file, function, variable, class, object. Keep it plain, no jargon dump. */}\n\n## What code is made of\n\nCode is built from a handful of parts, and naming them is most of the battle:\n\n- A **file** is one document of code, like one page in a binder.\n- A **function** is a named block that does one job when you call it, like `sendEmail`.\n- A **variable** is a labeled box holding one value, like `total = 42`.\n- A **class** is a blueprint for a kind of thing, say a `User`.\n- An **object** is one real thing built from that blueprint, one actual user.\n\nThat is enough vocabulary to follow along. You are recognizing shapes, not memorizing a language.\n\n{/* KEEP: trace ONE action through the few functions it touches, ignore the rest. Do not read a file top to bottom. Diagram of the path. */}\n\n## Follow one path, not the whole file\n\nNever read a file top to bottom. Pick one action, a user logging in, and follow only the functions it actually touches:\n\n1. **Start where it begins:** the login button or the request that fires.\n2. **Step into each function it calls,** one at a time, ignoring everything around them.\n3. **Stop when you reach the answer,** the check that passed or the value that was wrong.\n\nEverything else on the page is noise for this question. You are tracing one thread through the cloth, not reading the whole cloth.\n\n```mermaid\n%% caption: Trace one action through only the functions it touches, and stop at the answer.\nflowchart LR\n  A([Login click]) --> B[checkPassword]\n  B --> C[findUser]\n  C --> D{Match?}\n  D -->|Yes| E([Logged in])\n  D -->|No| F([Rejected])\n```\n\n{/* KEEP: the agent is your reading guide: have it explain any file or line in plain words, at your level. This is the payoff, the prompt + Do this now. */}\n\n## Let the agent be your guide\n\nYou do not read alone. The same agent that wrote the code will explain any file, function, or single line in plain words, pitched at exactly how much you already know. Ask it to walk you through the one path you care about, and to stop and define any term you do not recognize.\n\n```prompt\nAct as a senior engineer reading code beside a curious\nteammate who is still learning. Check my architecture\nmap and my module boundaries first, so you can tell me\nwhere this file sits in my own project.\n\nWalk me through the file below by following ONE path:\nthe action I name, step by step through only the\nfunctions it touches. Skip the rest.\n\nFor each step, say in one plain sentence what it does and\nwhy. Define any term I would not know the first time it\nappears. Do not assume I have read code before. If the\npath crosses a module boundary or breaks my conventions,\nsay so in plain words too.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/reading-code\n\nThe file and the action I want to follow:\n```\n\n**Do this now:** open one file your agent wrote, name a single action in it, and paste the prompt so the agent walks you down that one path in plain words."
          },
          {
            "slug": "reading-diffs",
            "title": "Read the Change, Not the Whole File",
            "label": "Diffs",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/reading-diffs",
            "content": "---\ntakeaway: Read the diff before you accept it\nshare: \"Most of the time you are not reading a whole file, you are looking at a change and deciding whether to accept it. This chapter gets you reading that red-and-green view so you can judge a change before you click accept.\"\nrequires: [project-folder, ai-agent, editor]\nproduces: [review-habit]\nteaches: [diff]\nuses: [file, function, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = most of the time you are NOT reading a whole file, you are looking at a CHANGE: the agent proposes an edit, shows red and green lines, asks you to accept. That view is where you actually judge code. This chapter gets you reading it. Optional-part framing carries over, do not re-sell. */}\n\nMost of the time you are not reading a whole file. You are looking at a change: the agent proposes an edit, shows you red lines and green lines, and asks you to accept. That view is where you actually decide whether code is any good, and it has its own way of being read. This chapter gets you reading it.\n\n{/* KEEP: Concept. A diff is the view of what a change adds and removes, not the whole file. It is the moment you approve or reject the agent's work, so it is the highest-value thing to be able to read. Bold-first: diff. */}\n\n## The diff is where you actually look at code\n\nA **diff** is the view of what a change adds and removes, not the whole file. When the agent finishes an edit, this is what it shows you: the few lines that moved, not the hundreds that stayed.\n\nIt is also the exact moment you approve or reject the work. That makes the diff the highest-value thing to be able to read, more than any full file, because it is where your decision actually happens.\n\n{/* KEEP: Step. How to read it: minus lines removed, plus lines added, unchanged lines around them for context. What changed vs what stayed the same. Show a small diff artifact with +/- lines. */}\n\n## Red is removed, green is added\n\nThe diff uses two marks and nothing more. A line with a minus in front, shown red, was removed. A line with a plus in front, shown green, was added. The plain lines around them did not change, and they are only there to give you context.\n\nHere is a small one, changing how a total is calculated:\n\n```diff\n  function orderTotal(items) {\n-   return items.length * 10;\n+   return items.reduce((sum, item) => sum + item.price, 0);\n  }\n```\n\nRead it as one thought: the old line charged a flat ten per item, the new line adds up each item's real price. You judge the change by comparing the red to the green, not by rereading the whole function.\n\n{/* KEEP: Step. A huge sprawling change is hard to judge; a small focused one you can actually read. Ask the agent for focused changes. Refer to small-steps / code-quality by TOPIC, not number. */}\n\n## A small, focused diff is easier to trust\n\nA change that touches thirty files at once is not something you can honestly read, so you end up accepting it on faith. A change that touches one thing is something you can actually check. Smaller is safer here for a plain reason:\n\n- **You can hold it in your head.** A few lines fit; thirty files do not.\n- **You can spot the odd line.** In a small diff, the one wrong change stands out.\n- **You can undo it cleanly.** A focused change is easy to reverse if it turns out bad.\n\nSo ask the agent to work in small, focused changes, the same one-thing-at-a-time habit the chapter on building in small steps pushes. You are not being difficult, you are keeping the diff readable.\n\n{/* KEEP: Step. Judge the change WHEN you accept it: scan the diff before you click accept, ask the agent to explain any line you do not understand. This is exactly where \"is it any good\" gets decided. Prompt + Do this now. */}\n\n## Judge the change when you accept it\n\nThe accept button is a decision, not a formality. Before you click it, scan the red and green once: does the change match what you asked for, and is anything there that should not be? If a line makes no sense to you, that is not a reason to wave it through, it is a reason to ask.\n\nThe agent that wrote the diff will also explain any line in it, in plain words, at your level.\n\n```prompt\nAct as a senior engineer reviewing a change beside a\nteammate who is still learning. Walk me through the diff\nbelow: for each removed and added line, say in one plain\nsentence what changed and why it matters.\n\nCheck it against my rules file, my conventions, and my\narchitecture map, and flag any line that breaks them.\nThen tell me the one thing I should check before I accept\nit, and anything else that looks risky or out of place.\nDefine any term I would not know the first time it appears.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/reading-diffs\n\nThe diff I want to review:\n```\n\n**Do this now:** the next time your agent proposes an edit, read the red and green before you accept. Paste the prompt to have it walk you through any line you are unsure about."
          },
          {
            "slug": "files-and-formats",
            "title": "What Each One Is For",
            "label": "Files",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/files-and-formats",
            "content": "---\ntakeaway: Know what each file type is for\nshare: \"You open the project and see dozens of files with different extensions. This chapter gives you the quick read: which files are code, which hold data, which carry settings and secrets, and which you only need to recognize.\"\nrequires: [project-folder, ai-agent, editor]\nproduces: []\nteaches: [json, yaml, config, environment-variable, dotenv-file, markdown]\nuses: [secret, api-key, database, lockfile, package-manager, repo, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the project is a wall of files with different extensions, most you never touch; this chapter gives the quick read to glance at any file and know what it is for. Optional-part framing carries over, do not re-sell. */}\n\nYou open the project your agent built and the sidebar is a wall of files. A `.ts` here, a `.json` there, a `.env`, a `README.md`, a `Dockerfile` with no extension at all. Most of them you will never edit by hand. This chapter gives you the quick read: glance at any file and know what it is for, and whether it is yours to touch.\n\n{/* KEEP: four kinds of files, bold-first: code, config, data, not yours. The mental split that makes the sidebar legible. Use a table here (device variety vs the list-heavy reading-code before it). */}\n\n## Every file is code, config, data, or not yours\n\nAlmost every file falls into one of four buckets, and sorting them is most of the battle:\n\n| Kind | Holds | Looks like |\n|---|---|---|\n| **Code** | the logic that runs | `.ts`, `.tsx`, `.py` |\n| **Config** | settings and wiring | `.env`, `.yaml`, `tsconfig.json` |\n| **Data** | information the app reads | `.json` |\n| **Not yours** | code you installed or your machine generated | `node_modules/`, `dist/` |\n\nName the bucket first and no file looks like noise.\n\n{/* KEEP: the fourth bucket owns almost the whole file count. node_modules/venv, dist/build/.next, .git are never hand-edited; collapse them forever, gitignore already excludes them. NOTE (July 2026): \"package manager\" is taught properly in the Dependencies chapter now, so it is only recalled here in passing, not bolded and not re-defined. */}\n\n## The biggest folders are not yours to touch\n\nNearly every file in the project sits in that fourth bucket, and none of it is yours. Three folders account for almost all of it:\n\n- `node_modules/`, or `venv/` in Python: the outside code you installed. Thousands of files, owned by your package manager, the tool that installs and updates them.\n- `dist/`, `build/`, or `.next/`: the packaged copy of your app your machine generated. Delete it and the next build writes it again.\n- `.git/`: where version control keeps its own history.\n\nCollapse all three in your sidebar and leave them collapsed. Nothing in them is ever edited by hand, and your `.gitignore` already keeps them out of version control.\n\n{/* KEEP: JSON and YAML are the two data/config formats you'll meet most. tiny json + yaml samples. bold-first: JSON, YAML. Where each shows up. */}\n\n## JSON and YAML hold your data\n\nTwo formats carry most of the data and settings you will see. [**JSON**](https://www.json.org) is the everyday one, used by data files and by `package.json`:\n\n```json\n{\n  \"name\": \"Ada\",\n  \"active\": true,\n  \"roles\": [\"admin\", \"editor\"]\n}\n```\n\n[**YAML**](https://yaml.org) says the same kind of thing with less punctuation, and shows up in config and deploy files:\n\n```yaml\nname: Ada\nactive: true\nroles:\n  - admin\n  - editor\n```\n\nBoth just store labeled values. You can read them straight off the page, which is the whole point of them.\n\n{/* KEEP: config vs code; environment variable; the .env file; secrets live here not in code. cross-ref Secure by topic. bold-first: configuration, environment variable, .env. Diagram = secrets separation, not a bucket restatement. */}\n\n## Config and secrets stay out of the code\n\n**Configuration** is everything that changes between your laptop and the live server: the database address, an API key, a feature toggle. It lives apart from the code so the same code runs anywhere.\n\nThe values that differ per machine are **environment variables**, usually listed in a file named **.env**:\n\n```bash\nDATABASE_URL=postgres://localhost/myapp\nSTRIPE_KEY=sk_live_not_a_real_key\n```\n\nA secret like that key lives in `.env`, never pasted into the code, because code gets shared and read while `.env` stays private. The Secure part covers why that line matters and how to keep it airtight.\n\n```mermaid\n%% caption: Code is shared and read by others; secrets sit in a separate, private env file.\nflowchart LR\n  subgraph SHARED[Shared, read by others]\n    CODE[Code files]\n  end\n  subgraph PRIVATE[Private, never shared]\n    ENV[env file, secrets]\n  end\n  CODE -.->|reads values from| ENV\n```\n\n{/* KEEP: the rest at a glance, one line each: Markdown/README, package.json + lockfile, Dockerfile + infra. recognize them, the agent writes them, deep coverage is Ship (by topic). bold-first: Markdown. */}\n\n## The rest you just need to recognize\n\nA handful more you only need to recognize, not master:\n\n- [**Markdown**](https://commonmark.org) (`.md`) is plain text with light formatting. Your `README`, the front-door notes for a project, is Markdown.\n- `package.json` lists the outside code your app depends on. The lockfile beside it pins the exact versions, and your package manager writes it, never you.\n- A [`Dockerfile`](https://docs.docker.com/reference/dockerfile/) and other infra files describe how the app is packaged and run on a server. Your agent writes these, and the Ship part is where they matter.\n\nYou recognize the shape and move on. The agent handles the contents.\n\n```prompt\nAct as a senior engineer giving me a tour of my repo. Read\nmy rules file and the architecture map in it first, so you\nname things the way my project already names them.\n\nList every distinct file type in the project and, for\neach, say in one plain sentence what it is for and whether\nI would ever edit it by hand.\n\nGroup them as code, config, data, or not mine (installed\nor generated). Flag any file that holds secrets so I know\nto keep it private. Flag anything sitting where my\narchitecture map does not account for it, so I can fix\nthe map or move the file.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/files-and-formats\n\nMy project:\n```\n\n**Do this now:** paste the prompt over your repo. Have the agent label every file type in plain words, so the sidebar stops being a wall of unknowns."
          },
          {
            "slug": "code-building-blocks",
            "title": "What Code Is Made Of",
            "label": "Building Blocks",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/code-building-blocks",
            "content": "---\ntakeaway: Name the pieces and code stops looking like noise\nshare: \"Open a code file and it is a small set of pieces repeating everywhere. Name the five you will meet most, variable, function, class, object, module, and code stops looking like an undifferentiated wall.\"\nrequires: [project-folder, ai-agent, editor]\nproduces: []\nteaches: [module, type, error, exception, async, variable, function, class, object]\nuses: [file, database, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = open a code file, it is a small set of pieces that repeat everywhere; name them once and code stops looking like noise. You met a few while tracing a path; here they are as the subject. Optional-part framing carries over, do not re-sell. */}\n\nOpen a file your agent wrote and it looks like a wall of symbols. It is not. Code is built from a small set of pieces that repeat on every page, and you met a few of them while tracing a single path. This chapter puts them side by side and names the fifth that ties them together, so any file resolves into parts you recognize instead of noise.\n\n{/* KEEP: the five pieces, bold-first each: variable, function, class, object, module. One plain line each + a tiny ts snippet showing all five together. Reword the four from reading-code so this is not a verbatim repeat; module is the new one. */}\n\n## The five pieces you'll see everywhere\n\nFive pieces make up almost everything in a code file:\n\n- A **variable** is a named slot that holds one value.\n- A **function** is a named block of steps you run by calling it.\n- A **class** is a template for a kind of thing, say a `User`.\n- An **object** is one concrete thing made from that template.\n- A **module** is one file's code, packaged so other files can pull it in.\n\nHere they are together, all five in a few lines:\n\n```ts\nclass User {              // class: a blueprint\n  name = \"Ada\"            // variable: one value\n  greet() {               // function: does one job\n    return \"Hi, \" + this.name\n  }\n}\n\nconst ada = new User()    // object: one real User\nexport { User }           // module: usable elsewhere\n```\n\nRead the comments, not the syntax. You are spotting five shapes, not learning to type them.\n\n{/* KEEP: the pieces nest. a variable in a function, a function in a module (one file), modules make the app. This is why \"where does this live\" always has an answer. */}\n\n## The pieces nest to make the app\n\nThese pieces are not a flat list, they nest inside each other. A variable lives in a function, a function lives in a module, and many modules together make the app.\n\nThat nesting is why \"where does this live\" always has an answer: every piece sits inside a bigger one, up to the whole app.\n\n{/* KEEP: words you'll also hear, one line each, no deep dive: type, error/exception, async. Say the agent handles them and the book returns to them where they matter (Debug for errors, Scale for async), by topic. bold-first: type, error, exception, async. */}\n\n## The words you can leave to your agent\n\nA few more words come up constantly. You only need to recognize them, the agent handles the rest:\n\n- A **type** says what kind of value something is, a number, some text, a date, so whole classes of mistakes get caught before the app runs.\n- An **error** (or **exception**) is the code's signal that a step failed, so the failure can be handled instead of silently ignored.\n- **async** marks work that takes time, a network call or a database read, so the app keeps responding while it waits.\n\nEach gets its due where it matters: errors run through the Debug part, and async comes up in Scale. Here, knowing the word is enough.\n\n```prompt\nAct as a senior engineer reading a file beside me. Read my\nrules file and its architecture map first, so you can tell\nme where this file sits in my project and which layer it\nbelongs to.\n\nPoint at the file below and name each piece in it in plain\nwords: every variable, function, class, and object, and\nwhere the module boundary is.\n\nFor each, one short sentence: what it is and the job it does\nhere. Do not assume I have read code before, and define any\nother term the first time it appears.\n\nEnd with anything in this file that breaks my recorded\nconventions or structure. Change nothing.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/code-building-blocks\n\nThe file:\n```\n\n**Do this now:** open one file your agent wrote and paste the prompt. The agent names each piece in it, and the file resolves from a wall into parts you recognize."
          },
          {
            "slug": "how-code-connects",
            "title": "How the Pieces Connect",
            "label": "Connections",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/how-code-connects",
            "content": "---\ntakeaway: Loose connections keep your app changeable\nshare: \"Files are not islands, one file calls another. See how files connect through imports and what coupling means, so you understand why loose connections let you change one part without breaking five.\"\nrequires: [project-folder, ai-agent, editor]\nproduces: [dependency-map]\nteaches: [import, dependency, coupling]\nglosses: [adapter]\nuses: [file, function, adapter, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = files are not islands, one calls another; how tightly they lean decides whether you can change one without breaking five. This chapter shows how the pieces connect and why loose connections keep an app changeable. Optional-part framing carries over, do not re-sell. */}\n\nThe files in your project are not islands. One file calls another, which calls a third, and the whole app runs on those connections. How tightly the files lean on each other decides everything about change: whether fixing one means touching five, or just one. This chapter shows you how the pieces connect, and why loose connections are what keep an app you can actually change.\n\n{/* KEEP: files call each other, bold-first: import, dependency. a file uses another by importing it. tiny snippet + a dependency-chain diagram. */}\n\n## Files use each other through imports\n\nA file uses another file's code by **importing** it, pulling in a function or value by name:\n\n```ts\nimport { sendEmail } from \"./email\"\n\nsendEmail(\"welcome@myapp.com\")\n```\n\nThat one line creates a **dependency**: this file now needs `email` to work. Follow the imports across the project and you have mapped how the whole thing hangs together.\n\n{/* KEEP: coupling, bold-first: coupling. loose vs tight in plain words. WHY loose coupling keeps the app changeable (maintainable, not a demo). Reference coupling-and-cohesion in Architect by topic, do NOT re-teach. loose-vs-tight diagram. */}\n\n## Loose coupling keeps the app changeable\n\nHow tightly two files lean on each other is their **coupling**. Loosely coupled files know as little as possible about each other, so you can change one without the other noticing. Tightly coupled files reach deep into each other, so one change drags the rest along.\n\nLoose is what you want, for one plain reason: at AI speed you change code constantly, and loose connections keep a change local instead of rippling across the app. The Architect part designs for this deliberately; here, the goal is just to see it when you read.\n\n```mermaid\n%% caption: Loose coupling lets you swap a piece; tight coupling reaches into its internals.\nflowchart LR\n  subgraph LOOSE[Loosely coupled]\n    A1[Checkout] -->|through a wrapper| P1[Payment]\n  end\n  subgraph TIGHT[Tightly coupled]\n    A2[Checkout] --> P2[Payment]\n    A2 --> DB2[(Payment data)]\n  end\n```\n\n{/* KEEP: one-line bridge to the next chapter: named shapes like the adapter exist to keep these connections loose. Do not teach the adapter here, just point forward. */}\n\n## This is why patterns exist\n\nKeeping connections loose is a solved problem, and the solutions have names. A thin wrapper called an **adapter**, for instance, sits between your app and an outside service so you can swap that service without the rest of the app noticing. Those named shapes are the next chapter.\n\n```prompt\nAct as a senior engineer auditing how my code hangs\ntogether. Read the architecture map and the layer rule in\nmy rules file first, then map which files import which, so\nI can see the dependencies at a glance.\n\nThen flag the three most tightly coupled spots: files that\nreach deep into each other, where one change would force\nchanges in several others. For each, name the smallest step\nthat would loosen it.\n\nCall out every import that crosses a layer or module\nboundary my map says it should not, and tell me which is\nwrong, the code or the map. Change no code yet. If the code\nis right and the map is stale, update the map.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/how-code-connects\n\nMy project:\n```\n\n**Do this now:** paste the prompt over your project and have the agent map the dependencies and flag the tightest couplings, so you know which parts resist change before you try to change one."
          },
          {
            "slug": "patterns",
            "title": "The Names Worth Knowing",
            "label": "Patterns",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/patterns",
            "content": "---\ntakeaway: Know pattern names so you can ask for them\nshare: The code your agent writes is full of named, proven shapes. Learn the handful you will actually meet, MVC, middleware, factory, repository, service layer, adapter, so you can recognize them and ask your agent for the right one by name.\nrequires: [project-folder, ai-agent, first-feature]\nproduces: []\nteaches: [design-pattern, mvc, middleware, factory, repo, service-layer, adapter, anti-pattern]\nuses: [database, coupling, object, function, layer, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the agent's code uses named, proven shapes; knowing the names lets you recognize them and ask for them. Recognize, do not memorize. Optional-part framing carries over from the first chapter, do not re-sell it here. */}\n\nOpen a file your agent wrote and you will see the same shapes repeat: a piece that routes requests, a piece that talks to the database, a piece that holds the rules. These are not the agent's invention. They are named, proven solutions that engineers reach for over and over. Learn the names and two things happen: you recognize what you are looking at, and you can ask your agent for the right shape by name.\n\n{/* KEEP: a design pattern = a reusable solution to a common problem, WITH a name. You recognize them, you do not memorize them. Bold-first: design pattern. */}\n\n## A pattern is a proven shape\n\nA **design pattern** is a reusable solution to a problem that comes up again and again, packaged under a name everyone knows. Someone hit the problem years ago, found a clean answer, and the answer stuck.\n\nYou do not memorize patterns or learn to build them from scratch. Your agent already knows dozens. Your job is lighter: recognize a few by sight, so the code stops looking like an undifferentiated wall.\n\n{/* KEEP: the handful you'll actually meet: MVC, middleware, factory, repository, service layer, adapter. One line each; adapter carries its WHY (thin wrapper to swap an integration, keeps coupling loose and maintainable). One tiny snippet (repository). Bold-first each. Keep snippets tiny, language-fenced. */}\n\n## The handful you'll actually meet\n\nA handful of names cover most of what you will see in a typical app:\n\n- **MVC** splits a feature into three parts: the data (model), the screen (view), and the glue between them (controller).\n- **Middleware** is a checkpoint every request passes through, for things like login checks or logging.\n- A **factory** is one function whose job is to build and hand back an object, so the rest of the code never builds it by hand.\n- A **repository** is the one place that talks to the database, so nothing else has to know how data is stored.\n- A **service layer** holds the business rules, sitting between the request and the repository.\n- An **adapter** is a thin wrapper around an outside service. Swap one payment or email provider for another and the rest of the app never notices, which keeps coupling loose and the code easy to change.\n\nA repository, for instance, is often just this shape:\n\n```ts\nconst userRepository = {\n  findById: (id) => db.users.find(id),\n  save: (user) => db.users.insert(user),\n}\n```\n\nEverything else in the app asks `userRepository` for a user and never touches the database directly.\n\n```mermaid\n%% caption: A request passes through middleware, then the service layer, then the repository to the database.\nflowchart LR\n  R([Request]) --> M[Middleware]\n  M --> S[Service layer]\n  S --> RP[Repository]\n  RP --> DB[(Database)]\n```\n\n{/* KEEP: patterns are a shared language: naming them lets you and the agent talk precisely instead of describing shapes longhand. */}\n\n## Patterns are a shared language\n\nThe real value of the names is precision. \"Put the database calls behind a repository\" is one clear instruction; describing that same shape in your own words takes a paragraph and still leaves room to be misread.\n\nThe names are a language you and your agent already share. Using them, you say exactly what you mean in three words, and the agent builds exactly the shape you pictured.\n\n{/* KEEP: no pattern is also an answer. The criterion a senior applies: two real callers, or a real reason to swap what sits behind it. One-caller factory / one-implementation interface = pattern for its own sake. Bold-first: anti-pattern. This is what stops the reader over-applying the names they just learned. */}\n\n## No pattern is also an answer\n\nKnowing the names creates a new risk: asking for them everywhere. A pattern earns its place when there are two real callers, or a real reason to swap the thing behind it later. When neither is true, a plain function is the better answer.\n\nA factory that builds exactly one object, or an interface with a single implementation, is a pattern applied for its own sake. That is an **anti-pattern**: a shape that looks professional and makes the code harder to change. Ask for the pattern when you can name what it buys you, not because it sounds senior.\n\n{/* KEEP: ask the agent to use the right pattern by name. Prompt + Do this now. The prompt should have the agent both identify patterns in existing code AND recommend/apply the right one, AND flag patterns to collapse back to a plain function. */}\n\n## Ask the agent to use the right one\n\nYou can point at code and ask which patterns are in it, or ask the agent to reshape a tangled feature into the right one. Either way you lead with the name.\n\n```prompt\nAct as a senior engineer. First read my rules file and\nthe architecture map in it, so you judge this code\nagainst my own conventions and layers, not a generic\nideal.\n\nThen read the code below and name the design patterns\nalready in it, one line each, in plain words a newcomer\nwould follow.\n\nThen tell me whether the right patterns are being used\nfor this feature. If a cleaner, more standard shape fits\n(repository, service layer, factory, middleware, adapter,\nMVC), name it, say why, and show the smallest change\ntoward it. Flag the reverse too: any pattern here that\nhas one caller or one implementation and should collapse\nback to a plain function.\n\nIf the better shape would contradict my architecture map,\nsay so and what the map would have to change to, rather\nthan quietly diverging from it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/patterns\n\nThe code and what the feature does:\n```\n\n**Do this now:** paste the prompt over one feature your agent built, and have it name the patterns already there and flag any place a more standard shape would fit."
          },
          {
            "slug": "code-quality",
            "title": "What Makes It Good",
            "label": "Code Quality",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/read/code-quality",
            "content": "---\ntakeaway: Good code is code you can change later\nshare: AI writes working code, not always good code. Good code is code you can still change six months from now. Here is the small bar that carries most of quality, and how to make your agent hold to it every time.\nrequires: [project-folder, ai-agent, rules-file, first-feature]\nproduces: [quality-bar]\nteaches: [maintainable, single-responsibility, kiss, dry, solid, code-smell]\nuses: [function, file, error, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = AI writes WORKING code, not always GOOD code. Good code is code you can still change later. Here is the small bar and how to make the agent hold it. Optional-part framing carries over, do not re-sell. */}\n\nYour agent writes code that runs, and a passing demo tells you nothing about what happens next. Working code and good code are different things. Good code is code you can still change six months from now without dreading it. This chapter gives you the small bar that separates the two, and the way to make your agent hold to it on every feature, not just when you remember to ask.\n\n{/* KEEP: good code = MAINTAINABLE over clever. The measure is whether you (or the agent) can change it later without breaking it. Clever code that no one can touch is a liability. Bold-first: maintainable. */}\n\n## Good code is code you can change\n\nThe one quality that matters most is that code stays **maintainable**: easy to read, easy to change, hard to break by accident. Everything else is downstream of that.\n\nClever code that only its author understands is not a prize, it is a liability. At AI speed you will change this code constantly, so the code that bends without breaking wins over the code that shows off.\n\n{/* KEEP: the few rules that carry most of quality: single responsibility, small functions, clear names, no duplication (DRY), explicit errors. Name SOLID as the fuller set the agent already knows. Bold-first: single responsibility, DRY, SOLID. Use a list. */}\n\n## The few rules that carry most of it\n\nMost of quality comes from six plain rules you can check by eye:\n\n- **Single responsibility:** each piece does one job, so you always know where a change goes.\n- **Keep it simple (KISS):** the simplest thing that works, no cleverness the reader has to decode later. **KISS** is short for \"keep it simple.\"\n- **Small functions:** short enough to read at a glance, not a scroll.\n- **Clear names:** a name says what the thing is, so `daysUntilRenewal` beats `d`.\n- **No duplication (DRY):** the same logic lives in one place, so a fix lands once, not five times. **DRY** is short for \"don't repeat yourself.\"\n- **Explicit errors:** failures are handled out loud, never silently swallowed.\n\nThese are the readable slice of a larger set called **SOLID**, five design principles your agent already knows by name. You do not need to study them. Naming SOLID in an instruction is enough to pull the whole set in.\n\n> **Rule of thumb:** if you cannot tell what a function does from its name and a few lines, that is the code to question, no matter how well it runs.\n\n{/* KEEP: big file is a SMELL, not a verdict. Size is a signal to LOOK, not an automatic fail. A code smell = a surface sign worth investigating, not proof of a bug. Bold-first: code smell. Decision diagram. */}\n\n## Big file is a smell, not a verdict\n\nA **code smell** is a surface sign that something might be off, a hint worth a look, not proof of a problem. A file that has grown huge is the most common one.\n\nSize alone does not condemn a file. It is a flag that says look here, then you judge: is this one thing that is genuinely large, or five things that drifted into one file and should split?\n\n```mermaid\n%% caption: A big file is a signal to look; the split decision depends on whether it does one job or many.\nflowchart TD\n  F[Large file] --> Q{One job, or many drifted together?}\n  Q -->|One job| K[Leave it, it is fine]\n  Q -->|Many jobs| S[Split into focused files]\n```\n\n{/* KEEP: what to DO with a bad verdict, the missing half of judging quality. Act now ONLY on sensitive areas (payments, login, user data) or code you are about to build on; log the rest. The three responses and nothing else: accept, send back with the rule it broke, revert. Systematic cleanup is the refactoring chapter's job, cross-ref BY TOPIC. */}\n\n## Fix it now, or write it down\n\nA bad verdict is not an instruction to rewrite everything. Fix now only what sits in a sensitive area, payments, login, or user data, or what you are about to build on top of. Log the rest and keep moving.\n\nWhen you do act, you have three moves:\n\n- **Accept it.** Ugly, but not in your way.\n- **Send it back.** Name the rule it broke so the agent fixes that one thing.\n- **Revert it.** Not worth repairing, so drop the change and ask again.\n\nCleaning up code you already shipped, deliberately and at scale, is its own job, and the chapter on refactoring covers it.\n\n{/* KEEP: make the bar the agent's STANDING rule, not a per-request ask: a rules file (or a prompt) that holds the agent to these every time. The book taught agent rules earlier, this points back to that. Prompt + Do this now. */}\n\n## Make it the agent's standing bar\n\nAsking for quality once is weak. The fix is to make this bar standing, written into the rules file your agent reads on every task, so it applies without you repeating it.\n\n```prompt\nAct as a senior engineer setting the quality bar for every\nchange from now on. Read my rules file and add these\nbeside what is already there, without duplicating or\ncontradicting a rule it holds:\n\n- One responsibility per function and file.\n- Small functions with names that say what they do.\n- No duplicated logic (DRY); shared logic lives in one place.\n- Errors handled explicitly, never silently swallowed.\n- Follow SOLID where it fits.\n\nThen review the code I name below against this bar and\nagainst the architecture map and conventions already in\nthat file. List, worst first, what to fix and the smallest\nchange for each. Run my existing checks before you call\nanything done.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/read/code-quality\n\nThe code to review:\n```\n\n**Do this now:** paste the prompt to fold this bar into your agent rules file, then have it review one existing feature against the bar and hand you the worst offender first."
          }
        ]
      },
      {
        "id": "amplify",
        "title": "Build an AI agent into your product",
        "chapters": [
          {
            "slug": "talking-to-a-model",
            "title": "Talking to a Model",
            "label": "Model Calls",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/talking-to-a-model",
            "content": "---\ntakeaway: Call a model like any other service\nshare: Your app can now ask a model a question in plain language, but that is a real API call with cost, latency, and limits. This chapter gets you making it correctly, behind one thin layer so you are never locked into a single model.\nrequires: [running-app, ai-agent, env-file]\nproduces: [model-adapter, model-api-key]\nteaches: [prompt, token, multimodal, streaming, model-router, gpu, inference-server, quantization]\nuses: [model, api, adapter, api-key, context, context-window, ai-coding-agent, hosting]\n---\n{/* KEEP: lead-in = the AI now moves INSIDE the product (distinct from the dev agent that builds it); a model call is not magic, it is an API call with real cost, latency, and limits; payoff = make that call from your product, correctly. */}\n\nUntil now, AI was the tool you built your app with. In this part it moves inside the app, so your product can ask a model a question in plain language and act on the answer. That is not magic; it is an API call, text in and text out, with real cost, latency, and limits. This chapter gets you making that call from your product, correctly.\n\n{/* KEEP: a model is a service you call: you send a **prompt** (your text/instructions) over an API and get text back; treat it like any external service (slow, can fail, costs money) and wrap it the same way. Bold-first: prompt. Also: models are multimodal (images and audio in, some generate them), the call shape is identical and only the message content changes, so scan-a-receipt / read-a-document / transcribe / generate-an-image are the same call; point at the agent for specifics. Bold-first: multimodal. */}\n\n## A model is a service you call\n\nA model call is just another service call. You send a **prompt**, your text and instructions, over an API, and you get text back. Nothing more mysterious than that.\n\nSo treat it like any external service you already rely on. It can be slow, it can fail, and it charges you for every call. Wrap it with the same care you give any other outside dependency.\n\nText is not the only thing you can send. Many models are **multimodal**: they also read images and audio, and some generate them. The call keeps the same shape and only the message content changes, so these are the same API call you are about to write:\n\n- reading a photo, a scan, or an uploaded document\n- transcribing a voice note\n- generating an image\n\nAsk your agent for the specifics the day your product needs one.\n\n{/* KEEP: the model knows only what you send it this call (no memory of your app); text is measured in **tokens**, you pay per token and the reply slows as the prompt grows; send only what the task needs, not your whole database. Bold-first: token. Rule-of-thumb callout. ALSO KEEP (added July 2026): tokens are not only cost and latency, there is a HARD CEILING, the same context window the reader already owns from the Build part, and a call that exceeds it fails outright rather than being trimmed. That is what turns \"keep it small\" from a preference into a constraint, and it is why the RAG chapter retrieves a few chunks and not the whole corpus. */}\n\n## Feed the right context, and mind the tokens\n\nThe model knows only what you put in the prompt this call. It has no memory of your app, your database, or your last request, so the context it needs has to travel with every message.\n\nThat context is not free. Text is measured in **tokens**, roughly chunks of a few characters, and you pay per token while the reply gets slower as the prompt grows. Send what the task needs, not everything you have.\n\nYou do not have to send it all to one model, either. A common way to cut cost is **model routing**, sending each request to the cheapest model that can handle it. A strong model takes the hard requests, a small cheap one takes the simple ones.\n\nThere is a hard ceiling too. Each model holds only so much text in one call, the same context window your coding agent works inside. A request that goes over it fails outright, instead of being trimmed for you. That is how a feature that stuffs a whole document into the prompt passes your testing and breaks on your first large customer.\n\n> **Rule of thumb:** if you would not paste it into the message by hand, do not stuff it into the prompt.\n\n{/* KEEP: a model replies slowly, a piece at a time; **streaming** shows each piece the moment it is generated so the user sees words appear instead of a spinner; the wait is the same but it feels fast. Bold-first: streaming. */}\n\n## Stream the answer so it feels fast\n\nA model writes its reply a piece at a time, and a long answer can take many seconds. Make the user stare at a spinner for all of it and your app feels broken.\n\n**Streaming** sends each piece the moment it is generated, so words appear on screen as the model writes them. The total wait is the same, but it feels fast because the user sees progress from the first word.\n\n{/* KEEP: do not lock into one model: put the call behind one thin layer (adapter, by topic) so you switch by changing settings, not code; a **router** like OpenRouter reaches many models behind one call. REAL artifact = the adapter chat-completion call, model swappable. Then the copy-paste prompt. Bold-first: router. Link: openrouter.ai. */}\n\n## Do not lock into one model\n\nModels change fast, and the best one for your job this month may not be the best next month. So never scatter one model's name and address across your code, or switching means a painful hunt.\n\nPut the call behind one thin layer your app talks to, the same adapter habit you use for any external service. Point that layer at a **router** like [OpenRouter](https://openrouter.ai), which reaches many models and providers behind a single call. If you already run on one of the big clouds, its own model service is a third path that hosts foundation models behind that same layer. Switching then becomes a change of settings, not code.\n\nAll three paths call a model someone else hosts, which is the right default. You can instead run your own open-source model, if you ever have a real reason: cost at scale, privacy, or an offline need. That means renting a **GPU** server and serving the model with an **inference server**, and **quantization** shrinks a model to run on cheaper hardware.\n\nBe honest about the money, though. A GPU is expensive and sits idle unless it is busy, so self-hosting only pays off once you have enough steady traffic to justify it. Until then a hosted API is cheaper and simpler. Hand this to your agent when the reason is real, not before.\n\n```ts\n// One thin layer between your app and any model.\n// Swap MODEL or the URL; the rest of your app never changes.\nexport async function askModel(prompt: string) {\n  const res = await fetch(\n    \"https://openrouter.ai/api/v1/chat/completions\",\n    {\n      method: \"POST\",\n      headers: {\n        Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify({\n        model: process.env.MODEL, // switch models here\n        messages: [{ role: \"user\", content: prompt }],\n      }),\n    },\n  );\n  const data = await res.json();\n  return data.choices[0].message.content; // the text back\n}\n```\n\nYour agent writes this; you read it. This is the bare shape, text in as `messages` and text back as `content`; the prompt below adds streaming and error handling.\n\nThis prompt hands the whole setup to your agent:\n\n```prompt\nAct as a senior AI engineer wiring my app's first\nmodel call. Follow my architecture map and the\nadapter pattern I already use for outside services:\nput it behind one thin adapter so the rest of my app\ncalls askModel(prompt) and nothing else knows which\nmodel or provider sits behind it.\n\nRequirements:\n- Route through OpenRouter so I switch models by\n  changing one config value, never my code.\n- Stream the reply so the user sees words appear\n  instead of waiting on a spinner.\n- Send only the context the task needs, and keep\n  the API key in an environment variable, with a\n  placeholder added to my .env.example.\n- Handle a slow or failed call cleanly, with a\n  timeout and a clear message, not a crash.\n- Record the model and provider choice with its\n  reason as a short ADR, and note it in my\n  changelog.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/talking-to-a-model\n\nMy app and what I want the model to do:\n```\n\n**Do this now:** paste the prompt and have your agent build the adapter, then call `askModel` with one real question from your app and watch the answer stream back."
          },
          {
            "slug": "managing-prompts",
            "title": "Managed Like Code, Stored Like Docs",
            "label": "Prompt Files",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/managing-prompts",
            "content": "---\ntakeaway: Keep prompts in files, never in code\nshare: 'The prompt is the most-edited, least-reviewed thing in an AI product. Pull it out of the code into small versioned files you can read, diff, and roll back like anything else you ship.'\nrequires: [ai-agent, project-folder, model-api-key, model-adapter]\nproduces: [prompt-library]\nteaches: []\nuses: [model, ai-coding-agent, prompt, repo]\n---\n{/* KEEP (added July 2026, user mandate): the missing half of building on a model. The book teaches how to CALL a model but never how to manage the text you send it, which is the thing you edit most and review least. This chapter is about the prompt as a shipped artifact, not about writing better prompts, which the Build part already covers. */}\n\nYou are calling a model now, and somewhere in that code is a long string of instructions. It will be the most edited thing in your product and the least reviewed, and right now it is buried in a function where nobody can see it change. This chapter pulls it out.\n\n{/* KEEP: CONCEPT, the hard rule. A prompt is content, not code, and mixing them means you cannot find it, read it, or see what changed. Move it to its own file next to the code that loads it. State the consequence plainly: a prompt inside a string is a prompt nobody reviews. */}\n\n## A prompt is content, not code\n\nA prompt buried in a source file is invisible. You cannot skim it, your agent edits it without you noticing, and a change to two words of instruction looks exactly like a change to the code around it.\n\nSo keep it out. Prompts live in their own files, in plain text or markdown. The code loads them by name:\n\n```\nprompts/\n  support-reply/\n    system.md          the role and the hard rules\n    tone.md            how it should sound\n    examples.md        two or three worked examples\n```\n\nNow the instruction is readable by you, editable without touching code, and every change to it shows up as a change to a document rather than a change to a program.\n\n{/* KEEP: STEP. Compose from pieces rather than one wall of text, and the reason is blast radius: your agent editing the tone file cannot damage the safety rules. Small files are also the only way you can tell what actually changed. Same single-source-of-truth habit as config, so reference it by topic, do not re-teach it. */}\n\n## Build it from pieces, not one wall\n\nOne enormous prompt is a single blast radius. Ask your agent to soften the tone and it rewrites the whole thing, and the safety rule you spent an afternoon on quietly disappears in the middle.\n\nSplit it. The role and the non-negotiable rules in one file, the tone in another, the examples in a third, and the code assembles them at call time. Now an edit to tone touches the tone file and nothing else, and you can see that at a glance.\n\nThe shared pieces follow the same habit as your settings: one copy, loaded by everything that needs it, never pasted twice.\n\n{/* KEEP: STEP. Prompts are shipped artifacts and must be versioned like one: a version on each, git history for what changed and when, and the version recorded on the calls it produced so a quality change can be traced to a prompt change. This is the piece that connects to the outcome loop later in the book, but do NOT re-teach that, one clause only. */}\n\n## Version them like anything else you ship\n\nA prompt change is a product change. Yesterday's answers came from yesterday's instructions, and if you cannot say which version produced a result, you cannot tell a model problem from a prompt problem.\n\nGive each prompt a version and stamp it on the calls it makes:\n\n```\n# prompts/support-reply/system.md\nversion: 4\nupdated: 2026-07-30\nchange: refuse refund promises, escalate instead\n```\n\nYour repo already keeps the full history, so version four is one command away from version three. That matters most on the day quality drops and nobody remembers touching anything.\n\n{/* KEEP: STEP. The honest warning: a prompt edit ships with none of the safety a code change gets, no type checker and no compiler, and reads as harmless. So it goes through the same gate as code: reviewed, and checked against the eval set before it ships. Reference evals BY TOPIC, the reliability chapter owns them. */}\n\n## Treat an edit like a deploy, because it is\n\nA two-word prompt edit ships with none of the protection a code change gets. Nothing type-checks it, nothing compiles it, and it looks completely harmless in a diff.\n\nIt is not. Changing \"be concise\" to \"be brief\" has flipped output quality in production systems. So a prompt change goes through the same gate as any other. You review it, then run it against the set of examples you use to judge model quality before it reaches users.\n\n> **Watch out:** never let an agent edit a prompt as a side effect of some other task. Prompt files are content it will happily tidy. Make prompt edits their own change, always.\n\n{/* KEEP: the prompt. Extracts prompt strings ALREADY in the code into split files, adds versions, stamps the version onto calls, and adds a command listing every prompt with its version and where it is used. Forbids rewording anything during the extraction, that is the trap. One append slot. */}\n\n## Pull your prompts out of the code\n\n```prompt\nAct as a senior engineer reorganizing the prompts in my\nproduct. Find every prompt string currently living in\nmy source code and list them first, before changing\nanything.\n\nMove each into its own folder under a prompts\ndirectory, split into separate files: the role and hard\nrules, the tone, and the examples. The code loads and\nassembles them by name. Do not reword a single\ninstruction while moving it; this change must be\nbehaviour-neutral and I want to diff it.\n\nGive each prompt a version number and a one-line note\nsaying what last changed, and stamp that version onto\nthe calls it produces so I can trace an answer back to\nthe instructions that made it.\n\nFinally, add one command that lists every prompt, its\nversion, and where in the code it is used.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/managing-prompts\n\nMy product, and where its model calls live:\n```\n\n**Do this now:** paste the prompt and get every instruction string out of your code and into a file you can actually read."
          },
          {
            "slug": "giving-the-model-your-data",
            "title": "Giving the Model Your Data",
            "label": "RAG",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/giving-the-model-your-data",
            "content": "---\ntakeaway: Ground the AI in your own data\nshare: \"A model answers from what it was trained on, not your private data. Retrieval-augmented generation fetches the pieces of your data that fit the question and hands them to the model, so it answers from your facts instead of guessing.\"\nrequires: [running-app, ai-agent, model-adapter, project-docs]\nproduces: [rag-pipeline]\nteaches: [rag, chunk, embedding, vector-database, fine-tuning, hybrid-search, reranking, graphrag, multi-hop-retrieval]\nuses: [model, prompt, context, database, ai-coding-agent, cache]\n---\n{/* KEEP: lead-in = a model knows only its training snapshot, not your data, docs, or product; asked about them it answers confidently and wrong. This chapter gets it answering FROM your data. CODE-FORWARD. */}\n\nA model knows what it was trained on: a snapshot of public text, frozen at a point in time. It has never seen your data, your internal docs, or how your product actually works. Ask it about those and it will answer anyway, confidently and wrong. This chapter gets the model answering from your data instead of inventing it.\n\n{/* KEEP: S1 concept = the model has no access to your private data; the fix is not retraining but fetching the few relevant pieces at call time and handing them to the model with the question. This pattern is RAG (retrieval-augmented generation). Bold-first: RAG. Mermaid = question + fetched pieces both feed the model, no forward leak. Fine-tuning is NAMED here with its honest rule (RAG for facts that change, fine-tuning for style/format/one narrow cheap task) and the reason it is not the default (re-run on every data change, wrong answers baked in), never dismissed in half a sentence. Bold-first: fine-tuning. */}\n\n## The model doesn't know your world\n\nThe model runs in a sealed box. It cannot reach your database, read your files, or look anything up on its own, so anything specific to you is a blank it fills with a plausible guess.\n\nThe fix is not to retrain it on your data. Instead, when you ask a question, you fetch the few pieces of your data that answer it, then hand those to the model. That pattern is **RAG**, retrieval-augmented generation: retrieve the relevant facts, then let the model generate its answer from them.\n\nRetraining has a name, **fine-tuning**, and it is a real tool with a narrow job. The honest rule: RAG for facts that change, fine-tuning for a consistent style, a fixed output format, or one narrow task you want a small cheap model to do reliably. It is not the default because you re-run it every time your data changes, and a wrong answer is baked in until you do.\n\n```mermaid\n%% caption: RAG in one flow: the question pulls matching pieces of your data, and both feed the model.\nflowchart LR\n  Q[Your question] --> R[Fetch matching pieces of your data]\n  R --> P[Build the prompt]\n  Q --> P\n  P --> M([Model]) --> A[Grounded answer]\n```\n\n{/* KEEP: S2 = split your data into chunks, then turn each chunk into an embedding, a list of numbers capturing meaning, so similar meanings sit close together. Bold-first: chunk, embedding. Artifact: text becomes a vector of numbers. */}\n\n## Turn text into vectors you can search\n\nFirst you split your data into **chunks**, small self-contained passages: a paragraph of a doc, one help article, a single record. Then you turn each chunk into an **embedding**, a long list of numbers that captures its meaning, produced by a model built for exactly this.\n\n```\n\"Reset your password under Settings, then Security.\"\n\nbecomes a list of numbers that captures its meaning:\n\n[0.021, -0.184, 0.077, 0.005, ...]   # often 1,000+ numbers\n```\n\nThe trick is that meaning becomes distance. Chunks about the same idea get similar numbers and sit close together. So \"reset my password\" lands near \"I forgot my login\", even with no shared words.\n\n{/* KEEP: S3 = a vector database stores every chunk's embedding and finds the closest matches to a question by meaning, not exact keywords. Bold-first: vector database. REAL ARTIFACT: embed the query, then similarity search with top_k. */}\n\n## Store and search them in a vector database\n\nA **vector database** stores every chunk's embedding and is built to answer one question fast: which stored chunks sit closest to this one? You load your embeddings in once, then query it as often as you like.\n\nTo search, you embed the question the same way, then ask for its nearest matches. It matches on meaning, not exact keywords, so a question worded nothing like your docs still finds the right passage.\n\n```python\n# embed the question the same way you embedded your data\nquery = embed(\"How do I change my password?\")\n\n# ask the vector database for the 3 closest chunks\nmatches = db.search(query, top_k=3)\n# each match is a stored chunk, with its text and score\n```\n\n{/* KEEP: S4 = paste the top matching chunks into the prompt and the model answers FROM them; keep the retrieved set small and relevant (three to five, not everything). Refs the prompting chapter by topic. Ends with the RAG-setup prompt + Do this now. */}\n\n## Retrieve, then answer\n\nYou already know how to write a prompt; retrieval just changes what goes into it. You paste the top matches in, above the question, with a line telling the model to answer only from them.\n\nNow the model reads real facts instead of reaching for a guess. Keep the retrieved set small: the best three to five chunks, not everything you own. Too much context buries the answer and costs more.\n\n> **Rule of thumb:** if the answer is not in the chunks you retrieve, the model cannot know it. Retrieval quality is the whole game.\n\nStart simple, and if basic retrieval is not accurate or cheap enough, reach for the known upgrades and hand them to your agent by name. Add plain keyword matching alongside the vector search (**hybrid search**), reorder the retrieved chunks so the best ones lead (**reranking**), and cache repeated answers to cut cost. For complex, connected data, fancier variants like **GraphRAG** and **multi-hop retrieval** exist, but only reach for them when the simple pipeline falls short.\n\nThis prompt sets the whole pipeline up on your data:\n\n```prompt\nAct as a senior AI engineer setting up RAG for my app.\nRead my architecture map and my data model first, and\nput this behind the model adapter I already have,\ninside the module that owns the data.\n\nSplit my data into clean chunks, embed each one, and load\nthem into a vector database. At answer time, embed the\nquestion, retrieve the few closest chunks, and put only\nthose into the prompt so the model answers from my data,\nnot its training. Recommend a chunk size and how many\nchunks to retrieve, and flag anything I should not embed,\nlike secrets or private user data.\n\nRecord the vector database you picked as an ADR with\nits tradeoff, and add the pipeline to my changelog.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/giving-the-model-your-data\n\nMy data and what I want it to answer:\n```\n\n**Do this now:** paste the prompt, point it at one folder of your docs, and ask a question those docs answer that the model could never answer on its own."
          },
          {
            "slug": "agents-in-your-product",
            "title": "Agents in Your Product",
            "label": "AI Agents",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/agents-in-your-product",
            "content": "---\ntakeaway: Use an agent when a call isn't enough\nshare: \"A chatbot answers in one shot, but some features need the AI to decide, look something up, then act, sometimes several times over. This chapter gets you knowing when your product needs an agent, how its tool-using loop works, and how to keep it from doing damage.\"\nrequires: [running-app, ai-agent, model-adapter]\nproduces: [in-app-agent]\nteaches: [ai-agent-in-product, agent-tool, least-privilege]\nglosses: [state]\nuses: [model, prompt, function, library, framework, api-key, state, ai-coding-agent]\n---\n{/* KEEP: lead-in = you shipped an AI feature that was one model call; then it needed to decide, look something up, and act, several times over. That is where a plain call becomes an agent. Distinct from the dev-agent OS that builds your code: this one ships INSIDE the product for your users. Payoff = when your product needs an agent, and how one works. */}\n\nYou added an AI feature to your app, and for a while one model call did the job: text in, answer out. Then it needed more: look something up, decide what to do, then act, sometimes several times over. That is the moment a plain call becomes an agent, and not the kind that builds your code, but one you ship inside your product for your users. This chapter gets you knowing when your product needs an agent, and how one works.\n\n{/* KEEP: CONCEPT. a plain call answers (text in, text out, done); an agent acts by running a loop: decide, call a tool, observe the result, go again until done. Bold-first: agent, tool. The loop is what makes it an agent, not the wording of one reply. Mermaid = the loop with a real fork. */}\n\n## A call answers; an agent acts\n\nA plain call answers. You send text, the model sends text back, and the exchange is over. An **agent** acts instead: it runs a loop, deciding and doing and checking until the task is actually done.\n\nEach time around, it decides the next step, calls a **tool** (a function you let it run to fetch data or take an action), and reads the result before deciding again. The loop, not the wording of any one reply, is what makes it an agent.\n\n```mermaid\n%% caption: A plain call is one shot; an agent loops, calling tools until the task is done.\nflowchart TD\n  T([Task]) --> D[Decide the next step]\n  D --> Q{Need a tool?}\n  Q -->|Yes| C[Call the tool]\n  C --> O[Observe the result]\n  O --> D\n  Q -->|No| A([Answer, done])\n```\n\n{/* KEEP: STEP. tools = the functions the agent may call to act on the world; words tell it what you want, tools let it do it. A tool is name + description + inputs. REAL ARTIFACT: a tool definition + the think/call/observe loop, sketched. The loop is the whole engine; the design work is which tools and how tightly scoped (bridge to S4). */}\n\n## Give it tools, not just words\n\nWords tell the agent what you want; tools are what let it act on the world. A tool is a plain function with a name, a short description so the model knows when to reach for it, and the inputs it takes.\n\n```\n# A tool the agent may call\ntool lookup_order:\n  description: \"Look up one order by its id.\"\n  input:  { order_id: string }\n  access: read-only\n\n# The loop that decides when to use it\nwhile not done:\n    step = model.decide(context)         # think\n    if step.wants_tool:\n        result = run(step.tool, step.args)  # call\n        context.add(result)                 # observe\n    else:\n        answer = step.text                  # model has it\n        done = true\n```\n\nThat loop is the whole engine. The real design work is which tools you expose, and how tightly you scope each one.\n\n{/* KEEP: STEP. you can hand-write the loop for one or two tools (a dozen lines you understand). Frameworks (LangChain, LangGraph) handle the loop, state, and tool-wiring when it grows; name plainly as options, no endorsement, link official. When a simple loop is plenty vs when a framework earns its place = two-column table. Reaching too early buys complexity before you have the problem. */}\n\n## Reach for a framework when the loop gets real\n\nYou can write that loop yourself, and for one or two tools you should: it is a dozen lines and you understand every one. Libraries such as [LangChain](https://www.langchain.com/) and [LangGraph](https://www.langchain.com/langgraph) exist to handle the loop, the **state** (what the run remembers between steps), and the tool wiring once it grows.\n\nName them as options, not defaults. Reaching for one too early buys complexity you have to learn before you have a problem it solves.\n\n| Keep it a simple loop | Reach for a framework |\n| --- | --- |\n| One or two tools | Many tools to coordinate |\n| A few steps, then done | Long or branching runs |\n| You can read every line | State and retries to manage |\n\n{/* KEEP: STEP. an in-app agent with tools can do real damage because the model decides when to pull each power. Give each tool the LEAST PRIVILEGE that works (read-only over write, scoped key over master key, test target over prod), and a human approval gate before anything irreversible. Same discipline the security chapters apply to agents reading untrusted input (reference by topic, not number). Bold-first: least privilege. Then the prompt. */}\n\n## Keep it on a leash\n\nAn agent with tools can do real damage, because a tool is real power and the model decides when to pull it. Give each tool the **least privilege** that still does the job: read-only over write, a scoped key over a master key, a test target over production.\n\nFor anything you cannot undo, deleting data, sending money, emailing users, the agent proposes and a human approves. It is the same discipline the security chapters apply to agents that read untrusted input: the shorter the leash, the less any mistake or attack can reach.\n\n```prompt\nAct as a senior AI engineer. Look at the feature I\ndescribe and answer the honest question first: does it\nactually need an agent, or is one model call enough?\nIf a plain call does the job, say so and stop there.\n\nIf it truly needs an agent, design the smallest one\nthat works. Route every model call through the adapter\nI already have instead of adding a second vendor path,\nand put its code where my folder layout says this\nfeature lives. List only the tools the task requires,\nand give each the least privilege that still works:\nread-only over write, a scoped key over a master key,\na non-production target by default. Put a human\napproval step in front of every irreversible action\n(delete, send money, email users). Show the tool\ndefinitions and the think, call, observe loop.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/agents-in-your-product\n\nMy feature:\n```\n\n**Do this now:** paste the prompt, and only if your feature truly needs an agent, wire the smallest tool-using loop with least-privilege tools and an approval gate before any action you cannot undo."
          },
          {
            "slug": "ai-workflows",
            "title": "Chaining the Steps",
            "label": "AI Workflows",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/ai-workflows",
            "content": "---\ntakeaway: Chain small steps, not one giant prompt\nshare: \"Some AI tasks are really several steps: read the input, decide what it means, then write the result. Cram them into one giant prompt and it turns unreliable and hard to debug; chain small checked steps and each one is reliable and you can see where it broke.\"\nrequires: [running-app, ai-agent, model-adapter]\nproduces: [ai-workflow]\nteaches: [workflow, orchestrator, state, human-in-the-loop]\nglosses: [retry]\nuses: [model, prompt, ai-agent-in-product, ai-coding-agent, retry]\n---\n{/* KEEP: lead-in = some AI tasks are really several steps (read this, decide that, write the result); one giant prompt makes the model unreliable and impossible to debug because you can't see which part failed. This chapter = break multi-step AI work into small, checkable steps. CODE-FORWARD. */}\n\nSome AI tasks are not one task. They are several: read this input, decide what it means, then write the result. Cram all three into one giant prompt and the model turns unreliable and impossible to debug, because you cannot see which part it got wrong. This chapter gets you breaking multi-step AI work into small, checkable steps.\n\n{/* KEEP: concept = define workflow: chains small model calls, each one clear job, so each step is reliable and you can SEE which step failed. Contrast: mega-prompt = one opaque box (works or fails, tells you nothing about where); workflow = line of small boxes you inspect between. Bold-first: workflow. */}\n\n## Many steps beat one mega-prompt\n\nA **workflow** chains small model calls, each doing one clear job. One call reads the input, the next decides what it means, a third writes the result. Because every step is small and focused, each one is reliable, and when something breaks you can see exactly which step did it.\n\nA single mega-prompt is one opaque box: it either works or it fails, and a failure tells you nothing about where. A workflow is a line of small boxes you can open and inspect between. That visibility is the whole point.\n\n{/* KEEP: one call handles a single job (classify/summarize/extract); reach for a workflow ONLY when the task has multiple stages or a branch (one step's result changes what's next). Do NOT over-engineer a one-call task (extra steps = cost + failure points for nothing). Refer to the product's agent by topic. Device: comparison table. */}\n\n## Know when one call is enough\n\nNot every task needs a workflow. The agent you gave your product answers most things in one call, and you reach for a workflow only when a task genuinely has stages or a branch.\n\n| One call is enough | You need a workflow |\n| --- | --- |\n| One clear job: classify, summarize, extract | Several stages: read, then decide, then write |\n| The output is one shape you check at once | A step's result changes what happens next |\n| Redoing it is cheap if it is wrong | A bad early step must be caught before the rest |\n\nDo not wrap a one-call task in a workflow. The extra steps only add cost and more places to fail, for nothing.\n\n{/* KEEP: orchestration = sequencing steps, branching on results, retrying a failed one. You don't hand-wire it: a workflow tool (LangGraph and others, name as OPTIONS) runs the chain, follows branches, retries. Real artifact = the small checked chain (read -> decide -> write, check between each). Bold-first: orchestration. Link: langchain.com/langgraph. Mermaid = checked chain with retry/stop branch. */}\n\n## Orchestrate the steps\n\n**Orchestration** is sequencing the steps, branching on their results, and running a failed one again, a **retry**. You do not wire this by hand for anything real. A workflow tool like [LangGraph](https://www.langchain.com/langgraph), and others like it, runs the chain for you: it calls each step in order, follows the branch, and retries a step that failed.\n\nYou do not memorize the shape, your agent writes it. Here is what a three-step chain looks like, one small model call per step, a check between each:\n\n```python\ndef handle_ticket(email):\n    facts = extract(email)       # step 1: read\n    check(facts, \"request\")      # stop if none found\n\n    route = classify(facts)      # step 2: decide\n    check(route, CATEGORIES)     # stop if invented\n\n    reply = draft(facts, route)  # step 3: write\n    check(reply, max_len=800)    # stop if it rambled\n    return reply\n```\n\n```mermaid\n%% caption: Each step runs, then a check gates it: a passing result feeds the next step, a failing one retries or stops.\nflowchart TD\n  R[1. Read the request] --> C1{Output valid?}\n  C1 -->|no| X1[Retry or stop]\n  C1 -->|yes| D[2. Decide the category]\n  D --> C2{Output valid?}\n  C2 -->|no| X2[Retry or stop]\n  C2 -->|yes| W[3. Write the reply]\n  W --> C3{Output valid?}\n  C3 -->|no| X3[Retry or stop]\n  C3 -->|yes| S([Send])\n```\n\nThe tool also handles the retries and shows you each run. A flaky step recovers on its own, and you see exactly where a run stopped.\n\nA workflow often needs to remember what earlier steps produced. Carrying that along is **state**, another main thing the tool manages for you.\n\n{/* KEEP: validate each step's output before feeding the next, so one bad step doesn't poison the rest. Treat each step's result like untrusted input from outside your code. Watch out callout = an unchecked bad step corrupts every step after it; final answer looks confident and wrong. Refer to input validation / reliability by topic (no forward-ref jargon). Prompt + Do this now live here. */}\n\n## Check between the steps\n\nThe checks are the point. Validate each step's output before you hand it to the next, so one bad step does not poison the rest. Treat every step's result like input from outside your code: never trust it blindly.\n\n> **Watch out:** an unchecked bad step does not just fail itself. It quietly corrupts every step after it, and the final answer comes out confident and wrong.\n\nA check can be plain: the field exists, the category is one you allow, the text is not empty and not too long. This is the same input-checking that keeps any feature reliable, applied between AI steps instead of only at the front door. Some workflows go further and pause for a person to approve or correct a step before continuing, a **human-in-the-loop** step.\n\nThis prompt turns your task into a checked workflow:\n\n```prompt\nAct as a senior AI engineer. Read my rules file and my\nspec first, and route every model call through the\nadapter I already have, never a fresh direct vendor\ncall.\n\nTake my multi-step AI task below and turn it into a\nworkflow: small steps, each one model call doing a\nsingle job, sequenced in order. Between every step,\nadd a check that validates the output before the next\nstep runs, so one bad step cannot poison the rest. Add\na retry on any step that can fail for transient\nreasons.\n\nTell me whether a plain script or a workflow tool like\nLangGraph fits my case, and why. Record that call as a\nshort decision record in my docs. Then show me how to\nrun and inspect one step at a time.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/ai-workflows\n\nMy multi-step AI task:\n```\n\n**Do this now:** take one AI feature that reads, decides, then writes inside a single prompt, paste this, and split it into three checked steps."
          },
          {
            "slug": "making-ai-reliable",
            "title": "Making AI Reliable",
            "label": "AI Reliability",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/amplify/making-ai-reliable",
            "content": "---\ntakeaway: Assume the model will be wrong sometimes\nshare: \"An AI feature that dazzles in your demo can hand a real user a made-up answer in production. This chapter gets it to fail safely: force the model into a shape you can validate, catch regressions with an eval, and fall back cleanly when the call is slow or wrong.\"\nrequires: [running-app, ai-agent, model-adapter]\nproduces: [hardened-ai-feature, ai-eval-suite]\nteaches: [hallucination, structured-output, jailbreak, guardrail, moderation, eval, drift, llm-tracing, timeout, fallback, quota]\nglosses: [regression]\nuses: [model, prompt, schema, json, test, regression, cache, ai-coding-agent]\n---\n{/* KEEP: lead-in = the Problem. A model sounds as confident when it is wrong as when it is right, so an AI feature that demos fine can hand a real user a made-up answer in production; you cannot trust raw model output the way you trust code you wrote and tested. This chapter = make the AI feature fail safely, not confidently. */}\n\nA model sounds the same when it is wrong as when it is right. So an AI feature that works in your demo can quietly hand a real user a made-up answer in production. You cannot trust raw model output the way you trust code you wrote. This chapter gets your AI feature to fail safely instead of confidently.\n\n{/* KEEP: Concept = models hallucinate (fluent, plausible, false output); confidence is not correctness. Plan for wrong answers, do not hope for right ones; treat every response as an untrusted guess until something you control has checked it. Bold-first hallucinate. */}\n\n## The model will be confidently wrong\n\nA model has no sense of when it is wrong. It predicts fluent, plausible text, so a made-up answer reads exactly like a correct one.\n\nModels **hallucinate**: they produce output that is fluent, plausible, and false. It is not a rare glitch you patch out, it is a property of how the model works.\n\nSo plan for wrong answers instead of hoping for right ones. Treat every response as an untrusted guess until something you control has checked it.\n\n{/* KEEP: Ask for structured output (a fixed shape like JSON), validate every response against a schema, reject malformed so it never flows downstream. Same discipline as validating any external input (by topic). Bold-first structured output. Real artifact: JSON + schema check code. */}\n\n## Constrain the output and validate it\n\nFree-form prose is hard to check by machine. So ask the model for **structured output**, a fixed shape like JSON, not a paragraph you have to interpret.\n\nA shape you defined is a shape you can check. Validate every response against a schema with a validator like [Zod](https://zod.dev), and reject anything that does not fit. It is the same discipline you apply to any external input.\n\n```js\n// Ask the model to reply as JSON, then check\n// the shape before you trust it.\nconst schema = z.object({\n  sentiment: z.enum(['positive', 'negative']),\n  score: z.number().min(0).max(1),\n})\n\nasync function classify(text) {\n  const raw = await model.json(text)\n  const result = schema.safeParse(raw)\n  if (!result.success) {\n    throw new Error('Model returned a bad shape')\n  }\n  return result.data\n}\n```\n\nMalformed output never flows downstream: a response that fails the check is dropped or retried, not passed to the user.\n\nOnce real users can reach the feature, wrong answers are not the only risk: some will try to make the model say something harmful or break its own rules, a **jailbreak**. The defense is a **guardrail**, a checkpoint that inspects what goes into and comes out of the model and blocks or rewrites anything unsafe. The easy win is running text through a **moderation** service instead of hand-writing filters; the input side, users smuggling instructions into their text, is the prompt-injection problem the security part covers.\n\n{/* KEEP: An eval = example inputs paired with expected results, run on every change, so you catch regressions when you swap a model or edit a prompt instead of eyeballing one case. It is testing aimed at a fuzzy feature (by topic). Bold-first eval. Real artifact: tiny eval loop reusing classify. Start with 5 cases, grow on each failure. Drift needs a MECHANISM: record every call (input, output, model, tokens, latency, validation result) = LLM tracing, Langfuse named + linked, recorded failures become new eval cases, forward pointer to Operate. Bold-first llm tracing. */}\n\n## Evaluate it, do not eyeball it\n\nYou tweak a prompt, try it once, and the answer looks better. But one hand-check says nothing about the cases you did not try, and one fix often breaks another.\n\nAn **eval** is a set of example inputs paired with the results you expect, run against your feature after every change. It is testing aimed at a fuzzy feature. When you swap a model or edit a prompt, it flags any **regression**, an answer that used to be right and got worse.\n\n```js\n// An eval: inputs paired with expected results,\n// run after every prompt or model change.\nconst cases = [\n  { text: 'I love this', want: 'positive' },\n  { text: 'Worst thing ever', want: 'negative' },\n]\n\nfor (const c of cases) {\n  const got = await classify(c.text)\n  if (got.sentiment !== c.want) {\n    console.log('Regression on:', c.text)\n  }\n}\n```\n\nStart with five cases that matter, including ones the feature has gotten wrong before. Grow the set each time you find a new failure, the way a test suite grows.\n\nAn AI feature can also degrade silently over time as real-world inputs shift or the model behind it changes. That slow slide is **drift**, and it is why you keep the eval set running instead of checking once.\n\nDrift is only visible if you kept the evidence, so record every model call from day one: what went in, what came back, which model answered, and whether validation failed. That is **LLM tracing**, and a tool built for it like [Langfuse](https://langfuse.com) adds each call's tokens, latency, and cost. Every recorded failure is a free new eval case, and the Operate part turns these traces into alerts when quality slips.\n\n{/* KEEP (added July 2026, user mandate): the money failure mode, which is separate from the wrong-answer failure mode the rest of this chapter covers. Core idea: with a paid model your cost scales with YOUR USERS' usage, not your traffic, so one user, one loop, or one abuser spends your money. Two moves: attribute every call to a user (you already record the call, add the id) and cap per user with a HARD stop. Explicitly say a request-per-minute limit is NOT a cost limit, since that is the trap. Bold-first: quota. Keep the margin line, it is the business point the reader cannot get anywhere else in the book. */}\n\n## Every call spends your money, not theirs\n\nThe other way an AI feature hurts you has nothing to do with wrong answers. Every call your product makes is money you spend on behalf of one user, so your bill grows with how much they use it rather than with how many of them there are.\n\nThat makes one user enough to hurt you. A customer who leaves a tab open, a loop your agent wrote wrong, or somebody who notices your feature is free and expensive to run.\n\nYou are already recording every call for tracing. Record the user with it, and you can answer the two questions that matter: what does one user cost me, and is that less than they pay me.\n\nThen give each account a **quota**, a hard limit on how much it can spend in a period, refused rather than warned about once it is hit. Free accounts get a small one, paying accounts get one sized to their plan.\n\n> **Watch out:** a limit on requests per minute is not a limit on cost. Ten expensive calls a minute, all day, is a bill you did not agree to. Cap the spend, not just the speed.\n\n{/* KEEP: Wrap the call in a timeout (a limit on run time) and a fallback (a safe answer) so a slow or failed model degrades the feature instead of breaking it. Same as resilient external calls (by topic). Mermaid: in-time-and-valid fork to use vs fallback. Holds the prompt + Do this now. */}\n\n## Give it a timeout and a fallback\n\nA model call is a network call to a service that can be slow or down, so it needs the same guardrails as any external call. Put a timeout on it, a limit on how long the call may run, so a slow response cannot hang your feature. Add a fallback, a safe answer for when the call times out, errors, or fails validation.\n\nThe fallback is whatever keeps the feature usable without the model: a cached answer, or an honest message that the smart version is unavailable. A bad model call should degrade the feature, never break it.\n\n```mermaid\n%% caption: A time-boxed, validated call has one safe exit and one fallback, so slow or wrong output never reaches the user.\nflowchart TD\n  Call[Call the model] --> Check{In time and valid?}\n  Check -->|yes| Use[Use the output]\n  Check -->|no| Fall[Fallback response]\n```\n\nThis prompt wraps one AI feature in all three defenses:\n\n```prompt\nAct as a senior AI engineer making one AI\nfeature fail safely, without changing what it\ndoes for the user. Read my spec and my rules\nfile first: the fallback must still honor the\nbehavior and the targets I committed to, and\nthe call stays behind my model adapter.\n\nAdd three layers of defense.\n\n1. Structured output. Make the model return a\n   fixed shape, then validate every response\n   against a schema. Reject or retry anything\n   malformed so it never flows downstream.\n2. An eval. Example inputs with their expected\n   results, plus a script that runs the feature\n   against them, so I catch regressions when I\n   change a prompt or a model. Seed it with\n   cases it has gotten wrong before.\n3. A timeout and a fallback. Bound how long\n   the call may take, and return a safe\n   fallback when it times out, errors, or\n   fails validation.\n\nGive me the failure points first as a short\nlist, then the fix for each. Keep the\nhappy-path behavior identical.\n\nThen record the eval run in my rules file, as\na check that must pass before any prompt or\nmodel change counts as done.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/amplify/making-ai-reliable\n\nThe AI feature to make reliable:\n```\n\n**Do this now:** paste the prompt with your riskiest AI feature, the one whose wrong answer a user would act on, and let your agent wrap it in a schema check, an eval, and a fallback."
          }
        ]
      },
      {
        "id": "debug",
        "title": "Diagnose and fix what the agent breaks",
        "chapters": [
          {
            "slug": "stack-traces",
            "title": "Reading What Broke",
            "label": "Stack Traces",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/stack-traces",
            "content": "---\ntakeaway: Read the error trace\nshare: \"Your app was running, then it crashed and dumped a wall of red text. That wall is a stack trace, a precise map to where and why it broke, and its top and bottom lines point you straight at the fix.\"\nrequires: [running-app, project-folder, ai-agent, terminal-access, editor]\nproduces: [bug-diagnosis]\nteaches: [stack-trace, frame]\nglosses: [cors]\nuses: [ai-coding-agent, prompt, function, library, terminal, http-status-code]\n---\n\n{/* KEEP: lead-in = at the end of the last part the app RAN; a change broke it and it dumped a wall of red text; the reader panics because it looks like a language they do not speak. This chapter gets them to read that wall instead of fearing it. First Debug chapter: something built earlier now broke. */}\n\nAt the end of the last part your app ran. Then you changed one thing, reloaded, and instead of your app you got a wall of red text and a crash. The instinct is panic: it reads like the machine broke in a language you do not speak. That wall is the single most useful thing on your screen right now, and this chapter teaches you to read it.\n\n{/* KEEP: concept = a stack trace is the report a program prints the instant it crashes, newest event first. Not noise, a precise record. Each indented line is a FRAME (one running function + its file/line). Bold-first: stack trace, frame. */}\n\n## What a stack trace is\n\nA **stack trace** is the report a program prints the instant it crashes. It is not noise, and it is not the machine yelling at you. It is a precise record of what the program was doing the moment it failed, printed newest event first.\n\nEach indented line under the message is a **frame**: one function that was running, plus the file and line it was on. Together the frames are the trail of calls that led to the crash, a breadcrumb path back toward the start.\n\n{/* KEEP: read it in two moves. TOP line = the error itself (type + message, WHAT broke). Frames below: each called the one above it; top frame is where it blew up, walk down toward what set it off (the cause). What at the top, why a frame or two down. */}\n\n## Top for the error, bottom for the cause\n\nRead a trace in two moves. The very top line is the error itself: its type and a message saying what went wrong, like reading a value that was not there.\n\nBelow it, each frame called the one above it. The top frame is where the program actually blew up, and walking down the frames traces back toward what set the crash in motion. What broke sits at the top; why it broke is usually a frame or two down.\n\n{/* KEEP: THE technical artifact. Show a real short trace; point out the error line and which frame is the crash site vs the calling path. Then the move that matters: skip library frames, find the FIRST frame naming a file YOU wrote (app/ or src/). Rule-of-thumb callout. */}\n\n## Find the file and line\n\n```\nTypeError: Cannot read properties of undefined (reading 'total')\n    at calculateBalance (app/lib/ledger.ts:42:19)\n    at buildSummary (app/lib/summary.ts:15:22)\n    at Home (app/page.tsx:8:14)\n```\n\nThe top line is the error: something was undefined when the code expected a value. The first frame, `ledger.ts:42`, is where it crashed, so that is the file and line to open first. The frames beneath it show the path that got there, through `summary.ts` and your home page.\n\nMost real traces bury your code under library frames you will never touch. Scan past them for the first line naming a file you wrote, usually under `app/` or `src/`. That is where you look.\n\n> **Rule of thumb:** the top line tells you what broke; the first frame pointing at your own file tells you where.\n\n{/* KEEP: the classifier. Not every wall of red is a trace, and the four a beginner meets first each have a DIFFERENT diagnosis a trace cannot give: HTTP status (which side to debug), CORS (server headers, not the frontend), module not found (install problem), port in use (stale process). Three-column table, what you see / what it means / where to look. Gloss CORS in the cell. */}\n\n## Know which kind of error you are looking at\n\nSome of the red text you will meet is not a stack trace at all, and each kind points somewhere different. Classify it before you paste it:\n\n| What you see | What it usually means | Where to look |\n|---|---|---|\n| A request returns `401` or `404` | The request was wrong: not logged in, or wrong address | The code making the request |\n| A request returns `500` | The server crashed while handling it | The server's own logs, where a real trace waits |\n| \"blocked by CORS policy\" | Your server did not tell the browser it was allowed to answer | The server's headers, never the frontend |\n| \"Cannot find module\" | Something is not installed | Run your install command again |\n| \"address already in use\" | An old copy of your app is still running | Stop that process, the code is fine |\n\nTwo of these are not bugs in your code at all, which is exactly why guessing costs you an afternoon.\n\n{/* KEEP: the fastest fix = copy the WHOLE trace, every line, into your agent. Do NOT summarize or paste only the top line; the frames are the context that finds the cause. Then the senior-voice prompt (expert fixed top, one append slot \"The error and stack trace:\"). */}\n\n## Paste it to your agent\n\nYou do not have to diagnose it alone, and you should not try to. The fastest fix is to copy the entire trace, every line, and hand it to your agent. Do not summarize it and do not paste only the top line: the frames are the context that lets the agent find the real cause fast.\n\nThis prompt turns the trace into a targeted fix instead of a guess:\n\n```prompt\nAct as a senior engineer debugging a crash with me.\nRead the full stack trace below. Identify the top\nline as the error type and message, then walk the\nframes down to the first one that points at a file I\nwrote, not library code. Tell me the exact file and\nline to open, explain in one plain sentence what\nwent wrong there, and give me the smallest fix that\nrespects the conventions and the layer rule in my\nrules file.\n\nDo not refactor anything unrelated. If the real\ncause is in a different frame than where it crashed,\nsay so and why. If the fix would contradict my spec,\nmy API contract, or a decision already recorded,\nstop and tell me before changing a line.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/stack-traces\n\nThe error and stack trace:\n```\n\n**Do this now:** copy the full stack trace from your terminal or browser console and paste it under the prompt. Let your agent point you at the exact file and line."
          },
          {
            "slug": "silent-bugs",
            "title": "When the App Runs but It's Wrong",
            "label": "Silent Bugs",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/silent-bugs",
            "content": "---\ntakeaway: Make an invisible bug visible\nshare: \"Not every bug throws a red wall of text. Often the app runs fine and just does the wrong thing, and this chapter gives you a way to make that invisible bug visible so your agent can fix it.\"\nrequires: [running-app, project-folder, ai-agent, editor]\nproduces: [debug-log]\nteaches: [silent-bug, developer-tools, log, debugger, breakpoint]\nuses: [stack-trace, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the Problem. Not every bug crashes; often the app runs fine and just does the wrong thing (total off, wrong data, dead click). No stack trace to paste, so you are stuck describing a symptom. This chapter gets them a way to make an invisible bug visible. */}\n\nNot every bug throws a red wall of text. Often the app runs fine and just does the wrong thing: the total is off, the wrong name shows, a click does nothing. There is no crash and no trace to paste, so you are stuck describing a symptom your agent cannot see. This chapter gets you a way to make that invisible bug visible.\n\n{/* KEEP: Concept = a silent bug gives you nothing. A crash prints a stack trace (refer to that chapter by topic) pointing at the spot. A silent bug runs to the end and produces a wrong result, with no error pointing anywhere. That absence is why it is harder. Bold-first: silent bug. */}\n\n## Not every bug crashes\n\nA crash is loud. As the stack-trace chapter covered, it prints a report that points straight at the file and line where the code gave up. You have somewhere to look.\n\nA **silent bug** gives you none of that. The code runs all the way to the end and produces a wrong result, so nothing errors and nothing points at the spot. That absence is exactly what makes it harder: there is no red text to follow, only a wrong number on the screen.\n\n{/* KEEP: Step = the evidence exists if you know where. NAME and LINK the developer tools (bold-first, official Chrome DevTools docs), and keep the one-line Safari path, since Inspect does not exist there until it is enabled and a Mac reader is blocked at the chapter's first instruction. Three places: browser console (errors/warnings the page printed), network tab (a request that failed or returned the wrong thing), and the wrong value on screen itself. Use a small table. */}\n\n## Look in the console and the network tab\n\nThe evidence is usually already there, in a part of the browser you have not opened yet: the **developer tools**, the inspector built into every browser. Right-click the page and choose Inspect. On Safari there is no Inspect until you turn it on, under Settings, Advanced, \"Show features for web developers\".\n\nThree places in there tell you most of what you need. [Chrome's own guide](https://developer.chrome.com/docs/devtools) is the reference if you want more than this.\n\n| Place | What it shows |\n| --- | --- |\n| Console | Errors and warnings the page printed |\n| Network tab | A request that failed or returned wrong data |\n| The screen | The actual wrong value, next to what it should be |\n\nOpen all three before you touch the code. A warning in the console or a failed request in the network tab often names the problem outright.\n\n{/* KEEP (added July 2026, user mandate): the tool nobody tells a beginner about, and the one the AGENT needs most because it is the one doing the debugging. A log answers one question you already knew to ask; a debugger lets you stop time and look at everything. Bold-first: debugger, breakpoint. Say plainly that you connect it to the agent as a tool, but do NOT use the term MCP, that is taught much later in the Automate part. Links must be official and curl-verified. Production caveat is not optional: pausing a live process freezes real users. */}\n\n## Give your agent a real debugger\n\nA log answers one question you already knew to ask. When you do not know which question, you want the tool nobody tells beginners about.\n\nA **debugger** stops your program mid-run and lets you look around. You set a **breakpoint**, a marked line where execution pauses, then step forward one line at a time and inspect every value in scope, without adding a single print. Your editor has one built in already: [VS Code's debugger](https://code.visualstudio.com/docs/editor/debugging) covers most languages, and [Node](https://nodejs.org/api/debugger.html) ships its own underneath.\n\nThe part that matters here is that this is a tool you hand to your agent, not just to yourself. Your agent is the one doing the debugging, and by default it is working blind, guessing from source code and asking you to paste output back. Connected to a debugger it can set its own breakpoints, run to them, and read the actual values, which is the difference between a theory and an observation. [DebugMCP](https://github.com/microsoft/DebugMCP) is one way to connect it, and [Chrome DevTools](https://developer.chrome.com/docs/devtools/agents/get-started) does the same for anything happening in a browser.\n\n> **Watch out:** never attach a debugger to production. A breakpoint pauses the process, which means it freezes real customers mid-request, and everything in scope at that moment is visible to whoever is looking. Debug locally or against staging; in production your logs are the evidence.\n\n{/* KEEP: Step = the core move. Ask your agent to add a log line (or a few) at the suspect spot, run it, read what the values ACTUALLY are, see where reality diverges from what you expected. Real artifact = a tiny console.log / print example. Bold-first: log. */}\n\n## Add a log to see what's happening\n\nWhen nothing on the surface explains it, the core move is to add a **log**: a line that prints a value so you can watch what the code actually holds. You ask your agent to drop one at the suspect spot, run it, and read the result.\n\nHere is what one looks like, in JavaScript and in Python:\n\n```\nconsole.log('cart total before discount:', total)\n\nprint('cart total before discount:', total)\n```\n\nRun it, and the real value prints where you can see it. If you expected 90 and it prints 100, you have found the exact point where reality diverges from what you assumed.\n\n```mermaid\n%% caption: A log turns an invisible value into something you can read.\nflowchart LR\n  SPOT[Suspect spot] --> LOG[Add a log line]\n  LOG --> RUN([Run it])\n  RUN --> REAL[Real value prints]\n  REAL --> DIFF([See where it diverges])\n```\n\n{/* KEEP: Step + Action = give the agent the OBSERVATION, not the symptom. Not \"it's broken\" but the real values and output you captured. Concrete evidence breaks the guessing loop (refer to agent-loops chapter by topic). Then the senior-voice prompt (expert top, one append slot). Do this now. */}\n\n## Hand the agent the observation, not the symptom\n\n\"It's broken\" or \"the total is wrong\" gives your agent nothing but your guess. It will guess back, and you both circle. A loop like that only breaks when you feed in something concrete, which is exactly what the next chapter is about.\n\nThe something is what you just captured: the failed request, the console warning, the value your log printed versus the value you expected. Hand that over and the agent stops guessing and starts tracing.\n\n```prompt\nAct as a senior engineer helping me find a bug\nthat does not crash. The app runs, but it produces\nthe wrong result. Do not guess at the cause yet.\n\nFirst read my spec, so you know what correct looks\nlike, and my architecture map, so you know which\nlayer owns this value.\n\nThen tell me where to look: what to check in the\nbrowser console, what to look for in the network\ntab, and which value on screen to compare against\nwhat I expected. Name the most likely spot in the\ncode and give me one log line to add there so I\ncan see the real value. When I paste back what it\nprinted, use that observation to find the cause and\ngive me the smallest fix. Work from the evidence I\ncapture, not from a guess.\n\nIf a rule would have prevented this bug, add it to\nmy rules file.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/silent-bugs\n\nThe wrong behavior and what I expected instead:\n```\n\n**Do this now:** open the console and network tab on the page that misbehaves, paste the prompt with what you see, and add the one log line your agent gives you to turn the invisible bug into a value you can read."
          },
          {
            "slug": "agent-loops",
            "title": "When Your Agent Goes in Circles",
            "label": "Loops",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/agent-loops",
            "content": "---\ntakeaway: Break the retry loop\nshare: \"Your agent insists it fixed the bug, hands you the same error, and quietly undoes its own work. Learn to catch that retry loop in the first two rounds and break it with the one fact it is missing.\"\nrequires: [running-app, project-folder, ai-agent]\nproduces: [ranked-diagnosis]\nteaches: [retry-loop]\nuses: [ai-coding-agent, context, context-window, prompt, model]\n---\n{/* KEEP: lead-in = the agent claims it fixed the bug, the same error returns, it reapplies and later reverts its own edit; it is going in circles and burning the session. This chapter = catch the loop early and break it. */}\n\nYour agent says it fixed the bug. You run it, the same error comes back. It says it sees the real problem now, changes the file, and hands you the same error again.\n\nTwenty minutes later it is undoing the edit it made ten minutes ago. This chapter teaches you to catch that circling early and break it before it eats your whole session.\n\n{/* KEEP: concept = define retry loop; the tell is repetition (same edit made/reverted/reapplied, same error unchanged, confident \"now it is fixed\" that is not). Real artifact: a short transcript sketch of the loop. Bold-first: retry loop. */}\n\n## Recognize a retry loop\n\nA **retry loop** is when the agent keeps shipping variations of the same broken fix, each time sure it has it. The tell is repetition:\n\n- the same edit made, reverted, and reapplied\n- the same error message coming back unchanged\n- a confident \"now it is fixed\" that is not\n\nCatch it by the second round, not the fifth. It usually reads like this:\n\n```\nYou: still failing, same TypeError.\nAgent: I see the issue now. Fixed it.\nYou: same TypeError.\nAgent: You're right, the real fix is here. Done.\nYou: same TypeError.\nAgent: I see the issue now...   <- you are in a loop\n```\n\n```mermaid\n%% caption: The retry loop: the same broken fix keeps circling back unchanged.\nflowchart TD\n  A[1. Agent says fixed] --> B([2. You run it])\n  B --> C{Same error?}\n  C -->|yes| D[3. Agent re-edits]\n  D --> A\n  C -->|no| E([Bug gone])\n```\n\n{/* KEEP: why = not laziness; it lost the thread. Window is full of its own failed attempts so it pattern-matches on those, or it has a wrong mental model that one missing fact would break. Cross-ref the context chapter (poisoned context) by topic, do NOT re-teach reset here. */}\n\n## Why the agent goes in circles\n\nIt is not being lazy. It lost the thread. The window is now full of its own failed attempts, so it keeps pattern-matching on those instead of the real cause. Those are the same dead ends you saw poison a drifting session in the chapter on managing what the agent sees.\n\nThe other cause is a wrong mental model. It is reasoning from one false assumption that nothing in the chat corrects, so every fix is internally sensible and still wrong.\n\n{/* KEEP: break = stop it before the next attempt; then do one of two things: hand it the missing fact or force a fresh diagnosis before any edit. The missing fact is usually something only you can see (real console error, actual variable value, the file that runs is not the one it edits). */}\n\n## Break the loop\n\nStop it before the fourth attempt. Then do one of two things: hand it the fact it is missing, or force a fresh diagnosis before it touches a single line.\n\nThe missing fact is usually something only you can see. The real error in the browser console. The actual value of a variable. Or that the file it keeps editing is not the file that runs.\n\nOne such fact ends more loops than ten more retries.\n\n```mermaid\n%% caption: Break a loop by feeding the missing fact, or resetting once it has already churned.\nflowchart TD\n  S([Same error twice]) --> STOP[Stop the agent]\n  STOP --> Q{Churned three attempts?}\n  Q -->|no| FACT[Hand it the missing fact]\n  Q -->|yes| FRESH[Fresh session]\n  FRESH --> DIAG[Ranked diagnosis first]\n  FACT --> DIAG\n```\n\n{/* KEEP: reset = after three churned attempts the window carries all of them, so one more message rarely helps; start a fresh session (point to the context chapter, do not re-teach) and open with the fact + a clean ask. Then the copy-paste prompt that asks for a ranked fresh diagnosis before any edit. */}\n\n## Reset the context and retry\n\nIf it has already churned through three attempts, the window is carrying every one of them, and one more message rarely pulls it out. Start a fresh session, the way the context chapter describes, and open with the missing fact plus a clean ask.\n\nThis prompt forces a ranked diagnosis before any edit, which is what actually breaks the loop:\n\n```prompt\nAct as a senior engineer taking over a stuck\ndebugging session. The previous attempts all\nfailed. Ignore them. Do NOT edit anything yet.\n\nRead my rules file and the architecture map in\nit first, so you reason about where this code\nactually lives instead of guessing.\n\nThen state the top three things that could\ncause this, ranked by likelihood. For each,\nname the ONE observation that would confirm\nor rule it out, and tell me how to get it.\n\nDo not propose a fix until one cause is\nconfirmed. If the cause turns out to be a\nchoice my rules file or spec already made, say\nso rather than quietly changing it. If you\ncannot explain why the last fix failed, say so\ninstead of guessing.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/agent-loops\n\nWhat it keeps failing to do:\n```\n\n**Do this now:** next time the same error returns twice, stop the agent, open a fresh session, and paste this prompt with the one fact only you can see."
          },
          {
            "slug": "bisecting",
            "title": "Finding What Broke It",
            "label": "Bisecting",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/bisecting",
            "content": "---\ntakeaway: Find the breaking change\nshare: \"A bug appears and dozens of changes have landed since it last worked. Instead of reading every one, halve the history: git bisect walks you to the exact change that broke it in a handful of tests.\"\nrequires: [git-repo, project-folder, running-app, terminal-access, ai-agent]\nproduces: [first-bad-commit]\nteaches: [bisect]\nglosses: [head]\nuses: [git, commit, diff, test, dependency]\n---\n{/* KEEP: lead-in = something worked last week, is broken now, and many changes landed since. Reading each one is hopeless. This chapter: get to the exact change fast by halving the search, not walking it. */}\n\nSomething that worked last week is broken now, and dozens of changes have landed since. Reading every one to find the guilty change would eat your whole day, and staring at the current code tells you nothing about when it went wrong. This chapter gets you to the exact change that broke it, fast, by halving the search instead of walking it.\n\n{/* KEEP: concept = binary search over history. Two markers: a point where it worked (good) and a point where it is broken (bad, usually now). Test the midpoint, throw away half the suspects. Bold-first: bisect. */}\n\n## Find when it last worked\n\nYou need two markers: a past point where the feature worked, and a point where it is broken, usually right now. Every change between them is a suspect.\n\nInstead of checking each suspect in order, check the one in the middle. Is the bug there or not? That single test tells you which half to throw away.\n\nTo **bisect** is to cut the range in two, test the midpoint, and keep only the half that still contains the break. A hundred suspects fall to seven tests.\n\n```mermaid\n%% caption: Each test halves the suspects until a single bad commit is left.\nflowchart TD\n  R([1. Range of suspects]) --> T{2. Bug at midpoint?}\n  T -->|no| L[3a. Keep newer half]\n  T -->|yes| E[3b. Keep older half]\n  L --> M{4. More than one left?}\n  E --> M\n  M -->|yes| T\n  M -->|no| B([5. First bad commit])\n```\n\n{/* KEEP: step = git bisect automates the bookkeeping. You give one good commit and one bad, it checks out the midpoint for you. Link official git bisect docs. WHY it lands on a readable diff: small green commits (ref small-steps chapter by topic), do not re-teach committing. */}\n\n## Narrow it with git\n\nGit does this bookkeeping for you with [git bisect](https://git-scm.com/docs/git-bisect). You hand it one commit where the feature worked and one where it is broken. It then checks out the midpoint for you to test, over and over, until one change is left.\n\nThis is where committing in small green slices pays off. Because each saved step did one thing, the change bisect lands on is a short, readable diff, not an afternoon of braided edits you cannot untangle.\n\n{/* KEEP: step = the mechanics, mark each checkout good/bad, git narrows. Three preconditions FIRST, the ones that break a beginner's first bisect: uncommitted changes block the start, dependencies may need reinstalling per checkout, and git bisect skip exists for a checkout that will not run at all. Then the REAL artifact: a full session converging from many suspects to one culprit. Gloss HEAD here, it is defined nowhere else in the book. */}\n\n## Halve the history each time\n\nThree things trip up a first bisect, so clear them before you start:\n\n- Git refuses to begin with uncommitted changes, so save or stash your work first.\n- A checkout from weeks ago may need its dependencies reinstalled before the app will even start, because `package.json` changed in between.\n- Some checkouts will not run at all, for reasons unrelated to your bug. That is what `git bisect skip` is for.\n\nThen you start it, mark each checkout `good` or `bad`, and git narrows the range every time until it stops on the culprit. You mark today's broken state with **HEAD**, git's name for the commit you are sitting on right now.\n\n```bash\n$ git bisect start\n$ git bisect bad HEAD\n$ git bisect good a1b2c3d\nBisecting: 6 revisions left to test after this\n[e4f5a6b] feat: cache the user profile\n\n# test the app... bug is gone here\n$ git bisect good\nBisecting: 3 revisions left to test after this\n[a0b1c2d] chore: bump the build tool\n\n# this one will not even start, so skip it\n$ git bisect skip\nBisecting: 2 revisions left to test after this\n[b7c8d9e] refactor: reuse the fetch helper\n\n# test again... bug is back\n$ git bisect bad\nBisecting: 1 revision left to test after this\n[c9d0e1f] fix: trim the search input\n\n# test... still broken\n$ git bisect bad\nc9d0e1f is the first bad commit\n```\n\n{/* KEEP: step = git names the first bad commit, the exact change. Open its diff, it is a small slice you can read. Then git bisect reset to return. git bisect run <script> automates the testing. Prompt + Do this now. */}\n\n## Land on the bad change\n\nGit prints the first bad commit: the exact change that introduced the break. Open its diff and the cause is a handful of lines you can actually read, not a needle in the whole codebase. When you are done, run `git bisect reset` to return to where you started.\n\nIf testing each step by hand is tedious, hand the whole hunt to your agent:\n\n```prompt\nAct as a senior engineer running git bisect to find\nthe change that broke a feature. Read the evidence I\nalready captured on this bug first, so we do not\nre-derive it. Then walk me through it:\n- Confirm the bug is present now (bad), and pick a\n  past commit where it worked (good).\n- Check I have no uncommitted work, then start the\n  bisect, mark that commit good and HEAD bad, and\n  tell me exactly what to test each step.\n- After I report good or bad, give the next command\n  until we land on the first bad commit. If a\n  checkout will not build or run at all, tell me to\n  git bisect skip it instead of guessing.\n- If the check can be scripted, reuse a command I\n  already run and put it under git bisect run.\n- End by showing the culprit's diff, then run\n  git bisect reset. If it broke a rule my rules\n  file does not yet state, give me that one line\n  to add.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/bisecting\n\nWhat broke and when it last worked:\n```\n\n**Do this now:** on your next mystery bug, start a bisect with a known-good commit and today's HEAD, and let it walk you to the first bad commit."
          },
          {
            "slug": "verifying-fixes",
            "title": "Is It Actually Fixed?",
            "label": "Verification",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/verifying-fixes",
            "content": "---\ntakeaway: Confirm it's really fixed\nshare: \"Your agent says the bug is fixed and the app still runs, but that is a claim, not proof. This chapter gets you to prove it: reproduce the bug, confirm the change kills the root cause instead of hiding the symptom, re-run the exact case that failed, and check nothing else broke.\"\nrequires: [running-app, project-folder, ai-agent, bug-diagnosis]\nproduces: [repro-steps, verified-fix]\nteaches: [repro, symptom, root-cause, regression]\nuses: [ai-coding-agent, prompt, test]\n---\n{/* KEEP: lead-in = the Problem. \"Fixed\" is a claim, not proof; the app still running is not the same as the bug being dead. You never watched it die. This chapter gets the reader to prove a fix is real before trusting it. */}\n\nYour agent reads the error, changes a few lines, and reports the bug fixed. The app still runs, so it is tempting to believe it and move on. But \"fixed\" is a claim, and a claim is not proof: you never watched the bug actually die. This chapter gets you to prove a fix is real before you trust it.\n\n{/* KEEP: Concept + first step = you cannot confirm a fix you were never able to make fail. Reproduce the bug first, run the exact steps/input, watch it break. Bold-first **repro**. If the agent jumped to a fix with no repro, it was guessing. Rule-of-thumb callout: watched it fail, then watched it pass. */}\n\n## Reproduce before you trust the fix\n\nYou cannot confirm a fix you were never able to make fail. Before you trust anything, reproduce the bug yourself: run the exact steps, or feed the exact input, that triggered it, and watch it break. That gives you a **repro**, the precise steps that force the bug to happen, and it is the one case that proves the fix later.\n\nIf the agent jumped straight to a fix without a repro, it was guessing at the cause. Make it show you the bug first, then the fix.\n\n> **Rule of thumb:** you have not fixed a bug until you have watched it fail, then watched the same steps succeed.\n\n{/* KEEP: Concept = a bug is a symptom of a deeper cause. Fast wrong move = silence the symptom (swallow the error, return a safe default, special-case the one input). Bold-first **symptom** and **root cause**. The real artifact: before/after code contrasting a symptom-hiding patch vs a root-cause fix. */}\n\n## A real fix, not a hidden symptom\n\nA bug is a **symptom** of a deeper cause. The fast, wrong move is to silence it: swallow the error, return a safe-looking default, or special-case the one input that broke. The app stops complaining, and the real defect stays in, waiting for the next input.\n\nA **root cause** fix changes why the bug happened, so the same kind of input can never trigger it again. The difference shows in the code.\n\n```js\n// Symptom hidden: crash gone, wrong total stays.\nfunction lineTotal(item) {\n  try {\n    return item.price * item.qty\n  } catch {\n    return 0\n  }\n}\n```\n\n```js\n// Root cause: a deleted product left a dead id in\n// the cart. Drop dead ids when the cart loads, so\n// every item is real before we price it.\ncart = cart.filter(item => productExists(item.id))\n```\n\n{/* KEEP: Step = re-run the EXACT repro, unchanged, not something similar. Same steps that failed before. If it passes for the reason the fix claims, the bug is dead. If you changed the input to make it pass, you tested a different bug. */}\n\n## Test the exact case that failed\n\nNow re-run the exact repro from the first step, unchanged. Not something similar, the same steps that failed before. If it now behaves correctly, and for the reason the fix claims, the bug is dead.\n\nIf you quietly changed the input to make it pass, you tested a different bug and left the original one alive.\n\n{/* KEEP: Step = regression. A fix edits code other features rely on, so it can break something that worked. Bold-first **regression**. Re-run the neighbors: same feature, inputs on either side, the screen it lives on. Forward pointer: automated tests come later in Harden; here, checking neighbors by hand is enough. Do NOT deep-dive test suites. */}\n\n## Check nothing else broke\n\nA fix edits code that other features rely on, so it can break something that was working a minute ago. That is a **regression**: new damage caused by the change itself, not by the original bug. The fix is not done until you have looked for it.\n\nRe-run the things nearest the change: the same feature, the inputs just on either side of the one that broke, the screen it lives on. Doing this by hand every time does not scale, which is why later, when you harden the app, your agent builds automated tests that re-check everything on each change. For one fix, checking the neighbors yourself is enough.\n\n```mermaid\n%% caption: Proving a fix: reproduce it, confirm the root cause, re-run the exact case, check the neighbors.\nflowchart LR\n  R[Reproduce the bug] --> W([Watch it fail])\n  W --> RC{Root cause or symptom?}\n  RC -->|symptom| BACK[Find the real cause]\n  RC -->|root cause| RE[Re-run exact case]\n  RE --> P([Watch it pass])\n  P --> REG[Check the neighbors]\n```\n\nRun all four as one command, and make the agent do the proving, not the promising:\n\n```prompt\nAct as a senior engineer verifying a fix before it\nships, not the one who wrote it. Be skeptical.\n\nStart from my debug log and the diagnosis already\nwritten for this bug, not a fresh theory.\n\n1. Reproduce the original bug first: state the\n   exact steps or input that triggered it, and\n   confirm it truly failed before the change. If\n   you cannot reproduce it, say so and stop.\n2. Judge root cause vs symptom: does this change\n   fix why the bug happened, or does it hide the\n   failure (a swallowed error, a guard that\n   returns a wrong value, a special case for one\n   input)? If it hides it, name the real cause.\n3. Re-run the exact case that failed and confirm\n   it now passes for the right reason.\n4. Check for regressions: what nearby behavior or\n   input could this change have broken? Name the\n   cases to re-test, and flag any fix that reaches\n   across a module boundary.\n\nReport each step's result plainly. If the fix is\nnot proven, say what is missing. Do not rewrite\nthe code, only verify it. Once it is proven, add\nthe repro steps to my debug log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/verifying-fixes\n\nThe bug and the fix to verify:\n```\n\n**Do this now:** take the last bug your agent fixed, reproduce it from before the change if you still can, then paste the prompt with that bug and fix so the agent proves it root-cause dead, not just quiet."
          },
          {
            "slug": "rollback",
            "title": "Reverting Safely",
            "label": "Rollback",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/rollback",
            "content": "---\ntakeaway: Revert without losing work\nshare: A change made things worse and you cannot fix it fast. Learn to undo the one bad change without losing the good work you did after it, and to judge when to roll back instead of patching forward.\nrequires: [git-repo, project-folder, running-app, ai-agent, terminal-access]\nproduces: [revert-commit]\nteaches: [revert, fix-forward, rollback]\nuses: [git, commit, branch, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = a change made things worse, you cannot fix it fast, and you did real work after it you do not want to lose. This chapter: undo the one bad change, keep the rest, land on a version that runs. */}\n\nYou changed something and the app got worse, not better. You have poked at it for twenty minutes and it is still broken. You have also done real work since that change, work you do not want to throw away. This chapter gets you out clean: undo the one bad change, keep everything else, and land back on a version that runs.\n\n{/* KEEP: concept = undoing is not all-or-nothing; history is a line of saved snapshots and you can lift out exactly one without touching the rest. The trap is deleting an hour to kill a five-minute mistake; you never pay that. */}\n\n## Undo without losing unrelated work\n\nUndoing a bad change does not mean throwing away the good work you did after it. Your history is a line of saved snapshots, and you can lift out exactly one of them while the rest stay put.\n\nThe trap is treating undo as all-or-nothing: deleting the last hour to kill one five-minute mistake. You never have to pay that price. Point your agent at the single change that broke things and leave everything else standing.\n\n{/* KEEP: step = define revert (a new commit that cancels one specific past commit, nothing else); adds to history, does not erase, so later work stays. Artifact = git revert <hash>; contrast the safe revert with the dangerous git reset --hard that wipes everything after. Bold-first: revert. Link git-revert + git-reset. */}\n\n## Revert the one change\n\nA [**revert**](https://git-scm.com/docs/git-revert) is a new commit that cancels out one specific past commit and nothing else. The work you did after the bad change stays exactly where it is, because you are adding to history, not erasing it.\n\nYour agent runs it against the commit that caused the trouble:\n\n```bash\ngit revert a1b2c3d\n```\n\nContrast that with the bulldozer. A hard [reset](https://git-scm.com/docs/git-reset) back to the last good commit throws away every change since, including the unrelated work you want to keep:\n\n```bash\ngit reset --hard 9f8e7d6   # deletes ALL work after 9f8e7d6\n```\n\nRevert is surgical and safe to run. A hard reset destroys history, so it is the move you almost never want here.\n\n```mermaid\n%% caption: Revert cancels just the bad commit; a hard reset destroys every change after it.\nflowchart TD\n  Q{How to undo the bad change?} -->|revert| R[New commit cancels it]\n  R --> RK([Later work kept])\n  Q -->|hard reset| H[Roll history back]\n  H --> HW([Later work destroyed])\n```\n\n{/* KEEP: step = sometimes you do not need surgery, just stop the bleeding and get onto the last version that ran. Branch path: throw away the broken experiment branch, main is untouched. On main: revert the last commit. Goal = a version that runs right now so you can think clearly. */}\n\n## Get back to a working state\n\nSometimes you do not need surgery, you need to stop the bleeding. If the last few changes are tangled and you cannot say which one broke things, get back onto the last version you know ran, then move forward from there.\n\nIf the work was on its own branch, the cleanest path is to throw that branch away and return to main, which never felt the damage. If the mess is already on main, revert the last commit to land back on solid ground without erasing anything.\n\nEither way the goal is the same: a version that runs right now, so you can think clearly instead of debugging in a panic.\n\n```mermaid\n%% caption: Where the mess lives decides the exit: drop a bad branch, or revert the last commit on main.\nflowchart TD\n  M([Tangled changes]) --> Q{On a branch or on main?}\n  Q -->|own branch| DROP[Throw the branch away]\n  DROP --> SAFE([Main untouched])\n  Q -->|on main| REV[Revert the last commit]\n  REV --> GREEN([Back on solid ground])\n```\n\n{/* KEEP: step = the judgment call. Fix forward = leave the change in, patch on top. Roll back = undo now, retry later calm. Rule is about time and understanding, not pride: one-line fix you know -> fix forward; stuck or do not understand it -> roll back to green first. Bold-first: fix forward. Decision table. */}\n\n## Roll back vs fix forward\n\nEvery broken change forces one call: roll back or fix forward. **Fix forward** means leaving the change in and patching the problem on top. Roll back means undoing it now and retrying later with a clear head.\n\nThe rule is about time and understanding, not pride.\n\n| The change... | Do this |\n| --- | --- |\n| broke in a way you understand, one-line fix | Fix forward |\n| has you stuck, or you cannot explain why | Roll back |\n| left you debugging in a panic | Roll back, then diagnose |\n\n{/* KEEP: prompt (senior-engineer voice, fixed content + one append slot \"The bad change I need to undo:\"). Agent finds the exact bad commit, reverts ONLY it, never hard-resets away later work, gets back to the last running commit if tangled, confirms the app runs, advises fix forward vs retry. Do this now = paste it. */}\n\n## Hand the undo to your agent\n\nWhen a change goes bad, hand the cleanup to your agent with clear rules:\n\n```prompt\nAct as a senior engineer doing damage control.\nA recent change made things worse and I need it\nundone safely. Read my repro steps and the\ndiagnosis I already wrote before you touch git.\nRules:\n- Find the exact commit that caused the problem.\n- Undo ONLY that commit with a revert, a new\n  commit that cancels it out. Never hard-reset\n  or delete work I did after the bad change.\n- If several recent changes are tangled, get me\n  back to the last commit that ran, and tell me\n  which one that is.\n- Run my quality gate and confirm the app works\n  again before we move on, then advise: fix\n  forward now, or roll back and retry later.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/rollback\n\nThe bad change I need to undo:\n```\n\n**Do this now:** the next time a change makes things worse, paste the prompt above with that change, and let your agent revert just that one commit instead of throwing away your afternoon."
          },
          {
            "slug": "getting-unstuck",
            "title": "Getting Unstuck",
            "label": "Escalation",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/debug/getting-unstuck",
            "content": "---\ntakeaway: Know when to take over\nshare: \"You can loop with an agent forever on a bug it will never solve. This chapter gives you the judgment to know when to stop it, step in yourself, ask a human, or accept the problem is beyond the tool for now.\"\nrequires: [running-app, project-folder, ai-agent, git-repo, editor]\nproduces: [root-cause-hypothesis]\nteaches: [hypothesis, minimal-reproduction]\nuses: [retry-loop, rollback, context, ai-coding-agent, prompt, library, stack, repro]\n---\n{/* KEEP: lead-in = the Problem. You have gone in circles on the same bug; the agent keeps trying, each attempt sounds confident, none work. The hard skill is knowing when to STOP letting it try. This chapter gives that judgment: stop, step in, ask a human, or accept it is beyond the tool for now. */}\n\nYou have been going in circles with your agent on the same bug for an hour. It keeps trying, each attempt sounds just as confident as the last, and none of them work. The hard skill here is not another fix, it is knowing when to stop letting the agent try. This chapter gives you that judgment: when to take over, when to call a human, and when to accept the problem is beyond the tool for now.\n\n```mermaid\n%% caption: The escalation ladder: stop the agent, step in, ask a human, then call a pro.\nflowchart TD\n  L([Stuck in circles]) --> S[1. Stop the agent]\n  S --> ST[2. Step in and narrow]\n  ST --> Q{Still stuck?}\n  Q -->|no| DONE([Unstuck])\n  Q -->|yes| H[3. Ask a human]\n  H --> Q2{High stakes?}\n  Q2 -->|yes| PRO[4. Call a professional]\n  Q2 -->|no| RETRY[4. Roll back, retry later]\n```\n\n{/* KEEP: Concept = the point of diminishing returns. An agent has no meta-sense that it is failing; that judgment is yours. Recognize the three signals: it has looped, its context is poisoned, it is guessing. Real artifact = the \"stop and take over\" checklist. */}\n\n## When to stop the agent\n\nAn agent has no sense that it is failing. It will cheerfully attempt the same broken idea a tenth time, because nothing in it tracks that the last nine did not work. That meta-judgment is yours, and noticing the point of diminishing returns is the whole job here.\n\nWatch for three signals. It has looped over the same two or three fixes, its context is now full of dead ends so it contradicts itself, or it has stopped reasoning and started guessing. When you see them, stop. Another attempt only buries the real signal deeper.\n\n```\nStop and take over when:\n[ ] The same error survives three or more attempts\n[ ] Each fix trades one error for a new one\n[ ] It changes lines at random, not by reason\n[ ] It contradicts what it said a few messages ago\n[ ] It edits files you never asked it to touch\n[ ] You no longer understand what it is doing\n```\n\n{/* KEEP: Step = you take over, but you do not have to fix it all. Read the actual code around the failure, form a hypothesis (bold-first, glossed = a specific testable guess at the cause), then hand the agent ONE smaller precise task. Reference retry-loop chapter for the fresh context. Rule-of-thumb callout: narrow, do not solve. */}\n\n## Step in yourself\n\nTaking over does not mean writing the fix by hand. It means reading the actual code around the failure yourself, so you stop guessing along with the agent. A fresh **hypothesis**, a specific and testable guess at the cause, is usually the exact thing a stuck agent is missing.\n\nThen hand it back a much smaller task. Not \"fix the login,\" but \"the token is null here, check whether it is set before this line runs.\" As the retry-loop chapter covered, starting the agent clean on that narrow task often breaks a loop nothing else could.\n\n> **Rule of thumb:** when you step in, your job is to narrow the problem, not to solve it. A smaller, precise task is usually all the agent needed.\n\n{/* KEEP: Step = some problems need a person, not the tool. When you and the agent are both out of ideas, ask a real human at the library's own issue tracker, Stack Overflow, or a community for your stack. Bring the specific error and what you tried. Someone has hit it before. Also bring a MINIMAL REPRODUCTION (smallest snippet that still fails, agent does the stripping from the existing repro); without one you get ignored, and minimizing usually finds the cause before anyone answers. Bold-first: minimal reproduction. */}\n\n## When to ask a human\n\nSometimes both of you are out of ideas, and the answer only lives in a person's head. Bring the specific error and what you already tried to where the experts are: the library's own issue tracker on [GitHub](https://github.com), [Stack Overflow](https://stackoverflow.com), or a community for your stack.\n\nBring one more thing, or you will be ignored: a **minimal reproduction**, the smallest file or snippet that still shows the failure, with everything else stripped out. Have your agent do the stripping, cutting one piece at a time from the repro you already have and re-running until only the failure is left.\n\nDo it even when you never post it. Minimizing finds the cause more often than the answer does, because the piece you remove that makes the bug disappear is the piece that caused it.\n\n{/* KEEP: Step + Action bridge = a few problems are genuinely beyond the tool for now, and naming that is judgment, not defeat. Where the cost of getting it wrong is high (money, user data, security, data loss), an hour of a real professional is cheap insurance. Funnels to calling a pro. Roll back first (rollback chapter) so you are not stuck AND broken. Then the diagnosis prompt + Do this now. Closing nods that unsticking a build is what lets you carry it into hardening, no re-teaching. */}\n\n## Know when it's beyond the tool\n\nA few problems are genuinely beyond what the tool does well right now, and saying so is judgment, not defeat. Sometimes the cost of getting it wrong is high: real money, user data, security, or work you cannot afford to lose. There, an hour of an actual professional is cheap insurance against a very expensive mistake.\n\nBefore you burn a day on any hard bug, roll back to the last working state, as the rollback chapter showed, so you are never both stuck and broken. Then, when you do take over, make the agent hand you a clean diagnosis instead of one more guess:\n\n```\nStop trying to fix this. Step back and act as a\nsenior engineer doing a fresh diagnosis. Treat\nevery fix we already tried as noise; it failed.\nBased only on the evidence below, state in plain\nwords the single most likely root cause, and why.\nIf you are unsure, say what you do not know and\nwhat one piece of information would settle it.\nThen propose the smallest experiment to confirm\nor kill that theory: one change, one thing to\nobserve, nothing more. Do not write the full fix.\n\nWhere I'm stuck:\n```\n\nWhen the checklist trips, this prompt forces one clean theory instead of another guess:\n\n```prompt\nAct as a senior engineer taking over a stuck debugging\nsession. Do not attempt a fix yet. Read my debug log,\nmy repro steps, and the architecture map in my rules\nfile first.\n\nRestate what is actually broken in one sentence, in\nterms of what the user sees, and what my spec says\nshould happen instead. Then list what we have already\ntried and what each attempt ruled out.\n\nThen give me your single most likely cause, the one\ncheapest observation that would confirm or kill it,\nand what you would try next if it is killed. If the\nevidence supports no single theory, say so and tell me\nwhat to capture instead.\n\nAppend the theories you ruled out to my debug log, so\nwe never retest them.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/debug/getting-unstuck\n\nThe bug, and everything we have tried so far:\n```\n\n**Do this now:** take the bug you are most stuck on and run the stop-and-take-over checklist against it. If it trips, paste the prompt above to get one clean theory instead of another guess, then carry the fix forward."
          }
        ]
      },
      {
        "id": "test",
        "title": "Prove it works, and keep it working",
        "chapters": [
          {
            "slug": "testing-and-qa",
            "title": "When AI Writes the Code",
            "label": "Why Test",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/testing-and-qa",
            "content": "---\ntakeaway: Test before users do\nshare: 'The agent swears the feature works, and it does, until a user does the one thing you never tried. Automated tests are the net that catches that before a real person does.'\nrequires: [running-app, ai-agent, first-feature]\nproduces: [test-suite]\nteaches: [test, critical-path, end-to-end-test, regression]\nglosses: [unit-test]\nuses: [ai-coding-agent, prompt, unit-test, function]\n---\n{/* KEEP: lead-in = the agent says it works and it does on the happy path, but a user hits the case you never tried. Tests are the net that catches it first. When AI writes most of the code, tests are how you (and the agent) know it still works. Distinct from verifying-fixes (one fix); this is a standing safety net. */}\n\nThe agent tells you the feature works, and it does, right up until a real user does the one thing you never thought to try. You cannot click through every path by hand on every change, and when the agent rewrites something next week, you will not remember what to re-check. This chapter gives you the net that catches a break before a user does.\n\n{/* KEEP: a test = code that runs your app and checks it did the right thing, automatically. It is worth most exactly when AI writes the code, because it is how you AND the agent know a change did not break what worked. Machines re-check tirelessly; you do not. Bold-first: test. Also state the opinion: testing is the invest-from-day-one exception, you defer CI but you do NOT defer tests; reference the start-small-but-invest-early principle BY TOPIC. */}\n\n## Tests are your safety net\n\nA **test** is a small piece of code that runs part of your app and checks it did the right thing, without you clicking anything. It matters most precisely because the agent writes the code: a test is how both of you know a new change did not quietly break what already worked.\n\nYou cannot re-check everything by hand, and you will not want to. A machine re-checks every path on every change and never gets bored.\n\nThis is the one thing you invest in from day one, not something you grow into. You can deploy from your own machine, and you can add **continuous integration**, automatic test runs on every push, later.\n\nTests are the deliberate exception, so start on day one, even with a thin near-empty scaffold. Adding a test onto an existing habit is easy, while retrofitting tests into an untested app is brutal. That is the start-small-but-invest-early rule, applied to the one place skipping it hurts most.\n\n{/* KEEP: don't test everything, test what would hurt most if it broke: the critical paths (log in, pay, save the thing). Cover those first; the login-and-checkout flow earns a test long before a settings toggle. Bold-first: critical path. */}\n\n## Cover the critical paths first\n\nDo not try to test everything. Test what would hurt most if it broke. The **critical paths** are the few flows your app exists for: a user logs in, saves their work, pays.\n\nCover those first and you have protected the parts that lose customers when they fail. A checkout flow earns a test long before a settings toggle does.\n\n{/* KEEP: the agent writes the tests; you say what to check, it writes them, and it can run them itself before declaring a task done (ties to guardrails/rules by topic). Show a real tiny test artifact. Name a real tool + link official. Bold-first: end-to-end. */}\n\n## Let the agent write and run them\n\nYou do not hand-write these. You tell the agent the behavior to protect and it writes the test, then runs it on every change. A quick one for a single function, an **end-to-end** test (with a tool like [Playwright](https://playwright.dev)) to drive the whole flow like a user:\n\n```ts\ntest(\"a user can log in\", async ({ page }) => {\n  await page.goto(\"/login\");\n  await page.fill(\"#email\", \"a@b.com\");\n  await page.fill(\"#password\", \"secret\");\n  await page.click(\"text=Log in\");\n  await expect(page).toHaveURL(\"/dashboard\");\n});\n```\n\nFor the smaller pieces, a **unit test** checks one function on its own, run by a tool like [Vitest](https://vitest.dev). Add the test run to the checks the agent must pass before it says done.\n\n{/* KEEP: automated tests catch REGRESSIONS: a green suite that goes red tells you the exact change that broke something, on every edit, for free. That is what lets you and the agent move fast without fear. Bold-first: regression. Then QA the whole flow like a real user before shipping (the human pass tests can't fully replace). */}\n\n## Green before you ship\n\nOnce the tests exist, they catch a **regression** the moment it appears: the suite was green, your last change turned it red, and now you know exactly what broke. That is what lets you keep changing a live app without holding your breath.\n\nTests are not the whole job. Before you ship, walk the real flow yourself once, on a phone, as a new user would, because some things (a confusing label, a broken layout) only a human notices.\n\n```mermaid\n%% caption: Every change runs the tests; only green code reaches your own QA pass and ships.\nflowchart TD\n  C[Your change] --> T[Tests run]\n  T --> Q{All green?}\n  Q -->|Red| FIX[Fix the regression]\n  FIX --> T\n  Q -->|Green| QA[Walk the flow yourself]\n  QA --> S([Ship])\n```\n\nThis prompt sets up the safety net for your app:\n\n```prompt\nAct as a senior engineer adding tests to my app.\nRead my spec and my must-have user stories first, and\ntake the critical paths from them, the flows that would\nhurt most if they broke, instead of guessing at what\nmatters. Follow the conventions in my rules file so the\ntests match the rest of the codebase.\n\nWrite a test for each: end-to-end for whole flows, unit\ntests for tricky logic. Tell me which flows you covered\nand why, and name any must-have story left uncovered.\n\nThen add the test run to my rules file as a check that\nmust pass before you call any task done.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/testing-and-qa\n\nThe critical flows to test:\n```\n\n**Do this now:** paste the prompt, let your agent cover your critical paths, and make a green test run part of every change from here on."
          },
          {
            "slug": "unit-and-integration-tests",
            "title": "The Pieces and Their Seams",
            "label": "Unit & Integration",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/unit-and-integration-tests",
            "content": "---\ntakeaway: Test the pieces work\nshare: 'A test can check one tiny piece on its own or two pieces working together at their seam. Knowing which is which tells you where bugs hide and what to hand the agent to protect.'\nrequires: [running-app, ai-agent, test-suite, stack-chosen, database-chosen]\nproduces: [test-suite]\nteaches: [unit-test, integration-test]\nuses: [test, function, database, module, critical-path, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = you already know tests are the safety net and critical paths first (ref why-test by topic); the NEW thing is there is more than one KIND of test. One checks a tiny piece alone, another checks two pieces where they meet. Which kind decides where and how fast you catch the bug, and what you tell the agent to protect. */}\n\nYou know tests are your safety net, and that the critical paths come first. But there is more than one kind of test. One checks a single tiny piece on its own; another checks that two pieces still work where they meet. Which kind you reach for decides where you catch the bug, and how fast. This chapter gets you that difference, so you can tell the agent exactly what to protect.\n\n{/* KEEP: a unit test = checks ONE small piece (a single function) on its own, input -> checked output, nothing else running (no db, no app). Isolation = fails fast, names the exact function. Show the tiny fenced unit test artifact. Name + link the official runner (Vitest, plain link) on first mention. Bold-first: unit test. */}\n\n## A unit test checks one piece\n\nA **unit test** checks one small piece of your code, usually a single function, on its own. You hand it an input, it runs that one piece, and it checks the output matches what you expected. Nothing else runs, no database, no whole app, just the piece.\n\nThat isolation is the point. When it fails, it fails fast and names the exact function, not a vague \"something broke somewhere.\"\n\n```js\ntest(\"applyDiscount takes 20% off\", () => {\n  const final = applyDiscount(100, 0.2);\n  expect(final).toBe(80);\n});\n```\n\nA tool like [Vitest](https://vitest.dev) runs hundreds of these in a second. It is the fast default on a modern JavaScript build; [Jest](https://jestjs.io) does the same job and you will meet it in older projects. Every language ships its own: [pytest](https://pytest.org) for Python, `go test` built into [Go](https://go.dev), [JUnit](https://junit.org) for Java, [RSpec](https://rspec.info) for Ruby. Name yours and the rest of this part is identical.\n\n{/* KEEP: an integration test = checks two pieces work together at the SEAM (a function + the real database, two modules). Bugs hide at seams, not inside one clean function. Show the real save-then-load artifact with the actual db underneath; a unit test on either piece alone misses it. Bold-first: integration test. */}\n\n## An integration test checks the seams\n\nAn **integration test** checks that two pieces still work where they meet. The bug is rarely inside one clean function; it hides at the seam, where your code hands off to the database, or where two modules trusted different assumptions.\n\nSo you exercise the real seam. Save a record, load it back, and check you got the same thing out, with the actual database running underneath:\n\n```ts\ntest(\"a saved user loads back the same\", async () => {\n  await saveUser({ email: \"a@b.com\" });\n  const user = await loadUser(\"a@b.com\");\n  expect(user.email).toBe(\"a@b.com\");\n});\n```\n\nIf saving and loading ever stop agreeing, this turns red. A unit test on either one alone would sail straight past it.\n\n{/* KEEP: don't test every line or trivial getters; test the tricky/important logic that hurts if wrong (pricing math, discount rule, who-gets-in check). Rule-of-thumb callout: costs money / loses data / lets the wrong person in = earns a test; ordinary = skip. A few tests on real logic beat many on code that cannot surprise you. */}\n\n## Test the logic that matters\n\nYou do not test every line, and you do not test a function that just hands back a value. You test the logic that would hurt if it were wrong: the pricing math, the discount rule, the check that decides who gets in.\n\n```mermaid\n%% caption: Logic earns a test when a mistake would cost money, lose data, or let the wrong person in.\nflowchart TD\n  L([A piece of logic]) --> Q{Mistake costs money or data?}\n  Q -->|yes| TEST[Earns a test]\n  Q -->|no, ordinary| SKIP[Skip it]\n```\n\n> **Rule of thumb:** if a mistake there would cost money, lose data, or let the wrong person in, it earns a test. If it is ordinary, skip it.\n\n{/* KEEP: you write none of it; you name the behavior to protect, the agent writes + runs the tests. Judgment is yours (which logic, which seam); the agent fills the cases you'd forget (zero, empty, the error path). End with the senior-voice prompt, ONE bottom slot \"The logic I want protected:\", then Do this now. */}\n\n## Let the agent write them\n\nYou hand-write none of this. You name the behavior to protect; the agent writes the tests and runs them. The judgment is yours: which logic is worth the net, which seam is fragile. Give it that and it fills in the cases you would forget, the zero, the empty input, the one that should throw an error.\n\nThis prompt hands your agent the logic to protect:\n\n```prompt\nAct as a senior engineer writing tests for me.\nRead my spec and my API contract first, and\nassert the behavior they promise, not whatever\nthe code happens to do today.\n\nFor the logic I name below, write focused unit\ntests for the tricky cases: the boundaries, the\nzero and the empty input, the case that errors.\nWhere two pieces meet (a function and the\ndatabase, two modules), add one integration test\nthat exercises the real seam, not a fake. Use my\nstack's standard runner and the naming\nconventions in my rules file, and put each test\nin the feature folder its code lives in.\n\nReport each case you covered and the ones you\ndeliberately skipped. Where the code and the\nspec disagree, say which one is wrong.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/unit-and-integration-tests\n\nThe logic I want protected:\n```\n\n**Do this now:** paste the prompt, name the one piece of logic that would hurt most if it broke, and let your agent write the tests that pin it down."
          },
          {
            "slug": "test-data-and-mocking",
            "title": "Fake Data and Fake Services",
            "label": "Test Data",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/test-data-and-mocking",
            "content": "---\ntakeaway: Feed tests fake data, not the real thing\nshare: 'Tests need controlled input to run on, and your code that calls a payment provider or an email sender must never touch the real one in a test. This gets you reliable fake data and safe stand-ins for the outside world.'\nrequires: [running-app, ai-agent, test-suite, data-model]\nproduces: [test-fixtures]\nteaches: [fixture, factory, mock]\nuses: [test, unit-test, integration-test, database, api, library, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = you have tests now, but they need data to run on, and some of your code calls real outside services (payments, email). A test must not charge a real card, send a real email, or lean on data that changes. This chapter gets reliable test data + safe fakes for the outside world. */}\n\nYou have tests now, but a test needs something to run on. Some of your code also reaches out to the real world: a payment provider, an email sender, another API. A test must never charge a real card, send a real email, or depend on data that changes underneath it. This chapter gets you controlled test data and safe stand-ins for those outside services.\n\n{/* KEEP: a test needs predictable, controlled input, never your real or production data (which changes). Prepared test data = a fixture. Show a tiny fixture artifact. Bold-first: fixture. */}\n\n## Tests need their own data\n\nA test can only check \"did I get the right answer\" if it knows the answer in advance. That means predictable, controlled input, never your real or production data, which changes the moment a user edits something.\n\nPrepared test data like this is a **fixture**: a fixed, known record your test runs against. Your agent writes these; here is the shape:\n\n```ts\nexport const testUser = {\n  id: \"u_1\",\n  email: \"test@example.com\",\n  plan: \"free\",\n};\n```\n\nThe test uses `testUser` and knows exactly what to expect, every run, forever.\n\n{/* KEEP: hand-writing test data is tedious and brittle; a factory/generator produces realistic fake data on demand. Link Faker on first mention. Show a small factory building a fake user. Bold-first: factory. */}\n\n## Make data with a factory, not by hand\n\nWriting each fixture by hand gets tedious fast, and one change to the shape of your data breaks every one you typed out. When you need many records, or just realistic-looking ones, use a **factory**: a small function that builds fake data on demand.\n\nA library like [Faker](https://fakerjs.dev) fills in believable names, emails, and dates for you:\n\n```ts\nimport { faker } from \"@faker-js/faker\";\n\nexport const makeUser = (over = {}) => ({\n  id: faker.string.uuid(),\n  email: faker.internet.email(),\n  ...over,\n});\n```\n\nCall `makeUser()` for a random one, or `makeUser({ plan: \"pro\" })` to pin the one field a test cares about.\n\n{/* KEEP: replace an external service (Stripe, email, another API) with a mock: a stand-in returning a canned response, so tests are fast and never touch the real world or spend real money. Mention Mock Service Worker for HTTP, link it. Show a small mock artifact. Bold-first: mock. */}\n\n## Never call the real service in a test\n\nYour code calls out to services you do not own: a card gets charged, an email gets sent, another API answers. In a test, none of that can happen. You cannot spend real money or send a real email a thousand times a day.\n\nSo you swap the real service for a **mock**: a stand-in that returns a canned response instead of doing the real thing. Tests stay fast, and they never touch the outside world.\n\n```mermaid\n%% caption: In a test, calls to the outside world hit a mock that returns a canned answer, never the real service.\nflowchart LR\n  T[Your test] --> C[Your code]\n  C --> M[Mock]\n  M --> R([Canned response])\n  C -.->|blocked in tests| EXT[Real Stripe / email]\n```\n\nFor code that talks to an API over HTTP, [Mock Service Worker](https://mswjs.io) intercepts the request and hands back whatever you tell it:\n\n```ts\nhttp.post(\"https://api.stripe.com/v1/charges\", () =>\n  HttpResponse.json({ id: \"ch_test\", status: \"succeeded\" })\n);\n```\n\nThe code under test thinks it charged a card. Nothing left your machine.\n\n{/* KEEP: each test must start clean and not depend on another; reset the test database/state between runs so a passing test never leaves data that makes the next one pass or fail by accident. Say WHERE the test database comes from (second db on the same server, throwaway SQLite, container per run) with the choose-by criterion, plus the hard rule that the test connection string never points at dev or production because reset means delete. Prompt: senior engineer sets up fixtures/factories + mocks every external service + resets state between tests. */}\n\n## Reset between tests, so they don't leak\n\nA test that leaves data behind poisons the next one. Say test A creates a user and test B counts users. B passes only because A ran first. The day you run B alone, it fails for no reason you can see.\n\nSo every test starts from a clean slate. Reset the test database and any shared state before each one runs, so no test can depend on the leftovers of another. Your agent wires this into the test setup once.\n\nYou have one database, so where does the test one come from? Three options: a second database on the server you already run, a throwaway [SQLite](https://sqlite.org) file for speed, or a fresh container per run. Use the same engine as production for anything testing SQL you actually rely on, and the fast throwaway one for everything else.\n\nThen treat the connection string as a hard rule, because \"reset before each test\" means \"delete everything\". It points at the test database and nowhere else. Point it at your development or production database and the next test run wipes it.\n\n> **Rule of thumb:** any test must pass on its own, in any order. If it only passes after another test runs, something is leaking, reset it.\n\nThis prompt sets up test data and safe fakes for your stack:\n\n```prompt\nAct as a senior engineer setting up test data\nfor my app. Read my data model and my vendor\nadapters first: fixtures follow the entities I\nalready defined, and fakes replace my adapters,\nnot the vendor SDKs behind them.\n\nThen do three things.\n\nFirst, add fixtures and factories: fixed records\nfor known cases, a factory (Faker or my stack's\nequivalent) for realistic data on demand.\n\nSecond, give each adapter a fake that returns\ncanned responses, so no test touches a real\npayment, email, or outside API.\n\nThird, set up a separate test database, never my\ndevelopment or production one, and reset it and\nany shared state before each test, so tests never\ndepend on each other and pass in any order.\n\nReport what you faked and what you reset, and add\none line to my rules file: tests never call a\nreal service.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/test-data-and-mocking\n\nMy app and stack:\n```\n\n**Do this now:** paste the prompt and name the outside service your app calls first. Let your agent replace it with a mock before another test ever risks the real thing."
          },
          {
            "slug": "end-to-end-tests",
            "title": "The Whole Flow, Like a User",
            "label": "End-to-End",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/end-to-end-tests",
            "content": "---\ntakeaway: Test the whole flow\nshare: 'Every piece can pass its own test while the journey a user actually takes still falls apart between them. An end-to-end test walks that whole journey like a real person, so the few flows your business runs on never break without you knowing.'\nrequires: [running-app, ai-agent, test-suite, first-feature]\nproduces: [e2e-tests]\nteaches: [critical-journey, flaky]\nuses: [end-to-end-test, unit-test, test, critical-path, database, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = each piece passes its own test, but the real journey crosses all of them, and the break lives in the seam where two pieces meet. This chapter gets a handful of tests that walk each whole journey front to back like a real user. Builds on testing-and-qa (safety net, critical paths) and the unit-tests chapter (the small pieces) by topic. */}\n\nYour login works and your payment code works. Each piece passes its own test. Yet a real user still gets stuck halfway through checkout, because the break lives in the seam where two pieces meet for the first time. This chapter gets you a handful of tests that walk each whole journey, front to back, the way a real user would.\n\n{/* KEEP: an end-to-end test = code that opens a real browser and drives the whole app the way a user does (clicks real screens, types real fields), exercising every layer at once. Distinct from a unit test (one function alone) from the prior chapter. Name + link Playwright official on first mention, with the honest verdict against Cypress: one config runs the same test in Chromium, Firefox and WebKit, which is how cross-browser breaks get caught. Bold-first: end-to-end test. */}\n\n## Drive the app like a user\n\nAn **end-to-end test** opens a real browser and drives your whole app the way a person does, clicking through real screens and typing into real fields. Where a unit test checks one function alone, an end-to-end test exercises every layer at once: the button, the code behind it, the database, and the screen that comes back.\n\nA tool like [Playwright](https://playwright.dev) runs that browser for you, invisibly and in seconds. Your agent writes the script; you just name the journey it should walk.\n\n[Cypress](https://www.cypress.io) is the other common choice, and Playwright wins for us on one thing. From a single config it runs the same test in Chromium, Firefox and WebKit, the engine behind Safari. That is how you catch the break that only happens in one browser without writing anything twice.\n\n{/* KEEP: a critical journey = one of the critical paths from the safety-net chapter walked end to end (sign up, pay, the one core action). Test THESE; a settings toggle does not earn one. Bold-first: critical journey. Show the real artifact here, a fenced e2e test of ONE journey, richer than the login one in the anchor (signup + core action across pages). */}\n\n## Cover the critical journeys\n\nYou already know your critical paths from the safety-net chapter. A **critical journey** is one of those paths walked end to end:\n\n- sign up, then land on the dashboard\n- add an item, then pay for it\n- create the one thing your app exists to make\n\nPick three or four. Here is one test, for a new user who signs up and creates their first project:\n\n```ts\ntest(\"a new user signs up and creates a project\", async ({ page }) => {\n  await page.goto(\"/signup\");\n  await page.fill(\"#email\", \"new@user.com\");\n  await page.fill(\"#password\", \"hunter2pw\");\n  await page.click(\"text=Create account\");\n  await expect(page).toHaveURL(\"/welcome\");\n\n  await page.click(\"text=New project\");\n  await page.fill(\"#title\", \"My first project\");\n  await page.click(\"text=Save\");\n  await expect(page.locator(\"text=My first project\")).toBeVisible();\n});\n```\n\n{/* KEEP: keep them FEW (a handful, not hundreds) because e2e tests are slow and heavier to maintain; keep them STABLE because a flaky test that fails at random trains you to ignore red, and an ignored net is no net. Flakiness usually = waiting on a fixed timer instead of a real condition. Bold-first: flaky. One Watch out callout on flakiness. */}\n\n## Keep them few and stable\n\nEnd-to-end tests are slow and heavier to maintain than the small ones, so keep them to a handful, the few journeys that lose you customers when they break.\n\nKeep them stable, too. A **flaky** test passes and fails at random on the very same code. It trains you to shrug at red, and a net you have learned to ignore is no net at all.\n\n```mermaid\n%% caption: Waiting on a fixed timer makes a test flaky and teaches you to ignore red; wait on a real element instead.\nflowchart TD\n  T{What does the test wait on?}\n  T -->|fixed timer| FLAKY[Flaky, random red]\n  FLAKY --> IGNORE[You learn to ignore red]\n  T -->|real element or URL| STABLE[Stable and trustworthy]\n```\n\n> **Watch out:** Flakiness almost always means the test waits on a fixed timer instead of a real condition. Tell your agent to wait for the element or the URL to appear, never for a set number of seconds.\n\n{/* KEEP: the payoff = run the whole e2e set before every ship, so a break lands on your screen while you can still fix it, not in a user's message. Same gate as the agent's checks in testing-and-qa/guardrails; the automatic-on-every-change version comes in a later chapter (CI) without naming it here. Then the senior-voice prompt, ONE bottom slot \"My critical user journeys:\", then Do this now. */}\n\n## Run them before every ship\n\nA journey test is only worth writing if it actually runs. Run the whole set before every ship. Then a break lands on your screen while you can still fix it, not in a message from an angry user.\n\nMake it part of the checks your agent runs before it calls a task done, the same gate you set up for the safety net. A later chapter makes that gate run on its own, on every change.\n\nThis prompt sets your agent up to write them:\n\n```prompt\nAct as a senior engineer writing end-to-end tests\nfor my app. Read my spec first: the user stories and\nthe screen map name the real journeys and the\nscreens to drive.\n\nFor each journey I list below, write one test that\ndrives a real browser through the whole flow the way\na user would: visit the page, fill the fields, click\nthrough every step, and assert on what the user\nshould finally see. Use Playwright, or my stack's\nstandard browser driver if it has one, and run the\nset across Chromium, Firefox and WebKit.\n\nKeep it small and stable: wait for real elements and\nURLs, never fixed timers.\n\nThen add the suite to the checks my rules file\nalready requires before any task is done, and tell\nme which journeys you covered.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/end-to-end-tests\n\nMy critical user journeys:\n```\n\n**Do this now:** paste the prompt and list your three or four critical journeys. Let your agent write one end-to-end test for each, then wire the suite into the checks it runs before every ship."
          },
          {
            "slug": "visual-and-snapshot-tests",
            "title": "Catching What the Eye Sees",
            "label": "Visual",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/visual-and-snapshot-tests",
            "content": "---\ntakeaway: Catch UI changes you didn't mean to make\nshare: 'Your tests pass green while the page looks visibly broken, because a normal test checks values, not appearance. Snapshot and visual tests watch the output itself, so an unintended layout break turns red before a user sees it.'\nrequires: [running-app, ai-agent, test-suite]\nproduces: [visual-tests]\nteaches: [snapshot-test, visual-regression, rendered-output]\nglosses: [ui-component, accessibility]\nuses: [test, regression, diff, ai-coding-agent, prompt, ui-component, accessibility]\n---\n{/* KEEP: lead-in = every test passes but the page looks broken (a button moved, a layout collapsed, text overlaps), because a normal test checks values, not appearance, and sails past a visual break. This chapter gets tests that catch a change in how things look or render, not just what they return. */}\n\nYour tests all pass, but the page looks broken: a button jumped, a layout collapsed, two lines of text overlap. A normal test checks values, not appearance, so it sails right past a break the eye catches instantly. This chapter gets you tests that catch a change in how things look or render, not just what they return.\n\n{/* KEEP: Concept. A test that checks a value can be green while the screen is visibly wrong; you need a test that checks the OUTPUT itself, not just a returned value. */}\n\n## Assertions miss what the eye catches\n\nA test that checks a value confirms the total says 42 and the email field holds text. It says nothing about whether the total sits off the edge of the screen or the field overlaps the button next to it.\n\nThat gap is the whole problem. To catch a visual break you need a test that checks the **output** itself, the actual thing rendered, not just a number returned from the code behind it.\n\n{/* KEEP: Step 1. A snapshot test records the rendered output (the HTML a component produces) the first time, then flags any later change so you review the diff. Show a tiny snapshot example. Bold-first: snapshot test. */}\n\n## A snapshot test freezes the output\n\nA **snapshot test** records the exact output a piece of your app produces the first time it runs, saves it, then compares every future run against that saved copy. Any difference turns the test red so you can look at what changed.\n\nFor a single **component**, one self-contained piece of your interface, the output it records is the HTML that component renders. Your agent writes this, using a helper like [Testing Library](https://testing-library.com) to render the component outside a browser; here is the shape:\n\n```ts\ntest(\"the price tag renders\", () => {\n  const html = render(<PriceTag amount={42} />);\n  expect(html).toMatchSnapshot();\n});\n```\n\nThe first run saves the HTML. If a later edit changes that markup, the test fails and shows you the exact lines that moved.\n\n{/* KEEP: Step 2. A visual regression test takes a screenshot of a real screen and compares it pixel-by-pixel to an approved baseline, catching layout breaks a snapshot of markup would miss. Use Playwright's screenshot compare, toHaveScreenshot example. Name + link Playwright official on first mention. Bold-first: visual regression. Two must-keeps after the example: baselines are machine-specific, so generate them in the same environment that runs them (Playwright's container image) or keep the suite local, otherwise every automated run is red; and the same screenshot run can carry an axe accessibility check that flags unlabeled fields and bad contrast. */}\n\n## A visual test compares screenshots\n\nA snapshot of markup misses a break the markup itself does not show: a broken stylesheet, an overlap, a collapsed layout. For that you need to look at the actual pixels.\n\nA **visual regression** test takes a screenshot of a real, rendered screen and compares it pixel by pixel against an approved baseline image. [Playwright](https://playwright.dev) does this in one line:\n\n```ts\ntest(\"the dashboard looks right\", async ({ page }) => {\n  await page.goto(\"/dashboard\");\n  await expect(page).toHaveScreenshot();\n});\n```\n\nThe first run saves the baseline. Every run after compares against it and fails on any visible drift, catching the button that moved even when the code behind it is unchanged.\n\n> **Watch out:** a baseline captured on your machine fails on another one over font rendering alone. Generate and store baselines from the same environment that will run them, usually Playwright's own container image, or keep the visual suite local until you have.\n\nThe same screenshot run can check more than looks. Have your agent add an accessibility check, [axe](https://www.deque.com/axe/) inside a Playwright test, and every run also flags unlabeled fields and unreadable contrast.\n\n{/* KEEP: Step 3. These tests turn red on ANY change, intended or not; the skill is reviewing the diff and updating the baseline only for changes you meant, never blindly accepting the new image (that defeats the test). One Watch out callout. Then the senior-voice prompt, ONE bottom slot, then Do this now. */}\n\n## Review the diff, never rubber-stamp it\n\nThese tests turn red on any change, the ones you meant and the ones you did not. The whole value lives in one habit: when a test goes red, you look at the diff and decide.\n\nIf the change is one you intended, you update the baseline so the new look becomes the approved one. If it is a break you did not mean, you fix the code. Accepting every new image without looking defeats the test entirely.\n\n> **Watch out:** Blindly re-approving a failed visual test is the same as deleting it. The red is the point; the diff is the thing you are paying for. Always look before you update the baseline.\n\n```mermaid\n%% caption: A visual test goes red on any change; you look at the diff and decide, never rubber-stamp the new image.\nflowchart TD\n  T[Visual test goes red] --> D{Look at the diff}\n  D -->|change I meant| U[Update the baseline]\n  D -->|break I did not mean| F[Fix the code]\n```\n\nThis prompt sets your agent up to add both:\n\n```prompt\nAct as a senior engineer adding visual safety to\nmy app. Put the new tests with my existing test\nsuite and follow its conventions, do not stand up\na second setup beside it. Add snapshot tests for\nmy key components so any change to their rendered\noutput turns red. Add visual-regression screenshot\ntests, using Playwright's screenshot compare, for\nthe few most important screens I list below.\nGenerate the baselines in the same environment\nthat will run them, and add an axe accessibility\ncheck to the same screenshot run. Wire the suite\ninto my quality gate, and add one line to my rules\nfile: never update a baseline without showing me\nthe diff and what changed.\nTell me which components and screens you covered.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/visual-and-snapshot-tests\n\nMy most important screens:\n```\n\n**Do this now:** paste the prompt and list your two or three most important screens. Let your agent add snapshot tests for the key components and one visual-regression test per screen."
          },
          {
            "slug": "test-driven-development",
            "title": "Writing the Test First",
            "label": "TDD",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/test-driven-development",
            "content": "---\ntakeaway: Write the test first\nshare: 'Most tests get written after the code, to confirm what already works. Flip the order and the failing test becomes a precise spec your agent codes to, one it cannot fake its way past.'\nrequires: [running-app, ai-agent, test-suite]\nproduces: [test-suite]\nteaches: [tdd, red-green-refactor]\nglosses: []\nuses: [test, unit-test, spec, ai-coding-agent, prompt, repro]\n---\n{/* KEEP: lead-in = reader knows tests as a safety net added AFTER code works; TDD flips the order: write the test first, it describes success in advance, the agent writes code until it passes. Ends by naming the payoff (how to run the loop + when it is worth it). Cross-ref the safety-net chapter by topic. */}\n\nYou have seen tests as a safety net you add after the code already works. There is a sharper move that flips the order: you write the test first, before the code exists, describing exactly what success looks like. Then the agent writes code until that test passes. This chapter shows you how to run that loop with an agent, and when the flip is worth it.\n\n{/* KEEP: concept = TDD means writing the test before the code it tests; the test IS the spec you build toward. Writing it first forces the definition of done before the feature exists. Bold-first: test-driven development. */}\n\n## Write the test before the code\n\n**Test-driven development** (TDD) means writing the test before the thing it tests. You describe the behavior you want as a test that must pass, then write only enough code to make it pass. The test is not a check you bolt on at the end. It is the specification you build toward.\n\nThe order sounds backwards until you see what it buys. You cannot write a test for \"checkout works\" without first deciding what \"works\" means. Writing the test first forces that definition before a single line of the feature exists.\n\n```mermaid\n%% caption: TDD flips the usual order so the test comes first and becomes the spec the code chases.\nflowchart LR\n  subgraph SG1[Usual order]\n    C1[Write code] --> T1[Test after]\n  end\n  subgraph SG2[Test-driven]\n    T2[Write test first] --> C2[Code to pass]\n  end\n```\n\n{/* KEEP: the three-beat cycle. Red: a failing test proves it actually checks something. Green: the least code to pass. Refactor: clean up, test stays green so you know nothing broke. Show the real red->green artifact. Bold-first: red-green-refactor. */}\n\n## Red, green, refactor\n\nThe cycle has a name, **red-green-refactor**, and three beats you repeat:\n\n1. **Red:** write one small failing test and run it. It fails because the code it needs does not exist yet, and that red proves the test really checks something.\n2. **Green:** write the least code that makes the test pass. Nothing extra, nothing clever, just green.\n3. **Refactor:** with the test passing, clean up the code, improving its shape without changing what it does. It stays green, so you know the cleanup broke nothing.\n\n```mermaid\n%% caption: The red-green-refactor loop, repeated one small test at a time.\nflowchart LR\n  R[Red, test fails] --> G[Green, least code]\n  G --> RF[Refactor, stay green]\n  RF -->|next test| R\n```\n\n```js\n// 1. RED: write the test first, before the code exists.\ntest(\"splits a bill evenly\", () => {\n  expect(splitBill(100, 4)).toBe(25);\n});\n\n$ npm test\nFAIL  splitBill is not defined\n\n// 2. GREEN: the agent writes just enough to pass.\nfunction splitBill(total, people) {\n  return total / people;\n}\n\n$ npm test\nPASS  splits a bill evenly\n```\n\n{/* KEEP: the core why-AI point. A failing test is the most precise, unfakeable instruction you can hand an agent; green is a fact, not an opinion. It closes the agent's \"it's done\" escape hatch. */}\n\n## Why it fits AI so well\n\nHanding an agent a failing test is the most precise instruction you can give it. Most prompts describe what you want in words the agent can read loosely. A test is exact: this input must produce that output, and the machine runs it to check.\n\nIt also closes the agent's favorite escape hatch. An agent will cheerfully report a feature done. A red test that has to go green is a fact it cannot talk its way around, so you get a spec it codes toward and a finish line it cannot fake.\n\n```mermaid\n%% caption: A worded prompt the agent reads loosely; a failing test is exact and machine-checked.\nflowchart TD\n  WANT([What you want]) --> W[Worded prompt]\n  WANT --> T[Failing test]\n  W --> LOOSE[Agent interprets loosely]\n  T --> EXACT[Machine checks it green]\n  EXACT --> FIN([Finish it cannot fake])\n```\n\n{/* KEEP: judgment. Use for tricky logic with a right answer and for bugfixes (write the test that reproduces the bug, then fix to green); skip for exploratory UI / prototypes / judge-by-eye layout. Dividing line = can you state \"correct\" before building. Cross-ref the safety-net chapter for the cover-after path. */}\n\n## When to use it, when to skip it\n\nTDD shines when you can state success exactly before you build. It gets in the way when you are still discovering what you want.\n\n| Write the test first | Skip it, cover it after |\n| --- | --- |\n| Tricky logic with a right answer (pricing, dates, permissions) | Exploratory UI you are still shaping |\n| A bug: write the test that reproduces it, then fix to green | A quick prototype you may throw away |\n| A rule you must never break again | A layout you judge by eye, not by assertion |\n\nThe dividing line is that one question: can you write down what \"correct\" means before the code exists? When you can, write the test first. When the honest answer is \"I will know it when I see it,\" build first and cover it after, the way the safety-net chapter showed.\n\n```mermaid\n%% caption: One question decides whether to write the test first or cover it after.\nflowchart TD\n  Q{Can you state correct before building?}\n  Q -->|Yes| TF[Write the test first]\n  Q -->|No| CA[Build first, cover after]\n```\n\n{/* KEEP: the part's highest-value habit, promoted out of the table cell. Every fixed bug becomes a test: the repro from the Debug part IS the test, run it against the old code to watch it fail, then fix to green. It is the one rule that stops the agent reintroducing the same bug. */}\n\n## Turn every bug you fix into a test\n\nThis is the habit worth more than any other in this part, and it is free: every bug you fix gets a test before it is closed. You already have the ingredient, the repro you wrote when you proved the fix was real.\n\nTurn that repro into a test and run it against the code from before the fix. It must fail. Then apply the fix and watch it pass.\n\nThat is the red-then-green cycle, handed to you by the bug itself. It is also the only thing that stops your agent quietly reintroducing the same bug three weeks from now.\n\n```prompt\nAct as a senior engineer practicing test-driven\ndevelopment on my app. Read my spec and my\nexisting test suite first: use the same runner,\nthe same fixtures, and the naming my conventions\nalready set. Never add a second framework.\n\nWrite one small failing test that says exactly\nwhat success looks like, and run it so we both\nwatch it fail. Then write the least code that\nmakes it pass, run it green, and refactor without\nbreaking it. Work one test at a time, and never\ncall a step done while its test is still red.\n\nIf what I give you is a bug rather than a\nfeature, take its repro from my debug log, turn\nthat into the test, confirm it fails on the\ncurrent code, then fix to green.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/test-driven-development\n\nThe feature or bug to work test-first:\n```\n\n**Do this now:** pick one piece of tricky logic in your app, write the failing test for it first, and let your agent turn it green before it writes anything else."
          },
          {
            "slug": "trusting-your-tests",
            "title": "Do the Tests Actually Test?",
            "label": "Trust",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/trusting-your-tests",
            "content": "---\ntakeaway: Green tests can still test nothing\nshare: 'A passing suite feels like proof, but a test can be green and check nothing at all. This gives you a fast way to tell a real safety net from a green light that means nothing.'\nrequires: [test-suite, ai-agent]\nproduces: [test-audit-report]\nteaches: [coverage, assertion, mirror-test, over-mocking]\nuses: [test, unit-test, mock, ai-coding-agent, prompt, eval, model, json, end-to-end-test]\n---\n{/* KEEP: lead-in = a green suite feels safe, but a test can pass while checking nothing, AND the agent that wrote your code wrote your tests with the same blind spots. Ends naming the payoff: a way to tell a real safety net from a meaningless green light. */}\n\nYour suite is green, so you feel safe. But a test can pass while checking nothing at all, and the agent that wrote your code also wrote your tests, with the same blind spots baked into both. A green suite you cannot trust is worse than no suite, because it tells you to stop looking. This chapter gets you a way to tell a real safety net from a green light that means nothing.\n\n{/* KEEP: concept = a test that asserts nothing, or asserts something trivially true, is green and worthless. Green is only ever as good as what the test actually checks. */}\n\n## A passing test can check nothing\n\nA test passes when nothing in it fails. That sounds obvious until you see the trap: a test that checks nothing also has nothing to fail, so it passes forever.\n\nGreen is only as good as the check inside the test. A test that runs your code but never asserts the result is a green light wired to nothing. It will stay green while the feature underneath rots.\n\n{/* KEEP: step = coverage is the percent of code a suite RUNS; useful for finding untested code, but 100% coverage can miss every real bug because running a line is not checking its result. Bold-first: coverage. Link Vitest coverage docs. Show high-coverage test that asserts nothing meaningful. */}\n\n## Coverage counts lines, not correctness\n\n**Coverage** is the percent of your code that your tests actually run. Tools like [Vitest coverage](https://vitest.dev/guide/coverage) report it, and it is genuinely useful for one thing: finding code no test touches at all.\n\nBut high coverage is not proof of correctness. Running a line is not the same as checking what it produced. This test hits every line of `applyDiscount` and asserts nothing that matters:\n\n```js\ntest(\"applyDiscount runs\", () => {\n  applyDiscount(100, 0.2); // 100% covered\n  expect(true).toBe(true); // checks nothing real\n});\n```\n\nThat is 100 percent coverage on a test that would stay green if `applyDiscount` returned garbage.\n\n{/* KEEP: step = name the worthless-test smells in plain terms, as a list: no real assertion; over-mocked so it only checks the mock; mirror test that restates the implementation so it can never catch a bug. */}\n\n## Watch for tests that can't fail\n\nA worthless test is one that cannot turn red no matter how broken the code gets. Three smells give them away:\n\n1. **No real assertion:** it runs your code but never checks the output, or only asserts something trivially true like `expect(true).toBe(true)`.\n2. **Over-mocked:** so much of the real code is faked that the test only checks the mock you wrote, not your actual logic.\n3. **Mirror test:** it restates the implementation instead of the expected result, so it agrees with any bug the code already has.\n\n{/* KEEP: step = the AI features from the Amplify part fit the suite three ways: assert shape and constraints, never exact words; mock the model call in unit and e2e tests so they stay fast, free, and repeatable; run the eval set as its own scheduled job, not as a gate on every push. Without this the reader's model-backed features sit outside the safety net entirely. */}\n\n## Test an AI feature on shape, not on words\n\nThe AI features you built earlier fail this chapter from both ends at once. Assert the exact sentence a model returned and the test is flaky by design; assert nothing and it is a green light wired to nothing.\n\nSo assert on shape and constraints instead: valid JSON, a category that is one of the values you allow, a score between zero and one, an answer that cites a document which exists. In your unit and end-to-end tests, mock the model call the way you mock any paid outside service, or your suite is slow, expensive, and different every run.\n\nThe eval set you built for that feature is a different animal, and it does not belong in the suite that gates your merges. Run it on a schedule and read the results, because a real model call costs money and can fail for reasons that have nothing to do with your change.\n\n{/* KEEP: step = the fastest trust check is to deliberately break the code under test and confirm a test turns red; if everything stays green, those tests never tested. Have the agent do this. */}\n\n## Break the code on purpose\n\nThe fastest way to trust a test is to make it fail on purpose. Change the code it guards to something wrong, rerun, and watch for red.\n\nIf the test turns red, it was really checking that behavior. If everything stays green after you broke the code, those tests were never testing anything.\n\n```mermaid\n%% caption: Break the code, rerun; red means the test was real, green means it was never testing.\nflowchart LR\n  B[Break the code] --> R{Any test red?}\n  R -->|Yes| REAL[It was really testing]\n  R -->|No| FAKE[It never tested this]\n```\n\nYou do not do this by hand. Hand the check to your agent, which can break each piece, rerun, and report which tests actually caught it:\n\n```prompt\nAct as a senior engineer auditing my test suite\nfor tests that pass without testing anything.\nTake what this suite must protect from my spec's\nmust-haves and my non-functional targets, never\nfrom the tests themselves.\nFind and flag three failure modes: tests with no\nreal assertion, tests so heavily mocked they only\ncheck the mock, and tests that mirror the\nimplementation so they can never catch a bug.\nReport coverage honestly: separate code no test\nruns from code that runs but whose result is never\nchecked. Then prove the important tests work by\nbreaking the code they guard, one piece at a time,\nrerunning, and listing which tests turned red and\nwhich stayed green when they should not have.\nEnd with the must-haves no real test covers.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/trusting-your-tests\n\nMy suite and what it should protect:\n```\n\n**Do this now:** paste the prompt, then pick your most important test and break the code under it by hand to confirm it turns red."
          },
          {
            "slug": "manual-and-exploratory-qa",
            "title": "The Human Pass",
            "label": "Manual QA",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/manual-and-exploratory-qa",
            "content": "---\ntakeaway: Some bugs only a human will find\nshare: 'Green tests only prove the cases you thought to check. This chapter gives you the human pass: a real-device walkthrough and a bug report your agent can act on, so the ugly, confusing, and broken-but-passing bugs surface before your users find them.'\nrequires: [running-app, test-suite, ai-agent]\nproduces: [release-checklist, bug-report-template]\nteaches: [exploratory-testing, reproducible-bug-report, agentic-qa]\nglosses: [release]\nuses: [test, assertion, release, ai-coding-agent, prompt, end-to-end-test]\n---\n{/* KEEP: lead-in = your tests are green and trustworthy, but they only ever check what you thought to check. A machine sails past a confusing label, a broken phone layout, a flow that works but feels wrong. This chapter gets the human pass that catches what no assertion can. Builds on testing-and-qa and end-to-end-tests by topic. */}\n\nYour automated tests are green and you trust them, but they only ever check what you thought to check. A confusing label, a broken layout on a phone, a flow that technically works but feels wrong: a machine sails past all of it. This chapter gets you the human pass that catches what no assertion can.\n\n{/* KEEP: a test checks the cases you imagined; a real person hits the ones you did not, and notices the working-but-wrong (ugly, confusing, awkward). No assertion asks \"does this feel right\". That gap is human-only. */}\n\n## Automated tests miss the human bugs\n\nA test only ever checks a case you thought of in advance. You wrote it, or your agent did, to confirm the thing you already pictured. It cannot flag the case that never crossed your mind.\n\nIt also never asks the question a person asks without trying: does this feel right? A form can submit, save, and pass every check while its button sits in a place no one would look. That whole class of bug, ugly, confusing, awkward, working but wrong, is human-only.\n\n{/* KEEP: exploratory testing = poking at your app like a curious or careless user with no script. Click the wrong order, submit the empty form, hit back mid-flow, resize the window, try the weird thing. The point is to leave the path you designed. Bold-first: exploratory testing. */}\n\n## Explore, don't just follow a script\n\n**Exploratory testing** is poking at your app like a curious or careless user with no script in hand. You deliberately leave the path you designed and see what breaks.\n\nThe moves that find bugs are the ones a tidy user never makes:\n\n- click things in the wrong order\n- submit the empty form, then the same one twice\n- hit the back button in the middle of a flow\n- resize the window small, then tiny\n- paste an essay into a field built for a name\n\nSpend ten unhurried minutes doing the weird thing. That is where the bugs no test imagined are hiding.\n\n{/* KEEP (added July 2026, user mandate): agentic QA. The reader's agent can now drive a real browser, so the pass above no longer has to be entirely yours: you write the case in plain English, the agent walks it, checks what the backend actually stored, and reports or fixes. Bold-first: agentic QA. Real artifact = the plain-English case. Bound it honestly: it does not replace your own pass, because it only checks what you thought to ask, and taste is the part you keep. */}\n\n## Hand the boring passes to an agent\n\nYour agent can drive a real browser too, which means the repetitive half of this does not have to be yours. **Agentic QA** is writing the case in plain English and letting the agent walk it. It checks what actually landed in the database, then reports back or fixes what it finds:\n\n```\n# qa/checkout.md\nSign up as a new user, add two items, pay with the\ntest card, then confirm: the order exists, the total\nmatches, and the confirmation email was queued.\n```\n\nThat covers the passes you would skip on a Friday. It does not replace your own ten minutes, because an agent only checks what you thought to ask, and noticing that something feels wrong is still yours.\n\n{/* KEEP: a release checklist = a short manual list you actually walk before every ship, on a REAL device (a real phone, not just the desktop simulator). Show it as a fenced plain-text checklist: log in, core flow, phone layout, empty states, error states, a second browser (Safari), keyboard-only pass, built-in accessibility audit. Beginner framing: same list every time, muscle memory. The last three are not polish: Safari differs from Chrome, and a flow you cannot finish by keyboard is a flow some customers cannot use. Signature device #1. */}\n\n## Keep a release checklist\n\nBefore every **release**, every time you ship a new version to users, walk one short list by hand on a real device. Not the desktop browser shrunk narrow, an actual phone, because that is where layout and touch bugs live. The same list every time turns into muscle memory:\n\n```text\nRelease checklist (walk before every ship)\n[ ] Log in and log out\n[ ] Complete the one core flow end to end\n[ ] Do all of it once on a real phone\n[ ] Empty state: a brand-new account with no data\n[ ] Error state: submit a form with fields left blank\n[ ] Wrong input: bad email, huge number, pasted text\n[ ] Hit back and refresh mid-flow, nothing breaks\n[ ] Read every label out loud, does it make sense\n[ ] Open the core flow in a second browser, Safari\n[ ] Do the whole flow with the keyboard, no mouse\n[ ] Run the browser's accessibility audit\n```\n\nKeep it to what would embarrass you if it shipped broken. A list you actually finish beats a long one you skip.\n\nThose last three are not polish. Safari behaves differently from Chrome often enough that it is the classic thing a human pass catches. And a flow you cannot finish with a keyboard is a flow some of your customers cannot use at all.\n\n{/* KEEP: a good bug report is REPRODUCIBLE: steps, expected result, actual result, environment. Vague \"it's broken\" wastes a round with the agent; a clear repro gets it fixed first try. Show as a fenced plain-text template. Signature device #2. Then the senior-QA prompt, ONE bottom slot, then Do this now. */}\n\n## Write a bug report your agent can fix\n\nWhen the human pass finds something, how you write it up decides whether the agent fixes it in one round or three. A vague \"the signup is broken\" forces the agent to guess and re-ask. A **reproducible** report, the exact steps plus what should happen and what did, gets it fixed on the first try.\n\nFill in the same four parts every time:\n\n```text\nTitle: one line, what is wrong\n\nSteps to reproduce:\n1. Go to ...\n2. Click ...\n3. Type ... and submit\n\nExpected: what should have happened\nActual: what happened instead\n\nEnvironment: device, browser, phone or desktop\n```\n\nHand your app to a senior QA engineer and let them build both artifacts around your specifics:\n\n```prompt\nAct as a senior QA engineer reviewing my app\nbefore release. Read my spec, my screens, and the\nend-to-end tests I already have, then do three\nthings.\n\n1. Write a short manual release checklist built\nfrom my own user stories and screens: the core\nflow, empty and error states, wrong input, a real\nphone, a second browser, keyboard only. Skip what\nmy automated tests already cover, and keep it to\nwhat would hurt if it shipped broken.\n\n2. Give me a reusable bug-report template with\nsteps, expected, actual, and environment.\n\n3. List the exploratory edge cases most worth\ntrying by hand for this app: the weird orders,\nbad inputs, and interrupted flows a careless\nuser would hit.\n\nKeep both documents in my project docs, so every\nrelease runs the same pass.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/manual-and-exploratory-qa\n\nMy app:\n```\n\n**Do this now:** paste the prompt, then walk your app's release checklist by hand on a real phone before your next ship."
          },
          {
            "slug": "load-testing",
            "title": "Will It Hold Under Load?",
            "label": "Load",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/load-testing",
            "content": "---\ntakeaway: Test that it survives many users at once\nshare: 'Every test so far proves the app works for one person: you. This chapter gets you a way to find out how many real users it can take at once before it slows down or falls over, while you can still fix it.'\nrequires: [running-app, ai-agent, deployed-url]\nproduces: [load-test-results]\nteaches: [load-test, virtual-user, breaking-point, bottleneck]\nuses: [test, critical-path, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = every test so far proves it works for ONE user (you); launch day or a post that takes off means hundreds or thousands at once, and \"works for me\" says nothing about that. This chapter gets a way to find how much traffic the app takes before it slows or falls over, while you can still act. Distinct from the correctness tests in the safety-net, unit, and end-to-end chapters (by topic). */}\n\nEvery test so far proves one thing: the app works for one user, you. But launch day, or a post that takes off, means hundreds or thousands of people hitting it at the same moment. \"Works for me\" says nothing about that. This chapter gets you a way to find out how much traffic your app can take before it slows down or falls over, while you can still act on the answer.\n\n{/* KEEP: Concept. Correctness tests answer \"does it work\"; load testing answers a DIFFERENT question, \"does it still work when a crowd shows up at the same moment\". Bold-first: load testing. Keep the two-questions framing. */}\n\n## One user passing isn't many users passing\n\nYour correctness tests answer one question: does it work. **Load testing** answers a completely different one: does it still work when a crowd shows up at the same moment.\n\nThe two never overlap. A checkout that passes every test for one shopper can still crawl to a halt when three hundred of them click Pay in the same minute. You will never see that by testing alone.\n\n{/* KEEP: Step. A load-test tool fires many simulated users at the app at once and measures how it responds as the number climbs. Use k6, link official on first mention. Show the REAL artifact: a small k6 script ramping virtual users against the critical endpoint, with beginner framing (your agent writes this; here is the shape). Bold-first: virtual users. */}\n\n## A load test simulates a crowd\n\nA load-test tool fires many fake users at your app all at once and measures how it holds up as the number climbs. Each fake user is a **virtual user**: the tool pretends to be one person hitting your app, then runs thousands of them in parallel.\n\nThe standard tool for this is [k6](https://k6.io). [JMeter](https://jmeter.apache.org) and [Locust](https://locust.io) do the same job; k6 wins here because its scripts are plain JavaScript, which is the version your agent writes best. Your agent writes the script; you just name the endpoint and the peak. Here is the shape:\n\n```javascript\nimport http from \"k6/http\";\nimport { check } from \"k6\";\n\nexport const options = {\n  stages: [\n    { duration: \"1m\", target: 100 },  // ramp to 100\n    { duration: \"3m\", target: 100 },  // hold\n    { duration: \"1m\", target: 500 },  // push higher\n    { duration: \"1m\", target: 0 },    // ramp down\n  ],\n};\n\nexport default function () {\n  const res = http.get(\"https://your-app.com/checkout\");\n  check(res, {\n    \"status is 200\": (r) => r.status === 200,\n    \"under 500ms\": (r) => r.timings.duration < 500,\n  });\n}\n```\n\n{/* KEEP: Step. You ramp the load up until response times climb or errors start; THAT number is your ceiling. Knowing it now beats discovering it during your busiest hour. Bold-first: breaking point. Mermaid diagram of load climbing until it breaks. */}\n\n## Find the breaking point before users do\n\nYou push the load up until response times start climbing or errors start appearing. That number, the traffic level where it stops coping, is your **breaking point**, and it is the single most useful thing this test tells you.\n\nKnowing it on a quiet Tuesday beats discovering it during your busiest hour. If it holds at five hundred users but buckles at six, you know exactly how much headroom you have.\n\n{/* KEEP: Step. Load-test the flow that would hurt MOST under a rush (checkout, signup, the core action), not every page. When it buckles, finding and fixing the slow part is the job of the Scale part's work on bottlenecks and capacity (refer BY TOPIC, not number). Bold-first: bottleneck. Then the senior-voice prompt, ONE bottom slot, then Do this now. */}\n\n## Test the path that matters, then fix the bottleneck\n\nDo not load-test every page. Test the one flow a rush would hurt most: checkout, signup, or whatever core action your app exists for. That is where slowness costs you real customers.\n\nWhen it buckles, the slow part is your **bottleneck**, the one piece the whole flow waits on. Finding and fixing it is a separate job, and the Scale part's chapters on bottlenecks and capacity are where you do it. This chapter only finds the limit; that is where you raise it.\n\nThis prompt sets your agent up to run the test:\n\n```prompt\nAct as a senior performance engineer load\ntesting my app. Read my non-functional targets\nfirst and use the response time and traffic\nnumbers I already committed to as the pass\nmark, not a generic one.\n\nWrite a k6 script for the one critical path I\nname below. Ramp virtual users up to a\nrealistic peak for my launch, hold, then push\npast it. Report where the app starts to\ndegrade: the user count where response times\nclimb and where error rates rise. Then name\nthe single most likely bottleneck behind that\nlimit, so I can hand it off to be fixed.\n\nSay plainly whether the measured limit meets\nmy targets or misses them, and save the\nnumbers next to those targets in my specs\nfolder, so what we design against is measured.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/load-testing\n\nMy critical path and expected peak:\n```\n\n**Do this now:** paste the prompt, name your one critical path and the peak you expect, and let your agent run the load test to find the number your app breaks at."
          },
          {
            "slug": "continuous-integration",
            "title": "Running Tests on Every Push",
            "label": "CI",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/test/continuous-integration",
            "content": "---\ntakeaway: Run tests on every push\nshare: 'You wrote tests, but they only guard you when someone remembers to run them. Continuous integration runs the whole suite automatically on every push and blocks the merge when it is red, so broken code can never land.'\nrequires: [git-repo, remote-repo, test-suite, ai-agent, project-folder]\nproduces: [ci-pipeline]\nteaches: [ci, branch-protection]\nuses: [git, commit, branch, merge, repo, push, test, git-hook, model, stack, deployment, ai-coding-agent, prompt, command]\n---\n{/* KEEP: lead-in = a test only protects you if it actually runs; on your own machine it runs only when you or the agent remember, so one skipped run lets a break slip through. This chapter makes the whole suite run itself on every push, on a machine that is not yours. Gloss push once (already met commit/branch/main/merge in version-control). */}\n\nYou wrote tests, and they pass. But a test only protects you if it actually runs, and on your own machine it runs only when you or the agent remember to. One skipped run and a break slips through anyway. This chapter makes your whole suite run itself on every push, every time your code goes up to the shared repo, on a machine that is not yours.\n\n{/* KEEP: concept = continuous integration (CI): a service that runs your entire test suite automatically on every push, on a fresh cloud machine that does not depend on your laptop or the agent remembering. Bold-first: continuous integration. Plain-link GitHub Actions to the official CI docs. A green result there means green for everyone. */}\n\n## Tests only help if they run\n\nThe fix is **continuous integration**, or CI: a service that runs your whole test suite automatically, on every push, on a fresh machine that is not yours. The common one is [GitHub Actions](https://docs.github.com/en/actions), and every major host has its own.\n\nBecause it runs from scratch in the cloud, it does not care what is installed on your laptop or whether the agent remembered to run anything. A green result there means green for everyone.\n\n{/* KEEP: the real artifact = a minimal GitHub Actions workflow (.github/workflows/ci.yml) that checks out the code and runs the test command on every push. Beginner framing: you do not memorize this, the agent writes it, what matters is the shape. Swap npm test for your command. */}\n\n## Run them on every push\n\nYou set this up with one small file in your repo. It installs your project on a clean machine and runs your tests every time you push:\n\n```yaml\n# .github/workflows/ci.yml\nname: CI\non: [push, pull_request]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 20\n      - run: npm install\n      - run: npm test\n```\n\nYou do not memorize this, your agent writes it for your stack. What matters is the shape: on every push, a fresh machine checks out your code and runs your test command. Swap `npm test` for whatever your project uses.\n\nOnly two lines change for another language. `setup-node` becomes `setup-python`, `setup-go`, or your stack's equivalent, and the install and test commands become yours. Everything else in the file is the same.\n\n{/* KEEP: running the tests is only half; the other half is refusing to merge on red. A branch protection rule requires the CI check to pass, so a branch with a red suite cannot merge into main. Mechanical gate, not discipline. Callout = rule of thumb. Do NOT overlap the deploy pipeline chapter. */}\n\n## Block the merge on red\n\nRunning the tests is only half of it. The other half is refusing to merge when they fail. Turn on a [branch protection](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) rule that requires the CI check to pass, and a branch with a red suite simply cannot merge into main.\n\nNow broken code is not a matter of discipline. The gate is mechanical: green merges, red waits until it is fixed.\n\nCheck that it actually blocks, because the common failure is a check that runs the tests in the background and reports afterwards. That is a notification, not a gate. If the change lands while the result is still pending, you own neither.\n\n```mermaid\n%% caption: Every push runs the full suite on a fresh machine, and a red result blocks the merge.\nflowchart TD\n  P([1. Push]) --> CI[2. CI runs full suite]\n  CI --> Q{3. All green?}\n  Q -->|Green| M[4. Merge into main]\n  Q -->|Red| B[4. Merge blocked]\n  B -.->|fix and push| P\n```\n\n> **Rule of thumb:** a test suite that cannot block a merge is a suggestion, not a guardrail.\n\n{/* KEEP: the OTHER place tests run = a git hook on your own machine (introduced in version-control), fires automatically before code leaves, catches a break before it is even shared. Speed problem: the full suite gets slow as it grows, so the hook runs only the tests your CHANGE affects (fast), CI runs the full suite (thorough). Stage advice: solo/starting, a pre-push hook is often enough; add CI when others join or the suite grows. Cross-link version-control (hooks) by topic, do not re-teach hooks. */}\n\n## Catch it before it even leaves\n\nCI runs in the cloud, after your code is already pushed. There is a faster place to catch a break: a git hook on your own machine, the automatic check from the version control chapter, run right before the code leaves. It fails the push and tells you, before anyone else ever sees the break.\n\nThe catch is speed. As your suite grows, running all of it on every push turns slow enough that you start skipping it. So split the work: the hook runs only the tests your change actually touches, which stays fast, and CI runs the full suite on a fresh machine, which stays thorough.\n\nStarting out and working solo, a hook that runs the affected tests is often enough on its own. Add CI the moment someone else touches the project, or the suite grows past what you want to wait for locally.\n\n{/* KEEP: the auto-repair loop = a failing hook (break, missing test, stale format) hands the failure to an agent that FIXES it (adds/updates the test, cleans the format) and re-runs, so the block becomes self-repair. Mechanical fixes, so a cheap/fast model is plenty; save the expensive one for real thinking. Same wiring works for the other hooks. This is programming automation (the hook) plus AI automation (the agent), the full loop. Keep conceptual: the reader tells the agent to wire it, does not hand-code it. */}\n\n## Let an agent fix what the hook catches\n\nA failing check does not have to stop you cold. The hook caught something mechanical: a break, a missing test, a formatting slip. Hand that failure straight to an agent, and it adds the missing test, updates the stale one, or cleans up the format. The check then runs again and passes on its own.\n\nThese are chores, not thinking, so a cheap, fast model handles them fine, and you save the expensive one for real work. Wire the same auto-repair into your other hooks too, and the check that used to block you quietly fixes itself instead.\n\n```mermaid\n%% caption: A failing check hands the failure to an agent that fixes it and re-runs until green.\nflowchart TD\n  CK[1. Check fails] --> A[2. Agent fixes it]\n  A --> RE[3. Check re-runs]\n  RE --> Q{4. Green now?}\n  Q -->|No| A\n  Q -->|Yes| DONE([5. Passes])\n```\n\n{/* KEEP: one file committed once guards every push forever, free, for every contributor, no maintenance. TEST-PART CLOSER: a tested app that stays green is one you can safely harden and change (bridge to the Harden part). Cross-ref automating-your-deployment BY TOPIC (the same gate later guards the deploy, do not teach CD here). Then prompt + Do this now. */}\n\n## Set it up once, it guards forever\n\nThat one file is committed once and then guards every push forever, for you and for anyone who ever touches the project. You do not run it or remember it. It runs on its own, free, and turns red the instant something breaks.\n\nThis closes your safety net. A suite that runs itself and a gate that blocks red give you an app you can change without holding your breath. That gate is also the thing the next part stands on: you only hand work to an autonomous system once something independent can tell you it still works. Later, the chapter on automating your deployment puts the deploy itself behind this same gate.\n\nThis prompt wires CI for your project:\n\n```prompt\nAct as a senior engineer setting up CI for me.\nRead my project's real install and test commands\nfrom its manifest and my rules file, do not guess\nthem. Add a workflow that runs on every push and\non every pull request: install the project on a\nclean machine and run my full test suite,\nincluding the end-to-end and visual checks I\nalready have. Then tell me the exact branch\nprotection setting that blocks a merge into main\nuntil that check is green.\n\nKeep it minimal and explain each line the first\ntime. Then record in my rules file that green CI\nis the bar for any merge, so neither of us\nreasons around it later.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/test/continuous-integration\n\nMy stack and test command:\n```\n\n**Do this now:** paste the prompt, commit the CI workflow your agent writes, then turn on the rule that blocks a merge until the suite is green."
          }
        ]
      },
      {
        "id": "ai-os",
        "title": "Setup your AI operating system",
        "chapters": [
          {
            "slug": "os-first",
            "title": "System Comes Before the Code",
            "label": "OS-First",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/os-first",
            "content": "---\ntakeaway: Build the system before the app\nshare: You have built one app by hand, step by step. The people who win with AI build the system that runs all of it for them, and then the app is just one thing that system produces.\nrequires: [project-folder, running-app, test-suite, ai-agent]\nproduces: [operating-base]\nteaches: [operating-base]\nuses: [ai-coding-agent, test, spec, rules-file]\n---\n{/* KEEP (rewritten July 2026, user mandate): this part no longer INTRODUCES the system, that now happens on day one in the Set Up part. By here the reader has run the loop by hand through Build, Debug and Test, and this part is where trust has been earned and the machinery arrives. Lead-in must say that plainly, do NOT re-teach the factory metaphor or \"build the system before the app\", both now live earlier. */}\n\nYou defined the system on your first day and you have been feeding it ever since: rules, a spec, decisions, gates, tests. Every bit of it you have driven by hand. That was the point, because you cannot hand over work you have never done. You have now done it, and this part is where you start handing it over.\n\n{/* KEEP: the reframe that answers \"why is the automation part so late\". Doing the loop manually is what earns the right to automate it; a beginner who automates on day one has built a machine that produces work they cannot judge. Name what changes here: the same loop, now with machinery and a crew, still yours to steer. */}\n\n## Automation is what trust buys\n\nAutomation is one component of the system, not the system itself, and it is deliberately the last one to arrive.\n\nAnyone can put an agent on a schedule on day one. What they get is a machine producing work they have no way to judge, faster than they can check it. You spent the last stages learning what good output looks like on your own project, which is the only thing that makes handing it over safe.\n\nSo nothing about the loop changes here. What changes is who runs each step, how much of it survives between sessions, and how many agents can work at once without colliding.\n\n{/* KEEP: machinery earns its place. Add each piece only when a real task hurts without it; the system never hauls dead weight. Keep the one long-running-setup proof, it is the concrete evidence in the chapter. */}\n\n## Machinery earns its place\n\nAdd each piece of machinery only when a task actually hurts without it. The people who run real operations this way never carry a part they have not needed, and neither should you.\n\nThe proof is never glamorous. In one long-running setup, a single plain file describing how the deploy really works ended a mistake the agent had repeated in every session. That one page paid for the whole system inside a week.\n\n```mermaid\n%% caption: Each piece of the system arrives because a real task hurt without it, never in advance.\nflowchart LR\n  T([A task hurts]) --> W{Would one piece fix it?}\n  W -->|Yes| ADD[Add that piece, once]\n  W -->|No| SKIP[Carry nothing extra]\n  ADD --> T\n```\n\n{/* KEEP: the whole-system map, the one page that shows the reader the system was NOT started here. Keep the \"where it gets built\" column, it is what makes the arc visible. Ends by naming what this part actually adds, so the reader knows only the last blocks are new. Do this now = create the one folder that will be your operating base, separate from any single app's code. */}\n\n## The whole system, and where each piece came from\n\nOnce the machinery exists, your agents have a home: they know where things go, what matters right now, and how you want the work done. You stop re-explaining yourself and start giving commands.\n\nEverything below belongs to the software department of your operating system, the one this book builds end to end. The growth department attaches to the same tree later, and the last part of the book points at where.\n\nHere is every piece of it on one page:\n\n| Piece | What it gives you | Where it gets built |\n| --- | --- | --- |\n| One entry file every session reads | The agent walks in knowing your project | Already done, in Set Up |\n| A spec, an architecture, decisions on record | Something to build against, not vibes | Already done, in Plan and Architect |\n| Gates that block bad work mechanically | Rules that hold when nobody is watching | Already done, in Build and Test |\n| The tree, departments, and a control center | One home for everything that is not app code | This part |\n| Agents with roles, tools, memory, and limits | A crew instead of a chat window | This part |\n| A shared board, a ledger, and one task path | Work that survives the session it started in | This part |\n| Version stamps, verdicts, and a freshness sweep | Knowing whether any of it actually worked | Later, once you are live |\n\nOnly the last two blocks are new. Everything above them you already own, which is exactly why you can be trusted with what comes next.\n\n{/* KEEP: message1 = building your OWN operating system is the ideal and the ONE deliberate exception to the reuse-first ladder (choosing-your-stack): you learn how it works, it fits how YOU build, and it keeps growing with you (your own testing, your own inbox for the tasks you and your agents create, your own content system, all custom to you). message3 = it already runs a real company in production; a shareable install-and-adapt version may come next; reader can follow and vote. Link = the vote discussion (/discussions/3). Do NOT reveal the author's internal architecture. */}\n\n## Build your own, and grow it with you\n\nEverywhere else this book tells you to reuse before you build. Your operating system is the one deliberate exception, and building it yourself is the point. You learn exactly how it works, it fits how you build, and it keeps growing with you.\n\nThat means your own way to test your work, your own inbox for the tasks you and your agents create, your own way to run your content. Each piece is shaped to what matters to you, not to a generic template.\n\nIf you would rather start from a ready-made one, a system like the one this part describes already runs a real company in production. A version you can install and adapt is what could come next. You can [follow it and vote for it here](https://github.com/Mahmoudz/vibe-coding/discussions/3).\n\nThis prompt sets the base up and, more importantly, teaches your agent that it now has one:\n\n```prompt\nAct as a senior engineer setting up my operating\nbase. Read my rules file first so this fits what is\nalready recorded. Create one folder that will hold\nhow I run everything, kept outside any single app's\ncode, and put a short README in it saying what it is\nfor and what does NOT belong there, so neither of us\nfills it with app code later. Leave it otherwise\nempty; the next chapters fill it in. Then add one\nline to my rules file naming this folder as the home\nfor plans, decisions and progress, so every future\nsession looks here first.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/os-first\n\nWhere my project lives, and what I am running:\n```\n\n**Do this now:** paste the prompt so the folder exists and your agent knows it is the home for everything that is not app code."
          },
          {
            "slug": "unified-system",
            "title": "One System for Everything",
            "label": "Unification",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/unified-system",
            "content": "---\ntakeaway: Put everything in one file tree\nshare: Your plans are in one app, your tasks in another, your notes in a third, and your agent can see none of them. Put the whole operation in one tree of plain files the agent can actually read.\nrequires: [operating-base, ai-agent, project-folder]\nproduces: [agent-os-tree]\nteaches: [markdown, single-source-of-truth]\nuses: [ai-coding-agent, convention]\n---\n{/* KEEP: lead-in = your operation is scattered across apps (Notion/Trello/head) and the agent sees none of it. This chapter puts everything in one tree of plain files the agent can read and write. */}\n\nYour plans live in one app, your tasks in another, your notes in a third, and your agent can open none of them. This chapter puts your whole operation into one tree of plain files on your machine, so nothing that runs your work is hidden from the thing doing it.\n\n{/* KEEP: one tree, not ten apps. Everything (plans, tasks, notes, decisions, the app) lives in one folder tree; NOT Notion for docs, Trello for tasks, chat for decisions. Reason: the agent can open a folder, it cannot open your Notion or your memory. Show a small folder-tree sketch (device variety, os-first was all prose). */}\n\n## One tree, not ten apps\n\nEverything about your operation lives in one folder tree on your machine: your plans, your tasks, your notes, your decisions, and the app itself. Not a docs app, a task app, and a chat thread each holding a piece.\n\nThe reason is blunt: your agent can open a folder. It cannot open your Notion, your task app, or your memory of what you decided last Tuesday.\n\n```\noperating-base/\n  plans/\n    roadmap.md\n  tasks/\n    todo.md\n  decisions.md\n  app/            (your actual application code)\n```\n\nThat is day one. A production tree grows branches you will build through this part: reports the agents write, skills they load, a log of everything that happened.\n\n{/* KEEP: everything is a plain file (usually markdown = plain text with light formatting), not a proprietary format locked in an app. A plan, a task list, a decision = a plain text file the agent reads and writes natively, and that you can still open in ten years. Gloss markdown (new term). Bold-first: markdown. */}\n\n## Everything is a plain file\n\nEvery piece is a plain text file, usually [**markdown**](https://commonmark.org), which is just plain text with light formatting. Not a document locked inside some app's format.\n\nA plan is a text file. A task list is a text file. A decision is one line in a text file. That is exactly what your agent reads and writes on its own, and what you can still open in ten years when today's apps are gone.\n\n> **Hint:** some people formalize this into a shared convention, so every agent reads a knowledge base the same way. One is the [Open Knowledge Format](https://okf.md): markdown files plus a few shared rules for how each file is labeled. You do not need a spec to start, but it is a useful reference once your tree grows.\n\n{/* KEEP: one source of truth. Because it's one tree, each thing lives in exactly ONE place; the current priorities are one file, not remembered three ways. Change it there and every agent reading it sees the truth. No syncing, no \"which version is right\". */}\n\n## One source of truth\n\nBecause it is all one tree, each thing lives in exactly one place. Your current priorities are one file, not three half-remembered versions in your head and two apps.\n\nWhen something changes, you change it there. Every agent that reads it then sees the same truth, with no syncing and no \"which copy is right.\"\n\n```mermaid\n%% caption: Change the one priorities file and every agent that reads it sees the same truth.\nflowchart LR\n  YOU([You]) -->|change once| F[(Priorities file)]\n  F -->|reads| A1([Agent 1])\n  F -->|reads| A2([Agent 2])\n  A1 --> SAME[Same truth]\n  A2 --> SAME\n```\n\n{/* KEEP: why one beats many. Ten apps = ten silos the agent can't cross + a picture only you can assemble in your head. One tree = the agent sees the whole thing, moves work between parts, nothing hidden. Also it's YOURS: plain files on your disk, portable, backed up with your code, not locked in someone's cloud. */}\n\n## Why one system beats many\n\nTen apps mean ten silos your agent cannot cross, and a full picture only you can hold, in your head. One tree means the agent sees everything, moves work between the parts, and misses nothing.\n\nIt is also yours. Plain files on your own disk are portable, backed up alongside your code, and never locked inside someone else's cloud.\n\nThis prompt does the first move for you, and sets the rule that keeps the tree one tree:\n\n```prompt\nAct as a senior engineer starting my one system.\nRead my rules file and my operating base README so\nthis lands where it belongs. I will name one thing I\ncurrently track somewhere else. Move it into a plain\ntext file inside my operating base, in the format the\nrest of the system will use, and tell me what I can\nnow stop opening. Then record in my rules file that\nthis tree is the single source of truth for how I\nrun things, and that new tracking goes here as a\nplain file rather than into another app.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/unified-system\n\nThe one thing I track elsewhere today:\n```\n\n**Do this now:** paste the prompt and move one thing out of another app and into your system. That file is the start of the tree."
          },
          {
            "slug": "departments-and-folders",
            "title": "Folders as an Org Chart",
            "label": "Departments",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/departments-and-folders",
            "content": "---\ntakeaway: Organize folders like company departments\nshare: Every operation is already an org chart, you just have to make the folders match it. Draw the company as directories and anyone, human or agent, understands it in ten seconds.\nrequires: [operating-base, agent-os-tree, ai-agent]\nproduces: [department-folders, status-file]\nteaches: [status-file]\nuses: [ai-coding-agent, cohesion, prompt, repo, gitignore, secret]\n---\n{/* KEEP: lead-in = your work is many kinds of thing scattered with no place an agent knows to look. This chapter turns the operation into folders, an org chart on disk you and your agents read the same way. */}\n\nYour operation is a dozen different kinds of work, scattered across apps and your head, with no place an agent knows to look. This chapter turns it into folders: an org chart on disk that you and your agents read the exact same way.\n\n{/* KEEP: draw the company as directories before any automation (marketing, sales, money, customers, ops); the whiteboard tree = the on-disk tree, so the structure of the work and the structure of the files are the same. Anyone who opens it understands the operation in ten seconds. Show a folder-tree sketch. Also the privacy line, right where the tree is created: this holds revenue, customers and decisions, so a version-controlled operating base is a PRIVATE repo, .gitignore covers anything with a key, and real customer records stay in the app's database under the Protect part's rules. */}\n\n## Folders are your org chart\n\nBefore you write a line of automation, draw your operation as directories. Marketing, sales, money, customers, ops: each box on the whiteboard becomes a folder in your operating base.\n\n```\noperating-base/\n  marketing/\n  sales/\n  customers/\n  money/\n  ops/\n  app/          (the product itself)\n```\n\nNow the structure of the work and the structure of the files are the same thing. Anyone who opens the tree, you or an agent, understands the operation in ten seconds.\n\nNotice what those folders will hold: your revenue, your customers, your decisions. So if you put this tree under version control, the repository is private, and the same `.gitignore` habit from your secrets setup covers anything with a key in it. Keep notes about customers here if you like, but their actual records stay in the app's database, where the Protect part's rules about personal data apply.\n\n{/* KEEP: organize by FUNCTION, not by tool or file type. No \"spreadsheets\"/\"docs\" folders; one sales/ folder holds everything sales whatever the format. High cohesion inside, clean seams between: an agent working sales opens one folder and finds its whole world. */}\n\n## One folder per function\n\nOrganize by function, never by tool or file type. You do not want a spreadsheets folder and a docs folder; you want a `sales/` folder that holds everything sales, whatever the format.\n\nHigh cohesion inside each folder, clean seams between them. When an agent works on sales, it opens one folder and finds the whole world it needs, and nothing leaks across the walls.\n\n{/* KEEP: each folder gets ONE control file, a status file (call it _status.md), holding three things: the department's rules, its current state, and a running log. It's the surface an agent reads to work and writes to record what it did. You never hunt for a department's truth. Show a minimal _status.md skeleton. Bold-first: status file. */}\n\n## Each department runs from one status file\n\nEvery folder gets a single control file, a **status file**, call it `_status.md`. It holds three things: the rules for that department, its current state, and a running log.\n\n```\n# Sales - status\n\n## Rules\n- Never promise a date we have not agreed internally.\n\n## Current state\n- 3 live deals, 1 in contract.\n\n## Log\n- 2026-07-08: sent the Acme proposal.\n```\n\nIt is the one surface an agent reads to do the work and writes to record what it did. The rule is standing: any agent that works in a department appends a dated line to its Log before it finishes. That way you never hunt for the truth of a department. Later, your briefing command reads these files to build the one-screen picture, which is why keeping them honest pays off.\n\n{/* KEEP: start with the departments you HAVE, not the dream company. Three folders is fine. Add a department the day a real function appears, not before. The org chart grows as the operation grows, one folder at a time, never carrying rooms nobody lives in. Do this now = create one folder per function you run today + an empty _status.md in each. */}\n\n## Start with the departments you have\n\nDo not model the company you dream of. Model the one that exists today. Three folders is a fine start.\n\nYou add a department the day a real function appears, not before. The org chart grows the way the operation grows, one folder at a time, and it never carries rooms nobody lives in.\n\n```mermaid\n%% caption: Add a department only when a real function appears, never before.\nflowchart TD\n  Q{New function actually running?}\n  Q -->|Yes| ADD[Add a folder]\n  Q -->|Not yet| WAIT[Do not add it]\n```\n\nThis prompt has your agent build the tree for you:\n\n```prompt\nAct as a senior engineer extending my operating system.\nRead my operating base first and reuse the folders and\nnaming already in it, never duplicate or rename them.\n\nIn it, create one folder per function I run, and put an\nempty _status.md in each, with three headings: Rules,\nCurrent state, Log. Do not invent functions I did not\nname, and keep secrets and generated files out.\n\nTell me any function I named that already has a home in\nthe tree, so I do not end up with two of it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/departments-and-folders\n\nThe functions I run today:\n```\n\n**Do this now:** paste the prompt above and list the functions you actually run, so your agent builds the department tree for you."
          },
          {
            "slug": "control-center",
            "title": "Your Command Hub",
            "label": "Control Center",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/control-center",
            "content": "---\ntakeaway: Steer the whole operation from one cockpit\nshare: \"Ten departments running at once pull you in ten directions. Build one room you steer from: a cockpit above every folder where you see the whole operation on one screen and decide what matters.\"\nrequires: [operating-base, department-folders, ai-agent]\nproduces: [control-center, planner-file, decision-log]\nteaches: [cockpit, decision-log]\nuses: [ai-coding-agent, status-file, prompt, command]\n---\n{/* KEEP: lead-in = many departments running at once pull you ten directions. This chapter builds the one room you steer from: a cockpit above every folder where you see the whole operation on one screen and decide what matters. */}\n\nTen departments running at once will pull you in ten directions. This chapter builds the one room you steer from: a cockpit that sits above every folder, where you see the whole operation on one screen and decide what matters this week.\n\n{/* KEEP: create ONE top-level cockpit folder above every department; it does no work, it points at the work. From here you see everything and decide. Every other folder is an employee, this one is your desk. Show the cockpit tree. Bold-first: cockpit. */}\n\n## One hub steers it all\n\nCreate a single top-level folder, the **cockpit**, that sits above every department. Give it an obvious name so it sorts to the top:\n\n```\noperating-base/\n  _control/\n    planner.md      (what we're doing right now)\n    decisions.md    (every call, with the reason)\n    todos/          (the priority list)\n  marketing/\n  sales/\n  ...\n```\n\nIt does no work. It points at the work. Every other folder is an employee; this one is your desk, and it is where you stand to run everything.\n\n{/* KEEP: the heart of the hub = one planning file answering \"what are we doing right now\" (focus, roadmap, the few numbers that matter, money). Agents read it to prioritize, you read it to remember what you decided. When everything feels urgent, this file makes one thing win. Shown as a real artifact (planner.md sketch). todos/ glossed = the committed work the plan produces. */}\n\n## Set the current focus and priorities\n\nThe heart of the cockpit is one planning file that answers a single question: what are we actually doing right now.\n\n```\n# Planner\n\n## Focus (this week)\n- Get the first 10 paying users.\n\n## Roadmap\n- Now: onboarding emails. Next: pricing page test.\n\n## Numbers\n- 41 signups, 6 paying, $174 MRR.\n```\n\nAgents read it to know what to prioritize when they have a choice. You read it to remember what you decided. When everything feels urgent, this one file is what makes a single thing win.\n\nThe `todos/` folder next to it holds the committed work the plan produces, each task one small file.\n\n{/* KEEP: decision log = every meaningful call gets ONE line, newest first, with the reason (why a feature is on, why this price, why that channel died). Stops you AND the agents relitigating the same call monthly and silently reversing past choices. The log is the operation's memory of its own judgment. Show decisions.md lines. Bold-first: decision log. */}\n\n## Keep a decision log\n\nEvery meaningful call gets one line in a **decision log**, newest first, with the reason attached:\n\n```\n# Decisions (newest first)\n\n- 2026-07-08: Price at $29/mo, not $19. Room to discount later.\n- 2026-07-06: Dropped the LinkedIn channel. No signups in 6 weeks.\n```\n\nThis is not bureaucracy. It is what stops you and your agents from relitigating the same decision every month, or quietly reversing a choice you made for a reason you have since forgotten.\n\n{/* KEEP: the point of the hub = a single entry point, one command that pulls the state of every area into one briefing and shows what needs you. You don't visit ten folders, you run one command, read one screen, act. Forward-points softly to Reporting (commands built there); gloss, don't teach mechanics. Do this now = create the cockpit with a planner file + decisions log, write today's focus + one recent decision. */}\n\n## Drive it with one command\n\nThe whole point of the cockpit is that it can be read in one move. It is laid out so a single command can pull the state of every area into one briefing, instead of you opening ten folders by hand.\n\nIn a running system that briefing has a fixed shape: the numbers that moved, what landed since you last looked, and the decisions waiting on you. You build that command later, when you set up reporting. For now, know that the cockpit is the thing it reads: one screen in, one decision out.\n\n```mermaid\n%% caption: One command reads every department into a single briefing: one screen in, one decision out.\nflowchart LR\n  CMD[One command] -->|reads| MK[marketing status]\n  CMD -->|reads| SA[sales status]\n  CMD -->|reads| MO[money status]\n  CMD --> BR[One briefing]\n  BR --> YOU([You decide])\n```\n\nThis prompt stands up the whole cockpit for you:\n\n```prompt\nAct as a senior engineer setting up my operating system.\nRead my operating base and its department folders first,\nplus my rules file and spec, so the cockpit reflects the\noperation that already exists.\n\nAt the top of my operating base, create a _control folder\nwith: planner.md (my focus, roadmap, key numbers, money),\ndecisions.md (a dated log, newest first, each line with\nits reason), and a todos/ folder.\n\nSeed planner.md from what I tell you below. Seed\ndecisions.md with the calls already made and findable in\nmy rules file, spec, and department folders, one dated\nline each with its reason. Mark which ones you inferred\nrather than found.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/control-center\n\nMy focus and top priorities right now:\n```\n\n**Do this now:** paste the prompt and describe your current focus, so your agent builds the cockpit and seeds it."
          },
          {
            "slug": "configuring-agents",
            "title": "Standing Up Your Agents",
            "label": "Configuration",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/configuring-agents",
            "content": "---\ntakeaway: Give each agent a role in a file\nshare: An agent with no configuration is a stranger who shows up every morning having forgotten the job. Configuration is a file that hands it the job description before it starts.\nrequires: [ai-agent, project-folder, rules-file, project-docs]\nproduces: [agent-config]\nteaches: [role, skill, rule]\nglosses: [frontmatter]\nuses: [ai-coding-agent, model, prompt, commit, frontmatter, api, convention, code-review]\n---\n{/* KEEP: lead-in = an unconfigured agent is a stranger who forgot the job daily. Configuration = a file that hands it the job description before it starts. You set your project rules earlier; here you define a specific agent's role. CODE-FORWARD chapter. */}\n\nAn agent with no configuration is a stranger who shows up every morning having forgotten the job. Configuration is the file that hands it the job description before it starts. You already wrote your project's rules; this chapter defines a specific agent with a role of its own.\n\n{/* KEEP: a role is a FILE, not a paragraph you paste. Show the real shape: frontmatter (name, description, tools allowed) + standing instructions. A coworker defined in version control, not a mood set each session. Bold-first: role. */}\n\n## Give each agent a role\n\nA **role** is a small file, not a paragraph you retype into chat each time. In Claude Code it lives in `.claude/agents/`, and every serious tool has the same idea: a [YAML](https://yaml.org) **frontmatter** block, the settings at the top, plus instructions.\n\n```yaml\n---\nname: reviewer\ndescription: Reviews code after it's written. Use before any commit.\ntools: Read, Grep, Glob\n---\nYou review for correctness, security, and style. You do not\nwrite features and you do not refactor. Report issues by\nseverity, then stop. A hardcoded secret is a blocking issue.\n```\n\nThat is a coworker defined in a file your project keeps, not a mood you set and lose each session.\n\n> **Hint:** Each agent runs on a model, and the best model for one job is rarely the best for every job. Route your agents through [OpenRouter](https://openrouter.ai), one account across most models. That way you can match a model to a role and swap as the leaders change, without locking your whole system to a single vendor.\n\n{/* KEEP: a role carries two attachments, kept as SEPARATE composable files: skills = procedures loaded only when the task needs them; rules = hard lines, always on. Show the folder layout. Don't pour everything into one giant prompt. Bold-first: skill, rule. */}\n\n## Skills and rules per agent\n\nA role carries two kinds of attachment, and you keep them as separate files so they compose. A **skill** is a procedure loaded only when the task needs it. A **rule** is a hard line, always on.\n\n```\n.claude/\n  agents/reviewer.md         (the role)\n  skills/security-review.md  (loaded when reviewing auth code)\n  rules/no-secrets.md        (always on, every turn)\n```\n\nThat layout is Claude Code's; every serious tool has an equivalent folder. You never pour all of it into one giant prompt. You attach the right skill to the right role and let the rest stay out of the way until it is needed.\n\n{/* KEEP: DOCS AS SOURCE OF TRUTH = heavy or shared knowledge lives in ONE doc; the skill/rule POINTS to it instead of copying, so nothing drifts. Ties back to the docs written in the Architect part (README, architecture, ADR). Distinct from agent-memory's \"keep it short\" (memory-file bloat) and its MEMORY.md index: this is skill->doc single source of truth to kill duplication drift. */}\n\n## Point skills at your docs, don't copy them\n\nSome knowledge is heavy or shared: your API's rules, the architecture you wrote down, the conventions the whole project follows. Do not paste it into a skill. Keep one doc as the single source of truth and have the skill point to it: `follow the API contract in docs/api.md`.\n\nCopy the knowledge instead and the two versions drift the day one of them changes. A pointer stays true, because there is only one copy left to update.\n\n```mermaid\n%% caption: Every skill and rule points at one doc, so nothing drifts when it changes.\nflowchart LR\n  DOC[(docs/api.md)]\n  RS[reviewer skill] -->|points to| DOC\n  BS[builder skill] -->|points to| DOC\n  AR[api rule] -->|points to| DOC\n```\n\n{/* KEEP (added July 2026, user mandate): the compounding move. A skill written once by you goes stale; a skill the AGENT updates the moment it learns something durable is how the system gets better as you build instead of decaying. The trigger is the second correction: correct the same thing twice and it belongs in a skill. Explicitly bound it, or the agent writes a skill for everything and the folder becomes noise. */}\n\n## Let the agent write its own skills\n\nYou will not sit down and author these. The useful ones get written the moment something is learned, and the agent is the one who learns it.\n\nGive it one standing instruction: when I correct the same thing twice, write it into the skill that covers it, or start a new skill if none does. The second correction is the trigger, because the first might be a one-off and the third is one too many.\n\nThat is what makes the system compound. The deploy quirk you explained in March is in the deploy skill by April, and nobody explains it again.\n\n> **Watch out:** bound this or you get a hundred skills nobody loads. A skill earns its place when it is a repeatable procedure or a hard-won fact, not when it is a preference you happened to voice once.\n\n{/* KEEP: unconfigured agents DRIFT (same request, different shape Monday vs Friday); a rule file pins the shape. Show a real rules/output.md. The quality bar lives in a file, not in your memory of how you asked. */}\n\n## Configuration keeps output consistent\n\nUnconfigured agents drift: the same request gives a different shape of answer on Monday and Friday. A rule file pins the shape:\n\n```\n# rules/output.md\n- Answer in bullets, never a wall of text.\n- Back every claim about the system with a command you ran.\n- No \"should be\" or \"probably\". Check, then state.\n```\n\nNow the quality bar lives in a file, not in your memory of how you happened to ask last time.\n\n```mermaid\n%% caption: Without a rule the same request drifts in shape; a rule file pins it the same every time.\nflowchart LR\n  REQ([Same request]) --> Q{Rule file?}\n  Q -->|No rule| DR[Different shape each day]\n  Q -->|Rule pins shape| SAME[Same shape every time]\n```\n\n{/* KEEP: configuration is an ASSET, not a per-task chore. The role defined today serves every task that agent runs; the rule written once fires on every future turn. An hour standing an agent up right pays back on every job after. Config is committed alongside the code it governs. Do this now = create one role file for a job you repeat (a reviewer). */}\n\n## Write it once, reuse everywhere\n\nConfiguration is an asset, not a chore. The role you define today serves every task that agent ever runs, and the rule you write once fires on every future turn.\n\nAn hour spent standing an agent up correctly pays back on every job it does after. You are not configuring a task, you are configuring an employee, and the file is committed alongside the code it governs.\n\nThis prompt has your agent write its own role file, in your tool's format:\n\n```prompt\nAct as a senior engineer configuring my agents. Create a\nrole file for a reviewer agent, in the format my tool uses\nand in the folder my operating base already keeps agents\nin: frontmatter with name, description, and the minimum\ntools it needs, then standing instructions to review for\ncorrectness, security, and style and then stop, treating a\nhardcoded secret as a blocking issue. Point it at my rules\nfile, my architecture map, and my conventions instead of\ncopying any of them in, so there is one copy to update.\nKeep it short, then add one dated line to my decision log\nsaying this agent exists and what it is for. Finally, add\none standing rule to my rules file: when I correct the\nsame thing twice, write it into the skill that covers it,\nor start a new one, so the system learns as we go.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/configuring-agents\n\nMy tool and project:\n```\n\n**Do this now:** paste the prompt so your agent writes the reviewer role file, then read it and tighten one line yourself."
          },
          {
            "slug": "agent-memory",
            "title": "What the Agent Remembers",
            "label": "Memory",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/agent-memory",
            "content": "---\ntakeaway: Give the agent a memory file it always reads\nshare: \"Agents are brilliant and amnesiac, they forget your whole world between sessions. A memory file fixes the amnesia: one file the agent reads at the start of every session so you never re-explain.\"\nrequires: [ai-agent, project-folder, git-repo, rules-file, stack-chosen]\nproduces: [agent-memory-file]\nteaches: [memory-file]\nuses: [ai-coding-agent, rule, skill, repo, prompt]\n---\n{/* KEEP: lead-in = agents forget everything between sessions; a memory file is one file the agent auto-reads at session start so it walks in already knowing your world. You met the idea as a rules file (Part 2); this is the real per-tool file + the discipline that keeps it useful. CODE-FORWARD. */}\n\nAgents are brilliant and amnesiac. Close one and reopen it, and your project, your rules, your whole world are gone. A memory file fixes that: one file the agent reads automatically at the start of every session, so it walks in already knowing the room instead of asking you again.\n\n{/* KEEP: the concept, tightened (you met it as the rules file in Part 2). The memory file holds what is ALWAYS true: who you are, how you work, the project, what must never happen. Show a real CLAUDE.md-style example. It's the constitution, not the encyclopedia. */}\n\n## The file your agent reads first\n\nYou met this idea as your rules file. The **memory file** is that file, made real for each tool. It holds what is always true: who you are, how you work, what must never happen. A few lines, read before the agent does anything.\n\n```\n# Project: my-app\n\n- Stack: Next.js + Postgres. One language, TypeScript.\n- New code goes under src/, one folder per feature.\n- Never commit secrets. Read them from .env.\n- Run the app and confirm it works before saying done.\n```\n\nKeep it the constitution, not the encyclopedia: the standing law, not every detail.\n\n{/* KEEP: every serious tool has ONE always-loaded file; name the real ones (swappable). Table: tool -> file. The lesson: find yours and set it up first, not as an afterthought. Real tools named + linked. */}\n\n## Find your tool's file\n\nEvery serious agent tool auto-reads one file. Same idea, different name:\n\n| Tool | File it reads |\n| --- | --- |\n| [Claude Code](https://claude.com/claude-code) | `CLAUDE.md` at the repo root |\n| [Codex](https://developers.openai.com/codex) | `AGENTS.md` at the repo root |\n| [Cursor](https://cursor.com) and most editors | a rules file or `.cursor/rules/` folder |\n\nFind yours and treat it as the first thing you set up, not an afterthought. Any equivalent works; the file changes, the idea does not.\n\nThere is now a shared convention for this, [AGENTS.md](https://agents.md), a single file over 30 tools read the same way. If your tool supports it, one file covers most of them at once.\n\n{/* KEEP: plug-in pattern = for an agent with NO native memory file, keep one canonical file yourself and inject it at session start (by hand or a tiny wrapper). Mechanism varies, principle holds: the standing truth reaches the agent before it acts. */}\n\n## No built-in file? Inject it yourself\n\nIf your agent has no native memory file, you build the behavior. Keep one canonical file, `context.md`, and paste it (or have a tiny wrapper prepend it) at the start of each session.\n\nThe mechanism does not matter. The principle does: the standing truth of your project reaches the agent before it does anything else.\n\n{/* KEEP: keep it short = every line is re-sent every turn, so bloat costs on every request forever. Cap it, push topical detail into skills loaded on demand, fix a line the day a fact changes. The MEMORY.md index: one line per durable fact, detail in linked files. */}\n\n## Keep it short, or it rots\n\nEvery line of a memory file is re-sent on every turn, so bloat is a tax you pay forever, on requests that never even touch the topic. Keep it brutally short: only what must be true always. Push topical detail into skills the agent loads on demand.\n\nTreat a couple hundred lines as a rough ceiling. Past that, every extra line taxes every request whether or not it is relevant. If yours is longer it is doing too much, so move the topical detail into a skill.\n\nOne question sorts anything you are about to add. Would this need to fire on a turn that does not touch its topic? If yes, it belongs here. If no, it belongs in a skill that loads when the topic comes up.\n\nFor facts that pile up, keep an index instead of a wall:\n\n```\n# MEMORY.md\n- Auth: we use email + magic link. Details in auth/notes.md.\n- Billing: Stripe, test mode until launch. See money/stripe.md.\n```\n\nOne line per durable fact, the detail in a linked file. Fix any line the day the fact changes; a short current file beats a long stale one every time.\n\n{/* KEEP: how memory gets WRITTEN, not just read. Don't hand-maintain it: tell the agent to save the fact when you correct it, so the file grows itself. But two disciplines or it rots: one fact per file/line, and a recalled memory that names a file or flag is a hint to VERIFY against live reality, never a fact to act on (old memory = old documentation). */}\n\n## Let the agent write it, but verify what it recalls\n\nYou do not maintain this by hand. When you correct the agent, tell it to save the correction, and the file grows itself. Session 1 you fix a mistake. Session 40 it never repeats, because the note loads every time.\n\nTwo disciplines keep it from rotting. The first: one fact per line, deduped. The second: a recalled line that names a file or a setting is a hint to check, never a fact to trust.\n\nA note written months ago can point at something since renamed. Treat old memory like old documentation, and verify against reality before acting on it.\n\n```mermaid\n%% caption: You correct once and the agent saves it; a recalled line naming a file is a hint to verify, not a fact.\nflowchart LR\n  YOU([You correct]) -->|save it| MEM[(Memory file)]\n  MEM -->|loads next session| AG([Agent])\n  AG --> Q{Names a file or flag?}\n  Q -->|Yes| VER[Verify against reality]\n  Q -->|No| USE[Use the fact]\n```\n\n{/* KEEP: prompt = have the agent create the right memory file for the reader's tool, seeded from their project, kept short. Ends with Do this now. */}\n\n## Set up your memory file\n\nThis prompt has your agent create the right file for your tool:\n\n```prompt\nAct as a senior engineer setting up my agent's memory.\nFind the memory file my tool auto-reads (CLAUDE.md,\nAGENTS.md, or a rules file), create it at the right place,\nand seed it from what I already have: my rules file, my\nconventions, my architecture map, and my module\nboundaries. Do not write a second version of any of them.\n\nKeep it short, only what must be true every session. For\nanything topical, write one line pointing at the file\nthat holds it: my spec, my project docs, my decision log.\nIf two of those already contradict each other, tell me\nwhich to fix rather than copying both in.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/agent-memory\n\nMy tool and project:\n```\n\n**Do this now:** paste the prompt so your agent writes its own memory file, then read it and cut any line that is not true on every single session."
          },
          {
            "slug": "agent-tools",
            "title": "Connecting It to the World",
            "label": "Tools",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/agent-tools",
            "content": "---\ntakeaway: Check, don't guess\nshare: \"A model with no tools can only think and talk. Tools are how it reaches out and touches the real world: your database, your browser, your repo, your accounts, so it checks instead of guessing.\"\nrequires: [ai-agent, project-folder, stack-chosen, terminal-access]\nproduces: [agent-tools-config]\nteaches: [mcp, agent-tool, custom-tool]\nuses: [model, ai-coding-agent, database, api, function, prompt, repo]\n---\n{/* KEEP: lead-in = a model with no tools can only think and talk; tools let it touch the real world (database, browser, repo, accounts) so it checks instead of guessing. CODE-FORWARD. */}\n\nA model with no tools can only think and talk. Tools are how it reaches out and touches the real world: your database, your browser, your repository, your accounts. With them, the agent stops guessing and starts checking.\n\n{/* KEEP: MCP (Model Context Protocol) = the standard plug for connecting an agent to an external system; register a server in config, the agent gains real actions. Show the MCP JSON config. Real tools named + swappable. Bold-first: MCP. Link: modelcontextprotocol.io. */}\n\n## What MCP is\n\n**MCP** (the Model Context Protocol) is the standard plug for connecting an agent to an outside system. You register a server in a config file, and the agent gains a set of real actions. One plug shape covers every integration, so you never hand-wire them one by one:\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-postgres\",\n               \"postgresql://localhost/app\"]\n    }\n  }\n}\n```\n\nClaude Code reads this from an `.mcp.json` file; most tools read something like it. The servers are swappable; the plug is the same. See [modelcontextprotocol.io](https://modelcontextprotocol.io).\n\n```mermaid\n%% caption: MCP is one standard plug the agent reaches real systems through.\nflowchart LR\n  A([Agent]) --> MCP[MCP plug]\n  MCP --> DB[(Database)]\n  MCP --> BR[Browser]\n  MCP --> GH[GitHub]\n  MCP --> API[Paid APIs]\n```\n\n{/* KEEP: with connections wired the agent stops guessing and starts checking: queries the live DB instead of assuming a number, drives a real browser to test a page, opens PRs on GitHub, calls APIs you pay for. Show a real query. \"the agent just looked.\" */}\n\n## Databases, browsers, GitHub, APIs\n\nOnce it is wired, \"the agent cannot know that\" becomes \"the agent just looked.\" Instead of assuming a number, it runs the query:\n\n```sql\nSELECT count(*) FROM users\nWHERE created_at > now() - interval '7 days';\n```\n\nInstead of describing a bug it drives a real browser and reads the console. Instead of narrating a change it puts that change up for review on GitHub. Each connection turns a guess into a fact.\n\n{/* KEEP: custom tools = when no server exists, write one: a small named function with a TYPED input so the model calls it correctly every time. Show a @tool example. You give it a few exact levers, not everything. */}\n\n## Custom tools\n\nWhen no ready-made server exists, you write one, in whatever language your tool's SDK uses. A custom tool is a small named function with a typed input, so the model calls it the same way every time:\n\n```python\n@tool\ndef send_alert(message: str, level: Literal[\"info\", \"critical\"]) -> str:\n    \"\"\"Notify the operator. Use 'critical' only for outages.\"\"\"\n    post_to_channel(message, level)\n    return \"sent\"\n```\n\nYou are not teaching the agent everything. You are handing it a few exact levers that do the specific things your system needs.\n\n{/* KEEP: when a tool beats a prompt = if you explain the same procedure in prose more than twice, make it a tool. Prompts = judgment; tools = exact, repeatable actions. Move the mechanical into typed tools, leave the prompt for thinking. */}\n\n## When a tool beats a prompt\n\nThe rule of thumb: if you explain the same procedure in prose more than twice, it wants to be a tool. Prompts are for judgment; tools are for actions that must be exact and repeatable.\n\n\"Carefully format the currency like this, round like that\" is a tool waiting to be written. Move the mechanical into tools, and leave the prompt for thinking.\n\n```mermaid\n%% caption: Mechanical, repeated procedures become tools; judgment stays in the prompt.\nflowchart TD\n  Q{Same procedure explained twice?}\n  Q -->|yes, mechanical| TL[Make it a tool]\n  Q -->|no, needs judgment| PR[Leave it a prompt]\n```\n\n{/* KEEP: prompt = have the agent wire up one MCP server for the reader's stack (or write one custom tool) so it can check reality. Ends with Do this now. */}\n\n## Wire up your first tool\n\nThis prompt connects your agent to something real:\n\n```prompt\nAct as a senior engineer connecting my agent to my stack.\nPick the one connection that would help most right now (my\ndatabase, my repo, or my browser), set up its MCP server in\nmy tool's config, and show me one real check it can now run\ninstead of guessing. Give it read-only access unless a\nwrite is the whole point. Then record the choice as one\nline in my decision log, and add a line to my rules file\ntelling my agents to check through this tool rather than\nassume.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/agent-tools\n\nMy stack and what I want it to see:\n```\n\n**Do this now:** paste the prompt and wire up one connection, then ask your agent a question it can only answer by actually looking."
          },
          {
            "slug": "multiple-agents",
            "title": "When One Isn't Enough",
            "label": "Multi-Agent",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/multiple-agents",
            "content": "---\ntakeaway: Use more agents, each doing less\nshare: \"One agent doing everything is a solo founder doing every job: it works until it doesn't. The fix is not a bigger agent, it is more agents, each doing less, handing work to the next.\"\nrequires: [ai-agent, agent-config, project-folder, running-app]\nproduces: [agent-team, handoff-file]\nteaches: [handoff, lead-agent, specialized-agent]\nuses: [ai-coding-agent, role, skill, code-review, test, prompt, token, branch, worktree, merge]\n---\n{/* KEEP: lead-in = one agent doing everything is a solo founder doing every job; works until it doesn't. The fix isn't a bigger agent, it's more agents each doing less. CODE-FORWARD. */}\n\nOne agent doing everything is a solo founder doing every job. It holds up until it does not. The fix is not a bigger agent, it is more agents, each doing less, each handing clean work to the next.\n\n{/* KEEP: signs one agent isn't enough = loses the thread on long tasks; plans+builds+reviews in one breath so the review is soft (same mind grading its own work); context fills; quality sags on anything with several moving parts. */}\n\n## Signs one agent isn't enough\n\nYou feel it before you can name it. The agent starts strong and loses the thread on a long task. It plans, builds, and reviews in one breath, and the review is soft because the same mind that wrote the code is grading it.\n\nIts context fills up, and quality sags on anything with more than a few moving parts. Those are the signals that the work has outgrown a single seat.\n\n{/* KEEP: the first and most powerful split is by PHASE: one plans, one builds, one reviews with fresh eyes. The reviewer catches what the builder can't see precisely because it didn't write it. Separation of roles = separation of blind spots. COST is named here: three seats cost roughly 3x one pass because each re-reads the context, tokens are money and latency, so split only where the review earns it, put mechanical roles on cheap models (the reason for the one-provider routing hint), and cap spend before scheduling. */}\n\n## Planner, builder, reviewer\n\nThe first and strongest split is by phase. One agent plans the work, another builds it, a third reviews it with fresh eyes.\n\nThis mirrors how real teams work, and for the same reason: the reviewer catches what the builder cannot see, precisely because it did not write the thing. Separation of roles is separation of blind spots.\n\nIt also costs roughly three times one pass, because each seat reads the context again and every token is money and waiting. So split by phase where the review actually catches things, not everywhere. Put the mechanical roles on cheap small models, which is the real reason to route your agents through one provider that reaches many. And cap the spend before you put any of this on a schedule.\n\n{/* KEEP: beyond phases, spin up specialists (security reviewer, test writer, researcher), each with its own skills + narrow standard of \"good.\" A specialist beats a generalist on its home turf because its whole config is bent toward one job. Each is a role file (ref configuring-agents). */}\n\n## Specialized agents\n\nBeyond the phases, you spin up specialists: a security reviewer, a test writer, a researcher. Each is a role file of its own, with its own skills and its own narrow standard of good.\n\nA specialist beats a generalist on its home turf, because its whole configuration is bent toward one kind of excellence. You assemble a team, not a hero.\n\n{/* KEEP: the team is only as good as its handoffs; one agent's output must become the next's input cleanly. File-based handoff: agent A writes a file with frontmatter (source, verdict); agent B reads it and stamps it (planned_in) so it isn't re-read. The FILE is the contract. Show the frontmatter. */}\n\n## Handoffs between them\n\nA team is only as good as its handoffs. One agent's output has to become the next one's input with nothing lost in the gap. The cleanest handoff is a file: agent A writes it, agent B reads it.\n\n```yaml\n---\nsource: error-report\nverdict: needs-fix\nhandled_by: null\n---\nCheckout throws on empty cart. Repro + fix below.\n```\n\n{/* KEEP: the write-collision rule needs a MECHANISM, not just a rule: concurrent agents each get their own working copy (separate branch or git worktree) and come back through the normal review/merge path; anything you cannot separate runs sequentially. */}\n\nThe builder writes that, the reviewer reads it and stamps `handled_by` so it is never picked up twice. The file is the contract between agents, so no context lives only in one agent's head.\n\nSomeone has to run the team, and it is simpler than it sounds. One lead agent spawns the others with a clear brief each, waits, then reads back their summaries to decide what happens next. The children do not talk to each other. Reads fan out freely; writes to the same file stay with one agent, so two never edit it at once and clobber each other.\n\nKeeping that rule needs a mechanism, and you already have it. Agents that run at the same time each get their own working copy, a separate branch or a git worktree. Their work comes back through the normal review and merge path. Anything you cannot separate that way runs one after the other instead.\n\n```mermaid\n%% caption: One lead spawns the others and reads back their summaries; the children never talk to each other.\nflowchart TD\n  LD[Lead agent] -->|brief| BU[Builder]\n  LD -->|brief| RV[Reviewer]\n  LD -->|brief| TS[Tester]\n  BU -->|summary| LD\n  RV -->|summary| LD\n  TS -->|summary| LD\n```\n\n{/* KEEP: prompt = split the reader's one agent into a builder + a separate reviewer with a clean file handoff. Ends with Do this now. */}\n\n## Split your first team\n\nThis prompt turns your one agent into a small team:\n\n```prompt\nAct as a senior engineer setting up a two-agent workflow.\nRead my rules file and my existing agent setup first, and\nput the new roles where my agent files already live, not\nin a parallel structure.\n\nGive me a builder role and a separate reviewer role in my\ntool's format. Both load my rules file, so my map, my\nconventions, and my quality bar apply without being\nrepeated. The reviewer judges the change against that\nbar, nothing else.\n\nAdd a file-based handoff: the builder writes what it\nchanged to one file, the reviewer reads that file and\nreports issues before I commit.\n\nKeep both roles short, and add one line to my decision\nlog for why the work is split this way.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/multiple-agents\n\nMy tool and project:\n```\n\n**Do this now:** paste the prompt, set up the builder and reviewer, and run one change through both so you see the reviewer catch what the builder missed."
          },
          {
            "slug": "kinds-of-agents",
            "title": "What Each One Can Touch",
            "label": "Agent Types",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/kinds-of-agents",
            "content": "---\ntakeaway: Sort agents by what they may touch\nshare: \"Not every agent should be allowed to change things. Sort your fleet by what each one may touch: most should only look and report, a few earn the right to act. What it may touch is its blast radius, and blast radius is how much you can trust it alone.\"\nrequires: [ai-agent, agent-config, agent-tools-config, agent-os-tree]\nproduces: [agent-type-map]\nteaches: [blast-radius, reporter-agent, operator-agent, synthesizer-agent, watcher-agent, job-agent]\nuses: [ai-coding-agent, prompt, database]\n---\n{/* KEEP: lead-in = you've split into many agents; now sort them a SECOND way, by what each may TOUCH (permission), not by phase. Not every agent may change things. The chapter gives the reader the agent types + which are safe to trust running alone. */}\n\nYou have split one agent into many, each doing less. There is a second split that decides whether the system is safe to leave alone: which agents may actually change things, and which may only look. Not every agent should be allowed near your code, your data, or your money. This chapter sorts your agents by what they may touch, so you know which ones to trust running on their own.\n\n{/* KEEP: concept = an agent's TYPE is fixed by what it may DO when it runs, and that permission is its blast radius (the worst it could do if wrong). Real artifact = a 3-column type table: Type | What it may touch | Trust it alone. Bold-first: blast radius, reporter, operator, synthesizer, watcher, job. */}\n\n## What an agent may touch is its blast radius\n\nSplit your agents one more way, not by the phase they work in, but by what they are allowed to do when they run. That permission is the agent's **blast radius**: the worst it could do if it went wrong. One that only reads can embarrass you at most; one that can delete has a blast radius the size of your database.\n\nFive types cover almost everything you will build:\n\n| Type | What it may touch | Trust it alone? |\n| --- | --- | --- |\n| **Reporter** | reads only, changes nothing | Yes, from day one |\n| **Operator** | reads and fixes, inside limits you set | Earned slowly |\n| **Synthesizer** | reads many reports, writes one plan | Yes, it only proposes |\n| **Watcher** | a cheap check, often no AI, wakes another agent | Yes, it only pokes |\n| **Job** | a fixed routine, no AI, same output every time | Yes, it is predictable |\n\n```mermaid\n%% caption: Four types change nothing and run alone from day one; only the operator must earn trust.\nflowchart LR\n  subgraph EYES[Change nothing, safe alone]\n    RP[Reporter]\n    SY[Synthesizer]\n    WA[Watcher]\n    JO[Job]\n  end\n  subgraph HANDS[Changes things, earns trust]\n    OP[Operator]\n  end\n```\n\n{/* KEEP: most of the fleet should be REPORTERS. A read-only agent gives most of the value (knowing what's wrong) with none of the risk, so it runs unattended from day one. Resist the instinct to make everything a fixer. Let the fleet be mostly eyes. */}\n\n## Most of your fleet should be reporters\n\nThe instinct is to build agents that fix things. Resist it. A **reporter** that only reads hands you most of the value, knowing what is wrong, with none of the risk, so it can run unattended from the very first day.\n\nLet the fleet be mostly eyes and let only a few earn the right to act. Ten agents watching and telling you the truth is worth more, and far safer, than one agent quietly changing things you never see.\n\n```mermaid\n%% caption: Ten reporters telling you the truth beat one operator quietly changing what you never see.\nflowchart LR\n  subgraph SAFE[Mostly eyes]\n    R1[Reporter] --> TRUTH[You see the truth]\n    R2[Reporter] --> TRUTH\n  end\n  subgraph RISKY[One quiet fixer]\n    OP[Operator] --> HID[Changes you never see]\n  end\n```\n\n{/* KEEP: the OPERATOR is the only type that must earn its reach; match the leash to the reach. A reporter/watcher/job are safe running constantly because they change nothing or are predictable; the operator reads AND fixes, so it starts on a short leash that loosens only as it proves itself. This is the type that later chapters put on a ladder. */}\n\n## An operator earns its reach\n\nAn **operator** reads and then fixes, so it gets the opposite treatment: a short leash that loosens only as it proves itself. Match the leash to the reach. A reporter, a watcher, and a job are safe running constantly, because one changes nothing, one only pokes another awake, and the last does the same predictable thing every time.\n\nThe operator is the single type that has to earn its independence, one small class of action at a time. Knowing that up front is what lets you build the safe ones freely and hold the dangerous ones close.\n\n```mermaid\n%% caption: An operator earns reach one class of action at a time, its leash loosening only as it proves itself.\nflowchart LR\n  START[Short leash] --> PROVE[Proves one action]\n  PROVE --> LOOSEN[Leash loosens]\n  LOOSEN --> MORE[Earns next action]\n  MORE --> PROVE\n```\n\n{/* KEEP: prompt = classify the reader's planned agents into the five types, then set each one's permissions to MATCH its type (read-only agents get no tools that can change anything), and say which may run alone now. System-building chapter, needs the scaffolding prompt. Ends with Do this now. */}\n\n## Sort your agents by blast radius\n\nThis prompt types every agent you have and locks each one down to match:\n\n```prompt\nAct as a senior engineer classifying my agents by blast\nradius. Read my agent tree and each agent's existing\nconfig and tools first, and classify what they can do\ntoday, not what I meant them to do.\n\nFor each agent, name its type: reporter (reads only),\noperator (reads and fixes), synthesizer (reads reports,\nwrites a plan), watcher (a cheap check that wakes\nanother), or job (a fixed routine, no AI). Then set each\none's permissions to match: a read-only agent gets no\ntool that can change anything. Tell me which may run\nalone now and which must stay report-only until it\nearns more.\n\nFlag every agent whose current tools give it more reach\nthan its type allows, and record each promotion as one\nline in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/kinds-of-agents\n\nMy agents and what each one is meant to do:\n```\n\n**Do this now:** paste the prompt, and make every agent that only needs to look a reporter with no power to change a thing."
          },
          {
            "slug": "scheduling-your-agents",
            "title": "Putting Agents on a Clock",
            "label": "Scheduling",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/scheduling-your-agents",
            "content": "---\ntakeaway: Put work on a clock\nshare: \"The best work an agent does is the work you never asked for, because it was already on the calendar. Scheduling is how your system runs while you sleep and you wake up to finished work.\"\nrequires: [ai-agent, terminal-access, agent-os-tree]\nproduces: [scheduled-job]\nteaches: [cron, orchestrator, watchdog, headless-run]\nuses: [ai-coding-agent, command, operating-system, prompt, watcher-agent, model]\n---\n{/* KEEP: lead-in = the best work an agent does is the work you never asked for because it was on the calendar; scheduling is how the system runs while you sleep. CODE-FORWARD, cron-simple. */}\n\nThe best work an agent does is the work you never asked for, because it was already on the calendar. Scheduling is how your system stops waiting for you and starts running on its own, so you wake up to work that is already done.\n\n{/* KEEP: until now every agent waited for you to start it; scheduling flips that: put an agent on a clock and it runs on its own, on time, whether you show up or not. The system stops being a tool you operate and becomes one that operates. */}\n\n## Agents that run without you\n\nUntil now, every agent waited for you to press go. Scheduling flips that. You put an agent on a clock and it runs on its own, on time, whether or not you show up.\n\nThat is the moment the system stops being a tool you operate and starts being one that operates, doing the rounds because the clock struck, not because you remembered.\n\n{/* KEEP: look at everything you do on a rhythm (weekly numbers, daily health check, monthly money review); each is a scheduled agent. Show a cron line (plain). Write the job once, set cadence, runs forever. The important-but-never-urgent work finally gets done because a clock doesn't procrastinate. Bold-first: cron. */}\n\n## Put the routine work on a clock\n\nLook at everything you do on a rhythm: the weekly numbers, the daily health check, the monthly money review. Every one is a scheduled agent waiting to exist.\n\nYou set its cadence with a [**cron**](https://crontab.guru) line, five fields that mean \"run at this time\":\n\n```\n# min hour day month weekday\n0 8 * * *      # every day at 08:00\n0 9 * * 1      # every Monday at 09:00\n```\n\nWrite the job once, give it a cadence, and it runs forever. The work that is important but never urgent, and so never gets done, finally does, because a clock does not procrastinate.\n\nThat format is cron, which is built into Mac and Linux. Windows has the same thing under a different name, Task Scheduler. You do not set either up by hand: you tell your agent the cadence and let it wire the right one for your machine.\n\n{/* KEEP: two ways to fire the same job: on a schedule (every morning) or on demand (one command, now). You want both. Nod that event-driven triggers come later. A job runner (Prefect-style) exists for scale, one line, swappable. */}\n\n## Schedule it, or trigger it on demand\n\nThe same job has two doors. On a schedule it runs every morning at eight; on demand you run one command and it goes now. You want both: the schedule for the rhythm, the manual run for the moment you need the report early.\n\nA cron line is only the clock. What it fires is one command that runs your agent with no chat window, reading the job's instructions from a file. Your agent wires this, but you should recognize it:\n\n```\nclaude -p \"$(cat jobs/weekly-numbers.md)\"   # run this job once, headless\n```\n\nThe schedule fires that exact command for you at the set time. A plain cron runs it on your machine; a bigger engine handles it when you have many, which is the next choice to make.\n\n{/* KEEP: the scheduler landscape at awareness altitude, introduce options, do not prescribe. Floor = plain cron / process runner (runs while the machine is on, no dashboard). Step up = an orchestrator (Prefect/Airflow/Temporal) that runs unattended and gives a dashboard to see/control runs; author leans Prefect but the job is to name options. Also: some agent tools (e.g. Claude Code) ship a built-in scheduler, check first. What decides = cadence, must-run-without-opening-an-app, want a dashboard, where it runs. Note the space keeps evolving. Bold-first: orchestrator. */}\n\n## Pick the tool that fits how you run\n\nPlain cron is the floor: it fires jobs while your machine is on, with no dashboard. One step up is an **orchestrator**, a tool that runs your jobs unattended and gives you a dashboard to see every run, retry, and failure at a glance. [Prefect](https://prefect.io), [Airflow](https://airflow.apache.org), and [Temporal](https://temporal.io) are the common ones, and Prefect is the gentlest to start with. Some agent tools also ship their own scheduler, so check what yours already offers before you add anything.\n\nWhich one fits depends on four things: how often the job runs, whether it must run without you opening any app, whether you want a dashboard, and where it lives. This space keeps moving, so pick what fits today and swap later.\n\n```mermaid\n%% caption: Four questions pick your scheduler, cheapest option first.\nflowchart TD\n  Q1{1. Does your agent tool ship a scheduler?}\n  Q1 -->|Yes| BUILT[Use the one you already have]\n  Q1 -->|No| Q2{2. Must it run with your machine off?}\n  Q2 -->|No| CRON[Plain cron on your machine]\n  Q2 -->|Yes| Q3{3. Do you want a dashboard for every run?}\n  Q3 -->|No| SRV[Cron on a small always-on server]\n  Q3 -->|Yes| ORCH[An orchestrator like Prefect]\n```\n\n{/* KEEP: a scheduled run without safety+observability rots silently. The things that make an unattended run safe: it checks it's still allowed before acting (gate), it records what it did (ledger, built next chapters), something alerts you if it STOPS firing (watchdog), and it caps what one run can spend/retry (cost, an unattended loop is an open wallet; gate the costly agent behind a cheap watcher). The scary failure of a scheduler is silence, not a crash. Numbered flow = device variety in the back half. */}\n\n## Make an unattended run safe\n\nA job that runs while you sleep needs more than a clock, or it fails in the dark and you find out late. Three things make an unattended run trustworthy:\n\n1. **Gate:** before it acts, the agent confirms it is still allowed to (the guardrails of the next chapter). It fixes what is safe and escalates the rest, never spending or deleting on its own.\n2. **Record:** every run writes what it did to one log (you build this in the ledger chapter), so \"what ran last night\" has one honest answer.\n3. **Watchdog:** something tells you when a run stops firing. A scheduler does not fail loudly; it goes quiet, so you watch for the missing run, not just for errors.\n4. **Cap:** bound what one run may spend and how many times it retries. An agent left to loop is an open wallet, so a cheap no-AI watcher that wakes the costly agent only when there is real work keeps the bill small.\n\n{/* KEEP: cost gets its own section because an unexpected bill is the most common way a first scheduled fleet ends. Three moves: match the model to the job (a reporter runs on the cheapest small model, an operator does not), set a hard spend cap and a usage alert on the PROVIDER's side rather than trusting the agent, and read the first week's bill before adding jobs. */}\n\n## Know the bill before it arrives\n\nA fleet on a clock spends money every time it wakes, whether or not there was anything to do. That bill is the most common way a first scheduled system ends, and it is entirely preventable.\n\nMatch the model to the job. A reporter that summarizes a file runs fine on the cheapest small model; an operator that changes things does not. That one choice moves the bill more than anything else you can do.\n\nThen set the cap where the agent cannot argue with it: a hard spend limit and a usage alert in your model provider's own dashboard, not in a prompt. Read the actual bill after the first week, before you put a second job on the clock.\n\n{/* KEEP: the payoff = open your laptop and the reports are written, checks run, problems flagged or fixed; you review work that already happened. The system ran a full shift without you. */}\n\n## Wake up to finished work\n\nThis is the payoff, and it changes how the whole thing feels. You open your laptop and the reports are already written, the checks already run, the problems already flagged or fixed.\n\nYou are not starting the day's work. You are reviewing work that already happened. The system ran a full shift while you slept.\n\n{/* KEEP: prompt = take one routine task the reader does on a rhythm and turn it into a scheduled agent with a cron + a job definition. Ends with Do this now. */}\n\n## Put one job on a clock\n\nThis prompt turns a routine chore into a scheduled agent:\n\n```prompt\nAct as a senior engineer automating my routine work. First\nread my operating base: the department this work belongs\nto, the agent that owns it, and that agent's config, so it\nruns as that agent with the tools it already has.\n\nThen recommend the simplest scheduler that fits: plain\ncron, an orchestrator with a dashboard like Prefect, or a\nscheduler built into my agent tool if it has one. Weigh how\noften the job runs, whether it must run without me opening\nany app, and whether I want a dashboard to watch runs.\n\nThen write the task below as a small job in that agent's\nfolder, schedule it at the right cadence, and show me how\nto run it once by hand to test it first. Have each run\nappend its result to the status file, and add one line to\nmy decision log for the scheduler I chose and why.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/scheduling-your-agents\n\nMy setup, and the routine task (and how often):\n```\n\n**Do this now:** paste the prompt, pick one thing you do on a rhythm, and let your agent turn it into a job on a clock."
          },
          {
            "slug": "autonomy-guardrails",
            "title": "What Runs Alone, What Waits",
            "label": "Autonomy",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/autonomy-guardrails",
            "content": "---\ntakeaway: Decide what runs alone, what waits\nshare: \"Autonomy without guardrails is a loaded gun on a timer. Sort every action into safe-to-run-alone and must-wait-for-you, so the tireless work happens and only the risky calls reach you.\"\nrequires: [ai-agent, scheduled-job, rules-file]\nproduces: [guardrails-file]\nteaches: [decision-card, decision-queue, hook, defense-in-depth]\nuses: [ai-coding-agent, rule, decision-log, cockpit, prompt]\n---\n{/* KEEP: lead-in = this is the safety layer that keeps autonomy from hurting you. Autonomy without guardrails = a loaded gun on a timer. MUST come right after Scheduling. CODE-FORWARD. */}\n\nYou just put agents on a clock. That is power, and power without a brake is dangerous: an agent that can act on its own, on a schedule, can also break things on its own. This chapter is the brake, the line between what runs alone and what waits for you.\n\n{/* KEEP: not every action is equal; reading a dashboard and deleting an account are not the same risk. Sort every action into two buckets: safe to run alone (reversible, low blast radius) vs must wait for a human yes (money, real user data, security, removing a capability). The sort is the whole game. */}\n\n## Not every action is equal\n\nReading a dashboard and deleting a customer's account are not the same risk, so they must not have the same freedom. You sort every action an agent can take into two buckets.\n\nReversible, low-risk work runs on its own. Anything that touches money, real user data, security, or removes a capability stops and asks. That sort is the whole game.\n\n{/* KEEP: give agents a standing rule: fix what you're allowed to fix; for everything else, don't act, drop a card. Safe repair -> do it and log it. Risky (raise the bill, swap a vendor, change a price) -> write a short decision card, leave it in the queue. The agent never grows the stakes on its own. */}\n\n## Fix what's safe, escalate what's not\n\nGive every autonomous agent one standing rule: fix what you are allowed to fix, and for everything else, do not act, leave a card.\n\nWhen a scheduled agent finds a problem it can safely repair, it repairs it and logs it. When it finds something only you should decide, raising the bill, swapping a vendor, changing a price, it writes a short **decision card** and stops. The agent never raises the stakes on its own.\n\n```mermaid\n%% caption: The agent fixes reversible work itself and turns risky calls into a card that waits for you.\nflowchart TD\n  A[Agent finds a problem] --> Q{Reversible and low risk?}\n  Q -->|yes| FX[Fix it and log it]\n  Q -->|no| CD[Write a decision card]\n  CD --> QU[Decision queue]\n  QU --> YOU([You approve or reject])\n```\n\n{/* KEEP: the decision queue = all escalations land in ONE place, one card each (one question, one recommendation); you clear it on your schedule, approving or rejecting. This is what makes autonomy safe to live with: the system does the tireless work and hands you only the small set of real judgment calls. Show a decision card. */}\n\n## The decision queue\n\nEvery escalation lands in one place: a queue of decisions waiting on you. Each is one card, one question, one recommendation.\n\n```yaml\n# decision: raise the DB plan?\nWhy: we hit 90% of storage twice this week.\nRecommend: upgrade one tier (+$25/mo).\nOptions: approve / hold / do something else\n```\n\nYou clear the queue on your own schedule, approving or rejecting each. An approved card becomes a line in the decision log back in your cockpit, so the call and its reason are recorded, not lost. This is what makes autonomy safe to live with. The system does the tireless work, and hands you only the handful of calls that would hurt to get wrong.\n\n{/* KEEP: the hard lines can't live in your head or a mood; they live in rules files, always on, phrased as absolutes (never change billing without a yes, never delete without confirmation, never message a customer without approval). Each rule names a specific way things go wrong. Short, brutal, permanent, fires every turn. */}\n\n## Write the hard lines down, once\n\nThe guardrails cannot live in your memory. They live in a rules file, always loaded, phrased as absolutes:\n\n```\n# rules/guardrails.md\n- Never change billing or pricing without an explicit yes.\n- Never delete user data without confirmation.\n- Never send anything to a customer without approval.\n- Never rewrite an agent's own rules or instructions without your review.\n```\n\nEvery rule earns its place by naming a specific way things go wrong. The list is short, blunt, and permanent, and it fires on every turn whether the agent thinks to consider it or not.\n\nA rule the agent reads is a rule it can talk itself out of over a long, tired session. For the lines that must never break, add a second layer: a **hook**, a small program your tool runs automatically that mechanically blocks the action, no judgment involved. The rule tells the agent what not to do; the hook makes it impossible. Anything that spends money, deletes real data, or ships to production belongs behind a hook, not just a sentence.\n\n{/* KEEP (added July 2026, user mandate): the mindset, generalized from the rule-vs-hook pair above. The reason is specific and from experience: late in a session, with its context crowded, an agent makes calls it would never make fresh, and it bypasses the single control instead of satisfying it (disables the failing test, skips the hook). So the same check sits at more than one point, and each layer catches what the one before it missed. Bold-first: defense in depth. Ladder table. Then the human-only lock, stated HONESTLY as friction not a wall. Then recovery is the last layer, never the plan. */}\n\n## Stack the layers, one of them will fail\n\nOne control is one thing to bypass. Late in a long session, with its context crowded, an agent makes calls it would never make on a fresh start.\n\nAsked to fix a failing test, it disables the test. Asked to get past a hook, it skips the hook. It is not malice, it is a tired shortcut, and no amount of rule-writing removes it.\n\nThe answer is **defense in depth**: put the same check at more than one point, so a control that gets bypassed is not the only thing standing there.\n\n| Layer | Where it sits | What it survives |\n| --- | --- | --- |\n| The always-on rule | Every turn | Nothing mechanical, it is the first line only |\n| A hook on your machine | Before the change is saved to history | An agent that forgot the rule |\n| A gate in your automatic checks | Before the change reaches the main copy | A hook that got skipped |\n| A lock on the live environment | Before anything reaches real users | Everything above it failing at once |\n\nFor the handful of commands you never want run by accident, add friction a machine will not casually cross. Put a passphrase on the deploy script, one you keep and the agent does not. It could go looking for it, but a prompt that plainly reads \"human only\" gets respected far more than a line in a file, and that is enough to stop an accident.\n\nGive every gate a documented way past it, on purpose. A gate with no escape hatch gets switched off entirely the first time it blocks something urgent, and then it is gone for every change after. A named bypass you have to type is a bypass you can see in the history.\n\n> **Watch out:** history and backups let you undo a bad afternoon, and you still need both. They are the last layer, never the plan. Prevention costs minutes, recovery costs your weekend.\n\n{/* KEEP: prompt = have the agent split its own actions into safe/escalate and write the guardrail rules file for the reader's system. Ends with Do this now. */}\n\n## Draw your own lines\n\nThis prompt sets your guardrails before you let anything run alone:\n\n```prompt\nAct as a senior engineer setting safety guardrails for my\nautonomous agents. Read my rules file and my decision log\nfirst, so these lines match what I already decided and do\nnot quietly reverse a call I made.\n\nFrom what my system can touch, list which actions are safe\nto run alone (reversible, low risk) and which must wait for\nmy approval (money, user data, security, deletions, and\nanything public). Then write a short always-on guardrails\nfile that encodes the must-wait lines as absolutes, and\nhave a waiting action queue in my control center rather\nthan fail silently.\n\nRecord one line in my decision log: where you drew the\nline, and why.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/autonomy-guardrails\n\nWhat my agents can do and touch:\n```\n\n**Do this now:** paste the prompt, get your safe/escalate split and a guardrails rules file, and add it to your agents' always-on rules before any of them run on a schedule."
          },
          {
            "slug": "work-board",
            "title": "One List You Both Share",
            "label": "Work Board",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/work-board",
            "content": "---\ntakeaway: Share one work board with your agents\nshare: \"Work that lives in your head or gets buried in reports is work that gets lost. Put every task on one plain board that you and your agents both pull from, so nothing falls through and anyone can see the whole operation at a glance.\"\nrequires: [ai-agent, agent-os-tree, guardrails-file]\nproduces: [work-board]\nteaches: [work-board, ticket, status]\nuses: [ai-coding-agent, decision-queue, prompt]\n---\n{/* KEEP: lead-in = work lost in your head or buried in reports; one shared board both you AND the agents pull from, business and tech. Comes right after Autonomy Guardrails. CODE-FORWARD. */}\n\nYou now have agents that act on their own and a line between what they may do and what they must ask about. But the work itself still lives in your head, or gets buried at the bottom of a report you skimmed once. This chapter gives every piece of work one home: a shared board that you and your agents both pull from.\n\n{/* KEEP: concept = ONE board both the founder and the agents read and write, for the whole operation (business and tech). Not a report of what happened, a list of what still needs doing. Stops work from living in your head. Bold-first: work board. Name what is being rejected and why: GitHub Issues/Projects (already in the remote repo, agent-reachable), Linear, Trello, Jira. Criterion for the plain file = zero setup for the agent, lives beside the code. Criterion for graduating = a second human, or work needing comments and history. */}\n\n## One board both of you pull from\n\nKeep one **work board**: a single plain file that lists everything the operation still needs to do, business and technical, in one place. You add to it. Your agents add to it. Both of you read from it.\n\nA report tells you what already happened. The board is the opposite: it is the list of what has not happened yet. When every task lives here, none of it lives in your head, and nothing gets lost between one session and the next.\n\nReal trackers exist and you are skipping them on purpose. [GitHub Issues and Projects](https://docs.github.com/en/issues) is the closest call: it already sits in your remote repository, and your agent can reach it. [Linear](https://linear.app), [Trello](https://trello.com), and [Jira](https://www.atlassian.com/software/jira) are the heavier options.\n\nA plain file wins for now because an agent reads it with zero setup and it lives beside the code. Move to a real tracker the day a second human joins, or the day the work needs comments and history rather than a status.\n\n```mermaid\n%% caption: You and your agents both file tickets onto one board and both pull work from it.\nflowchart LR\n  YOU([You]) -->|file tickets| BD[(Work board)]\n  AG([Agents]) -->|file tickets| BD\n  BD -->|pull work| YOU\n  BD -->|pull ready tickets| AG\n```\n\n{/* KEEP: every piece of work is a ticket with a few fields: title, status, who. Keep it dead simple, readable at a glance, not a heavy tracker. Real artifact = ticket format + the status list. Bold-first: ticket, status. */}\n\n## Every piece of work is a ticket\n\nEach item on the board is a **ticket**: a title, a **status**, and a `who` that says whether you or an agent owns it. Nothing heavier. You should read the whole board at a glance, not learn a tool.\n\n```yaml\n# ticket: retry the failed payouts\nstatus: ready        # idea -> needs-approval -> ready -> doing -> done\nwho: agent\nnote: 3 payouts failed this week; retry them once.\n\n# the status ladder\nidea            a rough thought, not ready to work\nneeds-approval  waiting on your yes (risky, costs money, hard to undo)\nready           approved and safe; an agent may pick it up\ndoing           claimed and in progress (one owner at a time)\ndone            finished and logged\n```\n\n{/* KEEP: status moves one direction: idea -> (needs-approval) -> ready -> doing -> done. An agent only works a ticket that is READY and assigned to an agent. Nothing skips ahead. */}\n\n## Status moves one way, never backward\n\nA ticket walks the ladder in one direction: `idea`, then optionally `needs-approval`, then `ready`, then `doing`, then `done`. It never jumps a rung.\n\nThe rule that makes this safe is narrow: an agent may only start a ticket that is `ready` and assigned to an agent. An `idea` is just a thought. A `needs-approval` is yours to clear. Only `ready` is open season, and only for the work you marked as an agent's to take.\n\n```mermaid\n%% caption: A ticket climbs one rung at a time; only a ready ticket is open for an agent.\nflowchart LR\n  ID[idea] --> NA[needs-approval]\n  ID --> RD[ready]\n  NA --> RD\n  RD --> DO[doing]\n  DO --> DN[done]\n```\n\n{/* KEEP: an agent CLAIMS before working (marks it doing) so multiple agents never collide (ref multiple-agents by topic); does the smallest safe thing; marks done. Anything risky/costly/irreversible -> flip to needs-approval (this GENERALIZES the decision queue from autonomy-guardrails, cross-link by topic). */}\n\n## An agent claims a ticket before it works\n\nBefore an agent touches a `ready` ticket, it flips the status to `doing` and writes its name in `who`. That claim is what stops two agents from grabbing the same work at once, so a team of agents can share one workspace without clobbering each other.\n\nThen it does the smallest safe thing the ticket asks, and marks it `done`. If the work turns out to be risky, costly, or hard to undo, it does not push ahead: it flips the ticket to `needs-approval` and stops. That is the decision queue from the guardrails chapter, now generalized: every escalation, from any agent, surfaces as one ticket on the one board you already watch.\n\n```mermaid\n%% caption: An agent claims a ready ticket, does the smallest safe thing, then marks it done or escalates.\nflowchart TD\n  RD[Ready ticket] -->|claim, flip to doing| CL[Name in who]\n  CL --> WK[Smallest safe thing]\n  WK --> Q{Risky or costly?}\n  Q -->|No| DN[Mark done]\n  Q -->|Yes| NA[Flip to needs-approval and stop]\n```\n\n> **Rule of thumb:** if you cannot see all of tomorrow's work on one screen, the board has grown a process it does not need. Cut fields, not tickets.\n\n{/* KEEP: prompt = senior voice, sets up the board and/or has an agent pick and safely work the next ready ticket. Ends with Do this now. */}\n\n## Stand up your shared board\n\nThis prompt turns the work in your head into a board you both share:\n\n```prompt\nAct as a senior engineer setting up a shared work board.\nRead my planner file for the current focus, my decision\nlog so no ticket reopens a settled call, and my guardrail\nrules for what an agent may do unattended.\n\nCreate one plain board file in my _control folder where\nboth I and my agents file work as tickets, each with a\ntitle, a status (idea, needs-approval, ready, doing,\ndone), and an owner. Rank the ready work by the planner's\nfocus, not by arrival.\n\nThen have an agent take the top ready ticket assigned to\nit, mark it doing so nothing else grabs it, do the\nsmallest safe thing, and mark it done. Anything my\nguardrails call risky, flip to needs-approval and stop.\nRecord any real choice it makes as one line in the\ndecision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/work-board\n\nMy operation and the work piling up right now:\n```\n\n**Do this now:** paste the prompt, stand up your one board, and move every task living in your head onto it as a ticket."
          },
          {
            "slug": "reports-and-commands",
            "title": "Commands and What Comes Back",
            "label": "Reporting",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/reports-and-commands",
            "content": "---\ntakeaway: Command down, report up\nshare: \"A system you cannot see is one you cannot steer. Reporting is the two-way pipe: you send one command down, the work sends truth back up, and you sit at the top of the loop, not inside it.\"\nrequires: [ai-agent, agent-os-tree, status-file, control-center]\nproduces: [command-surface, report-format]\nteaches: [slash-command, report]\nuses: [ai-coding-agent, markdown, status-file, prompt]\n---\n{/* KEEP: lead-in = a system you can't see is one you can't steer. Reporting = the two-way pipe: commands down, reports up. You sit at the top of the loop, not inside it. CODE-FORWARD. */}\n\nA system you cannot see is a system you cannot steer. Reporting is the two-way pipe that lets you run the whole thing from one seat. You send commands down, the work sends truth back up, and you stay at the top of the loop instead of buried inside it.\n\n{/* KEEP: the shape of control: direction flows DOWN from you as commands, reality flows UP from agents as reports. You point the system at what matters and read back what it found. Down goes intent, up comes evidence, you sit where they meet. */}\n\n## You command down, they report up\n\nThe shape of control is simple. Direction flows down from you as commands. Reality flows up from the agents as reports.\n\nYou do not do the tasks. You point the system at what matters, and you read back what it found. Down goes intent, up comes evidence, and you sit where the two meet.\n\n```mermaid\n%% caption: Commands flow down as intent; reports flow back up as evidence, and you sit where they meet.\nflowchart TD\n  YOU([1. You]) -->|commands down| AG[2. Agents do the work]\n  AG -->|3. reports up| YOU\n```\n\n{/* KEEP: commands are your interface; don't operate by remembering ten folders and twenty scripts. A small set of named commands: one for the whole picture, one per area to go deeper. The command is one word; behind it is all the machinery. A good command set is the entire UI of your system. Show the command set. */}\n\n## Commands are your interface\n\nYou should not run the system by remembering ten folders and twenty scripts. You run it through a small set of named commands, each a single word that hides a mountain of machinery:\n\n```\n/status        # the whole picture, one screen\n/status growth # traffic, users, money\n/status tech   # errors, cost, agents\n```\n\nOne to see everything, one per area to go deeper. A good command set is the entire user interface of your operation.\n\nA command is a real file, not magic: in [Claude Code](https://claude.com/claude-code) each one is a markdown file in `.claude/commands/` (`status.md` becomes `/status`), holding the instructions the command runs. Your tool has the same idea under its own name. You write the workflow once; the slash name is the shortcut.\n\n{/* KEEP: reports are what comes back; every agent that works leaves a report (what it checked, found, did, what needs you), in a KNOWN place and KNOWN shape so you scan many fast. The report compresses a night of work into five minutes of reading, so you spend attention only on deciding. Show report frontmatter. */}\n\n## Reports are what comes back\n\nEvery agent that does work leaves a report: what it checked, what it found, what it did, and what needs you. They land in a known place, in a known shape, so you can scan many of them fast:\n\n```yaml\n---\narea: money\nverdict: needs-you\n---\nRevenue up 4%. One failed payout, decision card filed.\n```\n\nA keyed shape like that is what turns a night of autonomous work into five minutes of reading. It compresses the doing so you spend your attention only on the deciding. Reports land in their own `reports/` folder, separate from the department status files: a status file is a department's current truth, a report is one run's findings for you.\n\n{/* KEEP: keep the loop tight = the danger is a leaky loop (reports nobody reads, commands that no longer match the folders, a gap between what the system did and what you think it did). Fight it: one command surface, one report format, one place the truth lives. The tighter the loop, the more you can trust it, and trust is what lets you let go. */}\n\n## Keep the loop tight\n\nThe danger is a loop that leaks. Reports nobody reads, commands that no longer match the folders, a gap between what the system did and what you think it did.\n\nYou fight that constantly with three disciplines: one command surface, one report format, one place the truth lives. The tighter the loop, the more you can trust it, and trust is the only thing that lets you actually let go.\n\n{/* KEEP: prompt = have the agent set up the reader's command surface (one status command + a report format) over their operating base. Ends with Do this now. */}\n\n## Build your command surface\n\nThis prompt gives you one seat to run everything from:\n\n```prompt\nAct as a senior engineer building my command surface. Over\nmy operating base, create one command that pulls a single\nbriefing out of what my system already keeps: every\ndepartment's status file, the latest reports, anything\nwaiting at needs-approval on my work board, and the\ncurrent focus in my planner. Lead with what needs me and\nwhy. Then define one short report format (a few keyed\nfields at the top) that every agent writes into the\nreports folder, and add it to my guardrails so agents\nfollow it by default. Do not create a second place the\ntruth lives.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/reports-and-commands\n\nMy operating base and departments:\n```\n\n**Do this now:** paste the prompt, set up your one status command and report format, then run the command once and read your whole operation on a single screen."
          },
          {
            "slug": "event-ledger",
            "title": "One Log of Everything",
            "label": "Ledger",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/event-ledger",
            "content": "---\ntakeaway: Log everything in one append-only ledger\nshare: \"Reports tell you what happened this morning. A ledger tells you everything that ever happened, in order. The one place to answer 'what led to this' when something goes wrong.\"\nrequires: [ai-agent, agent-os-tree, scheduled-job]\nproduces: [event-ledger]\nteaches: [ledger, event, append-only]\nglosses: [alert]\nuses: [ai-coding-agent, status-file, report, prompt]\n---\n{/* KEEP: lead-in = reports = this morning; a ledger = everything that ever happened, in order. LIGHTER chapter (idea + when you need it), flag that a beginner may not need it yet. One small artifact. */}\n\nReports tell you what an agent found this morning. A ledger tells you everything that has ever happened, in order. You will not need it on day one, but the first time you ask \"what led to this?\" and cannot answer, this is the missing piece.\n\n{/* KEEP: under the folders and agents, one append-only log of events (deploy happened, signup came, alert fired, job finished). Each meaningful thing writes one line. Not a report you read top to bottom, the raw record everything pulses through. Show a small event log. */}\n\n## Events are the nervous system\n\nUnderneath the folders and the agents, you keep a **ledger**: one running log of **events**.\n\nA deploy happened. A signup came in. An **alert** fired, a warning that something is wrong. A job finished.\n\nEvery meaningful thing writes one line:\n\n```\n2026-07-10T08:00Z  job.finished    growth-daily ok\n2026-07-10T08:14Z  signup          user=4821\n2026-07-10T09:02Z  alert.fired     errors spiking\n```\n\nIt is not a report you read top to bottom. It is the raw record the whole system pulses through, the thing everything else can look back at.\n\n{/* KEEP: one rule makes it trustworthy: append only, never edit. A line once written stays; you never rewrite history. That's what lets you reconstruct exactly what happened weeks later, the truth, not a tidied summary. */}\n\n## Append only, never edit\n\nThe ledger has one rule that makes it trustworthy: you only ever add to it. You never rewrite a line.\n\nThat is what lets you reconstruct exactly what happened, and in what order, weeks later when something broke. You get the truth, not a summary someone tidied up. Its value is that nobody got to clean it.\n\n{/* KEEP: the power shows when local AND cloud write to the SAME ledger: the agent on your laptop and the service in production log to one stream, giving one timeline of the whole system. Ask \"what led to this\", one place to look, complete answer. */}\n\n## One place, both worlds\n\nThe real power shows up when your local work and your live service write to the same ledger. The way it works is one small rule: everything that logs an event calls the same single writer. The agent on your laptop and the app in production both append through one door, so there is one stream and not two.\n\n```mermaid\n%% caption: Laptop and production both append through one writer, so there is one timeline, not two.\nflowchart LR\n  LA([Laptop agent]) -->|append| WR[One writer]\n  PR([Production app]) -->|append| WR\n  WR --> LG[(Ledger)]\n  LG --> TL[One timeline]\n```\n\nNow you have a single timeline of the whole system, machine and human, code and business, in one order. This is the third and last record surface, and each of the three has one job:\n\n- **Status file:** a department's current truth.\n- **Report:** one run's findings, written for you.\n- **Ledger:** the raw timeline for looking back.\n\nWhen you ask \"what led to this,\" the ledger is the one place to look.\n\n{/* KEEP: a durable event stream isn't just for looking back, it's the surface agents can WATCH and react to; once you have one honest log, you can build agents that fire the instant an event lands. This sets up Triggers. Flag WHEN to add a ledger. */}\n\n## The ledger makes reflexes possible\n\nA durable stream of events is not only for looking back. It is the surface an agent can watch, so it can react the instant a certain event lands. That is the next chapter.\n\n> **Hint:** you do not need a ledger while it is just you and a few daily agents. Add one when you cannot answer \"what led to this,\" or when you want agents that react to events. Your plain log is the simple version; at scale the industry standard for this is [OpenTelemetry](https://opentelemetry.io/docs/specs/semconv/gen-ai/), which records the same kind of timeline in a format built for it.\n\n{/* KEEP: prompt = start a simple append-only event log the reader's agents write one line to. Ends with Do this now. */}\n\n## Start your ledger\n\nThis prompt gives your system a memory of its own history:\n\n```prompt\nAct as a senior engineer adding an event log to my\nsystem. Read my operating base first: the departments,\nthe scheduled jobs, and the status files already there,\nso the events you log are ones my system really emits.\n\nCreate one append-only file in my control folder that\nmy agents write a single line to whenever something\nmeaningful happens (a job finished, a signup, an\nalert). Give each line a timestamp, an event name, and\na short detail. Never edit past lines, and never\nduplicate what my status files or decision log already\nhold.\n\nThen add one line to my decision log naming what gets\nlogged and what deliberately does not.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/event-ledger\n\nMy system and the events worth logging:\n```\n\n**Do this now:** paste the prompt, start the log, and have one of your scheduled agents append a line every time it runs."
          },
          {
            "slug": "task-workflow",
            "title": "The Path Every Task Follows",
            "label": "Workflow",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/task-workflow",
            "content": "---\ntakeaway: One path every task walks, on disk\nshare: 'Ask an agent for something and it improvises a different route every time, then the reasoning dies with the window. Give it one standing path from ticket to record, where every stop leaves a file behind.'\nrequires: [ai-agent, agent-memory-file, work-board, event-ledger, spec-file, test-suite]\nproduces: [task-workflow]\nteaches: [task-workflow]\nuses: [ai-coding-agent, ticket, work-board, ledger, spec, test, rule, prompt]\n---\n{/* KEEP: lead-in = the reader now has roles, a board, and a ledger, but the part IN BETWEEN is still improvised: how a task actually gets done. Same request twice, two different routes, and the thinking behind both dies with the window. This chapter pins the route. CODE-FORWARD. */}\n\nYour agents have roles, a board to pull from, and a ledger that records what happened. What is still improvised is the part in between: how a task actually gets done. Ask for the same kind of work twice and you get two different routes, and the thinking behind both dies when you close the window. This chapter pins the route down.\n\n{/* KEEP: CONCEPT, the author's core point. Most of a session's value is not the code, it is the reasoning around it (why this approach, what was checked, what was ruled out, what broke first). That evaporates. Bold-first: task workflow, defined as one fixed path where every stop leaves a file behind. The hard rule: if a stop produced no file, it did not happen. Chat is where work is discussed, the repo is where it is kept. */}\n\n## What happens in the session does not survive it\n\nMost of what a working session produces is not the code. It is everything around the code: why that approach and not the other one, what the agent checked, what it ruled out, what broke on the first attempt. Close the window and all of it is gone.\n\nA **task workflow** fixes that. It is one path every request walks, where each stop leaves a file behind. If a stop produced nothing on disk, it did not happen. The chat is where work gets discussed; the repository is where it gets kept.\n\n{/* KEEP: STEP, the flow the author has described repeatedly: ticket, research, spec, build, verify, record. Numbered, one line each, each naming the artifact it drops. Diagram loops back so it reads as a cycle, not a one-off. Close on: the path never changes, only the size of each stop. Do NOT re-teach the board, the spec, or tests, those are earlier chapters. */}\n\n## One path, six stops\n\nEvery request, however small, walks the same path:\n\n1. **Ticket.** Open one on the board before anything else, so the work exists outside the chat.\n2. **Research.** Read the code, the docs, and the decisions that already cover this, then write the findings down.\n3. **Spec.** State what will change and what done looks like, and get your yes before any code.\n4. **Build.** Implement only what the spec says, in slices.\n5. **Verify.** Run the tests and the app. A green run is the proof, not the agent's opinion.\n6. **Record.** Close the ticket, log any real choice as a decision, and note the outcome.\n\nA one-line fix walks it in minutes and a feature takes a week. The path does not change, only the size of each stop.\n\n{/* KEEP (added July 2026, user mandate): the three kinds of work. Almost everything you ever ask an agent is one of them, and stops 2 and 3 differ per kind while the rest of the path is identical. Feature covers add, change AND delete, say so, people forget deleting takes the same path. Bug work must reproduce before diagnosing. Improvement work must have a number BEFORE the change or it is just tidying. Table, one row each, plus the trap each kind falls into. */}\n\n## Three kinds of work walk it differently\n\nAlmost everything you will ever ask for is one of three things. The difference shows up at stops two and three:\n\n| Kind of work | Research means | Written down before building | The trap |\n| --- | --- | --- | --- |\n| **Feature.** Add, change, or remove something users see | Read the spec and the decisions that already cover it | What changes, and what done looks like | Building before anyone wrote down what done means |\n| **Bug.** Something is wrong and you want it right | Reproduce it, then find the cause | The cause, and a failing test that proves it | Fixing the symptom you can see instead of the cause |\n| **Improvement.** Nothing is broken, something could be better | Measure the thing you want to improve | The number to beat, taken before you touch anything | Changing code because it feels untidy, with nothing to compare |\n\nRemoving a feature is a feature change, not a cleanup, and it takes the same path. Deletions break things exactly as often as additions do.\n\nImprovement is the one people run wrong. Speed, security, readability, scale, and stale documentation all live here, and every one of them needs a before-number or a named weakness first. Without one you cannot tell improvement apart from churn, and neither can your agent.\n\n{/* KEEP (diagram, July 2026): the ONE picture of the whole thing, placed here because everything in it has now been taught: the three triggers, the kind fork, the rules file loading the right skills and docs, the six stops with the real file each reads or writes, and the records at the end. It replaced the simpler six-stop loop that used to sit above, do not reintroduce that one. Keep node labels plain, no line breaks, the book's mermaid stays simple. */}\n\n{/* KEEP: three ways work STARTS, one path regardless. You in a chat, an event in the system, or the clock. The last two get their own chapters later in this part, so name them in one line and move on, do not re-teach them. The point is only that a scheduled agent does not get a shortcut. */}\n\n## Who starts it does not change the path\n\nWork reaches the path three ways: you ask for it, something in the system reacts to an event, or the clock starts a scheduled run. The last two get built later in this part.\n\nNone of them is a shortcut. An agent woken by a schedule at three in the morning opens a ticket, researches, and records the outcome exactly like you would. The whole value of the path is that a week later you cannot tell which work was yours.\n\nHere is the whole thing on one page, from whatever started it to the records it leaves behind:\n\n```mermaid\n%% caption: Any trigger lands on the same path; the rules file loads what that kind of work needs, and every stop reads or writes a real file.\nflowchart TD\n  Y([You ask]) --> T\n  E([An event fires]) --> T\n  C([The clock]) --> T\n  T[1 Ticket on the board] --> K{Feature, bug, or improvement?}\n  K --> RF[Rules file loads the skills and docs that kind needs]\n  RF --> R[2 Research]\n  R --> RD[(Reads the spec, the decisions, the code)]\n  RD --> S[3 Write down what changes]\n  S --> SD[(Writes a spec, a diagnosis, or a target number)]\n  SD --> A([You approve])\n  A --> B[4 Build]\n  B --> V[5 Verify]\n  V --> VD[(Runs the tests and the app)]\n  VD --> REC[6 Record]\n  REC --> RCD[(Ticket closed, commit linked, decision logged, feature doc updated)]\n  RCD --> T\n```\n\nThe ticket is the hub. Everything the work touches hangs off it: the change that shipped, the reasoning behind it, and the feature document that now describes how the thing behaves.\n\n{/* KEEP: STEP. Research is the stop everyone skips and the one that prevents the most rework: an agent that has not read your code will confidently invent how it works. The standard = cite the file read or the command run, ban \"should be\" and \"probably\", say so plainly when it did not check. */}\n\n## Demand evidence, not recall\n\nResearch is the stop people cut first, and it is the one that saves the most rework. An agent that has not opened your code will cheerfully invent how it works, and everything built on that invention has to come out again.\n\nSo write the standard down: every claim about your system names the file it read or the command it ran. No \"should be\", no \"probably\". If it did not check, it says it did not check.\n\n{/* KEEP: STEP, the real artifact. A path you must remember to ask for is not a path: it goes in the file the agent reads before every session, as a numbered procedure. Show the actual block to copy, ending with the nothing-stays-in-chat rule. */}\n\n## Write the path into the rules file\n\nA path you have to remember to ask for is not a path. It belongs in the file your agent reads before every session, as a procedure it follows without being told:\n\n```\n# Task workflow, follow on every request\n1. Open a ticket on the board. No ticket, no work.\n2. Research first. Cite the file read or the command\n   run behind every claim. Never guess.\n3. Write the spec, then wait for my yes.\n4. Build only what the spec says.\n5. Run the tests and the app. Paste the output.\n6. Close the ticket, log the decision, note the outcome.\n\nSteps 2 and 3 depend on the kind of work:\n- Feature: read the spec, define what done looks like.\n- Bug: reproduce it, find the cause, ship a failing test.\n- Improvement: measure first, state the number to beat.\n  No number and no named weakness means no work.\n\nSame path whoever started it: me, an event, or the\nclock. Nothing important stays in this chat, and a step\nthat produced no file is a step that is not done.\n```\n\n{/* KEEP: prompt = senior engineer writes the workflow into the rules file matching what the board/log already do (no parallel process), adds the nothing-stays-in-chat line, then walks the reader's NEXT REAL TASK through all six stops so they see it work. One append slot. */}\n\n## Put your agents on the path\n\n```prompt\nAct as a senior engineer defining how my agents work.\nRead my rules file, my work board, and my decision log\nfirst, and match what those already do rather than\ninventing a parallel process beside them.\n\nWrite one task workflow into my rules file as a\nnumbered procedure to follow on every request: open a\nticket, research and cite the file or command behind\neach claim, write down what will change and wait for my\napproval, build only that, run the tests and paste the\noutput, then close the ticket and log the decision.\n\nThen record how the middle two steps differ by kind of\nwork. For a feature, read the spec first and define what\ndone looks like. For a bug, reproduce it and find the\ncause before proposing a fix, and ship a failing test\nwith it. For an improvement, measure the thing first and\nstate the number to beat, and refuse the work if there\nis no number and no named weakness.\n\nState that this holds no matter who started the work: me,\nan event, or a scheduled run.\n\nAdd one standing line: nothing important stays in the\nchat, and a step that produced no file is not done.\n\nThen walk my next real task through all six stops, so I\ncan watch the path work before it becomes a habit.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/task-workflow\n\nMy system, and the next task I want done:\n```\n\n**Do this now:** paste the prompt so the path lands in your rules file, then run your next task through all six stops without skipping the research."
          },
          {
            "slug": "triggers",
            "title": "React Instead of Waiting",
            "label": "Triggers",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/triggers",
            "content": "---\ntakeaway: Make agents react the instant something happens\nshare: \"Scheduling put agents on a clock, but some work can't wait for the clock. A trigger is a reflex: an agent that fires the instant something happens, so the gap between it broke and we responded is near zero.\"\nrequires: [ai-agent, event-ledger, guardrails-file, scheduled-job]\nproduces: [event-trigger]\nteaches: [trigger, reflex]\nglosses: [alert]\nuses: [ai-coding-agent, event, ledger, alert, stack-trace, decision-card, watcher-agent, test, code-review, prompt]\n---\n{/* KEEP: lead-in = scheduling put agents on a clock, but some work can't wait for the clock, it must happen the instant something occurs, that's the reflex. LIGHTER chapter, pairs with the ledger. */}\n\nScheduling put your agents on a clock. But some work cannot wait for the clock: it has to happen the instant something occurs. That is the other half of autonomy, the reflex, and it is what this short chapter adds.\n\n{/* KEEP: a scheduled agent asks \"is it time yet\"; a triggered agent asks \"did the thing happen\". One is a heartbeat (steady, periodic), the other a reflex (dormant until an event, then instant). A serious system has both. */}\n\n## Scheduled is proactive, triggered is immediate\n\nA scheduled agent asks, \"is it time yet?\" A **triggered** agent asks, \"did the thing happen?\"\n\nThe first is a heartbeat, steady and periodic. The second is a **reflex**, dormant until an event pokes it, then instant. A serious system has both: the heartbeat does the rounds, the reflex catches the fire the moment it starts.\n\n{/* KEEP: some problems can't wait for the next sweep: a payment fails, a key expires, an error spikes. If your only mechanism is a schedule, damage runs until the next tick. Reflexes are for events where the gap between \"it happened\" and \"we responded\" must be near zero. Smoke detector, not a morning check. */}\n\n## Some problems can't wait for the next sweep\n\nA payment fails. A key expires. An error spikes. If your only mechanism is a schedule, the damage runs until the next tick fires.\n\nReflexes exist for exactly the events where the gap between \"it happened\" and \"we responded\" has to be near zero. You do not schedule a smoke detector to check for fire each morning; you wire it to react the instant there is smoke.\n\nHere is the whole reflex on one event:\n\n1. **An error lands** in the ledger.\n2. **The reflex wakes** and pulls the real context: the stack trace, the recent changes, the live state.\n3. **Safe and reversible?** It makes the fix, proves it with a test, and ships it through review.\n4. **Costs money or touches user data?** It stops, files a decision card, and waits for you.\n\nInvestigating is always safe, so that part runs on its own; only the risky call waits for you.\n\n{/* KEEP: a reflex = an agent watching the event stream for a specific line; when that event lands, it fires, does its one job, goes back to sleep. This is why the ledger comes first: no honest event stream = nothing to react to. Show a tiny trigger rule (on event -> run agent). */}\n\n## Triggers listen to the ledger\n\nA reflex is an agent watching the event stream for one specific line. Something has to do the watching, and the simplest version is a small watcher on a tight loop. It reads new lines in the ledger every few seconds, and when a line matches, it runs the right agent.\n\nBigger setups let the tool that raised the **alert**, the automatic warning something is wrong, call a web address itself. The idea is the same, a rule that maps an event to an agent:\n\n```\non event  alert.fired    -> run  incident-responder\non event  payment.failed -> run  billing-retry\n```\n\n```mermaid\n%% caption: A watcher reads new ledger lines on a tight loop and runs the mapped agent when one matches.\nflowchart LR\n  LG[(Ledger)] -->|new lines| WT[Watcher loop]\n  WT --> Q{Line matches a rule?}\n  Q -->|alert.fired| IR[incident-responder]\n  Q -->|payment.failed| BR[billing-retry]\n```\n\n> **Watch out:** the same event can arrive twice, and a reflex that fires twice can charge the customer twice. Have it mark the event handled before it acts. Have a scheduled job skip if its last run is still going. That way nothing ever runs on the same thing twice.\n\nThis is why the ledger comes first: without one honest stream of events, there is nothing to watch. With it, any event can become a trigger.\n\n{/* KEEP: heartbeat + reflex = complete coverage of time. Scheduled agents handle the rhythm (routine on a cadence); triggered agents handle the surprises (events that arrive on their own). Between them nothing falls through. Flag lighter: add reflexes when you have events worth reacting to. */}\n\n## Together they cover the whole clock\n\nHeartbeat plus reflex is complete coverage of time. The scheduled agents handle the rhythm of the work, the routine that happens on a cadence. The triggered agents handle the surprises, the events that arrive on their own and demand a response now.\n\nBetween the two, nothing falls through: if it happens on a clock, the heartbeat has it; if it just happens, a reflex catches it.\n\n> **Hint:** reach for reflexes once you have a ledger and a few events that genuinely cannot wait for the next scheduled run.\n\n{/* KEEP: prompt = wire one reflex: watch for a specific event in the ledger and run an agent when it lands. Ends with Do this now. */}\n\n## Wire your first reflex\n\nThis prompt gives your system its first reflex:\n\n```prompt\nAct as a senior engineer adding an event-driven trigger to\nmy system. Read my event ledger, my guardrails file, and\nthe jobs already on my scheduler, then pick the one event\nthat most needs an instant response and is not already\ncovered by a job on a clock. Watch the ledger for it and\nrun the right agent the moment it lands. Use an approach\nthat works on my operating system. Keep the agent's job\nsmall, inside the guardrails I already set, and record the\ntrigger as one line in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/triggers\n\nMy operating system and the event that can't wait:\n```\n\n**Do this now:** paste the prompt and wire one reflex to the single event you would hate to catch a day late."
          },
          {
            "slug": "the-autopilot",
            "title": "The System That Runs Itself",
            "label": "Autopilot",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ai-os/the-autopilot",
            "content": "---\ntakeaway: Earn autonomy rung by rung\nshare: \"Every piece this part built snaps together into one self-running loop: your autopilot. But you never switch it on at full trust. You earn the autonomy one rung at a time, only as fast as the evidence lets you.\"\nrequires: [agent-os-tree, control-center, agent-config, agent-memory-file, agent-tools-config, scheduled-job, guardrails-file, work-board, event-ledger, event-trigger, test-suite, spec-file]\nproduces: [autopilot]\nteaches: [autopilot, trust-ladder]\nuses: [ai-coding-agent, ledger, work-board, ticket, trigger, blast-radius, test, spec, prompt]\n---\n{/* KEEP: lead-in = every piece of this part snaps into ONE self-running loop; name it the autopilot; capstone of the part. You BUILD it first, then make it run itself. */}\n\nYou have built every piece: a unified system, agents with memory and tools, schedules, triggers, guardrails, a ledger, a shared board. This last chapter names what they become when they run together, and it says the honest thing about switching them on. You do not flip everything to full autonomy on day one. You build the machine first, then you earn its independence.\n\n{/* KEEP: concept = name the assembled thing the autopilot; the closed loop, signals -> ledger -> agents act (sweeps + triggers) -> safe fixes ship, else a ticket -> agent drains the board -> risky escalates -> you steer. Real artifact = plain-text sketch of the loop. Self-correcting one-liner. Bold-first: autopilot. */}\n\n## The loop that runs itself\n\nAssembled, the pieces form one closed loop. Call it your **autopilot**:\n\n```\nsignal lands in the ledger\n      |\n  agents act  (scheduled sweeps + reactive triggers)\n      |\n  safe to fix? --yes--> fix it, test it, ship it\n      |\n      no\n      |\n  file a ticket on the shared board\n      |\n  an agent drains the board, one ready ticket at a time\n      |\n  risky? --yes--> escalate it to you\n      |\n  you steer from the control center\n```\n\nOne principle keeps it honest: every scheduled sweep reads the latest state, so a problem one run introduces, a later run catches. You never chain your own follow-ups; the loop corrects itself.\n\n```mermaid\n%% caption: The autopilot is a closed loop: signals drive agents, safe fixes ship, and a later sweep rereads state.\nflowchart TD\n  SIG([Signal lands]) --> LG[(Ledger)]\n  LG --> AG[Agents act]\n  AG --> Q{Safe to fix?}\n  Q -->|Yes| SHIP[Fix, test, ship]\n  Q -->|No| TK[Ticket on board]\n  TK --> ESC{Risky?}\n  ESC -->|Yes| YOU([You steer])\n  SHIP -->|later sweep rereads| LG\n```\n\n{/* KEEP: SPINE = the trust ladder. You EARN autonomy one rung at a time; never switched on day one. 5 rungs, ordered: report-only -> review-with-AI-and-act-together -> shared board (tie work-board by topic) -> one agent takes a narrow action class after a week clean -> widen up to deploy. */}\n\n## You earn it one rung at a time\n\nAutonomy is not a switch, it is a ladder. You climb it only as fast as the agent proves it can be trusted:\n\n1. **Report only.** The agent reads and tells you what it found. You take every action yourself.\n2. **Act together.** You go through the reports with your AI; it proposes and drafts, you approve each call.\n3. **Share a board.** You and the agents both file work as tickets, and an agent works only what you marked ready.\n4. **One narrow action.** After a week or two of it recommending the right moves without breaking anything, you let one agent take one small class of action on its own.\n5. **Widen slowly.** You grant more, up to shipping to production, and each rung opens only once the one below it earned trust.\n\n{/* KEEP: start with the MOST ANNOYING, repetitive tasks first, end to end (A to Z). Lowest risk, soonest payoff; that's where autonomy earns its keep first. */}\n\n## Start with the work you hate most\n\nDo not hand over the interesting work first. Hand over the annoying, repetitive work: the task you have done by hand fifty times that never changes. And hand it over end to end, from trigger to finished.\n\nThat is where autonomy pays off soonest and risks the least. A boring chore fully automated buys back real time, and if it slips, the blast radius is small. Win there, then climb.\n\n{/* KEEP: what makes trust safe = QA/tests. Good tests check the LOGICAL OBJECTIVE from your original spec (Plan part), not the interface, so they keep passing when the UI changes and reliably prove the action was correct. Everything ties back to the first spec. Cross-link Plan + Test by topic. Note self-healing deploy/rollback lives in Ship + Operate. */}\n\n## Tests are what make trust safe to grant\n\nYou can only climb the ladder because something objective is watching. That something is your tests. Good ones check the logical objective you wrote in your original spec, not the look of the screen. So they keep passing when the interface changes, and they still prove the agent did the right thing.\n\nThis is why the plan you wrote at the very start matters here at the end: every safe action traces back to that spec. The heavier self-healing machinery, shipping a change and rolling it back on its own, is built in the shipping and operating parts. Here you are just wiring the judgment loop that decides what to hand over.\n\n{/* KEEP: prompt = senior voice, agent audits \"what still needs me, and what could the system safely take over next\" to push toward more autonomy. Ends with Do this now. */}\n\n## Push toward more autonomy\n\nThis prompt finds your next safe rung:\n\n```prompt\nAct as a senior engineer auditing my system for more\nautonomy. Read my guardrails file, my work board, and my\ncontrol center first, so you judge what the system runs\ntoday, not what I remember.\n\nTell me which of my manual steps are safe to hand over\nnext: the repetitive ones, fully covered by tests, that\ntouch nothing my guardrails call irreversible. For each,\nname the one rung of trust to grant and the guardrail\nthat keeps it safe.\n\nLeave the genuinely human calls with me, and say so if I\nhave drawn a line you now think sits in the wrong place.\n\nWrite every handover I accept into my guardrails file,\nand one line into my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ai-os/the-autopilot\n\nMy system, what it does now, and what I still do by hand:\n```\n\n**Do this now:** paste the prompt, find the one manual chore your tests already cover, and let a single agent own it for a week before you widen anything else."
          }
        ]
      },
      {
        "id": "harden",
        "title": "Make it a solid, complete product",
        "chapters": [
          {
            "slug": "designing-the-flow",
            "title": "Designing How It Flows",
            "label": "Flow",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/designing-the-flow",
            "content": "---\ntakeaway: Design the path to done\nshare: \"Your app has screens that each work, but using it is a maze: too many steps to the one thing the user came for, and every screen handles only the happy case. This chapter gets you the shortest clear path to done, with all four states on every screen.\"\nrequires: [running-app, ai-agent, spec-file, screen-map]\nproduces: [user-flow-map, screen-states-checklist]\nteaches: [user-flow, friction, empty-state, loading-state, error-state, success-state]\nuses: [ai-coding-agent, prompt, spec]\n---\n{/* KEEP: lead-in = the Problem. Screens each work, but the JOURNEY from opening the app to done is longer and more broken than it should be. The path across screens IS the product. This chapter = shortest clear route to the goal + every screen ready for the ways real use goes sideways. This chapter owns UX as FLOW; the LOOK of a screen is a separate chapter (do NOT re-teach it). */}\n\nYour app has screens, and each one works. But someone landed on it to get one thing done, and the path from opening it to done winds through more steps and dead ends than it should. That path is the product, more than any single screen is. This chapter gets you the shortest clear route to the goal, with every screen ready for the ways real use goes sideways.\n\n{/* KEEP: Concept = the user came for ONE job. user flow = the path across screens to reach it (entry -> few steps -> goal). Designing the experience = designing that path, not the styling of one screen. Styling is a separate job (LOOK chapter), do NOT re-teach it. Cross-link BY TOPIC: the goal traces to the spec from Plan. Bold-first **user flow**. */}\n\n## Design the shortest path to done\n\nA user came for one job: send the invoice, book the room, save the note. The **user flow** is the path they take across screens to reach it: an entry point, a few steps, the goal reached.\n\nDesigning the experience means designing that path, the journey between screens, not the styling of any one of them. Styling each screen is its own job; here you design how they connect. The goal at the end is the one from the spec you wrote when you planned, the reason the whole app exists.\n\n{/* KEEP: you cannot shorten a path you have not drawn. Map the main flow as a line, one box per screen the user actually touches, entry to goal. Seeing it is how you catch the step that should not be there. Show a concrete inline flow line. */}\n\n## Map the main flow before you judge it\n\nYou cannot shorten a path you have not drawn. Write the main flow as a single line, entry to goal, one box per screen the user actually touches: `Open app -> Pick a template -> Fill three fields -> Saved`.\n\nLaid out like that, the extra step jumps out at you: the confirmation nobody needs, the settings screen between the user and their goal. Read the line and ask of every box: does the user have to be here to reach the goal?\n\n{/* KEEP: the agent ADDS by default (extra pages, fields, confirmations); your job is subtraction. friction = a place the user has to stop and think. Cut it: fewer steps, sensible defaults, next action always obvious. Bold-first **friction**. */}\n\n## Cut the steps the agent piles on\n\nLeft alone, an agent adds. It offers a settings page nobody asked for, a confirmation step, a field that could default itself. Each one is **friction**: a place the user has to stop and think, and every stop loses some of them.\n\nYour job is subtraction. Fewer steps, sensible defaults so the common choice is already made, and a next action that is always obvious. When you truly cannot cut a step, make it the only thing on that screen.\n\n```mermaid\n%% caption: Ask it of every step; cut what the user does not need to reach the goal.\nflowchart TD\n  STEP{Must the user be here?}\n  STEP -->|no| CUT[Cut, default, or merge]\n  STEP -->|yes| ONLY[Only thing on screen]\n```\n\n{/* KEEP: THE sharpest, most concrete lesson. The agent builds the screen for the moment everything is present and correct, and ships only that. A real screen has FOUR states: empty, loading, error, success. Name all four or you get one. Real artifact = the four-states checklist (distinct device from the wireframe in the LOOK chapter). Bold-first the four state names. The accessibility floor now has its own section right after this one; only the deep pass is deferred to Scale. */}\n\n## Every screen has four states, not one\n\nHere is the flow lesson the agent skips hardest. It builds each screen for the one moment when everything is present and correct, and ships only that.\n\nA real screen has four states: **empty** (no data yet), **loading** (working), **error** (it failed), and **success** (it worked). Name all four or you get only the last one. The empty and error states are where flow is won or lost. An empty screen should show the first step instead of a blank box, and an error should say what broke and how to fix it.\n\n```\nEvery screen, four states:\n[ ] Empty    no data yet: show a first step, not a blank\n[ ] Loading  working: show it is busy, not a frozen page\n[ ] Error    it failed: say what went wrong and how to fix it\n[ ] Success  it worked: the result, and the obvious next action\n```\n\n{/* KEEP: the accessibility FLOOR belongs to flow, and it belongs in this part, not deferred whole to the paid chapter in Scale. Five checks, no more: keyboard, visible focus, real labels, alt text, contrast. The deep pass (speed + full accessibility) still lives later; do not re-teach it here. */}\n\n## Make every screen usable by everyone\n\nSome of your users move by keyboard, some by screen reader, some at 200% zoom, and a flow they cannot finish is a customer you cannot bill. Five checks are the floor, and your agent adds every one of them once you name them:\n\n```\nAccessibility floor, every screen:\n[ ] Keyboard   every action reachable without a mouse\n[ ] Focus      a visible ring showing where you are\n[ ] Labels     every input tied to a real label\n[ ] Alt text   on every image that carries meaning\n[ ] Contrast   text readable in daylight\n```\n\nThe deeper pass, making the whole app fast and properly accessible, comes later in the book.\n\nThis prompt maps your flow, marks the friction, and designs all four states:\n\n```prompt\nAct as a senior product designer. Do not restyle\nanything yet; work on the flow. Read my spec, my\nmust-have stories, and my screen map first.\n\nFirst, map the main flow as a line of screens from\nentry to the one goal my spec says users come for.\nKeep it to the fewest screens that reach it.\n\nThen flag friction: every extra step, field, or\nchoice on that path I could cut, default, or\nmerge. Recommend the shortest version.\n\nThen, for each screen in the flow, design all\nfour states: empty (no data yet), loading,\nerror (what failed and how to fix it), and\nsuccess (the result plus the next action).\n\nThen check each screen against the accessibility\nfloor: reachable by keyboard alone, a visible\nfocus ring, every input labelled, alt text on\nmeaningful images, and readable contrast.\n\nGive me the flow and the cuts first, for my\napproval, before you design the states. Where a\ncut drops something my spec promised, say so\ninstead of dropping it quietly, and record the\ncuts I approve in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/designing-the-flow\n\nMy app and the one job users come to do:\n```\n\n**Do this now:** paste the prompt and describe your app and the one job users come for. Have your agent map the flow, mark the steps to cut, and design all four states for each screen, before you polish how any of it looks."
          },
          {
            "slug": "designing-the-interface",
            "title": "How It Looks and Feels",
            "label": "Interface",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/designing-the-interface",
            "content": "---\ntakeaway: Give a design direction\nshare: \"Your app runs but looks like a default template. Sketch each screen, give every screen one clear action, and hand the agent a real design direction: a named style, references, and hard constraints, not 'make it nice.'\"\nrequires: [running-app, ai-agent, screen-map]\nproduces: [design-brief-file, wireframe-set]\nteaches: [wireframe, primary-action, consistency, hierarchy, feedback, design-direction, design-brief]\nuses: [ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = app works but looks like a default the agent generated. Harden part OPENS here: production-grade starts with how it looks and feels, before faster/accessible (speed and accessibility come later, in the Scale part). Chapter gets reader to hand the agent a real design direction. Do NOT narrate the page. */}\n\nYour app works. Every feature does its job, but the whole thing still looks like what it is: a default the agent generated, generic type, flat gray boxes, no point of view. Making it production-grade starts at the surface, with how it looks and feels, before you make it faster and more accessible. This chapter gets you to hand your agent a real design direction, so the screens look like a product you chose to build, not a scaffold nobody styled.\n\n{/* KEEP: concept/mental model = YOU decide the layout, the agent renders it; don't let it design and build in one shot or it invents the generic. wireframe = rough box sketch of a screen. Show a monospace wireframe (Ledger, continuity with scaffolding). Bold-first: wireframe. */}\n\n## Sketch the screens first\n\nThe mistake is asking your agent to design and build a screen in one shot: you get whatever it invents, and it invents the generic. Decide the shape yourself first. A **wireframe** is a rough sketch of a screen, plain boxes for where things go, no color and no polish, just what sits where and how big.\n\nDraw it on paper or type it as labeled boxes. Name the boxes top to bottom and mark which one dominates:\n\n```\nLedger - Dashboard\n  [ topbar: Ledger ............. account ]\n  [ This month                          ]\n  [ $4,210 spent          (large, bold) ]\n  [ + Add expense     (primary button)  ]\n  [ Recent                              ]\n  [ - Groceries    $82   Jul 18         ]\n  [ - Fuel         $54   Jul 17         ]\n```\n\nHand that over and the agent builds your layout, not its best guess at one.\n\n{/* KEEP: each screen has ONE thing you most want the user to do = primary action, the loudest element; secondary actions stay quiet, competitors get demoted or cut. Rule-of-thumb callout: can't point at the one button within a second = no primary action yet. Bold-first: primary action. */}\n\n## One clear action per screen\n\nEvery screen has one thing you most want the user to do: add the expense, confirm the payment, start the trial. That is its **primary action**, and it should be the loudest element on the screen, one button styled stronger than anything near it. Secondary actions stay quiet, and anything that competes with it gets demoted or cut.\n\n> **Rule of thumb:** if you cannot point at the one button you most want tapped within a second of seeing a screen, that screen has no primary action yet. Fix that before you touch colors.\n\n{/* KEEP: three fundamentals the agent skips unless named. consistency = same styles everywhere; hierarchy = size/contrast points the eye at the primary action; feedback = every action visibly responds (working/saved/failed). Numbered list, bold-first each of the three. */}\n\n## Consistency, hierarchy, and feedback carry the polish\n\nWhat separates a professional interface from an amateur one is three habits your agent skips unless you name them:\n\n1. **Consistency:** the same spacing, colors, and buttons on every screen, so the app reads as one thing, not ten. Reuse styles, never reinvent per page.\n2. **Hierarchy:** size, weight, and contrast that make the important thing look important, so the eye lands on the primary action first.\n3. **Feedback:** every action visibly responds. A tapped button shows it is working, a saved form confirms, a failure says what went wrong.\n\nPut these three in your instructions and hold the agent to them.\n\n{/* KEEP (added July 2026, user mandate): the user-facing counterpart to the admin screen. Your customers want the same reassurance you do, about their own account, and showing it is what turns anxiety into confidence. Bound it hard: only numbers that answer a question they are already asking, charts only where a shape beats a number. Do NOT let this become a vanity dashboard. */}\n\n## Show people their own numbers\n\nYou are about to build a screen full of data for yourself. Your users want a much smaller version of the same thing, about their own account, and almost nobody gives it to them.\n\nShow them what they are quietly wondering: how much they have used, what it is costing, what happened to the thing they submitted, when it last ran, whether it worked. Every one of those answers is a support message you never receive.\n\nReach for a chart only where the shape says more than the number. Usage over the month is a chart, because the trend is the point. Their current plan is a number, and putting it on a graph makes it harder to read, not easier.\n\n> **Rule of thumb:** if a number would make a user calmer, show it. If it would only make you look busy, leave it out.\n\n{/* KEEP: \"make it nice\" = no target = template average. design direction = named style + references + hard constraints, written once as a reusable design brief. Show the real design brief artifact (fenced). Material Design linked as one concrete example reference language. End with senior-voice prompt (brief + screen sketches, approve BEFORE styling) then Do this now. Bold-first: design direction, design brief. */}\n\n## Hand the agent a design direction, not \"make it nice\"\n\n\"Make it nice\" gives the agent no target, so it hands back the safe average: another template. Give it a **design direction** instead: a named style, a few references you admire, and hard constraints. A reference is a real product whose feel you want, or a design language like [Material Design](https://m3.material.io) your agent already knows in depth. Write it once as a short **design brief** and reuse it on every screen, because one brief everywhere is what makes ten screens feel like one app.\n\n```\nDesign brief - Ledger\nStyle: calm, precise, data-first. It should\n  feel like a sharp tool, not a landing page.\nMood: dark UI, one cool accent, generous\n  white space, square corners over rounded.\nType: one clean sans, two sizes, heavy weight\n  for the numbers.\nDo: strong hierarchy, consistent spacing, a\n  visible state for every action.\nDon't: gradients, stacked drop shadows, emoji,\n  stock-photo hero.\n```\n\nThis prompt has your agent draft that brief and lay out your screens before it styles anything:\n\n```prompt\nAct as a senior product designer and front-end\nengineer. Before writing any styling, read what I\nalready have: my screen map, my user flow, my\nscreen states checklist, and the visual direction\nI settled on earlier. Build on those, do not\nstart over.\n\nTurn that direction into a short design\nbrief: a named style with two or three real\nreference products, a mood (color, spacing,\nshape), one type family, and an explicit do and\ndon't list. Opinionated and specific, never\ngeneric.\n\nThen, for each screen on my map, sketch the\nlayout as labeled boxes and name the single\nprimary action, the one thing I most want the\nuser to do, and make it the loudest element\nthere.\n\nHold every screen to three rules: consistency\n(reuse spacing, color, and components), hierarchy\n(size and contrast point the eye at the primary\naction), and feedback (every state on my\nchecklist has a visible design).\n\nShow me the brief and the sketches before you\nwrite any styling. Then save the brief in my\nspecs folder and log the style choice in my\ndecision log, so later screens are held to it.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/designing-the-interface\n\nMy app and the feel I want:\n```\n\n**Do this now:** paste the prompt, describe your app and the feel you want, and have your agent draft the design brief and screen sketches. Approve those before it writes a line of styling."
          },
          {
            "slug": "data-accounts-and-payments",
            "title": "Data, Users, and Payments",
            "label": "Accounts",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/data-accounts-and-payments",
            "content": "---\ntakeaway: Add real accounts, data, and payments\nshare: 'A real app holds three things a demo never does: data that must survive, users who log in, and payments. Two of them you must never build yourself.'\nrequires: [running-app, ai-agent, database-chosen, data-model, env-file]\nproduces: [persistent-datastore, auth-system, payment-flow]\nteaches: [persist, authentication, provider, pci, payment-token, merchant-of-record]\nglosses: [backup, encryption]\nuses: [database, framework, library, encryption, backup, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = a real app holds 3 things a demo never does: persisted data, logins, payments. Two of the three (auth, payments) you must NEVER build yourself. Payoff = all three, plus the two hard rules that keep them from ending your app. */}\n\nYour demo runs fine on your laptop. A real app is different: it holds what people cannot afford to lose, their saved work, who they are, and their money. So it has to remember what they made after a restart, know them when they return, and charge them without ever mishandling a card. Two of those three you must never build yourself, and this chapter gets you all three plus the rules that keep them from ending your app.\n\n{/* KEEP: concept = a demo keeps data in memory and a restart wipes it; a real app PERSISTS it to a database. This is the first thing users trust you with, and the one part you cannot regenerate. Don't re-teach modeling; point to it. Bold-first: persist. */}\n\n## Store data that survives\n\nA demo keeps its data in memory, so closing it erases everything. A real app must **persist** what people create: write it to a database that survives a restart, a deploy, and a crash. The chapter on modeling your data covers the shape that data takes.\n\nTreat what you store as the most valuable thing you hold, because it is the one part you cannot regenerate. Keep a **backup**, a copy you can restore from, and never run a change that could erase it.\n\n{/* KEEP: hard rule #1 = never build auth yourself. authentication = proving who a user is. It is a security specialty with many subtle failure modes; one slip exposes every account. Use a provider. Bold-first: authentication (linked to OWASP), provider. */}\n\n## Accounts: never roll your own auth\n\nThe moment people log in, you are doing [**authentication**](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html): proving each person is who they claim to be. It looks simple and is not. Password hashing, session tokens, password resets, two-factor, breach checks: each is a place to get security subtly wrong, and one mistake exposes every account at once.\n\nSo do not build it. Use an authentication **provider**, [Auth0](https://auth0.com), [Clerk](https://clerk.com), [Supabase Auth](https://supabase.com/auth), or your framework's own vetted library, whose whole job is getting this right and patching it as attacks change. You wire your app to it and never store a password yourself.\n\n{/* KEEP: hard rule #2 = a raw card number must never reach your server; you are not allowed to store one. PCI = the standard that governs it. Use a payments provider (Stripe): card goes browser -> provider -> you get a token you store instead. Show the do/don't artifact. Bold-first: PCI (linked), token. Link Stripe. */}\n\n## Payments: never touch card numbers\n\nPayments have a stricter rule: a raw card number must never reach your server, and you are not allowed to store one. Handling cards safely is governed by a standard called [**PCI**](https://stripe.com/guides/pci-compliance), and meeting it yourself is a compliance project, not a feature.\n\nSo you never touch the card. A payments provider like [Stripe](https://stripe.com) gives you a form that sends the card straight from the user's browser to them. It hands back a **token**, a harmless reference you keep in place of the card. You charge the token; the provider carries the risk.\n\n```mermaid\n%% caption: The card goes straight from the browser to Stripe; your server only ever holds the token.\nflowchart TD\n  U([User browser]) -->|1. card number| ST[Stripe]\n  ST -->|2. token| SRV[Your server]\n  SRV -->|3. charge the token| ST\n```\n\n```\nDON'T let these reach your server\n  a card number, its CVC or expiry\n  a password you hashed yourself\n  login tokens you invented\n\nDO store only safe references\n  the auth provider's id for each user\n  Stripe's token in place of the card\n```\n\n{/* KEEP: the decisions the safety rule does not settle, all first-hour and all different code: one-time vs subscription, hosted checkout vs embedded form (hosted is the default), direct vs merchant of record (Paddle/Lemon Squeezy carry global VAT + sales tax a solo seller would owe personally), money stored as integer minor units never a float, and refunds/disputes wired before the first one. Bold-first: merchant of record. */}\n\n## Decide how you charge before you wire it\n\nThe safety rule is settled. The shape of the charge is still yours to pick, and each of these is different code:\n\n- **One-time or subscription.** A single charge and a recurring plan are separate objects at the provider, so decide before your agent writes either.\n- **Hosted or embedded.** The provider's own hosted checkout page handles far more edge cases than a form you embed. Take it unless you have a reason not to.\n- **Direct or merchant of record.** [Paddle](https://www.paddle.com) and [Lemon Squeezy](https://www.lemonsqueezy.com) sell to your customer on your behalf and carry the worldwide sales-tax and VAT registration you would otherwise owe personally. Selling globally as one person, that is usually worth the bigger cut.\n- **Whole cents, never a float.** Store money as an integer count of the smallest unit. Fractions do not divide cleanly in binary, and a total built from decimals drifts by a cent.\n\nRefunds and disputes are both certain, so wire those paths now rather than on the day the first one lands.\n\n{/* KEEP: synthesis = one pattern for all three, let specialists hold the dangerous parts and your app stores only references. Least access, encrypt, back up. Then the prompt hands the reader's specific case to their agent. */}\n\n## Protect what users trust you with\n\nThe pattern is the same for all three: let specialists hold the dangerous parts. The database keeps the data, the auth provider holds identities, the payments provider holds cards, and your app stores only references to them. Give each the least access it needs, put anything sensitive behind **encryption** so it is unreadable without the key, and back up what you cannot regenerate.\n\nThis prompt hands your case to your agent:\n\n```prompt\nAct as a senior engineer wiring up what a real\napp needs beyond a demo: persisted data, user\naccounts, and payments. Read my data model, my\nprivacy and cost targets, and my decision log\nfirst, so this fits limits I already set.\n\nEnforce two hard rules. Never roll our own\nauthentication: choose a provider (Auth0, Clerk,\nSupabase Auth, or the framework's vetted library)\nand wire to it, so we never store a password.\nNever let a raw card number reach our server: use\na payments provider (Stripe) so the card goes\nbrowser to provider and we store only its token.\nPut each provider behind its own adapter, like my\nother vendors.\n\nFor each of the three, tell me what we store, what\nthe specialist holds, and the least access it\nneeds. Then list the backup and encryption steps\nfor the data we cannot regenerate.\n\nFor payments also decide: one-time or\nsubscription, hosted checkout or embedded form,\nand direct or a merchant of record that carries\nglobal sales tax for me. Store money as integer\nminor units, and wire the refund and dispute\npaths from the start.\n\nRecord each provider choice as one line in my\ndecision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/data-accounts-and-payments\n\nMy app: what it stores, who logs in, what they pay for:\n```\n\n**Do this now:** paste the prompt with your app's specifics and let your agent wire each of the three to a specialist. Then confirm your server holds references, never a password or a card."
          },
          {
            "slug": "sending-email-and-notifications",
            "title": "Send Email Without Landing in Spam",
            "label": "Email",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/sending-email-and-notifications",
            "content": "---\ntakeaway: Send mail through a provider, not your server\nshare: \"The moment you have accounts and payments, your app owes people mail: receipts, verifications, resets, replies. Send it from your own server and most of it lands in spam. This chapter gets it delivered: through a provider, with the domain records inboxes trust, on the few events that deserve a notification.\"\nrequires: [running-app, ai-agent, auth-system, payment-flow, domain]\nproduces: [email-provider-setup, dns-email-records]\nteaches: [transactional-email, email-provider, spf-dkim, dmarc]\nglosses: [dns]\nuses: [provider, dns, prompt]\n---\n\n{/* KEEP: lead-in = the Problem. Once you have accounts + payments your app must send its own mail (receipt, verification, reset, notification); from your own server most lands in spam or never arrives. Payoff = get the app's mail actually delivered. */}\n\nThe moment you have accounts and payments, your app has to send mail: a receipt, a verification link, a password reset, a note that someone replied. Send it from your own server and most of it lands in spam or never arrives. This chapter gets your app's mail actually delivered.\n\n{/* KEEP: Concept = transactional email = the automatic one-to-one mail your app sends in response to a user action (receipt, verification, reset, notification), NOT a marketing blast. Auth provider already sends its own login/reset mail; this is everything else. Bold-first: transactional email. */}\n\n## A real app sends its own mail\n\nEvery action your app takes on someone's behalf can owe them a message. A receipt after a charge, a link to verify an address, a reset when they are locked out, a note that someone replied. That is **transactional email**, the automatic one-to-one mail your app sends in response to a single user action. It is not a marketing blast to a list; it is one message, to one person, triggered by one thing they did.\n\nYour auth provider already sends its own login and reset mail. This chapter is about everything else your app owes the user.\n\n{/* KEEP: Step = deliverability is a specialty; mail straight from your app server gets flagged as spam. Use an email provider (Postmark/Resend/SES) whose whole job is the inbox. Real artifact = a provider send call. One mermaid: direct = spam, via provider = inbox. Bold-first + link: email provider (link all three). Also: before the domain exists, test against a local mail catcher (Mailpit) instead of sending. */}\n\n## Never send mail from your own server\n\nGetting mail into an inbox is a specialty of its own. Send it straight from your app server and inbox providers treat an unknown machine as a likely spammer, so your receipts land in junk or vanish. Hand it to an **email provider** like [Postmark](https://postmarkapp.com), [Resend](https://resend.com), or [Amazon SES](https://aws.amazon.com/ses/), whose entire job is reaching the inbox.\n\nOne call does it, and your app never speaks the low-level mail protocol itself.\n\n```js\n// One call to your provider sends the receipt.\n// Your app never talks to SMTP; the provider does.\nawait resend.emails.send({\n  from: 'receipts@yourapp.com',\n  to: user.email,\n  subject: 'Your receipt',\n  html: renderReceipt(order),\n})\n```\n\nUntil you own the domain you will send from, none of this can be tested for real. So point your app at a local mail catcher like [Mailpit](https://github.com/axllent/mailpit), and read what it traps instead of sending it.\n\n```mermaid\n%% caption: Straight from your server, mail lands in spam; through a provider, it reaches the inbox.\nflowchart LR\n  APP([Your app]) -->|direct send| SPAM[Flagged as spam]\n  APP -->|via provider| PROV[Email provider]\n  PROV --> INBOX[Reaches the inbox]\n```\n\n{/* KEEP: Step = deliverability is the hard part. THREE domain records, not two: SPF and DKIM prove the mail is really from you, DMARC says what an inbox should do when one of them fails and is now required by Gmail/Yahoo for bulk senders, so a two-record setup is incomplete. Provider generates them, you add them to your domain ONCE; it also handles bounces + complaints. Judgment: start DMARC at p=none and read the reports before tightening. Bold-first: SPF and DKIM, DMARC. */}\n\n## Deliverability is the part you outsource\n\nInboxes only trust mail they can prove came from you, and three domain records do that proving. **SPF and DKIM** declare who may send for your domain and stamp each message with a signature only you could make. [**DMARC**](https://dmarc.org) tells inboxes what to do when one of those checks fails. Gmail and Yahoo now require it from anyone sending at volume, so two records is an unfinished setup.\n\nYour provider generates all three for you. You add them once to your domain's **DNS**, the settings that tell the internet how your domain works. Start the DMARC record at `p=none`, which asks for reports without changing how your mail is treated, and only tighten it once those reports come back clean.\n\nFrom then on the provider also absorbs the bounces and spam complaints that would otherwise wreck your sending reputation.\n\n{/* KEEP: Step = same rule covers other channels (in-app, push, SMS via a provider); pick events that truly deserve a notification, do not spam users. One caution callout: every extra notification trains people to ignore all of them. */}\n\n## Notify on other channels, but do not spam\n\nThe same rule covers every other channel. In-app alerts, push, and SMS all go through a provider built for them, never a pipe you run yourself. The harder question is not how to send but whether to. Pick the few events that genuinely deserve interrupting someone, a payment, a reply, a security alert. Let the rest live quietly in the app.\n\n> **Watch out:** every extra notification trains people to ignore all of them. A channel your users mute is worse than one you never built.\n\nThis prompt wires it all to a provider and picks the events worth sending:\n\n```prompt\nAct as a senior engineer wiring my app's\ntransactional email through a provider. Do not\nbuild SMTP or send from our own server.\n\nRead my architecture map and my decision log\nfirst, so this fits the structure and reverses\nno choice already recorded there.\n\n1. Pick an email provider (Postmark, Resend, or\n   Amazon SES) and wire it behind a vendor\n   adapter I own, so one call sends a message\n   and the provider stays swappable. Its keys\n   go in .env and .env.example, never in code.\n2. Set up domain authentication: generate the\n   SPF, DKIM, and DMARC records, tell me exactly\n   what to add to our DNS, start DMARC at p=none,\n   and confirm mail is signed.\n3. List which events should send mail (receipt,\n   verification, reset, reply) and which should\n   not, so we never spam users.\n4. For any other channel I need (in-app, push,\n   SMS), name the provider and the events worth\n   sending, and skip the rest.\n\nGive me the provider choice and the DNS records\nfirst, then the send code. Record the provider\nchoice as one line in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/sending-email-and-notifications\n\nMy app: what it sends, to whom, on what events:\n```\n\n**Do this now:** paste the prompt, wire your app's mail through one provider, and add its SPF, DKIM, and DMARC records to your domain before you send a single real message."
          },
          {
            "slug": "database-migrations",
            "title": "Changing the Database Safely",
            "label": "Migrations",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/database-migrations",
            "content": "---\ntakeaway: Change the schema safely\nshare: \"Your app's structure keeps changing after real users exist. Change it safely through a migration: a versioned, reversible file your agent applies by command, never a hand-edit to the live database.\"\nrequires: [running-app, ai-agent, persistent-datastore, git-repo, deployed-url]\nproduces: [migration-process]\nteaches: [migration, up-migration, down-migration]\nglosses: [backup]\nuses: [schema, database, relational-database, commit, backup, stack, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = app is live with real user data and its structure must change (new column, table split, missing field). This chapter: change a live database's structure safely, the same controlled way every time, and undo it cleanly when it goes wrong. */}\n\nYour app is live and people are using it. Now the structure has to change: a new column on `orders`, a table that should be split in two, a field that should have existed from day one. The data those users already created is sitting in the database, so you cannot just reshape it and hope. This chapter gets you changing a live database's structure safely, the same controlled way every time, and undoing the change cleanly when it goes wrong.\n\n{/* KEEP: concept = a migration is one versioned change to DB structure, written as a file, saved with the code, applied by a tool not by hand; the same numbered files replay identically across every environment. Bold-first: migration. Tool line: the reader's own stack ships one (Prisma Migrate / Alembic / Rails / Laravel); dbmate is the standalone fallback, link on first mention. */}\n\n## Every schema change is a versioned file\n\nA **migration** is one change to your database's structure, written as a file and saved alongside your code. Add a column, rename a table, split one table into two: each becomes its own migration, numbered so the changes run in a fixed order.\n\nThat order is what makes them safe to trust. Your own machine, a test copy, and the live server all apply the same numbered files in the same sequence. Every one of them ends up with an identical structure.\n\nYour agent writes these files and a migration tool applies them. Your stack almost certainly ships one already, [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate) in TypeScript, [Alembic](https://alembic.sqlalchemy.org) in Python, Rails and Laravel their own, with [dbmate](https://github.com/amacneil/dbmate) as the standalone option when yours has none. You never type the changes into the database yourself.\n\n{/* KEEP: hard rule = NEVER edit the live database by hand (no console ALTER, no dashboard column). A hand-edit is unversioned, unreviewed, not replicated, invisible to the next release. Structure changes only through a committed migration file, applied by the tool. Watch out callout. */}\n\n## Never edit the live database by hand\n\nThis is the one rule that keeps the whole system honest: never open the live database and change its structure by hand. Not a quick `ALTER TABLE` in a console, not a column added through a hosting dashboard.\n\nA hand-edit exists in exactly one place, that single server. It is not in your code, so no one can review it and your test copy never receives it. The next time new code goes live, it has no idea the change ever happened. Structure changes only ever through a committed migration file, applied by the tool.\n\n```mermaid\n%% caption: A hand-edit lives on one server and collides; a migration file is shared and safe.\nflowchart TD\n  CHG([Structure change]) -->|by hand| HAND[Live server only]\n  CHG -->|migration file| FILE[Committed to code]\n  HAND --> COLLIDE[Collides next release]\n  FILE --> SHARED[Reviewed and replayed]\n```\n\n> **Watch out:** The costly database disasters almost always start with a well-meaning manual fix on the live server. If it did not go through a migration, it lives on that one box alone, and it will collide with your next release.\n\n{/* KEEP: reversibility = every migration has an up (roll forward, apply) and a down (roll back, undo). Real artifact: dbmate up/down SQL file + apply/rollback commands. Bold-first: up, down. Note destructive changes (drop column) lose data, not cleanly reversible, back up first. LOCKING judgment lives here too: the example ADD COLUMN NOT NULL DEFAULT is the classic table-locking migration, so on a big table add nullable, backfill in batches, add the constraint, and never hold a lock during a deploy. Topic cross-ref to undoing a bad code change. Prompt (senior voice, one append slot \"The schema change I need:\"). Do this now = paste it. */}\n\n## Roll forward and roll back\n\nEvery migration has two halves. The **up** half rolls the change forward, applying it; the **down** half rolls it back, undoing it. When a change turns out bad, the tool runs the down half and the structure returns to exactly where it was.\n\n```sql\n-- db/migrations/20260720120000_add_order_status.sql\n\n-- migrate:up\nALTER TABLE orders\n  ADD COLUMN status text NOT NULL DEFAULT 'pending';\n\n-- migrate:down\nALTER TABLE orders\n  DROP COLUMN status;\n```\n\nYour agent applies it with the tool's up command, `dbmate up` here, and reverses it with `dbmate down`, never by hand. The chapter on undoing a bad code change did this for your code; a migration does the same for your database's structure.\n\nThat one line is also the classic way to freeze a live app. On a big table, adding a `NOT NULL` column with a default can lock every read and write while it rewrites each row. Whether it does depends on your database and its version.\n\nThe safe shape there is three steps: add the column nullable, backfill in batches, then add the constraint. Ask your agent which of your migrations takes a lock, and never run one that does in the middle of a deploy.\n\nOne catch: some changes cannot be undone perfectly. Dropping a column throws its data away, so its down half cannot bring that data back. Make those one-way changes deliberately, and take a **backup**, a saved copy you can restore from, before you run them.\n\n```mermaid\n%% caption: A reversible change undoes cleanly; one that drops data is one-way, so back up first.\nflowchart TD\n  Q{Does the change drop data?}\n  Q -->|no| REV[Down restores it exactly]\n  Q -->|yes| ONEWAY[One-way, back up first]\n```\n\nHand the change to your agent with the rules already set:\n\n```prompt\nAct as a senior engineer changing a live\ndatabase safely. Read my data model and my spec\nfirst, then turn my schema change into a migration\nfor the migration tool my stack already uses.\nRules:\n- Write it as a versioned migration file, never\n  a hand-edit to the live database.\n- Give it an \"up\" that applies the change and a\n  \"down\" that reverses it.\n- If the change drops or rewrites existing data,\n  warn me and tell me what to back up first.\n- Say whether it locks the table on a large one,\n  and if so split it: nullable column, batched\n  backfill, then the constraint.\n- Show me the up and down before anything runs,\n  then apply it by command, not by hand.\n- Once applied, confirm the app still runs, update\n  the data model in my spec to match, and log the\n  change and its reason in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/database-migrations\n\nThe schema change I need:\n```\n\n**Do this now:** the next time your live app's structure has to change, paste the prompt with your change. Let your agent write the up-and-down migration instead of touching the database directly."
          },
          {
            "slug": "making-it-reliable",
            "title": "Handling Failure Gracefully",
            "label": "Reliability",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/making-it-reliable",
            "content": "---\ntakeaway: Handle failure gracefully\nshare: \"Your app works when you click through it, then real users hit the dropped connection, the full disk, the service that is down. This chapter gets it to fail gracefully: handle every error instead of swallowing it, cover the empty and huge and concurrent cases your agent skipped, and never leave a half-written record behind.\"\nrequires: [running-app, ai-agent]\nproduces: [hardened-feature]\nteaches: [happy-path, timeout, retry, exponential-backoff, jitter, circuit-breaker, edge-case, transaction, idempotency, idempotency-key]\nglosses: []\nuses: [ai-coding-agent, prompt, database, test]\n---\n{/* KEEP: lead-in = the Problem. The app works because you only ever run the happy path; real users hit the failure paths (network drop, full disk, service down), and an agent writes the happy path by default. Bold-first **happy path**. This chapter = make the app stay trustworthy when things fail. */}\n\nYour app works every time you click through it yourself. That is the **happy path**, the run where nothing goes wrong. Real users hit the paths where something does, and an agent writes only the happy one by default. This chapter gets your app to stay trustworthy when the rest of reality shows up.\n\n{/* KEEP: Concept = every reach outside the code can fail and eventually will; treat failure as a normal branch you handle, not a rare accident you ignore. List the three failure points you hit first (network, disk, dependency service). The agent assumes all three succeed. */}\n\n## Assume every call can fail\n\nEvery time your code reaches outside itself, that reach can fail, and eventually it will. Treat failure as a normal branch you handle, not a rare accident you ignore.\n\nThe three you hit first:\n\n- The network drops or times out mid-request.\n- The disk is full, or the file you expected is gone.\n- A service you depend on is down, or slow enough to look down.\n\nYour agent assumes all three succeed. Your job is to assume they will not. Four defenses handle the reach that fails:\n\n- Set a **timeout** so a slow service cannot hang your app.\n- **Retry** a brief failure, with **exponential backoff**: wait longer each try.\n- Add **jitter**, a little randomness on each wait, so clients do not retry in lockstep.\n- If a service keeps failing, a **circuit breaker** stops calling it for a while so it can recover, and you fail fast instead of piling up.\n\n{/* KEEP: the core. Swallowing = a catch that returns a default/empty and moves on, so the failure vanishes with no record and the user is left blind. Handling = two jobs, always: log the real cause for you AND show the user a message they can act on. Real artifact: before/after code (empty-array swallow vs log + thrown user message). Rule-of-thumb callout: every catch does both jobs or it is a bug. */}\n\n## Catch the error, never swallow it\n\nWhen a call fails, an agent often buries it: a `catch` that returns an empty value and moves on. The app does not crash, so it looks fine, but the failure vanished with no record and the user is left staring at nothing.\n\nHandling an error means two things, always: **log** the real cause, a written record you can search later, and show the user a message they can act on.\n\n```mermaid\n%% caption: Swallowing hides the failure; handling logs the cause and gives the user a message to act on.\nflowchart TD\n  F([Call fails]) -->|swallow| SW[Return empty]\n  F -->|handle| HA[Handle it]\n  SW --> BL[Failure vanishes]\n  HA -->|log for you| LG[(Error log)]\n  HA -->|message for user| MS[User can act]\n```\n\n```js\n// Swallowed: the failure vanishes and the\n// user sees an empty list, never knowing why.\nasync function loadOrders() {\n  try {\n    return await api.getOrders()\n  } catch {\n    return []\n  }\n}\n```\n\n```js\n// Handled: log the real cause for you, show\n// the user a message they can act on.\nasync function loadOrders() {\n  try {\n    return await api.getOrders()\n  } catch (err) {\n    logger.error('getOrders failed', err)\n    throw new Error(\n      'We could not load your orders. Try again.'\n    )\n  }\n}\n```\n\n> **Rule of thumb:** every `catch` earns its place by doing two jobs, a log for you and a message for the user. An empty one is a silent failure you will hear about from a confused user instead.\n\n{/* KEEP: define **edge case** = a condition at the boundary of what the code expects. The agent tests the comfortable middle and skips the edges, so name them and hand them back. Table of four: empty, huge, concurrent, malformed, and what breaks when ignored. Plus the timestamp rule (store UTC, convert at display) as a storage decision, not an edge case. Forward pointer (by topic) to QA turning these into tests. */}\n\n## Cover the edge cases the agent skipped\n\nAn **edge case** is a condition at the boundary of what the code expects, the empty input or the huge one, not the tidy middle it was demoed on. Your agent tests the comfortable middle and skips the edges, so name them and hand them back.\n\n| Edge case | What breaks when you ignore it |\n|---|---|\n| Empty (no rows, blank field, zero items) | The layout breaks, or the math divides by zero |\n| Huge (a 2 GB file, 10,000 rows at once) | The page freezes or the server runs out of memory |\n| Concurrent (two people save the same second) | One save silently overwrites the other |\n| Malformed (letters where a number goes) | The code crashes on the first bad value |\n\nOne more the agent gets wrong by default is not an edge case but a storage decision: keep every timestamp in UTC and convert only at the moment you display it. Store local times instead and your first user in another country sees yesterday's data. The weekend the clocks change, some of it is simply wrong.\n\nLater, QA turns these same cases into tests that re-check them on every change. For now, handling them by hand is the win.\n\n{/* KEEP: the worst failure stops halfway (charge the card, crash before saving the order) = a half-written state, worse than a clean crash because nothing tells you it happened. Fix: group all-or-nothing steps into one **transaction** (the database undoes everything on failure). For non-DB steps (charge, email) make each safe to run twice. */}\n\n## Leave data consistent when it breaks\n\nThe worst failure is the one that stops halfway. A checkout charges the card, then crashes before it saves the order: the money moved and the record did not. That half-written state is far worse than a clean crash, because nothing tells you it happened.\n\nGroup the steps that must all happen, or none, into one **transaction**. The database runs them as a single unit and undoes everything if any step fails, so a crash leaves the data untouched.\n\nFor steps outside the database, like charging a card or sending mail, make each one safe to run twice, so a retry never doubles the damage. That property is **idempotency**. An **idempotency key**, a token you send with the request, is how a provider makes a repeated call take effect only once.\n\n```mermaid\n%% caption: A transaction runs all-or-nothing steps as one unit and undoes them if any step fails.\nflowchart LR\n  subgraph TX[One transaction]\n    SO[Save order] --> US[Update stock]\n  end\n  TX -->|all succeed| OK([Committed])\n  TX -->|any fails| RB([Rolled back])\n```\n\nThis prompt hardens one feature without changing what it does:\n\n```prompt\nAct as a senior engineer hardening one feature\nfor reliability. Do not add features or change\nwhat it does.\n\nRead my NFR targets and my conventions first:\ntimeouts, retries, and error wording must match\nthe numbers I already committed to, not new ones\nyou pick.\n\nWork through this feature and:\n1. Find every call that can fail: network,\n   disk, database, or another service. Make\n   sure each is handled, not swallowed.\n2. For each failure, log the real cause for me\n   and return a message the user can act on.\n   Flag every empty catch or silent default.\n3. List the edge cases it ignores, empty,\n   huge, concurrent, and malformed, and handle\n   each one. Flag any timestamp stored in local\n   time instead of UTC.\n4. Find any write that happens in several\n   steps. Wrap the steps that must all succeed\n   in one transaction, so a mid-way failure\n   leaves no half-written record.\n\nGive me the risks first as a short list, then\nthe fix for each. Touch behavior only where it\nwas unsafe. Add any standing rule you applied\nto my rules file, and note the change in my\nchangelog.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/making-it-reliable\n\nThe feature to make reliable:\n```\n\n**Do this now:** paste the prompt with your riskiest feature, the one that touches money, files, or another service. Let the agent turn its happy-path code into code that survives a failure."
          },
          {
            "slug": "background-jobs",
            "title": "Do Slow Work in the Background",
            "label": "Background Jobs",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/background-jobs",
            "content": "---\ntakeaway: Do slow work off the request\nshare: \"Some work is too slow to make a user wait on: sending an email, processing an upload, calling a slow model. This chapter gets it off the request onto a queue a worker drains, so the page stays snappy and the user hears back when it is done.\"\nrequires: [running-app, ai-agent, email-provider-setup]\nproduces: [background-worker]\nteaches: [background-job, queue, worker, scheduled-job]\nuses: [ai-coding-agent, prompt, model, cron]\n---\n\n{/* KEEP: lead-in = the Problem. Some work is too slow to run inside a request (sending an email, processing an upload, calling a slow model): do it inline and the page hangs on a spinner or the request times out. Payoff: get slow work off the request so the app stays snappy no matter how heavy the job. */}\n\nSome work is too slow to make a user wait on: sending an email, processing an uploaded file, calling a slow model. Do it inside the request and the page hangs on a spinner, or the request times out before the work finishes. This chapter gets that slow work off the request, so your app stays snappy no matter how heavy the job.\n\n{/* KEEP: Concept = a request has one job, return a response fast; slow work does not belong inline. Name the fix: a **background job** = work your app does AFTER it has already responded to the user. The request hands the slow part off and returns at once. Bold-first: background job. */}\n\n## Not all work fits in one request\n\nA web request has one job: take the input and return a response fast, ideally in well under a second. Slow work does not belong inside it. While the request waits on the file or the model, the user sits watching a frozen page, and if it waits too long the request times out and fails.\n\nThe fix is a **background job**: work your app does after it has already responded to the user. The request hands the slow part off and returns at once, then the job runs on its own time.\n\n{/* KEEP: split the request in two: accept the input, hand the slow part to the background, respond at once. The user hears \"we are on it\" in the same instant, while the heavy work runs after the response is already sent. Keep the \"we are on it\" line. Mermaid shows the async split (respond now vs work later, notify later). */}\n\n## Respond now, work later\n\nSo split the request in two. Accept the input, hand the slow part to the background, and respond at once. The user hears \"we are on it\" in the same instant, while the heavy work runs after the response is already sent.\n\nThat is why a well-built app feels fast even when the work behind it is not. The user gets an immediate, honest status instead of a spinner that might time out, and nothing on their screen is blocked on the slow job.\n\n```mermaid\n%% caption: The request responds at once while the slow work runs off the request path and reports back when done.\nflowchart TD\n  R([Request]) --> A[Your app]\n  A -->|responds now| U([User told we are on it])\n  A -->|hands off slow work| BG[Background]\n  BG --> W[Worker runs the job]\n  W -->|when done| N([User notified])\n```\n\n{/* KEEP: the core mechanism. A **queue** = a line of jobs sitting between your app and a **worker** that pulls jobs and runs each to completion. Same queue-and-worker setup as scaling out (by topic), aimed at slow work not traffic. Retries come almost free: a thrown job is handed back to run again (safe-to-retry ties to reliability, by topic). Real artifact = enqueue + worker. The TOOL FORK lives here, one line naming the three shapes (in your database / dedicated service / managed), links only, no hosting guidance. Bold-first: queue, worker. Watch out: a job can run more than once, make each safe to run twice. */}\n\n## A queue holds the work for a worker\n\nBetween your app and the slow work sits a **queue**: a line of jobs waiting to be run. Your app adds a job and moves on. A separate **worker** pulls jobs off the queue one at a time and runs each to completion, in its own process.\n\nThis is the same queue-and-worker setup that carries the load when you add more machines, aimed here at slow work instead of traffic. It buys retries almost for free: if a job throws, the queue hands it back to be run again, so a blip does not lose the work.\n\n```js\n// In the request: save the input, enqueue a\n// job, and respond. The user waits on none of\n// the slow work below.\nasync function handleUpload(req, res) {\n  const file = await save(req.file)\n  await queue.add('process-upload', {\n    fileId: file.id,\n  })\n  res.json({ status: 'processing' })\n}\n```\n\n```js\n// The worker: pulls each job and runs the slow\n// work off the request path. If it throws, the\n// queue re-delivers it for another try.\nqueue.process('process-upload', async (job) => {\n  const { fileId } = job.data\n  await processUpload(fileId)\n  await setStatus(fileId, 'done')\n})\n```\n\nWhich queue depends on what you already run. [pg-boss](https://github.com/timgit/pg-boss) keeps the jobs in the database you already have. [BullMQ](https://docs.bullmq.io) and [Celery](https://docs.celeryq.dev) trade a second service to run for more throughput. [Amazon SQS](https://aws.amazon.com/sqs/) and [Inngest](https://www.inngest.com) run the queue for you.\n\n> **Watch out:** the queue can deliver a job more than once, so make each job safe to run twice. Sending the same email or charging a card twice does real damage; this is the same safe-to-retry rule your risky writes already need.\n\n{/* KEEP: half of a real product's background work has no user behind it: nightly cleanup, weekly digest, trial expiry, renewal. **scheduled job** = work on a clock, not a request. Prefer the queue's own scheduler over a bare cron line so it inherits retries + the record. THE TRAP: a scheduled run can fire twice or be skipped, so each must be safe to run twice and safe to miss once. Bold-first: scheduled job. */}\n\n## Some jobs run on a clock, not a request\n\nHalf of a real product's background work has no user behind it at all: the nightly cleanup, the weekly digest, the trial that expires, the subscription that renews. That is a **scheduled job**, work that runs on a clock. Run it from your queue's own scheduler rather than a bare `cron` line on the host, so it inherits the same retries and the same record as every other job.\n\nOne trap catches everyone here. A scheduled run can fire twice, or be skipped entirely while a machine restarts, so write each one to be safe to run twice and safe to miss once.\n\n{/* KEEP: close the loop. The work finishes out of sight, so tell the user when the job is done or they are left wondering. Two honest ways: the worker writes a status the page checks (processing then done), OR it pushes a notification (email, in-app alert). Rule: never start background work with no way to report the result. Prompt = move slow ops (email, files, model calls) to background jobs with a queue, retries, and a done-notification. ONE append slot. Ends with Do this now. */}\n\n## Tell the user when it is done\n\nThe work now finishes out of sight, so close the loop and tell the user when the job is done, or they are left wondering if it worked. Two honest ways:\n\n- The worker writes a status the user's page checks, processing then done, and the page updates itself.\n- The worker pushes a notification when it finishes: an email, or an in-app alert the user sees next time.\n\nEither way the rule holds: never start background work without a way to report the result. A silent job that never reports back looks, to the user, exactly like one that failed.\n\nThis prompt moves your slow operations to the background:\n\n```prompt\nAct as a senior engineer moving my slow\noperations off the request path. Do not change\nwhat the app does, only when the work runs.\nRead my non-functional targets, my layer map, and\nmy folder layout first, so \"too slow\" is my own\nnumber and the new code lands where my structure\nsays it goes.\n\nGo through this feature and:\n1. Find the slow work that blocks the response:\n   sending email, processing files, or calling\n   a model. Anything over my response target\n   counts.\n2. Move each one to a background job. The\n   request should enqueue the job and respond\n   right away with a processing status.\n3. Sketch the worker that pulls jobs and runs\n   them, with retries on failure and each job\n   safe to run more than once.\n4. When a job finishes, report back: update a\n   status the page can poll, or send the user\n   a notification.\n5. Put recurring work (cleanups, expiries,\n   digests) on the scheduler I already run,\n   safe to run twice and safe to miss a run.\n\nGive me the slow spots first as a short list,\nthen the change for each one.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/background-jobs\n\nThe feature to move to the background:\n```\n\n**Do this now:** paste the prompt with your slowest feature, the one that makes users wait. Let your agent move it to a background job that reports back when it is done."
          },
          {
            "slug": "refactoring",
            "title": "Paying Down AI Debt",
            "label": "Refactoring",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/harden/refactoring",
            "content": "---\ntakeaway: Delete more than you add\nshare: \"Your agent keeps over-building: extra layers, dead code, and abstractions for callers that never came. This chapter makes cleanup mostly subtraction, you refactor by deleting more than you add, with your tests as the safety net.\"\nrequires: [running-app, ai-agent, git-repo, test-suite]\nproduces: [refactored-codebase]\nteaches: [refactoring, over-engineering]\nuses: [test, function, design-pattern, layer, ai-coding-agent, prompt]\n---\n\n{/* KEEP: lead-in = the Problem. App runs but the agent quietly bloated the codebase; cleanup here means deleting more than adding. Ends naming the payoff: clean it up safely. Do NOT re-teach coupling or testing here. */}\n\nYour app works, but the code behind it has quietly bloated. Every feature you asked for, the agent answered with more structure than the job needed: an extra layer, an abstraction nobody calls twice. The codebase is harder to move through now, and you are not always sure which parts even run. This chapter gets you cleaning it up safely, by deleting more than you add.\n\n{/* KEEP: Concept = define refactoring (improve structure, behavior unchanged). Bold-first + link on **Refactoring** (Fowler, refactoring.com). Fowler's discipline: change structure and behavior separately. Tests are the safety net; reference testing BY TOPIC, not number. */}\n\n## Improve without changing behavior\n\n[**Refactoring**](https://refactoring.com) is improving the structure of code without changing what it does. The behavior your users see stays identical; only the shape underneath gets clearer. Martin Fowler named the practice and gave it one core discipline: change structure and behavior in separate steps, never both in the same move.\n\nThis is why tests come first. The suite that pins your app's behavior down is what lets you reshape the code without fear: change the structure, run the tests, and if they stay green, only the shape moved.\n\n```mermaid\n%% caption: Reshape the code, run the tests, and if they stay green only the structure moved.\nflowchart LR\n  CH[Change structure] --> RT[Run tests]\n  RT -->|green| SAFE([Behavior preserved])\n  RT -->|red| RV[Revert and retry]\n  RV --> CH\n```\n\n{/* KEEP: Step = with AI the refactor inverts to subtraction. The delete-list (dead code, unused options, duplicate helpers, speculative abstraction). Rule-of-thumb blockquote: cannot justify a layer in one sentence, delete the layer. */}\n\n## Delete more than you add\n\nA human refactor usually means adding structure: extracting a shared function, adding a layer that was missing. With an agent the debt runs the other way. It already over-produced, so your cleanup is mostly subtraction, and every line you delete is a line you never have to debug.\n\nHunt for and delete:\n\n- dead code and branches that never run\n- options, parameters, and config nothing sets\n- duplicate helpers doing the same job\n- abstraction built for a second caller that never arrived\n\n> **Rule of thumb:** if you cannot say in one sentence why a layer exists, delete the layer, not the sentence.\n\n{/* KEEP (added July 2026, user mandate): the OTHER debt, and the practice the author runs. Refactoring pays down code you wrote; dependency versions are a second pile you did not write and that grows on its own. The three things that make it work: a booked session with NO feature work in it, reading the changelog before upgrading, and the honest payoff framing (this is the only work where someone else already did it for you). Small batches and lockfiles are already taught in Set Up, do NOT re-teach them. */}\n\n## Book a session for upgrades, with no features in it\n\nRefactoring pays down debt in code you wrote. There is a second pile you did not write and cannot refactor away: every library under your app, drifting further behind with every week you ignore it.\n\nThat work never happens by accident, because there is always a feature that feels more urgent. So book it like any other task: a session with no new features in it at all. Upgrade, read what changed, run the tests, ship. Once a month is plenty, and your tests are what make it safe enough to be boring.\n\nRead the changelog before each upgrade, not after something breaks. Maintainers announce the breaking change there, in plain language, and skipping it is how a routine upgrade eats an afternoon.\n\nThen notice what you are actually being handed. This is the only work in the whole book where somebody else already did it for you.\n\nSecurity holes closed, code made faster, bundles made smaller, new capability added: all of it finished and merged by people you will never meet, sitting there waiting for one command.\n\n> **Rule of thumb:** an upgrade session with one feature in it is a feature session. The upgrades lose, every time.\n\n{/* KEEP: Step + Action = simplify what is used but overbuilt. THE artifact: before/after, factory+interface+config collapsed to one function, same behavior. Senior prompt (one append slot: The code that feels overbuilt:) then Do this now. */}\n\n## Simplify what the agent overbuilt\n\nDeletion removes what is unused. Simplification shrinks what is used but overbuilt. An agent that adds abstraction and options nobody asked for is **over-engineering**, and refactoring is where you cut it back to the simplest thing that works.\n\nThe agent reaches for enterprise patterns on a problem that wants a plain function: a factory to build one object, an interface with a single implementation. Here it was asked only to join a first and last name.\n\n```ts\n// The agent's version: a factory, an interface, and a\n// config object, all to join two strings.\ninterface NameFormatter {\n  format(user: User): string;\n}\n\nclass DefaultNameFormatter implements NameFormatter {\n  constructor(private config: FormatConfig = {}) {}\n  format(user: User): string {\n    const sep = this.config.separator ?? \" \";\n    return [user.first, user.last].filter(Boolean).join(sep);\n  }\n}\n\nexport function createNameFormatter() {\n  return new DefaultNameFormatter();\n}\n```\n\n```ts\n// Same behavior. Nothing else set the separator, so\n// it is gone too. One function does the whole job.\nexport function fullName(user: User): string {\n  return [user.first, user.last].filter(Boolean).join(\" \");\n}\n```\n\nSame inputs, same output, a quarter of the code and one obvious place to change it. Have your agent run that same pass on your worst file:\n\n```prompt\nAct as a senior engineer refactoring for simplicity,\nnot adding features. Behavior must not change.\n\nRead my rules file first, the conventions, the\narchitecture map, and my quality bar, and keep the\nsmaller version inside them.\n\nState in one sentence what this code does, so we have\na fixed target to preserve. Then find everything safe\nto remove:\n- dead code and branches that never run\n- options, params, and config nothing sets\n- duplicate helpers that do the same job\n- factories, interfaces, or strategies with a\n  single implementation\n\nPropose the smallest version with identical behavior.\nShow a before/after diff and say why each removal was\nsafe. Add nothing new: no features, no comments, no\nabstraction. If tests exist, keep them green; if not,\ntell me what to test before I delete anything.\n\nNote anything notable you removed in my changelog.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/harden/refactoring\n\nThe code that feels overbuilt:\n```\n\n**Do this now:** open the file in your app you least want to touch, run the prompt on it, and let your agent show you a smaller version that keeps every test green."
          }
        ]
      },
      {
        "id": "secure",
        "title": "Protect your app, data, and users",
        "chapters": [
          {
            "slug": "security",
            "title": "Working Code Isn't Safe Code",
            "label": "Why Secure",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/secure/security",
            "content": "---\ntakeaway: Working code isn't safe\nshare: 'Your app works, so it feels finished. But working and safe are two different things, and your agent only aimed for the first. You do not need to be a security expert, you need to know what to protect and hand each piece to your AI.'\nrequires: [running-app, project-folder, ai-agent]\nproduces: [threat-model]\nteaches: []\nuses: [ai-coding-agent, prompt, requirement, api-key, database]\n---\n{/* KEEP: lead-in = the app works so it feels done, but working and safe differ and the agent optimized for working. Reassure: you do not become a security expert, you learn what to protect and make the AI lock it down. This is the AWARENESS anchor of the Secure part; auth, attacks, audit are their own chapters, point forward by topic, don't deep-dive. */}\n\nYour app works. Every feature does what you asked, so it feels finished. But working and safe are two different things, and your agent only ever aimed for the first.\n\nThis part gets your app safe, and you do not have to become a security expert to do it. You have to know what you are protecting, and make your AI lock each piece down.\n\n{/* KEEP: AI turns a request into code that RUNS, not code that is SAFE; you never asked for safety, so nothing guarantees it. The agent optimizes for the visible goal (it works) and skips the invisible one (it is safe). */}\n\n## AI writes working code, not safe code\n\nAsk your agent for a login and you get a working login. You did not ask it to stop someone from skipping that login, reading another user's data, or pasting in something that breaks your database. Nothing guarantees it did any of that.\n\nThe agent optimizes for the goal you can see: the feature works. Safety is the goal you cannot see until it fails, so unless you name it, it gets skipped.\n\n{/* KEEP: security is the requirement nobody writes down; invisible until someone finds it missing. Unlike a broken feature you notice immediately, a security hole sits quiet until it is exploited. So you name it on purpose. */}\n\n## Security is the requirement nobody asks for\n\nA broken feature shows itself the moment you click. A security hole shows nothing. It sits quiet and working until the day someone finds it, and by then the damage is done.\n\n```mermaid\n%% caption: A broken feature shows at once; a security hole stays hidden until it is exploited.\nflowchart LR\n  BF([Broken feature]) -->|first click| SEEN[Seen at once]\n  SH([Security hole]) -.->|until exploited| QUIET[Sits quiet]\n  QUIET --> DMG[Damage done]\n```\n\nThat is why security has to be a deliberate step, not something you hope the agent included. You name the requirement out loud, the same way you named what the app should do.\n\n{/* KEEP: reassurance = you do not need to be an expert or learn to hack. You need to know WHAT to protect and hand it to the AI, which is genuinely good at applying known defenses once you point at them. The judgment is yours, the implementation is the agent's. */}\n\n## You don't need to be an expert\n\nThis is not a hacking course, and you will not be writing cryptography. You need one thing the agent does not have on its own: the judgment to say \"protect this.\"\n\nOnce you point at a risk, the agent is genuinely good at applying the known, standard defense for it. Your job is knowing what to point at. The rest of this part hands you that list.\n\n{/* KEEP: name what you're protecting = the four surfaces. Show the artifact. Your DATA (what you store), your ACCOUNTS (who gets in), your INPUTS/SURFACES (everything a stranger can reach and send), your SECRETS (keys). The part walks each; forward-point by topic to auth, attacks, audit. */}\n\n## Name what you're protecting\n\nAlmost every risk lands on one of four things. Name them, and you know what to hand your agent:\n\n```\nProtect:\n- Your DATA      what you store about users\n- Your ACCOUNTS  who is allowed in, and as whom\n- Your SURFACES  every input a stranger can reach\n- Your SECRETS   the keys that unlock everything\n```\n\nThe next chapters take these in turn: locking the doors with real auth, guarding your surfaces against the common attacks, and running a full audit before you launch. Start by having your agent map the risks for your specific app:\n\n```prompt\nAct as a senior security engineer reviewing my app\nbefore launch. Read my spec, my data model, and the\narchitecture map in my rules file first, so this covers\nwhat my app actually stores and exposes.\n\nIn plain language, no jargon, list the main things I\nneed to protect: the user data I store, who can log in\nand what they can reach, the inputs a stranger can\nsend, and the secrets that must stay hidden. For each,\nname the single biggest risk and the standard way to\ndefend it.\n\nDo not fix anything yet, just give me the map. Save it\nin my specs folder, and flag anything my spec promises\nthat the code does not appear to protect.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/secure/security\n\nMy app and what it handles:\n```\n\n**Do this now:** paste the prompt, get your app's plain-language risk map, and keep it open as you work through the rest of this part."
          },
          {
            "slug": "attack-surface",
            "title": "Where They'll Get In",
            "label": "Attack Surface",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/attack-surface",
            "content": null
          },
          {
            "slug": "auth-and-tokens",
            "title": "Who Gets In, and How",
            "label": "Auth & Tokens",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/auth-and-tokens",
            "content": null
          },
          {
            "slug": "permissions",
            "title": "Who May Touch What",
            "label": "Permissions",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/permissions",
            "content": null
          },
          {
            "slug": "validating-input",
            "title": "Trusting No Input",
            "label": "Validation",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/validating-input",
            "content": null
          },
          {
            "slug": "common-attacks",
            "title": "The Ones Worth Knowing",
            "label": "Common Attacks",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/common-attacks",
            "content": null
          },
          {
            "slug": "secrets-and-leaks",
            "title": "What Never Goes in the Repo",
            "label": "Leaks",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/secrets-and-leaks",
            "content": null
          },
          {
            "slug": "supply-chain",
            "title": "The Code You Didn't Write",
            "label": "Supply Chain",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/supply-chain",
            "content": null
          },
          {
            "slug": "securing-your-agent",
            "title": "Injection and Tool Access",
            "label": "Agent Security",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/securing-your-agent",
            "content": null
          },
          {
            "slug": "gating-agent-actions",
            "title": "Gate the Action, Not the Intent",
            "label": "Approvals",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/gating-agent-actions",
            "content": null
          },
          {
            "slug": "locking-down-access",
            "title": "Your Admin Panel Isn't Public",
            "label": "Access",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/locking-down-access",
            "content": null
          },
          {
            "slug": "security-scanning",
            "title": "One Command, Every Surface",
            "label": "Scanning",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/security-scanning",
            "content": null
          },
          {
            "slug": "security-testing",
            "title": "Scanners and a Real Pentest",
            "label": "Testing",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/security-testing",
            "content": null
          },
          {
            "slug": "responsible-disclosure",
            "title": "Invite the Good Hackers",
            "label": "Disclosure",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/responsible-disclosure",
            "content": null
          },
          {
            "slug": "security-audit",
            "title": "Check It, Then Get a Review",
            "label": "Audit",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/secure/security-audit",
            "content": null
          }
        ]
      },
      {
        "id": "protect",
        "title": "Handle user data responsibly and legally",
        "chapters": [
          {
            "slug": "owning-user-data",
            "title": "You Own What You Collect",
            "label": "Responsibility",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/protect/owning-user-data",
            "content": "---\ntakeaway: You own collected data\nshare: \"The moment real users arrive, their data is your responsibility, not just an asset. Collect only what you need, know exactly what you hold, and you carry far less risk.\"\nrequires: [running-app, database-chosen, ai-agent]\nproduces: [data-inventory]\nteaches: [liability, data-minimization, pii, data-inventory]\nuses: [database, ai-coding-agent, prompt]\n---\n{/* KEEP: lead-in = first real users mean their data is now something you are on the hook for, not just a feature you built. Sets up the Protect part. Ends by naming the payoff: treat collected data as a responsibility you manage, starting by knowing what you hold. */}\nYour app just got its first real users, and every signup writes something real into your database: a name, an email, maybe a card number. Until now that data was a feature you were building. The moment a stranger trusts you with theirs, it becomes something you are on the hook for. This chapter gets you to treat collected data as a responsibility you manage, and it starts by knowing exactly what you hold.\n\n{/* KEEP: concept = their data is a liability, not an asset. Every record is something to protect, keep accurate, and be ready to delete. A leak is their exposed address or reused password, not your inconvenience. Bold-first: liability. */}\n## Their data is your responsibility\n\nIt is tempting to think of user data as an asset, a pile of value you are accumulating. Flip that. The moment it is real people's data, it is a **liability**: something you now have to protect, keep accurate, and be ready to hand back or delete.\n\nThat changes who a mistake hurts. A leak is not your inconvenience, it is a real person's home address in the open or their reused password in an attacker's hands. You are holding it on their behalf, so their exposure is your responsibility.\n\n{/* KEEP: step = collect only what you actually need. Less data = less risk + less liability. Data minimization is the cheapest control: data you never stored cannot be stolen. Be strictest with PII. Rule of thumb: if you cannot name why, do not collect it. Bold-first: data minimization, PII. */}\n## Collect only what you need\n\nEvery field you collect is one more thing to secure, keep correct, and answer for if it leaks. So collect the least you can. This is **data minimization**, and it is the cheapest security control you have: data you never stored cannot be stolen.\n\nBe strictest with **personally identifiable information (PII)**, the data that points at a specific human, like their email, phone, or home address. Ask of each field whether the app truly needs it now, or whether you kept it just because it was easy.\n\n> **Rule of thumb:** If you cannot name why you store a field, do not collect it.\n\n```mermaid\n%% caption: Every field must earn its place or it never enters the database.\nflowchart TD\n  F([New field]) --> Q{Can you name why you need it?}\n  Q -->|Yes| K[Collect and protect it]\n  Q -->|No| D[Do not collect it]\n```\n\n{/* KEEP: step = know what you hold and why. The data inventory artifact: what we store, why, how sensitive. Ties back to the data model (modeling-your-data) by topic: the inventory adds the why and the risk. Show the fenced inventory. Bold-first: data inventory. */}\n## Know what you hold and why\n\nYou cannot protect what you have not written down. A **data inventory** is one plain list of every kind of data you store, why you keep it, and how sensitive it is. You already sketched the things your app stores when you modeled your data; the inventory adds the why and the risk.\n\nHave your agent produce it and keep it in your system. It looks like this:\n\n```\nData            Why we store it       Sensitivity\nemail           login and receipts    medium\npassword hash   login                 high\ncard last 4     show the saved card   medium\nIP address      blocking abuse        low, drop at 30 days\n```\n\nThat one page tells you where to spend your protection effort, and it is the first thing you reach for when something goes wrong.\n\n```mermaid\n%% caption: The sensitivity column tells you which records to protect first.\nflowchart LR\n  INV[(Data inventory)] --> H[\"High: password hash\"]\n  INV --> M[\"Medium: email, card last 4\"]\n  INV --> L[\"Low: IP address\"]\n  H --> FIRST[Protect these first]\n```\n\n{/* KEEP: closing = the same clean inventory pays twice. Forward-link (one clause, by topic) to observability/Operate: clean, well-kept data is what powers AI-driven decisions and debugging once the app is live and you are watching it run. Then the prompt + Do this now. */}\n## Clean data pays you back twice\n\nKeeping this data lean and labeled is not only about risk. The same clean, well-kept data is what your AI reads to make decisions and trace bugs once the app is live. That is the second payoff the Operate part builds on, when you are watching the app run. Kept clean now, it pays twice.\n\n```mermaid\n%% caption: One clean dataset pays off twice, as protection now and as fuel for AI later.\nflowchart LR\n  CD[(Clean labeled data)] --> RISK[Less risk now]\n  CD --> AI[AI reads it]\n  AI --> DEC[Better decisions]\n  AI --> BUG[Faster bug tracing]\n```\n\nThis prompt has your agent draft the inventory from your app:\n\n```prompt\nAct as a senior engineer auditing what my app\ncollects. Read the real schema and my data model,\nnot only what my spec claims, then list every kind\nof data stored as a data inventory: the field, why\nwe store it, and how sensitive it is (low, medium,\nhigh). Flag any field that is personally\nidentifiable, and call out anything we collect\nwithout a clear reason, or that no user story in my\nspec asks for, so I can drop it. Keep it one plain\ntable. Record each field I drop, and why, as a line\nin my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/protect/owning-user-data\n\nMy app and the data it collects:\n```\n\n**Do this now:** paste the prompt, let your agent draft your data inventory, and delete any field it cannot give a clear reason for."
          },
          {
            "slug": "privacy-and-consent",
            "title": "Asking Before You Collect",
            "label": "Privacy",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/privacy-and-consent",
            "content": null
          },
          {
            "slug": "third-party-data",
            "title": "The Services You Share With",
            "label": "Third Parties",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/third-party-data",
            "content": null
          },
          {
            "slug": "encrypting-data",
            "title": "Encrypting the Data You Hold",
            "label": "Encryption",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/encrypting-data",
            "content": null
          },
          {
            "slug": "de-identifying-data",
            "title": "Stripping Identity from Logs",
            "label": "De-identify",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/de-identifying-data",
            "content": null
          },
          {
            "slug": "data-retention-and-rights",
            "title": "Keeping, Deleting, Handing Back",
            "label": "Retention",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/data-retention-and-rights",
            "content": null
          },
          {
            "slug": "breach-response",
            "title": "Reporting a Data Leak",
            "label": "Breach",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/breach-response",
            "content": null
          },
          {
            "slug": "compliance-and-the-legal-line",
            "title": "Where the Legal Line Is",
            "label": "Compliance",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/protect/compliance-and-the-legal-line",
            "content": null
          }
        ]
      },
      {
        "id": "ship",
        "title": "Deploy to production on real infrastructure",
        "chapters": [
          {
            "slug": "deploying-to-production",
            "title": "Going to Production",
            "label": "Deployment",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/ship/deploying-to-production",
            "content": "---\ntakeaway: Ship to real infrastructure\nshare: \"Your app runs on your laptop and nobody else can reach it. Going to production means putting it on real infrastructure the world can use, rebuildable from files, not clicked together by hand.\"\nrequires: [running-app, stack-chosen, ai-agent]\nproduces: [manual-deploy-plan, host-account, deployed-url]\nteaches: [production]\nglosses: [domain]\nuses: [hosting, command, domain]\n---\n{/* KEEP: lead-in = your app works on your machine, no one else can open it. Production = the leap to a real server the world reaches, carried by ONE mindset: the whole setup is rebuildable from files, not clicked by hand. This chapter frames the whole Ship part. */}\n\nYour app works on your machine, and nobody else can open it. Production is the leap to a real server the world can reach. This chapter gets you there. It also hands you the one mindset that makes every later step in this part sane: the whole setup is rebuildable from files, never clicked together by hand.\n\n{/* KEEP: concept = production is not a place you configure by hand once; anything set by clicking a dashboard is lost the day the server dies. Real production is described in files you re-run to recreate the whole thing. Bold-first: production. */}\n\n## Production is rebuildable, not clicked\n\n**Production** is not a machine you configure by hand and hope never dies. Anything you set by clicking around in a dashboard is gone the day that server does, and you are rebuilding it from memory.\n\nReal production is described in files. You run those files and the whole setup comes back, identical, on a fresh machine. That single idea is what the rest of this part builds, so treat every by-hand click as a note you still have to turn into a file.\n\n{/* KEEP: pick where it runs; honest default = cheap own-the-metal, not the big-cloud maze. A small box on a provider like Hetzner costs a fraction of the hyperscaler equivalent and you don't pay a tax for 100 services you'll never use. Rule of thumb: avoid the AWS maze unless you have a reason; if you must, raw EC2. Link Hetzner. */}\n\n## Pick a host you can afford to keep\n\nThe honest default is cheap, own-the-metal hosting, not the big-cloud maze. A small server on a provider like [Hetzner](https://www.hetzner.com) costs a fraction of the same box on a hyperscaler. You also stop paying a tax for a hundred managed services you will never touch.\n\n> **Rule of thumb:** skip the AWS managed maze unless you have a specific reason to be in it. If you must be on AWS, a plain server (an EC2 box) beats wiring ten services together to run one app.\n\n```mermaid\n%% caption: Default to a cheap box; only a specific reason justifies the AWS maze.\nflowchart TD\n  Q{1. Specific reason for AWS?} -->|No| CHEAP[2. Cheap box like Hetzner]\n  Q -->|Yes| EC2[2. Plain EC2 server]\n  EC2 -.->|not this| MAZE[Managed service maze]\n```\n\n{/* KEEP: do it by hand ONCE so you see every piece (a server, a domain, the app running, a way in); automating something you've never done by hand hides the parts that break. Then never again: capture each step as files, a deploy becomes a command not an afternoon. Prompt has agent draft the deploy plan for their host. */}\n\n## Deploy by hand once, then never again\n\nThe first time, do it by hand. Stand up a server, point a **domain** (the web address people type) at it, turn on HTTPS, then get the app running and open it from another device. Doing it once shows you every moving part, and automating a thing you have never done by hand only hides where it breaks.\n\nThen you never do it by hand again. Every step you just took becomes a file in the chapters that follow, and from then on a deploy is one command, not a lost afternoon.\n\nThis prompt turns your first deploy into a written plan:\n\n```prompt\nAct as a senior engineer planning my first production\ndeploy. Read my spec, my non-functional targets, and my\n.env.example, so the plan covers every service and\nvariable the app actually needs. For my stack and chosen\nhost, lay out the smallest real path to live: the server,\nthe domain and TLS, how the app runs, how migrations run,\nand how I reach it. Keep it manual for now, and mark which\nstep becomes a file I automate later. Say plainly if my\ntargets rule this host out, then log the host choice and\nits reason in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/ship/deploying-to-production\n\nMy stack and host:\n```\n\n**Do this now:** paste the prompt, get your manual deploy plan, and stand the app up on a real host once, by hand."
          },
          {
            "slug": "choosing-a-host",
            "title": "Where to Run It",
            "label": "Hosting",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/choosing-a-host",
            "content": null
          },
          {
            "slug": "domains-dns-and-tls",
            "title": "Your Real Address and the Padlock",
            "label": "Domains",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/domains-dns-and-tls",
            "content": null
          },
          {
            "slug": "dev-staging-production",
            "title": "Dev, Staging, Production",
            "label": "Environments",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/dev-staging-production",
            "content": null
          },
          {
            "slug": "infrastructure-as-code",
            "title": "Infrastructure as Code",
            "label": "IaC",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/infrastructure-as-code",
            "content": null
          },
          {
            "slug": "production-data-and-backups",
            "title": "The One Thing You Can't Rebuild",
            "label": "Prod Data",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/production-data-and-backups",
            "content": null
          },
          {
            "slug": "containers-and-kubernetes",
            "title": "Package and Run Your App",
            "label": "Containers",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/containers-and-kubernetes",
            "content": null
          },
          {
            "slug": "secrets-in-production",
            "title": "Keys and Passwords, Live",
            "label": "Secrets",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/secrets-in-production",
            "content": null
          },
          {
            "slug": "scripts-for-every-operation",
            "title": "One Command per Operation",
            "label": "Scripts",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/scripts-for-every-operation",
            "content": null
          },
          {
            "slug": "automating-your-deployment",
            "title": "Automating the Deploy",
            "label": "CI/CD",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/automating-your-deployment",
            "content": null
          },
          {
            "slug": "safe-releases-and-rollbacks",
            "title": "Safe Rollouts and Rollbacks",
            "label": "Releases",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/safe-releases-and-rollbacks",
            "content": null
          },
          {
            "slug": "deploy-verification",
            "title": "Prove the Deploy Worked",
            "label": "Verification",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/ship/deploy-verification",
            "content": null
          }
        ]
      },
      {
        "id": "operate",
        "title": "Run and maintain it in production",
        "chapters": [
          {
            "slug": "logging",
            "title": "Leaving a Trail",
            "label": "Logging",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/operate/logging",
            "content": "---\ntakeaway: Leave a useful trail\nshare: 'When something breaks in your live app, clean structured logs are the difference between an answer in seconds and a guess. Learn what to log, what never to log, and how to make it searchable.'\nrequires: [deployed-url, running-app, ai-agent, project-folder]\nproduces: [logs]\nteaches: [logging, log-level, structured-log, observability, audit-trail]\nuses: [prompt, secret, api-key]\n---\n{/* KEEP: lead-in = app is SHIPPED and live (opens Operate); you cannot see inside it; scattered print statements are noise you cannot search when it counts; chapter gets logs you can read back later and actually trust. */}\n\nYour app is shipped and running, and right now you cannot see inside it. A user hits an error, a nightly job dies, a page crawls, and you have no idea why. Scattered `print` statements are not a trail, they are noise you cannot search when it counts. This chapter gets you logs you can read back later and actually trust.\n\n{/* KEEP: log meaningful events with context (which user/record/what failed); NEVER secrets/passwords/tokens/API keys/card numbers/full personal data; OWASP link for what-never-to-log. Watch out = whole request/response objects smuggle secrets, log named fields not the raw blob. Do NOT re-teach the event-ledger. */}\n\n## Log the events, never the secrets\n\nA log is the app narrating what it just did. Log the moments that matter: a request handled, an error caught, a payment taken. Give each one enough context to answer \"what happened\" later, which user, which record, what failed.\n\nThe harder discipline is what never goes in. Never write sensitive data to a log: passwords, access tokens, API keys, full card numbers, anyone's private information. Logs get copied, forwarded to other services, and read by people who should never see any of it. The [OWASP logging guidance](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) spells out the full list; the rule of thumb is log that a login happened and whose, never the password typed.\n\n> **Watch out:** the fastest way to leak secrets is logging a whole request or response object. Tokens and personal data ride along inside it. Log named fields, never the raw blob.\n\n```mermaid\n%% caption: Every field faces one check before it reaches the log.\nflowchart TD\n  F([Field to log]) --> Q{Secret?}\n  Q -->|event, userId, ok| KEEP[Write to log]\n  Q -->|password, token, card| RED[Redact first]\n```\n\n{/* KEEP: bold-first log level (debug/info/warn/error) as a filter; bold-first structured logging = emit each log as data (level + named fields) not a glued sentence, so it is searchable/countable. Artifact = before/after: bare print string vs structured JSON line with level+fields, no leaked data. */}\n\n## Levels and fields make logs searchable\n\nGive every line a **log level** so you can filter by how much it matters:\n\n- `debug`: detail you only want while building\n- `info`: a normal event worth recording\n- `warn`: something off but handled\n- `error`: something broke\n\nIn production you keep `info` and up, and stay quiet below it.\n\nThen give every line the same handful of fields, so any one of them can pull the whole story back out. A **correlation id** is the important one: a value generated when a request arrives and stamped on every line, error and trace that request produces. Carry the user id and the running version beside it and you can filter by any of the three.\n\n```\n09:02 info  checkout.started  user=u_41 corr=a1b2 ver=1.4.2\n09:02 error checkout.failed   user=u_41 corr=a1b2 ver=1.4.2\n```\n\nOne id, and everything that happened in that moment comes back together, here and in every other tool you point it at.\n\n```mermaid\n%% caption: A line's level decides whether production keeps or drops it.\nflowchart TD\n  L([Log line]) --> Q{Level}\n  Q -->|debug| DROP[Dropped in production]\n  Q -->|info, warn, error| KEEP[Kept in production]\n```\n\nThen use **structured logging**: emit each log as data, a level plus named fields, instead of gluing a sentence together. A sentence you can only skim by eye. Structured lines you can search, filter, and count across millions of them.\n\n```js\n# Before: a sentence you cannot search, leaks data\nprint(\"user \" + email + \" logged in with \" + pw)\n\n# After: structured, leveled, safe to ship\nlog.info({ event: \"auth.login\", userId: 4821, ok: true })\n# -> {\"level\":\"info\",\"event\":\"auth.login\",\n#     \"userId\":4821,\"ok\":true,\"ts\":\"2026-07-10T08:14Z\"}\n```\n\n{/* KEEP: the DETECT half the security part never covers. One class of event gets logged even when nothing is broken: the privileged and irreversible (logins and failed logins, role changes, exports, deletes, money moved). That **audit trail** is how you notice a break-in yourself instead of hearing it from a stranger. Two of them get wired to alerts (failed-login spikes, any admin action), cross-ref alerting BY TOPIC. Same redaction rule still applies: an id and an event, never the token. */}\n\n## Log who did the dangerous things\n\nOne class of event you log even when nothing is broken: the privileged and the irreversible. Who logged in and from where, who failed to, who changed a role, who exported or deleted data, who moved money. That **audit trail** is how you notice a break-in yourself, instead of hearing about it from a stranger weeks later.\n\nTwo of those deserve to reach you, through the alerting the rest of this part sets up: a spike in failed logins, and any admin action at all. The rule above still holds on every one of these lines, an id and an event name, never the token or the password that came with it.\n\n{/* KEEP: bold-first observability = ask any question of the running system, get an answer from what it emits; clean structured logs are the base every metric/alert/timeline in the rest of Operate sits on (cross-ref by topic, don't name later chapters). Ends with senior prompt (one structured logger, levels, redaction, stack-appropriate; ONE append slot) then Do this now. */}\n\n## Logs feed observability\n\nClean, structured logs are the raw material for **observability**: asking any question of your running system and getting an answer from what it already emits. Why is this slow? How often does this fail? What did this one user hit?\n\nRandom print strings answer none of that. Structured events you can search, count, and alert on, and that is the base every metric, alert, and timeline in the rest of this part sits on.\n\n```mermaid\n%% caption: One structured logger feeds search, counts, and alerts.\nflowchart LR\n  APP([Your app]) --> LOG[Structured logger]\n  LOG --> LEDGER[(Ledger)]\n  LEDGER --> SEARCH[Search]\n  LEDGER --> COUNT[Count]\n  LEDGER --> ALERT[Alert]\n```\n\nSet that foundation now, one structured logger your whole app writes through:\n\n```prompt\nAct as a senior engineer setting up logging for\nmy running app. Replace scattered print and\nconsole statements with one structured logger the\nwhole app calls through.\n\nRead my data inventory, my retention policy, and\nmy naming conventions first.\n\nRequirements:\n- Emit each log as JSON with a level (debug, info,\n  warn, error), a timestamp, an event name in my\n  naming style, and named fields.\n- Log meaningful events, caught errors, and slow\n  or failed operations, each with enough context\n  to trace what happened.\n- Keep an audit trail of the privileged and the\n  irreversible: logins and failed logins, role\n  changes, exports, deletions, money moved, each\n  with who did it and from where.\n- NEVER log passwords, tokens, API keys, card\n  numbers, or anything my data inventory marks\n  personal. Redact those fields before anything\n  is written.\n- Pick the standard structured logger for my\n  stack, give me the exact setup and commands,\n  and add \"all logging goes through the logger\"\n  to my rules file.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/operate/logging\n\nMy app and what I need to see:\n```\n\n**Do this now:** paste the prompt, replace your `print` statements with one structured logger, and write your next log line with a level and named fields, no secrets in it."
          },
          {
            "slug": "observability",
            "title": "Seeing Inside Your App",
            "label": "Observability",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/observability",
            "content": null
          },
          {
            "slug": "admin-dashboard",
            "title": "The Screen You Run It From",
            "label": "Admin Screen",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/admin-dashboard",
            "content": null
          },
          {
            "slug": "tracking-changes",
            "title": "From a Number Back to the Change",
            "label": "Traceability",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/tracking-changes",
            "content": null
          },
          {
            "slug": "closing-the-loop",
            "title": "Did the Change Actually Work",
            "label": "Verdicts",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/closing-the-loop",
            "content": null
          },
          {
            "slug": "monitoring-and-alerts",
            "title": "Monitoring and Getting Paged",
            "label": "Alerting",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/monitoring-and-alerts",
            "content": null
          },
          {
            "slug": "reliability-targets",
            "title": "Decide What Healthy Means",
            "label": "Targets",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/reliability-targets",
            "content": null
          },
          {
            "slug": "backups-and-disaster-recovery",
            "title": "Disaster Recovery",
            "label": "Backups",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/backups-and-disaster-recovery",
            "content": null
          },
          {
            "slug": "maintenance-and-incidents",
            "title": "Maintenance When Things Break",
            "label": "Incidents",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/maintenance-and-incidents",
            "content": null
          },
          {
            "slug": "watching-the-bill",
            "title": "Watching the Bill",
            "label": "Cost",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/watching-the-bill",
            "content": null
          },
          {
            "slug": "automation",
            "title": "Letting It Run Itself",
            "label": "Automation",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/operate/automation",
            "content": null
          }
        ]
      },
      {
        "id": "scale",
        "title": "Grow it to handle real traffic and data",
        "chapters": [
          {
            "slug": "bottlenecks",
            "title": "Finding the Limits",
            "label": "Bottlenecks",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/scale/bottlenecks",
            "content": "---\ntakeaway: Find the real bottleneck\nshare: \"Your app is live and growing, and something will buckle first under the load. It is almost never the part you would guess. This chapter gets you to find the one real bottleneck by measuring, so you fix what actually moves and ignore the rest.\"\nrequires: [running-app, deployed-url, ai-agent, logs, dashboards]\nproduces: [bottleneck-report]\nteaches: [bottleneck, throughput, profiler, slow-query-log]\nuses: [ai-coding-agent, prompt, database, trace, log, load-test]\n---\n{/* KEEP: lead-in = opens the Scale part. The app is live and healthy (shipped, monitored, operating); now it is growing and something buckles first under load, almost never the part you would guess. This chapter = find the one real limit before touching anything. */}\n\nYour app is live and healthy: shipped, monitored, running without you babysitting it. Now it is growing, more users and more data arriving at once, and something in it will buckle first. That part is almost never the one you would guess. This chapter gets you to find the one real limit before you change a single line.\n\n{/* KEEP: concept = a bottleneck is the single slowest part that sets the ceiling for the whole system, the pipe's narrowest point. A request touching ten parts is only as fast as its slowest one, so the system's speed is the slowest part, not the average. Bold-first **bottleneck**; gloss **throughput**. */}\n\n## A bottleneck caps the whole system\n\nA **bottleneck** is the single slowest part that caps everything around it, the narrowest point in the pipe. Water moves only as fast as the tightest section allows, no matter how wide the rest of the pipe is.\n\nYour app works the same way. A request that touches ten parts is only as fast as its slowest one. The system's real speed is set by that single part, not by the average of the parts. The same goes for its **throughput**, how much work it can handle at once.\n\n{/* KEEP: the calibration anchor for the WHOLE Scale part. One modest server plus an indexed database serves hundreds of requests a second, millions a day, more than most products ever see. So a few hundred or few thousand users is not a capacity problem, it is one slow query, and the later rungs (replicas, sharding, load balancers) are insurance bought at a measured size. */}\n\n## One ordinary server goes further than you think\n\nGet the scale straight before you touch any of this. One modest server with a well-indexed database routinely serves hundreds of requests a second, which is millions a day, far more traffic than most products ever see.\n\nSo if you have a few hundred or a few thousand users and something feels slow, you are almost certainly not out of capacity. You have one slow query, and the heavier moves later in this part are insurance you buy at a size you can measure, not imagine.\n\n{/* KEEP: never guess at what is slow. Slowness rarely lives where it feels like it does; under load the part that buckles is usually invisible from the outside (a query, not the code you stare at). Measure first: reproduce real load, watch where time goes. NAME how: the load-test tool from the testing part (k6) pointed at the slow path, or, on a live app, read the real traffic from the traces you already have and only synthesize load to push past today's users. Cross-ref by TOPIC to the page-speed chapter (same rule, now system-wide) and to the observability already set up. */}\n\n## Measure before you optimize\n\nThe rule that saves you the most wasted effort: never guess at what is slow. Slowness rarely lives where it feels like it does, so a day spent speeding up the wrong part moves nothing. You met this rule tuning page speed; at scale it governs the whole system, not one screen.\n\nThe part that buckles under load is usually invisible from the outside: a database query, not the code you stare at. So measure first: put the app under realistic load, many requests at once, not the single idle click you test by hand. That is the same load-test tool from the testing part, [k6](https://k6.io), pointed at the slow path instead of at your launch peak.\n\nOn a live app you often do not need to simulate anything. The real traffic is already hitting you, so read where the time goes from the traces and logs you already have from making the app observable. Only synthesize load when you need to push past what today's users produce.\n\n{/* KEEP: find the slowest single part with real data: a profiler breaks one request into timed spans; simple timing; the database's slow query log (its record of queries that ran too long). The artifact = a request timing breakdown where ONE span dominates (db list = 814 of 842ms), the rest is noise. Bold-first **profiler**, **slow query log**. */}\n\n## Find the slowest part\n\nThree tools turn \"it feels slow\" into a number. A **profiler** breaks a single request into timed spans and shows how long each part took. Simple timing does the same by hand. The **slow query log** is the database's own record of every query that ran too long, and it is where scale problems hide most often.\n\nRun one and you get something like this:\n\n```\nGET /orders            842 ms total\n  auth check             3 ms\n  render page           11 ms\n  db: list all orders  814 ms   <- bottleneck\n  db: look up user       9 ms\n```\n\nOne span dominates. The 814 ms query is the bottleneck; everything else is rounding error. You are not guessing anymore, you can see it.\n\n{/* KEEP: fix ONLY the top one; fixing anything else moves the total by nothing (make everything but the 814ms query twice as fast, save a handful of ms). Rule-of-thumb callout: speeding up anything but the bottleneck barely changes the total. Then re-measure: the bottleneck moves to a new part; repeat, or stop when fast enough. Bridge opens the rest of the part. Prompt = whole loop, senior voice, one append slot. */}\n\n## Fix the one that matters\n\nFix that one query and nothing else. It is tempting to tidy the render step or the auth check while you are in there. But do the math: make everything except the 814 ms query twice as fast, and you save a handful of milliseconds out of eight hundred.\n\n> **Rule of thumb:** speeding up anything but the bottleneck barely changes the total. Finding it beats optimizing on instinct every time.\n\nThen measure again. The bottleneck does not vanish, it moves: fix the query and the next-slowest part becomes the new ceiling. Repeat until the app is fast enough for the load you have, then stop.\n\n```mermaid\n%% caption: Find the slowest part, fix only it, measure again; the bottleneck just moves.\nflowchart LR\n  M[Measure under load] --> F[Find slowest part]\n  F --> X[Fix only that one]\n  X --> R[Measure again]\n  R -->|bottleneck moved| M\n  R -->|fast enough| S([Stop])\n```\n\nThe rest of this part is how you fix each kind of bottleneck you find; this prompt finds the first one without letting your agent guess:\n\n```prompt\nAct as a senior engineer hunting a performance\nbottleneck. Do not guess and do not optimize on\ninstinct. Work from measurement only.\n\nRead my performance targets and my service levels\nfirst, and measure with the instrumentation, logs,\nand dashboards I already have before adding any\nnew tooling.\n\n1. Reproduce the slowness under realistic load,\n   not a single idle request. State how you load\n   it and what you measured.\n2. Profile it: break the slow path into timed\n   parts (request spans, function timing, the\n   database slow query log). Show where the time\n   actually goes.\n3. Rank the parts by share of total time. Name\n   the single slowest one. That is the bottleneck.\n4. Fix only that one. Explain the change and why\n   it attacks the real cause, not a symptom.\n5. Measure again and show before and after. Say\n   what the new slowest part is, and whether it\n   still misses my targets or is fast enough.\n\nReport numbers, not adjectives. If you cannot\nmeasure a step, say so instead of guessing. Record\nthe fix and its numbers in my decision log.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/scale/bottlenecks\n\nWhat feels slow and when:\n```\n\n**Do this now:** pick the one page or action your users call slowest, paste the prompt, and let your agent measure where the time actually goes before you change a single line."
          },
          {
            "slug": "accessibility-and-performance",
            "title": "Speed and Accessibility",
            "label": "Performance",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/accessibility-and-performance",
            "content": null
          },
          {
            "slug": "caching-and-the-database",
            "title": "Easing the Database",
            "label": "Caching",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/caching-and-the-database",
            "content": null
          },
          {
            "slug": "edge-and-cdn",
            "title": "Serve Static from the Edge",
            "label": "Edge & CDN",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/edge-and-cdn",
            "content": null
          },
          {
            "slug": "scaling-out",
            "title": "Adding Capacity",
            "label": "Horizontal Scaling",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/scaling-out",
            "content": null
          },
          {
            "slug": "database-scaling",
            "title": "Scaling the Database",
            "label": "DB Scaling",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/database-scaling",
            "content": null
          },
          {
            "slug": "capacity-planning",
            "title": "Staying Ahead of Growth",
            "label": "Capacity",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/capacity-planning",
            "content": null
          },
          {
            "slug": "rate-limiting",
            "title": "Cap the Load You Accept",
            "label": "Rate Limits",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/rate-limiting",
            "content": null
          },
          {
            "slug": "the-improvement-loop",
            "title": "The Improvement Loop",
            "label": "Optimization",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/the-improvement-loop",
            "content": null
          },
          {
            "slug": "running-experiments",
            "title": "Gate First, Then Test",
            "label": "Experiments",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/running-experiments",
            "content": null
          },
          {
            "slug": "when-to-call-a-pro",
            "title": "When to Call a Pro",
            "label": "Expertise",
            "status": "published",
            "access": "paid",
            "url": "https://zalt.me/guides/vibe-coding/scale/when-to-call-a-pro",
            "content": null
          },
          {
            "slug": "beyond-the-software",
            "title": "Beyond the Software",
            "label": "What Next",
            "status": "published",
            "access": "free",
            "url": "https://zalt.me/guides/vibe-coding/scale/beyond-the-software",
            "content": "---\ntakeaway: The software was the first stage, not the finish\nshare: You have shipped software that works, scales, and stays up. That is one stage finished, not the job. A product is not a business, a business is not a brand, and the next stretch is the one nobody warned you about.\nrequires: [deployed-url, running-app, admin-dashboard]\nproduces: []\nteaches: [product-market-fit, retention, acquisition]\nglosses: []\nuses: [ai-coding-agent, admin-dashboard]\n---\n\n{/* KEEP: this is the LAST page of the book. Its job is not to teach a skill, it is to reframe what the reader just finished and open the door to what comes next, including a future book. Tone: congratulatory but honest, no hype. Do NOT turn this into a marketing or business lesson, it stays high level on purpose. The reader has earned a straight answer about where they actually stand. */}\n\nYou started with a laptop and no idea how software gets built. You now have an app that is live, tested, secured, watched, and able to grow. Almost nobody who starts gets here. It is worth stopping to notice that.\n\nAnd here is the honest part: you have finished the first stage, not the job.\n\n{/* KEEP: the three-step reframe the author asked for: product != business != brand, possibly a company after that. Keep it as a short escalation, one line each, no lecturing. This is the page's core idea. */}\n\n## A product is not a business\n\nThey feel like the same thing when you are building, and they are not.\n\n- **A product** is software that solves a problem. That is what you just built.\n- **A business** is a repeatable way to reach the people with that problem and get paid. Pricing, distribution, margins, support.\n- **A brand** is what those people say about you when you are not in the room. It is why they pick you over the cheaper one.\n- **A company** is the machine that runs all of it without you personally touching every part.\n\nEach one is a different job with different skills, and each is roughly as large as the one you just finished. Nobody does all four at once.\n\n{/* KEEP: the data payoff, and the reason it lands HERE and not earlier. They have shipped, so users have generated real data, and the admin dashboard from Harden means they can already see it. Name the two metrics that matter first (acquisition and retention) and say plainly which one decides whether there is a business at all. Keep it to the level of \"here is what to look at\", never a marketing lesson. */}\n\n## You are sitting on data nobody else has\n\nEverything you built has been quietly collecting the one asset a competitor cannot copy: what real people actually do in your product. Your admin screen and your logs already hold it.\n\nTwo numbers matter before any others:\n\n- **Acquisition:** how people find you and what it costs to reach one more.\n- **Retention:** how many of them are still here next month.\n\nRetention is the one that decides whether you have a business. Acquisition without retention is a bucket with a hole in it, and it is the cheapest possible thing to measure now that your app is live. Everything after this, pricing, positioning, which feature to build next, is easier to decide from that number than from an opinion.\n\n> **Rule of thumb:** if people are not coming back, no amount of marketing fixes it. Fix the coming back first.\n\n{/* KEEP: the door. Say plainly that the next stretch (marketing, sales, partnerships, operations, hiring) is its own body of work and its own book, without promising a date. Then close the whole book on the reader, not on the author. Do NOT oversell the next book. */}\n\n## The next stretch is its own book\n\nMarketing, sales, partnerships, operations, hiring, the legal and financial scaffolding of a real company: that is a body of knowledge as large as everything in these pages, and it is where most technically good products quietly die.\n\nIt is not covered here, because pretending to cover it in a closing chapter would be worse than leaving it out. It is what I intend to write next.\n\nWhat you should take from this page is smaller and more useful than a reading list: **the hard part is no longer the software.** You proved you can build and ship it, and you can do that again whenever you want. What decides whether this becomes something is what you do with the people who show up.\n\nYour agent can pull the number for you, from the data you already have:\n\n```prompt\nAct as a senior engineer answering one question from\nmy own data. Using my database and my admin screen,\ntell me how many people used the product last month,\nhow many of those came back this month, and what that\npercentage is. Show me the query you ran so I can run\nit again. Do not build a dashboard, do not add\ntracking, and do not estimate: if the data cannot\nanswer it honestly, say exactly what is missing and\nthe smallest thing to record from now on. Then add\nthe number and the date to my decision log, so next\nmonth has something to compare against.\n\n\nIf you need the full reasoning behind this step, read\nhttps://zalt.me/guides/vibe-coding/scale/beyond-the-software\n\nMy app, and where its user activity is stored:\n```\n\n**Do this now:** paste the prompt and get your retention number. That single figure is the first honest read on whether you have a business, and it is the one to watch from here."
          }
        ]
      }
    ]
  },
  {
    "id": "building-ai-agents",
    "title": "Designing Reliable\nAgentic AI Systems",
    "subtitle": "Architecting, orchestrating, and shipping autonomous agents that do real work, not demos.",
    "tagline": "Build scalable AI agents from scratch",
    "description": "Architecting, orchestrating, and shipping autonomous agents that do real work, not demos.",
    "author": "Mahmoud Zalt",
    "authorRole": "Principal AI Architect",
    "status": "coming-soon",
    "url": null,
    "premium": null,
    "coverImage": "/images-optimized/blog/auto/building-ai-agents-cover-medium.webp",
    "edition": "2027 Edition",
    "version": "v0.0",
    "parts": []
  }
]
