GyaanStack. Blog

Articles / agentspython

Build an AI coding agent in Python: tools, loop, guards and a test gate

Build a small AI coding agent in Python that reads a repo, edits code and must make failing tests pass. Path and command guards, timeouts, real output.

By Raghunath · · 22 min read

A coding agent is a program that hands a model a few tools (list files, read a file, edit a file, run the tests) and keeps calling the model until the job is done. The model picks the next action. Your code runs it and decides whether the agent is allowed to stop.

This post builds one in about 200 lines of standard-library Python. It fixes a real bug in a toy repo, and it is only allowed to finish when the failing tests pass. Along the way it tries to read a file outside the repo, edit the test instead of the code, run rm -rf ., and declare victory before testing. Each attempt hits a guard, and the output below shows each one being refused.

The model is a scripted fake, so everything here runs with python3 and no API key. A 20-line adapter shows where the real Claude call goes, and you swap it in with one line.

If you want the design at scale (edit formats, repo maps for 40,000-file codebases, permission modes, OS sandboxes, cost per task), read Design an AI coding agent. This post is the build-along that sits under it. If tool calling itself is new to you, start with Function calling in LLMs.

What you are building#

           task: "tests/test_cart.py is failing. Fix the bug."
                                 |
                                 v
     +----------------------> model.next(messages, tools, system)
     |                           |
     |              tool calls?  |  no tool calls ("I'm done")
     |            +--------------+--------------+
     |            v                             v
     |    Workspace runs each call       tests green since last edit?
     |    through its guards:              yes -> stop, return True
     |      path inside repo?              no  -> "run the tests" -> loop
     |      not under tests/?
     |      command on allowlist?
     |      timeout, kill process group
     |            |
     +---- tool_result (or ERROR text) appended to messages

Four files:

File Job
tools.py The Workspace class: list_files, read_file, edit_file, run_tests, and the guards
model.py A next() interface, the scripted fake, and the Claude adapter
loop.py The agent loop with a step cap and the test gate
run_demo.py Copies the toy repo and runs the agent on it

Python 3.9 or newer is needed for Path.is_relative_to. I ran everything on Python 3.15.2 on macOS.

The toy repo, with a real failing test#

shop/cart.py has a bug. The docstring says the discount is a percentage, and the code subtracts it as a flat amount:

def total(prices, discount_pct=0):
    """Sum the prices, then take discount_pct percent off. Rounded to 2 places."""
    subtotal = sum(prices)
    return round(subtotal - discount_pct, 2)

tests/test_cart.py:

import unittest
from shop.cart import total


class TotalTests(unittest.TestCase):
    def test_no_discount(self):
        self.assertEqual(total([100, 50]), 150)

    def test_ten_percent_off(self):
        self.assertEqual(total([100, 50], discount_pct=10), 135.0)

    def test_full_discount_is_free(self):
        self.assertEqual(total([19.99], discount_pct=100), 0.0)


if __name__ == "__main__":
    unittest.main()

Running python3 -m unittest in the repo gives two failures (paths and caret lines trimmed):

F.F
======================================================================
FAIL: test_full_discount_is_free (tests.test_cart.TotalTests.test_full_discount_is_free)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../toy_repo/tests/test_cart.py", line 13, in test_full_discount_is_free
    self.assertEqual(total([19.99], discount_pct=100), 0.0)
AssertionError: -80.01 != 0.0

======================================================================
FAIL: test_ten_percent_off (tests.test_cart.TotalTests.test_ten_percent_off)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../toy_repo/tests/test_cart.py", line 10, in test_ten_percent_off
    self.assertEqual(total([100, 50], discount_pct=10), 135.0)
AssertionError: 140 != 135.0

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (failures=2)

The numbers tell you the bug: 150 minus 10 is 140, and 19.99 minus 100 is -80.01. The right answers are 150 × 0.9 = 135 and 19.99 × 0 = 0. The tests are the spec, and the agent is done when they pass.

Step 1: tools, with the guards inside them#

Put the guards inside each tool. A check that lives in the loop or in the system prompt is easy to bypass the day someone adds a fifth tool and forgets it. Here every path goes through _safe() and every command goes through the allowlist.

"""Tools the agent may call. Every path and command goes through a guard."""
import os, shlex, shutil, signal, subprocess, sys, tempfile
from pathlib import Path

MAX_READ = 20_000          # characters returned by read_file
MAX_OUTPUT = 4_000         # characters of test output kept (the tail)
ALLOWED_COMMANDS = {       # exact argv prefixes the agent may run
    ("python", "-m", "unittest"),
    ("python", "-m", "pytest"),
}


class ToolError(Exception):
    """Raised for a refused or failed tool call. The loop sends the text back to the model."""


class Workspace:
    def __init__(self, root):
        self.root = Path(root).resolve()

    def _safe(self, path):
        # resolve() follows symlinks and "..", so both escapes are caught here
        target = (self.root / path).resolve()
        if not target.is_relative_to(self.root):
            raise ToolError(f"path {path!r} is outside the workspace")
        return target

    def list_files(self):
        skip = {".git", "__pycache__", ".venv"}
        return sorted(
            str(p.relative_to(self.root))
            for p in self.root.rglob("*")
            if p.is_file() and not skip & set(p.relative_to(self.root).parts)
        )

    def read_file(self, path):
        target = self._safe(path)
        if not target.is_file():
            raise ToolError(f"{path} does not exist")
        lines = target.read_text().splitlines()
        numbered = "\n".join(f"{i:4}  {line}" for i, line in enumerate(lines, 1))
        return numbered[:MAX_READ]

    def edit_file(self, path, old, new):
        """Replace exactly one occurrence of `old` with `new`."""
        target = self._safe(path)
        if target.relative_to(self.root).parts[0] == "tests":
            raise ToolError("editing tests is not allowed; fix the code instead")
        text = target.read_text()
        count = text.count(old)
        if count != 1:
            raise ToolError(f"old text found {count} times in {path}; it must match exactly once")
        target.write_text(text.replace(old, new, 1))
        return f"edited {path}"

    def run_tests(self, command="python -m unittest", timeout=20):
        argv = shlex.split(command)
        if not any(tuple(argv[: len(a)]) == a for a in ALLOWED_COMMANDS):
            raise ToolError(f"command not allowed: {command!r}")
        argv[0] = sys.executable  # the interpreter running the harness
        with tempfile.TemporaryDirectory(prefix="agent-run-") as tmp:
            # run on a throwaway copy so a test cannot damage the real checkout
            work = Path(tmp) / "repo"
            shutil.copytree(self.root, work, symlinks=True,  # copy links as links, never their targets
                            ignore=shutil.ignore_patterns(".git", ".venv"))
            env = {"PATH": os.environ.get("PATH", ""), "PYTHONDONTWRITEBYTECODE": "1"}
            proc = subprocess.Popen(argv, cwd=work, env=env, text=True,
                                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                    start_new_session=True)
            try:
                out, _ = proc.communicate(timeout=timeout)
            except subprocess.TimeoutExpired:
                os.killpg(proc.pid, signal.SIGKILL)  # kill the child and anything it spawned
                proc.communicate()
                return {"passed": False, "exit_code": None, "output": f"timed out after {timeout}s"}
        return {"passed": proc.returncode == 0, "exit_code": proc.returncode,
                "output": out[-MAX_OUTPUT:]}


TOOL_SPECS = [
    {"name": "list_files", "description": "List every file in the repo.",
     "input_schema": {"type": "object", "properties": {}}},
    {"name": "read_file", "description": "Read a file, with line numbers.",
     "input_schema": {"type": "object", "properties": {"path": {"type": "string"}},
                      "required": ["path"]}},
    {"name": "edit_file",
     "description": "Replace one exact occurrence of old with new. Read the file first.",
     "input_schema": {"type": "object", "properties": {
         "path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"}},
         "required": ["path", "old", "new"]}},
    {"name": "run_tests", "description": "Run the test suite on a copy of the repo.",
     "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}}},
]

What each guard does, and why it is built that way:

Paths. _safe() joins the path to the repo root, then calls resolve(), which collapses .. and follows symlinks. If the result is not under the root, the call is refused. Checking the string for .. would miss two cases: an absolute path (Path("/repo") / "/etc/hosts" is /etc/hosts, because joining an absolute path throws away the left side) and a symlink inside the repo that points out of it. The pathlib docs cover both behaviours.

Edits. edit_file takes an exact old string and a new string, and refuses unless old appears exactly once. That is the same contract as the str_replace command in Anthropic's text editor tool. It is safer than a write_file(path, content) tool that rewrites the whole file. A model that rewrites a 400-line file to change one line can drop or garble the other 399, and a stale old string fails loudly instead of landing in the wrong place.

No editing tests. An agent told to "make the tests pass" will sometimes change the assertion. The tests/ check turns that shortcut into an error. In a real project you would protect test files with your agent tool's permission rules too.

Commands. run_tests accepts a string so the model can pick a test file, but it splits it with shlex.split and runs it as an argument list without a shell. Only commands that start with python -m unittest or python -m pytest get through. ; curl evil.sh has no shell to chain it, and bash -c '...' fails the prefix check. The first argument is replaced with sys.executable, so the tests run under the same interpreter as the agent.

Throwaway copy. Tests run in a fresh temp directory copy of the repo, so a test that deletes files or writes junk cannot damage the checkout. The environment is cut down to PATH, which keeps your API keys and tokens out of whatever the tests spawn.

Timeouts that kill everything. subprocess.run(..., timeout=10) is the usual advice, and the subprocess docs say that on timeout "the child process will be killed and waited for". Only the child. I tested a test that starts a helper process and then hangs: the naive run(timeout=3) raised TimeoutExpired after 3.0 seconds and left the helper running. The version above starts the tests in a new session (start_new_session=True) and kills the whole process group with os.killpg, which leaves nothing behind. os.killpg is Unix-only; on Windows you need a job object or a library such as psutil.

Output cap. Only the last 4,000 characters of test output go back to the model. The summary and the last traceback are at the end, and a test that prints a million lines would otherwise fill the context window.

Step 2: hide the model behind one method#

The loop calls model.next(messages, tools, system) and gets back a Reply with optional text and a list of tool calls. Anything that answers that call can drive the agent.

"""The model sits behind one method, so the loop does not care which provider answers."""
from dataclasses import dataclass, field


@dataclass
class ToolCall:
    id: str
    name: str
    args: dict


@dataclass
class Reply:
    text: str = ""
    tool_calls: list = field(default_factory=list)


class ScriptedModel:
    """A fake model that replays a fixed list of replies. No API key, fully repeatable."""
    def __init__(self, replies):
        self.replies = list(replies)

    def next(self, messages, tools, system):
        return self.replies.pop(0)


class ClaudeModel:
    """The real call. Pass an anthropic.Anthropic() client; it reads ANTHROPIC_API_KEY."""
    def __init__(self, client, model="claude-sonnet-5-5"):
        self.client, self.model = client, model

    def next(self, messages, tools, system):
        resp = self.client.messages.create(
            model=self.model, max_tokens=4096, system=system,
            tools=tools, messages=messages)
        reply = Reply()
        for block in resp.content:
            if block.type == "text":
                reply.text += block.text
            elif block.type == "tool_use":
                reply.tool_calls.append(ToolCall(block.id, block.name, block.input))
        return reply

ScriptedModel replays a fixed list of replies. It makes the demo repeatable and free, and later it is how you test the loop itself: feed it a script with a bad call in it and check the loop does the right thing.

ClaudeModel is the real call, through the official anthropic SDK (version 2.12.0 on PyPI when I installed it). The tool specs in tools.py are already in Claude's name / description / input_schema shape from the tool use docs. claude-sonnet-5-5 is a current model ID on the models overview page; pick whichever model fits your budget. I did not make a live API call for this post. To check the parsing anyway, I gave ClaudeModel a fake client that returns a real anthropic.types.Message built from a canned response:

"""Feed ClaudeModel a canned SDK Message (no network) to check the parsing."""
from anthropic.types import Message
from model import ClaudeModel

canned = Message.model_validate({
    "id": "msg_1", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5",
    "stop_reason": "tool_use", "stop_sequence": None,
    "usage": {"input_tokens": 900, "output_tokens": 40},
    "content": [{"type": "text", "text": "Checking the code first."},
                {"type": "tool_use", "id": "toolu_1", "name": "read_file",
                 "input": {"path": "shop/cart.py"}}]})

class FakeMessages:
    def create(self, **kwargs):
        print("create() got:", sorted(kwargs))
        return canned

class FakeClient:
    messages = FakeMessages()

print(ClaudeModel(FakeClient()).next([{"role": "user", "content": "hi"}], [], "sys"))
create() got: ['max_tokens', 'messages', 'model', 'system', 'tools']
Reply(text='Checking the code first.', tool_calls=[ToolCall(id='toolu_1', name='read_file', args={'path': 'shop/cart.py'})])

To switch the demo to Claude, replace ScriptedModel(script) with ClaudeModel(anthropic.Anthropic()) and set ANTHROPIC_API_KEY. For OpenAI, write an OpenAIModel.next() that sends the same tools in the function calling format and maps the returned tool calls into ToolCall objects; the loop does not change. A local model through Ollama's tool calling slots in the same way.

Step 3: the loop and the test gate#

"""The agent loop: ask the model, run its tool calls, feed results back, repeat."""
import json
from tools import TOOL_SPECS, ToolError

SYSTEM = """You fix bugs in a Python repo. Read the code and the failing test before editing.
Never edit files under tests/. After every edit, run the tests.
You are done only when run_tests reports passed: true."""


def run_agent(model, ws, task, max_steps=12, log=print):
    messages = [{"role": "user", "content": task}]
    tests_green = False                    # flips on a passing run, off on any edit
    for step in range(1, max_steps + 1):
        reply = model.next(messages, TOOL_SPECS, SYSTEM)

        if not reply.tool_calls:           # the model says it is finished
            if tests_green:
                log(f"[{step}] DONE: {reply.text}")
                return True
            log(f"[{step}] model claimed done, but tests are not green; sending it back")
            messages.append({"role": "assistant", "content": reply.text})
            messages.append({"role": "user", "content":
                             "The tests have not passed since your last edit. Run them and fix the failures."})
            continue

        messages.append({"role": "assistant", "content":
            ([{"type": "text", "text": reply.text}] if reply.text else []) +
            [{"type": "tool_use", "id": c.id, "name": c.name, "input": c.args} for c in reply.tool_calls]})

        results = []
        for call in reply.tool_calls:
            try:
                out = getattr(ws, call.name)(**call.args) if call.name in {
                    s["name"] for s in TOOL_SPECS} else f"unknown tool {call.name}"
                is_error = False
                if call.name == "edit_file":
                    tests_green = False
                if call.name == "run_tests":
                    tests_green = out["passed"]
            except (ToolError, TypeError) as exc:
                out, is_error = f"ERROR: {exc}", True
            text = out if isinstance(out, str) else json.dumps(out)
            log(f"[{step}] {call.name}({json.dumps(call.args)[:70]}) -> {text[:160]!r}")
            results.append({"type": "tool_result", "tool_use_id": call.id,
                            "content": text, "is_error": is_error})
        messages.append({"role": "user", "content": results})

    log(f"stopped: hit max_steps={max_steps}")
    return False

Three parts of the loop do most of the work.

The test gate is the tests_green flag. It turns true only when run_tests reports passed, and any edit turns it false again. If the model stops calling tools while the flag is false, the loop refuses to finish and tells the model to run the tests. Without this, "Done!" from the model ends the run whether or not the code works.

Errors go back to the model as tool results, with is_error: True, instead of crashing the loop. Anthropic's guide to handling tool calls describes this field. A refused path or a stale edit is information the model can act on: it reads the file again or picks another approach.

max_steps is the budget. Twelve steps is enough for this repo. Without a cap, a model that keeps retrying the same broken edit burns tokens until someone notices. The agent engineering cheat sheet lists the other stop rules worth adding (repeat detection, token budget, wall-clock limit).

The message shapes follow the Claude Messages API: the assistant turn carries tool_use blocks, and the next user turn carries one tool_result per call with the matching tool_use_id.

Step 4: run it on the toy repo#

run_demo.py copies toy_repo to work/ and gives the agent a script. The script plays a model that makes every common mistake once before getting it right.

"""Run the agent on a copy of toy_repo with a scripted model (no API key)."""
import shutil, sys
from pathlib import Path
from model import ScriptedModel, Reply, ToolCall
from tools import Workspace
from loop import run_agent

src = Path(__file__).parent / "toy_repo"
work = Path(__file__).parent / "work"
shutil.rmtree(work, ignore_errors=True)
shutil.copytree(src, work)
ws = Workspace(work)

def call(n, name, **args):
    return Reply(tool_calls=[ToolCall(f"t{n}", name, args)])

script = [
    call(1, "list_files"),
    call(2, "run_tests"),
    call(3, "read_file", path="shop/cart.py"),
    call(4, "read_file", path="../../.ssh/id_rsa"),                 # escape attempt
    call(5, "edit_file", path="tests/test_cart.py",                 # cheating attempt
         old="135.0", new="140"),
    call(6, "run_tests", command="rm -rf ."),                       # command not on the allowlist
    call(7, "edit_file", path="shop/cart.py",                       # stale old text
         old="return subtotal - discount_pct", new="..."),
    call(8, "edit_file", path="shop/cart.py",
         old="round(subtotal - discount_pct, 2)",
         new="round(subtotal * (1 - discount_pct / 100), 2)"),
    Reply(text="Fixed the discount math."),                         # claims done before testing
    call(9, "run_tests"),
    Reply(text="total() now takes discount_pct as a percentage; all 3 tests pass."),
]
ok = run_agent(ScriptedModel(script), ws, "tests/test_cart.py is failing. Fix the bug.")
print("\nresult:", "fixed" if ok else "not fixed")
print((work / "shop/cart.py").read_text())
sys.exit(0 if ok else 1)

Real output from python3 run_demo.py:

[1] list_files({}) -> '["shop/__init__.py", "shop/cart.py", "tests/__init__.py", "tests/test_cart.py"]'
[2] run_tests({}) -> '{"passed": false, "exit_code": 1, "output": "F.F\\n======================================================================\\nFAIL: test_full_discount_is_free (test'
[3] read_file({"path": "shop/cart.py"}) -> '   1  def total(prices, discount_pct=0):\n   2      """Sum the prices, then take discount_pct percent off. Rounded to 2 places."""\n   3      subtotal = sum(price'
[4] read_file({"path": "../../.ssh/id_rsa"}) -> "ERROR: path '../../.ssh/id_rsa' is outside the workspace"
[5] edit_file({"path": "tests/test_cart.py", "old": "135.0", "new": "140"}) -> 'ERROR: editing tests is not allowed; fix the code instead'
[6] run_tests({"command": "rm -rf ."}) -> "ERROR: command not allowed: 'rm -rf .'"
[7] edit_file({"path": "shop/cart.py", "old": "return subtotal - discount_pct", "new) -> 'ERROR: old text found 0 times in shop/cart.py; it must match exactly once'
[8] edit_file({"path": "shop/cart.py", "old": "round(subtotal - discount_pct, 2)", ") -> 'edited shop/cart.py'
[9] model claimed done, but tests are not green; sending it back
[10] run_tests({}) -> '{"passed": true, "exit_code": 0, "output": "...\\n----------------------------------------------------------------------\\nRan 3 tests in 0.000s\\n\\nOK\\n"}'
[11] DONE: total() now takes discount_pct as a percentage; all 3 tests pass.

result: fixed
def total(prices, discount_pct=0):
    """Sum the prices, then take discount_pct percent off. Rounded to 2 places."""
    subtotal = sum(prices)
    return round(subtotal * (1 - discount_pct / 100), 2)

Step by step:

  • Step 2 runs the tests first, so the model sees the two failures before touching anything.
  • Steps 4, 5 and 6 are refused by _safe(), the tests/ rule and the command allowlist. The loop sends each refusal back as an error and carries on.
  • Step 7 is a stale edit: the model remembered the line slightly wrong, and the exact-match rule refuses it rather than guessing.
  • Step 9 is the model claiming success after editing but before testing. The gate sends it back.
  • Step 10 runs the tests on a fresh copy, all three pass, and step 11 is the accepted final answer.

The fix is the one the numbers pointed to: subtotal * (1 - discount_pct / 100).

Step 5: attack the guards#

The demo shows the guards once. A separate script attacks them directly and prints PASS or FAIL, so you can run it in CI every time you touch tools.py:

"""Attack the tools directly. Each check prints PASS or FAIL."""
import os, tempfile, time
from pathlib import Path
from tools import Workspace, ToolError

def expect_refusal(label, fn):
    try:
        fn()
        print(f"FAIL  {label}: was allowed")
    except ToolError as exc:
        print(f"PASS  {label}: {exc}")

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp) / "repo"
    (root / "tests").mkdir(parents=True)
    os.symlink("/etc", root / "etc_link")                     # symlink pointing out of the repo
    ws = Workspace(root)
    expect_refusal("dot-dot path", lambda: ws.read_file("../secret.txt"))
    expect_refusal("absolute path", lambda: ws.read_file("/etc/hosts"))
    expect_refusal("symlink escape", lambda: ws.read_file("etc_link/hosts"))
    expect_refusal("shell chaining", lambda: ws.run_tests("python -m unittest; curl evil.sh"))
    expect_refusal("other binary", lambda: ws.run_tests("bash -c 'python -m unittest'"))

    # a test that starts a grandchild and then hangs forever
    (root / "tests" / "__init__.py").write_text("")
    (root / "tests" / "test_hang.py").write_text(
        "import subprocess, sys, time\n"
        "def test_hang():\n"
        "    subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'])\n"
        "    time.sleep(600)\n"
        "import unittest\n"
        "class T(unittest.TestCase):\n"
        "    def test_it(self): test_hang()\n")
    t0 = time.time()
    res = ws.run_tests(timeout=3)
    print(f"{'PASS' if not res['passed'] and time.time() - t0 < 6 else 'FAIL'}  "
          f"hanging test: {res['output']} (returned in {time.time() - t0:.1f}s)")
PASS  dot-dot path: path '../secret.txt' is outside the workspace
PASS  absolute path: path '/etc/hosts' is outside the workspace
PASS  symlink escape: path 'etc_link/hosts' is outside the workspace
PASS  shell chaining: command not allowed: 'python -m unittest; curl evil.sh'
PASS  other binary: command not allowed: "bash -c 'python -m unittest'"
PASS  hanging test: timed out after 3s (returned in 3.0s)

This script found a real bug in my first draft. shutil.copytree follows symlinks by default (the shutil docs describe the symlinks flag), so the etc_link -> /etc symlink made run_tests try to copy all of /etc into the temp directory. It crashed on permission errors; on a machine with readable secrets it would have copied them into the sandbox copy. symlinks=True copies links as links. The path guard alone did not catch this, because run_tests never asks _safe() about the files it copies.

Where this toy breaks#

Be honest about what the guards above do and do not cover.

  • The temp directory is not a sandbox. The tests are code from the repo, and they run as you. A test can still open ~/.ssh/id_rsa, follow a symlink in the copy, or call the network. The allowlist controls which command starts, not what that command does. For untrusted repos, run run_tests inside a container or VM with no network and no home directory mounted. The system design post covers OS-level sandboxes such as Seatbelt and bubblewrap.
  • python -m pytest loads plugins and conftest.py. Any file the agent can edit can run code when the tests start, so the allowlist is weaker than it looks once the agent has edited conftest.py. Block edits to it, or treat every test run as untrusted.
  • A scripted model tests the guards only. The fake shows every guard firing. It says nothing about whether a real model finds the bug. For that, collect 20 or 30 small repos with a known failing test each, run the real model on all of them, and count how many finish green within max_steps and at what token cost. That pass rate is your eval; the agent evals path goes deeper.
  • Tests can be weak. The gate trusts the tests. If the suite only checks that total() returns a number, the agent can pass it with the wrong formula. Read the diff before you merge.
  • One file at a time. edit_file changes one occurrence in one file. Bigger changes need several calls, and a failed call halfway through leaves the repo half edited. Commit or snapshot before each run so you can roll back.

What to add next#

In rough order of value: a search tool (grep over the repo) so the model does not read every file; a repeat guard that stops the run when the same failing call comes back three times; a git snapshot before each edit for undo; and a real model behind ClaudeModel, run against the small eval set described above. Each one is a few lines on top of the Workspace class, and the guard checks keep working as you add them.

Sources#