# Context selection

> `densityGreedyContextSelection` keeps a selection of messages or tool results within a hard token budget as candidates arrive and expire. Callers supply token counts and a monotone submodular marginal-gain oracle.

`densityGreedyContextSelection` keeps a selection of messages or tool results within a hard token budget as candidates arrive and expire. Callers supply token counts and a monotone submodular marginal-gain oracle.

## Result

> Packing three search hits into 21 words: new-query-terms-first keeps the setup rule and the version caveat in 19 words, where rank-and-truncate drops the caveat

## Modules

* [`knotkit/deque`](/modules/deque/): Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/sampling`](/modules/sampling/): Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests

## Figures

* 3 search hits, 21 words. Keep the setup rule and the version caveat.
* Rank and truncate uses 21 words and loses the version caveat.
* Gain per word uses 18 words and loses the setup rule.
* New query terms first keeps both in 19 words.
* With only the top two hits, the version caveat never arrives. At most 1 of 2 facts survive.
*
* At 0.1× input price, the cached log replaces the search result in a 600-token prompt.
* Prompt 300 → 600 tokens. Gain 9 → 4. Estimated cost 300 → 60 full-price tokens.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/context-selection/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.

## Reproduce

```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:context-selection
```

[`problems/context-selection/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/context-selection/README.md) states the fixture, the seed, and the result table.
