Repository navigation
Description
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 write_file echoes back the entire file the model just wrote #762 git_diff truncation is head-only, dropping the end of large diffs #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 [Feature] Token Usage & Cost Indicator per Response #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 write_file echoes back the entire file the model just wrote #762 git_diff truncation is head-only, dropping the end of large diffs #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 Bash output truncation is head-only, discarding the tail where build and test errors live #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
- I have searched existing issues to ensure this is not a duplicate
- 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)
Activity
Dhirenderchoudhary commentedon Aug 28, 2026
@akramcodez as i worked on semantic memory feature can i take this one
akramcodez commentedon Aug 29, 2026
Sure @Dhirenderchoudhary, but can you first provide a detailed implementation plan backed by thorough research on how we can implement this properly?
Dhirenderchoudhary commentedon Aug 29, 2026
@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.
Dhirenderchoudhary commentedon Sep 2, 2026
@akramcodez Did you checked my approach
akramcodez commentedon Sep 4, 2026
@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:
I would also like you to go deeper on the
read_filestub 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.
Dhirenderchoudhary commentedon Sep 4, 2026
@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
performAutoCompactis insource/utils/auto-compact.ts. defaults fromloadAutoCompactConfiginsource/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
performAutoCompactis the tui loop (conversation-loop.tsx~560)./compactis a different path —compact-handler.tscallscompressMessages/summariseWithLLMdirectly. it does not go throughperformAutoCompact.tui already caps too, before the request (
conversation-loop.tsx~300):capMessagesForModelthenclient.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.--plainisrunPlainConversationinsource/plain/conversation.ts. cap at ~162, chat at ~168. no auto-compact import.acp is
runAcpConversationinsource/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 doesclient.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_replaceand overwrite-write_filerefuse if unseen./clearwipes it increateClearMessagesHandler(app-util.ts~612).read_filestill returns the body every time.metadata_onlyreturns before anymarkFileSeen— 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)truncateToolResultatTRUNCATION_OUTPUT_LIMIT(2000), head+tail/usagealready existlsp_get_diagnosticsonly. no import graphso the hole is the other three loops, plus repeat
read_file.phase 1 — call the compact we already have
problem
autoCompactis on by default but only the tui hitsperformAutoCompact.--plain, acp, and subagents never do. that’s why local models die there.reuse
performAutoCompactas-is. same config. no new summariser, nocontextBudget.add
maybeAutoCompactnext to it: if compact is off, below threshold, or throws, return the same array. tui stays onperformAutoCompactso notify +setMessageskeep working. the other three use the wrapper and pass noonNotify, so we don’t print “auto-compacting…” into ci or the editor.performAutoCompacthas 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:
after, for plain / acp / subagent, same spot as tui (after the assistant message is on the history):
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 splitmessages[0]off, compact the rest, cap the rest, thenclient.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.tsdocs/features/context-compression.md— same settings on all four./compactstays tui-only.tui / --plain / acp / subagent
tui: no change.
--plainand acp: compact, then the cap they already have.subagent: compact + cap. that’s the new part.
what can break
toolrow.capMessagesForModelalready does that (message-capping.ts~25–27). don’t bypass it.tests
performAutoCompactspec)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 worthlessmaxMessages = 3, a few tool turns. last payload still starts with system, history does not start ontool, shorter than uncappedthen phase 2
those specs pass,
tsc --noEmitclean. 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
executeReadFiledumps 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,
hasSeenFileis still true, andstring_replacelets it inventold_str. the comment onread-tracker.tsalready says over-enforcement is what we have to avoid. stub state has to be a second map.reuse
same
read_filetool. tui /--plain/ acp / subagent all go throughexecuteReadFile.lstatfor mtime+size (file-cache.tsalready invalidates on mtime)./clearalready has one wipe inapp-util.ts.how i know the file didn’t change
second map, same module as the edit guard so
/clearstays one function:absPath → { mtimeMs, size, generation }generationstarts 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_*inconstants.ts), store mtime + size + current generation.next
read_fileon that path, nostart_line/end_line,metadata_onlynot set:lstatfirst. don’t fill the cache just to decideno 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=truei’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) →
markFileSeenon the three content paths (empty file ~110, preview ~131, full/range ~147).after: stub check at the top of
executeReadFile. stub does not callmarkFileSeen.metadata_onlystill does not mark seen.the interactions you asked about
/clear— wipe both maps. next read is real. edit guard resets, same as now./clearis tui;--plainsessions are one-shot anyway.auto-compact and
/compact— bump generation only. do not clearseenFiles. 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 alreadymarkFileSeen+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_replacealready fails ifold_strdoesn’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_CONTENT_MARKER, still mark seenstart_linepast the preview still does a real range./foovsfoo:resolve(), same asmarkFileSeenlstatthe path we resolved, don’t follow for identitytests
start_line/end_line→ range, never stubmetadata_only→ metadata, don’t write the stub mapclearReadTracker→ body againstring_replaceafter a stub: still allowed if there was a real read earlier; after/clear, still blockedthen 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_filegives the file back.after that i’d stop
not doing dual compact/full on every tool, lsp import trim, a
contextBudgetpref (that’s a second knob next toautoCompact.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.
akramcodez commentedon Sep 14, 2026
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?
addyCooks commentedon Sep 15, 2026
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 to
clearReadTracker().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 : )
Dhirenderchoudhary commentedon Sep 16, 2026
@addyCooks Thanks for the follow will raise my side PR today
fix: use params.sessionId for the /clear stub reset and refer to Nano…
fix: reset read_file stubs when the history is swapped (#1678)