Building Your Own Context System
by kirupa (https://www.kirupa.com/me/index.htm) | filed under AI Fundamentals (https://www.kirupa.com/ai_fundamentals/index.htm)
In Context Systems (https://www.kirupa.com/ai_fundamentals/context_systems.htm), we looked at how an AI factory finds the one piece it needs inside everything it knows. We walked through a stockroom with labeled bins, part numbers, a parts catalog, a where-used list, binders of rules, and a clerk who keeps all of it current. Then we looked at a real one, the smart index behind Nightowl, and measured what it saves.
That article left out the part a lot of you asked about next: how do we build one of these for our own stuff? And what if our stuff isn't only code? Most teams I talk to want agents that can build and fix a website, and they also want those same agents making slide decks and drawing figures that look like they came from the same company. Each of those jobs needs different context, and nobody wants to build and babysit three different systems.
In this article, we're going to build one context system that serves all of those jobs, one step at a time. I've also turned the result into a small open-source project called stockroom (https://github.com/kirupa/stockroom). It has no dependencies, keeps everything in one SQLite file, gives agents eight tools to ask it questions, and works with any agent that speaks the Model Context Protocol (https://www.kirupa.com/ai_fundamentals/model_context_protocol.htm). It's about 1,900 lines of JavaScript, so we won't walk through every line. We'll walk through every decision instead, and you can poke at the code whenever you want to see how a decision turned into a function. At the end, we'll switch from my context system to yours, with a step-by-step guide (and a prompt to paste at every step) for building one with an AI agent.
By the end, our agents will be the robot at the counter, not the one in the pile:
[Image: A clerk hands one exact part to a robot at a counter, while a second robot digs through a mountain of loose files.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_counter.png)
Onwards!
What We're Building
Throughout this article, we'll build a context system for Crumb & Co., the bakery that has shown up throughout this series. Crumb & Co. is small, but it needs the same things a big company does. It has a website with a menu, a cart, and two themes. To give it some staff, let's borrow a few familiar faces from AI Factories and pretend they've taken jobs at the bakery. Wren in sales takes a slide deck to cafes when there's a new menu. Marisol in marketing asks for figures for the blog, and Hollis, the art director, approves or rejects every one of them.
That gives us four jobs for our agents to do:
1. Fix the website. A customer reports a typo, a broken photo, or a button that looks wrong.
2. Create part of the website. Wren wants a new Catering page with an order form.
3. Make a slide deck. Wren needs a short deck for the holiday menu.
4. Draw a figure. Marisol wants a figure showing how an online order reaches the oven.
In the language of AI Factories (https://www.kirupa.com/ai_fundamentals/ai_factories.htm), these are the stations. What we're building is the one stockroom all of them share:
[Image: Four agent stations share one context system. Each asks questions at the same counter, which draws on six shelves of code, decks, figures, icons, rules, and examples kept current by a clerk.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_stations.png)
Here are the steps we'll go through to build it:
1. Write down the questions each station needs to ask.
2. Lay out the shelves.
3. Design the catalog, which is our database.
4. Hire the clerk, which builds the catalog.
5. Open the counter, which is the set of tools agents use.
6. Keep everything current.
7. Wire the counter into each job.
8. Measure whether any of it was worth it.
If you want to follow along on your own machine, everything below works with the sample bakery that comes with stockroom:
git clone https://github.com/kirupa/stockroom.git
cd stockroom/examples/crumb-and-co
node ../../bin/stockroom.js build
You'll need Node.js 22.13 or newer, because that's when SQLite started shipping inside Node itself.
If you'd rather start your own project than poke at the bakery, there's also a template repository called stockroom-starter (https://github.com/kirupa/stockroom-starter). It has empty shelves, starter rules for web pages, slide decks, and figures, and everything from Step 7 already wired up for GitHub Copilot and Claude Code. We'll come back to it at the end.
Step 1: Write Down the Questions
It's tempting to start a project like this by designing a database. Please don't! A context system is only as good as the questions it can answer, so the first step is to write those questions down, station by station. Here's what that list looked like for Crumb & Co.:
Station | Questions it asks
Fix the website | Where does this typo live? Which pages use this image, and does the file exist? Is this class defined anywhere? What else breaks if I change the header?
Create a page | What does every page need? Which components already exist? Which tokens do I use for color and spacing? How do we write button labels?
Make a deck | How are our decks structured? How big is the text on a punch slide? Which fonts and colors? What did a good deck and a bad deck look like?
Draw a figure | Does a figure for this already exist? Which icons do we have? Where does a callout's arrow start? What has Hollis approved and rejected, and why?
When I lined these up, something nice happened. Questions that look completely different turn out to have the same shape. Where does this typo live? and Does a figure for this already exist? are both a search. Is this class defined? and Which tokens do I use for color? are both a lookup of a name. Which pages use this image? and What breaks if I change the header? are both a question about who points at what.
In fact, every question on the list fits one of eight shapes:
1. Find some text.
2. Find where a name is defined and used.
3. Read one specific piece of a file.
4. Skim what's in a folder.
5. List what a file pulls in.
6. List what pulls in a file.
7. Find the rules for a kind of work.
8. Find approved and rejected examples for a kind of work.
The first six are the same six questions Nightowl's agents ask, and they cover most of the work on a website. The last two are what non-code work adds. A figure station spends very little time searching code. It spends most of its time asking what are the rules? and what does good look like? Those eight shapes become our eight tools in Step 5. Everything between here and there exists to answer them quickly.
Step 2: Lay Out the Shelves
The next step is to decide where everything lives. In AI Factories, we called this the Context Environment, which is everything the factory knows, in one place the factory can reach. For Crumb & Co., that's a single folder:
[Image: The Crumb & Co. Context Environment as six shelves: site, decks, figures, icons, guidance, and examples, each tagged with the kinds of work it serves.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_shelves.png)
A small file called stockroom.json sits at the top of the folder and names the shelves. It also says what kind of file each shelf holds and what kind of work it's for:
{
"name": "Crumb & Co.",
"shelves": [
{ "path": "site", "kind": "code", "for": ["web"] },
{ "path": "decks", "kind": "code", "for": ["slides"] },
{ "path": "figures", "kind": "code", "for": ["illustration"] },
{ "path": "icons", "kind": "code", "for": ["illustration", "slides", "web"] },
{ "path": "guidance", "kind": "guidance" },
{ "path": "examples", "kind": "example" }
],
"maxFileBytes": 262144
}
The for tags are what let one stockroom serve four stations. Without them, a slide station asking for rules would get the rules for building web pages too, and it would have to sort through them itself. The icons shelf is tagged for all three kinds of work, because the same oven icon shows up on the website, in decks, and in figures.
Guidance Is Written in Small Sections
The guidance shelf is where the binders of rules live. Each binder is a Markdown file, and how we write it matters more than anything else in this step. Here's the top of the arrows binder:
---
for: [illustration, slides]
summary: How arrows start, bend, and land in Crumb & Co. figures and slides.
---
# Arrows
Arrows show movement or point at something. Both kinds follow the same rules.
## Flow arrows
- Flow arrows join objects that happen in order, left to right.
- Use one gentle curve, never straight lines with sharp elbows.
...
## Callout arrows
- A callout arrow starts at the middle of its caption: sideways from the first or last letter, or straight out from the middle of the caption.
...
The front matter at the top says which kinds of work the binder applies to, along with a one-line summary. The more important detail is the headings. Every heading becomes a section that an agent can read on its own, so a station that needs to know where a callout's arrow starts can read the six lines under Callout arrows and nothing else. If your rules live in one giant document with no headings, the best any system can do is hand over the whole thing. So, before building anything, it's worth a pass over your guidance to break it into small sections that each answer one question.
Examples Carry Their Reasons
The examples shelf holds the approved and rejected work, organized by kind of work and verdict. The reason for each verdict sits right next to it in a small Markdown file with the same name (a sidecar):
examples/illustration/approved/order-flow-v2.svg
examples/illustration/approved/order-flow-v2.md
examples/illustration/rejected/order-flow-v1.svg
examples/illustration/rejected/order-flow-v1.md
Here's what's inside the rejected one's sidecar:
---
verdict: rejected
note: Words in boxes stand in for objects, arrows are straight with sharp elbows, the colors are off palette, and the callout arrow starts from the corner of its caption instead of its middle.
---
Hollis sent this back on October 28. Every problem in it is now a rule in illustrations.md or arrows.md.
If all an agent has is the rejected figure, it has to guess what was wrong with it. When the reason sits right next to the figure, the agent knows exactly which mistakes to avoid. In AI Factories, we said that every critique should become a rule. The sidecar is where the critique lives right after Hollis makes it, before (and after) it turns into a rule.
Step 3: Design the Catalog
Now we get to the database. stockroom uses SQLite, which keeps an entire database in one file. That one file is a big reason to like it here. We can copy it, delete it, rebuild it, and hand it to any program without running a database server. SQLite also ships inside Node.js, Python, and just about every phone, so there's nothing to install.
Every table in the catalog has a twin in the stockroom from the last article:
Table | Stockroom twin | What a row looks like
files | Labeled bins | site/css/site.css, its sha256 hash, line count, and a one-line summary
file_text | The index at the back of the catalog | Every file's text, broken into three-character chunks for fast searching
symbols | Part numbers | .card defined at site/css/site.css:184, or --primary used at site/css/site.css:44
refs | The where-used list | site/menu.html:35 pulls in the image site/images/scone.svg, which is missing
sections | Tabs in the binders | guidance/arrows.md, lines 17 to 22, Arrows > Callout arrows
examples | Approved and rejected samples | order-flow-v1.svg, rejected, with Hollis's note
skipped | A list of what's not on the shelves | site/js/config.local.js, left out because it looks like it contains a secret
Most of the interesting decisions are in the symbols and file_text tables, so let's look at those up close. Here's the symbols table, straight from src/schema.sql:
CREATE TABLE symbols (
file_id INTEGER NOT NULL REFERENCES files(id),
name TEXT NOT NULL, -- .card, #menu, --primary, addToCart, #c2410c
kind TEXT NOT NULL, -- class | id | token | function | color
role TEXT NOT NULL, -- def | use
line INTEGER NOT NULL,
scope TEXT, -- where a token is defined, like [data-theme="dark"]
value TEXT -- a token's value, like #c2410c
);
Every name keeps the prefix it has in CSS. A class is .card, an id is #menu, and a design token (a CSS custom property) is --primary. That way, one column can hold every kind of name without them stepping on each other. The role column is what makes this table so useful for fixing things. A class with uses and no definitions is almost always a bug. A token's row also carries its scope and value, so asking about --primary returns its value in the light theme and in the dark theme in one answer.
Hex colors get rows too. That one is mostly for the figure station, which we'll see in Step 7.
The file_text table is a SQLite full-text table that uses the trigram tokenizer:
CREATE VIRTUAL TABLE file_text USING fts5(body, tokenize = 'trigram', content = '');
A trigram tokenizer breaks text into every run of three characters. The word recieve becomes rec, eci, cie, iev, and eve. When we search for some text, SQLite looks up its trigrams and jumps straight to the files that contain all of them, without reading any of the others. Because the chunks are just letters, we can search for a misspelling, half of a class name, or an error message with punctuation in it, and the index still finds it. The content = '' part tells SQLite to keep only the index and not a second copy of every file's text, since the files table already has it.
There's one small trick in the files table worth pointing out. The for tags get stored as a string like ,illustration,slides,, with commas on both ends. That way, asking is this for slides? is a simple LIKE '%,slides,%', and it can never accidentally match a tag like slideshow.
Step 4: Hire the Clerk
The clerk is the code that fills the catalog. In stockroom, it's stockroom build, and it does the same thing for every file on every shelf:
[Image: The clerk hashes each file, sets aside binaries, oversized files, and secrets, extracts summaries, names, references, and sections from everything else, and swaps the finished database into place at the end.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_clerk.png)
Let's walk through that from left to right:
- The clerk hashes every file with sha256, which is a fingerprint that changes if even one character changes. We'll lean on these hashes a lot when we talk about keeping things current.
- Images, fonts, and other binary files get a row in files with their hash and size, but no text. An agent can still tell an image that exists from one that doesn't.
- Files that are too big (256 KB by default) or that look like they contain a secret, like a private key or an API key, go into the skipped table along with the reason. They're left out on purpose, and the tools say so when asked about them.
- Everything else gets extracted: a one-line summary, the names it defines and uses, the files it references, and its sections if it's Markdown.
Extracting With Regular Expressions
The extractors are the most interesting part of the clerk. Each kind of file has its own, and here's what each one pulls out:
File type | Names | References | Summary
HTML | ids defined, classes used, functions called from onclick and friends | stylesheets, scripts, images, links, server-side includes | the
and meta description
CSS | classes and ids in selectors, tokens defined and used, hex colors | @import, url() for images and fonts | the first comment
JavaScript | functions and classes defined, classes added with classList, ids from getElementById, tokens set with setProperty | import, require, fetch | the first comment
SVG | the same as HTML, plus every fill and stroke color | images and icons it uses | the and
Markdown | tokens, classes, and colors mentioned in backticks | links and images | the front matter summary
Every extractor is a handful of regular expressions instead of a real parser for each language. That keeps stockroom dependency-free, and it's accurate enough for the questions we care about. It also means it can be wrong, and I found out how wrong in a fun way. Once the sample bakery was working, I pointed stockroom at the public kirupa repo (https://github.com/kirupa/kirupa) on GitHub, which holds the examples from a lot of tutorials on this site. It built in about a tenth of a second, and the report said there were 28 classes used in the HTML and JavaScript that were never defined in any CSS. That seemed like a lot.
As it turns out, most of them were my fault. A selector like .cell.trail was only registering .cell, because my regular expression wanted a space or a symbol before every dot. After the fix, the count dropped to 9, and those 9 are real: classes that JavaScript toggles to track state without styling them, or that a stylesheet outside the repo defines. The lesson I'd pass along is to run your extractors against a real codebase early, because a toy sample is too tidy to break them.
Resolving References Once
When the clerk finds a reference, like
on the menu page, it doesn't just store the text. It works out the real path (site/images/scone.svg), checks whether that file is on a shelf, and records a status:
Status | Meaning
ok | The file is on a shelf.
missing | The file doesn't exist anywhere.
outside | The file exists, but not on any shelf, so the index can't tell us about it.
skipped | The file exists, but was left out on purpose.
external | A URL on another site.
package | A JavaScript import of a package, like react.
Doing this once, at build time, is what makes which pages use this image? a lookup instead of a search. It's also what powers stockroom report, which lists every reference that points at nothing. On the sample bakery, it found the two broken references I planted, including a scone photo that someone renamed without updating the menu.
Swapping the Catalog in All at Once
The last thing the clerk does matters more than it looks. It never writes into the catalog agents are reading. It builds a brand new database file next to the old one, and only when the new one is completely finished does it rename it into place:
const tmp = `${dbPath}.tmp-${process.pid}`;
const db = new DatabaseSync(tmp);
// ...catalog every shelf into the new file...
db.close();
fs.renameSync(tmp, dbPath);
On the same disk, a rename happens all at once. An agent reading the catalog sees either the old one or the new one, and never a half-built one. On the sample bakery, the whole build takes about 20 milliseconds:
Built .stockroom/context.db in 0.02 s (0.25 MB)
32 files, 39 sections, 323 names, 36 references, 4 examples, 1 skipped
Step 5: Open the Counter
Now for the part agents actually see. Workers at a good stockroom don't wander the shelves. They walk up to a counter and ask. Our counter has one tool for each of the eight question shapes from Step 1:
Tool | The question it answers | Stockroom twin
search_source | Which files and lines contain this text? | The catalog's index
find_symbol | Where is this class, id, token, function, or color defined, and where is it used? | Part numbers
read_source | Show me these lines of this file, or this one section of a binder. | Pulling a part from its bin
list_source | What's in this folder, with a one-line summary of each file? | The catalog's descriptions
follow_references | What does this file pull in, and does each one exist? | A product's bill of materials
who_references | Which files pull in this file? | The where-used list
find_rules | Which rules apply to this kind of work, about this topic? | The binders
find_examples | What has been approved and rejected for this kind of work, and why? | The approved and rejected samples
Building the tools themselves is the easy part, because each one is mostly a single SQL query. The hard part is deciding what each one hands back. These are the rules I ended up following, and I'd follow them again:
- Hand back pointers. Every answer is a short list of file:line locations with a trimmed line of text. The agent decides what's worth reading next.
- Make reading small. read_source returns at most 200 lines, and it can return a single section of a binder by its heading. An agent that wants the rule about callout arrows reads six lines.
- Name what you don't know. If an agent asks for a file that was skipped, the answer says it was left out on purpose and why. If it asks for a file that doesn't exist, the answer suggests files with a similar name. Either way, the agent learns to say a person needs to look at this instead of guessing.
- Say what each answer is. I learned this one the hard way. My first version of find_symbol answered a question about sold-out by mixing the --sold-out token's two definitions together with the .sold-out class's one use. An agent reading that could easily conclude that .sold-out was defined somewhere. Now every name gets its own group: --sold-out (token): 2 definitions, 2 uses
defined:
site/css/tokens.css:13 [:root] --sold-out: #9ca3af; /* anything that can't be ordered right now */
site/css/tokens.css:41 [[data-theme="dark"]] --sold-out: #57534e;
used:
site/css/site.css:169 background: var(--sold-out);
site/css/site.css:246 background: var(--sold-out);
.sold-out (class): 0 definitions, 1 use
used:
site/js/cart.js:37 card.classList.add('sold-out');
- Set limits. Each session gets 40 lookups and each answer is capped at 16,000 characters. When the lookups run out, the counter answers with a polite time's up, answer with what you have. This is the same idea as the token budget (https://www.kirupa.com/ai_fundamentals/token_budget_per_request.htm) Nightowl uses for every stage.
- Read only. No tool can write, run anything, or reach outside the shelves. That's least privilege (https://www.kirupa.com/ai_fundamentals/least_privilege_tools.htm), and it means we can hand the counter to any agent without worrying about what it might do with it.
Putting the Counter on the Network
The tools are only useful if agents can reach them. stockroom serve runs the counter as an MCP server, so any agent that speaks MCP can plug in. For GitHub Copilot's command-line agent, the setup is a few lines in its MCP config:
{
"mcpServers": {
"stockroom": {
"type": "local",
"command": "stockroom",
"args": ["serve", "--root=/path/to/crumb-and-co"],
"tools": ["*"]
}
}
}
The stockroom README has the equivalent setup for VS Code and Claude Code. When an agent connects, the server also sends a short set of instructions that tell the agent how to use the counter well: ask before reading, start creative work with find_rules, check who_references before changing anything shared, and say so when something isn't in the index.
The same eight tools are also plain commands, which turned out to be handy. When I'm wondering why an agent made a choice, I can ask the counter the same question it asked and see exactly what it saw.
Step 6: Keep It Current
In Context Systems, we said that an out-of-date catalog is worse than no catalog at all, because the agent trusts it. It'll read line 37 of a file with total confidence, even if line 37 moved last Tuesday. So this is the step I'd least want anyone to skip. stockroom handles it in three places.
Every Answer Checks the Shelves First
The catalog records two fingerprints of the shelves when it's built. The first is cheap: a hash of every file's path, size, and modification time. The second is exact: a hash of every file's sha256. Before answering any question, the counter recomputes the cheap one. If it matches, nothing changed, and the answer goes out. If it doesn't match, the counter checks every file's hash, because a Git checkout can touch modification times without changing a single byte. If the content really did change, the counter refuses to answer and says exactly what changed:
The index is out of date. 1 file has changed since it was built: site/css/site.css (changed). Run "stockroom build" (or keep "stockroom watch" running) and ask again.
Checking on every call sounds expensive, but the cheap fingerprint only looks at file sizes and times, and the counter remembers a good result for a second. On the sample bakery, the check takes about half a millisecond.
Edits Carry the Hash They Were Based On
Every read_source answer includes the file's sha256. The idea, which comes straight from Nightowl, is that an agent proposing an edit keeps that hash with the edit. Before the edit is applied, stockroom verify checks that the file still has the same hash. If someone changed the file in between, the edit is refused instead of landing on text the agent never saw.
Rebuilding Rides Along With Every Change
The rebuild needs to happen automatically, every time something changes. The trick from Context Systems still applies: tie the rebuild to the one path every change already takes, so nobody has to remember it. For Crumb & Co., everything lives in a Git repository, so a two-line Git hook does the job:
#!/bin/sh
# .git/hooks/post-merge: rebuild the catalog whenever new changes are pulled in
stockroom build
On a machine where agents run all day, stockroom watch does the same thing by rebuilding whenever a file on a shelf changes. And because the clerk swaps the new catalog in all at once, a running MCP server notices the new file and switches to it on its next question.
There's an even simpler option, too. If we start the server with stockroom serve --watch, the server becomes its own clerk. It rebuilds whenever a file changes, and if a question shows up before that rebuild finishes, it rebuilds right then instead of refusing. Here's the whole loop:
[Image: The freshness loop. Every change triggers a rebuild, the new catalog is swapped in at once, and the counter checks the fingerprint before every answer, refusing when the shelves have changed. Edits are verified against the hash they were based on.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_freshness.png)
Step 7: Wire It Into Each Job
We now have a stockroom with a clerk and a counter. What's left is teaching each station how to use it. Let's walk through all four jobs at Crumb & Co. and look at what each one asks.
Fixing the Website
A customer says that sold-out items on the menu don't look sold out. The fix station's first question is about the class the cart script adds, and find_symbol answers it with the output we saw a moment ago: .sold-out is used once, in site/js/cart.js on line 37, and it isn't defined anywhere. The station's next question is whether there's a similar class that does exist, so it searches for one:
2 matching lines in 1 file (the index narrowed 31 files to 1 candidate in 1.7 ms)
site/css/site.css:220 .card.is-sold-out {
site/css/site.css:224 .card.is-sold-out .card__photo {
That's the whole story. The stylesheet calls it .is-sold-out, which matches the web binder's rule that state classes start with is-, and the script still uses the old name. The station reads lines 34 to 38 of cart.js (and gets its hash along with them), changes 'sold-out' to 'is-sold-out', and proposes the edit with that hash attached. It read two short answers and five lines of code.
The broken scone photo works the same way. follow_references on the menu page shows nine references with one marked MISSING, site/images/scone.svg. A list_source of the images folder shows a cranberry-scone.svg summarized as Cranberry orange scone. Somebody renamed the photo and didn't update the menu.
Creating a Web Page
For Wren's new Catering page, the create station needs rules more than code. It starts with find_rules for web work, which returns a list of section headings with line ranges instead of the binders themselves. Then it reads only the sections it needs: Page skeleton, New pages, and Microcopy from the voice binder. It reads the About page whole, because it's the smallest page on the site and makes a good template. Finally, it asks find_symbol about .field, the form component the web binder mentions, to see how fields are already styled.
At no point does it read the whole stylesheet hoping to spot the right components. The web binder already names the components, so the station only has to look up the ones it plans to use.
Making a Slide Deck
Decks are where the for tags start earning their keep. When the deck station asks find_rules for slides, it gets back the slides binder, the voice binder, and the arrows binder (because the arrows binder is tagged for slides too). It doesn't get the web binder's rules about page skeletons, which would only crowd out the rules it does need. From there, it reads Punch slides and Type and color, and asks find_symbol about --font-display to get the actual font names.
Then it asks find_examples what good and bad look like:
2 examples for slides:
APPROVED examples/slides/approved/punch-slide.md
why: One sentence, set large enough to fill the slide in three even lines. Nothing else on the slide competes with it.
REJECTED examples/slides/rejected/wall-of-text.md
why: Five bullets, two fonts, and a paragraph. The audience reads ahead and stops listening. Split it into three slides.
Because past decks sit on their own shelf, the station can also search them. If Wren made a deck about the spring menu in March, the holiday deck can borrow its closing slide instead of inventing a new one.
Drawing a Figure
Marisol's figure about online orders is the job that leans on the stockroom the most. Before drawing anything, the illustrations binder says to check the figure library for one that already does the job, and list_source on the figures folder answers with one-line summaries pulled from each SVG's and . Nothing there shows an order's trip, so it's time to draw.
The draft station then reads Objects, not words, Color, and Callout arrows. It lists the icons folder to find the phone, the order ticket, the oven, and the pastry box. It asks find_examples for illustration and gets back Hollis's approved figure and the rejected one, each with its reason. That rejected figure is about as useful as context gets, because it shows the exact mistakes to avoid alongside why they're mistakes.
The check station uses the stockroom too. Every hex color in every figure is a row in symbols, and every token's value is a row too, so finding a color that isn't in the palette is one query. stockroom report lists them, and find_symbol explains any one of them:
#3b82f6 (color): 0 definitions, 2 uses
used:
figures/how-sourdough-rises.svg:19 that's Gus at work
figures/how-sourdough-rises.svg:20
#3b82f6 isn't the value of any token, so it isn't in the palette.
If we ask the same question about #c2410c, the answer ends by pointing out that it's the value of --primary, so the figure should use the token instead of the raw color.
Telling Each Station How to Ask
Each station's instructions point it at the counter and tell it which questions to start with. Here's roughly what the draft station's system prompt says about the stockroom:
You draw figures for Crumb & Co. You can't open files directly. Ask the stockroom:
1. list_source on figures, to see whether a figure already does the job.
2. find_rules for illustration, then read only the sections you need.
3. find_examples for illustration, to see what Hollis approved and rejected, and why.
4. list_source on icons, and use those icons before drawing new objects.
Use token names for every color. If the stockroom doesn't have something, say so instead of guessing.
The other three stations get the same kind of short list, with their own starting questions. The prompts only say where to find the rules, and the rules themselves stay in the binders. That keeps every prompt small, and when Hollis adds a rule, every station picks it up without anyone editing a prompt.
The starter repository has these prompts ready to go, one for each of the four stations plus a review station. The review station checks work against the rules and examples, and when it spots feedback that no rule covers yet, it suggests the rule to add. Each prompt is written once, in a stations folder, and a small script turns it into an agent file for GitHub Copilot and another for Claude Code, so the two never drift apart.
Step 8: Measure It
So, was any of this worth it? To find out, the stockroom repo includes a small benchmark. It runs eight tasks from the four jobs against the sample bakery, two ways each:
- In the loose files world, an agent gets the tools you'd use on a plain folder: list a folder's names, grep every file, and read whole files.
- In the stockroom world, the agent gets the eight tools on the counter.
Each task follows a fixed plan in each world, the way an agent would, with later steps using what earlier steps returned. The benchmark checks that each world actually found the evidence the task needed, and it counts tokens with a real tokenizer (OpenAI's o200k_base encoding). Here's what came back:
Job | Task | Loose files: calls | Loose files: tokens | stockroom: calls | stockroom: tokens
Fix the website | Fix a typo a customer reported | 2 | 710 | 2 | 191
Fix the website | The scone photo is broken on the menu | 2 | 698 | 2 | 217
Fix the website | Sold-out items don't look sold out | 3 | 2,065 | 2 | 193
Fix the website | Add a Catering link to the navigation | 2 | 250 | 2 | 281
Create a page | Build a new Catering page with an order form | 5 | 3,153 | 6 | 1,284
Make a deck | Make a short deck for the holiday menu | 7 | 1,192 | 6 | 815
Draw a figure | Draw how an online order reaches the oven | 10 | 1,687 | 7 | 1,399
Draw a figure | Check whether a sourdough figure already exists | 2 | 384 | 1 | 74
Total | | 33 | 10,139 | 28 | 4,454
Both worlds found the evidence for all eight tasks, and the stockroom world did it with 56% fewer tokens. Here's the same total as a picture:
[Image: Across eight tasks, loose files used 33 calls and 10,139 tokens, and stockroom used 28 calls and 4,454 tokens, which is 56% fewer, with both finding all the evidence.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_benchmark.png)
The savings aren't spread evenly, and the pattern is worth noticing:
- The biggest savings come from reading less. The sold-out task went from 2,065 tokens to 193 because the loose world had to read all of site.css and cart.js to learn what find_symbol and one search said directly.
- The rule-heavy jobs save less, but they still save a lot. A figure station really does need several rules and examples, so it reads more in either world. The difference is that the stockroom world reads the sections it needs instead of every binder end to end.
- One task got a little worse. Adding a link to the navigation took 281 tokens with stockroom and 250 without, because who_references lists each page with its line number and kind of link, and grep happened to return less text. Even so, I'd take the stockroom answer, because grep for a file name also matches any other file whose name happens to end the same way, which is exactly the mistake we saw in Context Systems.
There's one more honest note about this table. I left the timing columns out because every task, in both worlds, finished in under ten milliseconds. The bakery is tiny, 32 files in all, so even reading everything is quick. The time savings only show up at a bigger size, which is what we measured in Context Systems: on kirupa.com's 2,663 source files, every grep took about five seconds, and the index answered in milliseconds. The token savings are the part that carries over to a small project like this one. And because an agent re-sends the whole conversation on every turn, every token we save early gets saved again on every turn after it.
Building Yours With an AI Agent
So far, we've been looking at a context system for a bakery that doesn't exist. Now it's your turn. You'll probably be doing most of this with an AI agent, so the stockroom-starter (https://github.com/kirupa/stockroom-starter) template comes with five skills to help. A skill is a folder with a SKILL.md file of instructions that an agent loads when a task matches what the skill is for. GitHub Copilot and Claude Code both read skills from the .claude/skills folder, so the same five work in either one:
Skill | What it walks you and your agent through
set-up-context-system | Choosing your kinds of work, moving your work onto the shelves, and bringing in your design tokens
write-rules | Turning your style guides, brand docs, and feedback into rule files with small sections
add-example | Saving approved and rejected work with the reason next to it
test-context-system | Running the checks, asking the questions an agent asks, and giving you a scorecard
add-kind-of-work | Adding a new kind of work, like release emails, with its own shelf, rules, examples, and agent
The skills are written to ask you questions instead of guessing. When something is missing or unclear, the agent comes back with a list of open questions rather than making up a rule to fill the gap. That matters more than it sounds, because an agent trusts a made-up rule exactly as much as a real one.
Here's the path we'll take, one stop at a time:
[Image: Seven steps for building your own context system with an agent: make a copy, connect your agent, move your work in, write your rules, add examples, test it, and put it to work. A loop runs from putting it to work back to writing rules.] (https://www.kirupa.com/ai_fundamentals/images/building_your_own_context_system_agent_path.png)
You'll need Node.js 22.13 or newer, Git, and an agent that speaks MCP, like GitHub Copilot (in VS Code, the Copilot CLI, or the cloud agent) or Claude Code. Each skill commits its work when it finishes, so at every step you can see exactly what your agent changed, and undo any of it with Git.
Make Your Own Copy
On GitHub, open stockroom-starter (https://github.com/kirupa/stockroom-starter) and click Use this template. Or, if you have the GitHub CLI, do the same thing from a terminal:
gh repo create my-context --template kirupa/stockroom-starter --private --clone
cd my-context
npm install
npm run setup
npm run check
npm run setup turns on Git hooks that rebuild the index after every pull, merge, checkout, and rebase, and then it builds the index for the first time. npm run check should end with No problems found. Your copy already has everything from Step 7 wired up: the shelves, starter rules, five agents (fix-web, build-page, make-deck, draw-figure, and review), MCP configs, and a CI check that runs on every pull request.
Connect Your Agent
Open the folder in your agent. Each one finds the stockroom a little differently:
- VS Code with GitHub Copilot reads .vscode/mcp.json, and the five agents show up in Copilot Chat's agent picker.
- The GitHub Copilot CLI can start the stockroom from each agent's file. Run copilot in the folder and pick an agent with /agent. If the stockroom tools don't show up, add the server once with /mcp add, using npx --no-install stockroom serve --watch as the command.
- Copilot cloud agent runs .github/workflows/copilot-setup-steps.yml before it starts, which installs stockroom and builds the index.
- Claude Code reads .mcp.json. Run claude in the folder and approve the stockroom server when it asks.
Every one of these starts the server with stockroom serve --watch, so the index stays current while you and your agent work. To make sure the connection really works, paste this prompt:
List the stockroom tools you can use. Then call find_rules for web and show me what came back.
You should see the eight tools from Step 5 and a list of rule sections from guidance/web.md and guidance/voice.md. If your agent says it'll read the files directly instead, the stockroom isn't connected, and it's worth fixing that before going any further.
Move Your Work Onto the Shelves
Now we tell the agent what we actually make and where it lives. Paste something like this, with your own paths:
Use the set-up-context-system skill. We build and fix our website and draw figures for it,
but we don't make slide decks. Our site is in ~/code/our-site, and this repository will be
its new home. Our colors and fonts are in ~/code/our-site/css/tokens.css.
The skill asks about anything you leave out, one question at a time. Then it points each shelf at your work, copies your design tokens in, and takes out any kind of work you don't need. Dropping slide decks, for example, means removing the decks shelf, the slides rules, the slides examples, and the make-deck agent. Your original files are never moved or deleted.
At the end, the agent runs npm run check, and it's very likely to find something. That's a good sign! Those are real bugs in your work, not setup mistakes. When we tried this with the Crumb & Co. website, the check found the renamed scone photo and the cart script's leftover sold-out class within seconds of the copy landing.
Write Down Your Rules
The starter's rules are placeholders, and the agents will happily follow them until you replace them. Most teams have rules somewhere already, usually as one long document. Point the agent at yours:
Use the write-rules skill to replace the starter rules with our style guide at
~/Documents/style-guide.pdf. Ask me about anything it doesn't cover instead of guessing.
The skill splits a long document into one rule file per topic, each with a for: line, and breaks each file into small sections under headings an agent would search for. It also checks that every token and component a rule names really exists, and it compares the new rules with your approved examples. If an approved figure breaks a new rule, it asks you which one is right instead of picking one itself.
Expect a lot of questions. When we ran the bakery's website and style guide through these skills, the agent came back with thirteen open questions, like whether one joke per screen means one joke per menu card or one per page. Every question you answer now is a guess that no agent has to make later.
Add Examples With Their Reasons
Next, give the agents something to compare their work against. One approved example and one rejected example of the same kind of thing teach more than a stack of approved ones:
Use the add-example skill. We approved figures/order-flow-final.svg because it uses real
objects, curved arrows that stop short, and a callout arrow that leaves from the middle of
its caption. We rejected drafts/order-flow-first-try.svg because it uses words in gray boxes
instead of objects, straight arrows with sharp elbows, and colors that aren't in our palette.
The agent saves each one in the right examples folder, writes the reason into a sidecar next to it, and checks whether each reason is already a rule. If a reason isn't covered by any rule, it offers to write one.
Test It
Now for the fun part. There are two ways to see where your context system stands, and they're meant to be used together. The first is npm run doctor, which looks for gaps instead of mistakes. Here's what it says about the web work on a fresh copy of the starter:
web
[x] 5 files of web work on the shelves
[x] 12 rule sections in guidance/voice.md, guidance/web.md
[~] Still using the starter rules in guidance/voice.md, guidance/web.md
next: Use the write-rules skill to replace them with your own, then delete the "Starter rules" comment.
[ ] No approved examples for web
next: Use the add-example skill to add one to examples/web/approved/ with the reason next to it.
[ ] No rejected examples for web
next: Use the add-example skill to add one to examples/web/rejected/ with the reason next to it.
[x] An agent asks for web rules: stations/build-page.md
everything
[x] Every token and class the rules mention is defined
[x] 19 design tokens defined
9 ready, 3 to improve, 8 missing.
Every line that isn't ready names the skill that fixes it. The doctor also catches two problems that are easy to create and hard to spot by hand. It flags a rule that mentions a token or class nobody defined, and it flags two rule files that both apply to the same kind of work and share a heading. That second check exists because our own trial run found exactly that mistake in the starter. The illustration rules were tagged for slides too, so a deck agent got two File format sections that disagreed about where decks live.
The second way is the testing skill, which does what the doctor can't. It asks the stockroom the same questions each agent asks and judges whether the answers are good enough:
Use the test-context-system skill and give me the scorecard.
The skill works in three passes. It runs npm run check and npm run doctor. Then, for each kind of work, it reads the rules and examples an agent would read and checks that a changed file shows up in the very next answer. Last, it runs one small, real task per kind of work with that kind's agent and audits what the agent did. Did it start with find_rules and find_examples? Did it read sections instead of whole files? Did it use token names instead of raw colors? Did it run npm run check before finishing?
It ends with a scorecard that has one row per kind of work, a ready or not-ready mark for the checks, the rules, the examples, and the trial run, and the one next step that would help most. A kind of work is never marked ready while its shelf is empty, even if every check passes. Passing checks on an empty shelf only means there's nothing to break yet.
Put It to Work
Once the scorecard looks good, hand the agents real work. You can name an agent, or describe the work and let your tool pick one:
Agent | Try asking
fix-web | The logo on the About page is broken. Fix it.
build-page | Add a Pricing page with three plans and link it from the navigation.
make-deck | Make a 10-slide deck introducing our new onboarding flow to the sales team.
draw-figure | Draw a figure that shows how a support ticket goes from the inbox to a fix.
review | Review the figure in figures/ticket-flow.svg.
For the first few tasks, watch which tools each agent calls. A healthy run starts with a few small stockroom questions, reads a handful of sections and line ranges, and ends with npm run check. If an agent starts reading whole stylesheets, that's usually a sign a rule or component it needed is missing.
Turn Every Critique Into a Rule
This is the step to keep doing for as long as you use the system. Whenever you reject something an agent made, don't just fix it. Tell the agent why, and let the skills file it away:
I'm rejecting this figure because the labels are too small to read on a phone. Use the
add-example skill to save it as a rejected example, and use the write-rules skill to turn
the reason into a rule.
From then on, every agent gets that rule, for every request, from everyone. And when you're ready for agents to take on something new, like release emails or documentation, the last skill sets up the shelf, rules, examples, and agent for it:
Use the add-kind-of-work skill to add release emails. Our past emails are in ~/Documents/emails.
If you change an agent's instructions along the way, edit its file in the stations folder and run npm run agents. That regenerates the Copilot and Claude Code versions from the same file, and CI fails if you forget.
What It Doesn't Do Yet
stockroom is deliberately small, and there's a lot it doesn't do. If you build on it (please do!), these are the gaps I'd look at first:
- Permissions. Everyone who can reach the counter can read every shelf. For anything with salaries or unannounced plans in it, you'll want permission-aware retrieval (https://www.kirupa.com/ai_fundamentals/permission_aware_retrieval.htm).
- Searching by meaning. Search matches text, so a search for late pickup won't find a rule about orders after 3pm. Adding embeddings (https://www.kirupa.com/ai_fundamentals/embeddings.htm) next to the trigram index gives you hybrid search (https://www.kirupa.com/ai_fundamentals/hybrid_search.htm).
- Live data. Today's prices and what's left in the display case change by the minute, so they don't belong in a catalog that rebuilds on every change. A station should ask the system that owns that data, through its own MCP server.
- Names built at runtime. A class built from strings, like 'is-' + state, doesn't look like a class name to a regular expression, so find_symbol won't see it. Real parsers would catch more, at the cost of dependencies.
- Learning from what's missing. Every question an agent asks could be logged, and the searches that came back empty are a ready-made list of the shelves and rules we still need to write. stockroom doesn't log questions yet, and it's the feature I most want to add next.
Conclusion
We started with a question from the end of Context Systems: how do we build one of these for our own stuff, when our stuff includes web pages, slide decks, and figures? The answer turned out to be one stockroom with a few honest pieces. We wrote down the questions first and found that they fit eight shapes. We laid out shelves and tagged each one with the work it serves, and we wrote our rules in small sections and kept the reason next to every approved and rejected example. A clerk catalogs all of it into one SQLite file and swaps it in all at once. A counter answers the eight questions with small, precise answers, and it refuses to answer at all when the shelves have changed since the last build.
What makes this work for four very different jobs is that the stations ask the same kinds of questions. A fix station and a figure station both search, look up names, read small pieces, and check examples. The for tags make sure each one only sees the rules that apply to its job. On the sample bakery, that added up to 56% fewer tokens across eight tasks, with every bit of evidence still found.
If you want to try it, the quickest start is stockroom-starter (https://github.com/kirupa/stockroom-starter). Click Use this template, run npm install and npm run setup, put your own rules in the guidance folder, and run npm run check. The engine underneath is stockroom (https://github.com/kirupa/stockroom), if you'd rather wire things up yourself. If your project is anything like the sample bakery (or the kirupa repo), it'll find at least one broken reference you didn't know about. And if it doesn't, you can rename a scone photo and try again!
Idea | Where we cover it
What a context system is, and the real one behind Nightowl | Context Systems (https://www.kirupa.com/ai_fundamentals/context_systems.htm)
The factories that use the stockroom | AI Factories (https://www.kirupa.com/ai_fundamentals/ai_factories.htm), Nightowl: kirupa.com's AI Software Factory (https://www.kirupa.com/ai_fundamentals/nightowl.htm)
Choosing what goes into each request | Context Engineering (https://www.kirupa.com/ai_fundamentals/context_engineering.htm)
Plugging agents into tools | Model Context Protocol (https://www.kirupa.com/ai_fundamentals/model_context_protocol.htm), Tool Calling (https://www.kirupa.com/ai_fundamentals/tool_calling.htm)
Keeping an index in step with its source | Keeping the Index Fresh (https://www.kirupa.com/ai_fundamentals/keeping_the_index_fresh.htm)
Read-only tools with tight limits | Least-Privilege Access for Tools (https://www.kirupa.com/ai_fundamentals/least_privilege_tools.htm), Token Budget per Request (https://www.kirupa.com/ai_fundamentals/token_budget_per_request.htm)
[Mastery Quiz]
Test your knowledge!
Take the Building Your Own Context System Quiz: https://www.kirupa.com/quizzes/building_your_own_context_system.htm
Practice with 6 multiple-choice questions and an explanation after every answer.
[/Mastery Quiz]