The session log format
A stored session is lines of JSON: a header line first, then one entry per line in append order. Every line carries a type; the header carries the envelope "weft": 1, and an entry kind added after format 1 carries "v", its minimum reader version. A reader fails with thread.ErrNewerFormat on a kind it does not know or a "v" above what it reads, and ignores every other unknown key. Signatures and doc comments are on pkg.go.dev; this page groups the wire.
sessions/format.go writes a session with a parked call, a decision, a label, an info edit, a custom entry and a pool delegation, then reads the files back:
sessions := filepath.Join(dir, "format")st, err := jsonl.Open(sessions)if err != nil { return nil, nil, err}agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), // parks: refund requires approval wefttest.Say("Refunded order 1234."),), refundTool(), quiet)s, err := thread.Create(ctx, st, agent, ctxWindow, thread.PublicID("pub_42"), ids("s_fmt", "a"), at(base))if err != nil { return nil, nil, err}turn, err := s.Send(ctx, weft.User("Refund order 1234."))if err != nil { return nil, nil, err}if _, err := turn.Wait(); err != nil { return nil, nil, err}resumed, err := s.Decide(ctx, thread.Approve("call_1"))if err != nil { return nil, nil, err}if _, err := settle(resumed); err != nil { return nil, nil, err}if err := s.Label(ctx, "e_a1", "refund-asked"); err != nil { return nil, nil, err}if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return nil, nil, err}if err := s.Custom(ctx, "ticket", json.RawMessage(`{"id":88}`)); err != nil { return nil, nil, err}p := pool.New(1, childIDs())mailer := weft.New(wefttest.Script(wefttest.Say("Receipt sent.")), quiet)r, err := p.Submit(ctx, s, mailer, "Email the receipt.")if err != nil { return nil, nil, err}if _, err := p.Wait(ctx, s, r.ID); err != nil { return nil, nil, err}if err := p.Close(ctx); err != nil { return nil, nil, err}if err := s.Close(ctx); err != nil { return nil, nil, err}parent, err = fileLines(filepath.Join(sessions, "s_fmt.jsonl"))if err != nil { return nil, nil, err}child, err = fileLines(filepath.Join(sessions, r.Child+".jsonl")){"type":"session","weft":1,"id":"s_fmt","created":"2026-10-18T09:00:00Z","meta":{"weft.public_id":"pub_42"}}{"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Refund order 1234."}]},"run_id":"s_fmt-t1"}{"type":"message","id":"e_a2","parent":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"assistant","content":[{"type":"tool_call","id":"call_1","name":"refund","args":{"order_id":"1234"}}]}}{"type":"turn","id":"e_a3","parent":"e_a2","created":"2026-10-18T09:00:00Z","run_id":"s_fmt-t1","stop_reason":"tool_calls","usage":{"input_tokens":10,"output_tokens":5},"steps":1,"pending":[{"type":"tool_call","id":"call_1","name":"refund","args":{"order_id":"1234"}}],"policy":"queue","last_input":38}{"type":"approval_request","v":2,"id":"e_a4","parent":"e_a3","created":"2026-10-18T09:00:00Z","call_id":"call_1","tool":"refund","args":{"order_id":"1234"},"args_sha256":"7d0656a84e6bbb1695439d794ea5a55e75f09fcb176bbef1b717cf1142332df6","run_id":"s_fmt-t1","reason":"tool requires approval"}{"type":"approval_audit","v":2,"id":"e_a5","parent":"e_a4","created":"2026-10-18T09:00:00Z","call_id":"call_1","step":"park","outcome":"parked","run_id":"s_fmt-t1"}{"type":"approval_decision","v":2,"id":"e_a6","parent":"e_a5","created":"2026-10-18T09:00:00Z","call_id":"call_1","outcome":"approve","via":"user","run_id":"s_fmt-t1","request_id":"e_a4"}{"type":"approval_audit","v":2,"id":"e_a8","parent":"e_a6","created":"2026-10-18T09:00:00Z","step":"resume","outcome":"started","detail":"1 call(s) to resolve","run_id":"s_fmt-t2","decisions":["e_a6"]}{"type":"message","id":"e_a9","parent":"e_a8","created":"2026-10-18T09:00:00Z","message":{"role":"tool","content":[{"type":"tool_result","call_id":"call_1","name":"refund","content":"refunded 1234","is_error":false}]}}{"type":"message","id":"e_a10","parent":"e_a9","created":"2026-10-18T09:00:00Z","message":{"role":"assistant","content":[{"type":"text","text":"Refunded order 1234."}]}}{"type":"turn","id":"e_a7","parent":"e_a10","created":"2026-10-18T09:00:00Z","run_id":"s_fmt-t2","stop_reason":"stop","usage":{"input_tokens":10,"output_tokens":5},"steps":1,"last_input":30}{"type":"approval_audit","v":2,"id":"e_a11","parent":"e_a7","created":"2026-10-18T09:00:00Z","step":"resume","outcome":"completed","run_id":"s_fmt-t2"}{"type":"label","id":"e_a12","parent":"e_a11","created":"2026-10-18T09:00:00Z","entry":"e_a1","name":"refund-asked"}{"type":"info","id":"e_a13","parent":"e_a12","created":"2026-10-18T09:00:00Z","title":"Refund for order 1234"}{"type":"custom","id":"e_a14","parent":"e_a13","created":"2026-10-18T09:00:00Z","kind":"ticket","data":{"id":88}}{"type":"pool_receipt","v":4,"id":"e_a15","parent":"e_a14","created":"2026-10-18T09:00:00Z","status":"accepted","child":"c_1","prompt":"Email the receipt."}{"type":"pool_receipt","v":4,"id":"e_a16","parent":"e_a15","created":"2026-10-18T09:00:00Z","receipt":"e_a15","status":"running","child":"c_1"}{"type":"pool_receipt","v":4,"id":"e_a17","parent":"e_a16","created":"2026-10-18T09:00:00Z","receipt":"e_a15","status":"done","child":"c_1","stop":"Receipt sent.","usage":{"input_tokens":10,"output_tokens":5}}-- the child's header{"type":"session","weft":1,"id":"c_1","created":"2026-10-18T09:00:00Z","lineage":{"parent_session":"s_fmt"}}The ids and the clock are pinned by the demo’s ids and at helpers; an application gets time-sortable ids and real times. File order is append order, and parent is what links the tree. TestFormatLinesParse decodes every line back as the kind this page lists for it.
The file
Section titled “The file”| Aspect | thread/jsonl | thread/sqlite |
|---|---|---|
| Where a session lives | <dir>/<id>.jsonl | rows in one database file |
| The header line | line 1 of the file | sessions.header, verbatim; sessions.envelope holds its "weft" integer (0 for a row that is not a session header) |
| Entry lines | lines 2 onward, one per line, each ending in a newline | entries.line, one row per entry, ordered by entries.seq (arrival order) |
| A torn final line | bytes after the last newline | a row with entries.torn = 1, only in data written through threadtest.RawInjector’s Inject: sqlite’s own appends never tear |
| Derived columns | none: the file is the index | sessions.created, sessions.title (the last non-empty info title), sessions.gen (a random generation set at Create) |
| The writer lock | an advisory lock on the file, not in it | a session_locks row: host, owner, pid, taken, process, started |
| Schema version | the format itself | thread_migrations; migrations 0001_sessions, 0002_sessions_title, 0003_leases_keyset |
Both backends store the same line bytes, so they differ in where the lines live, never in what they say. Line numbers in a *thread.CorruptError and a thread.LoadReport are 1-based, the header being line 1. sqlite’s own time columns (sessions.created, session_locks.taken) are RFC 3339 with nine-digit nanoseconds, UTC, so their text order is time order. The stored lines keep their own encoding, the same bytes as jsonl.
Header
Section titled “Header”thread.Header is a session’s first line: its identity, creation time, fork origin, pool lineage and create-time metadata. "type": "session" marks it; no other line carries that type. Beyond that the header is immutable: title and metadata edits are info entries.
| JSON key | Go field | Type | Notes |
|---|---|---|---|
type | — | "session" | written by Header.MarshalJSON |
weft | Weft | integer | the envelope, 1; a zero Weft writes FormatVersion, and Create rejects any other value |
id | ID | string | the session id: 1 to 128 letters, digits, _ or - (thread.ValidID) |
created | Created | RFC 3339 time | |
parent | Parent | ParentRef | a fork’s origin; optional |
lineage | Lineage | Lineage | a pool child’s parent; optional (format 4) |
meta | Meta | object of strings | create-time metadata; optional. Keys under weft. are reserved: weft.public_id, weft.require_signed ("true"). A child a pool wrap made carries pool_agent, the wrap’s name |
run_meta | RunMeta | object of strings | the run metadata every turn of the session carries (thread.WithRunMetadata), stamped on each run under the session’s identity keys, which win; optional (0.18.0). Additive: a reader from before ignores it and stamps none |
Header.UnmarshalJSON enforces the envelope: a weft above FormatVersion fails with ErrNewerFormat; any other value but 1, or a type other than session, fails as not a header this format wrote. Unknown keys are ignored.
FormatVersion
Section titled “FormatVersion”thread.FormatVersion is 1: the wire version of every document the thread module writes, the integer every weft wire document carries. It moves only for a layout change a reader cannot handle additively; a new entry kind, a new optional key or a new entry version never moves it.
ParentRef
Section titled “ParentRef”thread.ParentRef names a fork’s origin. The fork’s file holds the copied path as its first entries, so it is self-contained.
| JSON key | Go field | Notes |
|---|---|---|
session | Session | the session the fork was made from |
entry | Entry | the entry its copied path ends at |
Lineage
Section titled “Lineage”thread.Lineage names a pool child’s origin. It is a reference, not a copy: the child’s file holds only its own entries.
| JSON key | Go field | Notes |
|---|---|---|
parent_session | Session | the parent session |
parent_call_id | Call | the delegating call, for a wrapped delegation; omitted for a Submit |
thread.Entry is the sealed set of entry kinds: a session is an append-only tree of them, and the leaf is the entry the next one attaches to. External types cannot join. Every entry of every kind carries these keys:
| JSON key | Go field | Notes |
|---|---|---|
type | — | the kind’s discriminator, written by each kind’s MarshalJSON |
v | — | the minimum reader version, on kinds added after format 1 (the version rule) |
id | ID | the entry’s id, unique in the session |
parent | ParentID | the entry it attaches to; omitted on a root (a session may have several roots) |
created | Created | RFC 3339 time, from the session’s clock |
Whether a kind enters the model’s context is part of its contract: message and custom_message do; compaction and branch_summary contribute their summary; the bookkeeping kinds never do.
UnmarshalEntry
Section titled “UnmarshalEntry”thread.UnmarshalEntry(b) decodes one entry line, dispatching on its type. A line with no type fails. A kind this build does not know fails with ErrNewerFormat, as does a known kind whose "v" is above the version this build reads of it. Every other unknown key is ignored. Each kind’s MarshalJSON writes it back with its type and, where it has one, its "v"; the goldens round-trip to the same bytes.
ErrNoEntry
Section titled “ErrNoEntry”thread.ErrNoEntry is returned when an operation names an entry the session does not hold, Pin’s target or a compaction’s FirstKept, or asks for one the leaf’s path does not have (Uncompact with no compaction to undo).
Entry kinds
Section titled “Entry kinds”type | Go type | Since | "v" | In the model’s context |
|---|---|---|---|---|
message | MessageEntry | 1 | — | yes |
turn | TurnEntry | 1 | — | no |
compaction | CompactionEntry | 1 | — (5 with trim) | the summary |
branch_summary | BranchSummaryEntry | 1 | — | the summary |
leaf | LeafEntry | 1 | — | no |
label | LabelEntry | 1 | — | no |
info | InfoEntry | 1 | — | no |
custom | CustomEntry | 1 | — | no |
custom_message | CustomMessageEntry | 1 | — | yes |
approval_request | ApprovalRequestEntry | 2 | 2 | no |
approval_decision | ApprovalDecisionEntry | 2 | 2 | no |
approval_audit | ApprovalAuditEntry | 2 | 2 | no |
grant | GrantEntry | 2 | 2 | no |
grant_revoked | GrantRevokedEntry | 2 | 2 | no |
receipt | ReceiptEntry | 3 | 3 | no |
pool_receipt | PoolReceiptEntry | 4 | 4 | no |
“Since” is the format step that introduced the kind: 1 is thread v0.1, 2 approvals (v0.2), 3 steering receipts (v0.3), 4 the pool (v0.5), 5 the trim record (thread 0.9.0). In the field tables below, every entry’s common keys are left out, and an optional key is one the writer omits when empty.
MessageEntry
Section titled “MessageEntry”thread.MessageEntry is one message of the transcript, embedded with the core’s message wire verbatim. It is how conversation content is stored, and it is always in the model’s context.
| JSON key | Go field | Type | Notes |
|---|---|---|---|
message | Message | weft.Message | {role, content: [parts]}; roles user, assistant, tool |
run_id | RunID | string, optional | on a turn’s prompt entry only: the run id minted for the turn, <session>-t<n>, written before the run does anything, so a reopened session never mints it again |
TurnEntry
Section titled “TurnEntry”thread.TurnEntry is the per-turn ledger: it records the turn’s outcome, never its content. One run, one turn entry; a turn that overflowed and re-ran leaves two, the failed attempt’s (with rerun) and the re-run’s. Session.Usage sums both.
| JSON key | Go field | Type | Notes |
|---|---|---|---|
run_id | RunID | string | <session>-t<n> |
stop_reason | StopReason | weft.StopReason, optional | stop, tool_calls, max_tokens |
usage | Usage | weft.Usage | input_tokens, output_tokens, optional cached_input_tokens, cache_write_tokens, reasoning_tokens |
steps | Steps | integer, optional | model steps the run took |
err | Err | string, optional | the error text on failure |
pending | Pending | tool-call parts, optional | the calls left on the approval boundary |
canceled | Canceled | bool, optional | the turn’s context ended: canceled (the caller walked away, an Interrupt or Rollback send, Close) or past its deadline; err says which |
policy | Policy | string, optional | the busy policy the Send was called under: queue, reject, steer, interrupt, rollback; a steer’s follow-up records steer; empty on a resume turn |
rerun | ReRun | string, optional | on an overflow attempt that was re-run, the re-run’s run id, written before it starts |
last_input | LastInput | integer, optional | the compaction trigger’s baseline: the final step’s reported input plus the estimated tokens of that step’s own messages; absent on a turn that ran no step |
late_steps | LateSteps | integer, optional | per-step appends that failed and were written late; nothing was lost, and the storage was unhealthy for that long |
CompactionEntry
Section titled “CompactionEntry”thread.CompactionEntry records one compaction (compaction). Nothing is deleted: the summarized entries stay in the file. A summary compaction is a format-1 line with no "v"; one carrying a trim record is written with "v": 5, so an older reader fails instead of replaying the trim from its own options.
| JSON key | Go field | Type | Notes |
|---|---|---|---|
summary | Summary | string, optional | the summary text; empty on a trim |
first_kept | FirstKept | string | the first entry kept raw after it |
tokens_before | TokensBefore | integer | estimated size of the context the model was shown when it ran (the compacted view, not the raw path) |
reason | Reason | thread.Reason, optional | manual, threshold, overflow, from_hook, trim |
summarizer_usage | SummarizerUsage | weft.Usage, optional | what the summary cost; absent on a trim |
summarizer_model | SummarizerModel | weft.ModelInfo, optional | {provider, name} of the model that made it |
files_read | FilesRead | strings, optional | |
files_modified | FilesModified | strings, optional | a format-1 field kept readable: no build writes it, and a file that carries it round-trips unchanged |
pinned | Pinned | strings, optional | entries kept through the compaction |
range_hash | RangeHash | string, optional | a hash of the summarized range |
trim | Trim | TrimRecord, optional | present exactly on a trim |
A trim is the same entry with an empty summary, reason trim and a trim record. It never moves the boundary: the latest summary compaction below it keeps governing the context, the stubs layer over the kept range, and its first_kept only repeats the boundary in force.
TrimRecord
Section titled “TrimRecord”thread.TrimRecord is what a trim did, persisted so the context replays it from the file alone: the walk applies exactly these stubs and never consults the session’s configured trimmer.
| JSON key | Go field | Notes |
|---|---|---|
stubs | Stubs | the TrimStub list |
TrimStub
Section titled “TrimStub”thread.TrimStub is one stubbed tool result. The stored result is untouched.
| JSON key | Go field | Notes |
|---|---|---|
entry | Entry | the entry that holds the result |
call_id | CallID | the call it answers |
content | Content | what the model sees in its place |
is_error | IsError | what the stubbed part reports; optional, false for the built-in trimmer’s stub |
BranchSummaryEntry
Section titled “BranchSummaryEntry”thread.BranchSummaryEntry summarizes the branch a Branch leaves behind, so the context shows the summary in place of that branch’s messages.
| JSON key | Go field | Notes |
|---|---|---|
summary | Summary | the text |
from_entry | FromEntry | the entry the abandoned branch grew from |
LeafEntry
Section titled “LeafEntry”thread.LeafEntry moves the session’s leaf to an existing entry: branch navigation without a rewrite. The next entry attaches to entry. Its parent is where the leaf entry itself was appended.
| JSON key | Go field | Notes |
|---|---|---|
entry | Entry | the entry the leaf moves to; empty is the root |
abandoned | Abandoned | true on the one leaf entry that is no navigation: a failed or refused send’s unwind, moving the leaf back to where that send found it. A reader naming the branch a turn descends from (weft.session.branch) skips it. Optional (0.18.0); a session written before reads its unwinds as navigations |
It is written by Branch, by Uncompact, by a Rollback send, and by an overflow re-run, whose failed attempt keeps its messages on their own branch. It is also written by the unwind of a Send that failed or was refused (a failed prompt or receipt flush, a refused interrupting send, a steer whose follow-up could not be queued). A failed turn whose final form differs from its raw tail writes no leaf entry: the corrected tail attaches after the last entry that still matches. ADR 0011 §7 says a leaf entry is written there; the code does not.
LabelEntry
Section titled “LabelEntry”thread.LabelEntry names an entry: bookmarks, checkpoints, a UI’s anchors.
| JSON key | Go field | Notes |
|---|---|---|
entry | Entry | the entry named |
name | Name | the label |
InfoEntry
Section titled “InfoEntry”thread.InfoEntry edits the title and metadata as an append. The current title is the last info entry’s non-empty title; the current metadata is every info entry’s meta merged in order over the header’s.
| JSON key | Go field | Notes |
|---|---|---|
title | Title | optional |
meta | Meta | object of strings, optional; never a weft. key |
CustomEntry
Section titled “CustomEntry”thread.CustomEntry carries application state. It survives every compaction and never enters the model’s context.
| JSON key | Go field | Notes |
|---|---|---|
kind | Kind | caller-chosen, not empty |
data | Data | any JSON, verbatim; optional (nil writes no key) |
CustomMessageEntry
Section titled “CustomMessageEntry”thread.CustomMessageEntry carries an application message that is always in the model’s context, a note the model must see without attributing it to the user.
| JSON key | Go field | Notes |
|---|---|---|
kind | Kind | caller-chosen, not empty |
message | Message | a weft.Message |
ApprovalRequestEntry
Section titled “ApprovalRequestEntry”thread.ApprovalRequestEntry is a parked call made durable, written in the same append as the turn entry that parked it. Its id names this one occurrence of the call: call ids repeat across turns, entry ids never do.
| JSON key | Go field | Notes |
|---|---|---|
call_id | CallID | the pending call; <child>/<call> on a pool mirror |
tool | Tool | the tool name |
args | Args | the arguments as the model wrote them; optional |
args_sha256 | ArgsSHA256 | hex SHA-256 of the arguments |
run_id | RunID | the run that parked the call |
reason | Reason | why it parked: tool requires approval, middleware required approval; optional |
expiry | Expiry | when the request lapses; optional |
child | Child | the pool child session this request mirrors; optional |
wrapper | Wrapper | the parent-side delegating call it parks under; optional |
ApprovalDecisionEntry
Section titled “ApprovalDecisionEntry”thread.ApprovalDecisionEntry is one decision over a parked call. The model sees it only through the result the resumed run produces.
| JSON key | Go field | Notes |
|---|---|---|
call_id | CallID | the call decided |
outcome | Outcome | thread.Outcome: approve, deny, resolve, resolve_error |
reason | Reason | a deny’s reason; optional |
content | Content | a resolve’s result; optional |
who | Who | the decider; optional |
via | Via | the channel: user, signed, approver, grant, expiry, interrupt, child, parent; optional |
run_id | RunID | the run the decided request belonged to; optional |
nonce | Nonce | a signed decision’s nonce, the replay guard; optional |
key_id | KeyID | the key that vouched for a signed decision, and its identity under Quorum; optional |
request_id | RequestID | the request entry the decision answers; empty on a grant’s or the Approver’s decision; optional |
always | Always | an ApproveAlways: the grant is minted when the verdict becomes approve; optional |
ApprovalAuditEntry
Section titled “ApprovalAuditEntry”thread.ApprovalAuditEntry is the decision chain’s own trail, automatic approvals included, so s.Audit() can tell the whole story from the file alone. detail is prose for a human and never parsed.
| JSON key | Go field | Notes |
|---|---|---|
call_id | CallID | optional |
step | Step | grant, approver, park, expiry, resume, signed |
outcome | Outcome | how the step ended, such as parked, or a resume’s started, completed, failed; optional |
detail | Detail | optional |
run_id | RunID | optional |
grant_id | GrantID | the grant a grant step matched; one entry is one use of a MaxUses grant; optional |
grant_shared | GrantShared | the grant is a GrantStore’s, and grant_id is the store’s id; optional |
key_id | KeyID | the key a refused signed decision claimed; optional |
decisions | Decisions | the decision entries a resume applied (resume, started); optional |
GrantEntry
Section titled “GrantEntry”thread.GrantEntry is a session-scoped grant made durable: a standing approval, or with deny a standing refusal, for future calls of one tool. It embeds thread.Grant, whose keys sit at the top level of the line. Liveness is derived, never stored.
| JSON key | Go field | Notes |
|---|---|---|
tool | Grant.Tool | the tool name, matched exactly |
args | Grant.Args | [{pointer, equals | prefix | glob}], every predicate must match; optional |
deny | Grant.Deny | a standing refusal; optional |
reason | Grant.Reason | a deny’s model-visible text (denied by grant when empty), or an approval’s note; optional |
expiry | Grant.Expiry | optional |
max_uses | Grant.MaxUses | counted from approval_audit.grant_id; optional |
GrantRevokedEntry
Section titled “GrantRevokedEntry”thread.GrantRevokedEntry ends a grant. Revocation is an append: the grant entry stays, and the audit trail keeps both.
| JSON key | Go field | Notes |
|---|---|---|
grant_id | GrantID | the grant entry’s id |
ReceiptEntry
Section titled “ReceiptEntry”thread.ReceiptEntry is the receipt of a message accepted while the session was busy. An idle Send writes no receipt: its message is the prompt entry. A steer is two entries, queued and then its fate linked by receipt; a queued send is one accepted entry, settled by its prompt entry landing or a dropped entry (Receipts).
| JSON key | Go field | Notes |
|---|---|---|
receipt | Receipt | the acceptance entry a later one settles; optional |
status | Status | queued, accepted, delivered, deferred, dropped |
msg | Msg | the message, on an acceptance; optional |
run_id | RunID | the run that delivered a steer, or the run minted for a queued send; optional |
turn | Turn | the prompt entry id a queued send or deferred steer will take; optional |
unanswered | Unanswered | on a delivered receipt: the run took the steer and failed before answering it; optional |
An accepted receipt with neither a prompt entry nor a dropped entry is a send the writer never got to: Open restores it to the queue.
PoolReceiptEntry
Section titled “PoolReceiptEntry”thread.PoolReceiptEntry is one step of a pool delegation’s journey (Receipts). One entry records acceptance; every later one links back to it by receipt.
| JSON key | Go field | Notes |
|---|---|---|
receipt | Receipt | the acceptance entry; empty on the acceptance itself |
status | Status | accepted, running, parked, done, failed, canceled, capped |
child | Child | the child session; optional on the wire, always set by the pool |
call | Call | the delegating tool call, for a wrapped delegation; optional |
prompt | Prompt | the task, on the acceptance; optional |
stop | Stop | on a settlement: the answer (done) or the cause; optional |
usage | Usage | on a settlement: the child session’s whole cost; summed into Usage.Delegated; optional |
The version rule
Section titled “The version rule”- The envelope. The header carries
"weft": 1. It moves only for a layout change a reader cannot handle additively. - Entry versions. A kind born in format 1 carries no
"v". A kind added later is written with"v": N, its minimum reader version. A format-1 kind that gains a field an older reader would misread writes"v": Non the entries carrying that field (the compaction’s trim record, 5). - What this build reads: the format-1 kinds at 1,
compactionup to 5, the approval kinds at 2,receiptat 3,pool_receiptat 4. - Additive keys need no version. A new optional key an older reader loses nothing by ignoring is added without one.
What a reader does with newer data
Section titled “What a reader does with newer data”An older reader never guesses (thread rule T5). This is what v0.20.2 does with lines a newer weft could write:
for _, line := range []string{ `{"type":"message","v":2,"id":"e_1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[]}}`, `{"type":"snapshot","v":6,"id":"e_2","created":"2026-10-18T09:00:00Z"}`,} { _, err := thread.UnmarshalEntry([]byte(line)) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err)}var h thread.Headererr := json.Unmarshal([]byte(`{"type":"session","weft":2,"id":"s_x","created":"2026-10-18T09:00:00Z"}`), &h)fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err)true thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1true thread: session format newer than this build: entry kind "snapshot" is unknown to this buildtrue thread: session format newer than this build: session header has weft=2, this build reads 1| It meets | It does |
|---|---|
| an unknown entry kind | fails with ErrNewerFormat, Salvage or not |
a known kind with "v" above what it reads | fails with ErrNewerFormat, Salvage or not |
a header envelope above FormatVersion | fails Load with ErrNewerFormat; List does not show the session |
| an unknown key on a line it reads | ignores it |
| a malformed line | thread.ErrCorrupt naming the line; skipped and reported under Salvage |
| a torn final line | drops it and reports it in LoadReport.Torn |
Two additions change what an older build does, not what it reads: a build from before the accepted receipt status reads the entry and does not restore the queued send, and one from before weft.require_signed ignores the key and does not enforce it. Upgrade weft has the operational side.
Format history
Section titled “Format history”The changes since format 1, from the CHANGELOG. The header envelope has been "weft": 1 throughout.
| Release | Wire change |
|---|---|
| thread 0.1.0 | the format-1 kinds message, turn, compaction, branch_summary, leaf, label, info, custom, custom_message; the {"weft":1} envelope and the "v" rule |
| thread 0.2.0 | approval_request, approval_decision, approval_audit, grant, grant_revoked, at "v": 2; a v0.1 reader fails loudly on a session that used approvals |
| thread 0.3.0 | receipt, "v": 3 |
| thread 0.5.0 | pool_receipt, "v": 4; the header’s lineage |
| thread 0.5.0 | approval_request: child, wrapper; mirrored call ids <child>/<call> (additive, no "v" change) |
| thread 0.9.0 | compaction with a trim record at "v": 5 (an older build fails on it on purpose; a summary compaction is unchanged) |
| thread 0.9.0 | message: run_id on a turn’s prompt entry |
| thread 0.9.0 | turn: policy, rerun, late_steps; canceled also set on a deadline |
| thread 0.9.0 | receipt: the status accepted with msg, turn, run_id; unanswered on a delivered receipt |
| thread 0.9.0 | pool_receipt: the status parked |
| thread 0.9.0 | approval_decision: request_id, always; via values interrupt, child, parent |
| thread 0.9.0 | approval_audit: grant_id, grant_shared, key_id, decisions; the step signed; the resume outcomes started, completed, failed |
| thread 0.9.0 | header metadata weft.require_signed ("true") |
| thread 0.9.0 | the signing challenge’s domain string weft/approval-challenge/v2, covering the request entry id and the run id; not stored; in-flight v1 signatures do not verify |
| thread 0.9.0 | thread/sqlite migration 0003_leases_keyset: session_locks gains process and started; sessions gains gen and envelope; the index sessions_order(envelope, created DESC, id DESC) replaces sessions_created; the title re-derived under the last-non-empty rule |
| thread 0.9.0 | grant uses counted from approval_audit.grant_id; uses recorded only as prose (detail) are not counted, so a MaxUses grant in such a file starts again |
| thread 0.9.0 | TurnEntry.Policy, ReRun, LateSteps, MessageEntry.RunID, ReceiptEntry.Unanswered and thread.ReceiptAccepted added to the Go API |
| weft 0.18.0 | the header’s run_meta (Header.RunMeta, WithRunMetadata); leaf: abandoned (additive, no "v" change) |
Goldens for every kind and most variants live in thread/testdata/format1 to format5, with a whole session in format1/session.jsonl. TestReadEveryGolden reads and re-marshals the goldens of all five formats to the same bytes; TestTrimRecordGolden also writes and pins format5/compaction_trim.json. No golden yet carries a mirrored request’s child and wrapper or a fork header’s parent. The format is not frozen: the freeze that would make it a compatibility promise is deferred (ADR 0011, amendment §D).
Complete example
Section titled “Complete example”sessions/format.go writes the session above and decodes newer data:
package main
import ( "context" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/thread/pool" "github.com/weftgo/weft/wefttest")
// demoFormat is the page "The session log format": it writes a real// session with a parked call, a decision, a label, an info edit, a// custom entry and a pool delegation, and prints its file.func demoFormat(ctx context.Context, w io.Writer, dir string) error { parent, child, err := formatCapture(ctx, dir) if err != nil { return err } for _, line := range parent { fmt.Fprintln(w, line) } fmt.Fprintln(w, "-- the child's header") fmt.Fprintln(w, child[0]) fmt.Fprintln(w, "-- a newer weft's data") return formatNewer(w)}
// formatCapture writes the session and returns the lines of the// parent's file and of its pool child's file.func formatCapture(ctx context.Context, dir string) (parent, child []string, err error) { quiet := weft.Logger(textLogger(io.Discard)) sessions := filepath.Join(dir, "format") st, err := jsonl.Open(sessions) if err != nil { return nil, nil, err } agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), // parks: refund requires approval wefttest.Say("Refunded order 1234."), ), refundTool(), quiet) s, err := thread.Create(ctx, st, agent, ctxWindow, thread.PublicID("pub_42"), ids("s_fmt", "a"), at(base)) if err != nil { return nil, nil, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return nil, nil, err } if _, err := turn.Wait(); err != nil { return nil, nil, err } resumed, err := s.Decide(ctx, thread.Approve("call_1")) if err != nil { return nil, nil, err } if _, err := settle(resumed); err != nil { return nil, nil, err } if err := s.Label(ctx, "e_a1", "refund-asked"); err != nil { return nil, nil, err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return nil, nil, err } if err := s.Custom(ctx, "ticket", json.RawMessage(`{"id":88}`)); err != nil { return nil, nil, err } p := pool.New(1, childIDs()) mailer := weft.New(wefttest.Script(wefttest.Say("Receipt sent.")), quiet) r, err := p.Submit(ctx, s, mailer, "Email the receipt.") if err != nil { return nil, nil, err } if _, err := p.Wait(ctx, s, r.ID); err != nil { return nil, nil, err } if err := p.Close(ctx); err != nil { return nil, nil, err } if err := s.Close(ctx); err != nil { return nil, nil, err } parent, err = fileLines(filepath.Join(sessions, "s_fmt.jsonl")) if err != nil { return nil, nil, err } child, err = fileLines(filepath.Join(sessions, r.Child+".jsonl")) return parent, child, err}
// fileLines returns a session file's lines, header first.func fileLines(path string) ([]string, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n"), nil}
// formatNewer decodes lines a newer weft could write: each fails with// ErrNewerFormat, never a skip.func formatNewer(w io.Writer) error { for _, line := range []string{ `{"type":"message","v":2,"id":"e_1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[]}}`, `{"type":"snapshot","v":6,"id":"e_2","created":"2026-10-18T09:00:00Z"}`, } { _, err := thread.UnmarshalEntry([]byte(line)) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) } var h thread.Header err := json.Unmarshal([]byte(`{"type":"session","weft":2,"id":"s_x","created":"2026-10-18T09:00:00Z"}`), &h) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) return nil}View on GitHub · run it from docs-site/examples:
go run ./sessions formatgo test ./sessionsThe output is the session’s lines above, then:
-- a newer weft's datatrue thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1true thread: session format newer than this build: entry kind "snapshot" is unknown to this buildtrue thread: session format newer than this build: session header has weft=2, this build reads 1Best practices & gotchas
Section titled “Best practices & gotchas”- Never write a line by hand into a session a Session holds. Write through the Session; a line behind its back breaks the one-writer rule and the stale check. (Source: AGENTS.md T1)
- A tool reading session files decodes with
thread.UnmarshalEntry, or applies its rule: fail on an unknowntypeor a newer"v", ignore unknown keys. (Source:thread/entry.go:979-998) - The format is documented, not frozen. Pre-1.0 a minor release may change it, with a CHANGELOG entry. (Source:
thread/header.go:9-24; ADR 0011 amendment §D) - ADR 0011 is stale on two points. It calls
threada module of its own (it is a package ofgithub.com/weftgo/weft), and its §7 says a failed turn’s rewrite writes a leaf entry (the code writes none). (Source:thread/turn.go:1592-1619; ADR 0027)
See also
Section titled “See also”- What is a session?
- Operate sessions in production: Salvage, backups, upgrades
- Store sessions: JSONL, SQLite or memory
- Package thread on pkg.go.dev
Symbols used: thread.Header · thread.ParentRef · thread.Lineage · thread.FormatVersion · thread.Entry · thread.UnmarshalEntry · thread.ErrNoEntry · thread.ErrNewerFormat · thread.ErrCorrupt · thread.CorruptError · thread.LoadReport · thread.ValidID · thread.MessageEntry · thread.TurnEntry · thread.CompactionEntry · thread.Reason · thread.TrimRecord · thread.TrimStub · thread.BranchSummaryEntry · thread.LeafEntry · thread.LabelEntry · thread.InfoEntry · thread.CustomEntry · thread.CustomMessageEntry · thread.ApprovalRequestEntry · thread.ApprovalDecisionEntry · thread.Outcome · thread.ApprovalAuditEntry · thread.GrantEntry · thread.Grant · thread.GrantRevokedEntry · thread.ReceiptEntry · thread.PoolReceiptEntry · weft.Message · weft.Usage · weft.ModelInfo · weft.StopReason