# Wonder: Automatic Context Resets via Memory Reconstruction

## Query
Can we automatically trigger context resets at optimal times to reduce token usage since we're using hooks to automatically inject relevant info all the time? There must be a point at which the context history can be completely reconstructed into the essential information and then completely wiped from context and then re-injected into a prompt with at least the highly relevant stuff but also "breadcrumbs" on how to find more if needed.

## Hypothesis
There exists an optimal point during a session where the information-theoretic value of raw context drops below what agentmemory's persistent belief store can reconstruct. At that point, a proactive context reset + belief re-injection would be more token-efficient than continued accumulation or lossy compaction.

## Methodology
- 2 subagents (prior art research + gap/contradiction analysis)
- Wonder CLI belief retrieval: 72 direct, 42 graph-expanded, 80 uncertain, 11 contradictions
- Sources: academic papers, open-source frameworks, stored belief graph

## Prior Beliefs (from agentmemory)
- [99%] Hook search is active on every prompt (7-layer, ~50ms)
- [95%] "No awareness of when compaction happens" -- system cannot observe its own compression events
- [95%] "No way to evaluate whether compaction lost important information"
- [95%] "The real win is preventing permanent memory pollution, not token savings"
- [94%] No test comparing 2K-token retrieval quality vs 10K-token full dump
- [93%] "Needs periodic compaction or rolling windows"
- [91%] Response quality increases monotonically with token budget up to 10K+ tokens
- [78%] Session crash recovery requires near-full context reconstruction from beliefs

## New Findings

### Agent 1: Prior Art

**Closest prior art: MemGPT/Letta** (Packer et al., 2023). Virtual memory hierarchy with page-in/page-out operations. Key limitation: reactive (triggers at capacity), not proactive (at optimality). https://arxiv.org/abs/2310.08560

**Information-theoretic building blocks:**
- LLMLingua (Microsoft, 2023-2024): perplexity-based token pruning, 2-20x compression. Could measure context degradation. https://github.com/microsoft/LLMLingua
- Compressive Transformers (DeepMind, 2019): learned compression of old activations. https://arxiv.org/abs/1911.05507
- Gisting (Mu et al., 2023): compress prompts into virtual "gist tokens." https://arxiv.org/abs/2304.08467

**Key finding:** The proactive reset -- triggered when `reconstructed_value >= raw_context_value` -- does not exist in the literature. It would be a novel contribution. LLMLingua's perplexity scoring is the best available building block for measuring the "raw context value" side. Agentmemory's confidence-scored beliefs provide the "reconstructed value" side.

**Other frameworks:** LangChain ConversationSummaryBufferMemory (crude threshold-based summarization), Zep (auto-summarization server). Neither has an information-theoretic trigger.

### Agent 2: Gaps and Contradictions

**Non-reconstructable information (fatal gap):**
1. Tool call results: exact file contents, git diffs, error tracebacks. Beliefs store conclusions, not evidence.
2. Partial reasoning chains: hypotheses considered and rejected, ordering of discovery.
3. Positional/relational state: "the file I just read" -- deictic references only meaningful within context.
4. User tone and intent cues: phrasing, emphasis, corrections-in-progress.

**The breadcrumb paradox:** After a reset, re-injected beliefs reference artifacts (file paths, line numbers, error messages) that no longer exist in context. The agent needs context to know what context to restore -- a circular dependency.

**Timing problem:** The agent cannot evaluate its own context quality from inside the context. An external hook can measure token count but not semantic coverage. The belief "tokens but not coverage" (0.93 confidence) directly flags this gap.

**Compaction vs. reset:** Compaction degrades gradually. A hard reset is a cliff edge. Compaction preserves conversation continuity; a reset breaks it entirely and relies on reconstruction. The stored belief about "preventing memory pollution" suggests the real value is in filtering, not resetting.

**Information loss cascades:** After a reset, the agent cannot know what it doesn't know. If reconstruction misses a critical constraint, the gap is invisible. Unlike compaction where degraded information is still partially present, a reset creates hard zeros.

## Contradictions
- Belief: "Response quality increases monotonically with more context" vs. the hypothesis that less (but better) context could match quality
- Belief: "The real win is preventing pollution, not token savings" vs. the query's focus on token usage reduction
- "No awareness of when compaction happens" contradicts the ability to trigger proactive resets

## Gaps and Open Questions
1. No empirical data on reconstruction fidelity -- how much of a session's working state can beliefs actually recover?
2. No measurement of the "context degradation curve" -- when does raw context become less valuable than retrieved beliefs?
3. The boundary between "compaction-time filtering" and "hard reset + reconstruct" needs a quantitative criterion
4. Who triggers the reset? Claude Code's compact events are not externally observable by hooks
5. Surprise-based segmentation (cognitive science: Zacks & Tversky, 2001) suggests checkpointing at task transitions, not at token thresholds -- but agentmemory cannot detect task transitions from outside

## Proposed Experiments

### Exp A: Reconstruction Fidelity Audit
Take 5 real sessions with known outcomes. At the midpoint, snapshot the raw context. Use only agentmemory beliefs to reconstruct the working state. Measure: what percentage of task-critical information is recoverable? What categories are lost?

### Exp B: Compaction Quality Measurement
Hook into PreCompact/PostCompact events. Before compaction, extract the "essential state" via belief search. After compaction, compare what survived vs. what the belief store would have provided. Measures whether compaction is already doing what the proposed reset would do.

### Exp C: Perplexity-based Degradation Curve
Use a small model to score per-token perplexity of the context window at intervals during a session. Plot the curve. Identify if there is a natural inflection point where context becomes "stale" relative to the current task.

### Exp D: Breadcrumb Retrieval Latency
After a simulated reset, measure how many additional tool calls the agent needs to re-acquire information that was in the pre-reset context. If the overhead exceeds the token savings, the reset is counterproductive.

## Verdict
The idea is theoretically sound but practically premature. The fatal gap is non-reconstructable information (tool results, reasoning chains, deictic references). The more productive path is:
1. Better compaction-time filtering (inject belief-based summaries into the compaction prompt)
2. PreCompact hook that snapshots critical state before lossy compression
3. Measure reconstruction fidelity before attempting automated resets

The novel contribution -- a crossover decision function comparing reconstruction quality vs. raw context value -- is real and publishable, but needs the empirical foundation from Exps A-D first.
