[Feature] Semantic Context Compiler (Intelligent Context Budget Management)
Description
Introduce a "Semantic Context Compiler" - a pipeline that runs before and during each agent turn to intelligently prune, deduplicate, and compress context before it is sent to the LLM. This unifies and resolves the root cause behind a cluster of existing issues (#762 #770) under a single, principled architecture rather than one-off per-tool fixes.
No open-source terminal coding agent has implemented a systematic, cross-tool context budget manager. This would be a genuine first and is especially critical for Nanocoder's core audience: local model users with smaller context windows.
Use Case
- A developer is 30 turns into a session on a 50,000-line codebase. The context window is filling up with stale file contents, repeated tool results, and redundant metadata. Model quality degrades and costs spike.
- A user on a local Ollama model (e.g., Llama 3.2 with an 8K context) is effectively blocked from working on any medium-sized project because tools flood the context before useful reasoning can happen.
- A power user on OpenRouter wants to minimize API costs on a long refactor session without manually managing what's in context.
Proposed Solution
The compiler runs as a middleware layer between tool execution and message assembly, with five stages:
- Semantic Deduplication - track a "seen symbols" registry per session. If a file or symbol has already been read, inject a lightweight reference stub (
[file: src/foo.ts - already in context, last read 3 turns ago]) instead of the full content. - LSP-Aware Dependency Trimming - use the existing LSP integration to resolve only the import chain relevant to the current task. Only pull transitive dependencies that the model demonstrably needs.
- Tool Result Compression - structured, token-optimal responses from all tools. Each tool declares a
compactoutput format alongside itsfulloutput. The compiler selectscompactwhen the context budget is under pressure. (This subsumes the individual fixes tracked in #762 #770.) - Context Budget Enforcement - a configurable hard cap on total context tokens per turn (e.g.,
"contextBudget": 32000in preferences). When the cap is approached, the compiler runs an LRU eviction pass weighted by recency and a relevance score derived from the current task description. - Visible Context Meter - a TUI element (aligned with #756's token usage indicator request) showing current context usage vs. budget, updated live per turn.
Alternatives Considered
- Per-tool one-off fixes - the current approach (issues #762 #770). Each tool gets patched individually. This is necessary short-term but leaves the root problem (no budget management) unaddressed and leads to an ever-growing list of similar issues.
- Truncation-only - simply cutting tool results at N characters. Crude, loses tail data (where errors live - see #764), and provides no intelligence about what to keep vs. evict.
- Leaving it to the model - models are increasingly good at ignoring irrelevant context, but this is wasteful and fails entirely on local models with hard context limits.
Additional Context
- [x] I have searched existing issues to ensure this is not a duplicate
- [x] This feature aligns with the project's goals (local-first AI assistance)
Related issues: #756 (Token Usage indicator), #760 (read_file round-trip), #762 (read_file markFileSeen), #763 (write_file echo), #764 (bash truncation tail), #765 (edit tool line prefixes), #766 (search_file_contents formatting), #767 (list_directory byte sizes), #768 (toLocaleString separators), #769 (global tool result cap), #770 (git_diff ceiling)
@akramcodez as i worked on semantic memory feature can i take this one
Sure @Dhirenderchoudhary, but can you first provide a detailed implementation plan backed by thorough research on how we can implement this properly?
@akramcodez I sat with this and researched before writing any code
I dont think the right move is a new 5 stage compiler sitting in front of every turn. a lot of this is already in the tree, just not named that.
we already compact. /compact and auto-compact, default on at 60% of the model window, llm summary with mechanical fallback. it even counts tool schemas so it matches the ctx% in the status bar. but it only runs in the tui loop, after the assistant replies. headless, acp, and subagents never call it. subagents also skip the message cap. thats the actual hole for local 8k models, not missing architecture.
tool results are already capped. global head+tail at 20k, bash at 2k. write_file already returns stats, it does not echo the file back. git_diff already --stats big multi file diffs. the meter is already there, ctx% and /usage.
markFileSeen is not dedup. its a read-before-edit guard so small models dont invent old_str. read_file still dumps the full file every time even if we just read it. thats the only real piece of stage 1 that isnt done, and it has to be based on the file actually changing, not that seen set, or the edit guard breaks.
lsp is diagnostics. there is no import graph to trim. a contextBudget pref would just be a second knob next to autoCompact.threshold. lru-by-relevance needs a scorer we dont have. compact already drops the old half and keeps recent turns.
so what I would actually do:
first, run the same auto-compact and message cap on headless, acp, and subagents. no new summariser. thats the local model fix.
then maybe a read stub: same path, last few turns, mtime/size unchanged, return a one liner instead of the body. model can still force a real read with line range or metadata_only. tests for file changed and /clear.
then stop. dual compact/full on every tool, lsp import trim, a second budget pref, another meter, I would not touch unless 1 and 2 are not enough in real sessions.
if you still want the full compiler as one package say so and I will redraw. otherwise I start with the wiring once you confirm.
@akramcodez Did you checked my approach
@Dhirenderchoudhary Yeah, I checked your approach, and I think the direction makes sense. I especially like that you looked at what already exists in the codebase instead of adding a completely new architecture that could duplicate the current compaction and context-management mechanisms.
Before we proceed, can you give me a detailed implementation plan with clearly separated phases?
For each phase, please explain:
- The exact problem it solves
- Which existing parts of the codebase you plan to reuse or modify
- The expected execution flow before and after the change
- The specific files/modules you expect to touch
- How the changes will work across TUI, headless, ACP, and subagent flows
- Edge cases and potential regressions we should consider
- The testing strategy for that phase
- Clear success criteria before moving to the next phase
I would also like you to go deeper on the read_file stub approach, especially how you plan to determine that a file has not changed, how the model can explicitly request the full content again, and how this interacts with /clear, compaction, edits, and multiple reads of the same file.
Please structure the plan into properly separated phases so we can review the architecture and implementation depth step by step. If the plan looks solid after reviewing it, I'll confirm and you can start implementing it.
@akramcodez went back through the files again before sending this. a couple things in my head were slightly wrong so this is the corrected version.
still the same call: no 5-stage compiler. two phases, then stop.
what is actually in the tree
performAutoCompact is in source/utils/auto-compact.ts. defaults from loadAutoCompactConfig in source/config/index.ts: enabled true, threshold 60, strategy llm, mechanical fallback if the llm path throws. it adds native tool-schema tokens to the gate so it matches ctx%.
the only caller of performAutoCompact is the tui loop (conversation-loop.tsx ~560). /compact is a different path — compact-handler.ts calls compressMessages / summariseWithLLM directly. it does not go through performAutoCompact.
tui already caps too, before the request (conversation-loop.tsx ~300): capMessagesForModel then client.chat([systemMessage, ...capped]). after the assistant message is appended (~533–548) it compact, then tools (~687). so tui is: cap → chat → append assistant → compact → tools.
--plain is runPlainConversation in source/plain/conversation.ts. cap at ~162, chat at ~168. no auto-compact import.
acp is runAcpConversation in source/acp/acp-conversation.ts. cap at ~177, chat at ~183. same, no compact.
subagents (source/subagents/subagent-executor.ts): messages start as [{role:'system', ...}, ...initial] (~148–151), then the loop does client.chat(messages, tools, ...) at ~436. no cap, no compact. system row stays in the array the whole time. that’s the 8k killer.
markFileSeen (read-tracker.ts) is the read-before-edit guard. string_replace and overwrite-write_file refuse if unseen. /clear wipes it in createClearMessagesHandler (app-util.ts ~612). read_file still returns the body every time. metadata_only returns before any markFileSeen — that part is already correct.
the rest of the original issue is already shipped:
write_filereturnsFile written/overwritten successfully (N lines, …)— no echogit_diff: oversized multi-file diffs switch to--stat. a single big file still returns a truncated patch (git-diff.tsx~73–90)- bash uses
truncateToolResultatTRUNCATION_OUTPUT_LIMIT(2000), head+tail - ctx% +
/usagealready exist - lsp is
lsp_get_diagnosticsonly. no import graph
so the hole is the other three loops, plus repeat read_file.
phase 1 — call the compact we already have
problem
autoCompact is on by default but only the tui hits performAutoCompact. --plain, acp, and subagents never do. that’s why local models die there.
reuse
performAutoCompact as-is. same config. no new summariser, no contextBudget.
add maybeAutoCompact next to it: if compact is off, below threshold, or throws, return the same array. tui stays on performAutoCompact so notify + setMessages keep working. the other three use the wrapper and pass no onNotify, so we don’t print “auto-compacting…” into ci or the editor.
performAutoCompact has no abort signal today. i’m not going to invent one in this phase. if it throws, leave history (tui already does that at ~593).
before / after
today:
- tui: cap → chat → append assistant → compact → tools
- plain + acp: cap → chat. never compact
- subagent: chat(full array including system)
after, for plain / acp / subagent, same spot as tui (after the assistant message is on the history):
- maybeAutoCompact
- capMessagesForModel (already on plain/acp; new for subagents)
- client.chat
subagent catch, because i actually looked at the array: compact does allMessages = [systemMessage, ...messages] then strips system from the return (auto-compact.ts ~135 and ~206–219). if we pass the subagent array in as-is we prepend system twice and double-count tokens. so split messages[0] off, compact the rest, cap the rest, then client.chat([system, ...history]) every turn.
pass native tools into the gate unless tools are disabled. tui already does that (result.toolsDisabled ? undefined : tools). xml/json fallback already has the defs in the system prompt.
files
source/utils/auto-compact.tssource/plain/conversation.tssource/acp/acp-conversation.tssource/subagents/subagent-executor.ts- one line in
docs/features/context-compression.md— same settings on all four./compactstays tui-only.
tui / --plain / acp / subagent
tui: no change.
--plain and acp: compact, then the cap they already have.
subagent: compact + cap. that’s the new part.
what can break
- compact throws → leave history
- cap after compact still has to walk back if the slice starts on a
toolrow.capMessagesForModelalready does that (message-capping.ts~25–27). don’t bypass it. - no notify on the non-tui paths
tests
- wrapper: compact off → same array. over the gate, force mechanical → returned history has no system role (same assertion as the existing
performAutoCompactspec) - plain + acp: pad history over the 50% min threshold, mechanical, second
client.chatpayload shorter than the filler. put the filler behind two older messages — mechanical keeps the last 2 (DEFAULT_KEEP_RECENT_MESSAGES) so if the filler is recent the test is worthless - subagent:
maxMessages = 3, a few tool turns. last payload still starts with system, history does not start ontool, shorter than uncapped
then phase 2
those specs pass, tsc --noEmit clean. this is also #1048. i’d ship it as its own pr and just ref 793 unless you want it all here.
phase 2 — read_file stub
problem
executeReadFile dumps the body on every call. that’s the only leftover from “dedup” that isn’t already handled.
not using markFileSeen
if we stub off that set, compact drops the old read from history, the model only has a stub, hasSeenFile is still true, and string_replace lets it invent old_str. the comment on read-tracker.ts already says over-enforcement is what we have to avoid. stub state has to be a second map.
reuse
same read_file tool. tui / --plain / acp / subagent all go through executeReadFile. lstat for mtime+size (file-cache.ts already invalidates on mtime). /clear already has one wipe in app-util.ts.
how i know the file didn’t change
second map, same module as the edit guard so /clear stays one function:
absPath → { mtimeMs, size, generation }
generation starts at 0.
this has to bump in both compact paths, because they are not the same function:
performAutoCompact(tui auto, and the new wrapper)handleCompactCommandincompact-handler.ts(manual/compact)/compact --restorein that same handler (~58–75) — bump again. restored messages might have the file, they might not. re-read is safer.
after a read that actually returned bytes (full file, a range, or the 250-line preview when the file is over 1500 — FILE_READ_PREVIEW_* in constants.ts), store mtime + size + current generation.
next read_file on that path, no start_line/end_line, metadata_only not set:
lstatfirst. don’t fill the cache just to decide- mtime or size changed → real read, update the entry. mtime alone misses two writes in the same second
- generation != current → real read. the old body is gone
- else → one liner
no hashing. no seen-symbols registry.
generation instead of “last N turns” because both compact paths delete or summarise old tool results. “we read this earlier this session” would lie after compact.
how the model asks for the file again
skip the stub if:
start_line/end_lineis setmetadata_only=true- mtime or size changed
- generation mismatch
i’ll put that in the tool description. stub text something like:
[file: src/foo.ts — already in context, unchanged since last read (1234 lines). pass start_line/end_line or metadata_only to read again.]
before / after
today: every read → cache/disk → body (or preview / metadata) → markFileSeen on the three content paths (empty file ~110, preview ~131, full/range ~147).
after: stub check at the top of executeReadFile. stub does not call markFileSeen. metadata_only still does not mark seen.
the interactions you asked about
/clear — wipe both maps. next read is real. edit guard resets, same as now. /clear is tui; --plain sessions are one-shot anyway.
auto-compact and /compact — bump generation only. do not clear seenFiles. if we clear the edit guard, every edit after compact bounces “read first”. if we stub and keep seen, they edit blind. so: bump generation (next read is real), leave seen alone so an edit right after compact still works if they already had the file.
/compact --restore — bump generation. see above.
edits (write_file, string_replace, diff-edit) — they already markFileSeen + invalidateCache. drop that path from the stub map. next read is real.
multiple reads, same file, nothing changed, same generation — first is the body, rest are stubs.
external edit on disk — next read sees mtime/size change, full body. seen might still be true; string_replace already fails if old_str doesn’t match.
tui / --plain / acp / subagent
one tool, so all four stub. the map is process-global, same as seenFiles. failing to stub is safe. blocking an edit is not. not making it per-conversation unless parent/subagent actually step on each other.
other edges
- empty file: keep
EMPTY_CONTENT_MARKER, still mark seen - big-file preview (first 250 of >1500): counts as a real read. later un-ranged read stubs.
start_linepast the preview still does a real range ./foovsfoo:resolve(), same asmarkFileSeen- symlink:
lstatthe path we resolved, don’t follow for identity
tests
- same path, same mtime/size, same generation → stub
- touch the file or change size → body
start_line/end_line→ range, never stubmetadata_only→ metadata, don’t write the stub map- bump generation → body again
clearReadTracker→ body againstring_replaceafter a stub: still allowed if there was a real read earlier; after/clear, still blocked- write then read → not stubbed
then we stop
repeat read of an unchanged file in the same window is a one-liner. edit still refuses if they never got a real body this session. compact then read_file gives the file back.
after that i’d stop
not doing dual compact/full on every tool, lsp import trim, a contextBudget pref (that’s a second knob next to autoCompact.threshold), or another meter.
if 8k sessions still blow up after 1 and 2, we tighten the existing threshold. we don’t invent a compiler.
two prs: phase 1 first (probably closes #1048), then the stub. close 793 after the stub if you’re ok leaving the rest.
if this looks right i’ll start on phase 1.
Hey @Dhirenderchoudhary, just checking in. Thanks for the detailed implementation plan - the approach looks good to me. Have you started working on Phase 1 yet?
Hey @Dhirenderchoudhary, following up from #1186: @will-lamerton asked me to bring my Phase 1 dedup mechanism here instead of building it separately. These are notes for your implementation, not a competing plan.
-
Identify repeats from the tool call, not the result. Use the call's arguments (
path,start_line,end_line) rather than parsing result text, which breaks when a formatter changes. -
Check freshness with a content hash. Same call and same hash: replace the result with a short stub naming the file, line range and step. Different hash: send the full content again.
-
Keep the ledger per conversation. Don't extend
read-tracker.ts: it's shared across the whole process, so a subagent would get stubs for content it was never shown. -
Rebuild it on
--continue/--resume, and clear it on/clear, next toclearReadTracker(). -
Measure success by cost, not tokens. Rewriting earlier messages can invalidate the provider's prompt cache, and
source/usage/response-usage.tsalready prices cache reads and writes separately. -
Put it behind a flag that defaults to off, so nothing changes until real cost numbers are in.
The full reasoning is in #1186 under Proposed Solution A
I hope some of this is useful please use whatever fits your approach and skip the rest, and I'm glad to explain any part of it if that helps : )
@addyCooks Thanks for the follow will raise my side PR today