All courses

Read your coding agent's code

Spot the shortcuts before they cost you.

What coding agents actually do and why, the tells of tests weakened, errors swallowed and APIs invented, and what finished work looks like. Real diffs in Python, TypeScript, Rust, Java and Go.

For developers who use AI coding tools. 75 lessons.

Lessons

  1. A coding agent is a model in a loopExplain the loop: the model proposes an action (read a file, run a command, edit code), a tool executes it, the output is appended to its input, and this repeats until the model decides to stop. Explain why that makes an agent more capable than a chat reply, and also why it can wander.
  2. What the agent sees: its contextList what is actually in the agent's context at a given step: your prompt, instruction files, the files it chose to open and the tool outputs it received. Explain that anything outside that context is invisible to it except through general training knowledge.
  3. What the agent cannot seeName what is usually missing from an agent's context: files it never opened, runtime and production behaviour, real data and its volumes, team decisions and the history of why the code looks the way it does, and the intent you never wrote down. Predict which mistakes follow from each gap.
  4. Why agent output always sounds sureExplain that the model generates fluent, plausible text, so its tone is the same whether it is right or wrong. Explain why its statements about itself ('tests pass', 'this handles all cases') are also generated text, not measurements.
  5. What 'done' means for a changeState the criteria for a finished change: it does what was asked, there is evidence it works, it breaks nothing else, it fits the codebase's conventions, it is small enough to review and it hides nothing. Contrast this with 'the agent stopped and said it's done'.
  6. You own every line the agent writesAdopt the stance of reviewing a pull request from a very fast contributor who is not accountable for the result: you sign off, so you answer for it. Explain why generating code is now cheap while review has become the bottleneck, and why evidence must outrank claims.
  7. Test doubles: stubs, fakes, mocks and spiesDistinguish the four kinds of test double: stubs return canned answers, fakes are working lightweight implementations, mocks verify interactions and spies record calls. Say what each kind lets a test verify, and what it lets a test silently skip.
  8. What makes a test able to failExplain a test as inputs plus an oracle, the expected result. The oracle must come from the specification rather than from the code under test. A test that cannot go red when the code is wrong proves nothing.
  9. Error handling idioms across languagesCompare exceptions (Python, Java checked and unchecked, JS/TS), Result/Option with ? (Rust) and error values (Go). For each, say where an error should be handled versus propagated and what 'ignoring' an error looks like.
  10. Race conditions and interleavingsExplain how concurrent code can interleave and produce wrong results, using check-then-act and read-modify-write as examples. Distinguish a data race from a logical race, and explain why only synchronization (locks, atomics, channels) creates ordering while timing does not.
  11. What awaiting actually doesExplain promises, futures and coroutines and what happens when one is never awaited. In Python the coroutine never runs. In Rust the future is lazy and does nothing. In JS/TS the work runs but its failure goes unobserved and ordering is lost.
  12. Trust boundaries and untrusted inputIdentify where data crosses from an untrusted source (users, network, files, third parties) into your code. Explain that injection bugs come from treating that data as code or commands, and that the defence is to validate and encode at the boundary.
  13. The agent knows only what its tools returnedExplain that if the agent did not run the test, it has not seen it pass. Show how truncated output, the wrong working directory or a stale build can mislead it. Read a transcript to tell claims backed by tool output apart from unbacked assertions.
  14. Why agents fill gaps with plausible guessesExplain that when information is missing, the model tends to produce the most typical continuation instead of stopping to ask. Its guesses therefore match common patterns from public code, not your codebase's helpers, conventions or constraints.
  15. Training cutoff and API driftExplain that a model's library knowledge is frozen at training time and blended across versions. It therefore defaults to whatever was most common in its training data, not to the version in your lockfile. Predict when this will bite (fast-moving libraries, recent major versions) and how to counter it: state the versions, and point the agent at the installed docs, type definitions or the lockfile.
  16. Agents optimise the signal they can seeExplain that 'make the tests pass' or 'make the error go away' is only a proxy signal, and the shortest path to satisfying it may defeat the real goal. This is specification gaming, and it is the root of most shortcut tells.
  17. Agents tend to agree with youExplain sycophancy: models adopt your stated premise, cave to pushback with 'You're right!' even when you are wrong, and rationalise the hypothesis you suggested. Predict when a leading question will steer the agent to a wrong fix.
  18. Long sessions: lost instructions and driftExplain how a filling context weakens attention to early constraints, how summarising or compacting the context can drop them, and how a pile of failed attempts pollutes later reasoning. Recognise drift when the agent starts violating rules it followed at the start.
  19. Making a failing test pass by weakening itSpot the forms in a diff: loosened assertions, an expected value edited to match buggy output, deleted tests, and skips (pytest.mark.skip/xfail, #[ignore], @Disabled, it.skip). Explain the later cost: the bug ships and the suite now vouches for it.
  20. Hardcoding the answer the test expectsRecognise code that branches on the exact fixture input, returns a canned expected value or detects that it is running under test. Explain why it passes the suite yet fails on the first real input.
  21. Errors swallowed by catch-all handlersSpot `except Exception: pass`, an empty `catch (e) {}`, Java's `catch (Exception e) { e.printStackTrace(); }`, Go's `_ = err` or `if err != nil { return nil }`, and Rust's `.ok()` discarding errors. Explain the later cost: failures become invisible and state is left half-updated.
  22. Silent fallbacks that hide bugsRecognise defaults that turn a loud failure into quietly wrong data: `unwrap_or_default()`, `?? ""`, `getOrDefault`, `dict.get(k, 0)`, returning [] on a parse error. Decide when a default is genuinely correct and when the code should fail or propagate the error instead.
  23. Silencing the checker: type escapes and suppressionsSpot the escape hatches that silence the compiler or linter instead of fixing the problem: `any`, `as`, non-null `!` and `@ts-ignore` in TS; `# type: ignore` and `cast` in Python; `@SuppressWarnings("unchecked")` in Java; `any`/`interface{}` in Go; `unsafe`; and `eslint-disable`, `//nolint`, `#[allow]`. Explain which guarantee each one removes.
  24. Rust tells: unwrap, clone and RefCell to appease the compilerRecognise Rust-specific shortcuts: `.unwrap()`/`.expect()` on fallible paths, `.clone()` scattered to dodge borrow errors, and `Rc<RefCell<_>>` or `Arc<Mutex<_>>` used where ownership needed redesigning. Explain the panics and runtime borrow failures these trade for a clean compile.
  25. Invented APIs, flags, config keys and packagesRecognise idiomatic-looking calls to methods, CLI flags, config options or packages that do not exist or belong to a different version: removed APIs, old import paths, options the installed version lacks. Check cheaply that each one exists, using the compiler, the docs, `--help` or the registry.
  26. Patching the symptom instead of the causeSpot fixes applied where the error surfaces rather than where it originates: a null check at the crash site, a special case for the failing input, a catch around the throwing line. Explain why the error disappears but the cause keeps producing bad results.
  27. Sleeps, retries and longer timeouts as 'fixes'Recognise a race 'fixed' with a sleep, a flaky call wrapped in a retry loop, or a raised timeout. Explain why these pass locally and in CI but fail under load or on slower machines, and what a real ordering fix looks like.
  28. Duplicating code instead of reusing itSpot a new helper, validator or client that duplicates one already in the codebase that the agent never opened. Explain the later cost when the copies diverge, and when merging the copies would instead create the wrong abstraction.
  29. Overbuilt code: speculative abstraction and defensive clutterSpot code bigger than the task needs: interfaces, factories or config options with one user, generic frameworks for a single case, and redundant null checks and try/catch on paths that cannot fail. Explain the later cost: more code to maintain, contracts blurred by defensive checks, and real bugs hidden in noise. Name the simpler version.
  30. Scope creep and unasked-for changes in a diffRecognise drive-by reformatting, renames, refactors, new abstractions, config tweaks and dependency bumps mixed into the requested change. Explain how they hide the real change, raise risk and make review and revert harder.
  31. Placeholders passed off as implementationsSpot code that only looks finished: TODOs, `pass`, `NotImplementedError`, `todo!()`, hardcoded sample data, or a mock left on the production path, all while the summary says 'implemented'. Search for these patterns before accepting a change.
  32. A confident summary that doesn't match the diffCheck the agent's summary claims ('added tests', 'handled edge cases', 'all tests pass') against the actual diff and the tool output in the transcript. Treat any claim that has no matching diff hunk or command output as unverified.
  33. Happy-path code: the edge cases it skippedProbe agent code for the structural inputs it typically ignores: empty collections, None/null/nil and missing keys, zero and negative values, and off-by-one boundaries on ranges, slices and pagination. Predict which of these a given function will mishandle, and write the one test that would show it.
  34. Text, time and money: classic data trapsSpot agent code that is wrong for real-world data: string length, slicing or case-folding that breaks on non-ASCII text, naive datetimes and DST or time-zone shifts, and floating-point arithmetic for money. Name the safe type or library in each language (for example Decimal or BigDecimal, integer cents, zone-aware datetimes).
  35. Fine on test data, broken at scaleRecognise code that passes small tests but fails on production volumes: N+1 queries from ORM calls inside loops, unbounded queries with no pagination, reading whole files or tables into memory, quadratic list lookups in loops, and regexes prone to catastrophic backtracking. Explain why the agent cannot see this coming, and which check (query log, profile, large fixture) exposes it.
  36. Unawaited async work and floating promisesanimatedSpot a missing `await`, a fire-and-forget call, `forEach` with an async callback, or a Python coroutine or Rust future that is created but never driven to completion. Explain the result in each language: work never runs, runs out of order, or fails silently.
  37. Leaked resources: files, connections, goroutinesSpot files, connections and locks opened without `with`, try-with-resources or `defer`, as well as `defer` inside loops, goroutines blocked forever and contexts never cancelled. Explain why these pass tests but exhaust resources in production.
  38. Races introduced by plausible concurrent codeRecognise races that look fine on the page: a Go map written from goroutines, unsynchronized lazy initialisation in Java, check-then-act on a cache, and async read-modify-write in JS. Name which tool or synchronization would catch or fix each one.
  39. Retrying operations that aren't idempotentSpot retry loops the agent wrapped around payments, POSTs, emails or queue publishes. Explain how they cause duplicates when the first attempt actually succeeded but its response was lost, and how an idempotency key or deduplication makes the retry safe.
  40. Half-finished changes: the call sites it missedRecognise a rename, signature change or semantic change applied only in the files the agent read, while other callers, reflection or string references, configs, docs and other services still use the old form. Check for missed sites with search and the compiler.
  41. Refactors that quietly change behaviorSpot 'pure cleanup' that changes behaviour: reordered side effects, a different error type, lost short-circuit evaluation, changed iteration order or null handling. Explain why callers who depend on that old behaviour break.
  42. Mocks that test nothingRecognise tests that mock the unit under test, assert that a mock returned what it was configured to return, or check only that calls happened without checking any outcome. Rewrite such a test to exercise real logic, using fakes where possible.
  43. Tests that restate the implementationSpot tests whose expected value is computed with the same formula as the code, snapshots that freeze current buggy output, and assertions that check only 'not null' or 'no exception thrown'. Explain why these stay green when the logic is wrong.
  44. See it fail: red before green and break-it checksConfirm a new test is red without the fix and green with it. Temporarily break the code to check that the suite catches the break, which is the core idea of mutation testing.
  45. Verify by running, not by reading claimsReproduce the original bug, then run the build, the relevant tests and the real scenario yourself, or require the agent to show the exact commands and their output. Decide which checks a given change needs before you accept it.
  46. Pin behavior before a refactorWrite characterization tests that capture what existing code currently does before letting an agent refactor it. Use them to catch unintended behaviour changes that the agent's own new tests would miss.
  47. Let the toolchain check firstLean on strict type checking, linters, race detectors, the full test suite and CI as cheap, impartial checks before human review. Confirm the diff did not loosen their configuration or add suppressions to get them green.
  48. String-built SQL, shell commands and HTMLSpot injection risks in agent code: f-string or concatenated SQL, `shell=True` or `exec` with interpolated input, and `innerHTML` or unescaped templates. Replace each with parameterised queries, argument arrays or safe encoding.
  49. Secrets in code, logs and commitsCatch hardcoded keys added 'to make it work', tokens written to logs or error messages, committed .env files and credentials pasted into test fixtures. Remember that any secret the agent reads enters its context and can resurface. Once a secret has been committed, rotate it: deleting it from the code is not enough.
  50. Security checks switched off to make it workRecognise protections turned off to get past an error: `verify=False`, Go's `InsecureSkipVerify`, Node's `rejectUnauthorized: false`, `Access-Control-Allow-Origin: *`, disabled CSRF protection and `chmod 777`. Explain the attack each one opens up.
  51. Endpoints that authenticate but don't authorizeSpot new endpoints or queries that check who the caller is but not whether they may access this record (insecure direct object references). Explain why agents copying a nearby handler often miss ownership checks that are enforced elsewhere in the codebase.
  52. Vetting a dependency the agent addedFor each new package, check that it is needed, that it exists under exactly that name (guarding against hallucinated or typosquatted names), and that it is maintained, pinned and licensed acceptably. Review what it does to the lockfile and the transitive dependency tree.
  53. Untrusted text can steer the agentExplain that instructions hidden in files, web pages, issues, READMEs or tool output enter the agent's context, and the agent cannot reliably tell data from commands. Predict what an injected instruction could make an agent with your permissions do.
  54. Limiting what the agent can breakSet up safeguards that bound the damage an agent can do: sandboxes or containers, no production credentials, separate branches or worktrees, and approval gates for destructive commands such as `rm -rf`, `git push --force`, `git reset --hard` and database migrations. Match the agent's permissions to how much you trust the task.
  55. Triage a diff: where to look firstReview in risk order: reread the task, then check changed or deleted tests, config, CI and dependency files, error paths and security-sensitive code, and compare the diff's size to the task's size. Decide how deep to review based on the risk.
  56. A clean, focused changeRecognise a mergeable change: one purpose per commit, no debug prints, commented-out code, dead helpers or stray files, it follows the codebase's conventions, and the commit message explains why the change was made.
  57. An honest report: what was verified and what wasn'tExpect, and ask for, a report that lists the commands run with their results, what is still untested, the assumptions made, open questions and known limitations. Recognise a report that overclaims compared with one you can rely on.
  58. Choose what to hand to an agentJudge how well a task fits an agent on four axes: how cheaply the result can be verified, how much unwritten context it needs, how reversible it is and how security-critical it is. Delegate well-specified, checkable, local work. Keep, pair on or split ambiguous, cross-cutting or high-stakes changes.
  59. Write a task the agent can finishWrite tasks that state the goal and the reason for it, the constraints, the non-goals and checkable acceptance criteria. Point out which ambiguities in a vague request would force the agent to guess.
  60. Give the context it can't findPoint the agent at the relevant files, existing helpers, examples to imitate, conventions, library versions and the commands for building and testing, and keep durable rules in a project instruction file. Explain which blind spot each piece of context closes.
  61. Size tasks so each step is checkableSplit work into small vertical slices, one concern per run, reviewed and committed between steps. Explain why large tasks produce drift, huge diffs and hidden shortcuts.
  62. Ask for a plan before codeHave the agent explore and propose a plan, listing the files it will touch, its approach and its assumptions, before it edits anything. Correct wrong assumptions at the plan stage, where they are cheap to fix.
  63. Give it an executable definition of doneProvide or first agree on a failing test or reproduction script that the agent works against, and protect that test from being edited. Explain why this narrows how far the agent can game the proxy signal.
  64. Rule out shortcuts explicitlyState the rules up front: do not modify or skip tests, add no new dependencies or suppressions, and stop and report when blocked instead of working around the problem. Then check the diff for compliance, because stated rules can still be broken.
  65. Feedback with evidence, asked neutrallyGive feedback as exact errors, outputs and reproduction steps instead of 'still broken'. Ask for a diagnosis before a fix, and phrase questions so they do not lead the agent toward your guess.
  66. When to stop, reset or take overRecognise a session going bad: the agent repeats a failed fix, the diff keeps growing, suppressions pile up or it contradicts itself. Then revert to a clean commit, start a fresh session with a distilled summary, or do the change yourself.
  67. Predict what an agent will do and whyGiven a task, its context and the available tools, predict where the agent will guess, which proxy signal it will chase, where it will drift and which claims it cannot back with evidence. Explain each prediction from the agent loop and context mechanics.
  68. Spot shortcut tells and name their later costRead agent code in any of the five languages and identify shortcuts: weakened tests, hardcoded answers, swallowed errors, silent fallbacks, type escapes, Rust unwraps and clones, timing band-aids, duplication, overbuilt code, placeholders and symptom patches. For each, state the concrete damage it will do after merge.
  69. Catch plausible-but-wrong codeFind bugs in code that compiles, reads well and passes its tests: skipped edge cases, text, time and money traps, scale problems, unawaited async work, leaked resources, races, unsafe retries, missed call sites, behaviour-changing refactors and invented APIs. Choose the check that would expose each one.
  70. Verify an agent change instead of trusting itFor a given change, build a short verification plan: reproduce the problem, see the tests fail and then pass, judge whether the tests could catch a real bug, pin behaviour before refactors and run the toolchain checks. Explain what evidence each step gives you.
  71. Review agent work for security and supply-chain riskCheck an agent change and session for injection, leaked secrets, disabled protections, missing authorization, risky new dependencies, prompt-injection exposure and excessive permissions. Rank the findings by impact.
  72. Review an agent diff fast and wellReview an agent diff in minutes. Triage by risk, read the test changes first, separate unrelated changes, reconcile the summary with the diff and run the decisive check yourself. End with a clear accept, change or reject decision and the reasons for it.
  73. Decide whether agent work is finished and trustworthyJudge a change against the definition of done: real implementation with no placeholders, every call site updated, the toolchain green without suppressions, a clean focused diff and an honest report. Name exactly what is missing before it can merge.
  74. Set up a task an agent can finish wellDecide whether and how to delegate a real request, then turn it into a well-sized task: a clear goal and acceptance test, the right context, a plan step, explicit guardrails and small checkable increments. Explain which failure mode each element prevents.
  75. Steer a running agent sessionWhile an agent works, give evidence-based and neutral feedback, check its claims against tool output, notice drift or looping early, and decide whether to redirect, reset with a fresh session or take over yourself.