# Retention

Retention decides
what zelk keeps for a session, where, and when it goes. Outputs and
[checkpoints](/internals/checkpoints/) belong to their session and are removed with it.

## Why

Keeping logs without expiry lets them grow without bound. Sharing outputs
would require a collector to mark every digest every log names, forks and
subagents included, while sessions run. Per-session storage and whole-session
cleanup bound retention without that collector.

Claude Code follows this approach. Everything a session produces lives under
that session: its transcript, large tool outputs, subagent transcripts and
file history. One sweep at startup deletes whole sessions idle for longer
than `cleanupPeriodDays` (30 by default); deleting a session deletes all of
it. Nothing is shared, so nothing needs collecting. zelk does the same.

## What a session owns

A session's storage is:

- its **log**;
- its **file history** (`store.FileHistory`, checkpoints);
- its **outputs**: content too large for the log, stored per session. That
  is long command output and fetched pages
  (`ToolResult.FullOutput`), the files of skills it loaded, and the replay
  provider's raw items and images;
- its **subagents**: child sessions, with everything they own.

The file store keeps them under one hex name per session:

```
sessions/logs/<hex id>.zlog        log
sessions/history/<hex id>/<digest> checkpoint versions
sessions/outputs/<hex id>/<digest> outputs
scratch/<12 hex>/                  the root session's scratch directory, shared with its subagents
```

The scratch directory (`zelk.WithScratch`) is named by a short hash of the
root session's ID rather than the ID, since tools make Unix sockets in it and
those fail past about 100 characters. A catalog given the directory
(`zelk.WithCatalogScratch`, which every host's catalog is) removes it with the
root session, before the root's log, so a removal cut short leaves the session
to be removed again rather than a directory nobody owns.

Leases (`leases/`), the hosts' last-session pointers (`last/`) and memory
(`memory/`) aren't a session's storage. Memory is kept across sessions, as
Claude Code keeps auto memory. A lease's record keeps its token counter so a
later holder of the same ID is always fenced above an older one; it stays.

## Outputs are per session

`store.BlobStore` takes the session:

- `Put(ctx, session, data, mediaType)` and `Get(ctx, session, ref)` keep
  these rules: content-addressed, durable on return, `ErrNotFound` for a
  digest the session doesn't hold, the digest checked on read.
- `Copy(ctx, from, to)` gives session `to` every output `from` holds. Putting
  content `to` already has is harmless.

Every writer and reader already knows its session: a tool through its call
(`toolcall.Call.Session`), the driver and `ReleaseMaterializations` through
the log they act for, `LoadSkill` through the session it loads into. So
`Read` with `file_path` `blob:<digest>` reads only the calling session's
outputs, and one session cannot read another's by guessing a digest.

`InvokeSkill` stores a skill's files before the command reaches the log,
and a new session has no log yet: to a sweep running meanwhile they look
like a fork cut short. `Session.Start` stores them again under the
session's lease once its log exists, which is idempotent.

A session's outputs are never pruned while it is kept. They are small and a
compacted conversation may still point to one ("Read the saved output with
Read, file_path blob:…").

## Forks and subagents

**A fork copies its source's outputs.** A fork's conversation can name the
source's outputs, in `FullOutput` refs and in compaction notes, and a fork
outlives its source (`fork.go`). `Agent.Fork` copies every output the source
holds before it writes the fork's first record, after checking, under the
fork's lease, that the fork's ID has no log. A source deleted
while it was copied fails the fork: deletion removes outputs only after
the tombstone, so a source still undeleted once the copy is done had them
all. Copying all of them is
simpler than finding the ones the conversation names, and outputs are small.
A crash after the copy leaves outputs under an ID with an empty log, or
none, which the sweep removes (below). A fork still starts with no file history.

**A fork owns its scratch.** When the source has scratch, the fork records
a sibling path named by the hash of its own ID. Its context names that path,
and its tools create the directory as needed. Deleting the source removes
only the source's scratch. The fork starts with empty scratch.

**A child is part of its conversation.** A child's ID is
`<conversation>/task/<hash>` (`event.ChildSessionID`): it sits directly
under its conversation however deep its parent, so its length never grows,
and its parent's log records it (`State.Subagents`). The hash is of its
parent session and the call that started it, and the child's own start
names both (`Config.ChildOf`): the fold refuses a start under a subagent's
ID unless that origin derives it, and refuses a conversation that names
one. A log at a Task's child ID can only be that Task's child, from a try a
crash cut short, never another session it would adopt. A conversation's ID is
at most 82 bytes, leaving room for its children's within the stores' 120.
Storage cleanup also recognises the retired `<conversation>/source/<hash>`
shape (`event.SplitStoredChildID`), so a tree that holds one is still found
through its conversation; nothing else does, and no session starts one. A child is removed with its
conversation and never on its own: the sweep judges a conversation by the
newest activity anywhere in its tree. The catalog finds a session's children in its state, and their
children in theirs.

## Removing a session

A store that can remove sessions implements `store.Remover`:

```go
RemoveSession(ctx context.Context, session string, token lease.Token) error
```

It takes the session's current lease token, refuses an older one with
`ErrFenced` as `Append` does, then removes the session's outputs, file
history, and last its log. Removing a session that holds nothing succeeds.
Removal checks fencing without decoding or repairing the log, so it also
works on logs with unsupported event versions or corruption (`store.ErrCorrupt`).
Adopting a file log still decodes its records and can fail for either reason.
The log goes last because it is what the listing finds: a crash part way
leaves a log, and the next sweep finishes the job.

The store's fence record for the session stays (the file store's
`<log>.fence`, 12 bytes), like the lease's record. A writer whose lease ended
before the removal may still hold the old log open; the fence keeps refusing
it. A broken log (`<log>.broken`) is refused: it is evidence, and removing it
is the operator's decision.

After removal the ID is unused. Opening it in the same store starts an empty
session, and its lease's next token is higher than any the old holders had.
zelk never reuses a removed ID: hosts name new sessions with version 7
UUIDs ([`core/uuid`](https://github.com/barevoidco/zelk/blob/main/core/uuid/README.md)), and a child's ID starts
with its removed parent's. Another process that had read the old log may
still cache what it read, so a store needn't support reuse across
processes.

Removing a tree takes the lease of every session in it first, the root's
then each child's, and holds them all until the end; a held session
anywhere leaves the whole tree untouched. Before writing anything it
checks every session: a busy subagent, or one owning publications with no
way to release them, refuses the removal. Then the root's tombstone, the
commit point; then each subagent's publications are released and its
session tombstoned and removed, children first, deepest first, and the
root's storage last. So a crash never leaves a child whose parent is gone.

## Delete

`Catalog.Delete` keeps its checks and its order: refuse a busy session or
one with unfinished children, release published materializations, append
the tombstone. Then it removes the session's
tree. The tombstone is the commit point: once it is written the session
never resumes, and a crash before removal finishes leaves a tombstoned log,
which the next sweep removes whatever its age.

`Catalog.ForceDelete(ctx, id)` is the explicit escape for an unreadable root,
and for processes nothing can settle.
Plain `Delete` still refuses an unreadable root and points to `ForceDelete`. Only
`event.ErrUnsupportedVersion` and `store.ErrCorrupt` enable the fallback: an I/O,
fencing, cancellation or reducer error must not bypass normal deletion checks.
A readable root always follows normal Delete, even with an unreadable child,
except for process records.

A process recorded as running refuses `Delete`: the catalog has no
environment to ask whether it ended, and it may be running still. After a
host restart or a reboot such records often outlive their processes, and
nothing but a resumed session can settle them ([background](/internals/background/),
Reattaching a shell process). `ForceDelete` is the user's explicit removal,
so such a record, in the session or in a subagent's, never refuses it: the
tombstone's append first records each running process as lost, so the
reducer admits it. `ForceDelete` stops no process. It still takes every
lease, and a live host's lease, the evidence that it may be running the
session's processes, refuses it. An idle session holds no lease, though, so
a conversation process an open agent elsewhere still runs for it outlives
the removal too, as does a process a supervisor keeps (persistent
lifetime): both are left running and recorded lost. What such a process
reports afterwards belongs to the deleted session and never reaches a
session later made under the same ID. A store that can't remove
sessions gets the same tombstone. The unreadable-root fallback never read the
records and ignores them as it ignores every other check.
An adoption error alone is insufficient: a record read must confirm the root
log is unreadable, since adoption can also fail on damaged fencing metadata.

The fallback discovers all listed descendants by the
`<conversation>/<kind>/<hash>` ID shape (`task`, or the retired `source`),
including unreadable children and
descendants whose intermediate parent's log is already gone. It takes every
lease, root first, before removing anything, then removes the children and
the root last.
It never adopts children or appends tombstones. A crash leaves a partial tree
the same call can finish; children already gone are harmless. A root with no
log returns `ErrNoSession`, as `Delete` does: removal takes the root last, so
none is left with its children behind it, and readable orphans keep `Delete`'s
checks.

The cost is explicit: busy and publication checks cannot run on a log nobody
can read, so owned publications (materializations) recorded in the tree are
not released. Held leases still spare the whole tree. Broken writers and
damaged fence files still refuse removal.

## The sweep

`Catalog.Cleanup(ctx, cutoff)` replaces `ExpireCheckpoints`. Hosts run it
once at start (the TUI, `zelk exec`, `zelk acp`) with
`-cleanup-days` (default 30, minimum 1), as Claude Code runs its cleanup at
startup. It removes:

- every session tree whose newest `Updated` is before the cutoff. A tree is
  headed by its conversation's root log and holds every session its ID
  names: only the subagent whose origin derives an ID may start under it,
  which the fold enforces. A subagent whose conversation has no root log, which removal
  never leaves since it takes the root last, doesn't expire on its own, and
  no tree is removed in a sweep that couldn't list every leftover;
- every tombstoned session, at once;
- outputs and file history under an ID with no log (a fork or removal cut
  short by a crash).

For each tree it takes every session's lease and folds its log. It skips
the tree, for a later start, when any lease is held, any log was written
since the listing (`Seq` differs), a run is under way, a child is
unfinished, or a publication can't be released. A leftover is judged
again under its lease: a fork that wrote its first records since the
listing is kept. A failure with one tree doesn't stop the others; every
failure is returned, even one a later step of the same sweep finished.

The session a host is about to take up (`-continue`, `-session`,
`exec resume`) is passed to the sweep, which spares its tree however old it
is: the sweep runs alongside the host's start, and would otherwise remove the
session from under the user. Taking it up makes it current. Any other
session a host offers waits for the sweep: the TUI's session picker lists
sessions only once it has finished, and `zelk acp`, whose client may load
any session, finishes it before serving.

The sweep never removes a tree any of whose logs it can't read, however old:
one written before the current format (`event.ErrFormatBreak`), one written by
a newer zelk (`event.ErrUnsupportedVersion`), or a damaged one
(`store.ErrCorrupt`). Removing it is the user's call, through `ForceDelete`,
which can't run the busy and publication checks on an unreadable log and
doesn't release owned materializations in the tree. A tree is judged whole: an
unreadable subagent keeps its readable root, and its leftovers stay too.

Kept unreadable logs are reported. A format break or an upgrade may leave many
of them, so each kind is reported as one count: "N session logs were written
before the current format and are kept as they are", and likewise for logs a
newer zelk wrote. Damaged logs are reported one by one. A host listing
sessions (`store.List`) leaves an unreadable one out and says how many it left
out: one such log doesn't keep the picker or `zelk sessions list` from
offering the rest.

With whole sessions expiring, checkpoints need no expiry of their own.
Pruning at 100 points and the move rules are unchanged.

## Hosts

- `-cleanup-days N` (default 30, minimum 1) replaces `-checkpoint-days`, with
  its `defaults.json` key (`cleanup_days`) and TUI settings row. An old
  `checkpoint_days` key is ignored with a debug line.
- Continuing a removed session (`-continue`, `exec resume --last`, through
  the last-session pointer) finds no log and starts a new session under a
  new ID, saying so: a removed ID is never taken up again, since another
  process may still cache what it read of the old log. The TUI's
  `-session ID`, which opens a session, refuses an ID with no log.
- `zelk sessions delete -force ID` calls `Catalog.ForceDelete`; plain delete
  refuses unreadable logs with guidance to this explicit flag. No TUI force
  control is added.
- The guide and READMEs say what's kept and for how long, as Claude Code's
  docs do.

## Tests that gate it

- Two sessions put the same content; removing one leaves the other's.
- `Read("blob:…")` of another session's output fails as "doesn't exist".
- A fork reads the source's output after the source is deleted.
- Delete removes the log, history, outputs and children; the ID then opens
  empty.
- The sweep removes an old tree, keeps a recent one, keeps a tree whose child
  is recent, and skips held, busy and since-written sessions.
- A crash at every removal step leaves state the next sweep finishes.
- `RemoveSession` with an old token is refused, and a writer replaced before
  the removal can't write afterwards.
- Conformance in `store/storetest` for the file and memory stores.
