Skip to content

The session log format

View as Markdown

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/format.go
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"))

sessions/format.go on GitHub

{"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.

Aspectthread/jsonlthread/sqlite
Where a session lives<dir>/<id>.jsonlrows in one database file
The header lineline 1 of the filesessions.header, verbatim; sessions.envelope holds its "weft" integer (0 for a row that is not a session header)
Entry lineslines 2 onward, one per line, each ending in a newlineentries.line, one row per entry, ordered by entries.seq (arrival order)
A torn final linebytes after the last newlinea row with entries.torn = 1, only in data written through threadtest.RawInjector’s Inject: sqlite’s own appends never tear
Derived columnsnone: the file is the indexsessions.created, sessions.title (the last non-empty info title), sessions.gen (a random generation set at Create)
The writer lockan advisory lock on the file, not in ita session_locks row: host, owner, pid, taken, process, started
Schema versionthe format itselfthread_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.

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 keyGo fieldTypeNotes
type—"session"written by Header.MarshalJSON
weftWeftintegerthe envelope, 1; a zero Weft writes FormatVersion, and Create rejects any other value
idIDstringthe session id: 1 to 128 letters, digits, _ or - (thread.ValidID)
createdCreatedRFC 3339 time
parentParentParentRefa fork’s origin; optional
lineageLineageLineagea pool child’s parent; optional (format 4)
metaMetaobject of stringscreate-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_metaRunMetaobject of stringsthe 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.

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.

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 keyGo fieldNotes
sessionSessionthe session the fork was made from
entryEntrythe entry its copied path ends at

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 keyGo fieldNotes
parent_sessionSessionthe parent session
parent_call_idCallthe 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 keyGo fieldNotes
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)
idIDthe entry’s id, unique in the session
parentParentIDthe entry it attaches to; omitted on a root (a session may have several roots)
createdCreatedRFC 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.

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.

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).

typeGo typeSince"v"In the model’s context
messageMessageEntry1—yes
turnTurnEntry1—no
compactionCompactionEntry1— (5 with trim)the summary
branch_summaryBranchSummaryEntry1—the summary
leafLeafEntry1—no
labelLabelEntry1—no
infoInfoEntry1—no
customCustomEntry1—no
custom_messageCustomMessageEntry1—yes
approval_requestApprovalRequestEntry22no
approval_decisionApprovalDecisionEntry22no
approval_auditApprovalAuditEntry22no
grantGrantEntry22no
grant_revokedGrantRevokedEntry22no
receiptReceiptEntry33no
pool_receiptPoolReceiptEntry44no

“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.

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 keyGo fieldTypeNotes
messageMessageweft.Message{role, content: [parts]}; roles user, assistant, tool
run_idRunIDstring, optionalon 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

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 keyGo fieldTypeNotes
run_idRunIDstring<session>-t<n>
stop_reasonStopReasonweft.StopReason, optionalstop, tool_calls, max_tokens
usageUsageweft.Usageinput_tokens, output_tokens, optional cached_input_tokens, cache_write_tokens, reasoning_tokens
stepsStepsinteger, optionalmodel steps the run took
errErrstring, optionalthe error text on failure
pendingPendingtool-call parts, optionalthe calls left on the approval boundary
canceledCanceledbool, optionalthe turn’s context ended: canceled (the caller walked away, an Interrupt or Rollback send, Close) or past its deadline; err says which
policyPolicystring, optionalthe busy policy the Send was called under: queue, reject, steer, interrupt, rollback; a steer’s follow-up records steer; empty on a resume turn
rerunReRunstring, optionalon an overflow attempt that was re-run, the re-run’s run id, written before it starts
last_inputLastInputinteger, optionalthe 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_stepsLateStepsinteger, optionalper-step appends that failed and were written late; nothing was lost, and the storage was unhealthy for that long

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 keyGo fieldTypeNotes
summarySummarystring, optionalthe summary text; empty on a trim
first_keptFirstKeptstringthe first entry kept raw after it
tokens_beforeTokensBeforeintegerestimated size of the context the model was shown when it ran (the compacted view, not the raw path)
reasonReasonthread.Reason, optionalmanual, threshold, overflow, from_hook, trim
summarizer_usageSummarizerUsageweft.Usage, optionalwhat the summary cost; absent on a trim
summarizer_modelSummarizerModelweft.ModelInfo, optional{provider, name} of the model that made it
files_readFilesReadstrings, optional
files_modifiedFilesModifiedstrings, optionala format-1 field kept readable: no build writes it, and a file that carries it round-trips unchanged
pinnedPinnedstrings, optionalentries kept through the compaction
range_hashRangeHashstring, optionala hash of the summarized range
trimTrimTrimRecord, optionalpresent 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.

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 keyGo fieldNotes
stubsStubsthe TrimStub list

thread.TrimStub is one stubbed tool result. The stored result is untouched.

JSON keyGo fieldNotes
entryEntrythe entry that holds the result
call_idCallIDthe call it answers
contentContentwhat the model sees in its place
is_errorIsErrorwhat the stubbed part reports; optional, false for the built-in trimmer’s stub

thread.BranchSummaryEntry summarizes the branch a Branch leaves behind, so the context shows the summary in place of that branch’s messages.

JSON keyGo fieldNotes
summarySummarythe text
from_entryFromEntrythe entry the abandoned branch grew from

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 keyGo fieldNotes
entryEntrythe entry the leaf moves to; empty is the root
abandonedAbandonedtrue 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.

thread.LabelEntry names an entry: bookmarks, checkpoints, a UI’s anchors.

JSON keyGo fieldNotes
entryEntrythe entry named
nameNamethe label

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 keyGo fieldNotes
titleTitleoptional
metaMetaobject of strings, optional; never a weft. key

thread.CustomEntry carries application state. It survives every compaction and never enters the model’s context.

JSON keyGo fieldNotes
kindKindcaller-chosen, not empty
dataDataany JSON, verbatim; optional (nil writes no key)

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 keyGo fieldNotes
kindKindcaller-chosen, not empty
messageMessagea weft.Message

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 keyGo fieldNotes
call_idCallIDthe pending call; <child>/<call> on a pool mirror
toolToolthe tool name
argsArgsthe arguments as the model wrote them; optional
args_sha256ArgsSHA256hex SHA-256 of the arguments
run_idRunIDthe run that parked the call
reasonReasonwhy it parked: tool requires approval, middleware required approval; optional
expiryExpirywhen the request lapses; optional
childChildthe pool child session this request mirrors; optional
wrapperWrapperthe parent-side delegating call it parks under; optional

thread.ApprovalDecisionEntry is one decision over a parked call. The model sees it only through the result the resumed run produces.

JSON keyGo fieldNotes
call_idCallIDthe call decided
outcomeOutcomethread.Outcome: approve, deny, resolve, resolve_error
reasonReasona deny’s reason; optional
contentContenta resolve’s result; optional
whoWhothe decider; optional
viaViathe channel: user, signed, approver, grant, expiry, interrupt, child, parent; optional
run_idRunIDthe run the decided request belonged to; optional
nonceNoncea signed decision’s nonce, the replay guard; optional
key_idKeyIDthe key that vouched for a signed decision, and its identity under Quorum; optional
request_idRequestIDthe request entry the decision answers; empty on a grant’s or the Approver’s decision; optional
alwaysAlwaysan ApproveAlways: the grant is minted when the verdict becomes approve; optional

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 keyGo fieldNotes
call_idCallIDoptional
stepStepgrant, approver, park, expiry, resume, signed
outcomeOutcomehow the step ended, such as parked, or a resume’s started, completed, failed; optional
detailDetailoptional
run_idRunIDoptional
grant_idGrantIDthe grant a grant step matched; one entry is one use of a MaxUses grant; optional
grant_sharedGrantSharedthe grant is a GrantStore’s, and grant_id is the store’s id; optional
key_idKeyIDthe key a refused signed decision claimed; optional
decisionsDecisionsthe decision entries a resume applied (resume, started); optional

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 keyGo fieldNotes
toolGrant.Toolthe tool name, matched exactly
argsGrant.Args[{pointer, equals | prefix | glob}], every predicate must match; optional
denyGrant.Denya standing refusal; optional
reasonGrant.Reasona deny’s model-visible text (denied by grant when empty), or an approval’s note; optional
expiryGrant.Expiryoptional
max_usesGrant.MaxUsescounted from approval_audit.grant_id; optional

thread.GrantRevokedEntry ends a grant. Revocation is an append: the grant entry stays, and the audit trail keeps both.

JSON keyGo fieldNotes
grant_idGrantIDthe grant entry’s id

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 keyGo fieldNotes
receiptReceiptthe acceptance entry a later one settles; optional
statusStatusqueued, accepted, delivered, deferred, dropped
msgMsgthe message, on an acceptance; optional
run_idRunIDthe run that delivered a steer, or the run minted for a queued send; optional
turnTurnthe prompt entry id a queued send or deferred steer will take; optional
unansweredUnansweredon 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.

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 keyGo fieldNotes
receiptReceiptthe acceptance entry; empty on the acceptance itself
statusStatusaccepted, running, parked, done, failed, canceled, capped
childChildthe child session; optional on the wire, always set by the pool
callCallthe delegating tool call, for a wrapped delegation; optional
promptPromptthe task, on the acceptance; optional
stopStopon a settlement: the answer (done) or the cause; optional
usageUsageon a settlement: the child session’s whole cost; summed into Usage.Delegated; optional
  • 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": N on the entries carrying that field (the compaction’s trim record, 5).
  • What this build reads: the format-1 kinds at 1, compaction up to 5, the approval kinds at 2, receipt at 3, pool_receipt at 4.
  • Additive keys need no version. A new optional key an older reader loses nothing by ignoring is added without one.

An older reader never guesses (thread rule T5). This is what v0.20.2 does with lines a newer weft could write:

sessions/format.go
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)

sessions/format.go on GitHub

true thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1
true thread: session format newer than this build: entry kind "snapshot" is unknown to this build
true thread: session format newer than this build: session header has weft=2, this build reads 1
It meetsIt does
an unknown entry kindfails with ErrNewerFormat, Salvage or not
a known kind with "v" above what it readsfails with ErrNewerFormat, Salvage or not
a header envelope above FormatVersionfails Load with ErrNewerFormat; List does not show the session
an unknown key on a line it readsignores it
a malformed linethread.ErrCorrupt naming the line; skipped and reported under Salvage
a torn final linedrops 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.

The changes since format 1, from the CHANGELOG. The header envelope has been "weft": 1 throughout.

ReleaseWire change
thread 0.1.0the 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.0approval_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.0receipt, "v": 3
thread 0.5.0pool_receipt, "v": 4; the header’s lineage
thread 0.5.0approval_request: child, wrapper; mirrored call ids <child>/<call> (additive, no "v" change)
thread 0.9.0compaction with a trim record at "v": 5 (an older build fails on it on purpose; a summary compaction is unchanged)
thread 0.9.0message: run_id on a turn’s prompt entry
thread 0.9.0turn: policy, rerun, late_steps; canceled also set on a deadline
thread 0.9.0receipt: the status accepted with msg, turn, run_id; unanswered on a delivered receipt
thread 0.9.0pool_receipt: the status parked
thread 0.9.0approval_decision: request_id, always; via values interrupt, child, parent
thread 0.9.0approval_audit: grant_id, grant_shared, key_id, decisions; the step signed; the resume outcomes started, completed, failed
thread 0.9.0header metadata weft.require_signed ("true")
thread 0.9.0the 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.0thread/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.0grant 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.0TurnEntry.Policy, ReRun, LateSteps, MessageEntry.RunID, ReceiptEntry.Unanswered and thread.ReceiptAccepted added to the Go API
weft 0.18.0the 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).

sessions/format.go writes the session above and decodes newer data:

sessions/format.go
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 sessions/format.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./sessions format
go test ./sessions

The output is the session’s lines above, then:

-- a newer weft's data
true thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1
true thread: session format newer than this build: entry kind "snapshot" is unknown to this build
true thread: session format newer than this build: session header has weft=2, this build reads 1
  • 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 unknown type or 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 thread a module of its own (it is a package of github.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)

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