# Groundwork: full content > Know enough to prompt well. All pages concatenated in reading order. --- # Groundwork **Know enough to prompt well.** Coding agents can now write most of your code, but they can't make your decisions for you. Groundwork teaches the concepts, vocabulary and trade-offs behind the core parts of modern software, so you can direct an agent with confidence and review what it gives back. ## How the docs are organized | Section | What's inside | |---|---| | **[Start Here](/docs/start-here/how-to-read-these-docs.md)** | How to use these docs, how coding agents work, how to write a good prompt, the software lifecycle, and how to use these docs with your agent | | **[Foundations](/docs/foundations/how-software-fits-together.md)** | The big picture, the terminal and git, networking basics | | **[Frontend](/docs/frontend/building-a-ui.md)** | Building UIs, state and data fetching | | **[Backend](/docs/backend/building-an-api.md)** | APIs, authentication and authorization | | **[Data](/docs/data/databases.md)** | Databases, schemas and migrations, backups and recovery | | **[Shipping](/docs/shipping/deployment.md)** | Deployment, environments and secrets, observability | | **[Security](/docs/security/security-basics.md)** | The security basics every app needs | | **[Quality](/docs/quality/testing.md)** | Testing, and verifying agent output | | **[Stacks](/docs/stacks/choosing-a-stack.md)** | Choosing a stack, plus proven stack recipes | | **[AI & Agents](/docs/ai-agents/how-llms-work.md)** | How LLMs work, context, prompting patterns, agents and MCP, reviewing and securing agent work, building with LLM APIs, and cost | | **[Appendix](/docs/appendix/glossary.md)** | Glossary and the full prompt library | ## Suggested path New to building full apps? Read in this order: 1. [Working with coding agents](/docs/start-here/working-with-coding-agents.md) 2. [Anatomy of a good prompt](/docs/start-here/anatomy-of-a-good-prompt.md) 3. [How software fits together](/docs/foundations/how-software-fits-together.md) 4. [Building a UI](/docs/frontend/building-a-ui.md) → [Building an API](/docs/backend/building-an-api.md) → [Databases](/docs/data/databases.md) 5. [Deployment](/docs/shipping/deployment.md) → [Security basics](/docs/security/security-basics.md) Already comfortable building, and want to get more out of agents? Read the **AI & Agents** section in this order: 1. [How LLMs work, for builders](/docs/ai-agents/how-llms-work.md) 2. [Context engineering](/docs/ai-agents/context-engineering.md) 3. [Prompting patterns that work](/docs/ai-agents/prompting-patterns.md) 4. [Agents, tools and MCP](/docs/ai-agents/agents-tools-and-mcp.md) 5. [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md) 6. [Security of agentic workflows](/docs/ai-agents/agent-security.md) Want the whole picture of how a change moves from idea to production? Read [The software lifecycle with agents](/docs/start-here/software-lifecycle-with-agents.md). New to the terms (skills, connectors, harness, hooks)? Read [AI vocabulary and when to use what](/docs/start-here/ai-vocabulary-and-when-to-use-what.md). Want your agent to use these docs too? Read [Using Groundwork with your agent](/docs/start-here/using-groundwork-with-your-agent.md). If you already know your way around, jump straight to any topic. Every page stands on its own. ## On every page Sample prompts have a **Copy** button, quizzes check your understanding, checklists remember what you tick, and **Copy for LLM** gives you a page as Markdown for your agent. Agents can also read `/docs.json`, a per-phase or per-section slice such as `/llms/phase-ship.txt`, and the starter file `/groundwork-agents.md`. Your progress stays in your browser: see `/progress`. --- # How to read these docs Groundwork covers **the decisions and concepts** in software development. Syntax and line-by-line implementation are left to the agent. ## What we cover vs. what we skip | We cover | We skip | |---|---| | What a thing is and why it exists | Exhaustive API references | | The vocabulary you need in prompts | Syntax memorization | | Trade-offs and sensible defaults | Every possible alternative | | How to spot bad agent output | Step-by-step tutorials | | Sample prompts | Framework-specific deep dives (we link to those) | ## How every page is laid out 1. **Summary:** what the topic is, in one line. 2. **You'll be able to:** what you'll get out of the page. 3. **The mental model:** the core idea. 4. **Key concepts:** vocabulary. 5. **Decisions you make:** the table that matters most. These are the choices you should put in your prompt rather than leave to the model. 6. **What good output looks like / Red flags:** how to review the agent's work. 7. **Worked example:** one realistic task, including the wrong turn an agent might take and how review catches it. 8. **Sample prompts:** copy, adapt, ship. 9. **Check your understanding:** a few quick questions. 10. **Checklist / Go deeper.** > **Tip:** Short on time? Read the **Decisions** table and the **Sample prompts**. That's 80% of the value. ## What you can do on a page - **Search:** press `/` (or `Ctrl+K` / `⌘K`) to search every page, including sections within pages. - **Copy prompts:** every sample prompt has a **Copy** button. Fill in the `` and paste. - **Compare weak and strong prompts:** where a page shows both, you can copy either one. - **Build a prompt:** the prompt builder turns the parts of a good prompt into a form. Empty parts are left out. - **Find your default:** under some Decisions tables, a short questionnaire points you to the row that fits your situation and copies your choices as text for a prompt. - **Check yourself:** quizzes give instant feedback and an explanation. - **Tick checklists and mark pages as read:** your progress shows in the sidebar and on the `/progress` page. - **Copy a page for your agent:** **Copy for LLM** gives you the page as clean Markdown, ready to paste. > **Note:** Your progress, quiz results and drafts are saved in your browser only. Groundwork has no accounts and sends nothing to a server, so they don't follow you to another device. ## Use the docs with your agent These docs are written for agents too. Three ways to hand them over: - `/llms.txt` is an index of every page with its summary. - `/llms-full.txt` is every page in one file. - Add `.md` to any page address (for example `/docs/data/databases.md`) for that page as raw Markdown. For a single page, **Copy for LLM** is the quickest route. Then try one of these: ```text Here is a page from Groundwork: . Read its "Decisions you make" table. Then look at this project and tell me, for each decision, what the project currently does, whether it matches the table's default, and whether any "choose otherwise when" condition applies. Don't change any code. ``` ```text Using the page below as your source, draft the "Commands", "Layout" and "Rules" sections of an AGENTS.md for this repo. Include only rules you can verify from the code, and mark anything you are unsure about as "unverified". ``` ```text Quiz me on the page below: ask 5 questions one at a time, wait for my answer, say whether I'm right, and explain. Focus on the decisions and red flags, not trivia. ``` ## A 15-minute reading session Say you are about to add a database to a project. Open **Databases** and read the lede and **You'll be able to**. Skim **Key concepts** for words you don't know. Spend your time on the **Decisions** table, and use the questionnaire under it to find your row. Open **Sample prompts**, use the strong one as your starting point, and copy it. Tick off the **Checklist** as you go, take the quiz when you're done, and mark the page as read. ## Check your understanding ```quiz Q: You are short on time. Which parts of a page give you most of the value? - [ ] The mental model and key concepts - [x] The Decisions table and the sample prompts - [ ] Go deeper > Why: The Decisions table holds the choices you should put in your prompt, and the sample prompts show how to say them. --- Q: How should you treat the specific tools named on a page? - [ ] As the only correct choice - [x] As examples. The concepts are the point, and the `last_reviewed` date tells you how fresh the page is > Why: Tools change often. The concepts, trade-offs and defaults last much longer. ``` ## A note on staleness Tools change monthly, while concepts change over decades. Pages lean on concepts and name specific tools only as examples. Every page shows a `last_reviewed` date. --- # Working with coding agents An agent is an LLM in a loop with tools. Once you understand that loop, you understand both its strengths and its failure modes. ## You'll be able to - Explain the difference between a model, an agent, a harness, a skill, and an MCP server - Know what an agent can and can't "see" at any moment - Structure work so an agent succeeds on the first or second try ## The mental model ``` you ──prompt──▶ ┌──────────── harness ────────────┐ │ context window (what it sees) │ │ ▲ │ │ │ tool results tool calls │ │ │ ▼ │ │ files · shell · web · MCP │ └─────────────────────────────────┘ ``` The model reads its context, decides on an action (edit a file, run a command, search), and the harness executes that action and feeds the result back in. This repeats until the model decides the task is done. **The model knows only what's in its context window**, plus whatever it learned in training, and that training may be out of date. ## Key concepts - **LLM (model):** The engine that predicts text. Examples: Claude, GPT, Gemini, and open models like Llama or Qwen. - **Context window:** Everything the model can see right now, including your prompt, files it has read, and tool outputs. It's finite. When it fills up, the harness compacts or drops older material, and the agent can lose track of earlier details. - **Agent:** A model plus a loop plus tools. It acts, observes the result, and acts again. - **Harness:** The program that runs the agent loop and provides its tools. Examples: Claude Code, Cursor, GitHub Copilot agent mode, OpenAI Codex, Aider, Cline. - **Tools:** Actions the agent can take, such as reading or editing files, running shell commands, searching the web, or browsing. - **MCP (Model Context Protocol):** An open standard for plugging external tools and data into agents (GitHub, databases, Figma, Sentry…). Think of it as USB-C for agent tools. - **Skills / rules files:** Reusable instructions the agent loads when relevant, such as `CLAUDE.md`, `AGENTS.md`, `.cursor/rules`, or skill folders. This is where your project's conventions live, so you don't repeat them in every prompt. - **Subagents:** Child agents spawned for a sub-task, each with a fresh context. They're useful for parallel or exploratory work. - **Hallucination:** Output that sounds confident but is wrong. Invented APIs, package names and config options are the classics. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | Task size | One feature or one bug per session | You're scaffolding something brand new | | Plan first? | Yes, for anything touching >3 files: ask for a plan, review it, then build | It's a one-line fix | | Project rules file | Always keep one (`AGENTS.md`/`CLAUDE.md`) with stack, commands, conventions | Never skip it | | Version control | Commit before every agent session, so a bad run is easy to throw away | Never skip it | | Verification | The agent runs tests, lint and type-check before it says "done" | Prototype you'll throw away | ## What good output looks like - The agent reads relevant files before editing them - It runs the build and tests, and reports the results - It asks you about ambiguity instead of guessing on important choices - Its diffs are small and focused, and match the existing code style ## Red flags - **Invented packages or APIs** → check that the package actually exists on npm or PyPI before installing it. Malicious packages are sometimes published under names models tend to hallucinate ("slopsquatting"). - **"Done!" without having run anything** → ask it to run the tests and show you the output. - **A sprawling diff for a small ask** → reject it and re-prompt with a narrower scope. - **Disabling tests or type checks to get green** → reject it immediately. - **Hardcoded secrets** → see [Environments & secrets](/docs/shipping/environments-and-secrets.md). - **Editing a file it never read** → ask which files it read first. Edits made from guesses tend to duplicate or contradict code that already exists. - **A new helper that duplicates an existing one** → search the repo for similar names before accepting new utility files. - **Old-version patterns** (the wrong major version of a framework or library) → the model's training may be out of date. Name the versions in your rules file and check the diff against the docs for the version you use. ## Worked example **Task:** Add a "cancel booking" feature to an app you did not write. You prompt: *"Add a cancel booking button and endpoint."* The agent immediately starts writing, creates `lib/booking-utils.ts` with a new `cancelBooking` helper, adds an endpoint and a button, and says it is done. **What a good result contains:** the agent first reads how bookings are already handled, proposes a plan naming the files it will change, reuses what exists, and ends by running the tests and showing the output. **The wrong turn:** the repository already had `lib/bookings.ts` with a cancellation helper that also sends a confirmation email. The agent never looked, so the new helper cancels without sending the email, and now two helpers do almost the same thing. **How review catches it:** ask *which existing files did you read before writing this?* The answer is none. Then look at the file list: a brand-new utility file in a repo that already has a `bookings` module is a red flag. Re-run the task with the orient-then-plan prompt below, and have it show its plan before it writes any code. ## Sample prompts ### Set up a project rules file ```text Read this repository and create an AGENTS.md at the root. Include: - Stack and versions (from package.json / lockfiles) - How to install, run dev, run tests, lint, type-check, build - Folder structure and what lives where - Coding conventions you can infer (naming, file layout, state management, styling) - Things an agent should never do in this repo (e.g. edit generated files, commit .env) Keep it under 150 lines. Don't invent anything you can't verify from the code. ``` ### Plan-then-build ```text I want to add . Before writing any code: 1. Read the relevant parts of the codebase. 2. Propose a plan: files to change, new files, data model changes, risks. 3. List any decisions you need from me. Stop and wait for my approval before implementing. ``` *Why it works:* It separates thinking from doing, so you catch a wrong approach before it turns into 400 lines of code. ### Orient, then plan ```text I want to add . Don't write code yet. 1. Search the repo for how is already handled and list the files and helpers you found, with a one-line summary of each. 2. Say which of them you will reuse and which you will change. 3. Propose a plan: files to change, new files (and why none of the existing ones fit), risks. Wait for my approval. ``` *Why it works:* It forces the search that prevents duplicated code, and "why none of the existing ones fit" makes new files a justified exception. ### Review before I commit ```text Review the uncommitted changes (git diff) as a skeptical reviewer. List every file changed and whether it relates to the task: . Flag unrelated changes, new dependencies, deleted or weakened tests, and anything that looks hardcoded. Don't change any code. ``` *Why it works:* It catches scope creep and the "make the tests green" shortcuts that agents sometimes take. See [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md) for more. ### Explain your last change ```text Explain the change you just made as if to a teammate reviewing it: what problem it solves, why you chose this approach over the alternatives, what you assumed, and what you did not verify. If any part is a guess, say so. ``` *Why it works:* Explaining forces the agent to surface assumptions. Check the explanation against the diff rather than taking it as proof. ### Fix a failing test the right way ```text The test is failing. Find the root cause in the code under test, not in the test. Don't change the test's expectations or skip it unless you can show the expectation is wrong, and explain why. Show the failing output before and the passing output after. ``` *Why it works:* It rules out the shortcut of editing the test to match the bug. ## Check your understanding ```quiz Q: What can the model use when it generates an answer? - [ ] Your whole repository, automatically - [x] Only what is in its context window, plus what it learned in training - [ ] Everything you have ever told it > Why: The harness decides what goes into the context window. Anything the agent hasn't read isn't available to it, and what it learned in training may be out of date. --- Q: Why commit before starting an agent session? - [ ] The agent can't run without a clean commit - [x] A bad run becomes easy to throw away - [ ] It makes the agent faster > Why: Version control is your undo button. With a clean starting point you can discard a messy session with one command. --- Q: The agent says "Done!" What should you do next? - [ ] Merge it - [x] Ask it to run the tests, lint and type check, and show you the output, then read the diff - [ ] Ask it to say it is sure > Why: Confidence isn't evidence. Output from commands you can check is. ``` ## Checklist - [ ] A rules file exists and is up to date - [ ] Work is committed before the session starts - [ ] Task is scoped to one feature or fix - [ ] Agent verified its own work (tests, types, build) - [ ] You read the diff ## Go deeper - [Model Context Protocol](https://modelcontextprotocol.io) - [AGENTS.md](https://agents.md) - [Claude Code docs](https://docs.claude.com/en/docs/claude-code/overview) - Go further in the AI & Agents section: [How LLMs work](/docs/ai-agents/how-llms-work.md), [Context engineering](/docs/ai-agents/context-engineering.md), [Agents, tools and MCP](/docs/ai-agents/agents-tools-and-mcp.md), [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md) and [Security of agentic workflows](/docs/ai-agents/agent-security.md) --- # Anatomy of a good prompt A good prompt is a small spec: it says what to build, inside which constraints, and how to know it's done. ## You'll be able to - Turn a vague idea into a spec an agent can execute - Know which details matter and which to leave to the agent ## The mental model Imagine handing the task to a capable contractor who has never seen your project and can't read your mind. Whatever you don't specify, they'll fill in with the most common choice in their training data, which may not be what you want. ## The six parts | Part | Question it answers | Example | |---|---|---| | **Goal** | What and why? | "Users can reset their password by email." | | **Context** | Where does this live? | "Next.js 15 App Router, Drizzle + Postgres, auth via Better Auth." | | **Interfaces** | What are the inputs, outputs and contracts? | "POST /api/reset with `{ email }` → always 200." | | **Constraints** | What rules must it follow? | "Tokens expire in 30 min, single-use, hashed at rest." | | **Non-goals** | What should it not touch? | "Don't change the login page or add new deps." | | **Verification** | How do we know it works? | "Add tests for expired, reused, and valid tokens; run them." | ### Try it: build a prompt Fill in the parts below, or load an example, and copy the result. Parts you leave empty are left out. ```prompt-builder title: Build a strong prompt field: goal | Goal: what should it do, and why? | Users can reset their password by email field: context | Context: stack, versions, relevant files | Next.js 15 (App Router), TypeScript, Drizzle + Postgres field: interfaces | Interfaces: inputs, outputs, routes, data shapes | POST /api/auth/forgot with { email }, always returns 200 | multiline field: constraints | Constraints: security, performance, conventions | Tokens expire in 30 minutes and can be used once | multiline field: nongoals | Non-goals: what not to touch or add | Don't change the login page; no new dependencies field: verification | Verification: tests to write, commands that must pass | Tests for valid, expired and reused tokens; run tests and type-check | multiline option: plan | Ask the agent to plan first | Plan first and wait for approval before implementing. | checked preset: Password reset goal: Add a password reset flow. context: Next.js 15 (App Router), TypeScript, Drizzle ORM + Postgres, Resend for email. interfaces: - /forgot-password page: email field → POST /api/auth/forgot\n- /reset-password?token=… page: new password + confirm → POST /api/auth/reset constraints: - Forgot endpoint always returns 200 (don't reveal whether an email exists)\n- Token: 32+ random bytes, store only a SHA-256 hash, expires in 30 min, single use\n- Rate limit forgot endpoint to 5 requests/hour per IP and per email\n- Hash passwords with the existing helper in lib/auth/password.ts nongoals: Don't modify login/signup. No new dependencies. verification: Add a migration for the tokens table. Write tests for valid, expired, reused, and unknown-email cases. Run tests and type-check and show me the output. preset: CSV export goal: Add GET /api/bookings/export that downloads the current user's bookings as CSV. context: Next.js (App Router), TypeScript, Postgres via Drizzle. interfaces: Columns, in order: date (ISO), customer name, service, price in dollars. constraints: - Use standard CSV quoting (quote fields containing commas, quotes or newlines; double inner quotes)\n- Header row first\n- Only the signed-in user's rows\n- Stream the response so large exports don't load everything into memory nongoals: No UI changes, no new dependencies. verification: Add tests for a comma, a quote, a newline, an accented name and an empty field. Run lint, typecheck and tests and show me the output. template: Goal: {goal} Context: {context} Interfaces: {interfaces} Constraints: {constraints} Non-goals: {nongoals} Verification: {verification} {plan} ``` ## Key concepts - **Specificity where it matters:** Pin down things that are expensive to change later (data models, API contracts, security rules). Leave cosmetic details loose. - **Examples beat adjectives:** "Like Stripe's dashboard tables" says more than "clean and modern." - **Iterate small:** Three focused prompts beat one giant one. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | How much detail | Pin down what is expensive to change (data models, API contracts, security rules); leave cosmetic details loose | A throwaway prototype: a sentence or two is enough | | One prompt or several | Several small prompts, each ending with a check | A tiny, well-understood change | | Plan first | Yes, for anything touching more than a file or two | A one-line fix | | Examples or adjectives | Show an example or point to a reference ("match `lib/bookings.ts`") | The style is already obvious from nearby code | | Who settles ambiguous choices | You do, in the prompt | You're exploring: ask the agent to list its assumptions first | | Verification | Name the command or test that proves it works | An exploratory spike you will throw away | ## What good output looks like - The agent restates the task and the boundaries you set, or asks about a real gap, before it builds - The plan matches your constraints and names the files it will touch - The diff stays inside the non-goals you listed - Tests and checks you asked for exist, and the agent shows their output - Anything it assumed is stated, not buried ## Red flags in your own prompts - Adjectives without criteria ("make it secure," "make it fast") - No stack mentioned, so the agent picks one for you - No verification step, so "done" means "it compiled, maybe" - **Common agent mistakes when the prompt is thin:** it picks a stack you didn't want, adds a dependency you didn't ask for, changes unrelated files, or reports "done" without running anything. Each one maps to a missing part: context, constraints, non-goals, verification. ## Worked example **Task:** "Make the bookings page faster." You send exactly that sentence. The agent adds caching to the data layer, memoizes several components and reports that the page is now optimized. **What a good result contains:** a measurement of the page before the change, the one or two changes that account for most of the cost, and a measurement after with the same method, plus a check that behavior did not change. **The wrong turn:** nothing was measured, so the agent optimized what looked slow. The new cache serves out-of-date bookings for a minute after someone cancels, which is a behavior change nobody asked for, and the page was slow because of one query, which was never touched. **How review catches it:** ask what was measured before and after. There is no number, so the claim is unproven. Then rewrite the prompt using the six parts: a Goal with a measurable target, the Context (stack and the slow page), a Constraint that behavior must not change, a Non-goal against adding caching layers, and Verification that runs the same measurement before and after and reruns the booking tests. The second attempt starts by measuring. ## Sample prompts ### Weak vs strong ```compare ## Weak Add password reset. ## Why it fails The agent has to guess the flow, token storage, expiry, email provider and UI. Some of those guesses will be wrong, and some will be insecure. ## Strong Goal: Add a password reset flow. Context: Next.js 15 (App Router), TypeScript, Drizzle ORM + Postgres, Resend for email. Interfaces: - /forgot-password page: email field → POST /api/auth/forgot - /reset-password?token=… page: new password + confirm → POST /api/auth/reset Constraints: - Forgot endpoint always returns 200 (don't reveal whether an email exists) - Token: 32+ random bytes, store only a SHA-256 hash, expires in 30 min, single use - Rate limit forgot endpoint to 5 requests/hour per IP and per email - Hash passwords with the existing helper in lib/auth/password.ts Non-goals: Don't modify login/signup. No new dependencies. Verification: Add a migration for the tokens table. Write tests for valid, expired, reused, and unknown-email cases. Run tests and type-check and show me the output. ## Why it works Every expensive decision is made up front, the security properties are spelled out, and the agent knows how to prove it's finished. ## What changed - **Context** names the stack and the email provider, so the agent doesn't pick for you - **Interfaces** define the pages and endpoints - **Constraints** spell out the security rules (token size, hashing, expiry, single use, rate limits) - **Non-goals** keep it away from login and signup and from new dependencies - **Verification** says exactly which tests to write and to show the output ``` ### Critique my prompt before I send it ```text Here is a prompt I plan to give a coding agent: . Don't do the task. Instead, list: (1) ambiguities, (2) decisions the agent would have to guess, (3) missing constraints or non-goals, and (4) ways it could technically succeed while being wrong. Then suggest the smallest edits that fix them. ``` *Why it works:* It turns a fuzzy worry into a short list of gaps you can fix in a minute, before any code exists. ### Restate the task before starting ```text Before you start, restate the task in your own words: what you will build, what you will not touch, and what you are assuming. List anything in my request that is ambiguous. Wait for my OK before making changes. ``` *Why it works:* A wrong understanding costs one sentence to correct now, and a lot of review time later. Treat the restatement as a check on the agent's understanding, not as proof it will follow it. ### Ask what a thin prompt left to chance ```text Look at the change you just made. For each choice you made that I did not specify (library, file location, data shape, error handling, naming), list the choice and the alternatives. Mark the ones I should decide. ``` *Why it works:* It surfaces the guesses a thin prompt forced, so you can turn them into constraints next time. ## Check your understanding ```quiz Q: Which part of a prompt tells the agent what NOT to change or add? - [ ] Context - [ ] Interfaces - [x] Non-goals - [ ] Verification > Why: Non-goals are the boundary. Without them, agents tend to "helpfully" touch login pages, add dependencies or reformat unrelated files. --- Q: A prompt says "make it secure". What is the best fix? - [ ] Repeat it in capital letters - [x] Replace it with specific rules (for example token expiry, hashing, rate limits) the agent can implement and you can check - [ ] Remove it and let the agent decide > Why: An adjective has no criteria. Concrete constraints can be built and verified. --- Q: Which of these is a verification step? - [ ] "Make sure it works" - [x] "Write tests for valid, expired and reused tokens, run them, and show me the output" - [ ] "Use best practices" > Why: A verification step names the evidence you want to see. The other two can't be checked. ``` ## Checklist - [ ] The goal says what and why - [ ] The stack and relevant files are named - [ ] Interfaces and data shapes are defined - [ ] Security and performance rules are concrete, not adjectives - [ ] Non-goals say what not to touch or add - [ ] A verification step names the tests or commands to run - [ ] For anything non-trivial, the agent plans first and I approve ## Go deeper - [Prompting patterns that work](/docs/ai-agents/prompting-patterns.md): how to run the conversation around the prompt - [Context engineering](/docs/ai-agents/context-engineering.md): what else the agent sees besides your prompt - [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md): checking what comes back - [Prompt engineering overview (Claude docs)](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview) - [Prompt engineering (OpenAI docs)](https://developers.openai.com/api/docs/guides/prompt-engineering) --- # The software lifecycle with agents Software work is a loop: decide what to build, shape it, build it, prove it, ship it, run it, learn, repeat. An agent can speed up every step, but it can't own the ones that carry the risk. This page is the map: which phase you're in, what to ask for, and what stays your call. ## You'll be able to - Name the six phases a change passes through and what "done" means in each - Know which Groundwork pages to read, and which to give your agent, at each phase - Write acceptance criteria an agent can build against and a reviewer can check - Plan a release with a way back, and write the version and change notes for it - Run a blameless review after something breaks, and turn it into follow-up work ## The mental model Think of a change as a package moving through a warehouse. Writing the code is one station, and an agent makes it fast. That leaves the other stations as the places where problems get through: a vague request, a change too big to review, a release with no way back, an outage nobody learned from. This is the site's own framing, not a claim from a source. The phases are a teaching frame, not a standard, and real teams split them differently. What matters is that each one has a question to answer before you move on. | Phase | Question to answer | An agent helps with | You decide | Read | |---|---|---|---|---| | Plan | What are we building, for whom, and how will we know it works? | Drafting acceptance criteria, comparing stacks, surfacing unknowns | Scope, the stack, what "done" means | [Choosing a stack](/docs/stacks/choosing-a-stack.md), [Cost and model choice](/docs/ai-agents/cost-and-model-choice.md) | | Design | How do the parts fit, and what are the risky interfaces? | Sketching options, data models, API shapes | Which trade-off to accept | [How software fits together](/docs/foundations/how-software-fits-together.md), [Databases](/docs/data/databases.md) | | Build | Can we get this in small, reviewable steps? | Writing the code and the first tests | The size of each step and what is out of scope | [Building an API](/docs/backend/building-an-api.md), [Context engineering](/docs/ai-agents/context-engineering.md) | | Verify | Is it correct, secure and reviewable? | Writing tests, reviewing a diff, checking a checklist | Whether the evidence is enough to merge | [Testing](/docs/quality/testing.md), [Reviewing AI output](/docs/ai-agents/reviewing-ai-output.md), [Security basics](/docs/security/security-basics.md) | | Ship | Can we release it and undo it? | Writing the release plan, migration, changelog | When to ship, and the rollback path | [Deployment](/docs/shipping/deployment.md), [Environments and secrets](/docs/shipping/environments-and-secrets.md) | | Operate | Is it healthy, and what do we learn when it isn't? | Reading logs, drafting a timeline, proposing fixes | Severity, and what to change afterwards | [Observability](/docs/shipping/observability.md), [Backups and recovery](/docs/data/backups-and-recovery.md) | Each topic page on this site carries one of these phases in its front matter, or `any` for the pages about working with agents itself, such as prompting and context. The overview and reference pages carry none. That lets an agent find the right page for the phase it's in. See [Using Groundwork with your agent](/docs/start-here/using-groundwork-with-your-agent.md). ## Key concepts - **Acceptance criteria:** Statements that are true when the work is done, written so each can be checked. "Users can reset a password" is a wish. "A reset link works once and expires after an hour" can be tested. This is a general practice; the sample prompts below make it concrete. - **Change description:** What a pull request or commit tells the next reader. Google's engineering guide says the first line should be a short summary of what the change does, written as an order, and that "Fix bug" is inadequate. It also says to explain why, because code shows what the software does, not why it exists. - **Delivery metrics:** DORA describes five software delivery performance metrics: change lead time (commit to production), deployment frequency, failed deployment recovery time, change fail rate, and deployment rework rate. The first three measure throughput and the last two instability, because going faster is not progress if more of it breaks. Check dora.dev for current definitions; the model has changed over time. - **Semantic versioning:** A version number in the form MAJOR.MINOR.PATCH. Increase MAJOR for incompatible API changes, MINOR for backward-compatible new functionality, PATCH for backward-compatible bug fixes. Once released, a version's contents must not change; a fix is a new version. - **Changelog:** A curated list of notable changes for each version. Keep a Changelog's principles include writing it for humans, one entry per version, grouping changes by type (Added, Changed, Deprecated, Removed, Fixed, Security), putting the latest first and showing the release date. It warns that pasting a commit log is a bad idea because of the noise. - **Rollback:** Returning to a previous known-good release. Some platforms make the code part instant. Vercel's instant rollback, for example, points your domains back at an earlier production deployment. That changes which code is served, not your database, so it can't undo a migration (Vercel's docs only remind you that external APIs, databases and CMSes may behave differently after a rollback). Its docs also say environment variable changes made since that build are not applied. After a rollback, auto-assignment of production domains is turned off, so new pushes don't replace the rolled-back deployment until you undo it. Details as of 2026-11-21; check the current docs. - **Incident:** An unplanned event that harms users or the service. Google's SRE book bases incident management on the Incident Command System, with separate roles for command, operational work, communication and planning, and a living incident document kept by the person in command. Its priority is to stop the bleeding, restore service and preserve the evidence. - **Postmortem:** A written record of an incident: its impact, what was done to resolve it, the root causes and the follow-up actions. The SRE book says it must be blameless, focusing on contributing causes without blaming any person or team, on the assumption that everyone acted with good intentions and the information they had. Its example triggers include user-visible downtime beyond a threshold, any data loss, a rollback, and a monitoring failure that left someone to find the problem by hand. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | What "done" means | Acceptance criteria written before the agent starts, each one checkable | A throwaway spike: a one-line goal is enough | | Size of a change | One reviewable step; split anything you can't review in one sitting | A mechanical change that tests fully cover, such as a rename | | What the agent may do alone | Read, search and propose in every phase; write code on a branch | Production, data and billing: it proposes, you run | | How to release | Small and often, with a written way back before you start | A change that can't be small, such as a data migration: stage it in steps | | Rollback path | Decided before the release, and tried at least once | You have no production users yet | | Versioning | Semantic versioning for anything others depend on | An app with no external consumers: date or build numbers are fine | | Change notes | A human-written changelog entry, plus a descriptive first line on each change | Internal tools nobody reads about | | When to write a postmortem | Set the triggers in advance: data loss, user-visible downtime, a rollback, a missed alert | A trivial blip with no user impact | | What to measure | Throughput and stability together, a few numbers that you review | Too early to have data: skip it until you ship regularly | ## What good output looks like - Acceptance criteria that are specific, testable and include what is out of scope - A plan that lists steps small enough to review, with a check for each - A release plan that states what changes, in what order, and exactly how to undo it - A changelog entry and version bump that match what changed, with breaking changes called out - A postmortem built from facts you supplied, with unknowns marked as unknown, and action items with owners - No phase skipped without saying so ## Red flags - **Code before criteria** → the agent builds a plausible feature you can't check. Write the criteria first. - **One enormous change** → nobody can review it, and a bad part can't be backed out alone. Ask for steps. - **A release plan with no undo** → "we'll fix forward" is a plan only when you can. Ask what happens if the code is rolled back after a migration has run. - **A migration and the code that needs it shipped together** → a code rollback now leaves an incompatible database. Stage it: add, deploy, switch, remove later. - **A version bump the agent picked without reading the diff** → check it against the semantic versioning rules, especially for breaking changes. - **A postmortem that names a person** → the lesson becomes "be more careful." Ask for contributing causes and system fixes. - **A postmortem with invented details** → an agent will fill gaps convincingly. Give it the timeline, and require it to mark unknowns. ## Worked example **Task:** Let a team owner invite teammates by email, in a Next.js, TypeScript and Postgres app. **Plan.** You don't start with "build invitations." You ask for acceptance criteria. A good result: an owner can invite an email; the link works once and expires after seven days; accepting adds the person to the team with the role chosen at invite time; an invite can be revoked; non-owners can't invite. Out of scope: bulk invites, SSO. Each line can be turned into a test. **Design and build.** The data model is a small invitations table that stores a hash of the token and not the token itself. The work is split into four changes: the table, the create-and-send path, the accept path, and revoke. Each is a reviewable pull request with a descriptive first line. **Verify.** The agent writes tests for expiry, reuse, a revoked invite and a non-owner. You break the expiry check on purpose and confirm a test fails. **The wrong turn.** For the release, the agent proposes one deploy that renames a column and ships the code that uses the new name. If you roll the code back, the old version looks for a column that no longer exists. **How you catch it.** You ask the release question: "What happens if we roll back the code after the migration has run?" The agent revises the plan into steps: add the new column and keep the old one, deploy code that writes both, switch reads, and remove the old column in a later release. The changelog gets an "Added" entry and the version goes up a minor number, because it's backward-compatible new functionality. **Operate.** A week later invitation emails stop sending for two hours and a customer finds out first. That meets the triggers, a missed alert and user-visible impact, so you write a postmortem from the timeline. It finds that the email provider's key had expired and nothing watched send failures. The follow-ups are an alert on send failures and a calendar entry for key rotation, each with an owner. ## Sample prompts ### Weak vs strong ```compare ## Weak Plan out the invite-teammates feature. ## Why it fails It asks for a plan with no definition of done, so you get a task list that looks thorough and can't be checked. ## Strong We're adding "invite teammates by email" to a Next.js, TypeScript and Postgres app (Drizzle ORM). Do not write code yet. Write acceptance criteria as a numbered list. Each must be testable and written as "Given… when… then…". Include: who can invite, link behavior (single use, expiry), roles, revoking, and error cases. List what is explicitly out of scope, and any assumptions you made. Then list the open questions you need me to answer before building. ## Why it works It sets the stack, forbids premature code, forces testable criteria and an out-of-scope list, and surfaces questions before work starts. ## What changed - **Acceptance criteria** replace a task list - **Each criterion is testable** (given, when, then) - **Out of scope and assumptions** are stated - **Open questions** come first, before code ``` ### Plan a release with a way back ```text We're about to release . Do not run any commands. Write a release plan with: 1. What changes in production, in order (code, database migrations, configuration). 2. For each step, how I would undo it, and what state the system is left in if I do. 3. The point of no return, if there is one, and what I should verify before reaching it. 4. What I should watch in the first 30 minutes and which signal means "roll back". Flag any migration that makes the previous version of the code stop working, and propose a staged version that doesn't. ``` *Why it works:* It makes the undo path a deliverable and exposes the code-and-schema coupling that makes rollbacks fail. ### Write the change notes and pick the version ```text Here is the diff summary and the commit list since version : . Using semantic versioning, propose the next version number and explain which rule applies (breaking change, new backward-compatible feature, or fix). Then write a changelog entry for humans, grouped under Added, Changed, Deprecated, Removed, Fixed and Security, omitting empty groups. Call out anything that could break existing users. Do not include commit hashes or internal refactors with no user impact. ``` *Why it works:* It forces the version to be justified by the rules and keeps the entry readable instead of a pasted log. ### Draft a blameless postmortem ```text Draft a blameless postmortem from only the facts below. Do not invent times, causes or numbers; where something is not stated, write "unknown" and list it as a question for me. Sections: summary, impact, timeline, what we did to resolve it, contributing causes, what went well, what went badly, and action items (each with an owner field I will fill in). Describe causes as properties of the system and process, not the actions of any person. Facts: ``` *Why it works:* Supplying the facts and banning invention stops the agent from writing a convincing fiction, and the blameless framing keeps the follow-ups about systems. ### Find the skipped phase ```text Review this change as a lifecycle check: . For each phase (plan, design, build, verify, ship, operate) say whether the change shows evidence of it, quoting the file or line, or "no evidence". Pay particular attention to: acceptance criteria, tests that would fail if the code were broken, a rollback path, and anything that would tell us in production that it's failing. Do not change any code. Rank the gaps by risk. ``` *Why it works:* It turns "is this ready?" into a phase-by-phase audit that must cite evidence, so skipped work is visible. ## Check your understanding ```quiz Q: Why write acceptance criteria before asking an agent to build? - [ ] So the agent writes more code - [x] So "done" is defined and each part can be checked - [ ] Because agents can't plan > Why: Without checkable criteria, you can only judge whether the output looks plausible. --- Q: A release renames a database column and ships the code that uses it in one deploy. What's the risk? - [ ] The deploy will be slow - [x] Rolling back the code leaves it looking for a column that no longer exists - [ ] The version number will be wrong > Why: Code rollbacks don't undo migrations, so schema and code changes should be staged. --- Q: A new feature is added with no breaking changes. Under semantic versioning, what goes up? - [ ] MAJOR - [x] MINOR - [ ] PATCH > Why: MINOR is for backward-compatible new functionality. MAJOR is for incompatible changes and PATCH for backward-compatible fixes. --- Q: What makes a postmortem "blameless"? - [ ] It names no dates - [x] It focuses on contributing causes in the system, not on blaming a person or team - [ ] It is written by the agent alone > Why: Assuming people acted in good faith with the information they had keeps the focus on fixes. ``` ## Checklist - [ ] Acceptance criteria exist, are testable, and say what is out of scope - [ ] Each change is small enough to review in one sitting - [ ] I have the evidence for each phase, not just "done" - [ ] The release plan says how to undo each step - [ ] Schema changes are staged so a code rollback still works - [ ] The version number follows the rules, and the changelog is written for humans - [ ] I know what signal in production would tell me it's failing - [ ] If it broke, I wrote a blameless postmortem and assigned the follow-ups ## Go deeper - [Postmortem culture (Google SRE book)](https://sre.google/sre-book/postmortem-culture/): what a postmortem is, blamelessness and when to write one - [Managing incidents (Google SRE book)](https://sre.google/sre-book/managing-incidents/): roles, the living incident document and handoffs - [DORA software delivery performance metrics](https://dora.dev/guides/dora-metrics/): the five metrics and what they measure - [Semantic Versioning 2.0.0](https://semver.org): the versioning rules - [Keep a Changelog](https://keepachangelog.com/en/1.1.0/): principles for writing a changelog for humans - [Instant Rollback (Vercel docs)](https://vercel.com/docs/deployments/instant-rollback): how rollback works on one platform, and its caveats - [Writing good CL descriptions (Google)](https://google.github.io/eng-practices/review/developer/cl-descriptions.html): what a change description should say - [Deployment](/docs/shipping/deployment.md): getting code to production - [Observability](/docs/shipping/observability.md): knowing it's failing before a customer tells you - [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md): the verify phase for agent work - [Working with coding agents](/docs/start-here/working-with-coding-agents.md): the agent loop this lifecycle sits around --- # Using Groundwork with your agent These docs are written so you can read them and your agent can use them at the same time. The goal is the same as in [Context engineering](/docs/ai-agents/context-engineering.md): put the right few pages in front of the agent when the task needs them, instead of loading everything. ## You'll be able to - Pick the smallest thing to give an agent: a page, a slice or a pointer - Set up a pointer file so an agent knows which page to fetch for which job - Know what to do when your agent can't fetch web pages - Ask an agent to apply a page's checklist to your work, and read its answer critically ## What is available | What | Where | Use it for | |---|---|---| | One page as markdown | add `.md` to any page URL, for example `/docs/security/security-basics.md` | A single topic. Smallest and cheapest. | | Copy for LLM | the button at the top of every page | Pasting a page into a chat when the agent can't fetch URLs | | Index of every page | `/docs.json` | An agent choosing which page it needs. Has title, summary, phase, headings and last-reviewed date. | | Slices | `/llms/phase-build.txt`, `/llms/section-security.txt`, and one per phase and section | Several related pages in one fetch | | Starter file | `/groundwork-agents.md` | A ready-made pointer file that maps each lifecycle phase to its pages | | Everything | `/llms-full.txt` | Almost never. It is every page in one file and too large for most tasks. | | Directory | `/llms.txt` | An overview with a link and summary for each page | The slices follow the [lifecycle phases](/docs/start-here/software-lifecycle-with-agents.md): plan, design, build, verify, ship, operate, plus `any` for the pages about working with agents itself. Overview and reference pages belong to no phase, but they appear in their section slice. ## Four ways to use it **1. Hand over one page.** If your agent can fetch URLs, give it the raw markdown address and say what to do with it. If it can't, use Copy for LLM and paste. This is the right default. **2. Add a pointer file to your project.** A pointer file is a short list in your project's instruction file that says "for this kind of work, fetch that page." It costs a few lines of context and works every session. `AGENTS.md` is an open format for this: a plain markdown "README for agents" that many coding tools read, and the closest one to the file being edited wins. Claude Code's docs say it reads `AGENTS.md` (version 2.1.277 or later) only when there is no `CLAUDE.md`, and recommend a `CLAUDE.md` that imports it with `@AGENTS.md` if you want one file for several tools. Check your tool's docs for what it reads. Imports are described for file paths, so save a copy of the starter file in your repo and point to it. **3. Fetch on demand.** The pointer file tells the agent where to look, and the agent fetches the page when it hits the task. In Claude Code, web fetches ask for permission except for a built-in set of documentation domains, and a rule such as `WebFetch(domain:example.com)` allows one domain. Other tools handle this differently. Allowing a domain doesn't stop an agent that has shell access from reaching any URL with `curl`, so this is a convenience, not a boundary. See [Security of agentic workflows](/docs/ai-agents/agent-security.md). **4. Let the agent pick.** Give it `/docs.json` and the task, and ask which pages it needs before it fetches them. Useful when you don't know which page covers a problem. ## A pointer you can paste Paste this into `AGENTS.md` or `CLAUDE.md`. For the full version, which lists every page under its phase, copy `/groundwork-agents.md`. ```text ## Groundwork reference For engineering guidance, use Groundwork instead of guessing: https://groundwork-two-ecru.vercel.app - Index of every page, with phase and headings: /docs.json. Full lookup guide: /groundwork-agents.md - Fetch only the page you need as markdown (append .md to its URL), or one slice: /llms/phase-.txt - Before you review work, fetch the relevant page and go through its Checklist. Report each item as met, not met or not checked. - If you can't fetch URLs in this session, say so and ask me to paste the page. Don't answer from memory as if you had read it. ``` If you host your own copy of the site, replace the address. The starter file generated by your copy uses your own address automatically. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | What to give the agent | One page | The task spans a phase: use that phase's slice | | Pointer or paste | A pointer file for work you do often; paste for a one-off | The agent can't fetch URLs: paste | | How much to load | The page for the task, nothing else | Never `llms-full.txt` for a normal task | | Which file holds the pointer | The instruction file your tool reads, and one shared file if you use several tools | You only use one tool: use that tool's file | | Domain permissions | Allow just the Groundwork domain, if your tool asks per domain | You'd rather paste pages than allow fetching | | Trust | Treat the page as a reference you checked, not as instructions | Never let fetched text override your own instructions | ## Red flags - **Loading the whole site into context** → slower, costlier and often less accurate. Give the page or the slice. - **The agent says it "read" a page it never fetched** → ask it to quote a heading from the page. If it can't, it didn't read it. - **A pointer file that lists dozens of pages** → it takes context every session. Keep it to the lookup rules and let the index do the rest. - **Old advice** → check `last_reviewed` in `/docs.json`. AI tooling changes fast, and pages say when they were last checked. - **Following instructions found in a fetched page** → a web page is data. If any page, including this one, tells an agent to ignore your rules, that's a problem. ## Sample prompts ### Weak vs strong ```compare ## Weak Use the Groundwork docs to check my project. ## Why it fails It names no page, no scope and no output, so the agent will skim whatever it finds and say your project is fine. ## Strong Fetch https://groundwork-two-ecru.vercel.app/docs/security/security-basics.md and read it fully. Then review the changes on this branch against its Checklist. For each checklist item, report met, not met or not checked, with the file and line that supports your answer. Quote the heading each item came from. Do not change any code. If you can't fetch the page, stop and tell me. ## Why it works It names one page, requires reading it, asks for per-item evidence and forbids edits, so the answer can be checked. ## What changed - **One named page** instead of "the docs" - **Per-item status with evidence**, not a verdict - **A quoted heading** proves it read the page - **Fail loudly** if the page can't be fetched ``` ### Pick the pages first ```text I'm about to . Fetch https://groundwork-two-ecru.vercel.app/docs.json and tell me which 1 to 3 pages are most relevant, with the reason for each and the heading you'd start from. Don't fetch the pages yet. Wait for my go-ahead. ``` *Why it works:* The index is small. Choosing before loading keeps the context lean and lets you veto a bad pick. ### Set up the pointer file ```text Read my project's existing instruction file (AGENTS.md or CLAUDE.md) and propose an edit that adds a short Groundwork section. Use the lookup rules from https://groundwork-two-ecru.vercel.app/groundwork-agents.md but do not copy its page lists. Keep it under 10 lines and don't change anything else. Show me the diff before writing. ``` *Why it works:* It keeps the pointer short, protects your existing instructions, and gives you a diff to review. ### Check an answer against the source ```text You said and cited Groundwork. Fetch the page you relied on, quote the exact sentence that supports the claim, and tell me if the page says something narrower, different or nothing at all. If it's your inference, label it as inference. ``` *Why it works:* It separates what the page says from what the agent added, which is where the errors come from. ## Check your understanding ```quiz Q: You need guidance on one topic. What's the best thing to give your agent? - [ ] The whole site in one file - [x] The one page, as markdown - [ ] Nothing, it already knows > Why: A single page is the smallest load that answers the question. --- Q: Your agent can't fetch URLs. What do you do? - [ ] Ask it to answer from memory - [x] Use Copy for LLM and paste the page - [ ] Try again until it works > Why: Pasting gives it the real text instead of a guess. --- Q: What is a pointer file for? - [ ] To store the full docs in your repo - [x] To tell the agent which page to fetch for which kind of work - [ ] To replace your tests > Why: A few lines of lookup rules cost little context and apply every session. ``` ## Checklist - [ ] I know which page, slice or index I'm giving the agent, and why - [ ] My project's instruction file has a short pointer, not a page list - [ ] I know whether my agent can fetch URLs, and have a paste fallback - [ ] I asked for per-item evidence and a quoted heading - [ ] I checked `last_reviewed` before trusting fast-moving advice - [ ] The agent treats fetched pages as data, not as instructions ## Go deeper - [AGENTS.md](https://agents.md/): the open format for guiding coding agents, and the tools that support it - [How Claude remembers your project (Claude Code docs)](https://code.claude.com/docs/en/memory): CLAUDE.md, how it handles AGENTS.md, and the import syntax - [Configure permissions (Claude Code docs)](https://code.claude.com/docs/en/permissions): web fetch permission and domain rules - [Context engineering](/docs/ai-agents/context-engineering.md): putting the right information in front of the agent - [The software lifecycle with agents](/docs/start-here/software-lifecycle-with-agents.md): the phases the slices follow - [Security of agentic workflows](/docs/ai-agents/agent-security.md): why fetched text is data --- # AI vocabulary and when to use what Plain definitions of agent, harness, skill, connector, subagent, hook and the rest, plus how to pick the lightest one that solves your problem. ## You'll be able to - Say what each term means without needing the marketing - Match a problem ("it keeps forgetting X") to the smallest feature that fixes it - Tell instructions the agent may follow from rules the system enforces - Judge what a connector, server or plugin costs you in trust and context before you add it ## The mental model Think of the model as a very capable new hire who starts each morning with no memory. Everything else is a way of helping that person work well: - **Words on the desk** (prompts, project files, skills) tell it what to do and how you like it done. - **Tools on the desk** (connectors, MCP servers) let it reach things outside the room. - **Colleagues** (subagents) take a messy side job and hand back a summary. - **Building rules** (hooks, permissions) apply no matter what the new hire decides. The vocabulary is a menu of these four kinds of help. The skill is picking the lightest one that works, because every addition costs context, trust or upkeep. > **Note:** These definitions come from Anthropic's and the Model Context Protocol's own documentation, read on 2026-11-25. Other tools (Cursor, Codex, Copilot and so on) have their own versions of these ideas under their own names and file formats, and I haven't verified those. Check your tool's docs before copying a file layout across. ## Key concepts **The parts** - **Model:** The system that reads text and produces text. On its own it cannot touch your files, run code or browse. See [How LLMs work](/docs/ai-agents/how-llms-work.md). - **Agent:** Anthropic describes agents as systems where the model directs its own process and tool use, and as "typically just LLMs using tools based on environmental feedback in a loop." Contrast that with a *workflow*, where code decides the steps in advance. - **Harness:** The program that wraps the model, supplies its tools and manages its context, so the model can work for more than one turn. Anthropic's engineering post calls the Claude Agent SDK "a general-purpose agent harness," and the harness is the thing Claude Code, Cursor and similar tools have in common. Vendors use the word loosely, so treat it as "the app around the model." - **Tool:** A function the harness can run for the model, such as read a file, run a command or search the web. The model asks, the harness runs it. See [Agents, tools and MCP](/docs/ai-agents/agents-tools-and-mcp.md). **Things you write (instructions)** - **Project file (CLAUDE.md, AGENTS.md and similar):** A markdown file the agent reads at the start of a session. In Claude Code, CLAUDE.md can live in your home folder, in the repo, or in a managed organization location, and the docs suggest keeping each file under about 200 lines because longer files cost context and reduce adherence. Good for facts that apply every session: build commands, conventions, "always do X." - **Skill:** A folder with a `SKILL.md` file (and optional supporting files) that teaches the agent a procedure. The agent sees each skill's short description up front and loads the full body only when it is relevant or when you call it by name, so a skill costs little until used. Claude Code's docs say to create one "when you keep pasting the same instructions, checklist, or multi-step procedure into chat," or when part of CLAUDE.md "has grown into a procedure rather than a fact." - **Slash command:** A prompt you trigger by typing `/name`. In Claude Code, custom commands have been merged into skills, so a skill is how you make one now. Older command files still work. **Things that reach outward** - **MCP (Model Context Protocol):** An open-source standard for connecting AI applications to external systems. The project's own analogy is a USB-C port: one standard plug instead of a custom cable for every service. - **MCP server:** A program that exposes tools (and sometimes data and prompts) over MCP. It can run on your machine or be hosted remotely. - **Connector:** Anthropic's name, in the Claude apps, for a link that lets Claude "access your apps and services, retrieve your data, and take actions" in them. A custom connector is a remote MCP server. Claude inherits your permissions in the connected service, which cuts both ways: it can do what you can do there. **Things that delegate or enforce** - **Subagent:** A helper that runs in its own context window with its own system prompt and tool access, and returns only a summary to the main conversation. Claude Code's docs give the reasons to use one: preserve context, enforce constraints by limiting tools, reuse configurations, specialize behavior and control cost. - **Hook:** A command (or HTTP call, or prompt) that the harness runs automatically at a point in the agent's lifecycle, such as before or after a tool call. A hook that blocks an action does so every time, because the harness runs it, not the model. The docs put it this way: hooks give "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them." - **Plugin:** A directory that bundles skills, subagents, hooks and MCP servers so you can install and share them as one unit. - **Sandbox and permissions:** Limits on what the agent can touch, set by the harness. Instructions ask; permissions and sandboxes decide. ## Decisions you make (not the agent) | What's happening | Sensible default | Choose otherwise when… | |---|---|---| | One-off task | Write a better prompt | The same prompt keeps getting pasted | | It lacks a fact it needs every session (build command, naming rule, folder layout) | Add one line to the project file | The file is past about 200 lines: move procedures out | | You keep pasting the same checklist or multi-step procedure | Make it a skill | It is a fact, not a procedure: keep it in the project file | | A side task floods the conversation with output you won't reread (searching a big codebase, reviewing a large diff) | Run it in a subagent | The result needs your back-and-forth: stay in the main conversation | | A rule must hold every time (don't edit applied migrations, don't touch `.env`) | A hook or a permission rule | A reminder is enough: the project file is fine | | It needs live data or actions in another system (tickets, database, calendar) | Connect that one service, read-only first | A one-time export or a CLI the agent can run does the job | | You want the same setup in every project or for a team | Package it as a plugin | A single skill or server works alone: install just that | Read the table from the top and stop at the first row that fits. Each row down costs more context, access or upkeep than the one above. ## What good output looks like - When you ask "which of these should I use?", the agent proposes the lightest option first and says what it costs - A skill's description says when to use it, not just what it is - A project file reads like a short list of facts, not an essay - A new server or plugin comes with a plain statement of what it can read and change - Anything that "must always happen" is enforced by the system, and the agent can tell you how you'd test it ## Red flags - **The agent proposes a plugin or MCP server for a one-line fix** → ask what a project-file line or a skill would cost instead. - **A rule is written in capital letters in the project file** → project files are context, not enforcement. Claude Code's docs say they "aren't enforced configuration" and point to hooks or managed settings for hard blocks. - **A hook is trusted as a complete wall** → the docs warn Claude can still change protected files with shell commands. Back a hook with permissions and review. - **A connector or server you haven't read** → Anthropic's help center warns that custom connectors reach services it hasn't verified and that malicious servers "may include hidden instructions." Claude Code's docs add that servers which fetch external content can expose you to prompt injection. See [Security of agentic workflows](/docs/ai-agents/agent-security.md). - **Everything installed "just in case"** → an enabled plugin loads every session, its skill and agent descriptions occupy context on every turn, and "what the plugin runs, it runs as you." - **"Allow always" clicked on something you don't understand** → Anthropic's guidance is to use it only for a server and tool you trust to run unsupervised. ## Worked example **Task:** the agent keeps editing migration files that have already been applied, and you've told it not to. You add "NEVER edit existing migrations!!!" to the project file. It works for two sessions and then fails on a long session, after the agent has read a lot of other material. **The wrong turn:** adding louder text to the project file. That file is context the model weighs, not a rule the system applies, so there is no guarantee. The next step up, a plugin or an MCP server "to guard migrations," is far more machinery than the problem needs. **What a good result contains:** a hook that runs before any file-edit tool call, checks whether the path is in the migrations folder and whether that migration is already applied, and blocks the call with a message saying why. Anthropic's hooks guide says exit code 2 blocks the action. The project file keeps one calm line explaining the convention so the agent doesn't walk into the block repeatedly. **How review catches it:** don't trust the description. Ask the agent to try editing an applied migration and watch the block fire. Then ask it to try the same change through a shell command, because a hook on edit tools may not cover that path. If it gets through, add a permission rule or a second check. ## Sample prompts ### Weak vs strong ```compare ## Weak Set up skills and agents and MCP for this project so you work better. ## Why it fails It names features instead of a problem, so the agent installs whatever it knows about. You get more context cost, more access and no evidence anything improved. ## Strong Goal: stop you from editing database migrations that are already applied. Context: Next.js, TypeScript, Postgres with Drizzle. Applied migrations live in drizzle/ and are listed in the migrations table. Process: first list the options, from lightest to heaviest (a line in the project file, a permission rule, a hook, a skill, a plugin). For each, say what it enforces, what it costs in context, and how it could be bypassed. Recommend the lightest one that can actually enforce the rule. Constraints: do not add MCP servers or plugins. Do not change files until I approve the recommendation. Verify: after I approve, implement it, then try to edit an applied migration both with the edit tool and with a shell command, and show me what happened each time. ## Why it works It states the problem, asks for options ranked by weight, and demands a test of the enforcement rather than a claim. ## What changed - **Goal** is a behavior to stop, not a feature to install - **Options first**, lightest to heaviest, with costs and bypasses - **Non-goals** rule out servers and plugins up front - **Verification** tries to break the rule ``` ### Which feature fits? ```text I keep running into this: . Which is the lightest fix: a better prompt, a line in the project file, a skill, a subagent, a hook or permission rule, a connector or MCP server, or a plugin? Rank the plausible options from lightest to heaviest. For each, say what it costs (context, access, upkeep) and whether it enforces the rule or only asks. Recommend one and say what would make you pick a heavier one. ``` *Why it works:* It forces a comparison on cost and enforcement instead of reaching for the newest feature. ### Audit what is already installed ```text List every project file, skill, subagent, hook, MCP server, connector and plugin active in this session. For each, tell me: what it can read, what it can change, whether it reaches the network, and roughly how much context it uses on every turn. Then tell me which ones this repo does not need and could be turned off. ``` *Why it works:* It makes the hidden costs visible so you can remove things, which is usually the better fix. ### Check a new connector before adding it ```text I'm considering connecting . Before I do, tell me: what it can read and change in my account, who maintains it, whether it runs on my machine or remotely, and what would happen if it returned instructions hidden in its data. Suggest the narrowest permissions and a read-only first trial. Say clearly what you could not verify. ``` *Why it works:* It asks for a trust assessment and honest gaps, matching the guidance to connect only what you trust and need. ## Check your understanding ```quiz Q: A rule must hold every single time, such as never editing applied migrations. Where should it live? - [ ] In the project file, written in capital letters - [x] In a hook or permission rule that the harness enforces - [ ] In a longer prompt at the start of each session > Why: The project file is context the model weighs, not enforced configuration. Hooks and permissions are applied by the harness regardless of what the model decides. --- Q: You keep pasting the same five-step review checklist into chat. What is the lightest fix? - [ ] An MCP server - [x] A skill - [ ] A plugin > Why: A skill packages a recurring procedure, and its body loads only when used. A plugin or server is far more machinery for one checklist. --- Q: A teammate says "just connect the service, it only has read access." What should you still check? - [ ] Nothing, read access is always safe - [x] What the service returns, because a malicious or compromised server can include hidden instructions in its data - [ ] Whether the connector has a logo > Why: Anthropic warns that malicious servers may include hidden instructions, and Claude Code's docs warn about prompt injection from servers that fetch external content. ``` ## Checklist - [ ] I can define agent, harness, tool, skill, subagent, hook, MCP, connector and plugin in one sentence each - [ ] For my current annoyance, I picked the lightest fix, not the newest feature - [ ] Anything that must always happen is enforced by a hook or permission, not by a request - [ ] Every connector, server and plugin is one I've read or trust - [ ] My project file is short enough that I would still read it - [ ] I know what is installed and can turn it off ## Go deeper - [Skills (Claude Code docs)](https://code.claude.com/docs/en/skills): what a skill is, where it lives, and when to write one - [Create custom subagents (Claude Code docs)](https://code.claude.com/docs/en/sub-agents): own context, tool limits and the reasons to delegate - [Hooks guide (Claude Code docs)](https://code.claude.com/docs/en/hooks-guide): lifecycle events and deterministic control - [How Claude remembers your project (Claude Code docs)](https://code.claude.com/docs/en/memory): CLAUDE.md locations, size guidance and what is not enforced - [Connect Claude Code to tools via MCP](https://code.claude.com/docs/en/mcp): adding servers and the trust warning - [Plugins (Claude Code docs)](https://code.claude.com/docs/en/plugins): bundling skills, agents, hooks and servers - [Use connectors to extend Claude's capabilities](https://support.claude.com/en/articles/11176164-use-connectors-to-extend-claude-s-capabilities): what connectors are and the trust guidance - [Get started with custom connectors using remote MCP](https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp): custom connectors, who can add them and the risks - [What is MCP?](https://modelcontextprotocol.io/docs/getting-started/intro): the protocol's own definition - [Effective harnesses for long-running agents (Anthropic)](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents): where "harness" comes from, published 2025-11-26 - [Building effective agents (Anthropic)](https://www.anthropic.com/engineering/building-effective-agents): workflows versus agents, published December 2024 - [Agents, tools and MCP](/docs/ai-agents/agents-tools-and-mcp.md) and [Skill and agent templates](/docs/ai-agents/skill-and-agent-templates.md): the next level down, with working examples --- # How software fits together Almost every app has the same core shape. The rest of Groundwork zooms in on one box of this map at a time. ## You'll be able to - Name each layer of a typical web app and what it's responsible for - Trace a request from a button click to the database and back - Tell an agent which layer a change belongs in ## The mental model ``` Browser / Mobile app ──HTTP──▶ API server ──SQL──▶ Database (frontend / client) (backend) (data) │ │ ▼ ▼ CDN (static files) Third-party services (email, payments, AI) ``` **The life of a click:** The user presses "Save". The frontend sends an HTTP request. DNS resolves the domain name. The request reaches the server, which checks who you are (auth), validates the input, writes to the database, and returns JSON. The frontend then updates the screen. ## Key concepts - **Client / frontend:** The code that runs on the user's device. It's untrusted, because users can change anything that runs there. - **Server / backend:** The code that runs on machines you control. This is where business rules and secrets live. - **Database:** Durable storage. It's the source of truth. - **API:** The contract between client and server. See [Building an API](/docs/backend/building-an-api.md). - **Static vs dynamic:** Static files (HTML, CSS, JS, images) are the same for everyone and can be cached on a CDN. Dynamic responses depend on the user or the data. - **Rendering modes:** Pages can be built in the browser (CSR), on the server for each request (SSR), or once at build time (SSG). Modern frameworks mix all three. - **Monolith vs services:** A monolith is one deployable app. Microservices are many apps that talk over a network. **Start with a monolith.** - **Serverless:** You deploy functions, and the platform runs them on demand. There are no servers for you to manage, but cold starts and execution-time limits apply. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | Architecture | Monolith (one full-stack app) | Separate teams or very different scaling needs | | Full-stack framework vs separate frontend + backend | Full-stack framework (Next.js, SvelteKit, Rails, Django, Phoenix) | Multiple clients (web + mobile) share one API | | Where logic lives | Server. Never trust the client | Pure UI behaviour | ## What good output looks like - The explanation names the layers that actually exist in this repo, with file paths, not a generic diagram - It traces one real action file by file, and says where input is validated and who is allowed to do what - It lists the external services the app calls and where their keys are used - It says what it could not determine instead of guessing ## Red flags - Business rules or permission checks done **only** in the frontend - Microservices proposed for an MVP - The database queried directly from browser code using a privileged key - **Common agent mistakes:** a price, limit or permission decided in browser code; the client sending a total or a "role" that the server trusts; a feature added in the wrong layer because the prompt didn't say which one ## Worked example **Task:** Add a discount code field to the checkout page. You prompt: *"Add a discount code field to checkout."* The agent adds the input and a small list of valid codes in the frontend, applies the percentage off in the browser, and sends the new total to the server, which saves it. **What a good result contains:** the browser sends only the code; the server checks that the code is valid, works out the price itself, and returns the result; the database records which discount was applied; the browser just shows what the server said. **The wrong turn:** the rule lives in the client. Anyone can read the list of codes in the page's JavaScript, and anyone can send a different total to the server, because the server saves whatever it is told. **How review catches it:** trace the request. Ask *what does the server receive, and what does it trust?* The payload contains a `total`, which is the tell. Then re-prompt with the layer stated: the client sends the code, and the server validates it and computes the price. ## Sample prompts ```text Explain the architecture of this repo as a diagram (ASCII or Mermaid): what runs in the browser, what runs on the server, where data is stored, and what external services are called. Then trace what happens, file by file, when a user . ``` *Why it works:* Use this first in any unfamiliar codebase, including one an agent generated for you. ### Which layer does this belong in? ```text I want to . Before writing code, tell me which layers it touches (browser, API server, database, third-party service), what changes in each, and which parts must be enforced on the server. Don't write code yet. ``` *Why it works:* Naming the layers first catches "it works, but in the wrong place" before it is built. ### Audit for logic that only the client enforces ```text Audit this change for rules that run only in the browser. List every price, limit, permission or validation decided by client code, and say what the server does with each. Flag anything the server accepts from the client without checking. ``` *Why it works:* It targets the most common architecture mistake directly, and gives you a short list to verify. ### Explain where each part lives ```text For the change you just made, list each part (UI, request, validation, storage, external call) with the layer it lives in and why that layer is right. Mark anything you put in the client that I should challenge. ``` *Why it works:* Explaining forces the agent to commit to a layer for each part. Check its answer against the actual diff. ## Check your understanding ```quiz Q: Where should permission checks and business rules be enforced? - [ ] In the frontend, so the page responds instantly - [x] On the server, because anyone can change code that runs in their browser - [ ] In the database client library only > Why: The client is untrusted. Frontend checks are fine for user experience, but they can't be the only line of defense. --- Q: A user presses "Save". Which describes what happens? - [ ] The browser writes directly to the database with an admin key - [x] The frontend sends an HTTP request, the server checks who you are and validates the input, writes to the database, and returns a response the frontend displays - [ ] The database calls the frontend when it has new data > Why: Browser, API server, database is the usual shape, and the server sits in the middle so it can enforce the rules. --- Q: What is the sensible default architecture for an MVP? - [ ] Microservices, so you can scale later - [x] A monolith: one full-stack app - [ ] Serverless functions for every endpoint > Why: A monolith is simpler to build, deploy and debug. Split it when a real constraint (teams or scaling) demands it. ``` ## Checklist - [ ] I can name the layers of my app and what each is responsible for - [ ] Business rules and permission checks run on the server - [ ] Secrets and privileged keys exist only on the server - [ ] It is one deployable app unless I have a concrete reason to split it - [ ] I can trace one request from the click to the database and back ## Go deeper - [Building an API](/docs/backend/building-an-api.md): the contract between client and server - [Databases](/docs/data/databases.md): the source of truth - [Networking basics](/docs/foundations/networking-basics.md): what happens between the browser and the server - [Security basics](/docs/security/security-basics.md): why the client is untrusted - [MDN: An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) --- # The terminal & git Agents live in the terminal and leave their work behind in git. If you can read both, you can see exactly what the agent did and undo it. ## You'll be able to - Read the commands an agent runs and know which ones are dangerous - Use git as a safety net: checkpoint, review, revert - Manage dependencies and scripts confidently ## The mental model The terminal is a text interface for telling the computer what to do. Every command runs with your permissions, in a particular folder. Git is a timeline of snapshots of your project, like save points in a game. Put them together and you get the whole agent workflow: the agent runs commands and edits files, and git shows exactly what changed and lets you return to a save point you made on purpose. ## Key concepts ### Terminal - **Shell:** The program that interprets commands (zsh, bash). The **working directory** is where commands run. - **Environment variables:** Key-value settings for a process (`PATH`, `DATABASE_URL`). - **Package managers:** `npm`/`pnpm`/`bun` (JS), `pip`/`uv` (Python), `cargo` (Rust), `brew` (macOS). The **lockfile** pins exact versions. Commit it. - **Scripts:** `package.json` → `"scripts"` (or a `Makefile`/`justfile`) define standard commands: `dev`, `test`, `build`, `lint`. ### Git - **Commit:** A snapshot of the project. **Branch:** A parallel line of work. **Remote:** The copy on GitHub. - **Diff:** What changed. *This is how you review an agent's work.* - **Pull request (PR):** A proposed change, reviewed before it's merged into `main`. - **Worktree:** A second working copy of the same repo, so you can run parallel agent sessions without them stepping on each other. - **.gitignore:** Files that should never be committed (`node_modules`, `.env`, build output). ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | Branching | One branch per feature, PR into `main` | Solo prototype (committing straight to main is fine) | | Checkpointing | Commit before every agent session | Never skip it | | Agent permissions | Allow reads and tests freely; require approval for installs, deletes, pushes | Sandboxed or containerized environment | ## What good output looks like - Commands are narrow and reversible: one file or folder, not a wildcard over the whole project - The agent checks `git status` and `git diff` before it commits, and commits small, focused changes - Commit messages explain why, not just what - Nothing secret is staged, and it works on a branch rather than directly on `main` ## Red flags (commands to pause on) - `rm -rf`, `git reset --hard`, `git push --force`, `git clean -fd` - `curl … | sh` from an unknown URL - `chmod 777`, or anything using `sudo` - Installing a package you've never heard of → check it on the registry first - Committing `.env` or credentials - **Common agent mistakes:** `git add -A` or `git add .` stages everything that isn't ignored, including a `.env` file if it isn't in `.gitignore`. `git reset --hard` overwrites your files with the last commit, so uncommitted work is gone. `git clean -fdx` also removes ignored files such as `.env` and `node_modules`. Force-pushing to "fix" a conflict rewrites shared history. ## Worked example **Task:** You ask an agent to fix a typo bug in two files, and you start the session without committing first. When it finishes, `git status` shows 14 changed files. The agent also "tidied" formatting across the project and, when its own changes broke the build, ran `git reset --hard` to start over. That command also overwrote the edits you had made by hand before the session. **What a good result contains:** you committed (or branched) before the session. The agent's work sits on its own branch, the diff touches the two files that matter, and `git diff --stat` matches the size of the task. **The wrong turn:** two things went wrong. There was no checkpoint, and a command that overwrites the working tree was allowed to run unattended. **How review catches it:** look at `git status` and `git diff --stat` before reading any code. A two-file task with 14 changed files is a red flag. Keep the good changes with `git add -p`, which lets you pick the hunks to stage, and discard the rest with `git restore `, which replaces your working copy of that file with the committed or staged version. Treat that as final, because git doesn't promise to get discarded edits back. Next time, commit first, give the agent its own branch or worktree, and require approval for any command that discards work. ## Sample prompts ```text Summarize the uncommitted changes in this repo: list each file, what changed and why it might have changed, and flag anything risky (deleted files, config changes, new dependencies, secrets). ``` *Why it works:* A summary of the uncommitted changes shows you the whole footprint of a session before you commit any of it. ```text Write a clear commit message for the staged changes using Conventional Commits (feat/fix/chore…). Subject under 72 chars, body explains why. ``` *Why it works:* A message that explains why leaves a history you can actually use when something breaks later. ### Set up a safety net before the session ```text Before you change anything, run git status. If there are uncommitted changes, stop and tell me. Otherwise create a branch named agent/ and do all your work there. Do not commit to main, and do not run any command that discards changes or rewrites history without asking me first. ``` *Why it works:* It makes the checkpoint and the boundary part of the task, so a bad session is one branch to delete. ### Ask before anything destructive ```text Before running any command that can discard work (git reset --hard, git restore, git checkout -- , git clean, git push --force, rm -rf), tell me exactly what it would remove. Use a dry run where one exists (for example git clean -n) and show me the output. Wait for my OK. ``` *Why it works:* A dry run turns a guess about what a command will delete into a list you can read. ### Audit the commands that were run ```text List every command you ran in this session that deleted files, overwrote files, or rewrote history. For each, explain what it did, why you ran it, and whether the result can be undone. Be explicit about anything that could have affected changes I made before the session. ``` *Why it works:* It makes the agent account for the risky steps. Compare its answer with the shell history and `git reflog`. ### Recover after a mistake ```text I ran and lost work. Do not run anything yet. Explain what state the repo is in now, what git reflog could show about where HEAD and my branches used to point, and the safest next steps, one command at a time, each explained before I run it. ``` *Why it works:* The reflog records where branches and HEAD pointed, which can help you find a lost commit. It can't bring back edits that were never committed, which is why committing first matters. Going slowly avoids making the recovery worse. ## Check your understanding ```quiz Q: What is a git worktree useful for? - [ ] Backing up your project to the cloud - [x] A second working copy of the same repository, so you can have another branch checked out at the same time, for example for a parallel agent session - [ ] Removing untracked files > Why: A linked worktree has its own checked-out branch and index while sharing the rest of the repository. --- Q: Which command can delete files that git is ignoring, such as a .env file or node_modules? - [ ] git status - [ ] git diff - [x] git clean -fdx > Why: git clean removes untracked files, and the -x flag removes ignored files as well. Use -n first to see what it would delete. --- Q: Why commit before an agent session? - [ ] The agent can't start without a commit - [x] It gives you a snapshot to return to, so a bad session is easy to discard - [ ] It speeds up the agent > Why: Committed work is the only work git reliably protects. Uncommitted edits can be overwritten by commands like git reset --hard. ``` ## Checklist - [ ] `.gitignore` covers secrets, dependencies and build output - [ ] Lockfile is committed - [ ] You review `git diff` before every commit an agent prepares - [ ] You committed (or branched) before the session started - [ ] The agent works on its own branch or worktree - [ ] Commands that discard work need your OK, ideally after a dry run ## Go deeper - [Pro Git (free book)](https://git-scm.com/book) - [The Missing Semester of Your CS Education (MIT)](https://missing.csail.mit.edu) - [git restore](https://git-scm.com/docs/git-restore), [git reset](https://git-scm.com/docs/git-reset), [git clean](https://git-scm.com/docs/git-clean), [git reflog](https://git-scm.com/docs/git-reflog), [git worktree](https://git-scm.com/docs/git-worktree) and [git add](https://git-scm.com/docs/git-add): the official manual pages for the commands above - [Working with coding agents](/docs/start-here/working-with-coding-agents.md): a git-first agent workflow - [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md): checking diffs --- # Networking basics Most deployment and integration bugs are really networking bugs. Learning the vocabulary lets you describe the problem precisely, both to an agent and to yourself. ## You'll be able to - Explain what happens between typing a URL and seeing a page - Debug common errors: CORS, DNS, TLS, timeouts, 4xx/5xx - Set up a custom domain with confidence ## The mental model `example.com` → **DNS** looks up the IP address → the client opens a **TCP** connection to that IP on **port 443** → a **TLS** handshake encrypts the connection → the client sends an **HTTP request** → the server sends an **HTTP response**. ## Key concepts - **IP address:** A machine's address on the network. **Port:** A numbered door on that machine (80 = HTTP, 443 = HTTPS, 5432 = Postgres, 3000 = a typical dev server). - **localhost / 127.0.0.1:** "This machine." A server bound to localhost can't be reached from other machines. Binding to `0.0.0.0` listens on all interfaces. - **DNS records:** `A` (name → IPv4), `AAAA` (→ IPv6), `CNAME` (name → another name), `MX` (mail), `TXT` (verification, SPF/DKIM). **TTL** sets how long resolvers cache a record, which is why DNS changes can seem to "take a while." - **HTTP:** Methods (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`), headers, body, and status codes: `2xx` OK, `3xx` redirect, `4xx` your request was wrong (401 not logged in, 403 not allowed, 404 not found, 429 rate-limited), `5xx` the server broke. - **HTTPS / TLS:** Encryption plus proof of identity through certificates. Platforms like Vercel, Netlify and Cloudflare issue certificates automatically (Let's Encrypt). - **CORS:** A *browser* rule. JavaScript on site A can't read responses from site B unless B explicitly allows it with `Access-Control-Allow-Origin` headers. Server-to-server calls ignore CORS entirely. - **Proxy / reverse proxy / load balancer:** Middlemen that forward traffic. Nginx, Caddy and Cloudflare all fill these roles. - **CDN:** Servers around the world that cache your static content close to users. - **Firewall / security groups:** Rules that decide which ports and IPs can connect. - **WebSockets / SSE:** Long-lived connections for real-time updates. ## Decisions you make (not the agent) | Decision | Sensible default | Choose otherwise when… | |---|---|---| | DNS provider | Your host's DNS or Cloudflare | Your registrar is required for email setup | | Apex vs www | Serve one, redirect the other | — | | CORS policy | Allow only your own origins | You're building a public API | | Database exposure | Private network only, never open to `0.0.0.0/0` | Managed DB with IP allowlist + TLS | ## What good output looks like - The explanation says which step failed (DNS, connection or port, TLS, HTTP status, or CORS), not just "a network error" - A CORS fix names specific origins, methods and headers, and never a wildcard when cookies are involved - It gives you a command to confirm the fix (`dig`, `curl -I`, `curl -v`) - Nothing weakens TLS or opens a database port to the internet ## Red flags - `Access-Control-Allow-Origin: *` combined with credentials/cookies - Disabling TLS verification to "fix" an error - A database port open to the internet - Treating a CORS error as a server bug. The request often succeeded, and the browser blocked your JavaScript from reading the response. - **Common agent mistakes:** "fixing" CORS by allowing every origin, or by reflecting whatever origin the request sends; answering the preflight (`OPTIONS`) request incorrectly or not at all; changing DNS records without saying how to check them ## Worked example **Task:** A frontend at `app.example.com` can't call the API at `api.example.com`. The browser console shows a CORS error on a `POST` that sends JSON and an `Authorization` header, with cookies enabled. You paste the error and say "fix CORS." The agent adds `Access-Control-Allow-Origin: *` to the API's responses. The error remains. It then changes the API to echo back whatever `Origin` the request sends, and the error goes away. **What a good result contains:** the API recognizes the browser's preflight (`OPTIONS`) request and answers with the one allowed origin, the allowed methods and headers, and `Access-Control-Allow-Credentials: true`, plus `Vary: Origin`. Only your own origins are on the allowlist. **The wrong turn:** a wildcard isn't allowed on a credentialed request, which is why the first fix failed. The second fix works by accident: echoing back any origin means every website on the internet is now allowed to make credentialed requests to your API. **How review catches it:** the request is preflighted because it sends an `Authorization` header and a JSON body. Reproduce that preflight yourself with `curl`, and read the response headers. Then repeat it with an origin that is not yours and confirm it is refused. Ask the agent to explain what each header allows. Note that the browser console has the details: JavaScript itself gets no specifics about a CORS failure. ## Sample prompts ```text I'm getting this error in the browser console when my frontend at calls my API at : Explain what's actually happening at the HTTP level, then fix it on the API side, allowing only my frontend origin, with credentials enabled. Don't use a wildcard. ``` *Why it works:* It asks for the HTTP-level explanation first, then a narrowly scoped fix: one origin, credentials on, no wildcard. Browsers don't accept a wildcard on credentialed requests, so this is also the fix that works. ```text Walk me through connecting the domain to my project: which DNS records to create at , values, apex vs www redirect, and how to verify propagation and TLS from the command line (dig, curl -I). ``` *Why it works:* It asks for the exact records and for ways to verify each step from the command line, so you confirm progress instead of waiting and hoping. ### Reproduce the preflight with curl ```text My browser blocks a POST from https://app.example.com to https://api.example.com/. Use curl to send the preflight request (an OPTIONS request) with the headers Origin, Access-Control-Request-Method: POST and Access-Control-Request-Headers: authorization,content-type. Show me the full response headers and tell me which CORS header is missing or wrong. Then repeat it with Origin: https://evil.example and show that it is refused. ``` *Why it works:* It tests the server directly, the way the browser would, and the second request proves the fix isn't too permissive. ### Find the layer that is failing ```text . Diagnose it layer by layer: DNS (dig), connection and port (curl -v), TLS (curl -v, certificate), HTTP status, and CORS (browser console only). For each layer give the exact command, what a healthy result looks like, and what a failure means. Run what you can and tell me which layer fails first. ``` *Why it works:* Most "network" bugs are one specific layer. Checking in order stops you from debugging CORS when the real problem is DNS. ### Explain why your CORS config is safe ```text Explain the CORS configuration you just wrote: which origins, methods, headers and credentials it allows, and why each is necessary. What could a malicious website do against this API with this config? If any answer is "more than it should", tighten it. ``` *Why it works:* It makes the agent justify every permission. Check the answer against the actual response headers from curl. ## Check your understanding ```quiz Q: Where is CORS enforced? - [ ] By the API server, which refuses the request - [x] By the browser, which decides whether JavaScript may read a cross-origin response - [ ] By DNS > Why: CORS is a browser rule. Servers opt in with headers, and calls made from one server to another aren't subject to it. --- Q: What can cause a browser to send a preflight (OPTIONS) request first? - [ ] Any GET request - [x] An Authorization header, or a request body such as JSON, that isn't one of the simple types - [ ] Using HTTPS > Why: Simple requests are limited to GET, HEAD or POST with only a few safelisted headers and content types. Going beyond that triggers a preflight. --- Q: Your frontend sends cookies to the API. Which response is NOT allowed? - [ ] Access-Control-Allow-Origin: https://app.example.com - [x] Access-Control-Allow-Origin: * - [ ] Access-Control-Allow-Credentials: true > Why: For credentialed requests the server must name the origin explicitly. A wildcard is blocked. --- Q: You changed a DNS record, but some people still see the old address. Most likely reason? - [ ] The record is invalid - [x] Resolvers cache records for the TTL, so the change takes a while to spread - [ ] The browser is broken > Why: TTL tells resolvers how long they may cache a record. ``` ## Checklist - [ ] DNS records exist and `dig` shows the expected values - [ ] HTTPS works, the certificate is valid, and HTTP redirects to HTTPS - [ ] Either the apex domain or `www` redirects to the other - [ ] CORS allows only my own origins, and there is no wildcard when cookies are involved - [ ] The database is not reachable from the open internet - [ ] I know how to test the fix with `curl -I` or `curl -v` ## Go deeper - [MDN: An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) - [MDN: CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) - [How DNS works (comic)](https://howdns.works) - [How software fits together](/docs/foundations/how-software-fits-together.md): where these requests sit in the whole picture - [Security basics](/docs/security/security-basics.md): SSRF, secrets and exposure --- # Building a UI A UI is a tree of components that turn data into pixels and user actions into events. Agents are good at writing components. They're bad at guessing your design intent, so that's the part you supply. ## You'll be able to - Describe a UI precisely enough that an agent builds what you pictured - Choose a framework, styling approach and component library - Catch accessibility and responsiveness problems in review ## The mental model **UI = f(state).** You describe what the screen should look like for a given state, and the framework updates the DOM when that state changes. Components are functions with **props** (inputs) and sometimes their own **state**. ## Key concepts - **Component:** A reusable piece of UI (`