> ## Documentation index
> Fetch the complete documentation index at: https://k7d.org/llms.txt
> Ask it with GET https://k7d.org/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.

# GRPO / agent tree search

> Wire k7d into a GRPO trainer, a tree-search agent, or an MCP-driven frontier model: fork_batch, protect, prune, auto_evict

If you already have Kubernetes tasks or scenarios (a Helm chart, a set of YAML manifests, an eval harness that talks to a kube-apiserver), the shape is:

1. **Boot the scenario once** — bring up your cluster (or adopt a running one that k7d already hosts) and wait until it is in the state you want every rollout to start from.
2. **Root a tree at that checkpoint.**
3. **For each GRPO group (or tree-search step):** `tree_fork_batch(N)` → run your N policies against the N copies → score → `tree_protect` the winners, `tree_prune` the losers → let the daemon `tree_auto_evict` under your RAM/disk budget.
4. **Roll forward** from a protected winner when you want the next generation to start from a better state, or `tree_rollback` to an earlier node when you don't.

Your training loop owns rewards and policy. k7d owns environments and budgets.

## Why byte-identical starts matter for GRPO

GRPO (and most group-relative methods) compare rewards *within a group*. If member A starts from a colder cache, a different etcd revision, or a half-ready Deployment than member B, the reward gap is noise, not signal.

A k7d fork is a copy of the live machine — same memory, same disk, same in-cluster TLS sessions, same kube-apiserver state. Every member of the group begins from a **byte-identical** world, then diverges only because of what your policy did. That is the difference between "we reset the env" and "we cloned the universe."

## How your agent talks to the tree

The agent talks JSON-lines over a Unix socket (`/run/k7d/k7d.sock`). The verbs you actually need:

| You want to… | Call |
|---|---|
| Start from a warm VM or live cluster | `tree_create` / `tree_create_cluster` / `tree_adopt_cluster` |
| Open N parallel rollouts from one checkpoint | `tree_fork_batch` |
| Try again from an earlier node without destroying it | `tree_rollback` |
| Pin a winner so budget pressure can't kill it | `tree_protect` |
| Drop a losing subtree | `tree_prune` |
| Tear the tree down (stops guests; your disk images stay yours to delete) | `tree_drop` |
| Enforce RAM/disk caps now | `tree_auto_evict` |
| Find a tree member's CID to exec on | `tree_nodes` → `live_guest_cids` (not `list_vms`) |
| Make waiting free | `auto_warp` / `dilation` / `dilation_policy` — see [Time warp](/k7d/guides/time-warp) |
| Watch the tree change | `tree_watch` — one streaming connection, one event per mutation |

Full request/response shapes: [Daemon API](/k7d/api/protocol). Budget semantics and LRU eviction: [Snapshot tree](/k7d/concepts/snapshot-tree).

## The gym: a lease service over cluster fork

Since 0.5.0 the public tree ships [`gym/`](https://github.com/katakate/k7d/tree/main/gym) — an HTTP sidecar for one k7d daemon, Python stdlib only, no GPU, no torch. A trainer `POST /lease`s N sibling clusters forked from one live, protected checkpoint, acts on them (`/env/{id}/obs`, `/env/{id}/fork`, `/env/{id}/prepare`), scores the group (`/lease/{id}/score` returns five reward terms per member — `liveness`, `workload_ready`, `source_intact`, `contained`, `restored`), and releases. The gym owns cleanup: a client that dies costs nothing after the lease TTL, and a lease that would not fit `1 source + n forks` in the tree budget is a `400` with the arithmetic, never a silent fallback.

```bash
GYM_SOURCE_MODE=ubuntu GYM_MEMORY_MB=2048 GYM_SCOREBOARD=grpo python3 gym/server.py --port 8080
curl -sS -X POST http://127.0.0.1:8080/lease -H 'Content-Type: application/json' \
  -d '{"fault_id":"kill-member-0","n":4,"group_id":"g1","ttl_s":120}'
```

The trainer substrate is **Ubuntu** (a 3-node k3s cluster booted through the socket, then `tree_adopt_cluster` + `tree_protect`); `GYM_SCOREBOARD` picks `health`, `tetragon` (source-vs-branch event-stream diff), `playbook` (a 20-page SRE exam, reward = passed/turns), `incident` / `selfplay`, or `grpo` (the same fault on every member, per-member scoring). See [`gym/README.md`](https://github.com/katakate/k7d/blob/main/gym/README.md) for the HTTP contract and every knob.

**Scenario packs.** With `GYM_SCENARIO_DIR` (requires `GYM_SCOREBOARD=grpo`) a lease with `fault_id: "scripted"` plus a `scenario_id` runs a fault from a directory of scenarios (`scenarios/<fault_type>/<variant>/`) instead of the built-in catalog; the lease echoes `scenario_id`, `fault_type`, `tier` and a `scenario_digest`, and tiers ≥ 1 blind the `services` / `links` observation keys. One scenario is a `scenario.yaml` (a deliberately tiny YAML subset: `id`, `fault_type`, `variant`, `tier` 0–3, `symptom`, timeouts, `obs` match rules, `hit_regex`, `wreck`, optional `decoy` and reward floors) plus four POSIX-sh scripts — `inject.sh`, `visible.sh`, `restored.sh`, `reference-fix.sh` — that run on member 0 of each fork. Validation is loud: bashisms, out-of-bound values or a missing key refuse to start the gym rather than partially load a pack, and the same validator is vendored into the `k7-scenarios` catalog so runtime and catalog cannot disagree.

**Durability under fork (0.5.0).** Ubuntu TreeFork hunts now stay up across a daemon crash (`tree_open` re-opens the on-disk tree after `k7d` is `SIGKILL`ed; resume, then fork again), across a held apiserver watch and ClusterIP TCP connection through the fork, and with a Redis AOF write in flight (3 × 2 GiB fork in **575 ms**, under the 1 s ceiling).

## Three reference clients

All three live in the repo's [`examples/`](https://github.com/katakate/k7d/tree/main/examples) and talk to the daemon over the socket. None is a finished SDK; each is the template for one way of driving the tree.

### `cluster-tree-search/` — the trainer loop

A thin Python client that covers exactly the loop above:

```bash
cd examples/cluster-tree-search
python3 run_demo.py --mode busybox --branches 4      # fast packaging demo
python3 run_demo.py --mode busybox --branches 50     # the density claim
python3 run_demo.py --mode inner-k3s --branches 4    # fork a live k3s cluster
```

The demo forks N branches from a live checkpoint, scores a trivial reward, protects the winner, prunes the losers, and prints the fork wall-clock. Useful flags: `--keep` (leave the tree around for `tree_nodes` inspection), `--tree-id NAME` (stable tree id), `K7D_SOCKET` (override the control socket).

### `k7d-mcp/` — a frontier agent with a fork button

A stdio MCP server that wraps the tree for Cursor CLI / Claude Code / Codex-style agents. The agent gets `tree_status`, `fork_batch(node_id, n)`, `branch_exec(node_id, member, cmd)`, `tetragon_diff(node_id)`, and `protect` / `prune` / `rollback` — every call appends one JSONL line (tool, args, latency, tree usage).

The shipped scenario plants a self-healing miner in a live Ubuntu Cilium + Tetragon cluster. The agent does not touch production first: it forks the cluster three ways, tries delete / scale-to-zero / watch on the copies, learns the miner respawns, forks again from the copy that already knows that, and replays only the winning pair of moves on the source. One lab is left broken on purpose; no rollback needed. [Video](https://github.com/katakate/k7d/blob/main/docs/assets/k7d-mcp-demo.mp4) · [how it works](https://github.com/katakate/k7d/blob/main/docs/demo/README.md) · [JSONL](https://github.com/katakate/k7d/blob/main/docs/assets/k7d-mcp-demo.jsonl).

### `k7view/` — the observer

A read-only dashboard: one SSE stream over `tree_list` / `tree_nodes` / `tree_watch`, a vsock probe thread that pings live agents for real RTT and `/proc/loadavg`, click-to-protect / evict. Fork latency chips are the daemon's `latency_ns`; the UI never invents a number or a parent edge. [The incident seen from the tree](https://github.com/katakate/k7d/blob/main/docs/assets/k7d-tree-view.mp4) · [a ×8 dilated tree recorded in real time](https://github.com/katakate/k7d/blob/main/docs/assets/k7d-dilated-tree.mp4).

## Sizing the loop

- A single 3-VM cluster fork is **~105 ms** on the minimal CI guest under API churn and **~1.1 s** on Ubuntu k3s + Cilium + Tetragon; a shared-pause batch of 50 CI-guest clusters is **~3.85 s** (~77 ms/cluster). See [Benchmarks](/k7d/deep-dives/benchmarks).
- Forks share memory until they diverge — RAM cost per group member is the dirty pages of its own rollout, not full guest RAM. Three idle k3s nodes dirty ~20% of guest RAM in 30 s (page-cache churn), so plan for that floor.
- Forking *from* a child costs a keyframe first: O(divergence), ~0.8 s idle / ~1.1 s under Kafka-style churn for 3 × 2 GiB. Fork from the root or from protected checkpoints when you can; `tree_prepare_fork_source` lets you pay it at a moment of your choosing. In 0.8.0, a long-lived root that has drifted far from its keyframe can be re-keyframed with `refresh: true`, so later forks copy only what changed since.
- Set the tree budget to your box: `max_live_vms`, `max_live_ram_bytes`, `max_disk_bytes`. The daemon proactively suspends least-recently-active unprotected nodes at 85% of the RAM budget, so a long training run doesn't OOM the host. `tree_nodes` and `tree_list` report live `usage` against the `budget`.
- If an episode is mostly waiting, run the tree with `auto_warp` `jump` (zero fidelity cost, 1.83× on a probe-heavy episode) or fork children at `dilation: 8` (8× on the same episode, bounded fidelity cost). In 0.8.0, `dilation_policy: down` backs a tree off from ×8 when its vCPUs saturate, and `track` also climbs back. [Time warp](/k7d/guides/time-warp) has the trade-off table.
