# `SuperPi.Durable.Context`
[🔗](https://github.com/oleksandr/super-pi-beam/blob/v0.1.0/lib/super_pi/durable/context.ex#L1)

Normative 10-Rule Context Derivation Engine (`packages/durable/docs/spec.md` §2.1).

Responsibilities:
1. Walk conversation fork ancestry (`libgraph` DAG) to collect visible entries in order.
2. Replay positional `pi.system` entries (`full` baseline + `delta` prompt sections and tools)
   and append minimal `delta` entries when configuration changes so provider prompt caches stay warm.
3. Slice the active window from the newest visible `head_entry_id` marker (`pi.compaction` or `pi.reset`).
4. Apply non-destructive `ContextEdit` operations (`omit` and `replace`) in entry order.

# `derived_context`

```elixir
@type derived_context() :: %{
  conversation_id: integer(),
  ancestry_graph: Graph.t(),
  system_sections: [%{required(String.t()) =&gt; String.t()}],
  system_prompt: String.t(),
  tools: [map()],
  head_marker_entry_id: integer() | nil,
  active_entries: [SuperPi.Durable.Schemas.Entry.t()],
  messages: [map()]
}
```

# `derive`

```elixir
@spec derive(integer(), {[SuperPi.Durable.Schemas.Entry.t()], Graph.t()} | nil) ::
  derived_context()
```

Derives the active LLM context for `conversation_id` according to the 10-rule specification.
`visible` is the result of `visible_entries_with_graph/1` when the caller already has it.

# `ensure_system_state!`

```elixir
@spec ensure_system_state!(
  integer(),
  [map()],
  [map()],
  [SuperPi.Durable.Schemas.Entry.t()] | nil
) ::
  {:unchanged | :full | :delta, SuperPi.Durable.Schemas.Entry.t() | nil}
```

Compares `desired_sections` and `desired_tools` against the conversation's replayed `pi.system`
state. Appends a `"full"` baseline on first request, a `"delta"` entry only when a section or tool
changed, or nothing when unchanged (preserving LLM prompt cache prefixes).

# `visible_entries_with_graph`

```elixir
@spec visible_entries_with_graph(integer()) ::
  {[SuperPi.Durable.Schemas.Entry.t()], Graph.t()}
```

Builds the fork ancestry DAG (`Graph`) and returns all visible entries for `conversation_id`
in chronological order, respecting `parent_entry_id` fork cutoffs.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
