Engineering notes

How coding-agent runtimes work

Five Kinds of Memory: How LemonCrow Remembers

LemonCrow uses the word memory for five distinct systems: named facts, archival recall, write-time arbitration, cross-vendor ingestion, and semantic file memory.

“Memory” is one of the most overloaded words in agent tooling. It can mean a vector store, a scratchpad, a fine-tune, a config file, or a chat history, and a product that promises “memory” rarely says which one it means. LemonCrow uses the word for five genuinely different systems, and conflating them is how teams end up with a feature nobody can reason about.

This post keeps them apart. How LemonCrow works introduces the runtime and the full technical inventory lists every subsystem; here we look only at memory: what each kind stores, when it runs, whether the model triggers it, and how it fails.

The five. Named fact memory (curated facts the agent stores and recalls), archival recall (search over everything that happened), memory arbitration (deciding what is worth writing), cross-vendor memory (reading what other tools already know), and semantic file memory (a cache of code structure that, despite the name, holds no conversation at all).

1. Named fact memory: the thing you call “memory”

The first kind is the one the model calls directly. LemonCrow exposes a memory tool backed by a fact service that stores user-created facts as named blocks, recalls them by subject, and lets the agent vote them up or down. Every fact is scoped to either the repository or the user, so the runtime knows how far it should travel.

The service runs on one of three interchangeable backends: SQLite by default, or Letta or OpenMemory when configured. A repository fact (“this service deploys from the release branch”) earns its place across every task in that repo; a user fact follows you between repositories. Up and down votes give the store a cheap, durable signal of which facts keep proving useful and which have gone stale.

2. Archival recall: search over everything that happened

The second kind is not facts but history. As a session runs, LemonCrow archives transcript passages and code chunks (split into a few hundred tokens with overlap, embedded, and dedup-hashed) so it can later search across everything that has happened, not just what is still inside the context window. Recall pulls a wide candidate window before it ranks.

Ranking is a hybrid. LemonCrow blends cosine similarity over embeddings with a BM25 lexical score, weighted sixty-forty toward the vector signal, so recall catches both “this means the same thing” and “this uses the exact identifier I typed.” Exact brute-force cosine is the default; an approximate index is opt-in behind an environment flag.

Two safeguards keep the ranking honest. The newest handful of passages are always kept as exact candidates, so the most recent context is never missed. And a passage is eligible only if it was embedded by the current model at the current dimension, which means a model upgrade cannot silently poison the results with vectors that no longer mean the same thing.

3. Memory arbitration: deciding what is worth remembering

The third kind runs before a fact is written. Instead of appending every claim, an optional arbiter compares a candidate fact against similar existing ones and chooses among four operations: ADD a new fact, UPDATE an existing one, DELETE a contradicted one, or NOOP when the store already says enough. It is how named-fact memory avoids filling with near-duplicates.

Similar blocks are found by token-overlap similarity on each fact’s label and value, and a local model ranks the candidates and picks the operation. An UPDATE merges into the existing block, a DELETE tombstones it, and a NOOP leaves the store untouched. The design choice that matters is the failure mode: if the arbiter is unavailable or returns anything malformed, it falls open to ADD. A write is never blocked by a missing arbiter, only refined by a present one.

4. Cross-vendor memory: reading what other tools already know

The fourth kind reaches outside LemonCrow entirely. Read-only adapters ingest the native memory files that Claude, Codex, and Gemini write and present them as one unified fact representation. If you have already curated memory in another assistant, LemonCrow can read it without you re-entering anything, and without a separate import step.

The emphasis is read-only, and it is load-bearing. Each adapter can check whether a vendor’s files exist, list the facts it finds, and report which paths it read, and nothing else. LemonCrow never writes back into another tool’s memory, so there is no way for one assistant to corrupt another’s state. Each ingested fact gets a stable id derived from its content, so the same upstream note is never counted twice.

5. Semantic file memory: structure, not conversation

The fifth kind is the odd one out: despite the name, it stores no conversation at all. Semantic file memory caches what LemonCrow has learned about the code (AST-derived outlines, symbols, imports, complexity scores, and summaries) keyed by a SHA-256 hash of each file’s contents rather than by path or timestamp.

Because the key is the content hash, the cache survives a git checkout, a container rebuild, or an rsync; only a file whose bytes actually changed is re-parsed. This is the memory that makes a smart read cheap: the outline the agent sees before it asks for a range, the first move of context engineering, comes straight from here, and the same data feeds the dependency graph used for blast-radius analysis. A read cap stops a pathological file from exhausting memory, and an outline is substituted only when it saves at least a quarter of the file’s tokens.

Why keep them separate

These five could be marketed as a single “memory” feature, but keeping them distinct is exactly what makes each one safe to reason about. They disagree on every axis that matters: what they store, when they run, whether the model triggers them, and what they do when something goes wrong.

KindStoresRunsWhen it fails
Named fact memorycurated factson a model memory callneeds a storage backend
Archival recallsession and code historycontinuously, plus on recallfalls back to lexical-only
Memory arbitrationnothing — a decisionbefore each fact writefalls open to ADD
Cross-vendor memoryother tools’ factson readempty if files are absent
Semantic file memorycode structureon read and indexingre-parses the changed file

A single abstraction would force one storage model, one trigger, and one failure policy onto all five, and most of those choices would be wrong for most of the jobs. LemonCrow’s bet is that naming the five honestly is worth more than collapsing them into one word that quietly means five things.

Sources and further reading

This article was checked against the current LemonCrow implementation on June 23, 2026.

Context Engineering: What LemonCrow Shows the Agent

How LemonCrow decides what a coding agent sees now, what can wait, and what must survive: projection, output budgets, deduplication, and compaction.

A language model does not see your repository. It sees a conversation: a sequence of messages, tool results, and instructions that has to fit inside a finite context window. Whatever made it into that window is the entire world the agent can reason about on a given turn.

Context engineering is the discipline of deciding what belongs there. It is the part of LemonCrow that chooses what the model should see now, what can wait, and what must survive into a later session. How LemonCrow works covers the tools the agent calls; this post is about the layer that decides how much of their output the model actually has to carry.

In short. LemonCrow engineers context in six moves: show a projection before the whole file, put a ceiling on every result, never send the same bytes twice, select blocks under an explicit token budget, order them so the provider’s cache stays warm, and compact at a real task boundary. Each move is deterministic code, not a model guess.

Context is a budget problem, not a search problem

Every token in the window costs money and crowds out something else. A coding agent spends most of its turns finding code, reading it, and re-reading it, so the cheapest path to a verified change is the one that puts the least unnecessary text in front of the model. Context is therefore a budget to be managed, not just a pile to be filled.

LemonCrow treats the window as a scarce resource with an explicit ledger of tool calls, tokens, and touched files. This is the same idea that drives how LemonCrow saves money, seen from the inside: end-to-end cost is mostly a function of what enters context, so the runtime works to keep that quantity small without ever losing access to the source of truth.

Progressive disclosure: a projection before the whole file

LemonCrow almost never hands the model a whole file first. Its source-projection layer can return six views of the same file (summary, exact, range, outline, compact, and minified) and it picks the smallest one that still answers the question. For a large file the default is an outline: imports, classes, functions, methods, and their line numbers.

The outline is elected by savings, not by a fixed line count. LemonCrow compares the outline’s token cost against the full file and only substitutes it when it clears a savings guard of roughly a quarter of the file’s tokens, so a small file is still returned whole. From an outline the agent requests an exact line range, and a compact or minified projection can strip comments and blank-line noise while keeping a mapping back to the real source. Because an edit must be grounded in real lines, range reads stay exact.

The shape of a session becomes a funnel: repository map, then file outline, then exact range, then edit. The agent starts broad and cheap and pays for detail only where it matters.

Every result has a ceiling

No single tool call is allowed to flood the window. LemonCrow’s search surface carries a default budget of 2,000 tokens; a broad match is ranked, summarized, or returned as file pointers rather than as an unbounded wall of source. Structured output is capped near 80,000 characters, and a file-paths-only listing is capped at 200 paths.

Other guards bound the work itself. A user-supplied regular expression gets a five-second deadline, files larger than five megabytes are skipped during search, and per-line character caps stop one pathological minified line from stalling the engine. These limits are configurable through environment variables, but they exist so that a single query cannot silently consume the whole turn.

When a result is genuinely large (a long build log, a wide query, a fetched page) LemonCrow does not truncate it and lose the evidence. It spills the full output to a store on disk, hands the model a head-and-tail summary plus a spill: reference, and lets a later call retrieve the whole thing or a specific slice. Spilled output is retained for about a day and swept on a file-count cap, so the evidence lives exactly as long as it is useful.

The cheapest duplicate is the one never sent

Agents reopen files “to be safe” even when the exact bytes are already in the prompt. LemonCrow keeps a within-session registry of read-style results, and when a tool would return content byte-identical to something already present in the current context epoch, it substitutes a small pointer instead of the duplicate.

Two thresholds keep this honest. Only results of at least four kilobytes are eligible, so the bookkeeping never costs more than the saving. For a file that changed since its last read, LemonCrow can emit a delta rather than the whole body, but only when the diff is at most half the file’s size; past that, repeating the full content is cheaper and clearer. The registry tracks a bounded set of recent resources and evicts the oldest, and a compaction advances the epoch so a pointer can never refer to context that no longer exists. The full technical inventory lists this alongside the rest of the deduplication and spilling machinery.

Selecting what fits under a budget

When several useful blocks compete for one budget, LemonCrow solves a knapsack rather than guessing. Each candidate block carries a token cost and a utility score in the zero-to-one range, and the budget optimizer chooses the subset that maximizes total utility without exceeding the limit. With OR-Tools installed it solves this exactly, as a CP-SAT model.

The exact solver runs under a two-second time limit and on problems up to a few hundred blocks. Beyond that, or when OR-Tools is absent, LemonCrow falls back to a greedy selection that ranks blocks by utility per token and adds a small bonus for drawing from a source it has not used yet. The diversity bonus matters: it stops the optimizer from filling the window with ten near-identical snippets from one file when a more varied pack would serve the next decision better.

Order for the cache, not just for the reader

Where a block sits in the prompt decides whether the provider can reuse its cache. LemonCrow classifies every block by a stability tier (static, session, branch, turn, or volatile) and by kind, from tool schemas and coding policy down to git diffs and scratchpads. Stable material goes first; volatile material goes last.

The prefix-cache planner splits the compiled prompt into a static prefix (the static and session tiers) and a dynamic tail (branch, turn, and volatile), hashes the prefix with SHA-256, and compares that hash across turns to detect exactly what invalidated the cache. Keeping the stable schema and policy blocks in a fixed order protects the provider’s prefix cache, so cache reads stay cheap turn after turn instead of paying full price for a prompt that barely changed.

Scoped context: assemble the smallest useful pack

Given a subtask, LemonCrow can build a context pack from scratch instead of waiting for the agent to discover everything by hand. The scoped-context capability takes a description, keywords, and affected paths, then seeds candidates from several channels at once: hybrid search on the description, lexical search on the keywords, in-file symbols for the affected paths, and commit history when the task looks historical.

Candidates are ranked by position, keyword overlap, and whether they touch an affected path, deduplicated by file and symbol so the same code is not packed twice, and then fitted to the subtask’s token budget. When the pack runs over budget, the packer drops the least essential fields first (snippets and signatures before paths) so the result degrades gracefully rather than dropping a whole file.

Compaction: shrink at a boundary, keep what continues

Eventually a long session fills its window, and LemonCrow compacts. The policy fires on a single fill threshold that depends on the chosen preset (around 72 percent on the balanced default, lower on the savings-focused presets) and it preserves a protected list of material: recent turns, active errors, recently touched files, and pinned memory.

Compaction is not just deletion. It advances the deduplication epoch so stale pointers cannot survive into a context that no longer holds their targets, and at the far end it can write a handover packet that a fresh session reads to continue the work. The goal is never the smallest possible context; it is the smallest context that still lets the agent finish correctly.

The ideas underneath

These mechanisms are different expressions of one stance: compression should defer detail, not destroy it. A projection keeps a mapping back to the file. A spill keeps a reference to the full output. A handover keeps the active errors and touched files. Nothing load-bearing is thrown away; it is only moved out of the window until it is needed again.

A few principles follow from that:

  • Progressive disclosure. Return the repository map before the files, the outline before the body, and the exact range before the whole module.
  • Prefer deterministic machinery. Parsers, budgets, hashes, and solvers do the work that does not require a model, so model reasoning is spent on decisions that actually need it.
  • Account conservatively. An errored read earns no saving, and the same full-file baseline is never credited twice.
  • Treat cache stability as a design constraint. A predictable block order that protects the prefix cache is often worth more than a marginally better selection that breaks it.

LemonCrow does not make the model smarter. It makes the model’s view of the repository smaller, truer, and cheaper to carry, which is most of what a long agent session actually spends its budget on.

Sources and further reading

This article was checked against the current LemonCrow implementation on June 23, 2026.

How LemonCrow Works: MCP Runtime for Coding Agents

LemonCrow sits between a coding agent and your repository, giving it structured ways to search, read, edit, run, and remember.

LemonCrow is not another coding model. It does not replace Claude Code, Codex, or the agent you already use.

It sits between the agent and your repository as a Model Context Protocol server. The agent still decides what to do. LemonCrow changes how it sees the codebase, how it applies changes, and how much context it needs to carry while doing the job.

The simplest way to understand LemonCrow is as a better working surface for a coding agent.

The agent gets tools, not a dump of your repository

When an MCP client connects, LemonCrow advertises a set of typed tools. The public surface includes tools for reading files, searching code, exploring symbols, editing, running commands, querying data, and managing memory.

The definitions come from the Python functions that implement each tool. LemonCrow reads their type hints and defaults, turns them into JSON Schema, and uses the same definitions to validate calls at runtime. The model sees a compact description of each tool rather than an open-ended shell prompt.

A request follows a straightforward path:

  1. The coding host sends a JSON-RPC tools/call request.
  2. LemonCrow validates and normalizes the arguments.
  3. The appropriate code, file, shell, or memory capability runs.
  4. The result is rendered into a form intended for a language model.
  5. Large or repeated output is reduced before it enters the conversation.

That boundary is implemented in src/atelier/gateway/adapters/mcp_server.py. The file is large because it is where many concerns meet: MCP transport, tool registration, request routing, workspace isolation, result formatting, session accounting, and failure handling. The search engines, memory stores, source projection, and workflow machinery live behind it.

Search first, then read narrowly

A normal coding agent often explores a repository with a loop like this:

search for a word
open a file
search for the next symbol
open another file
repeat

That works, but it treats a codebase like a folder of text files.

LemonCrow gives the agent several levels of navigation.

grep handles exact patterns, regular expressions, file globs, and file types. Its results have an explicit token budget, so a broad match does not automatically flood the conversation.

search handles ranked, natural-language lookup. It can return relevant snippets, locate an exact symbol, or build a compact repository map around known files.

explore uses code intelligence. Given a concept, it can group relevant source with caller, callee, and usage context. Given a known symbol, it can return its definition or a specific relation such as callers or usages.

The point is not that one search method always wins. The point is that the agent can choose the cheapest useful view. An exact error message belongs in grep. An unfamiliar feature belongs in ranked search. A known function belongs in symbol-aware explore.

Reading is a projection, not an all-or-nothing operation

Once the agent finds a file, LemonCrow’s read tool decides how much of it is useful.

For a large code file, the default view is an outline: imports, classes, functions, methods, and line locations. The agent can then request an exact range around the relevant symbol. Small files can still be returned in full, and expand=true is available when exact complete text is necessary.

For supported languages, LemonCrow can also project source into a smaller view by removing comments, excess whitespace, and other detail while preserving a mapping back to the original file. Exact range reads remain exact because an edit must ultimately be grounded in real source lines.

Large files are bounded at the source. Instead of loading a huge file and hoping the MCP client accepts it, LemonCrow returns a line-aligned prefix with the exact range needed to continue.

This creates a progressive workflow:

repository map -> file outline -> exact source range -> edit

The agent starts broad and cheap, then pays for detail only where it matters.

Edits are structured operations

LemonCrow’s edit surface accepts structured changes rather than asking the model to improvise file writes through shell commands. An edit can target an exact string, a line range, a symbol body, or a projected range from an earlier compact read.

Before and after the edit, the runtime tracks the affected paths and records the resulting diff. It can run formatting or verification hooks, protect sensitive paths, and reject mixed edit shapes that would make a batch ambiguous.

This does not make an agent infallible. It makes the operation observable. The result tells the agent what changed, and verification remains a separate, explicit step.

Shell commands still have a place for tests, builds, and repository tooling. They run through a managed command surface with timeouts and background-session support.

Cheap work should not wait behind expensive work

The MCP server accepts requests concurrently. It uses one worker pool for frequent operations such as reads and searches, and a smaller heavy pool for long-running work such as shell commands, edit verification, web requests, workflows, and agent runs.

That separation matters during a real session. A long test suite should not prevent the agent from reading a file or checking a symbol in parallel.

Initialization is handled synchronously so later requests see the client’s capabilities. Responses are serialized behind a stdout lock so concurrent workers cannot interleave JSON-RPC frames.

These are ordinary server-design choices, but they are important because the coding agent experiences them as responsiveness.

The session has memory and a budget

LemonCrow keeps a ledger of tool calls, files touched, outcomes, and context use. That ledger supports two different kinds of memory.

Working context is the material needed for the current task: recent turns, open files, active errors, and current decisions. When the context window fills, LemonCrow can recommend compaction or produce a handover packet for a fresh session.

Durable memory stores facts and playbooks that should survive the current conversation. It is separate from raw conversation history, so a useful repository fact does not have to be rediscovered on every task.

The runtime also isolates request state. Concurrent clients get their own session ledgers, and request-scoped project overrides are restored after each call. The MCP process can stay alive without letting one request’s workspace or accounting state leak into another.

Results are designed for the next decision

A tool result is not useful merely because it is complete.

Search responses are ranked and budgeted. File reads expose continuation ranges. Repeated content can be replaced with a small pointer. Very large shell, SQL, or web results are stored in full while the agent receives a recoverable summary. A final frame-size guard prevents one pathological response from disconnecting the MCP server.

This is the common thread across LemonCrow: preserve access to the source of truth, but do not put all of it into the model’s context at once.

The model remains responsible for reasoning. The coding host remains responsible for permissions and the user experience. LemonCrow supplies the layer in between: a structured, code-aware, context-aware way for the agent to work on a real repository.

Sources and further reading

This article was checked against the current LemonCrow implementation on June 23, 2026.

How LemonCrow Saves Money on Coding-Agent Tokens

LemonCrow reduces coding-agent cost by cutting repeated discovery, oversized file reads, redundant tool output, and unnecessary turns.

A coding agent does not spend most of its time writing the final patch.

It spends time finding the right file, opening code, following symbols, rerunning searches, reading test output, and carrying all of that material into later turns. The cost of a task is therefore shaped by the path to the answer, not just the answer itself.

LemonCrow saves money by shortening that path and reducing what enters the model’s context along the way.

It does not use a cheaper model behind your back. It improves the tools around the model you chose.

Every unnecessary result stays in the conversation

In a typical agent loop, a tool result becomes part of the conversation. The next model call includes that result along with earlier messages and newer work.

A 2,000-token file read is not necessarily paid for only once. It occupies space in the active context until the session is compacted or cleared. The same is true for a broad search result, a long build log, or a file that gets opened twice.

This makes early context decisions important. Saving tokens before the agent has found the answer also reduces the history carried through the rest of the task.

LemonCrow attacks that cost in four places:

  • discovery,
  • source reading,
  • tool output,
  • session lifecycle.

1. Find the relevant code with fewer calls

Without code intelligence, repository exploration becomes a sequence of guesses: search for a term, open one match, find another symbol, search again, and continue until the call path is clear.

LemonCrow’s search and explore tools combine work that would otherwise require several turns.

Ranked search returns relevant snippets within a fixed token budget. Symbol mode locates definitions without returning entire source bodies. Repository-map mode expands around a small set of seed files.

explore can group source with callers, callees, and usages in one response. When the symbol is already known, it can request only one relation rather than paying for the broader conceptual view.

The saving is not “search is magically free.” The saving is avoided interaction: fewer separate searches, fewer speculative file reads, and fewer model turns spent assembling a call graph manually.

2. Read the shape before reading the body

A full file is often the wrong unit of context.

In mcp_server.py, LemonCrow’s read tool defaults to an outline for code files over 200 lines. The outline contains the file’s structure and line locations. The agent can then request the exact range it needs.

For example, investigating one handler in a 1,000-line module can become:

read module outline
read lines 420-510

instead of:

read all 1,000 lines

For supported languages, source projection can reduce a full view further by removing comments and blank-line noise while retaining a mapping to the original source. When the agent requests a line range, LemonCrow returns an exact slice without the outline and projection metadata that would be redundant.

Batch reads also matter. If three independent files are required, the tool can read them in one call. That avoids additional agent turns whose prompts would each include the conversation history again.

The implementation tracks estimated tokens saved by outlines and projections, but it does not credit the same full-file baseline repeatedly. Once a file’s avoided full read has been counted in a session, later reads do not claim the saving again.

3. Put a budget on search and command output

Search tools can produce more text than the model can use.

LemonCrow’s grep and search surfaces both expose output budgets. The default search budget is 2,000 tokens. Broad matches are ranked, summarized, or returned as file pointers rather than as an unbounded wall of source.

Large command output gets a different treatment. Shell, SQL, and web results have strict inline limits. When a result is too large, LemonCrow stores the complete output and returns a head-and-tail summary with a retrieval reference.

This is cheaper than inserting a 100,000-character log into the conversation, but it does not destroy the evidence. If the failure is in the omitted middle, the agent can retrieve the relevant slice without rerunning the command.

The final JSON-RPC writer also enforces a hard frame limit. That guard is primarily about reliability, but it prevents an oversized result from killing the MCP connection and forcing the session to restart.

4. Do not send the same content twice

LemonCrow keeps a within-session registry for read-style results.

If a tool produces content that is byte-identical to something already returned in the current context epoch, the dispatcher can replace it with a small pointer. For file reads, it can also return a delta when the resource has changed rather than repeating the entire body.

The agent can explicitly force a fresh full result when necessary. Edits and compaction reset the relevant state so a pointer cannot silently refer to stale context forever.

This mechanism addresses a common agent behavior: reopening a file “to be safe” even though the exact content is already in the prompt.

A repeated read is not made faster by prompt caching if the model still has to process and reason over the duplicate result. The cheapest duplicate is the one not emitted.

5. Compact at a useful boundary

Eventually, a long session fills its context window. Compacting too early loses useful detail; compacting too late makes every subsequent turn expensive and risks exhausting the window.

LemonCrow tracks context use in its run ledger. The current implementation begins advising at 60 percent utilization, considers compaction at 80 percent, and prepares a handover at 95 percent.

Automatic compaction is gated by more than a percentage. The runtime looks for enough turns or unusually high utilization and checks for a structured task boundary, such as a passing test or successful command. A model merely saying “done” in free text does not count.

The compacted state preserves recent turns, active errors, recently touched files, pinned memory, and active playbooks. At the handover threshold, LemonCrow writes a packet that a fresh session can read.

The goal is not the smallest possible context. It is the smallest context that still lets the agent continue correctly.

Savings accounting should be conservative

Token-savings claims are easy to inflate, so the adapter contains explicit corrections.

An errored read receives no savings credit because it did not provide usable context. An outline and a later range from the same file cannot both claim that they independently avoided the entire full file. Code-intelligence credit is deferred: LemonCrow records the files surfaced by search or exploration, waits through an observation window, and cancels the credit if the agent reads those files anyway.

Accounting runs outside the model-facing result. It should measure behavior without adding more prose for the model to process.

This is a better way to evaluate context tooling: count what was actually avoided, not what could theoretically have been avoided.

Where the saving comes from

LemonCrow’s cost reduction is the sum of several ordinary decisions:

Source of wasteLemonCrow’s response
Repeated discovery callsRanked search and grouped code intelligence
Reading whole filesOutlines, exact ranges, and source projection
Separate calls for independent filesBatched reads
Unbounded search resultsPer-call token budgets
Huge logs in contextRecoverable spill summaries
Duplicate readsContent pointers and deltas
Overgrown sessionsBoundary-aware compaction and handover
Inflated savings reportsPer-file and per-session credit deduplication

The exact saving depends on the repository and the task. A small change in a tiny project may need only one search and one edit. A cross-cutting change in a large monorepo has much more redundant discovery and context to remove.

That is why the meaningful comparison uses the same model, the same task, and the same repository. LemonCrow does not make tokens cheaper. It helps the agent need fewer of them to reach a verified result.

Evidence and methodology

LemonCrow publishes its benchmark setup, raw reports, and implementation so the savings claims can be checked rather than taken on trust. Results vary by repository size, task, model, and host; the benchmark documentation separates gross context savings from net end-to-end cost.

Inside LemonCrow: technology and design ideas

A technical field guide to LemonCrow's MCP tools, code intelligence, context, memory, workflows, routing, safety, storage, and telemetry.

LemonCrow is easy to describe badly.

Calling it “code intelligence” misses the editing, memory, verification, routing, and workflow systems. Calling it an “MCP server” describes the transport but not what the runtime does. Calling it an “agent framework” suggests that it replaces the coding agent, which it does not.

A more accurate description is this:

LemonCrow is a host-neutral runtime that gives coding agents a structured, code-aware, cost-aware, and verifiable way to work on repositories.

This article is a technical inventory of that runtime. It covers the public product surface, the hidden administrative tools, the internal capability packages, and the technologies used to build them.

Not every item below is enabled, installed, licensed, or shown to the language model by default. LemonCrow deliberately keeps its default tool menu small. Optional backends, internal analytics, Pro features, and experimental capabilities are identified as such.

This inventory was checked against LemonCrow 0.4.25 on June 23, 2026.

Contents

Runtime foundation

The system in one diagram

Claude Code / Codex / OpenCode / another host
                       |
                MCP JSON-RPC
                       |
             LemonCrow gateway layer
     schema validation, routing, isolation
                       |
   +-------------------+-------------------+
   |                   |                   |
code context       tool execution       memory/context
search/index       edit/bash/sql         facts/passages
symbols/graphs     verify/web fetch      reuse/compaction
   |                   |                   |
   +-------------------+-------------------+
                       |
       ledgers, savings, telemetry, policy

The coding model still plans and reasons. The host still owns the conversation, permissions, and user interface. LemonCrow owns the working surface between the model and the repository.

The foundation

The core runtime is Python 3.12+ and is packaged with Hatch. Production wheels can compile the src/atelier package with mypyc, while development uses ordinary Python.

The main technology choices are:

AreaTechnology
Language and packagingPython 3.12/3.13, Hatch, uv workspaces, optional PyInstaller
ProtocolModel Context Protocol, JSON-RPC 2.0, stdio transport, HTTP/SSE transport
Schemas and validationPydantic 2, Python type hints, runtime-generated JSON Schema
CLIClick, Rich, prompt-toolkit
HTTP serviceFastAPI and Uvicorn
Local persistenceSQLite, JSON/JSONL sidecars, filesystem artifacts
Optional persistencePostgreSQL, pgvector
ParsingPython AST, Tree-sitter, tree-sitter-language-pack
Code intelligenceSCIP, Zoekt, ast-grep, LSP adapters, Git history
Text and rankingSQLite FTS, BM25, fuzzy matching with RapidFuzz, cosine/ANN retrieval
Token accountingtiktoken plus model pricing tables
Editingexact replacements, structured descriptors, diff-match-patch, AST rewrites
Git accessGitPython and pygit2
Web extractionurllib3, Beautiful Soup, trafilatura, markdownify
ResilienceTenacity retries, circuit breakers, bounded worker pools
Securitycryptography, redaction policies, path guards, SSRF protection
ObservabilityOpenTelemetry, OTLP, Prometheus, optional Langfuse
Testing and qualitypytest, pytest-xdist, Ruff, Black, mypy, vulture

There are optional integrations for Ollama, OpenAI embeddings, Letta, OpenMemory, LiteLLM, Langfuse, OR-Tools, Rope, PostgreSQL, and pgvector. The default local path does not require all of them.

The public MCP tool surface

LemonCrow registers more capabilities than it advertises. The default language-model surface contains ten tools.

ToolWhat it does
readReads one or many files as an outline, exact range, projected body, or full file
searchRanked code and documentation search, exact symbol lookup, and repository maps
grepRegex, glob, file-type, and multiline search with bounded rendering
exploreConcept exploration or exact definition/caller/callee/usage lookup
codemodAST-shaped search and rewrite through ast-grep, dry-run by default
editDeterministic file, line, notebook-cell, symbol, and projection-aware edits
bashManaged command execution with timeouts, background sessions, polling, and cancellation
sqlSchema inspection, SQL linting, and bounded queries; writes require an explicit opt-in
memoryFact storage, voting, archival recall, and symbol recall
web_fetchPublic URL retrieval with SSRF protection, caching, extraction, and Markdown conversion

The public list is intentionally short. A smaller menu costs fewer schema tokens and gives the model fewer overlapping choices.

Tool definitions come from typed Python functions. LemonCrow inspects each function signature, generates a Pydantic argument model, derives JSON Schema, removes schema noise, and registers the validated wrapper. The same contract drives tools/list and tools/call.

The boundary also repairs common client mistakes: a whole argument object sent as a JSON string, integers and booleans serialized as strings, a single glob sent where an array was declared, or an old parameter name retained by a client. Repair is conservative and validation still happens before the handler runs.

Hidden and administrative MCP tools

The following tools are registered and callable by internal code, tests, the CLI, or power users, but are not advertised to the model by default.

ToolPurpose
contextRetrieves playbooks, bootstrap context, symbols, or a token-bounded subtask context pack
compactCompresses a run ledger, consolidates history, or retrieves spilled tool output
rescueSuggests a different procedure after repeated failure
traceRecords structured task, command, tool, edit, test, and workflow events
verifyRuns a rubric or verification gate and returns structured evidence
agentRuns an LemonCrow-owned sub-agent with provider, model, budget, and cache-affinity control
workflowRuns, inspects, pauses, resumes, or stops durable workflows
graphBlast radius, dead code, cycles, coupling, centrality, doc drift, PR risk, and history analytics
scanBounded ast-grep security rules plus intra-procedural Python taint analysis
orientReturns the deterministic explore -> navigate -> edit -> verify playbook
indexBuilds or refreshes the repository code index
blameReturns Git blame and churn information for files or symbols
cacheReports or invalidates code-intelligence caches
statusline_segmentRefreshes the active session’s precomputed savings display

A user can hide additional public tools with configuration. This is not only cosmetic: every removed schema reduces fixed prompt material and model tool-choice deliberation.

Repository operations

Code intelligence: how LemonCrow understands a repository

LemonCrow does not depend on one universal parser or one universal search algorithm. It combines several sources of evidence and falls back when a richer source is unavailable.

Language registry

The canonical language table recognizes:

  • Python and Python stubs
  • TypeScript and TSX
  • JavaScript, JSX, MJS, and CJS
  • Bash, shell, and Zsh files
  • C and C++
  • C#
  • Go
  • Rust
  • Java
  • Kotlin
  • Scala
  • Ruby
  • Swift
  • PHP
  • SQL
  • Markdown
  • YAML
  • TOML
  • JSON
  • HTML
  • CSS
  • Lua

The registry also records available SCIP indexers. Examples include scip-python, scip-typescript, scip-go, scip-java, scip-ruby, scip-clang, and Rust Analyzer.

Parsing and symbol extraction

LemonCrow uses several parsing paths:

  • Python’s built-in AST for Python definitions, imports, calls, routes, and references.
  • Tree-sitter and the language pack for multi-language parsing and source projection.
  • SCIP artifacts for exact symbols, definitions, usages, and call edges.
  • Language-specific tags as a fallback symbol index.
  • LSP resolvers where language-server information is available.
  • Cross-language reference adapters for boundaries that one language index cannot resolve alone.
  • Markdown heading trees for opt-in design-document indexing.

SCIP artifacts can be generated by LemonCrow, discovered from external tools, read from cache, and watched for changes. The index has lineage metadata so cached data can be tied to the repository and embedder state that produced it.

The search stack includes:

  • exact symbol matching,
  • identifier and camel-case matching,
  • SQLite full-text search,
  • substring search,
  • fuzzy matching,
  • native regex search,
  • managed Zoekt search for large repositories,
  • semantic symbol retrieval when an embedding backend is explicitly configured,
  • Git-history search over commit chunks,
  • deleted-code and historical adapters.

Code semantic search is off by default unless a code embedder is configured. Available backends are local embeddings, OpenAI, Letta, Ollama, or a null backend. Ollama availability is checked at call time and falls back locally when unavailable.

Ranking and packing

Finding candidates is only half the problem. LemonCrow also has to decide which candidates deserve context.

Ranking signals include exactness, lexical score, fuzzy score, semantic similarity, file scope, symbol popularity, call-graph relationships, churn, imports, query intent, and whether the query appears to target tests.

Results are deduplicated, grouped, and fitted to a caller-specified token budget. Oversized candidates can be shortened to signatures, skeletons, or head snippets. Overflow can be written to an artifact rather than silently disappearing.

Search also carries an explicit verdict. A result can be found, missed, absent, or degraded because a search channel is unavailable. Reformulation history distinguishes “the first query missed” from “we have enough evidence that this symbol is absent.” A soft breaker discourages repeated unproductive searches.

Graph analysis

The code graph supports:

  • definition, usage, caller, and callee navigation,
  • transitive caller/callee expansion,
  • reverse-dependency blast radius,
  • affected-test discovery,
  • dead-code candidates,
  • import-cycle detection,
  • afferent and efferent coupling,
  • Martin instability,
  • degree and eigenvector centrality,
  • route and handler extraction,
  • optional synthesized runtime-style edges,
  • PageRank repository maps,
  • doc-to-code drift,
  • PR risk from blast radius, complexity, churn, and test gaps,
  • heuristic commit provenance,
  • symbol and file blame.

Heuristic results are labeled as heuristics rather than presented as compiler truth.

Progressive source reading

LemonCrow treats source text as a hierarchy of views.

Outline

Large code files default to a structural outline rather than a complete body. The outline contains imports, classes, functions, methods, and line numbers.

Range

An exact line range returns only the requested source. Redundant language and projection metadata is removed from ranged responses.

Full

Small files can be returned in full. expand=true requests an exact full read, subject to transport safety limits.

Compact and minified projections

For supported languages, a projected view can remove comments, repeated blank lines, and other low-value detail. LemonCrow reparses minified output to ensure the transform remains structurally valid.

A projection includes a mapping between projected coordinates and original coordinates. An edit can therefore refer to the smaller view while still applying to the real file. If the mapping is ambiguous, LemonCrow can recommend the exact source range to reread.

Large-file continuation

Moderately large files return a line-aligned prefix plus the exact continuation range. Extremely large files are bounded before they are fully materialized in memory.

Batch reads

Independent files can be read in one request. Savings and errors are tracked per file rather than letting one failed batch item invalidate the whole response.

Missing-path correction

When a file path is wrong, LemonCrow searches for nearby basename matches and reports candidates. If no such file exists under the workspace, it says so explicitly to prevent the model from retrying the same dead path.

Editing and code transformation

The edit tool accepts several distinct descriptor families:

  • exact text replacement,
  • file creation or replacement,
  • line-scoped replacement,
  • notebook-cell insert, move, replace, or delete,
  • symbol-body replace, prepend, or append,
  • projection-aware replacement mapped from a compact read.

A batch must use one compatible descriptor family. That keeps the operation deterministic and makes errors attributable to a specific edit shape.

The edit pipeline includes:

  • workspace path confinement,
  • protected-path checks,
  • per-path locks and deterministic lock ordering,
  • pre-edit snapshots,
  • fuzzy matching where exact context has drifted,
  • source-projection coordinate resolution,
  • change collection and unified diffs,
  • formatter or linter hooks,
  • optional verify gates,
  • rollback from snapshots when verification fails,
  • compact success proof,
  • grounding evidence that records which source was read before a target was edited,
  • test-weakening checks for removed assertions, added skips, and similar changes,
  • contract-literal review for stringly typed configuration and wire contracts,
  • automatic reindexing of files changed by structural rewrites.

The separate codemod tool uses ast-grep patterns. It matches syntax rather than text, supports metavariables such as $X and $$$, previews a unified diff by default, and only writes when dry_run=false.

Shell, SQL, and web execution

Shell supervision

The shell surface supports synchronous commands and managed background processes. Background calls return a session handle that can be polled or cancelled.

The wrapper:

  • applies a timeout,
  • preserves useful head and tail output,
  • keeps process-group cancellation under control,
  • blocks destructive commands such as rm -rf, git reset --hard, and git clean -fd,
  • prevents nested interactive shells,
  • redirects file reads and text searches toward the structured LemonCrow tools,
  • renders compact progress, status, duration, and exit information.

Long-running shell, workflow, agent, edit-verification, and web calls use a separate worker pool so they cannot starve cheap reads and searches.

SQL supervision

The SQL tool can discover connections, list tables, inspect schemas and relationships, search schema names, lint SQL, and run bounded queries. It automatically limits result size, enforces timeouts, and keeps writes disabled unless the caller explicitly opts in. Batches report avoided calls.

Web retrieval

The web fetcher accepts public HTTP and HTTPS URLs, blocks local and private targets, applies response and time bounds, caches results briefly, prefers Markdown when available, and can turn HTML into clean Markdown using extraction and conversion libraries.

Context and orchestration

Context engineering

Context engineering is the part of LemonCrow that decides what the model should see now, what can wait, and what must survive later.

Bootstrap context

A cold repository can enqueue background work that builds initial repository knowledge. Later calls reuse the bootstrap blocks rather than recomputing them.

Scoped context

Given a subtask, affected paths, keywords, exclusions, and a token budget, the scoped-context capability assembles the smallest useful context pack. It can combine code search, prior procedures, and known dead ends.

Prompt budgeting

The prompt budget optimizer selects context blocks under a token budget. It can use OR-Tools CP-SAT when installed and has a greedy fallback.

Prompt compilation

The prompt compiler classifies blocks by kind and stability, assembles cache-safe prompts, enforces budgets, and lints ordering. Stable, branch-level, session-level, and turn-level material can be arranged to protect provider prefix caches.

Prefix-cache planning

LemonCrow tracks stable-prefix hashes, cache-read tokens, invalidation reasons, input splits, and cache hit ratios. It can recommend cache-stable ordering and keep owned sub-agent spawns in a shared cache scope.

Result deduplication

Byte-identical read, search, grep, and explore results can be replaced with a small session pointer. File reads can return a delta for a previously seen resource. Compaction advances the deduplication epoch so old pointers do not survive into a context that no longer contains their targets.

Reversible output spilling

Large shell, SQL, web, and extreme file results are written to a spill store. The model receives a bounded head-and-tail summary and a reference. It can retrieve the full output or a slice later.

The order matters: LemonCrow stores the original before any lossy compaction. If the spill fails, it does not pretend the missing detail is recoverable.

Session compaction and handover

The run ledger tracks token use and events. The current policy:

  • advises at 60 percent context use,
  • considers compaction at 80 percent,
  • prepares a handover at 95 percent.

Automatic compaction also considers turn count and structured task boundaries. A passing test or successful command is evidence of a boundary; the model merely claiming success is not.

Compaction preserves recent turns, active errors, recently touched files, pinned memories, active playbooks, and repository instruction hashes. A handover packet lets a fresh agent continue without carrying the entire transcript.

Memory is five different systems

LemonCrow uses the word “memory” for several related but distinct jobs.

Named fact memory

The public memory service stores user-created facts as named blocks. Facts can be recalled and voted up or down. Storage can be SQLite, Letta, or OpenMemory.

Archival recall

Session transcript passages and code chunks are archived, embedded, and ranked. Recall combines BM25 and cosine similarity.

Memory arbitration

Before a fact write, an optional local arbiter compares similar memories and chooses ADD, UPDATE, DELETE, or NOOP. It fails open to ADD if the arbiter is unavailable.

Cross-vendor memory

Read-only adapters ingest native memory files from Claude, Codex, and Gemini into a unified fact representation. They do not mutate the other tool’s files.

Semantic file memory

Despite the name, this is code structure rather than conversational memory. It caches AST-derived file outlines, symbols, imports, and summaries for smart reads and code intelligence.

Related capabilities include symbol recall, session recall, staleness checks, knowledge extraction, playbook retrieval, dead-end tracking, procedure clustering, and sleep-time consolidation of recent traces.

Agents, roles, and workflows

LemonCrow packages role definitions separately from the host that runs them.

The standard roles are:

RoleIntent
codeMain collaborative coding mode
exploreRead-only code investigation
planRead-only implementation planning
executeFocused implementation of an accepted plan
reviewAdversarial read-only verification
researchExternal research with citations
solveAutonomous artifact-first problem solving
autoUnattended end-to-end execution
bareLean autonomous execution without token-heavy tools

The registry stores host-neutral tool policies. Host renderers translate those policies into Claude disallowedTools, OpenCode tool gates, or simpler host instructions. Read-only intent is declared once rather than being reimplemented independently for every host.

The packaged skills add benchmark runs, orchestration, performance review, durable recall, settings, multi-worktree swarm, and browser-based UX review.

Durable workflows

The default execute-review workflow contains explicit phases:

explore -> plan -> critique -> refine -> execute -> review -> fix

Each step has a role, effort level, read-mode hint, and fork relationship. Execution can require a reviewed plan. Review uses a fail-closed contract: missing evidence produces NEEDS_FIX, not an optimistic pass.

Workflow state is persisted. A run can be inspected, paused, resumed, or stopped. Spawn proof record model, provider, cache scope, reuse eligibility, and honored or dropped routing fields.

Owned execution and model routing

LemonCrow can run a sub-agent through configured provider APIs or installed host CLIs. Routing considers:

  • requested quality/cost budget,
  • configured vendors,
  • task complexity,
  • model availability,
  • provider rate limits,
  • high-risk domains and protected files,
  • verifier requirements,
  • cache-eviction cost,
  • model stickiness,
  • previous cache affinity,
  • explicit provider/model overrides.

The route produces a receipt rather than silently pretending a requested model or cache policy was honored.

Cross-vendor routing, quality-aware routing, tier routing, and owned execution are separate layers. This lets the runtime recommend a model, enforce a configured route, or leave the host’s current model untouched.

Reliability and deployment

Verification, safety, and governance

LemonCrow uses different failure policies for different classes of feature.

Optional analytics generally fail open: if PR-risk enrichment or cache diagnostics fail, the core tool result should still return.

Mutation and security boundaries are stricter.

Verification

The verifier runs deterministic lint, typecheck, and test commands over touched files. Failures become structured counterexamples that a later turn can consume. Retry budgets prevent endless repair loops.

Rubric gates, proof gates, and quality-router verifiers add higher-level checks. The live reviewer is opt-in and non-blocking. Review roles are explicitly prevented from editing.

Trajectory monitoring

Six monitors look for:

  • semantic loops,
  • skipped verification,
  • contradictory claims,
  • cyclic compression,
  • late task sprawl,
  • silent topic drift.

A difficulty finite-state machine combines those signals and controls when additional rescue context should be injected.

The dispatcher also detects identical repeated tool calls and can append a soft no-progress note.

Security scanning

The hidden scan tool includes a small, high-signal ast-grep rule pack for patterns such as dangerous eval/exec, interpolated shell=True, SQL string construction, and hardcoded secrets. A bounded Python taint pass follows request, argument, environment, and input sources to selected execution and SQL sinks.

The scanner labels severity, confidence, rule ID, CWE, source, and whether a result is heuristic. It explicitly does not claim to be a complete SAST engine.

Governance and audit

Governance policies define redaction and retention. Audit bundles can be exported and verified. Telemetry paths scrub sensitive arguments. Workspace and request paths are normalized and confined before mutation.

Team capabilities add roles, invites, shared-memory permissions, signed workspace state, audit events, Google OIDC, and usage attribution.

Licensing adds device registration, entitlement checks, local license state, and cryptographic verification.

Cost accounting and optimization

LemonCrow tracks cost at several levels.

Tool token ledger

Input and final emitted output are tokenized per tool. Accounting happens after compaction and spilling, so it measures the payload the host received rather than the hidden original.

Conservative savings credit

Read savings are credited against a full-file baseline once per file and context epoch. Errors receive no credit. Code-intelligence credit is deferred through an observation window and cancelled if the supposedly avoided files are later read.

Session analytics

SQLite analytics store session, token, cache, and cost history. JSONL sidecars provide live savings updates and status-line summaries without injecting those analytics into the model’s prompt.

Pricing

Pricing tables distinguish input, output, cache reads, and cache writes by model. Unknown models are not assigned invented prices.

Counterfactual and benchmark evidence

Counterfactual modules estimate alternative routing and pricing outcomes. Benchmark manifests, gates, and evidence records keep experimental results tied to exact configurations and artifacts.

Optimization advisor

The optimizer works at three levels:

  • real-time per-session budget guidance,
  • cross-session policy analysis,
  • static prompt and quality audits.

It can compare routing and compaction candidates, run non-inferiority checks, maintain optimization history, and prepare policy or pull-request proposals. It does not silently change policy just because a heuristic predicts lower cost.

Reporting

Savings summaries, session reports, dashboards, leadership-facing weekly reports, and audit exports all consume the same underlying traces and ledgers.

Storage and process architecture

LemonCrow is local-first.

The default store is SQLite plus filesystem artifacts under the LemonCrow root. PostgreSQL is available as an alternative store; pgvector is optional for vector workloads. Memory can stay in SQLite or bridge to Letta/OpenMemory.

Concurrency controls include:

  • per-path edit locks,
  • a global state lock for read-modify-write session state,
  • thread-local request and project context,
  • per-session HTTP ledgers with bounded LRU eviction,
  • separate light and heavy request executors,
  • a stdout lock for JSON-RPC frames,
  • process pools for parallel indexing,
  • file locks around shared indexes,
  • bounded caches and retention policies,
  • autosync workers for repository indexes.

The stdio server keeps initialization synchronous, then dispatches ordinary requests concurrently. The HTTP adapter exposes discovery plus request/response and SSE-compatible behavior with body limits and redacted errors.

Host integration

LemonCrow’s runtime detects and adapts to multiple coding hosts. The code contains host paths or projections for Claude Code, Codex, OpenCode, Antigravity, Cursor, Hermes, GitHub Copilot, and LangGraph-style integrations. The default MCP templates currently include Claude, Codex, and Antigravity.

Host integration includes:

  • generated MCP configuration,
  • generated agents and skills,
  • session-start and stop hooks,
  • post-tool verification hooks,
  • status-line sidecars,
  • workspace/session bridge files,
  • host-specific tool-deny policies,
  • model and session detection,
  • local or remote MCP operation,
  • zero-config workspace discovery from Git,
  • background daemon and stack management.

The CLI covers project initialization, updates, host setup, MCP serving, tools, context, memory, recall, playbooks, routes, sessions, savings, benchmarks, swarm, telemetry, database inspection, licensing, services, and administrative operations.

The long tail of internal capabilities

Some subsystems do not need a public tool of their own but are still part of LemonCrow’s architecture.

CapabilityRole
AnalyticsPersistent session, cost, and cache history
Archival recallHybrid passage and code recall
Audit exportSigned/exportable audit bundles
Auth and licensingDevices, entitlements, license verification
Benchmark manifests and gatesReproducible benchmark evidence
Budget optimizerToken-budget selection with CP-SAT or greedy fallback
Code healthDoc drift, PR risk, commit provenance, design-doc recall
ConsolidationSleep-time trace distillation
Context compressionEvent scoring, retention, and dropped-context records
Context reuseRanked procedures and dead-end avoidance
CounterfactualsAlternative cost and capability estimates
Cross-vendor memoryRead-only import from other agent ecosystems
Cross-vendor routingProvider-aware route recommendations
Failure analysisClustering and rescue procedures
GovernanceRetention and redaction policy
Grounded loopSearch-first behavior and evidence before editing
Knowledge extractionDurable facts and procedures from traces
Lesson promotionDrafting and proposing reusable lessons from failures
Live reviewerOpt-in automated review
Memory arbitrationADD/UPDATE/DELETE/NOOP fact decisions
Model routingComplexity tiers, stickiness, and cache-cost awareness
MonitoringFailure-pattern monitors and difficulty FSM
OptimizationPolicy candidates and non-inferiority testing
OrientationStatic tool-selection playbook
Owned sessionsPhase execution, keepalive, cache, and proof
Plugin runtimeHost plugin lifecycle support
Prefix cacheStable-prefix planning and diagnostics
Prompt compilerBudgeted, cache-safe prompt assembly
Proof gateCost-quality acceptance evidence
Provider registryModel discovery and rate limiting
Quality routerRisk-aware tiers and verifier requirements
RegistryCapability dependency graph
Repository mapPageRank-based structural summaries
ReportingDashboards, session reports, weekly reports
Scoped contextMinimal context for one subtask
SecurityBounded SAST and taint analysis
Semantic file memoryAST outlines and symbol maps
Session optimizerReal-time trace costs and budget guidance
Source projectionCompact/minified source plus reversible mappings
Style importMarkdown style-guide collection and chunking
SwarmsMulti-worktree children, waves, ranking, validation, and apply
TeamsRBAC, shared memory, audit, OIDC, attribution
Telemetry substrateShared event bus
Tool supervisionAnomalies, circuit breaking, and metrics
VerificationChecks, structured counterexamples, retry budgets
Workflow runtimeSchemas, durable state, spawn envelopes, pause/resume/stop
Workspace overridesPer-host and per-request project isolation

The ideas that connect everything

The technology list is long, but the system is organized around a small number of ideas.

1. Progressive disclosure

Return the repository map before the files, the outline before the body, and the exact range before the whole module.

2. Preserve the source of truth

Compact views need mappings. Omitted output needs a spill reference. A handover needs the active errors and touched files. Compression should defer detail, not destroy it.

3. Prefer deterministic machinery

Use parsers, indexes, schemas, diffs, locks, budgets, and test commands for work that does not require an LLM. Save model reasoning for decisions that actually need it.

4. Ground before mutation

Search and read evidence should precede an edit. The edit result should record exact affected paths. Verification should run against the resulting artifact rather than the model’s description of it.

5. Keep the public surface lean

A capability can exist without being advertised on every turn. Administrative tools, analytics, and advanced graph operations stay hidden until a CLI, workflow, or power user requests them.

6. Be tolerant at protocol edges and strict at safety edges

Repair stringified JSON and backward-compatible parameter names. Do not be equally permissive about path traversal, destructive shell commands, SQL writes, or unverified edits.

7. Fail open for enrichment, fail closed for proof

Missing cache diagnostics should not break a read. Missing evidence should prevent a review from passing.

8. Account conservatively

Do not count a failed read as a saving. Do not credit the same baseline twice. Do not claim a model price that is unknown. Keep gross context savings separate from net end-to-end benchmark cost.

9. Treat cache stability as a design constraint

Stable schemas, deterministic compaction, prompt-block ordering, model stickiness, and shared cache scopes all protect prefix reuse.

10. Separate host policy from runtime policy

Roles and tool policies are host-neutral. Claude, Codex, OpenCode, and other integrations receive projections of the same intent.

11. Make heuristics honest

PR risk, commit classification, inferred edges, and SAST findings carry confidence and provenance. They are useful signals, not facts disguised as compiler output.

12. Optimize for continuation

A good tool result should make the next decision cheaper. A good session compaction should let work continue. A good failure message should change the next attempt.

That is the unifying idea behind LemonCrow. It is not one clever index or one prompt. It is a collection of small, explicit controls around how an agent finds evidence, changes code, verifies work, spends context, and survives a long task.

Primary implementation sources