# Engram: Context Lifecycle Integration Findings

**Source**: Star Context Lifecycle design session (2026-02-02)
**Design doc**: `docs/plans/2026-02-02-star-context-lifecycle-design.md`

## What Star needs from Engram

### New daemon action: `context_monitor`

The Star statusline hook will send `used_percentage` to the daemon via socket every ~300ms. The daemon needs to:

1. Track `ContextSample(timestamp, used_pct, turn_number)` per `session_id`
2. Calculate velocity as moving average of last 5 samples
3. Calculate ETA: `(75 - used_pct) / velocity`
4. When ETA thresholds are crossed, generate an adaptive handoff document
5. Set a `handoff_ready` flag that Star's Stop hook will check

### New files needed

- **`handoff.py`** — Handoff schema with 6 typed templates. Session type classifier that analyzes stored memories for current `session_id`:
  - `file_ownership` entries → CODING
  - Decisions with "error" / many short checkpoints → DEBUG
  - References to PLAN.md / wave / task → GSD_EXECUTION
  - Voyager output / research_meta → VOYAGER
  - reporter_search / query_cache → BEACON
  - Default → RESEARCH

- **`calibration.py`** — Threshold config with adjustable defaults, per-type velocity baselines. All initial values are educated guesses.

### daemon.py changes

```python
# New data structure
@dataclass
class ContextSample:
    timestamp: float
    used_pct: float
    turn_number: int

# New state tracking
self._context_history: dict[str, list[ContextSample]] = {}
self._handoff_flags: TTLCache  # session_id -> bool, 1h TTL

# New action: context_monitor
# Receives: session_id, used_pct, turn_number, beacon_profile (optional)
# Returns: { advisory: bool, handoff: bool, emergency: bool, eta: int }
```

## Design constraint: hooks cannot trigger /clear

The Claude Code hook system is **one-way reactive**. No hook can execute `/clear` or `/compact`. The best achievable UX is:

1. Stop hook returns `decision: "block"` with reason text
2. Claude reads reason, uses `AskUserQuestion` (clickable buttons)
3. User clicks "Fresh start"
4. Claude says "type `/clear`"
5. User types `/clear`
6. SessionStart hook fires → daemon returns handoff

## Key insight: better context saves tokens

A structured handoff of ~500 tokens prevents ~5000 tokens of re-exploration. The daemon-generated handoff (no LLM involved) is faster and more precise than `/compact` (LLM summarization).

## Failure modes to address

- Daemon crash during handoff generation → fallback to existing checkpoint system
- Socket timeout during context_monitor write → statusline must fire-and-forget (non-blocking)
- Session type misclassification → handoff includes generic fields as fallback alongside typed fields
- Velocity prediction with insufficient samples (< 3 turns) → defer to EMERGENCY threshold only
