---
title: Label, branch and fork a session
description: 'Navigate a weft/thread session''s entry tree: Label an entry, Branch back to it (optionally summarizing what you leave), Fork into a new session, and set titles, metadata and public ids that every run carries.'
url: https://weftgo.dev/docs/sessions/tree/
type: how-to
sources:
  - weft/AGENTS.md:559-560 (identity metadata), 568-569 (block 8, Tree), 212-213 (block 6)
  - weft/README.md:777-779 (thread/examples/session)
  - weft/thread/branch.go:14-45 (BranchOption, SummarizeLeft), 67 (Branch), 266 (Fork)
  - 'weft/thread/turn.go:240-247 (a failed turn''s prompt and steps stay on the path); scratch proof: s.Branch(ctx, before) then Send carried the prompt once'
  - 'weft/thread/entry.go:204-210 (BranchSummaryEntry: no usage field); weft/thread/session.go:1532-1536 (Usage sums CompactionEntry, never a branch summary); scratch proof: SummarizeLeft made one model call and left Usage().Summaries zero'
  - weft/thread/session.go:165 (WithLineage), 185 (WithMeta), 244 (PublicID), 899 (Lineage), 935 (Leaf), 948 (Entries), 971 (Path), 1064 (Context), 1327 (Label), 1358 (SetInfo), 1387 (Title), 1413 (Meta), 1450 (Custom), 1481 (CustomMessage)
  - weft/thread/turn.go:1105-1113 (weft.approval.actor), 1357-1485 (runMetadata, identityMetadata); weft/thread/approval.go:1631 (approvalActorKey)
  - weft/thread/header.go:36-71 (Header, Lineage, ParentRef)
  - weft/thread/errors.go:15 (ErrBusy), 171 (ErrCreateOnly), 177 (ErrReservedKey)
  - weft/thread/doc.go (Identity)
  - weft/docs/adr/0011-thread-sessions.md (§2 entry kinds, §3 branching)
  - weft/docs/thread-operations.md (§13 observability)
  - weft/CHANGELOG.md:436 (a session's run carries its own identity), 4731 (PublicID), 4736 (run metadata), 5187 (Branch while a turn runs), 5315 (Branch, Fork), 5348 (thread/examples/session)
  - weft/thread/example_test.go ExampleMessageEntry, ExampleSession_Branch, ExamplePublicID
  - weft/thread/example_session_test.go ExampleSession_Fork, ExampleSession_Label, ExampleSession_Path, ExampleWithMeta
  - weft/thread/example_compaction_test.go ExampleSummarizeLeft
  - 'weft/thread/session.go:507-549 (Create: ErrExists only for a repeated session id; no public-id check), 214-224 (publicIDKey weft.public_id); weft/thread/storage.go:100-145 (Query.Meta on header metadata, Page.Sessions)'
  - 'scratch proof (weft v0.17.0, docs a10 fix): two thread.Create(ctx, thread.Memory(), agt, thread.PublicID("pub_x")) calls both returned nil errors (two session ids); thread.List with Query.Meta weft.public_id pub_x returned 2 sessions, Total 2'
  - 'weft/runtime/sessions.go:205-219 (resolveSession: a resolver answer whose id is not the run''s session is refused, the message quoted); weft/obsdb/db.go:679-685 (SessionQuery.PublicID: every session one of whose turns carries the public id is listed)'
  - weft/thread/examples/session/main.go
  - docs-site/examples/sessions/tree.go, sessions_test.go TestDemos/tree, TestBranchPathAndFork
  - 'weft v0.20.2: thread/session.go:196-207 (WithRunMetadata: the header at Create and Fork, held at Open, identity keys win, a Send''s own Metadata wins per key, a fork takes its origin''s); thread/turn.go:1460-1463 (Session.RunMeta: a copy); thread/example_session_test.go:512-539 (ExampleWithRunMetadata); docs/record-contract.md:163-164 (weft.turn.parent, weft.session.branch); weft/AGENTS.md:558-563 (block 8); weft/CHANGELOG.md:226 (0.18.0: WithRunMetadata)'
---

# Label, branch and fork a session

A session is a tree: [`s.Branch(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) moves the leaf back to any earlier entry so the next turn continues from there, [`s.Fork(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Fork) copies the path up to an entry into a new, self-contained session, and [`s.Label(ctx, entryID, name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Label) names an entry to come back to. Each is an appended entry or a new session; nothing is rewritten or deleted.

`sessions/tree.go` labels the end of the first turn, asks a second question, then branches back to the label, summarizing the abandoned turn:

```go title="sessions/tree.go"
shipped := s.Leaf() // the first turn's end
if err := s.Label(ctx, shipped, "shipped"); err != nil {
	return err
}
if err := send(ctx, s, "When was it delivered?"); err != nil {
	return err
}

// Back to the label; the abandoned turn is summarized, not lost.
if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil {
	return err
}
if err := send(ctx, s, "Refund it instead."); err != nil {
	return err
}
for _, m := range s.Context() {
	fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
}
path, err := s.Path(s.Leaf())
if err != nil {
	return err
}
fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries()))
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
user: "Where is order 1234?"
assistant: "Order 1234 shipped on Tuesday."
user: "<weft-summary>\nThe user asked when order 1234 was delivered: Thursday.\n</weft-summary>"
user: "Refund it instead."
assistant: "I have started a refund for order 1234."
path: 7 entries; tree: 12
```

The second question and its answer are off the path: the model sees the summary in their place. The tree still holds them, so it has 12 entries against the path's 7. In the demos, `ids` pins the ids for stable output and `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window ([why](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)).

## Branch and fork

> **Diagram:** A session log holds e1 (user: Where is order 1042?), e2 (assistant: Shipped this morning.), e3 (user: And 5678?) and e4 (assistant: Still processing.). s.Branch(ctx, e2) appends a leaf entry pointing at e2; nothing is rewritten. The next write, e5 (user: Cancel 1042 instead.), attaches to e2, so the model's context is e1, e2, e5. e3 and e4 stay in the file, off the path.

**Read the tree.** [`s.Leaf()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) is the entry the next one attaches to ("" while the session is empty). [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) is what the model sees at the leaf: the message and custom-message entries on its path, branch summaries as marked summaries, the latest compaction applied, and `weft.Repair` last. [`s.Entries()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) is the whole tree in append order, abandoned branches included. [`s.Path(entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) is one chain of parent links from a root to `entryID`, inclusive. Both return deep copies. Each entry is a sealed [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) kind with a `type` discriminator on the wire ([`ExampleMessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-MessageEntry), [`ExampleSession_Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Path)).

**Branch** appends a leaf entry pointing at `entryID`, and the model's context is rebuilt from that path alone: nothing appended on the abandoned branch reaches it again. `entryID` may be any entry the session holds, on any branch; `""` is the root, which restarts the conversation from nothing while the file keeps everything (the tree then has several roots). The context is rebuilt from the branch's own path only; tools come from the agent, not the tree. Branching is a between-turns operation: while a turn runs it fails with `thread.ErrBusy`, because the turn's transcript must land on the line it started on. A parked approval boundary is not a running turn, and branching away from it is the documented way out ([`ExampleSession_Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Branch)). Branching back to the `Leaf()` taken before a failed turn is also how to retry it without its prompt twice in the context ([Send turns › gotchas](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)).

[`thread.SummarizeLeft()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummarizeLeft), the one [`thread.BranchOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchOption), summarizes the branch being left (back to the common ancestor) into a `branch_summary` entry that the new branch's context carries in its place. The summarizer runs under the session's compaction chain, `SummaryModel` or the session's own model, with the lock released; the navigation and the summary land in one batch. The example's script answers the summary request with its third reply ([`ExampleSummarizeLeft`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-SummarizeLeft)).

### Label an entry

A label is an appended [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry), a bookmark a UI lists and a later `Branch` or `Fork` can return to. It never enters the model's context; `entryID` must be an entry the session holds and the name must not be empty. Read labels back from the tree:

```go title="sessions/tree.go"
for _, e := range s.Entries() {
	if l, ok := e.(thread.LabelEntry); ok {
		fmt.Fprintln(w, "label:", l.Name, "→", l.Entry)
	}
}
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
label: shipped → e_a3
```

The package example is [`ExampleSession_Label`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Label).

### Fork into a new session

> **Diagram:** Session A holds e1, e2 and e3. s.Fork(ctx, e2) writes a new session B whose header names its parent, A#e2: B holds copies of e1 and e2 and continues with its own e3. Session A keeps its leaf and its entries; Fork never moves it. Runs in B carry weft.session.forked_from = A#e2.

Fork copies the path root → `entryID` into a new session in the same storage and returns it positioned at the end of that path; when the fork had to append settling entries (below), its leaf is the last of them, with the same context. The new file holds the whole copied path, the entries keeping their ids, and its header's `Parent` names the session and entry it grew from:

```go title="sessions/tree.go"
leaf := s.Leaf()
fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f"))
if err != nil {
	return err
}
h, _, _, err := st.Load(ctx, fork.ID())
if err != nil {
	return err
}
fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context()))
turn, err := fork.Send(ctx, weft.User("Send a replacement instead."))
if err != nil {
	return err
}
if _, err := turn.Wait(); err != nil {
	return err
}
fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"])
fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf)
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
fork: s_whatif of s_tree at e_a3 messages: 2
fork run: s_whatif-t2 forked_from: s_tree#e_a3
this session's leaf moved: false
```

- **Options configure the fork**, as at `Create`: `IDs`, `Clock`, `WithMeta`, `PublicID`, the busy policy, compaction and approval options. Nothing is inherited from this session's options or header, not its public id, with one exception: a fork of a session that requires signed decisions requires them too.
- **It inherits what the path records**: the conversation, compactions and branch summaries, the title and `SetInfo` metadata, labels, custom entries, the turn ledger (its run ids continue after the copied turns, hence `t2`), grants, and an open approval boundary, which each session then resolves on its own.
- **It does not inherit work**: the running turn, queued sends and steers (recorded as dropped in the fork), mirrored pool requests, or unsettled pool delegations (settled as canceled).
- **It works mid-turn and on a closed session**: it snapshots under the lock and writes elsewhere, and never moves this session's leaf. A leaf entry is a navigation, not a position, so `Fork` rejects one; fork the entry it points to.

The fork is durable when `Fork` returns; if its entries cannot be written, the half-made session is deleted again. Its runs carry `weft.session.forked_from` as `<session>#<entry>`. The package example is [`ExampleSession_Fork`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Fork).

### Keep application state and notes

Two bookkeeping writes carry your own data. [`s.Custom(ctx, kind, data)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Custom) appends opaque JSON state under a kind you choose: it survives every compaction and never enters the model's context. [`s.CustomMessage(ctx, kind, msg)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CustomMessage) appends a message that is always in the context, a note the model must see:

```go title="sessions/tree.go"
if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context
	return err
}
if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it
	return err
}
fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text())
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
context: 6 messages; last: Note: the customer is on the paid plan.
```

Both reject an empty kind, and `Custom` rejects data that is not JSON. `CustomMessage` is a between-turns write: while a turn runs it fails with `ErrBusy`, because a message joining mid-run would land between the run's own messages. To reach a running turn, steer ([Steer into the running turn](https://weftgo.dev/docs/sessions/busy-and-steering/#steer-into-the-running-turn)). `Custom` is not restricted.

## Identity

A session's identity rides on every run it starts, as run metadata on every span and record:

```go title="sessions/tree.go"
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"),
	thread.PublicID("pub_7f3a"),                          // stamped on every run as weft.public_id
	thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it
if err != nil {
	return err
}
if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil {
	return err
}
err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"})
fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey))

turn, err := s.Send(ctx, weft.User("How long does a refund take?"))
if err != nil {
	return err
}
if _, err := turn.Wait(); err != nil {
	return err
}
md := meta.of(turn.RunID())
for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} {
	fmt.Fprintf(w, "%s = %s\n", k, md[k])
}
fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title())

page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}})
if err != nil {
	return err
}
fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID)
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
reserved key: true
weft.session.id = s_pub
weft.turn = 1
weft.public_id = pub_7f3a
weft.session.title = Refund for order 1234
meta: acme paid title: Refund for order 1234
found by public id: s_pub
```

| Key | Value |
|---|---|
| `weft.session.id` | the session id, always |
| `weft.turn` | the counter the run id `<session>-t<n>` was minted from, always |
| `weft.public_id` | the session's public id, when it was created with `thread.PublicID` |
| `weft.session.title` | the session's title as the turn starts, once `SetInfo` named one |
| `weft.session.forked_from` | `<session>#<entry>`, on a fork |
| `weft.session.parent`, `weft.session.parent_call` | the parent session and delegating call, on a pool child |
| `weft.approval.actor` | who decided, on a resume run that applies decisions; `""` on every other run |
| `weft.turn.parent` | since 0.18.0, the turn whose line this turn continues, on the first turn after a navigation (`Branch`, `Uncompact`, a rollback) took the leaf off the newest line; `"0"` when that line holds no turn; absent on a linear turn |
| `weft.session.branch` | since 0.18.0, the branch the turn's line descends from: the label on the entry the newest navigation went to, else that navigation's leaf entry id; absent on a line no navigation made |

Every run a session starts carries them: a send, a resume, an overflow re-run. The session's keys win over a colliding key you pass with `thread.RunOptions(weft.Metadata(...))`; other keys pass through. Studio's session page draws its tree view from `weft.turn.parent` and `weft.session.branch` ([A session's page](https://weftgo.dev/docs/observe/studio/sessions-and-traces/#a-sessions-page)). A key the session has no value for is stamped `""`, which the core reads as none: a turn sent from inside another session's tool handler, or a pool child's turn, never carries the enclosing run's public id, title, fork origin or lineage as its own. The title is a label, not content, so it survives a content-off destination, and Studio titles the session with it.

### Set a public id and metadata

[`thread.PublicID(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PublicID) sets an opaque, browser-safe handle for the session, stored as the header metadata key `weft.public_id`. It is exactly `thread.WithMeta(map[string]string{"weft.public_id": id})`, so `thread.List`'s `Query.Meta` finds the session by it. [`thread.WithMeta(meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) adds other header keys. Both are header options: `Create` and `Fork` write them, and `Open` fails with [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly):

```go title="sessions/tree.go"
_, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new"))
fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly))
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

```text
header option on Open: true
```

`Create` does not check that a public id is unused. Two `Create` calls with `thread.PublicID("pub_x")` both succeed, and `thread.List` then finds two sessions. Studio and the devtools panel scope a conversation by public id, so they show both sessions' turns under it. Deciding or steering a turn from the panel asks your `runtime.Sessions` resolver for the public id, and a turn of the session it does not return is refused: `the session resolver answered session <id> for public id <pub>, not the run's session <id>` ([app turns](https://weftgo.dev/docs/observe/devtools/app-turns/#decide-and-steer)).

To reuse a session per conversation, look the id up first with `thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": id}})` and `Open` the session it returns; `Create` only when it returns none.

The public id is fixed for the session's life, and a fork does not inherit it. [`thread.WithLineage(parentSession, call)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage) is the third header option, the pool lineage that [`s.Lineage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage) reads back; `thread/pool` sets it for its children ([pools](https://weftgo.dev/docs/sessions/pools/)). The examples are [`ExamplePublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-PublicID) and [`ExampleWithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithMeta).

To stamp your own pairs on every turn's run, such as a tenant or a batch tag, pass [`thread.WithRunMetadata(kv)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithRunMetadata) (since 0.18.0). They are the pairs `weft.Metadata` would stamp, on every span and record of each run. At `Create` and `Fork` they are written into the header (`Header.RunMeta`), so a reopened session keeps stamping them; at `Open` they are held over the stored pairs for that `Session`'s life, since the header is immutable. A fork takes its origin's pairs, its own over them. The session's identity keys always win, and a `Send`'s own `thread.RunOptions(weft.Metadata(...))` wins per key over the session's. [`s.RunMeta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.RunMeta) returns the pairs in force, a copy. [`ExampleWithRunMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithRunMetadata) creates a session with `tenant=acme` (its `weft.turn=9` loses to the identity key), reopens it with `batch=b7`, and prints `acme  turn 1`, then `acme b7 turn 2`.

### Edit the title and metadata

[`s.SetInfo(ctx, title, meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) appends an info entry, never a rewrite of the header. [`s.Title()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) is the last info entry's non-empty title, and [`s.Meta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Meta) the header's metadata overlaid by every info entry's, in append order. An empty title keeps the current one; a key set to `""` blanks it, and there is no removal. A call that names neither a title nor a key writes nothing. Keys under the reserved `weft.` prefix are the session's identity and belong to the header: `SetInfo` rejects them with [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) and writes nothing. `List`'s `Query.Meta` matches the header only, so a key `SetInfo` added never matches there, while runs read the merged `Meta`.

## Complete example

`sessions/tree.go` branches, labels, forks, keeps state and stamps identity. weft's own [`thread/examples/session`](https://github.com/weftgo/weft/tree/v0.20.2/thread/examples/session) walks the same tree on disk, with a previewed compaction and a reopen (`go run ./thread/examples/session` in the weft repository).

```go title="sessions/tree.go"
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/thread"
	"github.com/weftgo/weft/wefttest"
)

// demoTree is the page "Label, branch and fork a session".
func demoTree(ctx context.Context, w io.Writer, _ string) error {
	var meta runMeta
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Say("It was delivered on Thursday."),
		wefttest.Say("The user asked when order 1234 was delivered: Thursday."), // the branch summary
		wefttest.Say("I have started a refund for order 1234."),
		wefttest.Say("A replacement for order 1234 ships tomorrow."), // the fork's turn
	), meta.tap())
	st := thread.Memory()
	s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_tree", "a"))
	if err != nil {
		return err
	}
	if err := send(ctx, s, "Where is order 1234?"); err != nil {
		return err
	}

	shipped := s.Leaf() // the first turn's end
	if err := s.Label(ctx, shipped, "shipped"); err != nil {
		return err
	}
	if err := send(ctx, s, "When was it delivered?"); err != nil {
		return err
	}

	// Back to the label; the abandoned turn is summarized, not lost.
	if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil {
		return err
	}
	if err := send(ctx, s, "Refund it instead."); err != nil {
		return err
	}
	for _, m := range s.Context() {
		fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
	}
	path, err := s.Path(s.Leaf())
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries()))

	for _, e := range s.Entries() {
		if l, ok := e.(thread.LabelEntry); ok {
			fmt.Fprintln(w, "label:", l.Name, "→", l.Entry)
		}
	}

	leaf := s.Leaf()
	fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f"))
	if err != nil {
		return err
	}
	h, _, _, err := st.Load(ctx, fork.ID())
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context()))
	turn, err := fork.Send(ctx, weft.User("Send a replacement instead."))
	if err != nil {
		return err
	}
	if _, err := turn.Wait(); err != nil {
		return err
	}
	fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"])
	fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf)
	if err := fork.Close(ctx); err != nil {
		return err
	}

	if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context
		return err
	}
	if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it
		return err
	}
	fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text())
	if err := s.Close(ctx); err != nil {
		return err
	}
	return identity(ctx, w, st)
}

// send runs one turn and waits until the session is idle again.
func send(ctx context.Context, s *thread.Session, text string) error {
	turn, err := s.Send(ctx, weft.User(text))
	if err != nil {
		return err
	}
	if _, err := turn.Wait(); err != nil {
		return err
	}
	return s.WaitIdle(ctx)
}

// identity: the public id, the title and the metadata every run carries.
func identity(ctx context.Context, w io.Writer, st thread.Storage) error {
	var meta runMeta
	agent := weft.New(wefttest.Script(wefttest.Say("A refund takes three to five days.")), meta.tap())
	s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"),
		thread.PublicID("pub_7f3a"),                          // stamped on every run as weft.public_id
		thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it
	if err != nil {
		return err
	}
	if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil {
		return err
	}
	err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"})
	fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey))

	turn, err := s.Send(ctx, weft.User("How long does a refund take?"))
	if err != nil {
		return err
	}
	if _, err := turn.Wait(); err != nil {
		return err
	}
	md := meta.of(turn.RunID())
	for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} {
		fmt.Fprintf(w, "%s = %s\n", k, md[k])
	}
	fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title())

	page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID)
	if err := s.Close(ctx); err != nil {
		return err
	}
	_, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new"))
	fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly))
	return nil
}
```

[sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`:

```sh
go run ./sessions tree
go test ./sessions
```

```text
user: "Where is order 1234?"
assistant: "Order 1234 shipped on Tuesday."
user: "<weft-summary>\nThe user asked when order 1234 was delivered: Thursday.\n</weft-summary>"
user: "Refund it instead."
assistant: "I have started a refund for order 1234."
path: 7 entries; tree: 12
label: shipped → e_a3
fork: s_whatif of s_tree at e_a3 messages: 2
fork run: s_whatif-t2 forked_from: s_tree#e_a3
this session's leaf moved: false
context: 6 messages; last: Note: the customer is on the paid plan.
reserved key: true
weft.session.id = s_pub
weft.turn = 1
weft.public_id = pub_7f3a
weft.session.title = Refund for order 1234
meta: acme paid title: Refund for order 1234
found by public id: s_pub
header option on Open: true
```

`sessions/sessions_test.go` also pins a branch's context and a fork's `Parent`.

## Best practices & gotchas

- **Branch between turns.** `Branch`, `CustomMessage`, `Compact`, `ApplyCompaction` and `Uncompact` fail with `ErrBusy` while a turn is in flight; wait for the turn first. `Fork`, `Label`, `SetInfo`, `Custom` and `Pin` do not wait. (Source: `thread/errors.go:8-15`; `thread/branch.go:67` Branch godoc; `thread/session.go:1327-1450`; CHANGELOG.md:5187)
- **A fork is another session.** It has its own writer, its own public id (or none) and its own id; a branch keeps one session and one context line. (Source: `thread/branch.go:266` Fork godoc)
- **Put filterable keys in `WithMeta` at `Create`.** `SetInfo` metadata reaches runs and `Meta()` but never `Query.Meta`. (Source: `thread/storage.go:117-125`; `ExampleWithMeta`)
- **Never put a `weft.` key in `SetInfo`.** It is rejected with `ErrReservedKey`; identity is set once, in the header. (Source: `thread/errors.go:172-177`)
- **Look a public id up before you `Create` with it.** `Create` writes a second session under an id already in use; `thread.List`'s `Query.Meta` on `weft.public_id` finds the existing one to `Open`. (Source: `thread/session.go:507-549`; `thread/storage.go:117-125`)
- **Keep the public id opaque.** It is shown to browsers and stamped on every record; an email or a name does not belong there. (Source: `thread/session.go:244` PublicID godoc)
- **`SummarizeLeft` makes a model call.** It runs the session's summary chain (`SummaryModel`, else the session's model) before the branch lands, so it costs a request; in a scripted test it consumes a scripted reply. That request is on no ledger: a `branch_summary` entry records no usage, so `s.Usage().Summaries` does not count it. (Source: `thread/branch.go:33-45`; `thread/session.go:1532-1536`; `ExampleSummarizeLeft`)

## See also

- [What is a session?](https://weftgo.dev/docs/sessions/overview/)
- [Keep long sessions inside the context window (compaction)](https://weftgo.dev/docs/sessions/compaction/)
- [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/)
- [The session log format](https://weftgo.dev/docs/sessions/format/): `leaf`, `label`, `info`, `custom` and `branch_summary` entries

Symbols used: [`Session.Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) · [`Session.Fork`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Fork) · [`Session.Label`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Label) · [`Session.Leaf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) · [`Session.Custom`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Custom) · [`Session.CustomMessage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CustomMessage) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`Session.Title`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) · [`Session.Meta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Meta) · [`Session.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage) · [`thread.SummarizeLeft`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummarizeLeft) · [`thread.BranchOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchOption) · [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) · [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry) · [`thread.PublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PublicID) · [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) · [`thread.WithLineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy) · [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly) · [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) · [`thread.RunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
