# Stores, leases and recovery

> Keep sessions on disk, reopen them in another process, and recover after a crash.

By default an agent keeps sessions in memory, and they end with it. A store
keeps them; a lease makes sure only one process at a time drives each one.

## Sessions that outlive the process

[`store/file`](/reference/go/store-file/) keeps each session's log and blobs
in a directory. A store whose logs outlive the process needs a lease whose
fences do too, [`lease/file`](/reference/go/lease-file/), or `New` refuses
the pair. A second agent, here standing in for another process, reopens
the session and reads what the first did:

```go
// core/guide_example_test.go
dir, err := os.MkdirTemp("", "zelk-sessions-*")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()

for _, sub := range []string{"sessions", "leases"} {
	if err := os.Mkdir(filepath.Join(dir, sub), 0o700); err != nil {
		panic(err)
	}
}
open := func(turns ...replay.Turn) *zelk.Agent {
	store, err := filestore.New(ctx, filepath.Join(dir, "sessions"))
	if err != nil {
		panic(err)
	}
	leases, err := filelease.New(filepath.Join(dir, "leases"))
	if err != nil {
		panic(err)
	}
	p, err := replay.New(provider.Caps{}, turns...)
	if err != nil {
		panic(err)
	}
	a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass),
		zelk.WithStore(store), zelk.WithLease(leases))
	if err != nil {
		panic(err)
	}
	return a
}

first := open(replay.Reported("met", "Noted."))
s, err := first.Session(ctx, "notes")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Remember: the deploy is on Friday.")))
if err != nil {
	panic(err)
}
if _, err := x.Wait(ctx); err != nil {
	panic(err)
}
if err := first.Close(ctx); err != nil {
	panic(err)
}

second := open()
defer second.Close(ctx)
s, err = second.Session(ctx, "notes")
if err != nil {
	panic(err)
}
page, err := s.History(ctx, zelk.HistoryOptions{})
if err != nil {
	panic(err)
}
for _, item := range page.Items {
	for _, part := range item.Parts {
		if part.Kind == history.KindText {
			fmt.Printf("%s: %s\n", item.Role, part.Text)
		}
	}
}
// Output:
// user: Remember: the deploy is on Friday.
// assistant: Noted.
```

## Leases

A lease gives one holder at a time the right to append to a session. It
expires unless renewed, and each takeover raises its fence, so a process
that lost the lease can't write over the one that took over:

```go
// core/lease/file/example_test.go
dir, err := os.MkdirTemp("", "leases")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()

// Two processes would each open their own Lease on the same directory.
a, _ := filelease.New(dir, filelease.WithTTL(time.Minute))
b, _ := filelease.New(dir, filelease.WithTTL(time.Minute))

g, _ := a.Acquire(ctx, "session-1")
_, err = b.Acquire(ctx, "session-1")
fmt.Println(errors.Is(err, lease.ErrHeld))

_ = a.Release(ctx, g.Token)
next, _ := b.Acquire(ctx, "session-1")
fmt.Println(next.Token.Fence > g.Token.Fence)
// Output:
// true
// true
```

`lease/file` works across processes on one machine. Across machines, a
lease backed by a shared database does the same job; any implementation
must pass the conformance kit in `lease/leasetest`, as a store must pass
`store/storetest`.

## The catalog

A UI that lists sessions, a job that deletes old ones and a dashboard that
reads where each stands need no model and no workspace. `zelk.NewCatalog`
takes the store and the lease the agents use, and works on the stored
sessions without an agent. It needs a store that can list its sessions, as
`store/file` and `store/mem` can. It doesn't own or close what you give it.

```go
// core/guide_sessions_example_test.go
dir, err := os.MkdirTemp("", "zelk-catalog-*")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
for _, sub := range []string{"sessions", "leases"} {
	if err := os.Mkdir(filepath.Join(dir, sub), 0o700); err != nil {
		panic(err)
	}
}
logs, err := filestore.New(ctx, filepath.Join(dir, "sessions"))
if err != nil {
	panic(err)
}
leases, err := filelease.New(filepath.Join(dir, "leases"))
if err != nil {
	panic(err)
}

p, err := replay.New(provider.Caps{}, replay.Reported("met", "Noted."))
if err != nil {
	panic(err)
}
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass),
	zelk.WithStore(logs), zelk.WithLease(leases))
if err != nil {
	panic(err)
}
s, err := a.Session(ctx, "notes")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Remember the deploy.")))
if err != nil {
	panic(err)
}
if _, err := x.Wait(ctx); err != nil {
	panic(err)
}
if err := a.Close(ctx); err != nil {
	panic(err)
}

catalog, err := zelk.NewCatalog(logs, leases)
if err != nil {
	panic(err)
}
for info, err := range catalog.Sessions(ctx) {
	if err != nil {
		panic(err)
	}
	fmt.Println("stored:", info.ID)
}
// Status folds the log; it needs no provider and takes no lease.
status, err := catalog.Status(ctx, "notes", nil)
if err != nil {
	panic(err)
}
fmt.Println("last run:", status.Last.Outcome)

if err := catalog.Delete(ctx, "notes"); err != nil {
	panic(err)
}
remaining := 0
for _, err := range catalog.Sessions(ctx) {
	if err != nil {
		panic(err)
	}
	remaining++
}
fmt.Println("after delete:", remaining)
// Output:
// stored: notes
// last run: success
// after delete: 0
```

- **List.** `Catalog.Sessions` yields each stored session's `store.SessionInfo`:
  its ID, title, tags, workspace root, times and last sequence number, the
  most recently updated first. A subagent's session has an `AgentType`; a
  conversation, which a picker offers to resume, has none.
- **Read.** `Catalog.Status` folds a session's log and says where it stands:
  whether a run is under way, whether it waits for answers and what they are,
  how the last run ended and what it reported, the mode, the rules, the
  usage and, given a `Pricing` function, the cost. It reads only: it needs no
  provider, takes no lease and is safe while another process runs the
  session. An empty session gives `ErrNoSession`. With an agent in hand,
  `Session.Status` is the same fold, and `Session.History` pages the
  conversation the model has now, or with `HistoryOptions{Compacted: true}`
  the turns [compaction](/go/compaction/) removed too. `Session.Events` is
  the raw log.
- **Name.** `Catalog.Rename` and `Catalog.SetTags` change an idle session's
  title and tags. They append a command to its log under the lease, so they
  refuse a session with unfinished work (`ErrSessionBusy`) or one another
  process holds (`lease.ErrHeld`).
- **Delete.** `Catalog.Delete` removes an idle session for good, with its
  subagents, saved outputs and checkpoints. A tombstone in the log is the
  commit point: from it on the session never resumes, and a deletion cut
  short is finished by a later `Delete` or by `Cleanup`. A session with a
  process recorded as still running counts as busy, since the catalog can't
  tell whether it ended.
- **Delete what can't be read.** A log from an older zelk, a newer one or a
  damaged one is never removed on its own. `Delete` refuses it, and so does
  `Cleanup`. `Catalog.ForceDelete` is the explicit request to remove it, and
  to remove a session whose recorded process can no longer be settled, such
  as after a reboot. It takes the lease still, so a live host keeps it from
  happening, and it stops no process.
- **Expire.** `Catalog.Cleanup(ctx, cutoff, keep...)` deletes every session
  tree last updated before `cutoff`, finishes deletions that were cut short,
  and spares the sessions named in `keep`. Hosts run it as they start.

A session that published files into a materialized workspace owns them until
it is deleted. Give `zelk.WithCatalogCleanup` the same environment the agents
use, as [Sandboxing](/go/sandboxing/#a-private-cache-of-published-files)
shows, so `Delete` can release them before it writes the tombstone. Without
a backend for them, `Delete` refuses such a session rather than leave them
behind. `WithCatalogScratch` names the directory the agents' `WithScratch`
named, so a removed session's scratch goes with it.

## Recovery

Every effect, a model call or a tool call, is recorded as started before it
runs and as ended after. When a process dies mid-call, the next process to
open the session finds the started effect with no end and settles it by
kind. A model call is made again. A tool call runs again only when that is
safe: a trusted tool that is read-only and idempotent, or one that
deduplicates by its idempotency key. Any other is reported to the model as
unknown, with an instruction to check the state it would have changed
before retrying. Then the session goes on from its log.

Opening a session with an execution under way in a dead process works the
same way once its lease expires. [Durability and
recovery](/concepts/durability/) explains the order recovery runs in, what a
stop, an interrupt and a lease lost each leave, and what the guarantees don't
cover. The [durability contract](/internals/durability/) lists the recovery
rule for each effect kind, and `examples/external-driver` in the repository
drives a session through a crash with public APIs only.

## Next

[Running zelk in a service](/go/service/) puts the agent, the store and the
lease inside a long-running process.
