Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🚧 Day 2: Inspect a Workspace

Day 1 built a loop around a fake workspace. The model could request a tool, the loop could return an observation, and the model could finishβ€”but no tool looked at a real project.

Day 2 adds the smallest useful workspace: two read-only tools that let the model list a directory and read a text file. This makes the complete cycle visible without mixing in approval, edits, commands, or durable receipts.

model requests list_files
          |
          v
 Workspace checks the path
          |
          v
 loop returns the listing
          |
          v
 model requests read_file
          |
          v
 loop returns the file text
          |
          v
 model returns a final answer

The Teaching Boundary

Use these tools with a trusted operator and a disposable local repository. Path.resolve() containment and symlink refusal prevent ordinary path mistakes, but they are not a sandbox or a defense against a hostile filesystem. The tool result also becomes model input, so do not point the workspace at files you would not send to the model.

Day 3 adds operator-approved edits, one allowlisted validation command, and a simple receipt log. Keeping those effects out of Day 2 lets you first see the read-only agent loop clearly.

Files and Public Surface

The published starter is the cumulative Day 9 declaration scaffold. Receipt, checkpoint, compaction, and later modules are therefore visible already, but their implementation work belongs to later chapters. Day 2 owns only the workspace relationships below.

Implement the TODO bodies in:

FilePublic namesResponsibility
src/tiny_llm/agent/workspace.pyToolPolicy, WorkspaceBound one directory and expose list_files plus read_file.
src/tiny_llm/agent/__init__.pyDay 1 API plus ToolPolicy, WorkspaceComplete the Day 2 exports within the final scaffold.

The Day 2-owned prefix of ToolPolicy has three fields, in order:

root: Path
max_file_bytes: int = 64 * 1024
max_list_entries: int = 200

Day 2 implements this prefix of Workspace:

  • available_tools, always {"list_files", "read_file"};
  • resolve_path(raw, must_exist=True);
  • list_files(raw=".");
  • read_file(raw); and
  • execute(action).

The starter declarations are the contract. Do not implement or depend on the visible write, command, approval, receipt, checkpoint, compaction, steering, evaluation, branching, or evidence-retrieval declarations yet.

Task 1: Normalize One Workspace Root

ToolPolicy receives the directory the agent may inspect. Convert it to a resolved Path, require an existing directory, reject a symlink root, and require both numeric limits to be positive.

Normalizing once keeps every later check relative to the same root:

policy = ToolPolicy(Path("demo-project"))
workspace = Workspace(policy)

Task 2: Resolve Ordinary Relative Paths

resolve_path() accepts a non-empty relative path and returns its resolved location under policy.root. Reject:

  • absolute paths and .. traversal;
  • symlinked path components;
  • .git, .env, .ssh, .aws, and common credential or private-key names;
  • missing paths when must_exist=True; and
  • any resolved path outside the workspace.

Return a recoverable AgentError for these cases. The agent loop can turn that error into an observation instead of crashing.

This is deliberately an ordinary local-repository boundary. A different process can still race filesystem checks; defending against a hostile filesystem is outside this course checkpoint.

Task 3: List One Directory

list_files() lists direct children in sorted order. Emit one line per visible regular file or directory:

file README.md
dir src

Omit protected names, symlinks, and special files. Stop after max_list_entries lines. Return (empty directory) when no visible entry remains.

The tool is intentionally not recursive. The model can request another list_files action for a directory it wants to inspect.

Task 4: Read One Text File

read_file() accepts a visible regular file no larger than max_file_bytes. Read its bytes and decode UTF-8. Reject directories, oversized files, invalid UTF-8, protected paths, and symlinks with AgentError.

The size bound keeps a single observation from consuming the whole context window. Later checkpoints can add more deliberate context selection; Day 2 only needs one obvious limit.

Task 5: Turn Failures into Observations

execute() dispatches a parsed ToolAction to list_files or read_file. It returns successful text directly. A recoverable failure becomes a string beginning with error: so run_agent() can append it to the conversation and let the model choose another action.

A known future tool such as write_file is still disabled on Day 2. The system prompt describes only workspace.available_tools, and parse_action() checks that enabled set before dispatch.

Task 6: Run the Read-Only Cycle

The checkpoint uses a scripted model so it is deterministic and does not load weights:

responses = iter([
    '{"tool":"list_files"}',
    '{"tool":"read_file","path":"README.md"}',
    '{"final":"README says hello"}',
])

result = run_agent(
    "inspect the project",
    lambda messages: next(responses),
    workspace,
)

Inspect result.events: the first two events contain the parsed tool actions and exact observations, and the third contains the final answer. The same tool result appears in the next model input as Tool result:\n....

Run the Day 2 Checkpoint

From the repository root, run the cumulative learner checkpoint:

pdm run test --week 4 --day 2

Before you implement the TODOs, the implementation-dependent cases across eight task groups are expected to fail. The command force-refreshes the supplied learner tests for Days 1 and 2, then runs both; completed Day 1 behavior should remain green. During course development, check the supplied implementation with the day-local maintainer command:

pdm run test-refsol --week 4 --day 2

The course-code guard compares the starter and reference public signatures, dataclass fields, package exports, and solution-free method bodies.

Inspect the Supplied Fixture

From the checkout root after repository setup and pdm run build-ext-ref, run the scripted reference fixture.

PDM_CHECK_UPDATE=false pdm run --skip pre_run agent -- --autoreject-fixture

It starts in a fresh temporary directory containing only app.py. Look for listed and read in its JSON report to see the first two observations. The script continues with the fixed Day 3 edits and byte check. Run the Day 2 checkpoint tests to check your own implementation.

Try a Cached Week 2 Model

The guarded interactive command starts with the same greeting file. The Week 2 engine reads its cached weights and uses the Day 1 generate_response() helper with a fresh growing cache for each response. The guarded example uses the supplied implementation. For a manual run with your completed Weeks 1–2 and Day 1–2 code, pass --root and a task to the CLI.

On macOS with Apple Silicon, download the Qwen3-4B weights during setup.

pdm run hf download Qwen/Qwen3-4B-MLX-4bit

Run the inspection from the checkout root. The fixture loads existing local weights and exposes only list_files and read_file in its temporary workspace.

PDM_CHECK_UPDATE=false pdm run --skip pre_run agent -- --inspect-fixture \
  --model qwen3-4b

Look for action> ... "tool": "read_file", the following observation> with the source text, then fixture> observed the expected app.py bytes and finished>. A final answer before the read exits with an error. If the local weights are missing, run the download command and retry.

Checkpoint

Confirm that the deterministic run listed a directory, read exact UTF-8 file contents, returned recoverable path errors to the model, and completed without enabling any effect tool.

When this checkpoint is green, continue to Day 3: Edit, Validate, and Record.

After all nine days are complete, the supplied deterministic capstone composes this read-only inspection with checkpointing, compaction, steering, evaluation, branching, and bounded evidence. That orchestration is a separate week4-capstone command, not part of the real-model agent CLI.

Your feedback is greatly appreciated. Join our Discord community.
Found an issue? Open an issue or pull request at github.com/skyzh/tiny-llm.
tiny-llm-book Β© 2025 by Alex Chi Z is licensed under CC BY-NC-SA 4.0.