Most "AI agent" frameworks hide what is happening behind layers of abstraction. I wanted the opposite: a personal assistant where I can open every file, see every prompt, and explain every decision it makes.

The result is Personal AI: roughly 1,700 lines of Python that give a language model three things:

  • a job (an "agent": a short JSON file with instructions),
  • tools (22 plain Python functions called "skills"),
  • a memory (markdown files that grow as the assistant is used).

The one rule that shapes everything: the model proposes, Python disposes. The model never touches the network, the disk or your inbox. It can only emit text. Python reads that text, decides whether it is allowed, and only then does something.

The assistant also starts out knowing almost nothing, on purpose. Its system prompt says it must not rely on general world knowledge; it may trust only (1) its memory, (2) what its skills return, and (3) what you tell it. If it cannot find something out, it says "I don't know yet". That makes its behaviour auditable: every claim traces back to a file, a web page, a database row or something you said.

Full code: github.com/rash-aad/personal_ai.

Big picture diagram of Personal AI: the six layers from the command line interface down to the external systems it can reach

The Big Picture: Six Layers

  1. Interface — pai.py, installed as the console command pai. Commands include run, chat, index, search, approvals, approve, reject, agents, show, revert, create-agent, delete-agent, teach, memory, rules, log.
  2. Orchestration — runner.py runs the think → act → observe loop. agents.py loads, validates and backs up agents.
  3. Model access — llm.py. The only place the model is called. It runs the Claude CLI in print mode with every built-in tool and every user setting disabled.
  4. Capabilities — skills.py. 22 plain functions in one dictionary.
  5. State — memory.py (markdown), index.py (SQLite search), approvals.py (a JSONL queue). All plain files.
  6. Integrations — mcp.py plus connectors/. Email and the business database run as separate processes that speak the Model Context Protocol (JSON-RPC over stdin/stdout).

External systems it can reach: the Claude CLI (the model), Ollama (optional, local embeddings), DuckDuckGo and web pages, Gmail (IMAP/SMTP) and a local SQLite file.

What Is An "Agent" Here?

In this project an agent is not a class or a process. It is a JSON file in agents/. For example, the reader agent is essentially:

{
  "name": "reader",
  "description": "Reads .txt, .md and .pdf files and answers ...",
  "skills": ["read_txt", "read_pdf"],
  "instructions": "You are the reading agent. When the user mentions a file, open it with read_txt or read_pdf first..."
}

Four fields:

FieldWhat it does
nameWhat you type: pai run reader "..."
descriptionWhat the dispatcher reads to decide who fits a task
skillsThe allowlist: the only tools this agent may call
instructionsThe agent's personality and procedure (its system prompt); an optional max_steps overrides the default of 8

Two agents with the same code behave differently because their JSON is different. The eight agents that ship with the project:

AgentSkillsJob
browserweb_search, fetch_urlFinds facts on the public web
readerread_txt, read_pdfReads and summarises local files
writerwrite_file, read_txtDrafts text and saves it to files
businesssearch_docs, db_schema, db_query, email_search, email_read, email_send, write_fileThe "company assistant": answers from indexed documents, queries the database, handles mail (10 steps allowed)
plannerlist_agents, delegateNever works itself; splits a task and hands the pieces to other agents (12 steps allowed)
trainer9 self-management skillsEdits rules, agents and memory
chatnoneSmall talk
codernoneWrites code and reasons through its output

Because an agent is just a file, creating or editing one is just writing a file. And because a skill is only available if it is in the list, giving an agent less power is as simple as deleting a word.

One Run, Step By Step (The Agent Loop)

Diagram of the agent loop: load the agent, build the prompt, ask the model, parse the reply, guard checks, run the skill, observe, repeat until an answer or the step budget runs out, then learn and log

You type:

pai run business "What does the Q3 contract say about refunds?"

Here is exactly what happens, in order.

  1. Load the agent. agents.get("business") reads agents/business.json and fills in defaults for missing keys.
  2. Build the system prompt. runner.system_prompt() assembles, from scratch on every run:
    • the base rules (you know nothing; trust only memory, skill results and the user; reply with exactly one JSON object),
    • the agent's instructions,
    • standing rules from memory/rules.md (apply to every agent),
    • the brand guide from memory/brand.md,
    • memory: facts recalled for this task,
    • the list of skills this agent may call, each with its description and argument names.
  3. Ask the model. llm.ask() sends the prompt plus the transcript so far. The first transcript is just TASK: ....
  4. Parse the reply. The model must answer with one JSON object, either {"thought": "...", "skill": "search_docs", "args": {...}} to use a skill, or {"thought": "...", "answer": "..."} to finish. _parse() strips code fences and grabs the first {...} block. If the text is not valid JSON, the raw text simply becomes the final answer.
  5. Guard checks (all of them are listed further down). A skill request is only a proposal. Python checks that the skill is on this agent's list, that this exact call was not already made in this run, and whether the skill needs human approval.
  6. Run the skill. skills.run() calls the Python function. Any exception is caught and turned into a string beginning with error:. The model never sees a stack trace crash the program; it sees text it can react to.
  7. Observe. The result (clipped to 12,000 characters) is appended to the transcript as YOU CALLED: {...} and RESULT: ..., and the loop goes back to step 3 with the longer transcript.
  8. Stop. The loop ends when the model answers, or when the step budget (8 by default) is used up. In that case the runner returns "I ran out of steps before finishing" plus what was gathered.
  9. Learn. If learning is on, a second model call decides what is worth remembering (see the memory section).
  10. Log and return. One JSON line is appended to logs/runs.jsonl (time, agent, task, each skill used, answer, what was learned) and the answer is printed.

Notice how much the model is not trusted with: it does not choose the tools it has, it cannot repeat itself forever, it cannot take actions outside its allowlist, and it cannot run flagged skills at all.

How The Model Is Called (llm.py)

The whole model integration is one function. It shells out to:

claude -p --tools "" --setting-sources "" --output-format json \
       --system-prompt "<the prompt>" "<the transcript>"
  • --tools "" switches off Claude Code's built-in tools (file editing, shell, web). The model can only return text.
  • --setting-sources "" ignores CLAUDE.md files and user settings, so the model sees only the prompt this project built.
  • --output-format json returns an envelope the code can parse.

An optional PAI_MODEL environment variable adds --model. A failure (missing CLI, non-zero exit, timeout, error flag in the reply) raises LLMError; ask() retries twice with 2 s then 4 s backoff and a 300 s timeout per call.

Why wrap a CLI instead of an SDK? It keeps the project dependency-free (the only Python dependency is pypdf), and every model call in the whole system funnels through about 50 lines.

Web Search: The Exact Path

Diagram of the web search path: the model asks for web_search, Python queries DuckDuckGo, a regex extracts results, then the model picks a link and fetch_url strips the page to plain text

Agent: browser (skills web_search and fetch_url). Task: pai run browser "What does example.com sell?"

  1. The model replies {"skill": "web_search", "args": {"query": ...}}. It has no browser. All it did was ask.
  2. The runner checks the allowlist, the repeat set and the approval flag. All pass.
  3. skills.web_search() builds https://html.duckduckgo.com/html/?q=<query>.
  4. skills._get() sends the request with urllib: browser-like User-Agent and Accept-Language headers, gzip/deflate accepted and decoded, 30-second timeout.
  5. DuckDuckGo returns a plain HTML page. There is no JavaScript engine, no cookies and no login session in this project, so JavaScript-heavy sites will not render.
  6. A regular expression extracts up to 8 results, each as title, link and snippet. DuckDuckGo wraps links in a redirect; the real target is unwrapped from the uddg parameter. The list is appended to the transcript as RESULT.
  7. The model is called again and reads the results.
  8. It chooses a link and asks for fetch_url. The same guards run.
  9. _get() downloads that single page.
  10. _strip_html() removes script/style/noscript blocks and all tags, decodes HTML entities and collapses whitespace. The remaining plain text (clipped to 12,000 characters) becomes the RESULT.

The model then answers from that text only. Because the prompt forbids using world knowledge, an answer like "example.com is a placeholder domain" is traceable to the page that was fetched.

Failure behaviour: a network error, bad URL or timeout is caught by skills.run() and returned as error: .... The model can try another link or say that it could not find out.

Files: Reading, PDFs And Writing

Diagram of file handling: path resolution, read_txt, read_pdf, list_files and write_file, with every result clipped to 12,000 characters

There is no upload feature, and that is deliberate. Agents work on paths on your own disk; nothing leaves the machine except text that ends up in a prompt to the model.

Path resolution (skills._path):

  • an absolute path is used as given,
  • a relative path is looked up in the project root first; if it is not there, in workspace/,
  • a ~ is expanded to your home directory.

Skills:

  • read_txt reads any text-like file (txt, md, code, csv...) with errors="replace" so odd bytes never crash it.
  • read_pdf uses pypdf's PdfReader and extract_text() page by page, prefixing each page with --- page N ---. It extracts the text layer only: a scanned PDF with no text layer returns empty pages, because there is no OCR.
  • list_files lists a directory, folders first, hidden entries skipped, so the model can discover the right filename. It is in the registry, but none of the eight shipped agents has it on their list yet, so you would add it to an agent first.
  • write_file writes text to a path. Relative paths go to workspace/, missing parent folders are created. It returns wrote N chars to <path>.

Every read result is clipped to 12,000 characters (...[truncated, N chars total]). That is fine for a note or a short PDF, but too small for a 200-page contract. For big documents the right tool is document search (next two sections), which finds the relevant passages instead of dumping the whole file into the prompt.

Typical use:

pai run reader "summarise ~/docs/report.pdf"
pai run writer "write a one-page summary to summary.txt"   # -> workspace/summary.txt

Document Search, Part 1: Building The Index

Diagram of index building: walk folders, skip unchanged files, extract text, chunk with overlap, embed with Ollama, store in SQLite

pai index --add ~/docs/contracts     # register a file or folder and build
pai index                            # update the index later

What index.build() does:

  • Walk. Registered folders are scanned recursively. Hidden folders, .git, venv, node_modules and similar are skipped; only known file types are kept (pdf, docx, pptx, xlsx, txt, md, markdown, csv, json, py, html, rst).
  • Skip unchanged. If a file's modification time equals the one stored in the database, it is not re-processed. Re-running is cheap.
  • Extract text with standard-library code (except PDF, which uses pypdf):
    • PDF: pypdf, page by page
    • DOCX: a zip file; paragraphs parsed out of word/document.xml
    • PPTX: a zip file; text of each slide, labelled --- slide N ---
    • XLSX: a zip file; shared strings and cells, one tab-separated line per row
    • text: read directly
  • Chunk. The text is cut into pieces of 1,200 characters with 200 characters of overlap, preferring to cut at a newline or sentence end so a chunk is not cut mid-thought. Overlap means an answer that straddles a boundary still appears whole in one chunk.
  • Embed. Each chunk is sent to a local Ollama server (model nomic-embed-text) as search_document: <chunk>, in batches of 32, and the vector is normalised to length 1. If Ollama is not running, the chunk is stored without a vector and search degrades gracefully to keyword-only.
  • Store. SQLite file index/index.db with two tables: docs(path, mtime, title) and chunks(id, path, ord, text, vec BLOB), the vector stored as float32.
  • Clean up. Files that no longer exist on disk are removed from the index on the next build.

Document Search, Part 2: Finding The Answer

Diagram of hybrid search: BM25 and vector search each return a top 40, reciprocal-rank fusion merges them into 20 candidates, and the model reranks to the final passages

Agent: business, skill: search_docs.

Why two search methods? Keyword search (BM25) is precise when the query uses the same words as the document, but misses synonyms. Vector search catches paraphrases ("money back" vs "refund") but can be fuzzy about exact terms, numbers and names. Using both and combining them is called hybrid search.

  1. The model writes a plain-words search phrase and optionally how many passages (k, default 5). All chunk rows are loaded from SQLite into memory. (Fine at personal scale; a very large collection would want a real vector index.)
  2. Lexical leg. BM25 scores every chunk using term frequency, inverse document frequency and length normalisation (k1 = 1.5, b = 0.75). Only chunks sharing at least one word score; the top 40 are kept.
  3. Semantic leg. The query is embedded (search_query: ...) and compared with every stored vector by dot product (cosine similarity, since all vectors have length 1). Top 40 kept.
  4. If Ollama cannot be reached, this leg is skipped and BM25 alone carries the search.
  5. Fusion. Reciprocal-rank fusion. A chunk earns 1/(60 + rank) from each list it appears in; scores are summed. Chunks ranked well by both methods rise to the top. The best 20 become candidates.
  6. Rerank. The 20 candidates (first 700 characters each) are shown to the model as numbered passages with the query, and it returns the numbers that actually help, best first, as a JSON array like [3, 1, 7]. If this call fails, the fused top-k is used instead.
  7. Result. The kept passages are returned as [1] title (chunk n) - /path/to/file followed by the passage text, so the answering agent can cite the source file.
  8. Log. logs/search.jsonl records the query, whether the vector leg was used, the candidate ids and what was kept, so retrieval quality can be audited later.

The pai search command runs this same pipeline directly from the terminal (with an option to skip the rerank), which is handy for debugging retrieval without involving an agent.

Email And The Approval Gate

Diagram of the email approval flow: email_send is queued instead of run, the user runs pai approve, and only then does the mail server send over SMTP

Reading mail is safe: the mailbox is opened read-only, headers are fetched with BODY.PEEK so messages are not marked as read, and an email body is capped at 6,000 characters. Search uses Gmail's own query syntax (X-GM-RAW), e.g. from:sam newer_than:7d.

Sending mail is not safe, so it never happens inside the agent loop:

  1. The model asks for email_send(to, subject, body).
  2. email_send is flagged approval=True in the skill registry. The runner does not call it. Instead approvals.enqueue() appends a "pending" item to approvals/queue.jsonl and returns this text to the model: "queued for approval as #7. It has NOT happened yet: the user must run pai approve 7. Do not retry; tell the user it is waiting for their approval."
  3. The model tells you honestly that the email is waiting.
  4. Later you run pai approvals to see what is pending, then either pai approve 7 or pai reject 7.
  5. approve() calls skills.run(..., gated=False), the only way to run a flagged skill. The MCP client talks to the mailbox server, which logs in with your Gmail App Password and sends over SMTP (SSL, port 465). The queue item becomes "done" (or "failed") and the result is stored. Approving twice is refused.

An honest caveat: the gate lives in the Python runtime, not in the mailbox server. The server's own send tool has no gate, and the same server could be plugged into any other MCP client. The gate protects this app's agents from sending mail on their own; it does not protect the mailbox from every possible client.

The Business Database

Diagram of the database path: db_schema, one SELECT through the MCP client, a separate server that enforces read-only rules, and tab-separated rows returned

Agent: business. Skills: db_schema, db_query.

  1. The agent calls db_schema once. The result lists every table with its row count and columns.

  2. It writes one SELECT and calls db_query.

  3. The call goes through the MCP client to db_server.py, a separate process. The server enforces:

    • the statement must start with SELECT or WITH,
    • an inner semicolon is rejected (a trailing one is stripped),
    • LIMIT 50 is appended if the query has no LIMIT of its own,
    • the SQLite file is opened with the URI option mode=ro.

    The last point is the real safety net: even if a check were bypassed, a read-only connection cannot modify data.

  4. Rows come back as tab-separated text with a row count. A bad query returns its error text, so the model can fix the SQL and retry.

The database path comes from PAI_DB_PATH (mcp.json sets it to data/business.db), and scripts/import_leads.py seeds it from a leads workbook.

One detail worth knowing: the LIMIT 50 is a default, not a hard cap. A query that ends in its own LIMIT is passed through as written.

MCP: How Connectors Talk To Python

Diagram of the MCP protocol: the client in mcp.py starts server subprocesses from mcp.json and exchanges one JSON object per line over stdin and stdout

The Model Context Protocol is a standard way for an AI app to talk to a tool server. This project implements the small slice it needs, using only the standard library, in mcp.py:

  • Client. mcp.call(server, tool, args) looks the server up in mcp.json, starts it as a subprocess on first use, sends the initialize request and the initialized notification (protocol version 2025-03-26), then tools/call with the tool name and arguments. One JSON object per line over stdin/stdout. The process is kept alive between calls.
  • Server. mcp.serve(name, tools) turns a dictionary of Python functions into an MCP server: it answers initialize, tools/list, tools/call and ping. A function that raises returns an error result instead of crashing the server.
  • Config. mcp.json lists each server's command and environment. Two ship with the project: email and db.

Why separate processes? Isolation (a crash in the mailbox server cannot take the app down), one place that uses the credentials (only the mailbox server reads PAI_EMAIL_USER and PAI_EMAIL_PASS), and reuse: the same servers can be registered with any other MCP client. This is separation of code, not of secrets: the variables are set in the parent environment, which every subprocess inherits.

When the server is missing or dies, the client raises MCPError and the skill turns it into error: ... for the model.

Every Guardrail In One Place

Diagram of all guardrails around the model: no tools, allowlist, repeat check, approval queue, read-only database, step budget, output clipping, bounded delegation and reversible edits

  • The model has no tools. The CLI is started with --tools "" and --setting-sources "". It can only emit text.
  • Non-JSON replies cannot trigger actions; they become the answer.
  • Per-agent allowlist. A skill not in the agent's JSON is refused before running (skill '...' is not available to this agent).
  • No repeated calls. The exact same skill+args pair in one run gets an error telling the model to use the earlier result.
  • Approval queue. Flagged skills are queued; skills.run() also refuses them by default even if reached by another path.
  • Skill exceptions never crash a run. They become error: ... text.
  • Read-only database at the SQLite level.
  • Step budget (8 by default, set per agent).
  • Output clipping: 12,000 characters for file, page, document, email and database results (web_search is bounded at 8 results instead); 2,000 per call in the stored tool log.
  • Bounded delegation: one level deep, only existing agents, never to another planner.
  • Reversible agent edits: every agents.update() writes a timestamped backup first.

What it does not protect against, so you can judge it fairly: a model can still say something wrong using correct tool results; web pages are untrusted text that is fed back into the prompt (prompt injection is a real risk for any system that reads the web); rule overwrites and deleted facts are not backed up; and the approval gate does not secure the mailbox against other clients.

Memory: How It "Learns"

Diagram of memory: facts, rules and brand files are recalled into the prompt at the start of a run, and a second model call extracts new facts and rules after the run

There is no training and no fine-tuning. "Learning" means writing useful sentences to text files that are put into future prompts.

Three files:

  • memory/facts.md: for example - [2026-10-26, browser] example.com is a placeholder domain reserved for documentation
  • memory/rules.md: standing instructions applied to every agent (- Answer in short bullet points)
  • memory/brand.md: a brand guide you write by hand; the AI never edits it

After every run (memory.learn): a second model call receives existing memory, existing rules, the task, what the skills returned and the final answer, and is asked for JSON: up to 6 new facts and up to 3 new rules. It is told to keep concrete facts, files and URLs the user works with, preferences and corrections, and to ignore opinions, generic knowledge and temporary failures. New items are compared against what exists (ignoring dates and case) and only genuinely new ones are appended.

If the run itself edited rules or agent instructions (the trainer does), rule extraction is skipped for that run so the same wish is not written twice.

At the start of every run (memory.recall): with 60 facts or fewer, all of them go into the prompt. Above that, facts are scored by word overlap with the task, the top 50 are kept, the 10 newest are added, and the prompt says "showing N of M facts".

So the second time you ask about something, the assistant starts with what it found the first time. The memory is plain text you can read, correct or delete.

Chat Mode, Routing And Delegation

Diagram of chat routing: the router picks an agent from descriptions, the planner delegates self-contained sub-tasks to worker agents, and results return as ordinary RESULT text

pai chat

In chat you do not name an agent. You can type @agent_name ... to pick one directly. Otherwise:

  • Routing. runner.route() gives the model a list of every agent with its description and skills (plus the skill catalogue) and asks for one name. The reply is trimmed and lowercased. A known name runs that agent; an unknown name falls back to the first agent; the special answer NEW means "no agent fits".
  • NEW. create_agent_for() asks the trainer to build a suitable agent. If the trainer does not actually create one (it may just inspect the existing agents), chat reports that it could not, and suggests @trainer or pai create-agent.
  • History. Chat remembers the last 6 exchanges and prepends them to the next run as EARLIER - user: ... / EARLIER - you answered: ....
  • Delegation. For multi-step work the planner agent calls delegate(agent, task). delegate() checks three things: it is not already inside a delegation (one level only), the target agent exists, and the target is not itself a planner. Then it runs a full nested runner.run() for the worker with its own prompt, its own loop and its own memory update; the worker's answer comes back to the planner as an ordinary RESULT. Example: "compare last quarter's revenue in our DB with the pricing page" becomes one delegation to business (SQL) and one to browser (fetch the page), then the planner writes the comparison.

Because the worker will not see the conversation, the planner is instructed to make every sub-task complete and self-contained.

The Trainer: An Assistant That Edits Itself

Diagram of the trainer: it reads the rules, rewrites them, edits an agent with a timestamped backup, and pai revert restores the newest backup

The trainer is an ordinary agent whose skills happen to be management functions: list_agents, get_agent, set_agent_instructions, create_agent, get_rules, set_rules, read_memory, remember, forget.

Example:

pai run trainer "From now on answer in short bullets, and make browser cite its URLs"
  1. get_rules reads the current rules (set_rules replaces the whole file, so the model needs the old text to avoid dropping rules).
  2. set_rules writes the new rule file. From the next run, every agent gets it in its prompt.
  3. set_agent_instructions edits the browser agent. agents.update() first saves the previous definition to agents/history/browser-YYYYMMDD-HHMMSS.json, then saves the new instructions and stamps updated: <time> by trainer.
  4. The run ends; memory.learn() runs with rule extraction off.

Undo: pai revert browser restores the newest backup and removes it from history. Be aware of the asymmetry: agent edits are backed up, but set_rules overwrites rules.md and forget deletes facts for good, so keep a copy of anything you care about.

New agents can also be made by hand (pai create-agent) or via the trainer when chat finds no fit; when instructions are left blank, a model call writes 3 to 6 sentences of instructions from the name, purpose and skills.

Failure Behaviour At A Glance

What goes wrongWhat happens
Model replies with non-JSONRaw text becomes the answer
claude CLI missing / errorLLMError after 2 retries
Skill raises or gets bad argserror: ... text to the model
MCP server missing or deaderror: ... text; restarted on next use when it exited
Ollama not runningNo vectors; BM25-only search
Rerank call failsFused top-k used
Agent runs out of stepsReturns what it gathered
Memory extraction fails (LLMError)Answer still returned, run logged

The common thread: errors are data. They go back into the transcript as text so the model can adapt instead of the program dying.

The File Map

personal_ai/runner.py       the loop, the prompt template, routing
personal_ai/llm.py          the only model call
personal_ai/agents.py       load / create / update / revert agents
personal_ai/skills.py       the 22 skills + SKILLS registry
personal_ai/memory.py       facts, rules, brand, recall, learn
personal_ai/index.py        extract, chunk, embed, BM25, RRF, rerank
personal_ai/approvals.py    the human-in-the-loop queue
personal_ai/mcp.py          MCP client and server helper
personal_ai/connectors/     email_server.py, db_server.py
pai.py                      the command-line interface
agents/*.json               agent definitions (+ history/ backups)
memory/*.md                 what it has learned, rules, brand
index/                      sources.txt and index.db
approvals/queue.jsonl       pending and decided actions
logs/runs.jsonl, search.jsonl   an audit trail
workspace/                  where agents write files by default
tests/                      offline tests using a fake model

Try It

git clone https://github.com/rash-aad/personal_ai.git && cd personal_ai
python3 -m venv .venv
.venv/bin/pip install -e .          # installs pypdf and the pai command

Requirements: the Claude CLI on your PATH and logged in. Optional: Ollama with ollama pull nomic-embed-text for semantic search; an email App Password in PAI_EMAIL_USER / PAI_EMAIL_PASS for mail.

pai agents                                   # who exists
pai run reader "summarise ~/docs/report.pdf"
pai run browser "what does example.com sell?"
pai index --add ~/docs                       # build the library
pai search "refund terms"                    # test retrieval
pai chat                                     # talk; @name picks an agent
pai approvals ; pai approve 1                # human sign-off

What I Took Away From Building It

  • Treat the model as an untrusted planner, not as a program. Every guardrail here is ordinary code around an unreliable component.
  • Make failure legible. Turning exceptions into text the model can read made the system far more robust than raising errors.
  • Plain files beat clever infrastructure at this scale. JSON agents, markdown memory and a JSONL queue can all be inspected and edited with a text editor, and they make debugging trivial.
  • Hybrid retrieval is worth the extra 100 lines. Keyword and vector search fail in different ways; fusing them is cheap, and a final model rerank removes most remaining noise.
  • Be honest about limits: no OCR, no JavaScript rendering, in-memory vector scan, and an approval gate that lives in the app rather than the mailbox. Writing them down is part of the design.

Every diagram in this post was generated from the same facts as the code. If you read one file to understand the whole system, read runner.py: it is about 160 lines.