#4999: fix(memory-flush): use contextTokens instead of totalTokens for threshold check
Cluster:
Memory Management Enhancements
## Problem
`shouldRunMemoryFlush()` was using `totalTokens` from the session entry to decide if a memory flush should trigger before compaction. However, `totalTokens` is set by `session-usage.ts` with **tokens from the last turn only**, not the cumulative context size.
This caused memory flush to never trigger because it compared ~30k tokens (last turn) against the ~176k threshold, even when actual context was 188k tokens.
## Solution
Changed `shouldRunMemoryFlush()` to use `contextTokens` instead, which correctly represents the actual context window usage.
## Changes
- `src/auto-reply/reply/memory-flush.ts`: Use `contextTokens` instead of `totalTokens`
- `src/auto-reply/reply/memory-flush.test.ts`: Updated tests to match
<!-- greptile_comment -->
<h2>Greptile Overview</h2>
<h3>Greptile Summary</h3>
This PR fixes pre-compaction memory flush triggering by switching the threshold check in `shouldRunMemoryFlush()` from `totalTokens` (apparently last-turn tokens) to `contextTokens` (actual context window usage), and updates the associated unit tests accordingly.
Within the auto-reply compaction/memory-flush flow, this makes flush decisions reflect the real prompt/context size so the flush can trigger when the session is near the context limit.
<h3>Confidence Score: 3/5</h3>
- Mostly safe to merge, but includes an accidental symlink that should be removed.
- The core logic change is small and well-covered by updated tests, but the PR also introduces a `workspace` symlink to an absolute local path which will break in other environments and is likely unintended.
- workspace
<!-- greptile_other_comments_section -->
<sub>(2/5) Greptile learns from your feedback when you react with thumbs up/down!</sub>
<!-- /greptile_comment -->
Most Similar PRs
#12254: fix: add minimum token guard to prevent double compaction after flush
by Yida-Dev · 2026-02-09
87.7%
#20713: fix(compaction): trigger memory flush after missed compaction cycles
by zerone0x · 2026-02-19
85.4%
#15945: fix(memory-flush): only write memoryFlushCompactionCount when compa...
by aldoeliacim · 2026-02-14
85.4%
#15196: fix: clear stale token totals after compaction
by bufordtjustice2918 · 2026-02-13
85.4%
#15173: fix(session): reset totalTokens after compaction when estimate unav...
by EnzoGaillardSystems · 2026-02-13
85.1%
#17041: fix(memory-flush): add softThresholdPercent for context-relative th...
by Limitless2023 · 2026-02-15
82.0%
#12760: fix(memory-flush): fire on every compaction cycle instead of skippi...
by lailoo · 2026-02-09
82.0%
#9012: fix(memory): resilient flush for large sessions [AI-assisted]
by cheenu1092-oss · 2026-02-04
81.6%
#18997: fix: improve context overflow error messages and docs
by realhoratiobot · 2026-02-17
80.7%
#8919: Pr/memory flush improvements
by shortbus · 2026-02-04
80.0%