Durability
What zelk promises about a session log when a process crashes, stops or hands a session to another process, and how the log is stored. Every rule has an ID (E1, B3, …) that the tests covering it name, so a rule and its test can be found from each other.
The verification index links the stable rule anchors to their tests.
Loop states describes the session’s lifecycle as the reducer folds it, and which of these rules the reducer enforces and which rest on the driver.
Guarantees
Section titled “Guarantees”- Intent before action:
EffectStartedis appended before an effect is dispatched - Appends are atomic per batch, framed, checksummed and fsynced
- A torn tail is detected; only the writer truncates it. Corruption is reported, never truncated away
- An append is acknowledged only after it is durable; a failed write or
fsyncstops the writer instead of being retried or re-read - Blobs are written and synced before the event that refers to them
- Every started effect ends with exactly one terminal event, across crashes and restarts (E3)
- Every attempt is settled exactly once in the budget ledger (E4, B4)
- Recovering pending effects after a crash or stop (the per-kind recovery table)
- Cross-process leases with TTL, renewal, fencing and takeover; fences that survive restarts
- Timers with generations; the wake-up contract
- Budget ledger (tokens) and child allocations
- Command deduplication by caller-assigned
CommandIDacross restarts - Suspend and resume
- Gate hooks recorded as
HookDecided, never re-run by replay; approvals and session grants
1. Effects
Section titled “1. Effects”An effect is something the reducer (loop.Step) asks the driver to do: call the model, run a tool, and the other kinds the recovery table (R4) lists. Effects are plain data, and the reducer’s state lists every effect that hasn’t ended (State.Pending).
E1. Identity. An effect’s ID is deterministic from the session, the sequence number of the event whose fold asked for it, and its index among that fold’s effects (loop.EffectID), so folding a log again yields the same IDs. A child session’s ID derives from its parent effect’s ID, so effect IDs are unique across a session tree.
E2. Attempts. Each dispatch of an effect is an attempt, numbered from 1 and recorded by its own EffectStarted{effect_id, attempt}. Attempt n+1 may start only once attempt n is closed.
An effect is in one of four states, and an attempt in one of two:
| Effect state | Meaning |
|---|---|
pending |
asked for, never started |
running |
its latest attempt is open |
waiting |
a request effect (Q1) whose request is out: its one attempt is open, but nothing is in flight; it ends when its resolution is folded |
retryable |
its latest attempt is closed, and the effect hasn’t ended |
terminal |
it has ended; it is no longer in State.Pending |
| Event | Effect transition | Attempt transition |
|---|---|---|
EffectStarted{attempt: n} |
pending (n = 1) or retryable (n > 1) → running, or waiting for a request effect |
attempt n opens |
AttemptEnded{attempt: n, cause, charge} |
running → retryable |
attempt n closes |
EffectFinished{attempt: n} |
running → terminal |
attempt n closes |
EffectCancelled{attempt: n} / EffectReconciled{attempt: n} |
running → terminal, closing attempt n; or retryable → terminal, naming the last closed attempt and closing nothing |
— |
EffectFinished{attempt: 1} / EffectCancelled{attempt: 1} |
waiting → terminal |
the request’s attempt closes; requests reserve nothing, so it carries no charge |
AttemptEnded.cause is one of:
retry: the attempt failed in a way worth retrying (a provider error that isNotDispatched, transient or rate-limited), and the driver will try again.AttemptEnded.retry_atis the absolute time before which the next attempt mustn’t start, so a crash during the backoff neither skips nor restarts it (S4). TheWarning{provider_retry}the driver also records is for people;AttemptEndedis the record the reducer folds.lost: reconciliation found the attempt open after a crash or stop (recovery).deadline: reconciliation found the attempt open past its deadline, for an effect it may re-run (T8).
Only an effect R4 may re-run is ever made retryable by lost or deadline; any other open attempt is ended by EffectReconciled, so it never passes through a state the dispatch path would start again.
An effect never started, still pending, can be dropped by the reducer without any event when the run that asked for it ends (an interrupt, a budget stop): nothing was dispatched, so there is nothing to end.
loop.Pending.State reports an effect’s state. In the reducer each transition above has one function (core/loop/effect_state.go): ask makes an effect pending, openAttempt starts an attempt, closeAttempt makes it retryable, end makes it terminal, and drop removes one that never started.
E3. Terminal invariant. Every effect that started ends with exactly one terminal event: EffectFinished, EffectCancelled or EffectReconciled. It carries the model-visible result items and, if it closes an attempt, that attempt’s charge. Nothing ends an effect a second time: an event that would end a terminal effect, close a closed attempt, or start an attempt while one is open, is inconsistent (loop.ErrInconsistent), and the reducer refuses the log.
E4. Every attempt is charged exactly once. The event that closes an attempt (AttemptEnded, or the terminal event that closes it) carries the attempt’s charge in the budget ledger. An attempt closed by nothing yet, because the process died or stopped, keeps its reservation open until reconciliation closes it (R4). Effects that reserve nothing (RunTool) carry no charge.
E5. Error classes. Every port and tool error is classified, and the class decides what may happen next:
| Class | Outcome | Meaning | What may follow |
|---|---|---|---|
NotDispatched |
not_dispatched |
provably did nothing | a retry (AttemptEnded{retry}), or a failed result for the model |
Failed |
failed |
ran and definitely failed | the error goes to the model |
OutcomeUnknown |
unknown |
may have acted | never retried automatically (E6); the model is told to verify before trying again |
A plain Go error from a tool or port is unknown: zelk doesn’t guess that a failure was harmless. tool.Classify and provider.KindOf implement the mapping.
E6. Re-running. zelk re-runs a tool call only if running it again can’t do anything the first run didn’t:
- the tool is
ReadOnlyandIdempotent, and zelk trusts those claims (Trusted, built-in tools only); or - the tool declares an enforced idempotency key (
tool.WithEnforcedIdempotency(), recorded in the session’s tool spec). zelk then gives every attempt of the call the same key, the effect ID (tool.Call.IdempotencyKey()), and the tool guarantees that any number of runs with one key act at most once, for example by passing the key to a payment API that deduplicates by it.
Model calls (CallProvider) can always be re-issued: a lost call’s only side effect is the tokens it spent, which the ledger charges (B4).
E7. Late completions. A port that reports completion after its effect’s terminal event, such as an asynchronous tool whose callback arrives after a cancel, is recorded as Warning{late_completion} for audit. It folds to nothing, isn’t shown to the model, and never settles again. The built-in driver joins every goroutine it starts before recording an end, so it never produces one; external drivers and asynchronous ports can.
2. Budget ledger
Section titled “2. Budget ledger”The ledger accounts for model tokens across attempts, crashes and child sessions, so a budget holds even when the log can’t say exactly what a lost call used. It accounts for tokens; cost limits wait for a price table the host supplies.
B1. Dimensions. Usage is normalized by the adapters (event.Usage): input tokens that weren’t cached, cache reads and cache writes are disjoint, and output tokens include reasoning tokens (ReasoningTokens is the part of OutputTokens spent reasoning, never added again). The ledger tracks three dimensions:
- input =
InputTokens + CacheReadTokens + CacheWriteTokens - output =
OutputTokens - total = input + output
B2. Reservation. Before every attempt of an effect that calls a model (CallProvider, compaction calls included, and a tool that calls a model itself, such as WebFetch with an extractor), the driver reserves a conservative maximum and records it on that attempt’s EffectStarted as reservation{allocation_id, input, output}. allocation_id is <effect_id>#<attempt>, unique in the session. The reservation is fixed once recorded. The bounds come from the provider adapter, which renders the request and knows its wire format, and the capability snapshot records which kind of bound the adapter gives (Capabilities.InputBound):
- Output is the request’s maximum output tokens. An adapter whose provider doesn’t enforce a maximum can’t bound output, and the snapshot says so.
- Input, for an adapter that records the
bytesbound: the byte length of the request body exactly as rendered for the wire, which includes every text, schema transformation, raw payload sent back and all of the framing, plus the adapter’s documented allowance for text its provider adds on its own side (such as a tool-use preamble), capped at the context window W. This rests on a property of the tokenizers of the providers that adapter speaks, which the adapter documents and its transcript tests check against recorded usage: a text never takes more tokens than bytes. A request carrying anything but text (an image) reserves W. - Input, for any other adapter or model, such as an OpenAI-compatible server whose tokenizer zelk can’t know: W.
- A snapshot without a context window, or without an output bound, can’t be reserved for soundly:
zelk.Newrefuses hard limits for that model (zelk.ErrUnsupported), and reservations are then made for reporting only, from the bytes alone.
B3. Usage above the reservation. Measured usage above the reservation means the adapter’s bound was broken. A dimension reserved as zero is unknown, such as the output of the ChatGPT plan, which sends no output cap, and no usage exceeds it; a hard limit refuses models whose limits are unknown, so it never meets one. The measured usage is charged, a Warning{reservation_exceeded} records by how much, and if a hard limit is configured the run ends at once with max_budget, making no further call. A hard limit is therefore a guarantee for providers that keep the bounds their adapter records, and the overshoot of one call, reported, for any that doesn’t.
B4. Charges. Each attempt closes with exactly one charge (E4). Usage counts as reported only when the provider reported all of it: adapters say so explicitly (provider.Response.Usage is nil otherwise), so missing usage is never mistaken for zero. A charge has one of three bases:
| Basis | When | Charged |
|---|---|---|
measured |
the provider reported usage | the measured usage |
released |
the attempt provably wasn’t dispatched (not_dispatched) |
nothing |
reserved |
anything else: lost to a crash or stop, cut short by a cancel or deadline, failed without usage, or a response that arrived without usage | the whole reservation |
A reserved charge may carry an estimate (for a response without usage, its bytes by B2’s rule) for reporting; enforcement always uses the charge. A charge is recorded in the closing event, so the ledger is folded from the log and never recomputed from memory; folding the same log twice charges the same.
B5. Enforcement. Limits apply per run, like the turn limit: a run’s commitment in each dimension is the sum of the charges of its attempts plus every open reservation (attempts not yet closed, and child allocations not yet returned, B7), and a new run starts from zero. The fold also keeps session-wide totals, for reporting. Limits are configured per dimension (zelk.WithBudget), each hard or soft:
- Hard: a reservation that would take the commitment over the limit isn’t made. The model call isn’t dispatched, the run ends with outcome
max_budget, and its report says which limit stopped it. - Soft: once charges reach the limit, a
Warning{budget_soft_limit}is recorded and the run gets one wrap-up turn: the next model call carries a zelk-authored message asking the model to finish and summarize, its tool calls get “not run: the budget is spent” results, and the run then ends withmax_budget.
Hard limits always win over persistence, continuations and hooks.
Adapter bounds. A byte bound comes from the adapter’s exact renderer (driver.Reservation); the pure reducer cannot call that renderer. When that first reservation is refused, the driver records RunFinished{max_budget, refused: {allocation_id, input, output}} without starting an attempt. The fold verifies the refusal against the ledger, drops the unstarted effect, and retires its timers. The added refused field is necessary to replay an adapter-bound refusal without calling the adapter; a window-bound refusal can still be derived directly by the fold. This changes only the record carrying the refusal, not B2’s bound or B5’s limit.
B6. Reporting. Every RunFinished and zelk.Result reports usage from the ledger in four parts that add up to the commitment enforcement uses (B5), plus an annotation:
- measured: charges with basis
measured - unknown: charges with basis
reserved, at their reservation, which may overstate what was spent - reserved: open reservations, nonzero only in a result returned while attempts are still open (a stopped execution, X2)
- allocated: child allocations not yet returned (B7)
- estimated, an annotation that isn’t added in: the sum of the estimates that
reservedcharges carry, the best guess at what theunknownpart actually spent
B7. Child allocations. Subagents reserve their budget through the spawning call: the Task tool’s attempt reserves the child’s allocation (WithSubagentBudget), and the child’s usage settles with the call that reports it. The child records its allocation in its configuration and enforces it cumulatively over the child session’s whole life, across runs, as a hard limit independent of per-run limits (B5). Allocations don’t nest: a child never gets the Task tools, so it can’t start children of its own and a session tree is one level deep (a parent and its children).
ChildStarted and ChildFinished link the logs: the call that starts a child records ChildStarted{child_session, parent_effect, call_id, agent_type, background} with its result, its allocation being the attempt’s own reservation, and the call that learns how the child ended (the waiting Task, or TaskOutput, TaskStop or a resume) records ChildFinished{child_session, outcome, used}. The fold checks the link against the running call and counts nothing twice. Only the parent session’s lease holder writes its log. Runtime settlement of an uncollected child’s usage is described in background work.
3. Driver contract
Section titled “3. Driver contract”A driver runs the effects the reducer asks for and records them. zelk’s own (driver.Driver) is one; a host can write its own from the public pieces (C8) and get the same guarantees by following these rules.
C1. One writer. Only the session’s lease holder appends to its log (leases), and only through a driver. The events a driver appends are SessionStarted, CommandAccepted, EffectStarted, the record groups that end attempts (C4), TimerSet, TimerFired, ChildStarted, ChildFinished, Warning and RunFinished.
C2. The log decides. A driver decides what to do next only from the state folded from the log, its own appends included. After every append it folds what it appended; an appended event that doesn’t fold means the driver recorded something the reducer never asked for, and it stops.
C3. Dispatch protocol. For each attempt:
- Check authority (L5).
- Append the intent:
EffectStarted{effect_id, attempt, effect, deadline, reservation}, for all the attempts the step starts together in one batch (a wave of tool calls, or a step’s gate hooks once hooks exist). - Check authority again immediately before dispatching each attempt, including an attempt that waited for a free tool slot. A tool call’s intent exists only once its gates have allowed it (H1), so nothing else stands between intent and dispatch. If authority has ended, the attempt isn’t dispatched; its intent stays open, and the next holder reconciles it (R4), charging its reservation since the log can’t show it wasn’t dispatched.
- Dispatch, passing the lease’s fencing token and, for keyed tools, the idempotency key (E6).
- Append the attempt’s record group (C4).
C4. Record groups. What an attempt observed (FileObserved, CwdChanged, its Warnings) and the event that closes it (AttemptEnded or a terminal event) are one record group, appended in one batch and never split, so an observation is durable exactly when the result that relies on it is (O1). Each call’s group is appended as soon as the call ends, in the order the calls end, so a crash while a slow call runs loses none of the calls that ended beside it; the reducer places each result by its call, so the order doesn’t matter to it. The groups a cancelled wave leaves are appended together, in call order, in as few batches as fit the batch limit (store.MaxBatchBytes, or less if the host sets it). A crash can leave any subset of a wave’s ends committed and the rest open. An append that fails stops the recording but not the calls already running, which end as they would have. A wave whose intents don’t fit one batch runs in parts. A group too large for any batch has only its closing event shrunk (a result becomes a failed call that says so; a cancellation keeps its reason’s start); its observations are never dropped, and if they alone don’t fit, the driver stops with an error, leaving the attempt open.
C5. Append errors.
- Ambiguous (
store.ErrAmbiguous, only from stores whose reads stay authoritative): read the log fromexpectSeq+1and compare encodings with the batch. The same events mean it landed, and a log that implementsdriver.LandedObserveris told, with the seq of the batch’s last event, so whatever it tells readers of successful appends it tells them of this one (the core’s subscribers, and with them the wake of a background child, wait on exactly that); nothing means it didn’t, and the batch is appended again, up to three tries in all; anything else isstore.ErrConflict. The read-back is bounded byRecordTimeoutand by authority: if authority ends while resolving, the driver stops, and the next holder learns the outcome by folding. - Conflict or fenced (
store.ErrConflict,store.ErrFenced): another writer has the log. Stop. - Anything else, a failed
fsyncincluded: stop without dispatching anything further. The outcome is never resolved by reading the log, since after a failedfsyncreading can’t establish durability (see the file store’s write protocol below).
C6. Ends after a cancel. The record group of an attempt already dispatched is appended even once the run’s context is done (a stop or an interrupt), under a context of its own bounded by RecordTimeout, so finished work is never lost. Nothing is appended once authority has ended.
C7. Replay. Replay folds a log with effects suppressed. It never dispatches, reads the workspace, consults the clock or calls a port: everything a fold needs is in the log.
C8. The public pieces. driver.Acquire takes the lease and supervises it (L3, L4); driver.CallProvider and driver.RunTool run one attempt (steps 4–5) and return its complete record group; driver.Append appends a batch with C5’s rules; loop.Step folds and loop.Recover plans reconciliation (recovery). A driver built from them that follows C1–C7 has the guarantees of this document. examples/external-driver is one.
4. Leases and stores
Section titled “4. Leases and stores”A lease gives one driver at a time the right to write a session. zelk ships lease.Local, for drivers within one process, and lease/file, for processes on one machine; hosts bring others. Every implementation passes lease/leasetest.
L1. Grants and fences. Acquire(ctx, session) returns a Grant{Token{Session, Fence}, TTL} or ErrHeld; Renew(ctx, token) returns a fresh grant or ErrLost; Release(ctx, token) gives the lease up, or returns ErrLost. Every grant to a new holder gets a fence greater than every fence the session has had, including across restarts of the lease’s backing state, so comparing fences tells the current holder from every earlier one.
L2. Expiry and takeover. A grant expires TTL after the lease recorded it. While it is unexpired, Acquire by anyone else returns ErrHeld; once it has expired, Acquire grants a new holder a higher fence, and the old token’s Renew and Release return ErrLost. A lease is never taken from an unexpired holder.
L3. The holder’s deadline. A holder never relies on the lease’s clock. It reads its own clocks just before it sends Acquire or Renew, and its authority deadline is that time plus the grant’s TTL minus a safety margin, on both clocks: the monotonic clock, which no one sets, and the wall clock, which keeps running while the machine sleeps and the monotonic clock stops. Authority ends when either clock passes its deadline. Since the request left before the lease recorded the grant, the holder’s deadline falls before the lease’s expiry whenever the two clocks run at the same rate. So the clock must be read by whoever sends the request: driver.Acquire(ctx, lease, session) sends it and supervises the result, rather than taking a grant obtained elsewhere. A grant that arrives after the deadline it would set is released at once and authority is never granted. Authority only ever moves forward: a renewal sets a later deadline, and a renewal that returns after authority has ended doesn’t revive it.
L4. Supervision. Authority is supervised from the moment the lease is acquired, so it covers the configuration, replay and command appends that come before any effect. The supervisor renews at a third of the TTL, bounding each Renew by the time left, and a watchdog ends authority at the deadline whether or not a renewal has returned. Once ended, authority is final for that execution. When authority ends, by ErrLost or by the watchdog:
- no further append or dispatch starts;
- in-flight attempts are cancelled with the cause
driver.ErrLeaseLostand joined; their record groups are not appended, so the next holder reconciles them; - the execution returns
ErrLeaseLost.
L5. Checks. Authority.Check() reports whether the deadline is still ahead. A driver calls it before appending an intent and again right before each dispatch (C3).
L6. Release. When an execution ends, it releases its lease, even once its context is done, for at most 30 seconds. A release that fails is reported alongside any other error; the lease then expires on its own.
L7. Clocks. lease/file stores expiry as wall-clock time and compares it across processes on one machine. A backward jump of the wall clock only delays takeover. A forward jump, or a sleep (a suspended laptop or WSL VM) during which the wall clock runs on and the monotonic clock stops, lets a new holder take over as soon as the wall clock passes the recorded expiry. The old holder’s wall-clock deadline (L3) has passed by then too, so its next Check ends authority and no new append or dispatch starts. The watchdog’s timer stops with the monotonic clock during a sleep, so it looks at the wall clock at least once a second (or every margin, if shorter); after waking, attempts already in flight are cancelled within that second, and an effect such an attempt is in the middle of may overlap the new holder’s for that long. The store’s fence (L8) still refuses the old holder’s appends. Hosts that can’t accept that window use a lease backed by a single clock, such as a database’s.
L8. Fencing. Every Append carries the writer’s token. A store refuses, with store.ErrFenced, a token for another session and a token whose fence is older than the newest it has accepted for the session. The newest fence is durable: the store records it, durably, before it acknowledges the first append that uses it, so a restart never forgets it and an old holder stays refused. Fencing protects the log. It protects external side effects only through ports that check the token themselves (tool.Call.Token()).
L9. Writer locks. A store may add its own guard against two writers. The file store’s writer lock is an exclusive file lock taken for each append and released after the batch is synced, so an old holder that is alive but idle never blocks a new one; the fence decides who may write. Since another store may have written while the lock was free, everything a store remembers about a log (its end offset, last sequence number and newest fence) is refreshed under the lock, from the file and the fence file, before the append’s expectSeq and fence are checked. After an append whose durability is uncertain, the store keeps the lock until the process exits, as its write protocol below describes.
L10. File store fences. The file store keeps a session’s newest fence in <log>.fence: the fence as 8 bytes, little-endian, and their CRC-32C. Under the writer lock, an append (or an adoption, L11) with a fence newer than the file’s first writes the new fence to a temporary file, syncs it, renames it over <log>.fence and syncs the directory, and only then goes on. If any of those steps fails, the fence’s durability is unknown, and the session breaks exactly as after a failed fsync of the log: the append fails, the store keeps the lock and writes the broken marker, and no append is acknowledged with that fence. A missing fence file means no fence has been accepted yet; a damaged one is an error, never treated as zero. A crash between the fence and the append leaves a newer fence with no events from its holder, which only refuses older holders, as it should.
L11. Adopting a log. A new holder must not decide anything from data that may not be durable: another store’s reader can see a batch whose fsync is still pending or has failed (see the file store’s write protocol). So before folding, a driver adopts the log: LogStore.Adopt(ctx, session, token) makes everything the log holds durable, records the token’s fence (L8), and returns the last sequence number, and the driver folds only up to it. The file store adopts under the writer lock: it checks the broken marker, repairs a torn tail, syncs the log file and its directory, and persists the fence (L10); a failure in any step breaks the session, as above. The lock is held from write to sync by every append, so adoption sees either a whole synced batch or none, except from a writer that died between write and sync, whose batch the adopting sync makes durable. Stores whose reads are authoritative (mem, a database) adopt by recording the fence.
What adoption can’t settle. Adoption trusts that syncing the log makes what it holds durable. That fails in one situation: a write the kernel couldn’t write back, whose writer died before a broken marker existed. The writer may die after its sync reported the error but before writing the marker, or after a background write-back failed but before its own sync ran, or the marker write may itself fail. No second storage failure is needed. The page cache can then still show the failed batch, and on Linux a failed write-back can leave its pages marked clean, so the adopting sync reports success without writing them; the error itself isn’t durable (Linux reports it only to descriptors open when it happened, and macOS keeps no history of it at all). So the file store states it as outside the failure model (see Scope of the guarantees) rather than build a second commit protocol. The sound fix is known and bounded: a write-ahead pending marker, recording the pre-append offset, synced before each append and cleared after its sync, so adoption finds the one uncertain batch and rewrites it, at most store.MaxBatchBytes, instead of trusting the cache. It costs extra syncs on every append and gets its own specification and fault matrix if a host needs it. Until then, a host that can’t accept the window uses a store whose reads stay authoritative after a failure.
L12. The file lease. lease/file keeps, per session, a lock file <session>.lock, created once and never replaced or removed, and a data file <session>.lease holding the newest fence, whether it is held, and its expiry time, with a CRC-32C. (The fence alone identifies the holder: every grant has its own.) Every operation takes the lock file’s lock, reads the data file, decides, and, if anything changed, writes the new data to a temporary file, syncs it, renames it over <session>.lease and syncs the directory, before it releases the lock and answers. Locking a file that is never replaced keeps every process on one file, so no two can be in the critical section at once. A missing data file means the session has never been leased; a damaged one, or a failure to persist, fails the operation and grants nothing, and a fence is never reset to recover. Renew and Release succeed only for the holder whose fence matches and whose grant hasn’t expired.
5. Recovery
Section titled “5. Recovery”Recovery is what a driver does with a log another driver left: after a crash, a stop (S1), a lost lease or a takeover. It needs no record of why the last driver went away; the fold says what is open.
Records-mode StructuredOutput calls are serialized so their numbers come from the preceding durable record. A run continues at most twice after a model turn the output limit cut off without a tool call; the folded state keeps the count. Stale evidence sends a run back to the model for a fresh check, whether or not the host requires verification.
R1. Order at Start.
- Acquire the lease and start supervising it (L4).
- Adopt the log (L11) and fold it up to the adopted end.
- Check compatibility (R2).
- Append the commands given to
Start, in order (K4). - Fire overdue timers (T7).
- Reconcile (R3, R4, R5).
- Continue the run. Nothing is dispatched before reconciliation is complete.
So an answer or interrupt delivered at Start wins over a deadline that passed while nobody ran, and both are in the log before reconciliation decides anything.
R2. Compatibility. A driver refuses a log, with driver.ErrIncompatible and before appending anything, when:
- the log’s format generation differs from the current one: an earlier one with
event.ErrFormatBreak, a later one withloop.ErrNewerLog. Nothing migrates a log of another generation; - the session’s provider family isn’t the driver’s provider’s;
- a tool the session’s configuration records is missing (
ErrMissingTool), or differs in its properties, its idempotency key, or its canonical input schema (ErrToolChanged). A different description is allowed, the tool’s or any of its fields’ (the schema’sdescriptionkeywords): the model saw the recorded one, and the recorded one is what the session keeps sending. A property nameddescriptionis structure, and counts.
R3. Termination first. If the fold shows the run ending, because an Interrupt was accepted (S2) or a terminal timer fired (T4), but not every effect has ended, reconciliation finishes that ending and re-dispatches nothing: each running, retryable or waiting effect gets EffectCancelled with the ending’s reason (an open attempt charged reserved), each pending one is dropped, every tool call of the turn without a result gets one, and the run’s RunFinished follows. Retrying anything the user or a deadline has already stopped would undo their decision.
R4. Per-kind resolution. Otherwise, each effect with an open attempt is resolved by its kind. An attempt open past its deadline (T8) is resolved the same way, with cause deadline instead of lost:
| Effect | Resolution | Appended |
|---|---|---|
CallProvider |
retry | AttemptEnded{lost, reserved}; the normal dispatch path then starts the next attempt with a new reservation |
RunTool, trusted ReadOnly && Idempotent |
retry | AttemptEnded{lost}; re-run, and what it observes is recorded afresh (O3) |
RunTool with an enforced idempotency key |
retry | AttemptEnded{lost}; re-run with the same key (E6) |
RunTool, any other |
unknown | EffectReconciled{outcome: unknown} with the result “Outcome unknown: the session stopped while this call ran. Verify the state it would have changed before retrying.” |
SetTimer |
finish | never left open by a driver that follows T3; one left open is finished (EffectFinished{done}), since the timer is live from the fold that asked for it (T2) |
RunHook |
retry | re-invoke with the same invocation ID; hooks are idempotent per invocation ID. The gated tool call has no intent yet and waits for the decision (H1). Async hooks are best-effort and never re-run |
ClassifyAction |
retry | re-classify with the same action digest |
AwaitInput, an approval |
re-deliver | nothing: the effect is waiting (Q1), not lost. The request is delivered to the host again with the same approval_id; a decision already folded ends it (Q1) |
AwaitInput, a question or plan exit |
re-deliver | as an approval, with the same request ID |
RunTool that starts a subagent (Task) |
retry | the child’s session ID derives from the call: reopen the child if its log exists, create it otherwise |
CallProvider for a compaction |
retry | re-run; the result applies only if its replaces still matches the history |
Only a RunTool is ever reconciled: every other kind is retried, and loop.Step refuses an EffectReconciled for one as inconsistent (I16), so a host’s own driver can’t turn a retry into a failed run.
An effect already retryable needs nothing: the normal dispatch path starts its next attempt once its retry_at has passed (waiting only for what remains of the backoff), which makes the dispatch path the only place attempt numbers are assigned. A retry’s next attempt is reserved like any other (B2); if a hard limit refuses it, the run ends with max_budget and the effect is ended with EffectCancelled.
R5. Bounded batches, repeatable. Reconciliation’s events are appended before anything is dispatched, in as few batches as fit the batch limit, each batch made of whole resolutions (an effect’s closing event with its result items), never splitting one. After each batch the driver folds it and computes the remaining plan again from the fold alone (loop.Recover, pure), so a crash between batches, or during one, leaves a log from which the next recovery computes the rest of the same plan. Reconciling a log that needs nothing appends nothing.
R6. Processes of a dead holder. A crashed holder’s Bash commands may still be running. Their calls reconcile as unknown (R4), and the result tells the model to check what they did. Background processes are recovered only through an environment that implements ProcessReconciler and keeps their identity and I/O; a local environment can’t, so its lost commands are surfaced for inspection, never restarted (background work).
6. Stop, interrupt, detach and retry
Section titled “6. Stop, interrupt, detach and retry”Four ways an execution can be cut short, kept apart:
S1. Stop. Cancelling Start’s context, Execution.Cancel and Agent.Close stop the execution. It means “this process is going away”, not “the user wants the run to end”:
- nothing new is dispatched;
- in-flight attempts are told through their context;
- each attempt that then ends with outcome
donehas its record group appended (C6): finished work is never lost; - every other in-flight attempt is left open, with its reservation open, and is reconciled by the next
Start(R4); - no
RunFinishedis appended: the run is still in progress, and the nextStartcontinues it.
A stop is therefore a crash that loses no finished work. Wait returns the stopped snapshot (X2) with context.Canceled.
S2. Interrupt. The user’s interrupt is a command, Interrupt{reason} (Execution.Interrupt, or the CLI’s first Ctrl-C), accepted like any other (commands). Once it is folded nothing new starts. In-flight attempts are cancelled with the interrupt as the cause, and each ends with EffectCancelled (or EffectFinished, if it finished anyway); effects that are retryable (between attempts, during a backoff) end with EffectCancelled too, closing no attempt and charging nothing more; waiting effects end with EffectCancelled, closing their request’s attempt, which carries no charge; pending effects are dropped; every tool call without a result gets “cancelled by the user”; and the run ends with RunFinished{interrupted}. An interrupt accepted while no run is in progress changes nothing.
S3. Detach. A subscriber that goes away, or a client that disconnects, cancels nothing.
S4. Retry. Only model calls are retried automatically, and only for errors that are NotDispatched, transient or rate-limited: the attempt closes with AttemptEnded{retry, retry_at} and its charge, a Warning says why, and the next attempt starts once retry_at has passed. retry_at is the closing event’s time plus a deterministic backoff, plus any jitter the driver adds, so the wait is in the log and a recovered driver waits only what remains. A tool error is never retried by zelk; the model sees the result and decides.
7. Commands
Section titled “7. Commands”K1. IDs. Every command carries a CommandID the caller assigns: 1 to 128 bytes of valid UTF-8 without control characters. A command given without one gets a random ID, except a source occurrence, whose canonical kind/source/range ID is assigned automatically and may use up to 147 bytes. A caller that may deliver a command twice, for example after its own crash, gives it a stable ID.
K2. Acceptance. A command takes effect only once its CommandAccepted is folded. Commands the reducer couldn’t fold are refused before anything is appended.
K3. Deduplication. The fold keeps every accepted command’s ID with the SHA-256 digest of its payload as the event codec encodes it (event.Encode of the Command, which is deterministic for a given command). Before appending, a driver checks each command against the log and against earlier commands of the same batch:
- the same ID with the same content isn’t appended again; it is acknowledged with the original’s sequence number, marked as a duplicate;
- the same ID with different content is refused with
ErrCommandConflict, and nothing of that batch is appended.
A log holding two acceptances of one ID is inconsistent.
K4. Order. Commands are appended in the order they were given or received, each batch between appends of effects, never inside a record group. Start’s commands come before overdue timers and reconciliation (R1).
K5. Send. Execution.Send takes its own copy of the command and validates it before admitting it, so a caller changing its value afterwards changes nothing. It never blocks: it admits the command to a bounded queue and returns an Ack, or refuses it at once with ErrOverloaded (queue full) or ErrStopped (the execution is ending). Admission and the execution’s end are serialized, so a command is either refused or admitted before the end, never lost between. Every admitted command’s Ack resolves exactly once: with its acceptance (sequence number, and whether it was a duplicate), or with the error that kept it out of the log: stopped before it was appended, lease lost, a conflict, or a failed append. After a failed append the command may or may not be in the log; sending it again with the same ID is always safe.
K6. Waiting. Ack.Wait(ctx) waits for the resolution. Cancelling that wait stops the waiting, not the command.
K7. Policy changes. A session records its permission policy in SessionStarted: the mode, the modes a SetPermissionMode command may select, and an optional tool ceiling. A mode the policy doesn’t authorize, or that this reducer can’t enforce, is refused before it is appended (K2). An accepted change waits until no tool call is running, then applies in acceptance order and increments the policy revision; calls not yet decided are decided under the new mode, so no call is decided under one mode and run under another. Authorization is a pure function of the folded log: replay after any crash refuses exactly the calls it refused before, and a refused call never has an EffectStarted.
8. Timers and deadlines
Section titled “8. Timers and deadlines”T1. Identity. A timer has an ID, deterministic from the event that set it up, and a generation. Only the live generation of an ID can fire.
T2. Anchoring. Every deadline is absolute and derives from a persisted event: the originating event plus a duration recorded in the session’s configuration. The wall-time budget’s originating event is the event that started the run (X1). The reducer computes the deadline when it folds the originating event, from that event’s time, and the timer is live from that fold on, whether or not its registration (T3) has been recorded yet: no clock is read, a crash before registration reconstructs the same deadline, NextWake sees it, and it fires at Start if overdue. Time the session spent crashed counts, since the deadline doesn’t move.
T3. Registration. The reducer also asks for each timer with a SetTimer effect, so the log states every deadline plainly. Arming a timer in memory has no outside effect, so the driver records it whole, in one batch: EffectStarted, TimerSet{id, generation, deadline} and EffectFinished. A SetTimer is never left open, a TimerSet whose deadline isn’t the one the reducer computed is inconsistent, and a SetTimer still pending when its timer fires or retires is dropped.
T4. Firing. When a live timer’s deadline passes on the driver’s clock, the driver appends TimerFired{id, generation}, and the fold applies the consequence. The wall-time budget’s is termination: the run ends with max_budget, its in-flight attempts are cancelled with the timer as the cause, and they end as S2 describes, with the timer’s reason. The firing is appended before anything is cancelled, so a crash in between leaves a termination intent that reconciliation completes (R3).
T5. Retirement and stale firings. A timer is retired when what it guards ends: the run’s end retires its wall-time timer. Retiring is part of the fold and needs no event. A TimerFired for a retired timer or an old generation folds to nothing.
T6. Races. Completion and timeout race only in the log: whichever is folded first decides, and a firing folded after the run ended is stale.
T7. Overdue timers at Start. After Start’s commands are appended and before reconciliation, every live timer whose deadline has passed fires, in order of deadline and then ID.
T8. Effect deadlines. An attempt’s deadline (EffectStarted.deadline, from zelk.WithCallTimeout and zelk.WithToolTimeout) is absolute, set by the driver from the intent’s time, and passed to the port as its context’s deadline; how the attempt ends is classified as for any error (E5). An attempt found open at recovery after its deadline is resolved by R4 with cause deadline: an effect R4 may re-run gets AttemptEnded{deadline} and its next attempt; any other gets EffectReconciled, as if lost.
T9. Wake-up contract. zelk doesn’t schedule processes. zelk.NextWake(ctx, store, session) returns the session’s earliest live deadline, folded from its log, so a host that wants timeouts to fire on time calls Start by then. Suspended{wake_at} records the same value, and wall-time budgets exclude time spent suspended (configurable) by re-anchoring their timers, in a new generation, when a suspended session resumes.
9. Results
Section titled “9. Results”X1. Runs and results. A run starts at the event whose fold asks for its first model call: a CommandAccepted that arrives while the session is idle, or the RunFinished of the previous run when user messages were queued during it. Its sequence number is the run’s ID, which a RunStarted record names right after that event, and which the run’s ReportRecorded, RunFinished and decision records carry; its time anchors the run’s wall-time budget (so time a queued message spent waiting for the previous run doesn’t count), and every attempt the run starts is charged to it (B5). An execution’s Result describes the last run it drove, folded from the log: the outcome, the four-part usage (B6), the turns and the final text, meaning the last assistant message of the run if it ended the model’s turn. Since a run is identified by its starting event, not by the execution, a run recovered by a later Start reports its whole text and usage.
X2. Stopped. A stopped execution (S1), or one whose lease was lost (L4), returns a snapshot of the run in progress: Stopped set, no outcome, usage so far, open reservations included. Its error is context.Canceled or ErrLeaseLost.
X3. Not persisted. If the store fails at any recording boundary, Wait returns the result folded from the durable log with ErrNotPersisted. What the execution learned but couldn’t record, such as the measured usage of a call whose end failed to append, is reported beside it as Result.Unpersisted, marked as such; the durable ledger settles that attempt only when recovery closes it.
10. Hooks, control requests and suspension
Section titled “10. Hooks, control requests and suspension”H1. Hooks. Each hook invocation is a RunHook effect whose effect ID is its invocation ID, passed to the hook so a host can deduplicate side effects. A step’s gate hooks (PreToolUse and the like) are started together, in one batch, and each one’s decision is recorded as HookDecided{hook, event, decision} in its record group, so replay and resume use the recorded decision and never run the hook again. The tool call’s own intent is appended only after every gate’s decision is folded, in a later batch, so a tool intent in the log always means its gates allowed it; a crash before the decisions are in leaves no tool intent to reconcile, and recovery re-invokes the undecided gates with their invocation IDs (R4) before the tool can start. The combined decision (hooks) leads to:
allow: the tool call’s intent and dispatch, as usual;deny: no intent at all; the call’s result is the denial, derived by the fold from the recorded decisions;askordefer: anAwaitApprovallinked to the call (Q1), whichdeferadditionally lets suspend (P1). An approval resolved as allowed leads to the tool’s intent; denied or expired, to a denial result, again without an intent;- a gate that times out is recorded as a decision that fails closed.
Async hooks are not effects: they are best-effort, never recorded as intents, and never re-run.
As implemented: sessions record their gate hooks (Config.Hooks: name, event, matcher, timeout) in registration order. A run_hook effect’s intent carries the hook’s name and its full input, and its deadline is its recorded timeout. The driver appends each invocation’s HookDecided immediately before its EffectFinished, in one batch for all of a gate’s hooks; the fold refuses a HookDecided for anything but a running, undecided invocation, and an end without one. An open invocation found at recovery is closed lost and re-invoked with the same ID (it is always safe to re-run: the host deduplicates by the ID). A hook that errors, panics, times out or isn’t registered in the resuming process is recorded with error or timed_out, and its gate fails closed. The fault matrix covers PreToolUse and PostToolUse gates and approvals at every append boundary.
Q1. Control requests. AwaitApproval and AwaitInput are effects whose effect ID is the request ID (approval_id for approvals). As implemented, an approval is an AwaitInput of kind approval and its ApprovalDecision is an AnswerInput whose approval arm carries a decision and the action digest (AnswerInput is a tagged union of questions, plan and approval, or a denied answer with none), so approvals share every rule below with questions; a session grant’s PolicyAmended is a derived record appended in the same group as the answer. Their EffectStarted, with the request event (ApprovalRequested, QuestionAsked) in the same batch, puts them in the waiting state (E2): the request is out and nothing is in flight, so a crash, stop or suspension doesn’t lose it, and recovery only delivers it to the host again. Answers arrive as commands (ApprovalDecision, AnswerQuestion) naming the request ID, deduplicated by command ID (K3). A request’s expiry is a timer anchored on its EffectStarted (T2). The first of its answer or its expiry to be folded latches the request’s resolution in the state, for good: a later answer, or a firing after an answer, is accepted and folds to a Warning, changing nothing. Once a resolution is latched, the driver appends the request’s terminal event: EffectFinished with the answer’s items, or EffectFinished{failed} with an “expired” result. A crash between the latch and that event loses nothing: recovery appends the terminal event for the latched resolution, whatever was delivered at Start since.
P1. Suspension. An execution waiting on the outside world (an approval, a question, a hook returning defer) may suspend instead of holding a goroutine:
- Quiescence: in-flight foreground attempts finish or are cancelled (S2 rules).
- The driver appends
Suspended{pending_requests, wake_at}and returns. - The Agent cleans up execution-owned background work before releasing the lease. It requests interruption of the execution’s children and joins them. A child that can’t accept the interrupt is cancelled and its run may remain open for recovery. The Agent records the child endings it can establish. Conversation-lifetime children stay with the Agent and a child’s own suspension is reported through P3.
- The Agent then closes execution-owned processes as at any end of an execution (background). A reader may briefly see a suspended session whose background work is still running. The Agent records closed processes as
ProcessEnded{killed}while it still has authority (L4). Conversation and persistent processes keep their output cursors and ownership. With aProcessReconciler, the Agent detaches execution-owned processes and the log keeps theirProcessStartedrecords for lookup. A laterProcessOutputcan record their ends orProcessListthat they are lost. Background checks are still closed because the Agent cannot look them up later. - The Agent releases the lease.
WaitreturnsErrSuspendedalongside any cleanup or release errors.
The request effects stay waiting while suspended; they aren’t lost attempts, and resuming delivers them again with the same IDs (R4).
As implemented: a request’s EffectStarted carries the request (AwaitInput: the questions or the plan) and anchors its expiry timer. A session that can’t ask (InputPolicy deny) never starts one: the fold answers the call itself. Under the callback policy the driver asks the host’s callback and records the answer, or a fail-closed denial (denied, with its reason) for an error, a panic or the expiry, as AnswerInput command input:<request>. Under the suspend policy it records Suspended{requests, wake_at} and returns ErrSuspended; the next execution records Resumed before anything else. The fold keeps settled request IDs, so a later answer is accepted and changes nothing.
P2. Resume. Answers are delivered through Start (zelk.WithCommands), which follows R1: commands first, then overdue timers, then reconciliation. An answer given at resume therefore wins over a deadline that passed while the session was suspended.
P3. Trees. A child’s questions and approvals reach the host through its parent; a session tree is a parent and its children, one level deep (B7). A request records only the session that holds it, and no request carries an owner or a chain of links: the parent’s log records its children (ChildStarted, B7), and that record is the only routing state.
- Suspend policy: a child that needs an answer suspends, and the
TaskorTaskOutputcall that was waiting for it returns a report with outcomesuspendedand the child’s request IDs, without recording the child as finished. The parent’s model relays the questions to the user (AskUserQuestion), and that request, the parent’s own, is what suspends the root. The host answers the root’s request throughStart(P2), and the resumed parent passes the answers down withTaskOutput{agent_id, answers}. That call starts the child’s session and delivers each answer as a command markedrelayed, which the child’s reviewer reads as the parent model’s words, not the user’s, beside what the user has said. Its ID derives from the calling effect, so a re-run call answers once;TaskOutputrefuses an agent ID the parent’s log doesn’t record as its own. - Callback policy: the host’s callback is asked live, whichever session needs the answer;
InputRequest.Sessionnames it, so a host can tell a child’s request from its parent’s.
A child is started and resumed by the parent’s calls, which run while the parent’s execution holds its lease, and the child’s Start acquires the child’s own. So a child’s lease is taken while its parent’s is held. That is a consequence of who starts whom, not a rule the code enforces: no code orders the two. Request expiry deadlines keep their absolute times; active-time budgets are re-anchored on resume (T9).
11. Observations
Section titled “11. Observations”An observation is anything a session learns from outside its log: a file’s revision, the working directory, project instructions, skills and capabilities.
O1. Durable with the result. An observation is gathered while its attempt runs and appended in that attempt’s record group (C4), so it is durable exactly when the result that relies on it is, and before any later effect can use it.
O2. Replay reads nothing. The fold rebuilds what a session knows (State.Files, State.Cwd) from its observations. Replay never reads the workspace to learn them again (C7).
O3. Fresh on re-run. An attempt lost to a crash appended no observations. A re-run (R4) records what it observes then, so the log never claims a file was read at a revision nobody read.
O4. Kinds. Sessions record FileObserved, CwdChanged, InstructionsLoaded (a project instruction file’s load, reload, omission or removal, per directory), TodosUpdated (the task list), SkillLoaded (a skill’s content-addressed bundle manifest) and ProcessStarted/ProcessEnded (background processes by handle and generation-bearing process ID), each recorded in its call’s record group; the skill index and the top directory’s instructions are part of the resolved configuration. A record repeating the current revision changes nothing, so parallel calls may record the same file. Content too large for the log goes to a blob written before the event. The resolved configuration a session runs with is recorded in SessionStarted and ConfigChanged, never re-resolved on replay.
Model changes record resolved settings and capabilities in CommandAccepted
with CommandSetModel. The fold retains them in acceptance order and updates
the model portion of configuration only after effects and tool results close.
Cross-family changes additionally wait for RunFinished, before queued user
messages start another run. The accepted command is the durable input to this
derived transition; replay never queries capabilities. Host wiring resolves the
recorded provider for dispatch, and incompatible wiring fails before dispatch.
A tool that calls a model itself (WebFetch with an extractor) declares a reservation in its recorded descriptor. Each call reserves it when its intent is recorded, runs alone so reservations are checked one at a time, and is refused with an error result when a hard limit can’t cover it (B2). What the call reports spending is settled like a model call’s (B4).
A compaction call (compaction) is a CallProvider effect whose spec carries
Compact{cut, native, reactive}: its reservation, retries, recovery (R4:
re-issued as a new attempt) and ledger settlement are those of every model call.
Its EffectFinished holds the summary and, for a native compaction, the
provider’s window (native); the fold replaces the history before cut only
then, so a crash before it leaves the history as it was. A model call refused as
too long records error_kind: context_overflow, from which the fold compacts.
Every other classified failure records its class too (transient,
rate_limited, invalid_request, auth, quota, unsupported,
malformed). The RunFinished of a run such a failure ended repeats it, so a
host explains the ending and the recovery that fits (present.End) from the
log rather than from the error’s text. The model learns it
too: when a run that didn’t succeed ends, the next run’s first request carries
a harness note giving the outcome and recorded cause. Without the note, a run
a failed model call ended would leave nothing in the history, and a model
asked why it stopped could only guess.
CommandInvokeSkill records a skill the user invoked, resolved by the host
like a model change: the skill’s manifest (SkillLoaded) and the rendered text
the model receives. Its blobs are stored before the command is sent. The fold
treats the text as a queued user message and activates the skill when that
message joins the history; replay reads no skill.
CommandInjectContext records additions to dynamic host context. It changes
subsequent requests without starting a run or changing the static system prefix.
The fold copies configuration before the update; an in-flight call keeps its
original request snapshot. Resends deduplicate by command ID under K3.
CommandHostNotice records the host’s word of something outside
the conversation, such as a command the user ran that failed. The fold holds it
as a harness note for the model’s next call, framed as not the user’s word; it
starts no run and isn’t pending work, so an idle session stays idle.
Event encoding
Section titled “Event encoding”Each event is a JSON envelope carrying its payload’s kind and the log’s format generation (see event/README.md):
{"seq":1,"time":"2026-10-15T09:00:00Z","kind":"warning","v":108,"payload":{"code":"c"}}- zelk reads only its own generation,
event.Generation. An envelope of an earlier one is refused withevent.ErrFormatBreakbefore its payload is read, and nothing is upcast; one of a later generation is refused as unsupported. - An unknown kind in an envelope of the current generation is kept, and
event.Encodewrites it back byte for byte. - The wire format of every kind is pinned by
event/testdata/payloads.golden.jsonl.
File store record format
Section titled “File store record format”Sync. Wherever this document says a file or directory is synced or fsynced, the store calls Go’s (*os.File).Sync: fsync on Linux, and on macOS fcntl(F_FULLFSYNC), which also flushes the drive’s cache (plain fsync there doesn’t survive a power loss), falling back to fsync only on filesystems that don’t support it, such as SMB mounts, which are outside the scope below. On Windows, file sync uses FlushFileBuffers through Go, and directory sync uses a write-capable directory handle as described below.
The file store (store/file) keeps one log file per session.
The writer lock is taken per append (L9), the newest fence is kept in
<log>.fence(L10), and a new holder adopts the log before folding it (L11).
Header. A file starts with an 8-byte header: the 7 ASCII bytes ZELKLOG followed by one format-version byte (currently 1).
Creation. A log is created under a temporary name in the same directory: write the header, fsync the file, hard-link it to the log’s name (which fails if the name exists, so a concurrent creator’s log is never replaced), fsync the directory. A file at a log’s path therefore always starts with a complete, synced header, so a partial, damaged or foreign header is corruption and is never repaired: the file might not even be a zelk log, and the writer must not truncate it. A header with the right magic but a newer format version is refused as unsupported.
Records. After the header comes a sequence of records, one per append:
+----------------+-----------------+----------------+-----------------------+------+| length: u32 LE | payload: u32 LE | header: u32 LE | payload: length bytes | '\n' || | crc32c | crc32c | | |+----------------+-----------------+----------------+-----------------------+------+lengthis the payload’s length in bytes, from 1 to 16 MiB.- The payload checksum is the CRC-32C (Castagnoli) of the payload bytes.
- The header checksum is the CRC-32C of the first 8 bytes (length and payload checksum). The length is checked before it is trusted, so a corrupted length is detected as damage instead of sending the reader past the record, or past the end of the file.
- The payload is one line of JSON: an array of the events appended together, each encoded with
event.Encode. A batch is therefore all-or-nothing: either its record is valid, or none of its events exist. - The trailing newline keeps the file readable with line tools; it is checked on read.
A record is valid if its header is complete, its header checksum matches, its length is in range, its payload and newline lie within the file, and its payload checksum matches.
Failure model. One writer appends records one at a time and acknowledges each only after fsync (below). A crash can therefore damage only the final append, the one not yet acknowledged, and in any way: the file may end inside it, or the filesystem may have kept the file’s new size but not all of its data, leaving zeros or stale bytes. Records before it were synced and are intact.
Reading and damage. A reader reads valid records from the start. At the first record that isn’t valid, at offset X, it looks for a valid record starting at any offset after X:
| Situation | Meaning | What happens |
|---|---|---|
| The file ends exactly after a valid record | clean | read everything |
| A damaged record at X, and no valid record anywhere after it | torn tail: the bytes from X on are the unacknowledged final append | readers stop before it without an error, since it was never acknowledged, and never change the file; only the writer, holding the lock, truncates the file to X, and it logs the repair |
| A damaged record at X, and a valid record somewhere after it | corruption: acknowledged data follows the damage | an error; nothing is truncated |
A torn tail is the only damage the failure model allows, so it is the only damage repaired automatically. Anything else means the storage misbehaved, and dropping data would hide that. (Garbage that happens to form a valid record needs two matching CRC-32Cs, which is negligible.)
Write protocol.
- Encode the batch and frame it as one record.
- Write the record at the end of the file.
fsyncthe file.- Only then acknowledge the append.
A failed write or fsync breaks the session. After an fsync error the record’s durability is unknown, and it can’t be learned by reading the file: the data may still be in the page cache, readable by every process on the machine, while never reaching the disk, and a later fsync may report success without writing it. So the file store doesn’t retry and doesn’t consult the tail. It returns an error, and the driver stops the execution without dispatching the effect whose intent was being recorded. The session is then refused, for both appends and reads:
- by the store that failed, for good, even after
Close; - by other writers, in this process or another, through the log’s lock: a broken session’s log stays open and locked until the process exits, even after
Close. The lock is the one guard that can’t fail, so no writer can adopt the uncertain batch while the page cache might still show it; - by other stores and processes, readers included, through a marker file next to the log (
<log>.broken). Writers check it only once they hold the lock, when it is conclusive. The marker is deliberately not synced: it only has to last as long as the page cache might show the unsynced batch, which ends with a power loss, after which the disk is the truth again. If writing it fails, other stores’ readers aren’t warned, but the lock still stops other writers. Removing a marker that survives is an operator’s decision.
A failed torn-tail repair breaks the session the same way. Within one store, appends hold the session’s lock from write to sync and readers take it shared, so readers of that store never see a batch whose sync is pending or failed. A reader going through a different store can’t coordinate with another store’s append in progress and may see such a batch, which is why a new holder adopts the log (L11) and decides only from what adoption made durable. What the log holds is decided by what is on disk the next time it is opened after a restart.
Ambiguous appends are a different case. Some stores can report an append as ambiguous, for example a database whose commit timed out, while their reads stay authoritative. Such a store returns an error marked ambiguous, and the driver resolves it by reading the log from the sequence number after the expected one (expectSeq+1) and comparing what is there with the batch it sent: identical events (compared by their encoding) mean the append landed (the log is told, if it implements driver.LandedObserver), nothing means it didn’t, anything else is a conflict. This works for any batch, whether or not it holds effects. A batch that provably didn’t land is appended again, up to three tries in all; after that, or on a conflict, the driver stops without dispatching anything further. The file store never reports ambiguity, because its reads after a failure are not authoritative.
Blobs are stored as files named by their SHA-256 digest. A blob is written to a temporary file, synced, linked into place, and its directory synced, all before any event that refers to it is appended.
Directories and names. The host owns the store’s directory and makes it durable; it must exist when the store opens. The store creates its logs/ subdirectory, and each session’s output and history directories as they are first needed, and syncs the store directory before use, because creating missing ancestors would leave their entries in unknown, unsynced parents. A log or content name that exists is not necessarily durable: the writer that linked it may have failed to sync its directory. So whoever finds or makes a name syncs its directory before relying on it.
Scope of the guarantees
Section titled “Scope of the guarantees”The file store doesn’t cover the case described under L11: a write-back failure whose writer dies before a broken marker exists, read back by another holder while the machine stays up. These guarantees assume local filesystem semantics: sync makes data durable, rename is atomic, and file locks are released when their process exits. The Windows NTFS evidence below covers process crashes. Network filesystems may not honour all of these. Hosts that need durability elsewhere implement their own LogStore and run the store/storetest conformance kit against it.
Windows NTFS
Section titled “Windows NTFS”The Windows contract covers acknowledged changes across a process crash. OS-crash behavior and power-loss ordering of file data and directory metadata on NTFS remain unverified. Reopening after a process kill leaves the OS and its cache running. Fault injection checks call ordering against a model of synced data and names.
The following tests ran natively on Windows 10.0.26300, NTFS, with Go 1.26.11 (windows/amd64), using this command from WSL.
WINTEST_DIR=/mnt/c/src/zelk-storage scripts/wintest core test -tags=integration ./store/... ./lease/... ./memory/... ./env/materialize/... ./internal/osfile/...| Behavior | Verification |
|---|---|
LockFileEx locks one byte at offset 2^62, excluding other lockers while allowing data I/O. The process exit releases the lock. |
osfile/TestLocks, TestLockLeavesDataAccessible, TestLockReleasedWhenHolderDies, store writer handoff and killed-holder tests, and lease takeover across processes. |
| Opens share deletion, including the writer unlinking its locked log. | osfile/TestOpenSharesDelete and real-filesystem session removal and reopen tests in the store conformance kit. |
Replacing rename on NTFS uses FileRenameInformationEx with POSIX semantics. Open readers retain the old file. An exclusive, directory-relative rename refuses a collision. |
osfile/TestOpenSharesDelete, TestRenameNoReplace, and memory/file/TestReplaceNoteWithOpenReader. |
Directory flush uses FlushFileBuffers on a write-capable handle opened with backup semantics. A rooted caller resolves the path from its open handle and verifies the reopened handle has the same identity. |
osfile/TestSyncDir, TestSyncDirHandle, and the real-filesystem store and lease conformance kits. |
| File identity combines the volume serial and 128-bit file ID from the open handle. The store also checks the handle’s link count when verifying materialized content. | osfile/TestStat verifies identity across aliases and the hard-link count. |
| Log appends, fences, blobs, inbox snapshots, history, and lease grants use the same sync ordering as on Unix. | Native conformance and reopen tests, plus the store and lease fault-injection suites run with native path handling. |
| Materialization commits and withdraws the receipt with a file rename. Verified cleanup can remove a tree and reuse its path while an old file handle shares delete access. | materialize/TestCommitWithOpenStagedFile, TestInterruptedStages, and TestRecordedCleanupAfterReopen. |
Completion decision groups
Section titled “Completion decision groups”loop.Records prepares an atomic append containing each
causal event followed immediately by its derived completion, continuation,
shortcut and task-attempt records. It previews on isolated state; only committed
events advance the authoritative fold. Decision IDs derive from the originating
sequence and within-event order. A live fold (loop.Step) requires the exact owed
payload before any later event, rejecting forged goal revisions, evidence IDs,
counts and verdicts, as well as missing, reordered or duplicated decisions. Atomic
append failure preserves the previous state; a committed append with lost
acknowledgement is recovered from the log without resetting counts or repeating
decisions. External executors must use the complete group returned by
loop.Records before dispatching the effects of its fold.
Recorded decisions
Section titled “Recorded decisions”A stored log is folded with loop.Replay, where recorded decisions win. A
heuristic’s outcome is recorded right after the event that led to it, in the
same append. Replay holds each event until the next event of a kind that isn’t
owed (loop.Owed), or Flush, and hands the reducer the hinted decisions
recorded for it, those whose decision ID names its sequence number. The reducer
uses them instead of deriving them again: a log folds as it ran, whatever has
changed in the heuristics since. A recorded decision must still be structurally
valid: one for a call that isn’t pending, a run that isn’t current or an effect
that never started is inconsistent, as before. The hinted kinds are
ShortcutFlagged, WorkspaceMoved, CompletionChecked and PolicyDecided.
A PolicyDecided is the final decision, a wake envelope’s gate included: the
envelope once ran after the recorded decision and was derived again on replay,
so rewording its refusal broke every log holding the old wording.
Likewise an EffectStarted stands as recorded when it is the same action as the
effect derived (same kind, call, tool, input, model, question or timer), so an
approval’s wording or a compaction’s cut is what was dispatched. The other owed records
(continuations, task attempts, run starts, warnings, steering, requirement and
background records) follow from the hinted ones and the log, so replay derives
them and requires them to match.
loop.Step keeps deriving every decision and refusing one that differs. The
live path uses it for the events it has just recorded, and the tests fold every
log the current build writes with it, which catches a reducer that derives a
decision differently twice, as from nondeterminism.
What stays derived, and the rule. Notes added to the history, counters
(repeated calls, refusals, attempts, continuations) and the text of the
reducer’s own records are derived on replay. Changing how one of them is
derived moves it to a recorded decision in the same commit. There are no
version gates: ReducerVersion refuses logs from a newer build
and nothing else.
Before the first release, removing the erroneous derived
approval-revision notice is an intentional correction to conversation history,
not a change to the recorded protocol. The approval answer, session grant
(PolicyAmended) and permission verdicts remain recorded; replay reconstructs
the corrected history without the host-internal prose. No new decision record
or reducer-version gate preserves that leak. A regression compares the former
and corrected event sequences and folds the former sequence with Replay to
check that effects and owed decisions remain unchanged.
Deferred tool dispatch
Section titled “Deferred tool dispatch”Config.DeferredTools fixes the session’s deferred schema selection.
ToolSearch computes its bounded result from recorded tool specifications and
has no external effect or recovery protocol. CallTool is resolved while the
provider result is folded, before target hooks, permission checks, scheduling,
mutation accounting and reservations. Its pending RunTool carries the target
name/input and the provider-visible wrapper call ID. The ordinary tool attempt
protocol and recovery table therefore apply unchanged: an untrusted MCP target
with an open attempt reconciles as outcome unknown and is never retried merely
because the wrapper was used. Invalid wrappers produce an error result without
starting an action. Full target schemas remain recorded and compatibility
checks still compare them on resume.
Workspace observations
Section titled “Workspace observations”A session records whether it requires env.Differ. Before any dispatch in a
run, the driver captures and appends one WorkspaceBaseline containing bounded,
self-contained JSON and the run ID. Capture is read-only; losing a capture
before append permits repeating it because no action has yet dispatched.
The folded baseline survives suspension, process replacement and takeover.
Replay performs no filesystem I/O. A resumed driver must supply a compatible
Differ; the local baseline carries a version and rejects unsupported shapes.
At finalization the driver diffs against the original baseline and writes
TurnDiff.Workspace with the ending group. Losing that append permits another
read-only comparison; an acknowledged ending needs none. Diff failures surface
as execution errors, never an invented empty change set. Finalization after an
interrupt uses the ordinary bounded record lifetime. RunFinished retires the
baseline. Workspace observations include concurrent external mutations and
report exclusions/incompleteness rather than claim atomic attribution.
Session catalog mutations
Section titled “Session catalog mutations”Tags and deletion are commands in the session’s original log. Provider-free
catalog mutations acquire supervised authority, adopt and fold the log, refuse
unfinished runs, and atomically append the metadata command. Rename and tags
retain the session’s history;
the deletion command is a tombstone. Listings suppress it,
and the reducer rejects every subsequent event; the driver refuses continuation
with store.ErrDeleted. Deletion also refuses live background processes.
The tombstone is the commit point of deletion: the session is then removed
whole, outputs and checkpoints before the log, and a removal cut short
leaves a tombstoned log that the next sweep finishes
(retention). The durable fence outlives the log, so an old
lease holder stays refused.
Removal does not promise secure erasure.
Finished-child continuation
Section titled “Finished-child continuation”TaskContinue is a separate, enforced-idempotent tool effect using the existing
run_tool dispatch protocol. It keeps ordinary hook, permission, reservation
and recovery handling rather than introducing a second child runner. Its
arguments identify an owned finished child, the child’s last reported sequence,
and a new prompt. It does not detach or spawn another child. The tool resolves
the sequence of an idle child itself and settles a child that
ended uncollected before continuing it; a recovered effect reuses the sequence
its accepted command recorded, and settles the run before that acceptance.
The host verifies ownership against the parent’s recorded child links, not
merely a session-ID prefix. The child command ID is a hash of the stable parent
effect ID. Under the child’s lease, continue_child acceptance compares the
expected sequence, refuses active/foreign/deleted children, intersects the
child’s existing policy with the parent’s current policy and assigns a fresh
allocation. Policy changes and the prompt are one atomic command acceptance.
Trace records are appended after this acceptance so observation does not
invalidate the caller’s cursor. A stale request is refused and must use the
refreshed one.
Child policy may only narrow: old deny/human/ask rules and protected paths are retained, tool ceilings intersect, allow grants intersect, and the mode cannot exceed either policy. The child’s fixed tool schema and history remain recorded. The allocation ceiling becomes prior session commitment plus this call’s new allocation; parent settlement accounts only for the new run’s usage. Neither a missing allocation nor numeric overflow may turn a bounded child unbounded.
The parent records ChildContinued with its call/effect/reservation link, then
ChildFinished with the new run’s outcome and usage, in the tool completion
record group. The current child link advances; old starts, allocations and
outcomes remain in the event log. Pending child questions retain the existing
TaskOutput answer path. Parent cancellation still owns the foreground execution,
and continuation never holds the workspace mutation lock while waiting.
If the parent crashes after child admission, replaying its effect finds the same accepted child command. An unfinished original run resumes; a finished one returns its historical result and usage without another prompt or model call. If later child work exists, only the original run’s ending can satisfy the old effect; later results cannot stand in for it. A mismatched prompt or policy for the same identity fails closed. A rejected prompt that starts no run cannot reuse a previous run’s successful result.
New sessions offer TaskContinue; recorded tool schemas of older parents stay
unchanged. Child reports include their last recorded sequence for guarded
continuations. Go hosts can use the resolved event.ContinueChild command while
holding the usual session authority; network clients must not supply an
unverified parent policy or impersonate parent ownership.
Recorded skill publication
Section titled “Recorded skill publication”A session explicitly recording Materializer requires the optional Environment
capability and recorded blob reader on resume. MaterializeRequested selects a
loaded revision; the reducer derives a distinct materialize effect containing
its exact file manifest and stable publication key. It validates safe paths,
file/directory collisions, digests and bounds before deriving the intent.
The driver persists EffectStarted before reading blobs or publishing, and
prioritizes publication over pending provider/tool work. Session ownership, key,
paths, sizes and hashes define the canonical publication identity.
SkillMaterialized precedes the successful EffectFinished in one atomic
append. A missing, mismatched or foreign receipt cannot finish successfully.
The reducer retains the receipt and original manifest and updates only the
loaded skill’s directory. A failed publication ends the run honestly; it never
allows dependent work to use a partial tree. Publication has no model-token
reservation or charge.
Recovery closes a lost attempt and retries the same recorded input. The local
backend verifies complete existing trees; matching partial staging is removed
and a fresh stage is used. Each new execution verifies/recreates publications
before dispatch, so cleanup or host restart cannot silently select current
source bytes. On Windows NTFS, the local store checks the cache’s inheritable
private ACL and the ACLs of published files on their open handles. It flushes
each staged file through its writable handle before publishing. Linux and macOS
publish the synced directory with an exclusive rename. Windows stages at the
final directory name and commits with an exclusive rename of the synced receipt
from .pending to .manifest. NTFS can refuse to rename a directory with
open descendants. A receipt rename leaves those handles unaffected. Windows
treats a directory without the commit marker as an interrupted stage, even if
its files are accessible under the reserved cache path. The backend returns
a directory only after commit. MXC grants the cache read-only to workloads
and pins its namespace until they exit.
Completed publication groups survive execution cancellation;
interrupted work remains retryable. Publication itself grants no Bash or tool
permission. Agent rendering, materialized-byte quotas and session-end lifecycle
wiring are still separate implementation steps before automatic opt-in.
Changing a loaded skill’s runtime directory preserves its original script source directory for the existing Bash hash guard. Commands naming either path remain checked against the recorded bundle. A publication’s logical directory must remain stable across resume, including after backend recreation. A newer load accepted during publication is not overwritten by the old completion; that completed artifact still retains its cleanup ownership.
Materialized-byte preflight
Section titled “Materialized-byte preflight”The session configuration records MaterializedBytes limits per session and
execution. The meter charges each canonical publication identity once, reconstructing identity
history from durable receipts on resume. Verification/recreation of a previously
recorded artifact does not spend another allocation. Execution scope charges
identities first published in that execution.
Before intent, blob reads or backend publication, the driver compares the
recorded manifest size with the remaining configured limits. A refusal records
QuotaExceeded{Used, Proposed, Limit} with measured consumption and refused
bytes kept distinct. Only materialized bytes admit a proposed preflight; other
quota records describe measured consumption over the limit. Refusal closes the
run as quota_exceeded without publishing. A lost publication attempt charges
nothing until its receipt and success become durable, so ambiguous appends and
repeated recovery do not charge an artifact twice.
The reducer retains every started materialization input, including an attempt whose backend acted before an error or lost completion. Cleanup must account for these potential artifacts, rather than relying only on successful receipts. A deletion tombstone cannot discard this ownership. The catalog refuses deletion until durable cleanup is available, and disabling the capability with owned artifacts is rejected.
Owned publication cleanup
Section titled “Owned publication cleanup”MaterializationReleaseRequested is admitted only while idle. It selects an
identity only from the full-log ownership map, including started publication
attempts that may have acted without returning a receipt. It derives a distinct
release_materialization effect containing the original recorded manifest.
The provider-free driver records its start before blob reads or backend calls,
passes the current lease fence, and records MaterializationReleased plus a
successful EffectFinished in one atomic batch. Only that acknowledgment clears
ownership. Missing results, foreign identities and model usage are rejected.
Cleanup does not alter historical quota charges or fabricate model-run endings.
Lost attempts replay the recorded bundle through env.BundleReleaser; absent
artifacts succeed without allocating a new publication. Cancellation retains the
retryable effect. Failed/unknown cleanup retains ownership and reports the error.
Local cleanup verifies every candidate before mutation and withdraws the
publication before removing checked paths. Linux and macOS move the tree to a
staging name. On Windows, cleanup renames the receipt back to .pending, syncs
the directory, and removes verified entries through the rooted NTFS operations.
POSIX deletion on NTFS frees the name while old handles that share delete
access retain their files. Interrupted deletion remains reclaimable from the
recorded bytes. Unknown or changed data is preserved.
The local Store serializes session fence checks with mutations and refuses stale or downgraded callers. Its process-lifetime exclusive lock prevents simultaneous Stores; Close joins operations and permanently disables the old receiver before a new Store may open. Thus an earlier process/receiver cannot act after takeover.
Cleanup requires idle authoritative state, no running background processes and no unfinished children. Suspension is not session end. Catalog deletion requires the same cleanup backend and appends its tombstone only after all possible artifact ownership has been durably released. Hosts coordinate any references shared beyond the owning session. Pending cleanup is recovered through the management API, not through provider execution.
Publication-aware skill loading
Section titled “Publication-aware skill loading”InvokeSkill.RequiresMaterializer records when an explicit load’s
instructions await publication. Admission validates this against recorded
session support before accepting the command. The Skill builtin receives that
same support from its immutable call view. Hosts advertising Materializer plus
BundleReleaser opt new Agent sessions in; a session without recorded
support refuses publication-dependent invocations rather than silently promising
scripts it cannot publish.
Verified current directories are derived request context, matched against the loaded manifest and receipt identity. Materialization can finish after provider work was derived; queuing a harness note would postpone its directory until another turn. Dynamic context reaches that pending call, remains available after native compaction and removes released/superseded paths. Resume still verifies physical bytes before dispatch. Rendering grants no script/tool permissions.
Local publication namespace protection
Section titled “Local publication namespace protection”local.NewMaterializing installs cache protection before returning any usable
Environment. Every tool launch protects the entire cache, so a process started
before publication cannot write the later tree. File mutations resolve a parent
through the workspace jail, check its real inode ancestry and use that same
open descriptor for the mutation. Final write symlinks are refused; hard-linked
files are checked before truncation. Namespace ancestors cannot be removed or
renamed through the file layer. Linux retains its final-component openat2 mount
checks; macOS uses os.Root plus directory search descriptors; Windows uses os.Root
plus a handle-by-handle walk that confirms the parent’s real ancestry by file
identity, so aliases, 8.3 short names and case variants of a protected
directory are protected like the name itself. Hosts retain
exclusive control of this namespace outside these operations.
Storage construction follows the protected Environment; failures close handles without exposing an unprotected receiver. Generated cache contents are excluded from workspace capture/search and reported as exclusions. Read and execution still see published paths. Close joins processes before releasing the Store’s exclusive process lock, preserves content and permanently closes the old Store. No user repository index, refs or ignore files are modified.
Binding publication ownership to its backend
Section titled “Binding publication ownership to its backend”The session configuration optionally records a SHA-256 MaterializerNamespace. The local Store
binds canonical absolute storage and Environment-visible mapping, excluding
transient inodes and lease epochs. The Agent records this optional capability.
Normal execution and provider-free cleanup compare it before provider resolution,
command admission or dispatch. A different empty cache cannot report an artifact
absent and clear ownership of the cache that actually published it, including
attempts whose successful receipt was never recorded.
Changing the namespace requires zero possible owned artifacts. Recreating an absent directory at the same mapping retains identity and rehydrates recorded bytes. Older/generic backends without namespace support retain their explicit same-backend injection contract. The CLI requires a recorded namespace for cache cleanup and refuses ephemeral one-shot publication, so persisted ownership is available for later cleanup. It rejects aliased cache paths before opening them.
Image admission and replay
Section titled “Image admission and replay”History validation checks the recorded image envelope (media type and exactly one of data/reference), not image decoding. The driver admits untrusted tool-result and attachment images with imagefit.AdmitImages before recording. Type and size admission runs once, before recording. Supported decodable bytes (PNG, JPEG, GIF, WebP) are fitted and relabelled from their sniffed encoding; unresolved references are refused as placeholders. GIF inputs become static PNG first frames, so animation cannot poison a later provider request.
Admitted tool images remain in the log even under a text-only model. The fold’s loop.Request retains images: compaction scheduling (stepper.estimate), derived reservations (reservation, NativeReserve) and budget checks keep their previous inputs, preserving replay under the rule in “What stays derived, and the rule”. Each image still contributes compact.ImageTokens (1600) to the estimate; for a text-only model this is conservative and may compact early, never late because of this swap.
Outside the fold, loop.ProviderRequest starts with Request and replaces images in item parts and tool-result content with text notes whenever the current Capabilities.Images is false. The driver uses it for dispatch, adapter reservation bounds, native compaction and captured prompts, including compaction requests and provider-native windows. The adapter’s exact bound reaches EffectStarted.Reservation through execution.callProvider and execution.start; stepper.started accepts the recorded reservation rather than re-deriving the adapter bound on replay. Inline notes include media type and byte count; reference-only notes omit the byte count. Copies of changed parts and tool results preserve recorded state, so switching back to an image model restores the images in provider requests. Neither rendering nor estimates rewrite recorded image events, and no recorded-decision change is needed. Read and user-image commands still refuse new images immediately under text-only models.
Recorded open tool schemas
Section titled “Recorded open tool schemas”ToolSpec.schema_kind is omitted for canonical tools (event.SchemaCanonical, its zero value). open marks a foreign object-root JSON Schema, preserved in stable key order. ConfigChanged, snapshots, child configuration and ToolSearch retain the discriminator. Compatibility and MCP migration compare the kind as well as the contract; switching interpretation requires an explicit idle migration. Replay treats the spec as recorded data and never narrows or regenerates its schema. Runtime validation compiles the local-only contract; OpenAI strict null-to-omission mapping applies exclusively to canonical specs.
When image admission changes an attachment, Attachment.ImageSourceDigest (image_source_digest,omitempty) records the original type/content identity without retaining unusable bytes. A resend is compared as admitted, so an identical one returns its existing acceptance even after the session’s model stops taking images; that comparison comes before the model’s image capability is checked. Different rejected images never collapse into the same command merely because their placeholders match.
MCP connection diagnostics
Section titled “MCP connection diagnostics”Agent construction joins concurrent server handshakes in configuration order.
A server failure removes only that server’s tools, retaining its reason in
MCPServer and a mcp_server_unavailable warning at session creation. Cancellation
remains fatal and closes connections established by the cancelled construction.
Hosts consume the retained MCP status after construction; they do not rebuild the agent to remove servers requiring OAuth. The original typed cause remains available to sign-in interfaces.
MCP stdio recovery preserves E5: calls interrupted after a possible write retain unknown outcomes. Only a connection known closed before dispatch permits sending the request on a new initialized transport. Replacement joins the old process and reader. Automatic restarts use an injected clock: at most three, first immediate and then minimum gaps of 1 and 2 seconds. Requests inside the gate are not dispatched. A successful request after one minute of uptime resets the sequence before exhaustion; exhaustion stays latched until explicit reconnect. A reconnect re-lists tools and updates resource capability.
A streamable HTTP 404 with a session ID is proof of non-dispatch under MCP. The client may initialize a new session and resend that request exactly once. It does not infer this proof from a 404 without a session, nor retry an uncertain network error. Concurrent requests cannot replace the same generation twice.
MCP discovery is live agent state, not reducer state. One owned worker per server
coalesces pending notifications and publishes compiled tool/resource snapshots
under a lock. Idle root execution load migrates the recorded inventory and MCP
status with ConfigChanged, preserving deferral and tool ceilings. Each execution
resolves and validates implementations matching those recorded descriptors, then
keeps its own map until completion. Old implementations remain in the agent’s
archive for suspended runs and children; removal cannot invalidate an in-flight
call’s validation, digest or dispatch. Replay never consults this archive.
Mid-run migration is intentionally unsupported: the reducer rejects
ConfigChanged for any busy run, even with no tool currently executing. A safe
between-turn transition would need its own durable protocol for pending calls,
authorizations and provider contracts. Run-start migration preserves that
invariant. Subagents retain their assigned tools.
CLI and ACP overviews include MCP status: Agent views are live and Catalog views
use recorded MCP metadata. MCP model tools are not ACP slash commands, so their
inventory changes do not emit available_commands_update. The TUI reconnects
in place and polls status/revision changes through its existing background tick.
Stdio write-side closure and partial frames retire the whole connection even if stdout stays open. Retirement does not convert the failed call to not-dispatched or replay it; only later requests can use a fresh initialized connection.
The idle tool-preparation boundary joins discovery already in progress before selecting a revision. It may probe a previously connected failed client once; the client still enforces its restart circuit. Initial connection failures need explicit reconnect. Process death is reported even without an active call. Automatic exhaustion is latched: only explicit reconnect revives it. Prior to exhaustion, a successful request after one minute of uptime resets the sequence; merely waiting while dead is not evidence of health. Recovery counters let hosts report a reconnect even when their polls coalesce a short failure and recovery.
An HTTP server advertising tool-list changes may deliver them on its independent
GET SSE stream, as well as a call’s response stream. The transport owns the GET
reader and joins it on replacement or close. A 405 is an unsupported optional
stream; a clean end does not fail the server. Malformed streams surface a
connection diagnostic. Idle root preparation re-lists, in parallel, only servers with a pending
notification or reconnect and recovers failed ones; a quiet, healthy server is
not polled on every prompt, since a server whose tools change must announce it
(list_changed also rides on response streams when the GET stream is refused). There is no
unbounded stream reconnection loop. Multiline events are bounded per message and
fuzzed. Saved host names are mapped through the same ACP normalization for status
and reconnect actions, while sign-in guidance retains the saved name.
Source records and occurrence admission
Section titled “Source records and occurrence admission”create_source, pause_source, resume_source, end_source and occurrence
are ordinary CommandAccepted records under C1/K2–K4. Ending also represents
cancellation. Creation records Source{id, kind, description, idle}; later
lifecycle records carry only the ID. IDs are 1–96 UTF-8 bytes without controls,
reserved permanently. Descriptions are 1–4096 UTF-8 bytes. At most 128 non-ended
sources exist, including paused sources. They are session state across rewind.
An occurrence records {source, kind, from, to, payload:{text, folded, missed}}.
Text is nonblank valid UTF-8, at most 256 KiB. Counts cannot overflow together;
folded cannot exceed to-from. Its canonical command ID is
<kind>:<source>:<from>-<to> (up to 147 bytes, a specific exception to K1).
Under the lease, the reducer refuses unknown, paused or ended sources, a kind
mismatch, from other than cursor+1, reversed/zero ranges, a waiting/suspended
session, or a busy session for an idle-only source, with loop.ErrInconsistent.
The driver previews commands in batch order before appending anything.
Acceptance, cursor advancement, background notice and receiving run association are one atomic append. An idle session starts a run; a joining notice retains the run. Goal, permission review and UserPromptSubmit hooks are unchanged. Crash-before/after admission tests retry the identical ID and payload and prove one acceptance. Existing schedules, watches and job ends are not migrated yet.
Observer inbox persistence
Section titled “Observer inbox persistence”The optional store.InboxStore.Inbox() capability has a separate Append
receiver because Go cannot overload the log’s Append. store.Occurrence holds
number and the fixed occurrence payload. Append requires zero number and
folded count, assigns last+1 and acknowledges only after persistence. Source
and session IDs use the same validators as the log records. Text bytes alone
count toward 256 KiB; the 64-record bound bounds metadata separately.
A bound folds only an unexposed suffix, keeping the newest text and summing its
replaced/missed counts under a newly assigned number. Pending durably seals the
returned prefix before exposing it, including across processes and restarts.
A fully exposed queue cannot both fold and preserve possible admissions:
Append returns store.ErrInboxFull without changing records or numbering.
Observers retain refused input; no record is silently discarded. Trim accepts
only an exposed boundary (or an already-trimmed one), and keeps numbering and
sealing watermarks after removing payloads. The log acknowledgment always
precedes Trim; a crash between the two retries the same immutable command.
The file store keeps bounded snapshots at
inbox/<hex session>/<hex source>.zinbox: ASCII ZELKINB, byte 1, and one
framed CRC-32C record as above, containing {last,sealed,trimmed,entries}.
A partial trailing record is ignored; a damaged header or committed snapshot,
invalid state, or interior damage is corruption. Snapshots compact logically
appended occurrences without changing any exposed record. Each mutation takes
the existing session writer lock, writes a temporary file, syncs it, renames
it, then syncs its directory. No lease or log append is involved. Failed writes
before rename publish nothing. A failed directory sync after rename breaks the
session and retains the writer lock, following the log’s uncertain-publication
rules. Deletion removes inbox files before the session log; leftover discovery
includes inbox-only storage.
The shared inbox conformance kit covers both stores; file tests add simulated power loss, publication cuts at mutation boundaries, torn tails, corrupted snapshots and concurrent independent processes. Payload and snapshot decoders have fuzz targets.
Inbox admission acknowledgement
Section titled “Inbox admission acknowledgement”The driver admits sealed inbox ranges after queued commands, at lease acquisition and between dispatches; a local observer can poke it during a port call. Head is a nonmutating numbering read. Payload composition is fixed by wakes.md: ordered texts separated by two newlines and summed counts, bounded by a maximal prefix. Acceptance atomically advances the cursor and receiving run under K2. Only then may Trim discard payloads. Restart first trims through the log cursor, then reads new input: cuts after append, after acceptance and after trim each admit once. Another host’s observer needs no lease; contention defers admission, not recording.
One-shot schedule creation creates its source in one acceptance. Due
schedule:<id>:1-1 admission checks idle state and exact recorded text,
advances the cursor and ends the source atomically, with no inbox. A cancel
ends the source.
Interaction mode of a woken run
Section titled “Interaction mode of a woken run”A joining occurrence admitted into an idle session records the follow-up run’s interaction mode on the occurrence: interactive if the admitting host has a person, autonomous if not. The run keeps that mode through recovery by any host, and an autonomous run never asks, whatever callback the host resuming it has.