Specification (draft)
Status: Draft
Version: 0.4.0-draft
Last updated: October 27, 2026
Abstract
Section titled “Abstract”AgentSessions defines a durable agent session: an append-only, hash-chained event log plus zero or one live compute incarnation. A client creates a session, runs executions (turns) against it, suspends and resumes its compute, forks it into children, reads its log back, and can permanently tombstone it. An agent implementation (a harness) connects through a streaming protocol in which the host records every model call it makes for the harness and every host-executed tool call before the harness observes its result, so a session whose harness routes its model calls through the host can be reconstructed from its log without calling the model again. A harness that calls its model from its own compute instead (§8.8) gives up that reconstruction and relies on memory snapshots.
This specification defines the session model, the event log and its append rules, the canonical
encoding and provenance chain, execution, replay and recovery semantics, tool execution and approval
receipts, the harness wire protocol, the placement gate and runtime contract, the API surface, and
conformance classes. It documents the behavior of the reference implementation at
github.com/agent-primitives/sessions on main. It does not introduce behavior the reference
implementation lacks.
1. Conventions
Section titled “1. Conventions”The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, NOT RECOMMENDED, MAY, and OPTIONAL are to be interpreted as described in BCP 14 (RFC 2119, RFC 8174) when, and only when, they appear in all capitals.
Requirements carry identifiers such as LOG-3. Identifiers are stable within a draft version and
are the unit that reviews and conformance reports cite.
Unless stated otherwise:
- message, field, enum, and RPC names refer to the protobuf package
agentsessions.v1inapi/; their field-level reference is API reference, which this document does not repeat; - a sequence number (
seq) is a signed 64-bit integer scoped to one session; - a hash is lowercase hexadecimal SHA-256 with no algorithm prefix, except where a field is
defined with a
sha256:prefix; - “status code” means a gRPC status code.
1.1 Terminology
Section titled “1.1 Terminology”- Host: the process that serves the Sessions API, owns the event log of the sessions it runs,
and drives harnesses. The reference host is
agentsessionsd(oragentctlin embedded mode). - Harness: an agent implementation that serves the
Harnessservice, or the in-process Goapi.Harnessinterface. It runs one execution per invocation. - Mediated harness, unmediated harness: the two harness classes (§8.8). A mediated harness
makes every model call through the host; an unmediated harness makes some or all of its model
calls from its own compute, through the runtime’s egress. The class concerns model calls only and
is independent of tool
Mediation(§9.1). - Producer: a client of the Sessions API (an issue tracker, chat platform, or application).
- Runtime: a compute backend implementing the
api.RuntimeGo interface plusDescribe(§13.3). - Session: a durable resource identified by a
uid, with an event log and session metadata. - Execution (turn): one invocation of a harness against a session, identified by an
execution_id. - Record: one committed log entry (
LogRecord): anEventplusseq,prev_hash,content_hash, andfence. - Head: the
seqof the last committed record of a session; 0 for an empty log. - Fence: a per-session, monotonically issued integer token that identifies the current writer (incarnation).
- Host-owned event: an event kind only the host may journal:
EVENT_EXECUTION_START,EVENT_APPROVAL_REQUEST,EVENT_APPROVAL_RESULT, and lifecycle markers. - Reconstruction replay: re-running a harness against recorded effects, as distinct from the
ReplayRPC, which only reads records.
1.2 Reference CLI contracts
Section titled “1.2 Reference CLI contracts”create, get, suspend, resume and delete accept --json and return a protobuf Session;
list returns an aggregated ListSessionsResponse with no next-page token, fork a ForkResponse,
and approve/deny an ApproveResponse with the original decision and resumed session.
All CLI JSON, including harness output, uses protobuf JSON with proto field names:
snake_case names, full enum names, string-encoded int64s,
omitted default-valued fields and preserved message presence. replay --json emits JSON Lines,
one full protobuf LogRecord per line in sequence order, with unshortened hashes; it overrides
-v, performs no model calls and does not add chain verification. Empty replay emits nothing.
The content, not whitespace or key order, is the contract. Proto field naming matches CHAIN-1,
but CLI JSON is not the RFC 8785 canonical bytes used for hashing. A successful response requires
a successful command exit;
an RPC, encoding or output failure is not converted into a success. Approval recovery failure
still reports that the decision committed. JSON serialization does not change canonical bytes,
the hash chain or the journal format.
exec --json emits JSON Lines, one protobuf ExecUpdate per line in the order the stream delivers
them: session frames and committed records, each record the same LogRecord replay --json
prints. The first line is the session frame Exec sends before the turn runs. A turn that pauses
for approval exits successfully and ends with a session frame: a snapshot of the session when the
stream closes, which carries pending_approval unless a concurrent decision has already resolved
it. Only a recorded END shows that a turn completed. Streamed delta chunks are not committed and
are omitted; readers ignore update kinds they do not expect. A stream error leaves the lines already
written and exits unsuccessfully, without retrying the turn. A failed stdout write, including a pipe
whose reader has exited, ends the command unsuccessfully after the stream is read to its end, so the
turn is not cut short. Without --json, exec keeps the default Unix behavior and exits on SIGPIPE
when its pipe closes. That ends its stream, which cancels a turn still running, embedded or remote;
since the turn may already have ended, the outcome is unknown until the journal is read, and the
turn is not retried.
Without --json, create retains its bare UID output, and the human output of exec, replay and
fork is not a stable contract; scripts use --json. Harness JSON content is unchanged. Approval
JSON changes from lowerCamelCase to snake_case field names. Non-JSON diagnostics, including the
deletion PENDING warning, go to stderr even in JSON mode.
Session commands default their endpoint from
AGENTSESSIONS_SERVER; explicit --server wins, including an empty value to select embedded mode.
An environment-selected target is announced on stderr before making requests; failure to write
that notice refuses the operation. Explicit --journal with a remote target is an error.
Remote errors never fall back to embedded mode. Harness commands require a separate explicit
operator endpoint. See CLI output and migration.
2. Scope
Section titled “2. Scope”This draft specifies:
- the session resource, its two-axis state, its deletion state, and its metadata (§5);
- the event log: record shape, event kinds, sequence assignment, compare-and-swap append, fencing, and the Go session and harness stores (§6);
- the canonical encoding and the provenance hash chain, including fork lineage (§7);
- executions, the determinism invariants, reconstruction replay, and crash recovery (§8);
- tool execution modes, receipts, and at-most-once re-drive (§9);
- the durable approval gate for
STATELESS_REPLAYandREQUIRES_MEMORY_SNAPSHOTharnesses (§10); - the Sessions lifecycle operations, including permanent soft deletion, and their status codes (§11);
- the
Harness.Connectwire protocol (§12); - placement, resumability tiers, and the runtime contract (§13);
- the operator-facing harness registry (§14);
- the API surface and conformance classes (§15, §16).
3. Non-goals
Section titled “3. Non-goals”This draft does not specify:
- a credential format, authorization policy, transport assembly, or tenancy isolation (see §17 for optional Go authentication and embedded RPC authorization);
- a storage schema for the event log; the SQLite layout in
sqlitelog/is an implementation detail; - erasure of a session’s journal or metadata, or reclamation of its compute on deletion:
DeleteSessionrecords durable intent only (§11.8); - in-flight cancellation (
Cancelis declared and returnsUNIMPLEMENTED); - an HTTP/JSON mapping of the API; the only transport is gRPC;
- a warm (resident) pause;
COMPUTE_WARMis declared but never reported; - approval policy, expiry, or automatic decisions;
- a policy language for the pre-dispatch tool policy hook (§9.4);
- any compute, sandbox, cloud, or vendor technology. Backends such as agent-substrate are examples of the runtime contract (§13.4), not requirements;
- compaction or retention of the log (
LIFECYCLE_BASELINEis declared but has no defined semantics).
4. Conformance classes
Section titled “4. Conformance classes”| Class | Implements | Sections |
|---|---|---|
| Sessions host | Sessions service, controller semantics, harness driving |
§5, §6.3 to §6.5, §8 to §12, §13.1 to §13.3, §15 |
| Event-log store | the append, head, fence, read and verify contract | §6, §7 |
| Session store | session.SessionStore and session.HarnessStore (§6.7) |
§5.1 to §5.4, §6, §7, §10.2, §11.2, §11.8, §14, §17 |
| Harness | Harness service (Describe, Connect) or api.Harness |
§8.4, §9, §10.3, §12 |
| Runtime backend | api.Runtime plus Describe (§13.3) |
§13 |
| Chain verifier | independent recomputation of content_hash |
§7 |
An implementation MAY claim several classes. Passing one class does not imply another.
flowchart LR P[Producer] -->|Sessions gRPC| H[Host] O[Operator] -->|HarnessRegistry gRPC, separate listener| H H -->|append / read / fence| L[(Event-log store)] H -->|Describe, Connect| N[Harness] H -->|Describe, Create, Snapshot, Restore, Fork, Stop| R[Runtime backend] V[Chain verifier] -->|reads| L
5. Session model
Section titled “5. Session model”5.1 Resource
Section titled “5.1 Resource”SES-1:CreateSessionMUST assign a newuid. A caller-suppliedmetadata.uidis ignored. The reference format issess-followed by 24 hexadecimal characters; clients MUST treat theuidas opaque.SES-2:CreateSessionstores onlyproject,name,harness,model,labels,annotations,origin, andidentity. Output-only fields in the request (exec_state,compute_state,pending_approval,deletion_state,deletion_requested_time,last_seq,parent_uid,fork_seq,compute) MUST be ignored.SES-3: An emptyprojectMUST be replaced by the host’s default project. An emptyharnessMUST be replaced by the host’s default harness.SES-4:CreateSessionappends no event. A new session reportslast_seq = 0.SES-5:labels,annotations,origin, andidentityMUST be returned unchanged byCreateSession,GetSession, andListSessions, with one exception: anoriginoridentitythat is set but has no populated field is stored as absent and returned unset.SES-6:identityis recorded provenance. A host conforming to this draft MUST NOT treat it as an authorization decision (§17).Session.compute(ComputeRef) is not populated by the reference host. The suspend snapshot reference is carried on theLIFECYCLE_SUSPENDrecord instead (§13.3).
Model defaults
Section titled “Model defaults”SES-15: A host MAY configure an explicit default model and allowed model IDs per harness route. The reference host exposesplacement.WithModelPolicyto Go embedders; daemon binding configuration is not provided. IDs are opaque. The default MUST be nonempty and in the allowed set, which MUST NOT contain an empty ID.Descriptor.modelsMUST NOT supply a default.SES-16: When policy is configured, registration MUST check that everyDescriptor.modelsentry belongs to the host’s allowed set before making the route usable or persisting a new registration. An empty declaration is valid and never widens that set. The reference host bounds thisDescribeto 10 seconds; failure refuses registration without exposing peer diagnostics. A policy mismatch isFAILED_PRECONDITION; a failed policy Describe isUNAVAILABLE, unless the caller’s cancellation/deadline caused it (CANCELLED/DEADLINE_EXCEEDED). A policy-enabled static route can therefore refuse startup, and a failed stored route remains unservable until restart. Routes without policy retain their existing no-probe registration behavior.SES-17: Every newly created session MUST be eligible for selected-route model admission, independently of whether its creation route currently has policy. Model admission runs after any §17 authorization. AtCreateSession, a configured policy MUST reject a nonemptySession.modeloutside its allowed set withINVALID_ARGUMENT, before persistence. Empty means that route’s explicit default; metadata keeps the requested value, including empty. New executions MUST apply any current selected-route policy, including a harness override from an initially unconfigured route, and reject a disallowed session default withFAILED_PRECONDITIONbefore provisioning compute. Policy activation on the original route also applies to these new sessions. A route without policy retains its existing model behavior while it is unconfigured.SES-18: Genuine pre-policy sessions MUST retain existing behavior even if policy is configured later, including sessions with no events. The reference SQLite v6model_policyinteger stores independent host-owned flags: bit 0 records creation-time policy opt-in, bit 1 marks a new session even on an unconfigured route. Zero is legacy; bit 0 alone also marks a session eligible. All new service-created sessions set bit 1; normal metadata updates MUST NOT clear either flag. Fork inherits both flags withmodel, never marking a legacy child as new. For modern children, inherited route/default/admission metadata MUST commit with the first child row, before fan-out finalization: a later clone failure or interruption MUST NOT leave a runnable legacy child. No old event or hash is rewritten. Unsupported flag bits refuse Get/List reads rather than silently disabling admission.
5.2 Two-axis state
Section titled “5.2 Two-axis state”A session reports an execution axis (exec_state) and a compute axis (compute_state). There is
no flattened lifecycle enum.
-
SES-7:exec_stateMUST be derived from the log atlast_seq, by reading it or from a projection updated in the same transaction as the append (LOG-8), which is what the reference host reads. The value is:EXEC_RUNNINGwhen the projection lags the journal head, missed earlier records, or the reporting evidence is ambiguous (invalid execution/approval structure or incomplete declared inputs). The reference store never skips a projection gap to regain reporting authority;EXEC_AWAITINGwhen a valid, owned, unanswered host approval request exists in the latest execution (§10);- otherwise
EXEC_PENDINGwhen the log has no execution records (lifecycle-only histories remain pending); - otherwise
EXEC_COMPLETEDwhen the latest execution’s last non-lifecycle event is anEVENT_ENDwith a body; - otherwise
EXEC_FAILEDwhen that event is anEVENT_ERRORwith a body; - otherwise
EXEC_RUNNING.
Latest means first-seen execution order, not the execution ID of the last record. ID-less legacy execution records share one reporting identity; their last non-lifecycle event selects the outcome. An ID-less non-lifecycle record after modern execution begins violates
EXE-16: reporting corruption is sticky, reports RUNNING and suppresses pending approval references. A valid unanswered approval otherwise takes precedence over a recorded ERROR. Deletion leaves this value as it was: a deleted session with a valid unanswered request still reportsEXEC_AWAITING, but withoutpending_approval(SES-12). Other lifecycle records preserve the execution outcome; FORK excludes inherited approval calls under §10. A fork cut mid-execution therefore reports RUNNING until later execution records change it, without asserting the child is actively executing. -
EXEC_RUNNINGmeans unfinished or uncertain, not confirmed controller liveness. Crashed executions may remain RUNNING; execution leases and liveness reporting are separate work (#213). FAILED does not make a modern execution unrecoverable (EXE-6): subsequent journaled progress reports RUNNING, or END reports COMPLETED. Merely taking a fence or entering Run changes no execution records and therefore does not clear FAILED. These values grant no admission or recovery authority. The reference host does not reportEXEC_CANCELED; Cancel remains unimplemented. -
SES-8:compute_stateMUST be updated in the same transaction as the append that changes it:LIFECYCLE_SUSPENDandLIFECYCLE_FORKsetCOMPUTE_COLD;LIFECYCLE_RESUMEsetsCOMPUTE_LIVE;- any non-lifecycle event other than
EVENT_APPROVAL_REQUESTandEVENT_APPROVAL_RESULTsetsCOMPUTE_LIVE; LIFECYCLE_BASELINE,LIFECYCLE_CANCEL,LIFECYCLE_DELETE, and approval events leave it unchanged;- a session with no events reports
COMPUTE_NONE.
-
The reference host never reports
COMPUTE_WARMorCOMPUTE_TERMINATED.
5.3 Listing
Section titled “5.3 Listing”SES-9:ListSessionsMUST enumerate sessions from durable metadata, including sessions with no events.projectis an exact-match filter; empty selects the default project. A deleted session (§5.4) MUST be omitted, and omitted before paging, so it takes no slot of a page.SES-10: Paging MUST be keyset over(create_time DESC, uid ASC). Apage_tokenthe host cannot parse MUST beINVALID_ARGUMENT.next_page_tokenis empty on the last page.SES-11: Apage_sizeof 0 or less selects the server default (50 in the reference host). A value above the server maximum (500) is clamped, not rejected.
5.4 Deletion state
Section titled “5.4 Deletion state”deletion_state is a third axis, independent of exec_state and compute_state.
SES-12: A session MUST reportDELETION_ACTIVEuntilDeleteSessioncommits (§11.8), andDELETION_PENDINGfrom then on.deletion_requested_timeis unset whileACTIVEand, whilePENDING, is the time the host recorded in the deletion transaction (OPS-31). APENDINGsession MUST NOT reportpending_approval.SES-13:PENDINGis a permanent tombstone and durable intent, not a report that compute or snapshots were reclaimed (OPS-35). No transition leaves it. The reference host never reportsDELETION_STATE_UNSPECIFIED; the internal completion state reserved for cleanup has no wire value and is never written.SES-14:GetSessionMUST keep returning a deleted session, with its metadata, lineage,last_seq(which counts theLIFECYCLE_DELETErecord), andupdate_time(equal todeletion_requested_timein the reference host).
6. Event log
Section titled “6. Event log”6.1 Records
Section titled “6.1 Records”LOG-1: A record MUST consist ofseq,prev_hash,content_hash,fence, andevent(LogRecord).Eventcarries no sequence or hash fields; field numbers 1, 5 and 6 are reserved for that reason.LOG-2: Records are totally ordered per session byseq. The first record hasseq = 1. Each append assignsseq = head + 1; the caller never choosesseq.LOG-3:fencerecords the token of the writer that appended the record. It is not covered bycontent_hash(§7.1).LOG-4: An event carriesexecution_id,ts,schema_version,kind,actor, and at most one body. The reference host leavesschema_versionunset and setstsonly onEVENT_APPROVAL_RESULT, except onLIFECYCLE_DELETE, which carriesschema_version = 1and atsequal todeletion_requested_time(OPS-31); other events carry whatever their producer supplied.
6.2 Event kinds
Section titled “6.2 Event kinds”| Kind | Body | Written by | Notes |
|---|---|---|---|
EVENT_EXECUTION_START |
ExecutionStart |
host | First record of every new execution (§8.1). |
EVENT_INPUT |
Message |
host | One per input message. |
EVENT_MODEL_CALL |
ModelCall |
host | Recorded before the provider is invoked. Journal form keeps model, params, input_hash, id; the reference host records only model, input_hash and id, so params is covered by input_hash alone (EXE-11). |
EVENT_OUTPUT |
Message |
host | The finalized model completion (EXE-12), or text the harness emits through Output: one assistant text record per call (a wire harness’s message keeps only its text parts). Streaming deltas (ExecUpdate.delta) are never journaled. |
EVENT_TOOL_CALL |
ToolCall |
host | Intent, recorded before a host-executed tool runs. |
EVENT_TOOL_RESULT |
ToolResult |
host | Receipt, or a harness-reported result. |
EVENT_APPROVAL_REQUEST |
ApprovalRequest |
host only | §10. |
EVENT_APPROVAL_RESULT |
ApprovalResult |
host only | §10. |
EVENT_USAGE |
Usage |
host | Per-call usage reported by the harness. |
EVENT_LIFECYCLE |
Lifecycle |
host only | SUSPEND, RESUME, FORK; DELETE, written only by DeleteSession with an empty execution_id (§11.8); BASELINE, CANCEL declared, unused. |
EVENT_END |
HarnessEnd |
host | Written with state = "COMPLETED" on success. |
EVENT_ERROR |
Error |
host | Best-effort record of a failed execution or recovery. |
EVENT_PARKED |
ApprovalRef |
harness | Transport only; never journaled (§10.3). |
EVENT_RECONSTRUCTION_INFO |
ReconstructionInfo |
harness | Stream-bound class metadata before reconstruction Start; transport only, never journaled (WIRE-3a). |
LOG-5: A host MUST NOT journalEVENT_PARKEDorEVENT_RECONSTRUCTION_INFO. The host-side sink has no operation that emits either. The wire client accepts the former only as the park acknowledgement (§10.3) and the latter only before reconstructionStart(WIRE-3a), and refuses either as an ordinary harness event.- The reference SQLite store refuses to append both transport-only kinds. The in-memory reference
store refuses
EVENT_RECONSTRUCTION_INFO; it retains its legacy acceptance ofEVENT_PARKED. LOG-6: The reference host writesEVENT_ERROR, notEVENT_END, when an execution fails. It never writesHarnessEnd.statevalues other thanCOMPLETED.LOG-18:LIFECYCLE_DELETEMUST be written only by the deletion transaction (OPS-31), never throughAppend. The reference SQLite store refuses anAppendof it. The in-memory reference store does not check the kind, and has no deletion.
6.3 Append and compare-and-swap
Section titled “6.3 Append and compare-and-swap”LOG-7:Append(expected_last_seq, fence, event)MUST commit the event asseq = head + 1only ifexpected_last_seqequals the current head. Otherwise it MUST fail with a conflict error (eventlog.ErrConflict) and commit nothing.LOG-8: The head read, the sequence check, the fence check, the insert, and any projection updates (compute_state, execution/approval projection) MUST be atomic. Two concurrent appends at the same head MUST NOT both commit; if either carries the current fence, exactly one commits. The loser fails with the conflict error, or with the fenced error (LOG-12) when its fence is stale and it reaches the store first.LOG-9: When both the sequence and the fence are stale, the reference store reports the conflict error, because the sequence check runs first.LOG-10: A host MUST map the conflict error toABORTED.
6.4 Fencing
Section titled “6.4 Fencing”LOG-11:NewFenceMUST atomically advance and return the session’s fence. The first token is- A token of 0 is never minted.
LOG-12:AppendMUST fail with a fenced error (eventlog.ErrFenced) whenfenceis lower than the session’s current fence, and commit nothing. A host MUST map it toABORTED.LOG-13: A writer that receives the fenced error has been superseded and MUST NOT retry the append. When the fenced error reaches the host, the host MUST end that operation and reportABORTED.- In the reference host a fenced append is not sticky in the sink, except for the approval
request and approval receipt appends (§10). Every later append fails fenced too, so the
superseded writer journals nothing more. A wire harness’s sink errors reach the host unchanged,
and a harness that returns without error fails on its
EVENT_ENDappend. An in-processapi.Harnessthat returns its own error without wrapping the sink error (%w) is reportedINTERNAL; to haveABORTEDreported, it returns the sink error unchanged or wrapped with%w. - The reference store accepts a
fenceequal to or greater than the current fence and does not store a greater value as current. For a session with no metadata row, the current fence is 0. - Open question: Should a store reject a
fencegreater than the last minted value? The reference store accepts it and no test pins either behavior. LOG-14: Every operation that starts writing to a session (Exec, Resume, Suspend, Approve, the approval repair in §10.4, Fork children) MUST mint a fresh fence before its first append, so that any earlier writer is superseded.DeleteSessionadvances the fence in the same transaction as its append (OPS-31).LOG-19: A store that supports deletion MUST refuseAppendandNewFencefor a deleted session with a deleted error (eventlog.ErrDeleted) and commit nothing, whatever the fence and cursor, and MUST NOT rewrite a deleted session’s metadata. A session with no metadata row is writable. The reference SQLite store enforces this and checks deletion first, so a deleted session reports the deleted error, not a conflict or fenced error. The in-memory store has no deletion. A store MAY also expose a read-only writable check (CheckWritable), which the reference host runs before any runtime call (OPS-34); a wrapper around such a store has to forward it to keep that ordering. The journals of a Go session store MUST expose it (STORE-7).
6.5 Idempotency
Section titled “6.5 Idempotency”LOG-15:Appendhas no idempotency key. A retried append after a successful commit fails with the conflict error; it is never deduplicated by the store.- The Sessions RPCs carry no request id. The exceptions are
Approve(an exact retry returns the existing decision, §10.2) andRegisterHarness(idempotent on the spec digest, §14).CreateHarnessis deliberately not idempotent (REG-3a). - Tool-level deduplication is the executor’s responsibility (§9.3).
6.6 Reads
Section titled “6.6 Reads”LOG-16:Read(from_seq)MUST return all records withseq >= from_seqin order, with the storedprev_hashandcontent_hash(not recomputed).LOG-17: TheReplayRPC streams committed records only.from_seq <= 0reads from 1;to_seq = 0reads to the head. It never emits deltas and never runs a harness.- The reference SQLite-backed
Replayreads stored protobuf events directly (through the journal’sReadProto, §6.7), preserving field presence, including present empty messages, rather than round-tripping through domain events. It returns the stored hashes without verifying or recomputing them. - The reference host returns an empty, successful stream for an unknown or empty session on
Replay; it does not returnNOT_FOUND. Replayof a deleted session MUST keep returning its records, includingLIFECYCLE_DELETE.
6.7 Session and harness stores
Section titled “6.7 Session and harness stores”The reference host reaches durable state through two Go interfaces in
session/store.go: session.SessionStore (session metadata, journals,
listing, deletion), taken by session.NewService, and session.HarnessStore (the harness
catalog), taken by session.NewHarnessRegistry and session.ReserveStaticHarnessNames.
*sqlitelog.Store implements both and is the only implementation in this repository. The
session metadata and harness catalog types (SessionMeta, SessionInfo, HarnessRecord and
their list options) and the sentinel errors for them are sqlitelog’s. The journals a store
returns are eventlog.SessionJournal values (STORE-7), each an eventlog.Store with a
required CheckWritable deletion preflight: their records and sentinel errors,
eventlog.ErrDeleted among them, are eventlog’s, and they meet §6.1 to §6.6 and §7. This
section adds what the host needs from the rest. It specifies no storage schema (§3). A host that
serves sessions gives both interfaces the same store, because session admission (STORE-3)
reads the catalog that registration writes; the reference daemon does.
STORE-1: A store MUST return these sentinel errors, wrapped so thaterrors.Ismatches, for these conditions:sqlitelog.ErrSessionNotFound:SessionInfoorDeleteSessionof auidwith no metadata row;sqlitelog.ErrSessionExists:CreateOwnedSessionof any existinguid, deleted or created by a journal write included;sqlitelog.ErrInvalidPageToken: aListSessionspage token the store cannot parse (SES-10);sqlitelog.ErrHarnessNotFound:HarnessorRetireHarnessof a name with no registration, and admission (STORE-3) of a registered name with none;sqlitelog.ErrHarnessRetired: admission of a registered name whose registration is retired;sqlitelog.ErrHarnessNameCollision: admission of a static name that has a registration, active or retired, andReserveHarnessNamesof such a name;sqlitelog.ErrHarnessSpecConflict:RegisterHarnessof a taken name with a differentSpecDigest(REG-3);sqlitelog.ErrHarnessExists:CreateHarnessof a name with a registration, active or retired and whatever its spec (REG-3a);sqlitelog.ErrHarnessNameReserved:RegisterHarnessorCreateHarnessof a reserved name;eventlog.ErrDeleted:PutSessionorPutSessionOnActiveHarnessof a deleted session (the latter before its harness check), and the journal writes inLOG-19.
STORE-2:SessionInfoandListSessionsMUST reflect every journal append andDeleteSessionthat returned before the read:last_seq,exec_state,compute_stateandpending_approvalcome from the committed journal or from projections updated in the append’s transaction (LOG-8,SES-7,SES-8).ListSessionsMUST meetSES-9toSES-11, and filter byopts.Owner, when set, before paging (§17).STORE-3: Admission.PutSessionOnActiveHarnessandCreateOwnedSessiontakeregistered, the caller’s statement that the harness name is not one of its static harnesses. Each MUST check the catalog and write the session row in one transaction, and write only when the check passes: a registered name with an active registration, or a static name with no registration. ARetireHarnessor a registration that committed earlier, on any host sharing the store, is therefore always seen (OPS-4,REG-4).CreateOwnedSessionMUST also refuse an existinguidand recordownerin that transaction.PutSessionis an upsert with no admission check.STORE-4:RegisterHarness,CreateHarnessandReserveHarnessNamesMUST each check and write in one transaction, and each MUST check the others’ rows, so a name is reserved or registered, never both, and of concurrentCreateHarnesscalls for one name at most one succeeds (REG-3a), however hosts sharing the store interleave. A refusedCreateHarnesschanges nothing. A failingReserveHarnessNamesreserves none of its names, and a reservation is never released.HarnessNameReservedreports a reservation; the registry uses it only as a preflight, so it MAY read outside any transaction.RegisterHarnessof the same digest returns the stored registration, reactivating a retired one (REG-3);RetireHarnessof a retired one changes nothing (REG-4).ListHarnessesMUST return registrations in name order afteropts.Afterand, unlessopts.IncludeRetiredis set, only active ones, and fewer thanopts.Limitonly when none remain, because the registry pages until then.STORE-5:DeleteSessionMUST commitOPS-31in one transaction (theLIFECYCLE_DELETEappend, the fence advance, and the deletion fields) or commit none of it, and meetOPS-32. Once it returns, every journal the store returns for the session refuses writes (LOG-19), including on other hosts sharing the store (older binaries areOPS-36), andPutSessionandPutSessionOnActiveHarnessrefuse witheventlog.ErrDeleted.STORE-6:SessionLog(uid)andForkSessionLog(meta)MUST write nothing when called. AForkSessionLoghandle MUST commitmetain the transaction of its firstNewFence, so a fork child refused or not provisioned before that fence leaves no session, and a child with a fence has its inherited metadata (SES-18). The reference host takes children whose metadata carries a model-policy flag throughForkSessionLog, and writes every child’s metadata again withPutSessionafter the fan-out.STORE-7: Every journalSessionLogandForkSessionLogreturn MUST implement the deletion preflightCheckWritable(LOG-19); theireventlog.SessionJournalresult type requires it, and a journal that wraps another MUST forward it.CheckWritablewrites nothing. It MUST return an error wrappingeventlog.ErrDeletedonceDeleteSessionof the session has returned, including on other hosts sharing the store, andnilfor a session that is active or has no metadata row; any other error fails the operation. The reference host calls it beforeDescribe, a fence or a runtime call, and beforeApproveanswers an exact retry (OPS-34). Without it, a deletion that commits after the host’s lookup stops an operation only at its first fence or append, after its runtime work (STORE-5), and never stops an exact approval retry, which writes nothing (APR-7). A journal MAY also implement bothBeginAllocation(ctx, backend, operation)andConfirmAllocation(ctx, attempt, incarnation). When it does, the reference host callsBeginAllocationbefore each runtimeCreateandRestoreandConfirmAllocationwith the incarnation returned, and fails the operation if either call fails. A journal without them runs without the allocation ledger (§13.4,OPS-35). To record a resource plan (RT-4j) a journal MAY also implementBeginPlannedAllocation(ctx, backend, operation, resources...), used in place ofBeginAllocation, and for fork childrenBeginUnpublishedAllocationwith the same arguments; without them the host records no plan, and a fork child forks untracked. A journal MAY also implementReadProto(from_seq), returning the records ofLOG-16with their stored protobuf events. The reference host’sReplayuses it when present (§6.6); otherwise it converts theReadrecords, which keep the stored hashes but not field presence, so an audit client cannot detect presence-only tampering.- No conformance test runs a second store.
session/store_test.godrives the reference host through a wrapper that exposes only these interfaces, with and without the optional allocation andReadProtomethods, and commits a deletion between each operation’s lookup and its guarded work (§16.2).
7. Provenance chain and canonical encoding
Section titled “7. Provenance chain and canonical encoding”7.1 Canonical form
Section titled “7.1 Canonical form”-
CHAIN-1: The canonical bytes of an event MUST be the RFC 8785 (JCS) transform of its proto3-JSON form, produced with proto field names (not lowerCamelCase), enum values as names, and unpopulated fields omitted. Under proto3-JSON,int64is a string andbytesis standard base64. -
CHAIN-2:content_hashMUST be:content_hash = lowercase-hex( SHA-256( JCS({"event": <proto3-JSON(Event)>,"prev_hash": <prev_hash string>,"seq": <seq as a decimal string>}) ) ) -
CHAIN-3: The first record of a session MUST useprev_hash = ""(the empty string). Every later record MUST use thecontent_hashof the record atseq - 1. -
CHAIN-4:fenceis outside the hashed envelope. Copying a record into another session with a different fence does not change its hash. -
CHAIN-5: Fields that are wire-only MUST NOT be in the journal form and therefore are not hashed:ModelCall.messages,ModelCall.tools, andModelCall.tool_choice. The model input is covered byModelCall.input_hashinstead (§8.3). -
CHAIN-6: A zerotsis omitted.optionalfields keep presence:ExecutionStart.input_count = 0is emitted, an absent count is not. -
CHAIN-7: Structured content (google.protobuf.Struct: tool args, outputs,DataPart) is JSON-shaped. Integers above 2^53 inside aStructare not exactly representable; producers SHOULD NOT put them there. -
Externalized payloads (
FilePart.uri,ReasoningPart.opaque_uri,ToolResult.output_uri) carry their own digest field, so the chain covers them by reference. The host does not fetch or check the referenced bytes.
7.2 Fork lineage
Section titled “7.2 Fork lineage”CHAIN-8: A fork child MUST contain the parent’s records1..at_seqwith identicalseq,prev_hash,content_hash, and event, under the child’s own fence, followed by aLIFECYCLE_FORKrecord whoseprev_hashis the parent’scontent_hashatat_seq. The chain is a tree rooted at the first ancestor.- The reference host writes
Lifecycle.detail = "parent@<at_seq>". The parent uid is recorded in session metadata (parent_uid,fork_seq), not in the detail string. WhenForkreturns a compute instance (RT-4h), the marker records it inLifecycle.compute_instance; an empty one is omitted from the canonical bytes, so a marker without it hashes as before.
7.3 Verification
Section titled “7.3 Verification”CHAIN-9: A verifier MUST walk records fromseq = 1with expectedprev_hash = "", check that each record’sprev_hashequals the expected value, recomputecontent_hashperCHAIN-2, and report a mismatch of either as tampering.CHAIN-10: A verifier MUST recompute hashes from the event content, not trust stored hashes.CHAIN-12: A host MUST verify a session’s records perCHAIN-9andCHAIN-10before reconstruction (§8.5) serves them, recovery (§8.6) re-drives them,Exec(§11.4) appends a new execution after them, an approval-request repair (APR-13) appends to them, orFork(§11.7) copies them into a child. On a mismatch it MUST refuse before the harness runs, before any model or tool call, and before the operation appends anything (forFork, also before the parent is checkpointed and before any child is provisioned, fenced or written: copying re-hashes the prefix, so an unchecked copy would turn a changed record into a child chain that verifies); the session service reportsDATA_LOSS. Recovery refuses even when its no-op case (EXE-20) would apply.- The reference controller (
controller.ErrJournalTampered, wrappingeventlog.ErrTampered, which issqlitelog.ErrTampered) verifies the whole journal on its first read and afterwards only the records appended since, after checking that the last verified record still has the same seq andcontent_hash. A record below that point whose event changes later in the same controller’s life is not re-checked. - In the reference host the check runs in the controller, in placement before it answers an owned
gate with no decision (
APR-13: the park and the request repair both refuse, so a tampered parked journal isDATA_LOSSonResumeand input-lessExec), and at the start ofFork. OnExecandResumeearlier steps still run on unverified records: onExec, approval inspection, admission (Describe), runtimeCreateand the fence mint; onResume, approval inspection, recorded-harness routing, admission,Restoreand the fence mint. A tampered record that makes one of those steps fail is reported with that step’s error, notDATA_LOSS.Forkchecks the copied records1..at_seqbefore admission, the memory-tier parent snapshot andSUSPEND(OPS-25) and any per-childRuntime.Fork(OPS-24), and the controller checks them again before each child is fenced.Approveand theReplayRPC (§6.6) do not verify;Replayreturns the stored hashes so the caller can.GetSessionand the session frameExecsends before the turn report the stored session row, includingpending_approval, not journal records, and are not gated. - The chain is unkeyed.
CHAIN-12catches storage corruption and edits that do not recompute the hashes. A journal writer that rewrites an event and recomputes every later hash is not detected. agentctl verify --session UIDreads the reference host’s session head and records through the Sessions API and verifies that prefix locally, preserving protobuf field presence. It refuses sequence gaps, hash/link mismatches, and a prefix shorter than the reported head; it does not run a harness or call a model. A captured head of zero verifies the empty prefix without callingReplay, so later appends are excluded in that case too. This is not an independent external head anchor.- Verification proves internal consistency only. Removing records from the end of a log, or replacing the whole log, is not detectable from the log alone; detecting it requires an external anchor (for example a recorded head hash), which this draft does not define.
- Open question: Define an external head anchor (signed or published head
content_hash) so that tail truncation is detectable.
7.4 Golden vectors
Section titled “7.4 Golden vectors”CHAIN-11: A chain verifier MUST reproduce the golden vectors pinned incanon/canon_test.goandhack/verify_chain.py(python3 hack/verify_chain.py --golden). They cover an output event, threeEXECUTION_STARTshapes (opaque config with an int64 cursor above 2^53,input_count0,input_count2), a policy-aware start withmodelandinput_count0, and an output carrying a tool-call part withStructargs, each atprev_hash = ""andseq = 1.hack/verify_chain.py --journalaudits a SQLite journal end to end with an independent Python implementation.hack/verify_chain.shruns it against a recorded journal and against a tampered copy, which must fail.- Open question: The independent verifier is exercised on golden vectors and echo-harness journals.
The tool-call vector pins one exactly representable float (
1.5). Parity with the Go encoder is not verified for floats that are not exactly representable or that serialize in exponent form (for example0.1,1e21), for negative zero (-0, which RFC 8785 serializes as0), or for timestamps with fractional seconds.
7.5 Related digests
Section titled “7.5 Related digests”- The harness registry’s
spec_digestissha256:followed by the lowercase hex SHA-256 of the canonical bytes (CHAIN-1) of theHarnessSpecmessage (§14).
8. Executions
Section titled “8. Executions”8.1 Execution records
Section titled “8.1 Execution records”EXE-1: Every new execution MUST begin with a host-writtenEVENT_EXECUTION_STARTrecord, before anyEVENT_INPUTor effect. It carries the execution’sconfigbytes verbatim,resume_from_seq,input_count(always set, including 0), the host-resolved harness name, the harness’s advertisedversion, and, when the backend reports one, the compute instance the turn was placed on (compute_instance,RT-4h). Policy-enabled executions also record their effective default inExecutionStart.modeland deliver it inStart.model; empty retains pre-policy behavior. Replay/resume MUST restore this recorded default, not today’s policy default.EXE-2: The caller’s compare-and-swap cursor (§11.4) applies to theEXECUTION_STARTappend. If it fails, the harness MUST NOT run.EXE-3: OneEVENT_INPUTper input message MUST followEXECUTION_START. Each later append in the execution is made at the current head under the execution’s fence.EXE-4: Every event the host appends for an execution MUST carry itsexecution_id, except records appended while recovering a legacy execution (§8.7), which carry none. The reference host generates a random 16-hexadecimal-character id.EXE-5: A successful execution MUST end withEVENT_END(state = "COMPLETED"). A failed execution ends with a best-effortEVENT_ERRORand noEVENT_END. An execution that parked at an approval gate (§10) ends with neither.EXE-6: Outside the legacy execution (§8.7), an execution is complete if and only if it has anEVENT_END.EVENT_ERRORdoes not complete such an execution; a later recovery may still finish it. The legacy execution’s completion rule isEXE-29.EXE-7:Start.historyfor a new execution MUST be every event before itsEXECUTION_START, withApprovalResult.verified_approverleft empty (APR-8). The reference host always sends the full prior log, including after a memory restore.EXE-45: Before recording a new execution for a harness that supports run preparation, the host MUST prepare the actual Run without invoking the harness or sendingStart. A preparation failure appends no execution records, so the caller may retryExecat the same journal cursor. The successful preparation MUST be used for that execution at most once, and MUST be closed unused if a record append fails. Only afterEXECUTION_STARTand everyINPUTcommit may the host sendStart. Once preparation succeeds, a caller cancellation, send failure or receive failure does not prove non-delivery: any recorded execution remains durable and visible in later history underEXE-7andEXE-17.
8.2 Effects
Section titled “8.2 Effects”The host mediates exactly these harness operations, in the Go SPI as api.EventSink and on the
wire as §12 frames: model call, output, tool call, reported tool result, and usage. A harness that
makes model calls without the model call operation is unmediated (§8.8): the host journals its
other operations but never sees those calls.
EXE-8: The host MUST serialize the sink operations of one execution. After the harness’s run returns, further sink calls MUST fail.EXE-33: A failed sink operation reaches the harness as an error it can handle only in the Go SPI. An in-processapi.Harnesscan handle that error and continue, withinEXE-14(sticky divergence),APR-2(a park answers every later call), andLOG-13(a fenced writer appends nothing more).ControllerFramehas no error reply, so overHarness.Connectthe reference host ends the invocation on any sink error other than an approval park: it returns that error as the run’s result and cancels the stream. The harness’s pending call fails with the stream, nothing it does afterwards is journaled, and the execution fails (EXE-5,EXE-23). The rules below that return an error to the harness, includingEXE-22,EXE-30,TOOL-6, andTOOL-10, therefore fail the execution of a wire harness. An approval park is the exception: the host sendsControllerFrame.park, waits forEVENT_PARKEDand the stream’s close, and the execution ends parked, not failed (APR-3,APR-10).EXE-9: There is no mediated clock or randomness operation. A harness that uses wall-clock time or randomness to decide its actions is not reconstructible; this is a harness obligation (§8.4), not something the host enforces.
8.3 Model calls
Section titled “8.3 Model calls”EXE-10: On the live path the host MUST appendEVENT_MODEL_CALL(withinput_hashand a fresh call id) before invoking the provider, then append the completion asEVENT_OUTPUT. TheOUTPUTcarries no call id; its position after theMODEL_CALLis the correlation.EXE-11:input_hashMUST cover the full model request: model, messages, params, tool definitions, and tool choice. In the reference host it is SHA-256 over the Go JSON encoding ofapi.ModelRequest, with later-added fields omitted when empty so older hashes stay stable. It is host-internal: only the host that wrote it is required to reproduce it.- Open question:
input_hashis not language-neutral. Should it be redefined over canonical bytes (CHAIN-1) so a journal written by one host implementation can be replayed by another? EXE-34: For an invocation with a nonemptyExecutionStart.model, an emptyModelRequest.modelMUST resolve to that recorded default before hashing, journaling and provider dispatch; a nonempty ID is a per-call override. Each live request, including a trailing intent re-driven by Resume, MUST belong to the current configured host allowlist before provider IO. A rejection MUST be execution-fatal even if the harness catches it: no provider call, no newMODEL_CALLappended, no later harness effects, best-effortERRORand noEND. An existing trailingMODEL_CALLintent remains recorded. The reference Sessions API reportsFAILED_PRECONDITION. This fatal rule prevents an unrecorded handled refusal from making a successfully completed execution unreplayable.ERRORstill does not complete a modern invocation (EXE-6); retrying Resume rechecks live requests.EXE-35: Recorded replay/recovery prefixes MUST use the original effective per-call request and hash, independent of today’s allowlist. Completed effects MUST NOT call a provider again. New live effects of a policy-aware invocation face the current policy, if configured. Removing policy removes membership checks, not the invocation’s recorded default. Invocations with an empty recorded default, including markerless journals, retain their old model behavior without default resolution or membership checks. Per-call IDs remain in the existingModelCall.model; its format is unchanged.EXE-12: Model streaming deltas (ExecUpdate.delta) MUST NOT be journaled. Exactly oneEVENT_OUTPUTrecords each finalized completion. Text a harness passes toOutputis not a delta: each call is journaled as its ownEVENT_OUTPUT.
8.4 Determinism invariants
Section titled “8.4 Determinism invariants”These are named in the reference controller. The numbering is the code’s. I0, I1, and
EXE-13 assume a mediated harness; §8.8 states what an unmediated harness gets instead. I3
concerns host-executed tools and applies to both classes.
I0: On reconstruction replay, each model call the harness re-issues MUST have the sameinput_hashas the recordedMODEL_CALLat that position, its output text MUST equal the recordedOUTPUTtext, and reported usage MUST equal the recordedUSAGE(except in the legacy execution,EXE-32). Any mismatch is divergence (ErrReplayDiverged). Recovery checks served effects the same way, except that aREQUIRES_MEMORY_SNAPSHOTrecovery at a decided approval gate starts serving at the gate and does not check the prefix before it (APR-16).I1: Reconstruction replay MUST NOT invoke the model provider or the tool executor. Recorded completions and receipts are served from the log.I3: A host-executed tool intent recorded without a receipt is re-driven on recovery under the same recorded call and idempotency key when its executor declares durable dedup for the tool, and refused otherwise (§9.3).EXE-13: A harness MUST be deterministic given itsStart(config, history, inputs, cursor) and the served model and tool results. A harness MUST replayReasoningPartcontent verbatim. AREQUIRES_MEMORY_SNAPSHOTharness restored at a decided approval gate continues from its restored memory instead and MUST emit the gated call first (APR-16).EXE-14: Divergence MUST be sticky: once detected, every later sink operation in that execution fails with the same error, and the execution fails even if the harness swallowed the error.EXE-15: A reconstruction that consumes fewer recorded effects than the execution recorded MUST fail as divergence.
8.5 Reconstruction replay
Section titled “8.5 Reconstruction replay”EXE-16: Events MUST be grouped into executions byexecution_idin first-seen order. Lifecycle events are skipped. Any other event without anexecution_idafter the legacy prefix (§8.7) is an invalid log.EXE-17: Reconstruction replay re-runs only completed executions and appends nothing. Failed or unfinished executions remain visible in later executions’ history. The legacy execution (§8.7) is the exception: a log that is only a legacy prefix is replayed whole even if unfinished, and a legacy prefix followed by modern executions is replayed up to its lastEND(not at all if it has none; anERRORdoes not count here, unlikeEXE-29).EXE-32defines how the legacy execution is replayed.EXE-18: Before running any harness, reconstruction MUST check the chain (CHAIN-12) and every selected execution’s recorded harness identity (§8.6) and input completeness (§8.6).EXE-19: Inputs, config, andresume_from_seqMUST come from the journal, not from the caller.
8.6 Recovery (Resume)
Section titled “8.6 Recovery (Resume)”EXE-20: Recovery MUST select the latest execution. If the log has no execution (it is empty or holds onlyLIFECYCLErecords) or that execution is complete (EXE-6; for the legacy execution,EXE-29), recovery is a no-op once the chain verifies (CHAIN-12): it performs no harness identity check and noDescribeof its own.Resume’s admission (RT-1) still runs before recovery.EXE-21: Recovery serves recorded effects as in §8.5 until they are exhausted, then switches to the live path for new effects only. The exception is aREQUIRES_MEMORY_SNAPSHOTexecution whose latest gate is decided without a receipt: recovery serves from that gate (APR-16).EXE-22: Model cut rule, outside legacy recovery (EXE-30): if the trailing effect is aMODEL_CALLwith noOUTPUTand the re-issuedinput_hashmatches, recovery MUST invoke the provider once and append theOUTPUTafter the existingMODEL_CALL. A hash mismatch is divergence: the provider is not called and noOUTPUTis appended (the failed run’sEVENT_ERROR,EXE-23, still applies). A non-trailingMODEL_CALLwithoutOUTPUTMUST NOT reach the provider: the re-issued call returns an error to the harness, which is not divergence. The execution fails only if the harness does not handle that error; overHarness.Connectit always fails (EXE-33).EXE-23: Recovery that fails after the harness has started running appends a best-effortEVENT_ERROR; recovery that succeeds appendsEVENT_END. Failures raised before the harness runs (a chain mismatchCHAIN-12, invalid log, incomplete invocationEXE-24, harness identityEXE-25, inherited intentEXE-26, an undeclared trailing tool intentTOOL-10, an unfinished legacy execution without a session uidEXE-30) append nothing. A run stopped after an approval intent is recorded (a park, or a failure recording the approval request or receipt, §10) appends neitherERRORnorEND.EXE-24: Input completeness, for an execution that has anEXECUTION_START: a missing or negativeinput_count, anEVENT_INPUTwith no message, or a count different from the committedEVENT_INPUTrecords is an invalid log for a completed or selected execution. A trailing execution with fewer inputs thaninput_countis incomplete (ErrIncompleteInvocation). Both MUST be raised before the harness runs. An execution without anEXECUTION_START(§8.7) has no completeness check.EXE-25: Harness identity: a non-empty recordedExecutionStart.harnessMUST equal the name the host resolved for this run. A non-empty recordedharness_versionMUST equal the servedHarnessDescriptor.versionexactly, and an empty served version is a mismatch. An empty recorded version imposes no check.EXE-26: Recovery of a fork child MUST refuse an unresolved tool intent copied from before the child’sLIFECYCLE_FORK(ErrInheritedToolIntent,FAILED_PRECONDITION), beforeDescribe, run, or any append.- Open question: The code labels Resume recovery as invariant
I4; docs/architecture.md and docs/concepts.md useI4for “memory restore is not replay” and add anI5. Which numbering is authoritative?
8.7 Legacy journals
Section titled “8.7 Legacy journals”v0.1.x hosts journaled no execution_id and no EXECUTION_START. The reference host reads those
journals by the rules below, which differ from §8.1-§8.6. They also differ from v0.1.x recovery:
v0.1.x Resume treated a turn as complete only when an END followed its last INPUT, so it
re-ran a turn that had ended in ERROR. EXE-29 treats that ERROR as completing the legacy
execution, so Resume is a no-op for it. A harness invocation for a legacy execution
(reconstruction, or recovery of an unfinished one) also needs a session uid (EXE-30, EXE-32
and the wire execution id below), which v0.1.x did not. Resume of a complete legacy execution
invokes no harness and stays a no-op without one.
EXE-27: The records at the start of the log, up to the firstEXECUTION_STARTor the first non-LIFECYCLErecord that carries anexecution_id, MUST be read as one legacy execution if any of them is notLIFECYCLE. OnlyINPUT,MODEL_CALL,OUTPUT,TOOL_CALL,TOOL_RESULT,USAGE,END,ERROR, and interleavedLIFECYCLEare allowed in it; any other kind is an invalid log. A log that holds onlyLIFECYCLErecords has no execution.EXE-28: If the legacy execution’s last non-LIFECYCLErecord is neitherENDnorERROR(an unfinished legacy tail), the record that ends it MUST be anEXECUTION_START; any other record with anexecution_idthere is an invalid log. Reconstruction, recovery, andExecraise it before the harness runs and append nothing;ExecandResumefailFAILED_PRECONDITION. AnEXECUTION_STARTsupersedes an unfinished legacy tail:Execon such a log starts a new execution and never recovers the tail.EXE-29: Recovery selects the legacy execution only when no modern record follows it. For recovery, the legacy execution is complete if it has noINPUT, or if anENDor anERRORfollows its lastINPUT; recovery of a complete legacy execution is a no-op (EXE-20). AnERROR, including one appended by a failed legacy recovery, therefore ends the legacy execution, and a laterResumedoes not retry it.EXE-30: Recovery of an unfinished legacy execution MUST use only its lastINPUTasStart.inputsand every record before thatINPUTasStart.history, with emptyconfigandresume_from_seq0. It serves theMODEL_CALL,OUTPUT,TOOL_CALL, andTOOL_RESULTrecords after thatINPUTas in §8.5 and re-drives or refuses a trailing tool intent (TOOL-10). It differs from modern recovery as follows:- Recorded
USAGEis not an effect. Served completions carry no usage, and a harnessUsagecall is accepted without comparison while recorded effects remain and journaled after they are exhausted. - A trailing
MODEL_CALLwithoutOUTPUTis not re-driven (EXE-22does not apply): the re-issued call returns an error to the harness and the provider is not called. If the run then fails (overHarness.Connectit always does,EXE-33), itsERRORcompletes the legacy execution (EXE-29). - A
REQUIRES_APPROVALtool call that passesAPR-1is refused (ErrInvalidApprovalCall) before any append;APR-2does not apply. - Records it appends carry no
execution_id(EXE-4). - Without a session uid it fails (
ErrMissingSessionUID) before the harness runs and appends nothing.
- Recorded
EXE-32: Reconstruction runs the replayed legacy prefix (EXE-17) as one invocation, as v0.1.x did:Start.inputsis every legacyINPUTin it,Start.historyis that prefix itself, andconfigandresume_from_seqare empty. RecordedUSAGEis neither served nor compared. A legacy log with more than one turn can therefore fail reconstruction as divergence.- The reference host derives a wire execution id for a legacy execution
(
legacy-+ hex SHA-256 over the session uid,seq, and canonical event) and never journals it. Reconstruction derives it from the first legacyINPUT(or the first non-LIFECYCLErecord when there is none); recovery derives it from the lastINPUT, so retries keep the same id. Without a session uid, reconstruction fails like recovery of an unfinished legacy execution (EXE-30). EXE-31: An execution whose records carry anexecution_idbut that has noEXECUTION_START(written by unreleased hosts between v0.1.2 and the start marker) is otherwise a modern execution:EXE-6decides completion and §8.6 applies. It is read with defaults: emptyconfig,resume_from_seq0, no recorded harness identity (EXE-25imposes no check; recovery routes as inOPS-8), and no input-completeness check (EXE-24). AnEXECUTION_STARTthat is not the first record of its execution, or that has no payload, is an invalid log.
8.8 Harness classes
Section titled “8.8 Harness classes”Every harness belongs to one of two classes, set by where its model calls originate. The author
declares the class in HarnessDescriptor.harness_class; the host trusts that declaration because it
cannot observe a model call that does not reach it. HARNESS_CLASS_UNSPECIFIED, omitted by harnesses
from before the field existed, is read as MEDIATED for compatibility. A new harness SHOULD declare
its class. A wire value the host does not understand is not read as MEDIATED: reconstruction replay
fails closed. The class concerns model calls only; tool Mediation (§9.1) is independent of it.
EXE-36: A mediated harness makes every model call through the model call operation (EventSink.Modelin the Go SPI,EVENT_MODEL_CALLon the wire). The host makes the call with a credential it holds and journals it (EXE-10). Rules about model calls elsewhere in this specification describe calls made through the model call operation, by either class.EXE-37: A harness that makes any model call outside the model call operation is unmediated. Those calls originate in its own compute and leave through the runtime’s egress. An agent CLI that calls its provider itself, such as Claude Code, is an example.EXE-38: An unmediated harness MUST declareREQUIRES_MEMORY_SNAPSHOT(§13.1). Its conversation state lives in its compute, and the log, which holds no record of the model calls it makes outside the model call operation, cannot rebuild that state. The reference host rejects an explicitlyUNMEDIATEDdescriptor with any other tier before compute orHarness.Run, and before any record of an execution it would start. An ordinaryAPR-13call-only repair may appendAPPROVAL_REQUESTwithout admission; an override on a memory-capable backend performs the override admission before repair. Admission after a decision still refuses the contradictory descriptor before compute orHarness.Run.EXE-39: An unmediated harness reports what its model produced on a call outside the model call operation through the output, reported tool result (TOOL-2), and usage operations. On the live path the host journals each report as given: noMODEL_CALLprecedes such anOUTPUT, and nothing ties the report to a provider response.EXE-40: The value of the provider credential an unmediated harness uses MUST NOT enter the harness’s compute: not its environment, its filesystem, its memory, or a snapshot of any of them. The harness holds only a placeholder, which the runtime’s egress replaces with the credential on the way to the provider. The host takes no part in that exchange and cannot check it (§17).EXE-41: For each model call it makes outside the model call operation, an unmediated harness gives up what rests on the host making the call. A call it makes through the model call operation is handled as for a mediated harness: the host applies the model policy and journals the call (EXE-10).- Host-bounded spend. For a mediated harness every model call passes through the host, which
applies the model policy (
EXE-34,EXE-35) and is the place a deployment can bound spend; the reference host enforces no call, token, or cost budget. The host neither sees nor limits an unmediated harness’s calls outside the model call operation, and the policy and recorded default do not apply to them. Spend on those calls is bounded only by the harness, the runtime’s egress, and the provider account. - Model-call audit. No
MODEL_CALLorinput_hashis journaled for those calls. The log holds what the harness reported, not what the provider received or returned. - Replay.
I0,I1,EXE-13, and the model cut rule (EXE-22) do not hold for those calls. Reconstruction replay (§8.5) of an unmediated execution is not supported: re-running the harness calls the provider again and diverges (I0) unless the new output repeats the recorded text. The reference controller reads the supplied harness’s current declaration and refusesUNMEDIATEDbefore its first run; omission retains the legacy mediated behavior, so the declaration must be truthful. Reading the log with theReplayRPC and verifying the chain (§7.3) are unaffected.
- Host-bounded spend. For a mediated harness every model call passes through the host, which
applies the model policy (
EXE-42: An unmediated harness MUST NOT continue or re-run an interrupted execution. Recovery (§8.6) re-invokes the harness with that execution’sStart, serves its recorded effects, then goes live (EXE-21); for an unmediated harness the live part calls the provider again and repeats side effects the log does not record. A harness given aStartwhoseexecution_idnames an execution it already started MUST fail the run without calling its model, so the execution stays incomplete (EXE-23), and the caller re-prompts with a newExec(§11.4), which starts a new execution. The exception is an execution the harness left parked at an approval gate: recovery at the decided gate (APR-16) continues it from memory with the gated call, as for anyREQUIRES_MEMORY_SNAPSHOTharness.- Open question: How does an unmediated harness recognize recovery of an execution that its restored
memory holds no record of, and can a session reach that state past
RT-4handRT-4i? EXE-43: Mid-turn memory loss. If an unmediated harness loses its compute, and with it its memory, while an execution runs, thatExecfails: the host journals a best-effortEVENT_ERROR(EXE-5) and does not continue the execution, then or on a laterResume(EXE-42). The user re-prompts. Once the compute that held the memory is gone (RT-4e), or replaced on a backend that recordsComputeInstance(RT-4h, for exampleruntime/substrate), every laterExecandResumeon the session failsFAILED_PRECONDITION, so the re-prompt goes to a new session; the failed session’s log stays readable. When the compute and its memory are known to survive, or preparing the harness Run failed so no execution was recorded (EXE-45), the re-prompt is anExecon the same session. Cancellation after a successful preparation, or a stream failure once sending begins, does not prove that memory survived or that the harness did no work; any recorded attempt remains in later history. An unmediated harness with no state for a session whose history records an earlier execution MUST fail the run as possible state loss rather than start an empty conversation.EXE-44: Wrapper delegation. When a host-side wrapper performs work before delegating to an unmediated harness, a recorded execution that the wrapper positively knows was not delegated MUST be omitted in full fromStart.historyon later calls to that underlying harness. This is a derived inner call: the outer journal and theStart.historythe host sends the wrapper remain unchanged underEXE-7andEXE-17. Absence of an event emitted by the underlying harness is not proof that delegation did not occur: it may have changed memory or called its provider before emitting one. If delegation or delivery is uncertain, the wrapper MUST retain the execution.- Open question: How long does a reference substrate
Exectake to fail after the session’s actor dies mid-turn, and is the failure the stream’s end or a router timeout?
9. Tool execution and receipts
Section titled “9. Tool execution and receipts”9.1 Modes
Section titled “9.1 Modes”Mediation |
Who executes | What the host records |
|---|---|---|
MEDIATION_CONTROLLER_MEDIATED |
host executor | TOOL_CALL intent, then TOOL_RESULT receipt |
MEDIATION_REQUIRES_APPROVAL |
host executor, after a decision | TOOL_CALL, APPROVAL_REQUEST, decision, receipt (§10) |
MEDIATION_IN_HARNESS_REPORTED |
harness | TOOL_RESULT only, as reported |
TOOL-1: The tool-call effect MUST accept onlyCONTROLLER_MEDIATEDandREQUIRES_APPROVAL.UNSPECIFIED,IN_HARNESS_REPORTED, or an unknown value MUST be rejected (ErrUnmediatedToolCall) before anything is recorded. There is no defaulting of an unset mediation.TOOL-2: A harness that executes a tool itself MUST report the result asEVENT_TOOL_RESULT(Reportin the Go SPI). The host appends it as given, records no intent, and sends no reply.TOOL-3: A reported result MUST NOT carry approval sequence numbers and itscodeMUST beCODE_UNSPECIFIEDorEXECUTOR_ERROR; it MUST NOT target an approval-gated call id.
9.2 Host-executed tools
Section titled “9.2 Host-executed tools”TOOL-4: A host-executed call MUST carry a non-emptyidempotency_key. A call without one MUST be rejected (ErrMissingIdempotencyKey) beforeTOOL_CALLis recorded.TOOL-5: The host MUST appendTOOL_CALL, then call the executor with the session uid as scope, then appendTOOL_RESULTwithidset to the call id. A host MUST NOT run a tool executor without a non-empty session uid.TOOL-6: For an ordinary host-executed call, an executor that returns a transport error leaves the intent without a receipt; the error is returned to the harness (overHarness.Connectit ends the invocation,EXE-33) and noTOOL_RESULTis written. An approvedREQUIRES_APPROVALcall is different: an executor error becomes a durable receipt withcode = EXECUTOR_ERRORandis_errorset (§10), unless the host ended the recovery (APR-14). A refusal from the host’s pre-dispatch policy hook is not an executor error (§9.4).- A reference host with no tool executor configured records
TOOL_CALL, then fails the call (“no tool executor configured”) and the execution ends withEVENT_ERROR. The intent stays without a receipt, as inTOOL-6. TOOL-7: An ordinary receipt MUST NOT carry approval fields, and its code MUST beCODE_UNSPECIFIEDorEXECUTOR_ERROR, orPOLICY_DENIEDwithis_errorset when the host wrote it (TOOL-16).
9.3 At-most-once and re-drive
Section titled “9.3 At-most-once and re-drive”TOOL-8: On reconstruction or recovery, a re-issued call MUST match the recordedTOOL_CALLinid, tool name, mediation,idempotency_key, and normalized args, or fail as divergence before any effect. Args the journal form cannot represent are divergence.TOOL-9: A recorded call with a receipt MUST be answered from the receipt; the executor MUST NOT be called. A receipt whoseiddiffers from the call is divergence.TOOL-10: A trailing host-executedTOOL_CALLwithout a receipt, other than an approval-gated call (§10.4), MUST be re-driven on recovery with the recorded call (sameidempotency_key) and the same session uid only when the executor declares durable dedup for that tool (TOOL-11). Otherwise recovery MUST refuse it (ErrUnansweredToolCall,FAILED_PRECONDITION: “tool call has no recorded result; repeating it could repeat the action”) after the chain check (CHAIN-12) andEXE-26and before the controller’s ownDescribe, run, or any journal append, so a later recovery with a declaring executor can still re-drive it. A journal that failsCHAIN-12is refused as tampered whether or not the tool is declared, and its call is never re-driven. A host may act before that refusal without appending: the referenceplacement.Placer.Resumeadmits through the backend’sDescribe, restores compute, and mayDescribea connected harness first. The reference host declares per tool name (controller.WithDurableDedup,placement.WithDurableDedup); the stock daemon declares itsdurable_dedup: trueroutes and the tools it refuses before dialing (tool executors). With no executor configured it does not refuse: the re-issued call fails as on the live path (§9.2). A non-trailingTOOL_CALLwithout a receipt MUST NOT be re-executed: the re-issued call returns an error to the harness, which is not divergence. The execution fails only if the harness does not handle that error; an in-process harness that handled it originally can continue and complete. OverHarness.Connectthe execution fails (EXE-33).TOOL-11: An executor that declares durable dedup for a tool MUST deduplicate its calls on (session uid,idempotency_key) and MUST NOT repeat the external effect for a key it has already applied, or the tool MUST be safe to repeat (read-only or naturally idempotent). The host re-drives on every recovery that finds a declared intent unresolved, so at-most-once holds only if the declaration is true. First attempts and served receipts do not consult the declaration.TOOL-12:idempotency_keyis unique only within a session. Inherited intents across a fork are refused (EXE-26) rather than re-driven in the child.IN_HARNESS_REPORTEDtools have no intent record and therefore no host re-drive or at-most-once guarantee. On reconstruction a reported result consumes the next recordedTOOL_RESULTwithout comparing its content.- Open question: Should reconstruction compare a re-reported
IN_HARNESS_REPORTEDresult with the recorded one, as it does for output text?
9.4 Pre-dispatch policy
Section titled “9.4 Pre-dispatch policy”TOOL-13: A host MAY install a pre-dispatch policy hook (controller.WithToolPolicyorplacement.WithToolPolicyin the reference host). Without one, dispatch is unchanged. The hook runs on every executor dispatch, after the host’s own checks and right before the executor: for an ordinary host-executed call after itsTOOL_CALLis appended, live or re-driven (TOOL-10), and for an approvedREQUIRES_APPROVALcall after theAPR-14hash check. It does not run for a denied decision, a call answered from its receipt (TOOL-9), reconstruction replay, a reported result, or a host with no executor. Its input is the session uid, the execution id, a copy of the call in its journaled form, the verified caller of theExecorResumethat dispatches the call (empty when authentication is off, §17), and, for an approved call, the committed decision, including itsverified_approver(APR-8), and its sequence. The hook is host code, not a harness, soAPR-8’s clearing does not apply to it. It does not receive the decision’sEvent.actor, which is caller-supplied. The hook MUST NOT be able to change the call it judges: the reference host rebuilds the arguments from the JSON form theTOOL_CALLrecords. Without asking the hook, it refuses as a transient refusal (TOOL-15) a call whose arguments that form cannot represent, and a call whose arguments that form changes, read as the host’s typed values or as their JSON encoding: an integer with more than 53 significant bits, such as 2^53+1, however it is spelled; a decimal number below 2^53 whose value differs from the shortest JSON text of the 64-bit float the form records, such as0.30000000000000001recorded as 0.3; a 32-bit float whose JSON text reads as a different 64-bit number, such as 1e20; or a string that is not valid UTF-8. The hook would judge one value while the executor receives another. It does not refuse another spelling of the recorded value, such as3e-1for 0.3, or a nil list or map recorded as an empty one. It also refuses a value it cannot compare with that form: a Go struct that its JSON encoder writes field by field, and a value or non-string map key whose type supplies its own encoding (a GoMarshalJSONorMarshalTextmethod, astime.Timeandbig.Intdo), since the form records only that encoding while the executor receives the typed value. Below 2^53 in magnitude, a hook compares a 64-bit float argument as its JSON value, the shortest decimal that reads back as that float (Go’sstrconv.FormatFloat(f, 'g', -1, 64)), not as its exact binary expansion. At or above 2^53 every such float is an integer and the host dispatches only an argument with exactly that value, so the hook reads it exactly: 2^60 is 1152921504606846976, not the 1152921504606847000 its shortest text gives.TOOL-14: The hook returns allow, a transient refusal, or a definitive refusal. Allow calls the executor as if no hook were installed. The reference host treats a verdict it does not know, including an unset one, as a transient refusal. This specification defines no policy language.TOOL-15: A transient refusal (a credential refresh failed, a provider is down) MUST NOT call the executor and MUST NOT write a receipt. On an ordinary call it is handled as an executor transport error (TOOL-6): the error goes to the harness and the intent stays without a receipt, so recovery re-drives it only underTOOL-10; if the refusal ends the execution, the reference service reportsFAILED_PRECONDITION. On an approved call it is an exception toAPR-14: the host writes no receipt,ERRORorEND, the decision stays recoverable, and the call fails withFAILED_PRECONDITION(controller.ErrToolPolicyRefused), as for a missing executor. The next recovery asks the hook again.TOOL-16: A definitive refusal (a grant was revoked, policy says no) MUST NOT call the executor and MUST append aTOOL_RESULTreceipt with the call id,code = POLICY_DENIEDandis_errorset; on an approved call it also carries the approval sequences (APR-12). The reference host setscontentto the fixed text “Tool execution refused by host policy.” and puts the hook’s reason inerror, which is journaled and sent to the harness, so the reason must not carry secrets. The receipt is returned to the harness as a result, not an error, and later recovery and replay serve it (TOOL-9) without asking the hook or calling the executor. Only the host writesPOLICY_DENIED: an executor result or a harness report carrying it MUST be rejected (ErrApprovalReceiptReport) before any receipt is written, at both dispatch sites, and MUST NOT be rewritten to another code. On an ordinary call the error goes to the harness as forTOOL-6. On an approved call the host writes no receipt,ERRORorENDfor that result, the call fails withFAILED_PRECONDITION, and the decision stays recoverable: the next recovery calls the executor again under the same key, so an executor that applied the effect before returning the code must deduplicate on that key (TOOL-11) or the effect can repeat.
10. Approvals
Section titled “10. Approvals”10.1 Gate
Section titled “10.1 Gate”APR-1: The approval gate applies toSTATELESS_REPLAYandREQUIRES_MEMORY_SNAPSHOTharnesses. AREQUIRES_APPROVALcall from an in-process harness that declares any other tier, including none (the empty Go value), MUST be refused before an effect (ErrApprovalUnavailable), and so MUST recovery or reconstruction of an execution holding an approval record. A wire harness that omits its tier or sends an unknown one is read asSTATELESS_REPLAY(WIRE-3), so its call gets the gate.APR-2: A liveREQUIRES_APPROVALcall MUST have a non-empty, unused call id and a non-emptyidempotency_key. The host MUST appendTOOL_CALL, thenAPPROVAL_REQUEST{tool_call_id}, then park the execution. Every later sink call in that execution returns the park.APR-3: A parked execution MUST append neitherEVENT_ENDnorEVENT_ERROR. The host then closes the harness connection, takes an external snapshot (§13.3), and appendsLIFECYCLE_SUSPENDunder the execution’s fence before reporting success.APR-4: Only the host MAY writeAPPROVAL_REQUESTandAPPROVAL_RESULT. A harness that emits either, orEXECUTION_START, or an unsolicitedEVENT_PARKED, MUST fail the execution.
10.2 Decisions
Section titled “10.2 Decisions”APR-5:ApproveMUST beINVALID_ARGUMENTwhensession,execution_id, ortool_call_idis empty,request_seq <= 0, orapprovedis absent. An unknown session isNOT_FOUND. Opt-in authorization (§17) precedes validation and hides inaccessible sessions asPERMISSION_DENIED, subject to the earlier deletion exclusion (OPS-30).APR-6: A decision MUST target the selected request: the last gated call of the latest execution, owned by this session (not copied before aLIFECYCLE_FORK), not completed, and without a receipt. OtherwiseFAILED_PRECONDITION.APR-7: An exact retry (same tuple,approved,reason, identity, and verified approver) MUST return the existingAPPROVAL_RESULTrecord and append nothing, even after resolution, unless the session is deleted (OPS-34). A changed decision MUST beFAILED_PRECONDITIONand never overwrites. The verified approver is compared exactly, issuer and subject, so the same tuple from a different verified caller is a changed decision, as is an authenticated retry of a decision recorded without an approver, or an unauthenticated retry of one recorded with an approver.APR-8: A new decision MUST mint a fence and appendAPPROVAL_RESULT{tool_call_id, approved, reason, request_seq, verified_approver}withEvent.actorset from the request’s identity, at the head observed when the request was selected.verified_approveris the issuer and subject the host’s caller authentication verified for thisApprovecall (Goauthn.Caller), and MUST NOT be taken from any request field; it is empty when the host did not authenticate the caller, and the host MUST NOT append one with only issuer or only subject. An opt-in enforcing Go service (§17) ignores the request actor, normalizing it to empty before append and retry comparison.verified_approveris audit state that no harness receives: the host leaves it empty inControllerFrame.approval(APR-11), in the decision a Go harness receives with a receipt, and in everyAPPROVAL_RESULTit sends inStart.history(EXE-7) onExec,Resumeand replay. The journaled record keeps it.APR-9:ApproveMUST NOT resume compute or call the executor. The caller callsResume.- No expiry or automatic decision applies, and the optional pre-dispatch policy hook (§9.4) runs
when recovery dispatches the call, not at
Approve. The default service has no decision authorization; an enforcing Go service requires independent read and approve permissions.
10.3 Wire handshake
Section titled “10.3 Wire handshake”APR-10: While a request is unresolved, the host sendsControllerFrame.parkwith theApprovalRef. The harness MUST check the session, execution, call, andrequest_seq > 0, stop the run, send exactly one matchingEVENT_PARKED, and close its sending side withoutEVENT_END. The host MUST treat anything else as a failed exchange; the durable request remains recoverable.APR-11: On decided recovery or replay, the host MUST sendControllerFrame.approvalbefore the correlatedControllerFrame.toolreceipt, even when the receipt already exists.APR-12: Receipt rules, enforced by both sides:approval_request_seqequals the decision’srequest_seq, andapproval_decision_seq > 0identifies the committed decision in the same session;- a denial is
APPROVAL_DENIEDorNOT_EXECUTEDwithis_error = true, and the executor MUST NOT have been called; - an approval is
CODE_UNSPECIFIEDwithis_error = false,EXECUTOR_ERRORwithis_error = true,POLICY_DENIEDwithis_error = true, in which case the executor MUST NOT have been called (TOOL-16), orOUTCOME_UNKNOWNwithis_error = true, which makes no claim about the executor (APR-18). - Only
CloseApprovalwritesNOT_EXECUTEDandOUTCOME_UNKNOWN(APR-18). A harness report carrying either, and an executor result carrying either for an ordinary host-executed call, MUST be rejected (ErrApprovalReceiptReport) before any receipt is written, and a host MUST NOT relay either as the reply to an ordinary call. An executor result carrying either for an approved call, whatever itsis_error, is an executor failure and becomes anEXECUTOR_ERRORreceipt withis_error = true(APR-14), so a close code never comes from an executor.
10.4 Recovery
Section titled “10.4 Recovery”APR-13:Resume(or input-lessExec, §11.4) on an owned gate with no decision MUST return the current session without runtime IO. If onlyTOOL_CALLwas committed before a crash, the host MUST first mint a fence and append the missingAPPROVAL_REQUEST. When that turn ran on an override (OPS-7) and its backend hasmemory_snapshot, the host first runs admission (RT-1) on the override’s harness, before the fence: an admission error fails the call, and aREQUIRES_MEMORY_SNAPSHOTharness isFAILED_PRECONDITION.APR-14: After a decision, recovery MUST use the recorded invocation (harness, config, inputs, cursor) and snapshot reference. A denial writes anAPPROVAL_DENIEDreceipt without calling the executor. An approval calls the executor with the recorded call, whether or not the executor declares durable dedup for the tool (TOOL-10does not apply); an executor failure becomes a durableEXECUTOR_ERRORreceipt. An executor result carryingPOLICY_DENIEDis not an executor failure: it is rejected without a receipt (TOOL-16). The pre-dispatch policy hook, if one is installed, runs after the hash check below and before the executor (§9.4). The decision binds that call through the chain: itsrequest_seqnames the request that follows the call’sTOOL_CALLrecord, whosecontent_hashcovers the canonical args. Before calling the executor, the host MUST recompute thatcontent_hashover the call it is about to send and, on a mismatch, call nothing, write no receipt and fail as a chain failure (CHAIN-12,DATA_LOSS). When the executor fails with an error instead of a result, the reference host sets the receipt’scontentto the fixed text “Tool execution failed.” and keeps the error text inerror; a result the executor returns withis_error = truekeeps thecontentit returned. A result carrying a close code withis_error = falseclaimed success, so the reference host discards it as it does a failed call’s partial result: the receipt’scontentis the same fixed text and itserroris the result’serror, or the fixed text “tool executor returned a result code only the host writes” when that is empty (APR-12); no other field of that result is kept. An error the host caused by ending the recovery is not an executor failure: either the context the recovery runs under is done and the executor returned that context’s error, or that context’s deadline has passed and the executor returned a deadline error (a deadline enforced by I/O can surface just before the context reports it). The host MUST NOT write a receipt,ERRORorENDfor it, and returns the context error, so the decision stays recoverable as after a crash and the next recovery calls the executor again with the recorded call. The host decides by the recovery context’s state when the executor returns, not by which context ended the call, and matches the error by kind. An error returned while the recovery context is live and before its deadline MUST become anEXECUTOR_ERRORreceipt, including the error from cancelling a context the harness narrowed for that one call (api.Harness) or from its deadline. A cancellation error returned after the recovery context was cancelled, or a deadline error returned after its deadline passed, MUST NOT be receipted, even when that per-call deadline expired first. Any other error MUST become anEXECUTOR_ERRORreceipt, including one unrelated to either context returned after the recovery ended. A missing executor isFAILED_PRECONDITIONand leaves the decision recoverable. A transient policy refusal (TOOL-15) and an executor result carryingPOLICY_DENIED(TOOL-16) are the exceptions to the receipt rules above: each isFAILED_PRECONDITION, writes no receipt and leaves the decision recoverable. A definitive policy refusal writes aPOLICY_DENIEDreceipt instead of calling the executor (TOOL-16).APR-15: An inherited unresolved gate (copied by a fork) MUST be refused withFAILED_PRECONDITION. A reference inherited through fork cannot authorize an effect in the child.APR-16: AREQUIRES_MEMORY_SNAPSHOTharness restored at a decided gate continues from memory and does not re-emit the execution’s prefix. When the latest execution’s selected gate is decided without a receipt, recovery of such a harness MUST serve from that gate’sTOOL_CALL, not from the execution’s first effect (EXE-21), and is otherwise unchanged:- The gate’s
TOOL_CALL,APPROVAL_REQUESTandAPPROVAL_RESULTMUST be the last effects of the execution (ERRORis not an effect); otherwise the log is invalid and recovery fails before the harness runs. - The harness’s first sink call MUST be the gated call, matched as in
TOOL-8(id, name, args, mediation, key). Any other first call, or a run that succeeds without one, is divergence (ErrReplayDiverged,EXE-14): no receipt is written, oneERRORis appended, and the decision stays recoverable. A run that fails before any sink call keeps its own error. - A denial returns the
APPROVAL_DENIEDreceipt without calling the executor; an approval is host executed (APR-14). Later effects take the live path. - Call ids recorded before the gate stay used (
APR-2,TOOL-3) although they are not served. - Legacy executions, a gate that already has its receipt, and reconstruction replay serve from
the first effect as before; a memory-tier harness has no recovery path for a receipted gate
whose execution has no
END.
- The gate’s
- Requests and snapshots are retained indefinitely.
10.5 Close
Section titled “10.5 Close”CloseApproval lets the session owner end a gate the harness can no longer re-issue (its code
changed, or the turn is abandoned), so the session can take a new turn (OPS-14). It writes host
records only.
-
APR-17:CloseApprovalMUST beINVALID_ARGUMENTwhensession,execution_id, ortool_call_idis empty orrequest_seq <= 0. An unknown session isNOT_FOUND. Opt-in authorization (§17) precedes validation as forAPR-5, checking read and thenapproval.close. The tuple MUST name a journaledAPPROVAL_REQUESTthe session owns; a tuple that names none (including a call-only cut,APR-13), an inherited request (APR-15), or, when the call has no receipt, a request that is not the selected one (APR-6) isFAILED_PRECONDITION, as is a deleted session, even for a retry (OPS-34). A journal that fails hash-chain verification isDATA_LOSS(CHAIN-12). Contention (OPS-1,OPS-2), an append CAS conflict, or a superseded fence isABORTED. None of these writes anything. -
APR-18: When the call already has a receipt, from any writer and with any code, the host MUST return itsAPPROVAL_RESULTandTOOL_RESULTrecords, minting no fence and appending nothing, so a retry returns the first close’s records. Otherwise it MUST mint one fence and append, starting at the head it read when it selected the gate:- undecided:
APPROVAL_RESULT{tool_call_id, approved = false, reason = "approval closed", request_seq, verified_approver}, withverified_approverset from the caller asAPR-8defines it andEvent.actorempty, then, after that record, aNOT_EXECUTEDreceipt; - denied: a
NOT_EXECUTEDreceipt; - approved: an
OUTCOME_UNKNOWNreceipt. The journal cannot prove the executor never ran (a cancelled recovery, a crash after dispatch, another host’s recovery in flight), so the receipt makes no claim either way. It revokes the approval for later recovery but cannot stop a call another host has already dispatched; that host’s receipt append then fails (LOG-13).
Each receipt carries the call id,
approval_request_seq,approval_decision_seqandis_error = true. The reference host setscontentanderrorto the fixed text “Tool call was closed without running.” (NOT_EXECUTED) or “Tool call was closed; whether it ran is unknown.” (OUTCOME_UNKNOWN). The fixed reason marks a host close in the audit record; anApprovedenial that supplies the same reason cannot be told apart from one. A denied or approved close writes only aTOOL_RESULT, which has no identity field, so the journal does not record who closed it. If the undecided case’s receipt append fails after its denial committed, the gate is denied: a retry writes theNOT_EXECUTEDreceipt, or returns theAPPROVAL_DENIEDreceipt a recovery wrote in the meantime. After a close,Approveof the gate isFAILED_PRECONDITIONunless it is an exact retry of the recorded decision (APR-7).CloseApprovalMUST NOT call the executor, the pre-dispatch policy hook (§9.4), a harness, or the runtime. - undecided:
-
APR-19: After a close the call has a receipt, soExecwith inputs MUST be admitted (OPS-14). The host appends noEVENT_ENDfor the closed execution, soResumeor input-lessExecre-drives it: a harness that re-issues the call is served the decision and receipt (APR-11) and can finish the turn; a harness that diverges fails that recovery (ErrReplayDiverged) andExecstays admitted. AREQUIRES_MEMORY_SNAPSHOTharness restored at the gate is the exception (APR-16): recovery serves it from the execution’s first effect, so unless the gate is that effect, its re-issued call is refused (normallyErrApprovalUnavailable), that recovery fails and leaves the receipt, andExecwith inputs is the session’s route.CloseApprovaldoes not resume compute; the caller callsExecorResume. Open question: Should a close also end the closed execution withEVENT_ENDorEVENT_ERROR?
11. Session lifecycle operations
Section titled “11. Session lifecycle operations”11.1 Concurrency
Section titled “11.1 Concurrency”OPS-1: A host MUST serialize, per session,Exec,Resume,Suspend,Approve, andCloseApproval. An overlapping call MUST fail withABORTEDwithout changing compute or the journal. The reference guard is non-blocking.OPS-30: A host MUST also excludeDeleteSessionfrom each of those operations and from aForkof the same session, both ways: the call that arrives second failsABORTEDwithout writing. In the reference host the exclusion is perRegistry(one host). ForExec,Resume,Suspend,Approve, andCloseApprovalit covers two phases: the session lookup and routing, and the guarded operation (OPS-1). A deletion can commit between the two;OPS-34covers that case. ForForkit covers the lookup, and separately the fan-out until it ends, including any rollback (OPS-27). A deletion can commit after the fan-out ends, while the host records the children’s metadata. The children still stand, because the fan-out completed before the deletion; the fork returns them if those later metadata writes succeed. Lookup phases andForkdo not exclude each other or the operations inOPS-1.DeleteSessionneither waits for nor cancels the holder; the caller retries.OPS-2: A per-session checkpoint mark MUST be held bySuspend,Approve,CloseApproval, an approval park handoff, a cursor-checkedResumewhile it mints each fence and re-reads the head (OPS-29), and aREQUIRES_MEMORY_SNAPSHOTfork from checkpoint until its last child is cloned. A second checkpoint holder MUST fail withABORTED.ExecandResumeduring a checkpoint MUST fail withABORTEDunless a check the host runs before the mark check fails or answers the call. The reference host checks the mark only after the session guard (OPS-1), the deletion check (OPS-34), the request and harness checks (§11.3), the approval-state checks (APR-13,APR-15,OPS-14), admission (RT-1) and, onResume, the head check (OPS-29) and the snapshot lookup; an error from those is returned instead ofABORTED. AResumeor input-lessExecon an owned gate with no decision (APR-13) is answered before the check. Its call-only repair takes the mark only for aResumewithexpected_last_seqset (OPS-29); otherwise it can appendAPPROVAL_REQUESTunder a new fence during a checkpoint. Open question: Should the call-only approval repair refuse withABORTEDduring a checkpoint?OPS-3: AREQUIRES_MEMORY_SNAPSHOTfork MUST end any in-flight execution on the parent; that execution fails withABORTED.CreateSession,GetSession,ListSessions, andReplaytake no guard.Fork(either tier) does not take theOPS-1session guard, only the deletion exclusion (OPS-30). AREQUIRES_MEMORY_SNAPSHOTfork holds the checkpoint mark instead (OPS-2).
11.2 Create, Get, List
Section titled “11.2 Create, Get, List”- See §5.
GetSessionwith an emptyuidisINVALID_ARGUMENT; an unknownuidisNOT_FOUND. A deleted session is returned (SES-14) and is not listed (SES-9). OPS-4:CreateSessionwith a harness the host does not know isINVALID_ARGUMENT. A known but unservable registered harness isFAILED_PRECONDITION, refused when the name is resolved, before the insert. A retired registered harness, or a static harness name that also has a registration row, isFAILED_PRECONDITION, checked in the same transaction as the insert.
11.3 Harness selection
Section titled “11.3 Harness selection”OPS-5:ExecRequest.harnessempty selects the session’s stored harness. A different name runs that execution only; the stored harness does not change, andEXECUTION_START.harnessrecords the resolved name.OPS-6: If either the stored harness or the override is a registered harness (§14), a differing override MUST beFAILED_PRECONDITION(the session is pinned). This check runs before the override is resolved.OPS-7: An override that resolves to another registry entry than the session’s stored harness MUST beFAILED_PRECONDITION(placement.ErrStatefulOverride) when either harness isREQUIRES_MEMORY_SNAPSHOT, before any compute is provisioned, fence minted, or record written.SuspendandForkfollow the stored harness, so they would not checkpoint or clone a memory-tier override’s memory, and parking only an override cannot checkpoint a memory-tier stored harness. An alias of the stored harness’s entry is not an override. The reference host checks the stored harness’s half while routing, byDescribeon the stored harness when its runtime hasmemory_snapshot, and the override’s half on the descriptor admission reads (RT-1), again on the turn’s connection for a live-describing backend (RT-3). Recovery of a turn recorded on an override (OPS-8) applies both halves.OPS-8: Recovery (Resume, input-lessExecrecovery) MUST route by the recordedEXECUTION_START.harness. A recorded name the host does not serve isFAILED_PRECONDITION, with no fallback. With no recorded name (a legacy or markerless execution, §8.7; an emptyharness; or a journal with nothing to recover),Resumeroutes to the session’s stored harness, or to the host’s default when the session has none.
11.4 Exec
Section titled “11.4 Exec”OPS-9: An emptyExecRequest.sessionMUST create a session first (asCreateSessionwith onlyharnessset) and run against it.OPS-10: An unknown session isNOT_FOUND, except that a non-empty harness override on an unknown session is checked first: an unknown name isINVALID_ARGUMENTand a known but unservable registered harness isFAILED_PRECONDITION.OPS-11: The first frame of a stream that sends any frame MUST beExecUpdate.sessionwith the session as it was before the turn. Committed records and deltas follow. A caller MUST read the stream to completion. Whether an error arrives before or after that frame depends on the path:- Both paths: an overlap with
DeleteSession(OPS-30,ABORTED) and a session deleted before the lookup (OPS-34,FAILED_PRECONDITION) end the stream with no frame. A deletion that commits after the lookup fails the call after the frame (OPS-34). - Ordinary execution: the host resolves the session and routes the harness before the frame.
Auto-create failure, an approval-inspection failure, the approval block (
OPS-14), every session lookup or routing error, a journal head read failure, and a failure to materialize the session for the frame end the stream with no frame. Routing errors include an unknown session or harness (OPS-10), the pin (OPS-6), and the stored harness’s half of the memory-tier override check (OPS-7), which runsDescribeon the stored harness and can failUNAVAILABLE,FAILED_PRECONDITION, or with a context error. Placement admission (RT-1:Describe, descriptor id,CanPlace, and the override’s half ofOPS-7), the chain check (CHAIN-12),expected_last_seq(OPS-13), and the run itself fail after the frame. - Input-less approval recovery (
OPS-14): only the session lookup, the approval inspection, the journal head read, and materializing the session for the frame precede it. Routing by the recorded harness (OPS-8), the pin, the memory-tier override check, the deadline,expected_last_seq, and recovery itself fail after the frame.
- Both paths: an overlap with
OPS-12: On an approval park or input-less recovery, the host MUST send a finalExecUpdate.sessionframe with the latest cursor andpending_approvalbefore closing the stream with OK. A park is not a terminalENDorERROR.OPS-13:expected_last_seqhas explicit presence. When set (including 0, which asserts an empty log), theEXECUTION_STARTappend MUST use it as the compare-and-swap cursor; a mismatch isABORTED. When unset, the host uses the head it read when it accepted the request, so an append by another writer between that read andEXECUTION_STARTis stillABORTED.- On an ordinary execution, the reference host checks
expected_last_seqtwice: under the session guard after admission and before runtime creation, so a cursor that is already stale creates no compute and the message names both values, and again at the append, after runtime creation,Describe, and fence minting. On the input-less approval recovery path it is checked under the session guard before runtime IO or repair. OPS-14: While the session owns an approval call without a receipt,Execwith inputs MUST beFAILED_PRECONDITION, including after a decision.Execwithout inputs on a current, non-terminal approval-bearing execution MUST recover it via the recorded invocation (§10.4) without a newEXECUTION_START; requestharness,config, andresume_from_seqare ignored. Other input-lessExeccalls start a new execution.OPS-15:configbytes and a non-zeroresume_from_seqMUST be journaled inEXECUTION_STARTbefore the harness runs.configis durable and exposed byReplay; it MUST NOT carry credentials. The host does not interpretresume_from_seq.OPS-16:deadline_unix > 0bounds the execution. A deadline that expires during admission isDEADLINE_EXCEEDED.
11.5 Suspend
Section titled “11.5 Suspend”OPS-17:SuspendMUST call the runtime’sSnapshot(EXTERNAL), then mint a fence and appendLIFECYCLE_SUSPENDcarrying the returnedSnapshotRefat the current head. It takes no caller cursor.compute_statebecomesCOMPUTE_COLD.OPS-18:Suspendroutes to the stored harness, except that an owned unreceipted approval routes to its recorded harness (OPS-8).- The reference host accepts
Suspendon a session that is already cold or has never run, and appends anotherSUSPEND.Resumewithout a priorSuspendis also accepted. The host does not check either case itself; whether the call succeeds is up to the backend (RT-4b,RT-4c). Withruntime/localandruntime/remoteboth succeed. Withruntime/substrate, both fail when no actor exists for the session uid, for example a fresh session before anyCreatereachedCreateActor(a fork child gets its actor fromFork):SuspendActorandResumeActorreturnNOT_FOUNDand no marker is appended. For aREQUIRES_MEMORY_SNAPSHOTharness the backend reports that asapi.ErrMemoryStateLost, which the reference session service reports asFAILED_PRECONDITION; for aSTATELESS_REPLAYharness the service reportsINTERNAL(§13.4). A failedExecdoes not imply that case: whenCreatesucceeded and the dial or turn failed, orCreateActorsucceeded andCreate’sResumeActorfailed, the actor remains, since the host calls noStop(RT-7), and a laterSuspendorResumereaches it. WhenCreatesucceeded,runtime/substratehas noapi.CleanupRuntime, so unless the journal owns the actor, the error is aplacement.ComputeLeftRunningErrornaming the actor (RT-7). A partialCreate(CreateActorsucceeded,ResumeActorfailed) returns no incarnation, so the host has no actor to report: theExecerror is not aplacement.ComputeLeftRunningError, and nothing reports the actor left behind. The neutralagentsessionsdbuilds no substrate placement. Its substrate build (integrations/substrate/cmd/agentsessionsd) serves one static-substrate-harness; neither build accepts a registeredsubstrateplacement (REG-2a). - Open question: Should a repeated
Suspend, orResumewithout a priorSuspend, be refused or be a no-op? Current behavior appends a marker each time the backend call succeeds, and no test pins it.
11.6 Resume
Section titled “11.6 Resume”OPS-19:ResumeMUST, in order: admit the harness (§13.2), restore from this session’s own latestSUSPENDsnapshot reference (one inherited from a parent is skipped; with none, it uses{local: uid}), open the harness client, mint a fence, run recovery (§8.6), and appendLIFECYCLE_RESUMEat the current head. A cursor-checkedResume(OPS-29) also mints an early fence after admission and before restore.OPS-20:ResumeRequest.bootis deprecated and ignored.OPS-29:ResumeRequest.expected_last_seqhas explicit presence. When unset,Resumeperforms no cursor check. When set (0 asserts an empty journal), the host MUST compare it with the journal head and fail withABORTEDon a mismatch; the reference host’s message names both values. The comparison runs at each of these points that the call reaches:- under the session guard, before approval inspection, harness resolution, and invocation
validation, so a moved head is reported ahead of
EXE-24,EXE-26, and routing errors; - after the fence minted for an approval repair (
APR-13), before the missingAPPROVAL_REQUESTis appended; an undecided approval whose request is committed needs no fence and gets only the first check; - after an early fence minted after admission and before restore;
- after the turn’s regular fence, minted once the harness client is open, before the harness runs.
- under the session guard, before approval inspection, harness resolution, and invocation
validation, so a moved head is reported ahead of
- A refusal at the first check mints no fence and performs no runtime IO. A refusal after a fence
leaves that fence minted, so older writers are superseded (
LOG-12) even thoughResumerefused. A refusal at the last check may already have restored compute, but the harness does not run and nothing is appended. expected_last_seqis not an execution lease and does not make tool execution exactly-once: it cannot cancel effects already in flight, and a later writer can still supersede theResume.- Approval cases are in §10.4.
11.7 Fork
Section titled “11.7 Fork”OPS-21: AForkRequest.identitythat is present, including an empty message, MUST beINVALID_ARGUMENTbefore any other check or side effect.OPS-22:count > 128MUST beINVALID_ARGUMENT.count <= 0is treated as 1.child_namesMUST have 0 or exactlycountentries, elseINVALID_ARGUMENT.OPS-23:at_seq <= 0selects the head.OPS-24:STATELESS_REPLAYfork: the parent is untouched. Per child, the host callsRuntime.Forkwith{local: parent uid}, copies the parent’s records1..at_seq(CHAIN-8) under a new child fence, and appendsLIFECYCLE_FORK. The child’scompute_stateisCOMPUTE_COLD.OPS-25:REQUIRES_MEMORY_SNAPSHOTfork:at_seqother than the head MUST beFAILED_PRECONDITIONbefore any side effect. The host then takes the checkpoint mark, fences the parent, ends its open streams, re-checks the head (moved isABORTED), snapshots once, appendsSUSPENDto the parent with compare-and-swap atat_seq, and clones every child from that one snapshot. A snapshot without an external handle isFAILED_PRECONDITION; the parent’sSUSPENDremains committed.OPS-26: Children inheritproject,harness,model,annotations, andorigin.labelscome from the request only (never merged).nameischild_names[i]or empty.identityis unset.parent_uidandfork_seqrecord lineage. Children are returned in creation order.OPS-27: If the fan-out fails, the host MUST callRuntime.Stopbest-effort on each child it provisioned and return the mapped error.- Open question: A failed fork can leave child journal rows that list in the default project, and a
stateless fork with
at_seqabove the head records the requestedfork_seqwhile copying only to the head. Should fork be all-or-nothing in the journal, and shouldat_seq > headbe refused?
11.8 Delete and Cancel
Section titled “11.8 Delete and Cancel”DeleteSession is permanent soft deletion: it tombstones the uid and records durable intent. It
does not erase data or reclaim compute.
OPS-31:DeleteSessionwith an emptyuidMUST beINVALID_ARGUMENT. An unknownuidMUST beNOT_FOUNDand MUST NOT create a session or journal. On aDELETION_ACTIVEsession the host MUST, in one transaction: append a host-ownedLIFECYCLE_DELETErecord with an emptyexecution_idat the current head (seq = head + 1, chained perCHAIN-3), advance the session’s fence, setdeletion_state = DELETION_PENDINGanddeletion_requested_time, and movelast_seqandupdate_time. It takes no caller cursor. It returns the session as committed. The record’stsanddeletion_requested_timeare the same instant (LOG-4).OPS-32:DeleteSessionon a session that is already deleted MUST return the stored session and write nothing: no record, and no change to the fence, timestamps,update_time, or the compute projection. A caller whose reply was lost after the commit learns the outcome this way or fromGetSession; the commit cannot be undone.OPS-33: Deletion is permanent. Theuid, its metadata, and its journal are retained, no operation returns the session toDELETION_ACTIVE, and theuidis not reused (SES-1).GetSession(SES-14) andReplay(§6.6) keep working;ListSessionsomits the session (SES-9). Children are unaffected: a fork child keeps its own copied prefix (CHAIN-8), staysDELETION_ACTIVE, and can run and fork.OPS-34:Exec,Forkat anyat_seq,Resume,Suspend,Approve, andCloseApproval, including an exact retry of a committed decision (APR-7), on a deleted session MUST failFAILED_PRECONDITIONbefore routing,Describe, a fence, a journal write, or a runtime call. In the reference host the check follows only the request’s own field checks (APR-5,OPS-21, an empty session), the deletion exclusion (OPS-30), and the session lookup (NOT_FOUND); it precedesFork’scountandchild_nameschecks (OPS-22),Resume’s cursor check (OPS-29), and onExecthe first frame (OPS-11). The host repeats the check under the session guard (OPS-1) beforeDescribeor runtime IO, andForkrepeats it for the parent and every child before its checkpoint, so a deletion that commits after the lookup also failsFAILED_PRECONDITION(onExec, after the first frame; onApproveandCloseApproval, after the checkpoint mark,OPS-2). The store’s refusal (LOG-19) backs both checks.OPS-35:DELETION_PENDINGacknowledges intent only. The host MUST NOT report deletion as reclamation. The reference host calls no runtime method for it (noStop,RT-7), releases no actor, snapshot, or fork-child pin, and never reportsCOMPUTE_TERMINATEDor a completed deletion. Retained compute has to be reclaimed in the backend by the operator. The reference SQLite store records allocation attempts, but that incomplete intent ledger is not authoritative cleanup inventory. Authoritative cleanup inventory and automatic reclamation remain future work (#88).OPS-36: The exclusion inOPS-30and the checks inOPS-34are per host. Durable refusal (LOG-19) stops later writes from any host that enforces it, but a host that does not (an older binary that already has the journal open, §18) keeps writing, and another host can provision compute for the session before its first fence or append fails. Cross-host exclusion of compute effects is not guaranteed.- Other
DeleteSessionfailures: a storage fault isINTERNAL; the caller’s cancellation or deadline isCANCELLEDorDEADLINE_EXCEEDED. OPS-28:CancelMUST returnUNIMPLEMENTED. TheControllerFrame.cancelframe is declared but never sent; the host cancels an execution by ending the stream’s context.
11.9 Status codes
Section titled “11.9 Status codes”| Condition | Code |
|---|---|
Missing required field, bad page token, unknown harness name, fork count > 128, child_names length mismatch, fork identity set |
INVALID_ARGUMENT |
| Unknown session (Get, Exec, Suspend, Resume, Fork, Approve, Delete) | NOT_FOUND |
Compare-and-swap conflict, stale fence, session busy (including an overlap with DeleteSession, OPS-30), checkpoint in progress, snapshot superseded, compute busy with another operation (api.ErrComputeBusy) |
ABORTED |
Unplaceable harness, descriptor mismatch, pin violation, memory-tier override (OPS-7), retired or unservable harness, static harness name with a registration row, approval state violation, inherited intent, undeclared trailing tool intent (TOOL-10), memory fork at a historical seq, deleted session (OPS-34), memory-tier compute gone or replaced (api.ErrMemoryStateLost, RT-4e, RT-4h), invalid, stale or local-only runtime checkpoint (api.ErrInvalidCheckpoint) |
FAILED_PRECONDITION |
A suspended actor’s newest checkpoint still uploading to durable storage on Exec, Suspend, Resume or Fork (api.ErrCheckpointPending); once it completes, Suspend again to record it before Resume |
UNAVAILABLE |
Harness Describe (admission RT-1, the RT-3 recheck, or a Describe during the turn) could not reach the harness while the caller’s context is live: the peer returned UNAVAILABLE or DEADLINE_EXCEEDED; or, on admission and the recheck, the host’s own bound expired; or, during the turn, the error wraps context.DeadlineExceeded |
UNAVAILABLE |
Any other Describe error on those paths, for example a peer UNIMPLEMENTED or INTERNAL, or a plain error from an in-process harness (during the turn, even one returned after the host’s bound expired) |
INTERNAL |
Any Describe error in the stored harness’s half of the memory-tier override check (OPS-7) while the caller’s context is live |
UNAVAILABLE |
Preparing Harness.Connect for a new Exec fails with UNAVAILABLE or DEADLINE_EXCEEDED while the caller is live (EXE-45) |
UNAVAILABLE |
Caller deadline or cancellation that ends admission, compute allocation/start, any Describe above, Connect preparation, a Suspend or Fork runtime operation, or DeleteSession, unless a more specific lifecycle refusal above applies |
DEADLINE_EXCEEDED or CANCELLED |
Journal hash chain fails verification on Exec, Resume (including an APR-13 park or request repair) or Fork (CHAIN-12) |
DATA_LOSS |
Cancel |
UNIMPLEMENTED |
| Any other failure | INTERNAL |
Recognized lifecycle and compute-start failures carry one google.rpc.ErrorInfo with domain
agentsessions, the reason below and no metadata. Reasons follow the classified condition, not
the method: they apply to Exec, Resume, Suspend, Fork, Approve and CloseApproval wherever the
corresponding condition is classified. DeleteSession reports SESSION_BUSY and SESSION_DELETED;
Exec, Resume, Suspend, Fork, Approve and CloseApproval also report SESSION_BUSY while a
DeleteSession holds the session. HarnessRegistry.RegisterHarness and
HarnessRegistry.CreateHarness report HARNESS_UNAVAILABLE when placement admission cannot reach
the harness. Clients match domain and reason together; details are additive, and an older server
or an unclassified error may supply none.
| Code | Condition → reason (first matching condition within the code wins) |
|---|---|
ABORTED |
Append-CAS conflict → STALE_CURSOR; local session contention → SESSION_BUSY; fork snapshot superseded → SNAPSHOT_SUPERSEDED; compute contention → COMPUTE_BUSY; checkpoint in progress → CHECKPOINT_IN_PROGRESS; superseded writer fence → FENCED |
FAILED_PRECONDITION |
Deleted session → SESSION_DELETED; lost memory-tier state → MEMORY_STATE_LOST; refused checkpoint → CHECKPOINT_INVALID; known invalid compute configuration → COMPUTE_CONFIG_INVALID |
UNAVAILABLE |
Checkpoint uploading → CHECKPOINT_PENDING; unreachable harness → HARNESS_UNAVAILABLE; compute unavailable → COMPUTE_UNAVAILABLE |
RESOURCE_EXHAUSTED |
No eligible compute capacity → COMPUTE_RESOURCE_EXHAUSTED |
A stale cursor requires reading the head before retrying. Session/compute contention can be retried after the current operation finishes; a superseded fence needs a new writer. A checkpoint that fenced an in-flight turn reports CHECKPOINT_IN_PROGRESS rather than its incidental fence or canceled model call. Deleted sessions and lost memory state retain FAILED_PRECONDITION, not a retryable compute outage. Other existing preconditions retain their codes without a reason.
The Go runtime SPI’s ErrComputeUnavailable, ErrComputeResourceExhausted and
ErrComputeConfigInvalid explicitly classify compute-start failures. Existing lifecycle refusals
take precedence over these categories. A backend must have evidence for a configuration fault:
an arbitrary transport FAILED_PRECONDITION is not sufficient. No eligible capacity can include
constraints other than full workers; freeing quota alone need not fix it. Concrete runtimes must
opt into these sentinels; unclassified backend errors remain INTERNAL with no invented reason.
Diagnostics wrapped with these sentinels are visible to RPC callers even with authorization
active: the runtime must use credential-safe text, not raw provider bodies or credential-bearing
URLs. The authorization sanitizer handles INTERNAL only; classification is not text sanitization.
Backend transport codes, ErrorInfo and metadata are not copied as host-owned details.
Caller cancellation/deadline is CANCELED/DEADLINE_EXCEEDED with no reason when it interrupts
compute start or a public Suspend/Fork runtime operation and no established lifecycle refusal
applies. An Exec/Resume approval handoff’s automatic snapshot retains its operational failure
classification. Lifecycle refusal precedence remains unchanged. A live caller’s peer deadline is
not a caller deadline; mid-turn model/Run classification is unchanged. A later journal, independent
confirmation or cleanup failure is not reclassified from the caller context and does not replace
the primary failure’s code or reason; the RT-7 compute-left-running warning remains available.
Direct Go calls retain wrapped causes with errors.Is/errors.As; causes do not cross RPCs, and
authorization-enforced INTERNAL responses retain only their existing fixed, sanitized message.
Exec’s terminal status details survive after the first session frame, including through the Go SDK.
12. Harness wire protocol
Section titled “12. Harness wire protocol”12.1 Describe
Section titled “12.1 Describe”WIRE-1:Describereturns aHarnessDescriptor:id,models,tools(with default mediation),capabilities, an opaqueversion, andharness_class. The host MUST boundDescribe(10 seconds in the reference host, never extending an earlier caller deadline); a failure appends nothing.WIRE-2:versionis owned by the harness author and MUST change when deterministic execution or config interpretation changes. It round-trips verbatim, including empty.WIRE-3: On the wire, the host readsRESUMABILITY_REQUIRES_MEMORY_SNAPSHOTas that tier and every other value asSTATELESS_REPLAY:RESUMABILITY_UNSPECIFIED, a number this host does not know, and an absentcapabilitiesmessage.WIRE-3a: The host readsHARNESS_CLASS_UNMEDIATEDas unmediated andHARNESS_CLASS_UNSPECIFIEDas mediated for compatibility. Reconstruction replay MUST refuseUNMEDIATEDand an unknownHarnessClassnumber before the firstHarness.Run; it does not refuseExecor recovery, and raw journal replay is unaffected. OnHarness.Connect, the host sendsControllerFrame.reconstruction_probebeforeStart; the server recognizes the probe by that explicitoneofmember with an emptysessionandexecution_id, and MUST answer with transport-onlyEVENT_RECONSTRUCTION_INFOcarrying the class of the exact harness serving that stream and MUST NOT invokeHarness.Runbefore it receivesStart;Describeremains the required side-effect-free metadata operation. The explicit member distinguishes the probe from a malformed empty frame and gives non-Go servers a stable discriminator. The host sendsStartonly forMEDIATEDor compatibilityUNSPECIFIED. A server that cannot determine its class MUST return a non-OK status and MUST NOT acceptStart. A missing, malformed, unmediated or unknown response fails closed. The reference host bounds the stream metadata exchange to 10 seconds, without extending an earlier caller deadline.- Open question: Should an unknown
Resumabilitynumber be refused instead of read asSTATELESS_REPLAY? A harness declaring a tier added later is placed as the weakest one.
12.2 Connect
Section titled “12.2 Connect”Connect drives one execution. The host sends ControllerFrames; the harness sends Events.
There is no general protocol-version handshake; compatibility rests on Describe and
HarnessDescriptor.version. Reconstruction alone has the class probe in WIRE-3a.
sequenceDiagram
participant H as Host
participant N as Harness
opt reconstruction
H->>N: ControllerFrame{reconstruction_probe}
N->>H: Event RECONSTRUCTION_INFO {harness_class}
end
H->>N: ControllerFrame{session, execution_id, start}
N->>H: Event MODEL_CALL {id, messages, tools}
Note over H: journal MODEL_CALL, call provider, journal OUTPUT
H->>N: ControllerFrame{model: ModelResult{model_call_id}}
N->>H: Event TOOL_CALL {mediation, idempotency_key}
Note over H: journal TOOL_CALL, execute, journal TOOL_RESULT
H->>N: ControllerFrame{tool: ToolResult}
N->>H: Event END {state: COMPLETED}
WIRE-4: The first frame MUST carrystartand a non-emptyexecution_id. The harness MUST take the session and execution id from the frame envelope. The reconstruction probe inWIRE-3ais the only exception;Startremains the first execution frame.WIRE-5: The host sends exactly oneStartwithconfig,history,inputs, andresume_from_seq. The reference host does not setStart.identity.WIRE-6: A model call isEVENT_MODEL_CALLwithmodel,params,messages,tools,tool_choice, and a freshid. The host answers withControllerFrame.modelwhosemodel_call_idequals thatid. AModelResultwith zero usage leavesusageunset.WIRE-7: A host-executed tool call isEVENT_TOOL_CALL; the host answers withControllerFrame.toolwhoseidequals the call id.WIRE-8: Every control frame MUST carry theStartexecution_id. AModelResultMUST carry the outstandingmodel_call_id. A tool reply (tool,approval,park) MUST also carry theStartsessionand the outstanding call id. The reference harness server fails the call on a mismatch; it does not checksessionon a model reply. Every event the harness sends MUST carry theStartexecution_id; the host fails the execution otherwise.WIRE-9: An unknownToolChoice.modeMUST be rejected in both directions; it is never treated as the provider default.WIRE-10: The harness MUST issue one model or tool request at a time and wait for its reply.- There is no error reply frame. When the host’s sink operation for a request fails, other than an
approval park (
APR-10), the reference host sends no reply and ends the invocation (EXE-33). WIRE-11: A park, and a protocol or correlation failure on a tool reply, MUST be sticky for the rest of the execution. In the reference harness server a failed model reply (wrongexecution_idormodel_call_id) fails that call only and is not sticky.- Open question: Should a model reply also be checked against
Start.session, and should its correlation failures be sticky like tool replies? WIRE-12: A normal run MUST end with exactly oneEVENT_END. The reference harness server sendsstate = "COMPLETED", orstate = "FAILED"witherror.description. The host treats any state other thanCOMPLETEDas a failed execution. An approval park ends withEVENT_PARKEDinstead (§10.3). AfterEVENT_ENDthe reference host half-closes its sending side and waits up to 2 seconds for the harness to end the RPC before cancelling it, so the harness can flush telemetry and return its own status. It waits the same way when a sink call fails on the host side, unless the caller has already cancelled; the turn still fails with the host’s error. AfterEVENT_PARKEDit already waits for the harness to close (APR-10). A stream that closes cleanly beforeEVENT_END, or sends a host-owned or unsupported event kind, fails the execution as a protocol error; it is never inferred as successful completion. AfterEVENT_END{COMPLETED}, a non-OK final RPC status fails the turn while the caller remains live, but caller cancellation or deadline during the bounded telemetry-flush wait does not replace the harness’s completed result.WIRE-13: Harness dials in the reference host use no transport security (§17).
12.3 Wire conversion
Section titled “12.3 Wire conversion”WIRE-14: UnknownEventKind,Mediation, andLifecycle.Kindvalues decode to unspecified; a tool call with unspecified mediation is then rejected byTOOL-1.WIRE-15:ToolResult.codeis converted without validation; the checks inTOOL-3,TOOL-7, andAPR-12reject unexpected codes, including a code the peer’s build does not know. A peer built beforePOLICY_DENIED,NOT_EXECUTED, orOUTCOME_UNKNOWNtherefore rejects that receipt instead of serving it (§18).Start.historyis not checked: such a peer receives the unknown code as its number.- If an
Eventhas more than one body set, only the first in the converter’s order is kept.
12.4 Per-turn environment in Start.config (informative)
Section titled “12.4 Per-turn environment in Start.config (informative)”The host passes Start.config to the harness without interpreting it. The reference Claude Code
harness (integrations/claudecode) gives it one optional meaning,
described here as an example of a harness-defined config shape. Nothing in this section is a
requirement on a host or on other harnesses.
-
Opt-in. The harness reads
Start.configonly when its operator setsTurnEnvAllowlist. With the allowlist empty, the default,configis not read, and a node that predates the feature ignores it and runs the turn with its own environment. -
Shape.
configis a JSON object whose memberenv, matched case-sensitively, maps variable names to string values, for example:{"env": {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "user.name","GIT_CONFIG_VALUE_0": "bot"}}Other members are ignored, so a producer can add its own. An empty
config, a missingenvmember, or an emptyenvsets nothing. -
Allowlist. Each name must match an allowlist entry: an exact name, or a nonempty name prefix followed by
*. A name that does not match refuses the turn. -
Reserved names. These can be neither set nor allowlisted:
PATH,HOME,USER,SHELL,TMPDIR,LANG,LC_ALL,LC_CTYPE,ANTHROPIC_API_KEY,ANTHROPIC_AUTH_TOKEN,CLAUDE_CONFIG_DIR,NODE_OPTIONS,BASH_ENV,ENV,PS4,PROMPT_COMMAND,ZDOTDIR, and any name starting withLD_,DYLD_,BASH_FUNC_orCLAUDE_CODE_OAUTH_. An allowlist entry that is, or whose prefix could match, a reserved name is refused when the harness starts, soANTHROPIC_*andCLAUDE_CODE_*are refused and such settings are allowlisted by exact name. -
Limits.
envholds at most 256 names, each at most 256 bytes, and at most 64 KiB of names and values together. -
Duplicates. With a duplicate name in
envthe last one is used, but a duplicate name whose earlier value is a number, boolean, array or object refuses the turn even when a later value is a string. An earlier duplicateenvmember is ignored whatever its value. -
Invalid input. The harness refuses the turn, before it starts
claude, whenconfigis not a JSON object,envis not valid UTF-8 (an escaped unpaired surrogate such as\ud800included) or not an object of strings (anullvalue included), a name is not a valid variable name, is reserved or is not allowlisted, a value holds NUL, or a limit above is exceeded. A refusal from a check on one name or its value (an invalid, reserved or not allowlisted name, anullvalue, NUL in a value) names the variable, except a name over the length limit. A refusal while readingconfigorenv(a number, boolean, array or object value included) or for the entry or size limit names none. No refusal holds a value. -
Effect. The entries replace same-named variables in that turn’s
claudeprocess only; the next turn starts again from the harness’s base environment: its default variables and the names its operator passes through, with the node’s values. -
Retry. A
Startthe harness refuses before it marks the execution started because another turn is running, a fork is in flight or the turn was cancelled can be retried and reads the same journaledconfig. A refusal for lost harness state is not cleared by a retry, which the harness refuses the same way before it readsconfig; the user re-prompts asEXE-43describes. Once the execution is marked started, a refusal for itsconfigincluded, the harness does not run it again (EXE-42) and the caller sends a newExec. Only theconfigbytes are stable: the base environment and the allowlist are those of the node running the turn. -
Security.
configis durable and returned byReplay(OPS-15), so a value must not be a credential. An allowed variable can redirect where the process sends data or make a tool run commands (GIT_CONFIG_*,ANTHROPIC_BASE_URL), so an operator allowlists only what the producer buildingconfigneeds. The reserved list covers the credentials and code-loading variables known when written; checking that an allowed name is not a credential is the operator’s responsibility.
13. Placement and runtime contract
Section titled “13. Placement and runtime contract”13.1 Resumability tiers
Section titled “13.1 Resumability tiers”| Tier | Requires from the runtime | Suspend | Resume | Fork |
|---|---|---|---|---|
STATELESS_REPLAY |
nothing | Snapshot(EXTERNAL); memory capture not required |
Restore; reconstruct from the log |
no snapshot; copy the log prefix; any at_seq |
REQUIRES_MEMORY_SNAPSHOT |
memory_snapshot |
Snapshot(EXTERNAL) capturing memory |
Restore memory; continue |
snapshot parent once at head; clone children |
- The tier states what the host relies on, not what a backend captures.
CanPlaceadmits aSTATELESS_REPLAYharness on any runtime (RT-2), andSuspendandResumemake the same runtime calls for both tiers (OPS-17,OPS-19). - For
STATELESS_REPLAYthe host relies only on the log: it sends the full prior log on every start (EXE-7) and reconstructs from it (§8.6). A backend MAY capture memory anyway and reportmemory = true(RT-5);runtime/substratedoes when it observes MEMORY fidelity, whileruntime/localandruntime/remotedo not (§13.4). ItsRestoreMAY recreate the incarnation or bring back what it captured. - For
REQUIRES_MEMORY_SNAPSHOTthe host relies on the backend:Restore, andCreateon a suspended session (RT-4e), MUST bring back the captured memory, because the harness does not rebuild that state from the log. - An unmediated harness (§8.8) MUST declare
REQUIRES_MEMORY_SNAPSHOT(EXE-38): with noMODEL_CALLfor the calls it makes outside the model call operation, the log cannot rebuild its state, soSTATELESS_REPLAYwould be false. - The host does not read
SnapshotRef.memoryto choose a path. It records it onSUSPEND(RT-5) and decides by the harness tier. - Neither tier promises that
Suspend,Resume, or a memory-tier fork succeeds while the backend has no incarnation for the session. The host makes the sameSnapshotandRestorecalls, and the backend MAY refuse them (RT-4b,RT-4c).
13.2 Admission
Section titled “13.2 Admission”RT-1: BeforeCreate(Exec),Restore(Resume), and the fork source step, the host MUST run, in order: the backend’sDescribe(RT-4f, bounded as inWIRE-1); the expected descriptor id check if the harness was configured with one (ErrDescriptorMismatch); thenCanPlace(ErrUnplaceable). Both refusals areFAILED_PRECONDITION.RT-2:CanPlaceMUST refuse aREQUIRES_MEMORY_SNAPSHOTharness on a runtime withoutmemory_snapshot. It checks nothing else:requires_gpu,fork_safe,streaming,cow_fork,attest, andgpu_stateare not compared.RT-3: For a backend that reports a live harness (RT-4g),ExecandResumeMUST repeat the admission check on the execution’s own connection after the host opens the execution’s harness client, before it opens theHarness.Connectstream and mints the turn’s regular writer fence, because a second dial can reach a different replica.RT-3does not cover fences minted before the execution has a connection:- the approval repair fence (
APR-13), minted before admission; that call parks and returns without admission or a connection, except the override checkAPR-13runs before the fence; - the early fence of a cursor-checked
Resume(OPS-29), minted after the first admission and before restore.
- the approval repair fence (
- A refusal at the repeated check of a cursor-checked
Resumeleaves its early fence minted, so older writers are superseded (LOG-12) even thoughResumerefused. Forkopens no execution connection and does not repeat admission.Suspendapplies no admission check.
13.3 Runtime SPI
Section titled “13.3 Runtime SPI”The runtime contract is Go, not a wire protocol in this draft. A backend is the interface
api.Runtime in api/runtime.go plus Describe(ctx) (api.Descriptor, error).
The reference host takes it as placement.Backend in
placement/placement.go (placement.New); a type that implements only
api.Runtime cannot be attached to it.
-
RT-4: Methods:Describe,Create,Snapshot(kind),Restore(ref),Fork(ref),Stop,Status,Capabilities. The host identifies an incarnation only by the session uid and keeps no runtime handle between calls. -
RT-4a: A runtime MUST key each incarnation by its session uid.Createreceives it asSessionSpec.SessionUID. The only other fields the reference host sets areSessionSpec.StartedTurns, a function that counts the turns the journal records as started on the harness being placed (RT-4e), andSessionSpec.RecordedCheckpoint, a function that reads the session’s recorded checkpoint (RT-4i);Image,Harness, andIdentityare empty.Forkreceives the child’s uid asForkOpts.ChildSessionUID, and a laterRestoreof the child arrives as{local: child uid}until the child writes its ownSUSPEND(RT-4c). -
RT-4b:SnapshotandStopreceive anIncarnationcarryingID(the session uid).Suspendand the memory-tier fork source step also pass the latest recordedComputeInstancetoSnapshot(RT-4h), empty when none is recorded, and the recorded checkpoint inRecordedCheckpoint(RT-4i), zero when none is; nothing else is set. The runtime MUST resolve everything it needs from those. The host does not check that the uid has an incarnation:Suspend(OPS-17) and the memory-tier fork source step (OPS-25) callSnapshotfor a uid the backend may hold nothing for, for example aSuspendbefore anyExec. Whether one exists is the backend’s state, not the journal’s: a failedExeccan leave one behind (RT-7). A backend MAY failSnapshotfor a uid it has no incarnation for; the host returns the error and appends noSUSPEND(RT-5).runtime/localandruntime/remoteaccept it;runtime/substratefails it (§13.4). -
RT-4c:Restorereceives this session’s own latestSUSPENDref, or{local: uid}when the session has none (OPS-19). ASTATELESS_REPLAYForkreceives{local: parent uid}(OPS-24). AREQUIRES_MEMORY_SNAPSHOTForkreceives the ref the parent’sSnapshot(EXTERNAL)returned in the same call; the host refuses one withoutexternal_uribefore callingFork(OPS-25).Forkis not told the tier:runtime/substratechooses clone or replay from the descriptor it was built with.{local: uid}can name a uid the backend holds no incarnation for, for example onResumebefore anyExec(§11.5). A backend MAY fail thatRestore; the host returns the error before it dials and appends nothing.runtime/localandruntime/remoteaccept it;runtime/substratefails it (§13.4). When the backend implementsapi.InstanceRestorer, the host callsRestoreInstancein place ofRestore, with a reader for the latest recorded compute instance (RT-4h). The backend may call it before resuming, to refuse compute whose nonempty instance differs from the recorded one, and again after a failed restore, to see turns journaled meanwhile;runtime/substraterefuses without resuming when the first read fails. AREQUIRES_MEMORY_SNAPSHOTbackend reportsapi.ErrMemoryStateLost(FAILED_PRECONDITION) fromRestoreonly when it finds the compute that held the session’s memory gone or replaced, or back without that memory (runtime/substrate: resumed on a worker that restored only its volumes, §13.4), since a retry cannot help then, or, with no compute instance recorded to compare (RT-4h), finds compute it cannot tell from a replacement; otherwise it returns the restore error, since compute that is still there can fail a restore for another reason. With no recorded instance,runtime/substratereports lost after aNOT_FOUNDresume whenever the actor does not hold the session’s snapshot, if a lifecycle change races the held-ref preflight (§13.4). -
CreateandRestoreMUST return a nonemptyIncarnation.ID, regardless of the host’s log implementation. SQLite-tracked placement enforces this before dialing: an empty ID fails withsqlitelog.ErrAllocationConflictafter the runtime call, leaving the allocation attempt unresolved. Logs without allocation recording do not enforce this requirement and retain the diagnostic-only use of ID. Every in-repo backend sets it to the session uid; it is not the immutable compute-instance identity used to detect replacement (RT-4h). -
RT-4d: TheIncarnationreturned byCreateandRestoreMUST carry anAddressat which the harness is reachable (the reference dialer takesunix://<path>orhost:port). The host dials that address and attaches the incarnation’sCallMetadatato every call it makes to the harness, replacing any value set for the same keys.CallMetadatais routing (for example, naming a sandbox behind a shared ingress), not authentication. The reference host discards theIncarnationreturned byFork; a child is reached through its own laterCreateorRestore. -
RT-4e: The host callsCreateat the start of everyExec, not only the first. It passes no snapshot ref, and the uid can already have an incarnation: a live one from an earlier turn, a forked child’s fromFork, or a suspended one, sinceExecon a cold session goes throughCreate, notRestore.CreateMUST NOT fail because the incarnation exists. For aREQUIRES_MEMORY_SNAPSHOTharness it MUST attach to a live incarnation and bring back a suspended one’s captured memory rather than start a fresh one;runtime/substratedoes both, and fails withapi.ErrMemoryStateLostwhen the actor comes back without that memory (§13.4). When no incarnation exists for such a harness andStartedTurnsreports any,CreateMUST fail withapi.ErrMemoryStateLost(FAILED_PRECONDITION) instead of starting fresh compute: the journal cannot rebuild the lost memory. ASTATELESS_REPLAYbackend MAY start fresh, since the host sends the full log (EXE-7). -
RT-4h: A backend MAY setIncarnation.ComputeInstance, an opaque identity that differs between two compute instances reusing one session uid (runtime/substrate: the actor’s UID, set only for aREQUIRES_MEMORY_SNAPSHOTharness). The host records the oneCreatereturns in the turn’sEXECUTION_START.compute_instance(EXE-1) and the oneForkreturns on the child’sLIFECYCLE_FORK(§7.2). The latest recorded instance is the last one named after the session’s lastLIFECYCLE_FORK, that marker included, counting only theEXECUTION_STARTs of turns the host attributes to the same harness; a fork child’s copied prefix does not count.ExecandResumeMUST failFAILED_PRECONDITION(api.ErrMemoryStateLost) when the incarnationCreateorRestorereturned names another instance; the reference host checks after it mints the turn’s regular fence and before it appends any record or runs the harness. A backend that setsComputeInstanceMUST refuse aSnapshotgiven one (RT-4b) withapi.ErrMemoryStateLostwhen another instance, or none, is there, before it returns a ref. An empty instance records nothing and is not compared, so records written before the field existed are not compared. -
RT-4i: The host hands the backend the checkpoint the session’s journal last recorded: theSnapshotRefof the session’s latest ownLIFECYCLE_SUSPEND(one whoselocalnames the session, asRT-5reads it), or none.Creategets a reader for it inSessionSpec.RecordedCheckpoint,Snapshotgets it inIncarnation.RecordedCheckpoint(fromSuspendand a stateful fork’s capture of the parent), andRestoregets it as its ref. A backend whose compute can hold a snapshot the journal never recorded MAY refuse, withapi.ErrMemoryStateLost(FAILED_PRECONDITION) and before it resumes, attaches to or suspends anything, compute that holds another one;runtime/substratedoes for aREQUIRES_MEMORY_SNAPSHOTharness (§13.4). A backend MAY also refuse that way, fromCreateorRestore, compute its resume reports holding another one; that compute is left running and not handed out, and the host records nothing. From a statefulForkit MAY refuse a clone its resume reports holding a capture of its own, since the child records none; that refusal isapi.ErrComputeBusy(ABORTED), notapi.ErrMemoryStateLost, since the parent keeps its snapshot and a retry clones a new child. A clone the backend cannot show holds none (its client does not report it) is refused withapi.ErrMemoryStateLost(FAILED_PRECONDITION) instead, since a retry is refused alike. The backend tears the clone down best effort (a clone it cannot, such as one whose lease another caller holds, is logged atWARNnaming the clone and its tag for an operator to delete), and the host writes no child journal. This reads only fields the journal already has; a backend that does not need it ignores it. -
RT-4j: A runtime with dedicated per-session resources MAY implementapi.ResourceCleanupRuntime.CleanupKeynames the control plane as the runtime’s configuration identifies it, not a harness alias; an empty key opts out. Two control planes configured alike share a key unless the operator names them (the substrate daemon’s-substrate-control-plane-id).CleanupResources(operation, session_uid)returns the complete plan before I/O: opaque references with no UID, and at most one borrower each, which must be released first. The runtime returns the UIDs it proved it created inIncarnation.Cleanup, also alongside an error. The host records the plan before I/O and confirms only planned references with unchanged UIDs and borrowers. It never adopts an object it finds by name, and an unknown outcome stays unconfirmed. A success that proves no UID (an Exec that re-attaches, a stateless Resume) created nothing the runtime owns: the host drops its plan and confirms its session handle instead. Fork records each child’s plan without publishing the child, just before that child’s runtimeFork(§13.4). -
RT-4f:Describereturns the harness descriptor the host admits on. It MUST NOT provision compute: the host calls it beforeCreate,Restore, and the fork source step (RT-1), in the memory-tier override check (OPS-7), and when the registry reports a harness’s observed descriptor. A backend returns either a declaration fixed when it was built (runtime/substrate) or the descriptor of a harness it asks (runtime/localin process,runtime/remoteover the network). -
RT-4g: A backend whoseDescribeasks whichever harness answers at an address, so the answer can differ from the harness a turn’s own connection reaches, MUST say so with aDescribesLiveHarness() boolmethod that returns true (placement.LiveDescriber;runtime/remotedoes). That is the only trigger for the repeated check ofRT-3. Such a backend MUST provision nothing inCreateandRestore: a refusal at the repeated check closes the dial and returns, and the host never callsStopfor it (RT-7), so anything provisioned would leak. -
RT-5:Snapshot(EXTERNAL)is the suspend step. It MUST return aSnapshotRefthat a laterRestorecan use, and itslocalMUST equal the session uid. A failedSnapshot(including the refusalRT-4ballows) returns no ref;Suspendthen appends noSUSPENDandcompute_statedoes not change. Resume ignores aSUSPENDref whoselocalnames another session (it treats it as inherited from a fork parent,OPS-19) and falls back to an earlierSUSPENDof its own, or{local: uid}, so a runtime that puts its own handle inlocalloses the captured state.memory = trueonly if process memory was captured; either tier may report it (§13.1). The reference host calls onlySnapshot(EXTERNAL), and every in-repo backend refusesLOCAL. The host stores the ref on theLIFECYCLE_SUSPENDrecord (snapshot_local,snapshot_external_uri,snapshot_memory,snapshot_sealed); there is no side table. -
Cold is the session’s
compute_state, which the host derives from the journal (OPS-17), not a runtimeStatus. A backend with per-session compute suspends it inSnapshot; a backend with none releases nothing, and itsStatuscan still reportLIVE(§13.4). -
RT-6:ForkMUST tear down a partially created child on failure. A backend that checks the parent before cloning MUST return an error wrappingapi.ErrSnapshotSupersededwhen it finds the parent present but no longer holding the referenced snapshot (resumed, or suspended again with a different one). The host maps that error toABORTED, and a retry at the parent’s new head is meaningful. The rule does not cover a parent that cannot be read:runtime/substratereports a parent actor deleted outside the host asapi.ErrMemoryStateLost(FAILED_PRECONDITION), and returns any otherGetActorerror, which the reference session service reports asINTERNAL. A backend that does not check the parent (runtime/local,runtime/remote, andruntime/substrate’s replay fork) never returns the error. A backend that setsComputeInstance(RT-4h) returns the child’s fromFork, and the host records it on the child’sLIFECYCLE_FORK. Teardown covers only compute the fork created: whenruntime/substratefinds the clone replaced under the child’s name before its resume, it leaves the replacement in place and failsABORTED(api.ErrComputeBusy) with no child recorded. -
RT-7:Stopis destructive teardown and is not part of suspension. The reference host calls it only to roll back a failed fork fan-out (OPS-27), never forDeleteSession(OPS-35). It does not callStopwhen a later step ofExecorResumefails afterCreateorRestoresucceeded (the allocation confirm, the dial, theRT-3check, the fence, the run, an approval park’s handoff before itsLIFECYCLE_SUSPENDcommits, or theLIFECYCLE_RESUMEappend). Instead it reads the journal and verifies its hash chain (CHAIN-12) to decide who owns the compute:- The journal owns it: the journal as the host reads it after the failure leaves the compute
LIVE, what left itLIVEran on the harness the call runs on, and the runtime returned no replacement.LIVEhere is the host’s own fold of the records: it followsSES-8, except that aCloseApprovalreceipt (NOT_EXECUTEDorOUTCOME_UNKNOWN) changes nothing, since the host writes it without compute, so the records before it decide. The storedcompute_statestill readsLIVEafter the receipt (SES-8).LIVEwhen the call began does not count once a record committed during the call leaves the journal otherwise: after another host’sLIFECYCLE_SUSPEND,CreateorRestoremay have woken the compute that host suspended (runtime/substrateresumes a suspended actor), and the next case applies. A turn ran on the harness itsEXECUTION_STARTnames (this harness or an alias of it), or on the session’s own harness when it names none; a fork child’s turn re-driven across itsFORKmarker is still that turn. ALIFECYCLE_RESUMEran on the session’s own harness or on the harness of a turn with a record after the latestFORKmarker before it (any turn when there is none): a resume re-drives a pending turn on that turn’s harness, and two resumes that both found the turn pending can each run on it, the second appending itsLIFECYCLE_RESUMEafter the first’s. When all of those are the call’s harness, the resume ran there. A host with one harness counts every turn and resume, unless the journal does not attribute its turns (the third case). After a turn or resume on another harness (anExecRequest.harnessoverride, either way),LIVEis that harness’s compute, not what this call’s backend returned. A replacement is a nonemptyIncarnation.compute_instanceother than the latest one this harness’s turns, or the session’sFORKmarker, recorded: the run refuses it (api.ErrMemoryStateLost), andLIVEis the replaced instance. The host returns the error unchanged. - Another owner may hold it: a record committed during the call, or the call failed on a
checkpoint in progress, a newer fence, or a deleted session. A checkpoint that superseded the
turn (
OPS-2) counts as in progress: a stateful fork may still be snapshotting the compute, or may fail before it suspends it. The host releases nothing. - The owner is unknown: the host cannot read the journal or verify its chain, the journal ends
before the head it had when the call began (a lost tail can leave a prefix that verifies and
reads
LIVE), the journal readsLIVEbut does not attribute every turn to one harness, orLIVEcomes from aLIFECYCLE_RESUMEthat may have run on the call’s harness or on another one, and the journal does not record which. A journal does not attribute its turns when its chain verifies but it holds a record replay rejects for who wrote it: anEXECUTION_STARTwith noexecution_idor no payload, after other records of itsexecution_id, or naming a harness other than thatexecution_id’s firstEXECUTION_START(one naming the same harness is not a conflict), a record with noexecution_idthat no legacy writer would have written there, or, right after an unfinished legacy turn (its last record, lifecycle markers aside, is notENDorERROR), a record with anexecution_idother than anEXECUTION_START. The host then releases nothing unless the runtime returned a replacement, on a host with one harness too. For aLIFECYCLE_RESUME, it releases nothing when the call runs on one of those harnesses and the runtime returned no replacement; when it runs on none of them or the runtime returned a replacement, nobody owns the compute. - Nobody owns it: the host calls
api.CleanupRuntime.ReleaseSessionfor the session, bounded at 30s and detached from the caller’s cancellation. After a successful release it returns the error unchanged.
In the second and third cases, or when the backend has no
api.CleanupRuntimeor the release fails, the error is aplacement.ComputeLeftRunningError(placement.ErrComputeLeftRunning). It names the incarnation, wraps the original error, and says in fixed text why nothing was released; the journal, verification or release error behind that is only in theCleanupfield, and the host log carries the same fixed text. The public code is the original error’s. Undersession.WithAuthorization, which replaces anINTERNALmessage withinternal error, such anINTERNALfailure keeps fixed text naming the incarnation ID and, when the runtime returned one, the compute instance, with nothing from the cause or the request:internal error; compute instance "<id>" (uid "<instance>") may still be running. The host keeps no handle to that incarnation; a laterExecreaches it throughCreate(RT-4e) and aSuspendthroughSnapshot. - The journal owns it: the journal as the host reads it after the failure leaves the compute
-
RT-8:Capabilitiesreportsmemory_snapshot,cow_fork,attest, andgpu_state. Onlymemory_snapshotaffects placement (RT-2,OPS-7). -
The reference host does not call
Status.
13.4 Reference backends (informative)
Section titled “13.4 Reference backends (informative)”The SQLite placement path durably records allocation intent before Create/Restore and confirms
only the returned session-scoped handle, not an immutable compute-instance identity. A replaced
compute instance can reuse the same handle. Confirmation gets a bounded context independent of
client cancellation once the runtime returns. A successful confirmation atomically replaces prior
confirmed, unreleased attempts for the same (session, backend key, handle), retaining the attempt
being confirmed, not the one with the greatest random ID. Unresolved attempts and released history
are preserved, so repeated unknown outcomes can still grow the ledger. Confirming or releasing a
compacted attempt returns sqlitelog.ErrAllocationNotFound; cleanup must reread the live inventory
if a late confirmation retires a paged attempt. Addresses and call credentials are not inventory.
Optional api.CleanupRuntime keys identify exact non-destructive release configurations, not
harness aliases or a generic Stop fallback. Fork keeps its legacy allocation/rollback path at this
stage. Version 7 adds the allocation ledger and inventory completeness/evidence columns, without
fork-publication or reaper state. It enables no reclamation. Every newly created inventory remains
incomplete, as does every migrated row; tracking a later restore does not certify a previous
untracked fork. A host embedding sqlitelog can establish coverage by calling
Store.CertifyInventory only after explicit reconciliation. Stop all old writers before migration
and never downgrade the migrated journal to v0.3.0 or older.
Version 10 adds one allocation_resources row per planned resource and allocation_borrowers
edges (RT-4j). A Fork child’s plan is recorded without a sessions row, so a failed fan-out does
not publish the child. Nothing releases these rows yet: teardown is unchanged, and the cleanup
reaper and cleanup-complete state come later. The canonical_resource_id column ships empty for
that later work. Rollout is in §18.
runtime/local: serves the harness in the host process over a unix socket shared by all sessions.Describeasks that in-process harness. All capabilities false.Snapshot(EXTERNAL)returns{local: id, memory: false};Create,Restore, andForkreturn an incarnation at the shared socket. It has no per-session compute, soSnapshotreleases nothing and itsStatusstill reportsLIVEafter a suspend.runtime/remote: points every incarnation at an operator-configured harness address.Describedials it, and the backend is aLiveDescriber(RT-4g). Same capabilities and snapshot refs as local.Create,Restore, andForkprovision nothing, andStopleaves the harness running.runtime/substrate:memory_snapshot = trueby default, driven through its ownControlClientinterface.WithVolumesOnly()sets that capability false, so memory-required admission refuses.Describereturns the descriptor it was built with.Createattaches to a running actor, resumes a suspended one, and creates one only when none exists (RT-4e).Snapshotsuspends the actor’s per-session compute and returns the newest snapshot’s URI only if its durable copy is completed, withmemory = trueonly for observed MEMORY fidelity. VOLUMES and ROOTFS report false; unspecified or unrecognized fidelity also reports false for default stateless replay, not proof of files-only capture.WithVolumesOnly()requires observed VOLUMES and a nonempty URI; a memory-required descriptor or recorded compute instance instead requires MEMORY and a nonempty URI. Missing or mismatched evidence refuses without a ref, so noSUSPENDis journaled. Combining VOLUMES-only with a memory requirement refuses directSnapshotcalls too. The option validates results; template settings remain operator-owned. Invalid checkpoints wrapapi.ErrInvalidCheckpointand areFAILED_PRECONDITIONfrom Suspend/Fork; the actor may already be suspended when capture refuses, but no ref or SUSPEND is recorded. Create and Restore check a suspended actor’s durable URI and configured fidelity before resuming it. Restore decides whether MEMORY is required from the backend descriptor, not from a legacySnapshotRef.Memorybit, because journals written before this change recordedMemory: trueon every Substrate suspend, including stateless actors. A RESUMING or SUSPENDING actor isapi.ErrComputeBusy(ABORTED) before other checks. A RUNNING actor keeps the no-op resume, so a repeated Resume, a Resume retried after a failed dial and interrupted-turn recovery after an earlier Suspend succeed; for memory tier, a nonempty observed UID that differs from the nonempty recorded one isapi.ErrMemoryStateLostbefore the resume. For a stateless or VOLUMES-only backend, held URI refs are checked only against a SUSPENDED actor, which must hold exactly that durable checkpoint: a stale ref wrapssubstrate.ErrSnapshotNotRestorableandapi.ErrInvalidCheckpoint(FAILED_PRECONDITION), so inspect and explicitly Suspend again rather than retry it. Control-read refusals areINTERNAL. Default stateless empty-URI recovery ignores the legacy Memory bit; memory-descriptor no-held recovery (Memory:false) remains available, including interrupted turns and fork children, for an actor that holds no capture of its own. VOLUMES-only requires a held URI. Suspended fidelity admission still applies to every recovery path. Create/Exec check fidelity/readiness; for a memory tier they also compare the journal’s recorded checkpoint (RT-4i, below). Memory-required non-MEMORY evidence also wrapsapi.ErrMemoryStateLost. GetActor must report that evidence too. An identified SUSPENDED actor with authoritative generation-zero/empty-list evidence can reportActorInfo.NoSnapshotHistoryfor first placement between CreateActor and its first ResumeActor. False means present or unknown history, not an exemption; borrowed fork snapshots and refused captures do not qualify. At the pinned Substrate, an unsourcedCreateActorrecords the template’s current golden tag as generation 1, so this exemption exists only when golden snapshots are disabled or unavailable. Capture never uses this exemption. The adapter selects the highest generation before durable completion (later ties win). A newest pending/local-only entry exposes no URI/fidelity and setsActorInfo.SnapshotNotReady, plusActorInfo.SnapshotPendingonly for an explicitPENDINGupload; Snapshot returns zero ref for it. For aREQUIRES_MEMORY_SNAPSHOTharness, whose journal never records a checkpoint that is not ready, such an entry is a capture the journal did not record: Restore, Create’s attach andSnapshot(before suspending) refuse a suspended actor that holds one withapi.ErrMemoryStateLost(below), and as not ready only while its upload is pending; once that upload completes it is refused the same way, so neither waiting nor an explicit Suspend recovers the session. For a stateless or VOLUMES-only actor, Restore of a suspended actor and suspended attachment refuse withsubstrate.ErrSnapshotNotReady(wrapping ErrSnapshotNotRestorable), not permanent memory loss unless the actor is proven replaced. There, a pending upload also wrapsapi.ErrCheckpointPending(UNAVAILABLE): compute may already be released without a SUSPEND record, so once it completes, Suspend again to record the new ref before Resume; the older ref is stale. Local-only state wrapsapi.ErrInvalidCheckpoint(FAILED_PRECONDITION): it may never upload, so inspect and explicitly establish a durable checkpoint instead of waiting. The adapter requests a synchronous suspend (an unset mode is asynchronous at v1), soSuspendActorcapturing aRUNNINGactor returns only once its upload completed. An actor alreadySUSPENDED, for example by a worker-requested asynchronous suspend, is returned as it is in any mode, its upload stillPENDINGuntil the background upload completes: Suspend refuses it as pending, and suspending again does not upload it. This conservatively refuses default attachment to an out-of-band pending or local-only capture. Readiness is not effective restore-source evidence. These client checks can race lifecycle operations or router ingress; only Substrate can atomically bind expected snapshot/state to resume. Known limit: the effective resume source can differ from the durable checkpoint the adapter validated. Actors suspended outside sessions may hold an actor-local checkpoint that Substrate prefers on resume, while the adapter reports only durable checkpoint evidence. Validation can falsely refuse recoverable local state or accept a fidelity that does not meet the backend’s requirement. A newest local-only checkpoint is conservatively refused; local preference can still make durable VOLUMES pass validation while resume restores local MEMORY. Likewise, when a durable snapshot’s recordedActorTemplateUID differs from the actor’s current template UID (for example because the template was deleted and recreated under the same name), pinned Substrate restores at VOLUMES scope: a memory-tier session can pass durable MEMORY validation yet still cold-boot and lose RAM. Both cases remain open in issue #192; held-URI/readiness checks do not solve effective-source validation. A resume that Substrate (since v0.5.0) binds to a worker whose sandbox runtime cannot restore the recorded runtime of the MEMORY snapshot it restores from does not restore that memory: v0.5.0 restores the snapshot’s volumes only and v0.6.0 and v1 its root filesystem, and in both cases the actor loses RAM. The adapter reports it asActorInfo.MemoryNotRestored, and for aREQUIRES_MEMORY_SNAPSHOTharness the backend refuses that actor withapi.ErrMemoryStateLostwherever it would hand it out (Create, Restore, a stateful Fork’s clone) and beforeSnapshotsuspends it, recorded compute instance or not.Snapshotrefuses a RESUMING or SUSPENDING actor withapi.ErrComputeBusy(ABORTED) before its other checks, as Restore does, since the operation moving it may still record its capture.SuspendActortakes no precondition, soSnapshotalso refuses, withapi.ErrMemoryStateLost, a suspend whoseActorInfo.UIDorActorInfo.CaptureLineagediffers from the actor it checked (a replacement, a capture followed by a resume, or a resume onto another runtime, in between); the refused capture stays on the suspended actor. The refusal sticks through the journal (RT-4i): for aREQUIRES_MEMORY_SNAPSHOTharness, Create’s attach, Restore andSnapshot(Suspend, and a stateful fork’s capture of the parent) refuse withapi.ErrMemoryStateLost, beforeResumeActororSuspendActor, an actor, SUSPENDED or RUNNING, whose newest snapshot is not the one the latest recordedSUSPENDnames or, with none recorded, that holds a capture of its own (ActorInfo.NoCapturefalse). Restore and Create, on an attach or on the actor it just created, check the actor a successfulResumeActorreports the same way (Create reads the recorded checkpoint again), since a capture can land between the check, or the create, and the resume; a refused actor is left running and not handed out. A statefulForkchecks the clone itsResumeActorreports against the child’s empty checkpoint, so a clone another caller resumed and captured before that resume is refused withsubstrate.ErrActorBusy(ABORTED) and logged atWARN; the clone is torn down best effort (a failed teardown is logged atWARNnaming what it leaves), no child is recorded, and a retry clones a new child. This sees only what the response reports; it is no precondition on the resume. It fails closed: a capture whoseSUSPENDappend failed, another host’s capture before its append, or a suspend outside sessions is refused too, and nothing in sessions recovers the session after it. One window remains: a crash, revert and resume onto a worker of the same runtime between the check and the suspend keeps the lineage and the newest snapshot, so the capture lacks the turns since the last checkpoint. Only a precondition onSuspendActorthat substrate enforces (the worker assignment, generation or UID checked) closes it; v1 has none onSuspendActor(which takes only a durability mode) orResumeActor. A router resume alone keeps the recorded checkpoint, but a suspend by any other caller, such as a gateway’s idle suspend, leaves a capture noSUSPENDnames, so the host must be the only caller that suspends aREQUIRES_MEMORY_SNAPSHOTharness’s actor. One outside suspend inside the window with no resume after it is the captureSnapshotwould have taken, and is recorded.SnapshotandRestoredo not create missing actors. When no actor exists (for example a fresh session before anyCreatereachedCreateActor, and not a fork child, or an actor deleted outside the host) both fail with the control API’sNOT_FOUND(substrate module pinned inintegrations/substrate/go.mod,cmd/ateapi/internal/controlapi/actor.go). ARestoreof a ref that holds a checkpoint (a durable URI, any VOLUMES-only ref, or a RAM checkpoint) whose actor is gone, deleted or lost to a substrate reinstall, is refused before any resume or create withapi.ErrInvalidCheckpoint(FAILED_PRECONDITION), plusapi.ErrMemoryStateLostfor aREQUIRES_MEMORY_SNAPSHOTharness; nothing is created or journaled. The message names the actor, never the snapshot URI. A ref that records a checkpoint (a durable URI, or a RAM checkpoint) also names the session’s latestSUSPEND; a VOLUMES-only default ref of a session that never suspended has noSUSPEND, so its message says only that the session’s compute cannot be resumed. Any other ref keeps theNOT_FOUND, reported asapi.ErrMemoryStateLostfor aREQUIRES_MEMORY_SNAPSHOTharness. For such a harness it setsComputeInstanceto the actor’s UID (RT-4h), refuses to create an actor for a session with started turns (RT-4e), refuses before resuming an actor whose nonempty UID differs from the nonempty recorded one, and after a failed restore reports lost state only whenGetActorfinds no actor or one whose UID is not the recorded one; with no UID recorded, only an actor that does not hold the session’s snapshot after aNOT_FOUNDresume. An actor that another operation holds isapi.ErrComputeBusy(ABORTED). Running on agent-substrate has the details. A failedCreatecan still leave an actor:CreateActorsucceeded and theResumeActorafter it failed. In the pinned module aSuspendActoron a suspended actor and aResumeActoron a running one succeed without doing anything, so a repeatedSuspendand aResumeof a running actor, with or without a held ref, both succeed.Forkclones the parent’s snapshot for aREQUIRES_MEMORY_SNAPSHOTdescriptor and creates a fresh actor otherwise. The adapter that talks to agent-substrate is the separate Go moduleintegrations/substrate, an example of the runtime contract. The core module does not import it; CI assertsgo list -deps ./...contains noagent-substrateimport.
14. Harness registry
Section titled “14. Harness registry”The HarnessRegistry service (api/harness_registry.proto) is an
operator API. The reference host serves it only on a separate listener bound to a literal loopback
address, never on the Sessions listener.
REG-1: ARegisterHarnessname MUST be an RFC 1123 DNS label (INVALID_ARGUMENT). A reserved or statically configured name isALREADY_EXISTS. Statically configured names are not validated this way.REG-2: A spec MUST have exactly one placement, a resumability other than unspecified, no unknown fields or enum values, and canonical bytes (CHAIN-1) of at most 4096 bytes; elseINVALID_ARGUMENT.REG-2a: Which placements a host can instantiate is host-defined. A valid spec whose placement this host cannot build isFAILED_PRECONDITION, with nothing stored. The referenceagentsessionsdbuildsremoteplacements and refusessubstratethis way, in its substrate build too, which serves substrate harnesses only from-substrate-harness.REG-3:RegisterHarnessis idempotent onspec_digest(§7.5): the same spec returns unchanged (or reactivated if retired, keeping the uid); a different spec under a taken name isALREADY_EXISTS.REG-3a:CreateHarnessis create-only registration. It MUST check that the name has no registration row and is not reserved, and insert the new row, in one transaction of the store every host sharing the journal uses, so of concurrentCreateHarnesscalls for one name, on any hosts, at most one succeeds. It validates asRegisterHarnessdoes (REG-1,REG-2) before it reads registration rows, so an invalid spec isINVALID_ARGUMENTeven under a registered name. For a request that passesREG-1andREG-2, a name with a row (ACTIVEorRETIRED, any spec, loaded on this host or not), a static name, or a reserved one isALREADY_EXISTS, and the refusal stores, reactivates and loads nothing; a free name can still failREG-2a. A call that ends inDEADLINE_EXCEEDED,CANCELLEDor a transport error may have committed, and a retry then returnsALREADY_EXISTS; a client SHOULD inspect the name withGetHarnessrather than retry.spec_digestsays whether the stored spec is the one requested, not which caller stored it. A server built beforeCreateHarnessreturnsUNIMPLEMENTEDand changes nothing.REG-4:RetireHarnessis idempotent, rejects a reason over 1024 bytes, and isFAILED_PRECONDITIONfor a static harness andNOT_FOUNDfor an unknown one. A retired harness refuses new sessions only; existing sessions keep running on it.REG-5: A stored registration that cannot be loaded stays reserved and is unservable (FAILED_PRECONDITIONat routing). Registry entries are never replaced in place.REG-6: Sessions on a registered harness are pinned (OPS-6).
15. API surface
Section titled “15. API surface”API-1: The API is the gRPC servicesagentsessions.v1.Sessions,agentsessions.v1.Harness, andagentsessions.v1.HarnessRegistrydefined inapi/. There is no HTTP/JSON mapping.- Message- and field-level semantics are in API reference, generated from the proto comments. Where that reference and this document disagree, the disagreement is a defect to report; neither silently wins.
- The Go SPI (
api.Harness,api.EventSink,api.Runtime) mirrors the wire types and is the in-process form of the same contracts.
16. Conformance
Section titled “16. Conformance”16.1 Reference suite
Section titled “16.1 Reference suite”conformance/ is a Go test suite run against the reference stack (SQLite store,
controller, echo or test harness, in-process or over Harness.Connect). No runtime backend is
involved, and TestApprovalRawProtocol uses neither controller nor journal.
| Test | Asserts | Requirements |
|---|---|---|
TestReplayReconstructsNondeterministicOutput |
Reconstruction reproduces recorded output with 0 model calls | I0, I1 |
TestMultiTurnResumeContinue |
Three turns on three incarnations of one journal; chain verifies | EXE-1, CHAIN-9 |
TestCrashMidTurnRedriveAtMostOnce |
Truncated END recovers with 0 model calls and one output |
EXE-21, EXE-23 |
TestCrashAfterUsageDoesNotDuplicateAccounting |
Recovery after USAGE leaves exactly one USAGE |
EXE-21 |
TestReplayServesRecordedProviderUsage |
Recorded usage served with the completion | I0 |
TestResumeCutBeforeUsageJournalsZeroOrNoUsage |
Cut between OUTPUT and USAGE serves zero usage |
EXE-21 |
TestForkEquivalence |
Child prefix hashes equal the parent’s; both chains verify | CHAIN-8 |
TestSingleWriter |
A second controller with a stale cursor (0) is rejected | LOG-7, EXE-2 |
TestTamperedJournalRefusedBeforeUse |
A stored OUTPUT changed without its hash refuses reconstruction, recovery and Exec with 0 model calls and no append |
CHAIN-12 |
TestIntegrityGoldenVectorCrossImpl |
Python verifier reproduces the Go content_hash (skipped without python3) |
CHAIN-11 |
TestCrashMidToolCallAtMostOnce |
Declared trailing intent re-driven under the same key; one effect, one receipt | TOOL-10, TOOL-11 |
TestCrashMidToolCallUndeclaredRefused |
Undeclared trailing intent refused; no executor call, journal unchanged | TOOL-10 |
TestControllerMediatedToolRequiresKey |
Keyless call rejected; no TOOL_CALL recorded |
TOOL-4 |
TestUnmediatedToolCallRejected |
Unspecified mediation rejected | TOOL-1 |
TestReplayNeverReachesTheProvider |
A real HTTP provider client sees 1 request live, 0 on replay | I1 |
TestStreamingDoesNotChangeTheJournal |
Streamed turn journals one finalized OUTPUT |
EXE-12 |
TestReplayEmitsNoDeltas |
Reconstruction emits no deltas and makes 0 model calls | EXE-12, I1 |
TestWireDescribeRoundTrip |
Descriptor survives the gRPC round trip | WIRE-1 |
TestWireReplayRefusesUnmediatedHarnessBeforeConnect |
An unmediated descriptor is refused before opening Connect or invoking Run |
EXE-41, WIRE-3a |
TestWireReplayBindsClassToConnectPeer |
A mediated Describe cannot authorize an unmediated peer selected for Connect, including through a harness decorator |
EXE-41, WIRE-3a |
TestWireReplayPropagatesClassCheckThroughDelegatingServer |
A server delegating to another wire harness preserves reconstruction intent, so the inner stream also checks its class before Start |
EXE-41, WIRE-3a |
TestWirePropagatesExecutionID |
Remote Start execution id equals the journal’s |
WIRE-4 |
TestWireFailedHarnessSurfacesError |
Remote failure journaled as ERROR, not END |
EXE-5, WIRE-12 |
TestWireSinkErrorEndsInvocation |
A harness that handles a provider error completes in process but fails over the wire | EXE-33 |
TestWireNondeterministicReplay |
Remote reconstruction is byte-identical with 0 model calls | I1 |
TestWireControllerMediatedTool |
Host executes once; replay does not re-execute | TOOL-5, TOOL-9 |
TestWireToolRequestChangesFailReplayAndRecovery |
Changed id, name, args, mediation, or key diverges with 0 executor calls | TOOL-8 |
TestWireExecutionStartReopenResumeReplayAndFork |
Resume, replay, and fork deliver the original Start |
EXE-19, OPS-15 |
TestApprovalRawProtocol |
Protobuf-only peer: approval before receipt, park ack and close | APR-10 to APR-12 |
TestWireMemoryTierApproval/park |
A memory-tier gated call journals TOOL_CALL and APPROVAL_REQUEST and parks; 0 executor calls |
APR-1, APR-2 |
TestWireMemoryTierApproval/approve |
After a decision and reopen, the gated call first (no prefix) runs the executor once; receipt, then END |
APR-14, APR-16 |
TestWireMemoryTierApproval/deny |
A denial returns the APPROVAL_DENIED receipt with 0 executor calls |
APR-12, APR-16 |
TestWireMemoryTierApproval/wrong_first_call |
A first call other than the gated call diverges with one ERROR and no receipt; a later compliant recovery completes |
APR-16, EXE-14 |
TestWireMemoryTierApproval/stateless_unchanged |
STATELESS_REPLAY recovery still serves the prefix first |
EXE-21 |
TestApprovalCloseWire |
After CloseApproval, recovery serves each closed state to a protobuf-only peer as approval then NOT_EXECUTED or OUTCOME_UNKNOWN receipt, with no executor call |
APR-11, APR-12, APR-18, APR-19 |
CI also runs python3 hack/verify_chain.py --golden and hack/verify_chain.sh (CHAIN-9 to
CHAIN-11).
16.2 Coverage limits
Section titled “16.2 Coverage limits”- The suite is wired to the Go reference implementation. It is not packaged as a black-box suite that another host, store, harness, or runtime can run against itself.
- Open question: Package
conformance/(or a subset) as a black-box suite with requirement ids, so independent implementations can claim a class from §4. - Requirements without a conformance test are pinned by unit tests in the implementing package; some are untested and are listed in §19.
17. Security considerations
Section titled “17. Security considerations”The reference implementation protects the integrity of the record, not access to the system. See Security posture for deployment guidance.
- The reference daemon authenticates and authorizes no RPC, and no hop it assembles uses TLS.
Any caller that reaches its Sessions port can call every RPC, including
Approve. - Go hosts can opt into
authn.NewInterceptorsfor all unary and stream RPCs on a server, with no method exemptions.offskips verification and installs no identity.requiredneeds aCallerVerifier; unknown modes or a nil required verifier fail construction. The verifier owns credential parsing and trust validation, including rejection of missing, malformed, duplicate and expired credentials. It returns an exactapi.CallerIdentityand a futureValidUntil. Invalid identities/expiry or verifier errors return genericUNAUTHENTICATED, never an anonymous fallback. Only the interceptors install the private context read byauthn.Caller. - Unary calls authenticate once at admission. Credential expiry does not add a handler deadline,
end the call, or remove its verified caller; caller cancellation/deadlines still apply, but the
interceptor preserves the handler’s returned result and status.
Only authenticated stream contexts end at the earlier caller deadline or credential expiry. Expiry
returns
UNAUTHENTICATED; caller cancellation/deadlines retain their status codes. Cancellation is cooperative: no in-stream refresh, interruption of transport I/O already in progress, or undo of in-flight effects is promised. If expiry interrupts a runningExecharness and it returns an error, the controller journals a best-effortERROR, unless stopped after an approval intent. RetryingExecwith inputs and a fresh credential starts a new turn, rather than automatically continuing the interrupted one; pending approvals still followOPS-14. AnERRORdoes not prevent laterResumerecovery (EXE-6). Expiry before the harness runs need not journal anERROR. Verification runs once per RPC, so revocation beforeValidUntilis not noticed by an admitted unary call or an open stream. Authentication alone is not isolation: these interceptors provide neither per-RPC authorization nor TLS, and the daemon has no required-mode switch. - Custom Go hosts can opt into
session.WithAuthorization(api.Authorizer)onNewServiceandsession.WithRegistryAuthorization(api.Authorizer)onNewHarnessRegistry. Missing verified caller MUST beUNAUTHENTICATED, including direct handler calls, before validation. Nil policy MUST fail closed. The default service remains unenforced. Checks MUST precede runtime IO, fence minting, first stream frame and approval repair. The action mapping is Get/Replay → read, Exec → exec, Suspend → suspend, Resume → resume+exec, Delete → delete, Cancel → cancel thenUNIMPLEMENTED, Approve → read+approve, CloseApproval → read+approval.close. Inputless Exec entering approval-recovery Resume also MUST check resume; ordinary Exec, including restoration of suspended compute, requires only exec. The Resume RPC MUST check resume+exec even for a no-op. Create MUST check global create before inserting the verified caller as immutable owner; auto-create Exec also checks exec on the prospective UID before insertion. Fork checks parent fork and global create but MUST refuseFAILED_PRECONDITIONbefore discovery/effects until owner-before-log child publication is available. - ListSessions MUST check global list and filter exact verified owner in SQL before keyset paging.
Registry uses distinct global registry.read/list/register/retire actions, including read before
observed Describe. Global actions carry empty UID/owner; requests cannot supply ownership.
Every Go
api.AuthorizationRequest.MethodMUST carry the full originating RPC path, including direct handler calls and compound, recovery and global checks. For example, an inputless Exec checking resume retains/agentsessions.v1.Sessions/Exec, not the Resume path. This is a Go SPI field, not a protobuf message or wire field. The firstOwnerAllowlistAuthorizerpolicy composes ordinary owner checks with exact-caller allowlists for create/list/approve/registry actions. Ownership alone MUST NOT authorize approve; with this policy an approver must also own the session.approval.closeis an owner action: it can deny or revoke an approval but never grant one, soOwnerAuthorizerallows it for the owner and the allowlist policy delegates it unchanged. Unknown actions and mint remain denied. - Mutation owner lookups for Exec, Suspend, Resume, Fork, Approve, CloseApproval and DeleteSession
MUST probe deletion admission (
OPS-30) after authentication. The probe MUST acquire and release shared admission before owner SQL or policy evaluation; it MUST NOT lease SQL. An exclusive Delete present at the probe MUST returnABORTEDwithout waiting for SQL, even for a verified non-owner who knows the UID. This can disclose deletion in progress, but grants no access. The probe can race a later Delete; subsequent mutation guards remain authoritative. Owner queries, including later-denied queries, MUST NOT hold admission while waiting for SQL. Get/Replay remain unguarded audit reads; Cancel is unchanged. - Once the deletion probe permits owner lookup, unknown sessions and policy refusals MUST return
the same generic
PERMISSION_DENIED. Existing unbound rows MUST reach the policy with a zeroOwner;OwnerAuthorizerdenies them, but custom policies MAY allow them. Onlyapi.ErrPermissionDenied(possibly wrapped) is policy denial; unexpected policy/store failures MUST be sanitizedINTERNAL; anINTERNALExec or Resume failure that left compute running keeps only its fixedRT-7report afterinternal error. Caller cancellation/deadlines retain their codes. Policies own their failure logs and metrics; services MUST NOT log raw policy causes. In enforced mode only,INTERNALdiagnostics MUST includerequest_id,method,error_kindand stableerror_category. Known trusted host/store errors MUST log the full cause with categoryhost. Model/provider/harness and other unknown-origin errors MUST NOT log message text: category MUST beexecutionfor Exec/Resume,runtimefor Suspend/Fork, orexternalfor other methods. Unknown mixed execution/runtime phases MUST fail closed; store faults inside runtime MUST NOT qualify as trusted unless known at the service storage boundary. No heuristic redaction is used. Registry diagnostics and startup warnings use the logger supplied bysession.WithRegistryLogger, independently of the Sessions service’ssession.WithLogger. Absent or nil, the registry logger defaults toslog.Default()captured at construction. Request metadata, credentials and session payloads remain excluded; trusted/off behavior is unchanged. This diagnostic-only exception does not permit sensitive data in errors; see log data policy. Enforced Approve ignores request actor and stores an empty actor. It normalizes before retry comparison; historical nonempty actors are not identical retries. Approve records the verified caller asApprovalResult.verified_approverand binds exact retries to it (APR-7,APR-8). - Embedded enforcement still opens off-marked journals: unenforced hosts and CLI writers can bypass it. It is not cross-host isolation or supported required-mode deployment. Activation still needs owned fork reservation, journal policy/startup validation, daemon required-mode wiring and TLS assembly. There is no same-pod or self-dial exemption.
IdentityRef(session identity,Event.actor,ApproveRequest.identity) is caller-supplied provenance. It MUST NOT be read as authenticated identity.projectis a listing filter, not a tenancy boundary.- On the default service, any caller can delete any session it can name, irreversibly. Deletion is
neither erasure nor access revocation: the journal,
config, and metadata stay readable throughGetSessionandReplay(OPS-33), and compute and snapshots are retained until an operator reclaims them (OPS-35). - The harness is trusted code. Host mediation is a determinism mechanism, not containment; isolation
comes from the runtime backend, and
runtime/localhas none. An unmediated harness (§8.8) also sends the model calls it makes itself from its own compute, and only the runtime’s egress, not the host, can see or limit those calls. - Provider credential invariant: where the runtime isolates the harness from the host, the value
of a provider credential MUST NOT enter the harness’s compute, in either class (§8.8): not its
environment, filesystem, memory, or a snapshot of any of them.
runtime/localisolates nothing, so its harness shares the host’s credentials. A mediated harness needs no credential, because the host makes its model calls with one the host holds; the reference daemon reads it from its environment, never its arguments. An unmediated harness holds only a placeholder, which the runtime’s egress replaces with the credential on the way to the provider (EXE-40). That egress is a runtime capability this specification does not define, and the host cannot check that it is in place. A runtime that cannot inject the credential cannot host an unmediated harness under this invariant. - The runtime’s egress policy, which hosts and ports the compute may reach and which credential
the egress injects, is runtime configuration, not session state: it is not journaled and plays
no part in replay. A runtime that applies one installs it before the compute first runs, so no
turn runs without it. The reference substrate backend does this with
WithEgressPolicy, and replaces a stored policy that differs from the configured one before each later resume (Security posture). - The invariant keeps the value out of the harness, not its use. An unmediated harness can send
any request the egress allows with the injected credential, and the host neither bounds nor
records that spend (
EXE-41). Its prompts and outputs pass through the egress, which must see the request to inject the credential, so the egress is trusted with session content as well as the credential. - On Substrate v1.0.0 the reach of an installed policy follows from its source. The policy is stored
per actor name and deleted only with the actor, so a suspend and resume keeps it unless the
backend replaces it. The egress gateway reads it per request by actor name through a cache of at
most 10 seconds (
cmd/atenet/internal/router/egress/policycache.go) and denies an actor without one. A cached “no policy” can therefore only deny, and only within 10 seconds of a lookup of the same actor name made before the install; an actor deleted and recreated under its name can see the old actor’s policy for as long. - Open question: Verify end to end, against a live gateway, that an installed policy is enforced (an allowed host reachable, others denied), that the egress can inject a provider credential over a placeholder for an unmediated harness (request header, retries, TLS trust in the actor), and that no snapshot of the actor contains the value.
- The harness does not authenticate the host, and a harness registered by address is whatever answers there. A forged harness or a forged host can inject content that the chain then records faithfully. A verified chain proves the log was not altered after writing, not that its content was honest.
Describeadmission is not bound to theConnectstream.RT-3repeats it on the turn’s own connection, which narrows the window but does not close it: a reconnect or a proxy between the two calls can routeConnectto a different harness than the one that answeredDescribe.- The chain does not detect tail truncation or whole-log replacement (§7.3). It is unkeyed, so a
journal writer can also rewrite an event and recompute every later hash;
CHAIN-12refuses only journals whose stored hashes no longer match their content. ExecRequest.configand every journaled payload are durable and readable throughReplay. Credentials MUST NOT be placed in them.- At-most-once tool execution depends on executor deduplication (
TOOL-11). An executor that declares durable dedup but does not deduplicate can apply an effect twice after a crash. An approvedREQUIRES_APPROVALcall runs on recovery without the declaration (APR-14): the journal cannot tell its first attempt from a re-drive after a crash or host cancellation during execution, so an executor that does not deduplicate can apply that effect twice. - The harness registry chooses what the host dials and whose model credential pays for the calls made through the model call operation. It MUST NOT be served on the Sessions listener.
18. Versioning and compatibility
Section titled “18. Versioning and compatibility”- This document’s version tracks the Go module. The module is pre-1.0; v0.2.0 is the first release
under
github.com/agent-primitives/sessions, and v0.1.x stays atgithub.com/aramase/agentsessions. Until 1.0, a minor release MAY break the wire contract, the Go SPI, or this specification. Breaking changes are recorded in CHANGELOG.md. agentsessions.v1is a proto package name, not a stability promise.- CI runs
buf linton every change to the protos andbuf breaking(FILErules) against the most recentv*release tag. The gate armed at the first tag (v0.1.0) and is active now. - Generated Go stubs and
docs/api-reference.mdMUST match the protos; CI fails on drift. - Optional embedded RPC authorization identifies the full originating RPC path in Go
api.AuthorizationRequest.Method; built-in owner policies still decide by action. This Go SPI contract changes no protobuf fields, canonical events, journal schema or default daemon enforcement. - A server built before
ResumeRequest.expected_last_seq(OPS-29) ignores the field, and the API has no capability query. A client cannot learn from the API that the check ran; it needs to know which server version is deployed. - Journal compatibility:
CHAIN-2and the canonical options inCHAIN-1are compatibility surface. Changing them invalidates every existing chain and requires a migration and new golden vectors.- A new field in a hashed event changes
content_hashonly when populated. Older binaries that drop the field on read fail verification for records that carry it, so every host sharing a journal needs the new binary before any of them writes the field. - v0.1.x journals (no
execution_id, noEXECUTION_START) remain readable under §8.7 and verify unchanged. Recovery differs from v0.1.x: anERRORafter the lastINPUTcompletes the legacy execution (EXE-29), soResumeno longer re-runs that turn. A legacy harness invocation (reconstruction, or recovery of an unfinished legacy execution) needs a session uid;Resumeof a complete legacy execution is a no-op without one. - The reference SQLite store versions its schema with
PRAGMA user_version(seesqlitelog.SchemaVersion), migrates forward in one transaction without rewriting events or hashes, and refuses a newer or negative version. Open also creates a telemetry-onlysession_tracestable, holding each session’s latest trace context, without changing the version: it is outside the hash chain, never read by replay, and ignored by builds that do not know it. A read-only Open of a journal without the table skips it and reads no links. Version 4 adds the deletion state; migrated sessions areDELETION_ACTIVE. Version 5 adds exact caller ownership and an off-mode authorization marker. Legacy and RPC-created sessions remain unbound; these host-side contracts add no RPC enforcement. This host refuses required, unknown or missing authorization markers, even at version 5. Stop every older writer sharing a journal and back it up before its first version 5 open; an already-open older writer does not check the marker. The marker is checked only at Open, including by this build: changing the mode requires stopping every writer (including embedded CLI processes), then restarting all hosts with binaries that support the new mode. Version 6 adds explicit model-policy eligibility. Version 7 adds the allocation ledger and inventory completeness/evidence columns, without fork-publication or reaper state. Journal bytes are unchanged. Stop all older writers before that migration; no downgrade to v0.3.0 or older is supported. All inventories remain incomplete until explicit operator reconciliation (§13.4). - Version 8, new in
0.4.0-draft, changes no table and rewrites no event. Its stamp marks a journal whoseAPPROVAL_RESULTrecords may carryverified_approver(APR-8), so a version 7 build refuses the whole journal at Open. Decisions written earlier carry no approver and read as before. An older writer that already had the journal open is not stopped by the stamp: it drops the field on read, so itsExec,Resume,VerifyJournalandcontroller.Replayfail chain verification (DATA_LOSS) on a session holding one, while itsApproveRPC, and theReplayRPC of v0.3.0, read without verifying and omit the approver. Stop every older writer, including embeddedagentctl, and back up the database and WAL before the first version 8 open: Open stamps the journal even when the process only reads metadata, and there is no downgrade to version 7. - Version 10 adds the
allocation_resourcesandallocation_borrowerstables (§13.4). It adds no proto fields and changes no event bytes, and existing allocation rows are kept as they are. The migration is one-way. Stop every older host and embedded client sharing the journal, then back up the database and WAL before the first version 10 open. An older binary refuses a version 10 journal at Open, but one that already has it open is not stopped by the stamp. There is no downgrade; restore the backup to roll back. - Version 9 extends
approval_executionswith an execution outcome and rebuilds the shared execution/approval projection from the journal. Events, canonical bytes, hashes and fences do not change. An undecodable session reports RUNNING without an approval reference; SQL faults roll back the migration. A read-only open requiring migration fails, leaving the database at its original version; migrate with a writable open before using read-only clients. This reporting contract and schema change target v0.4.0. Stop all older hosts and embedded clients sharing a journal, and back up the database and any WAL before upgrading. Older binaries refuse v9 on open, but an already-open older writer can bypass the projection. There is no downgrade migration; rollback requires restoring the backup. - An older binary refuses a version 4 journal when it opens it, but one that already had the
journal open does not enforce deletion (
OPS-36): it can still append, mint fences, and update metadata after aLIFECYCLE_DELETE. Every older host and embeddedagentctlsharing a journal has to be stopped before the first version 4 open. - A verifier whose schema lacks
LIFECYCLE_DELETEcannot reproduce that record’s hash:CHAIN-1hashes enum names, and proto3-JSON writes an unknown enum value as a number. ToolResult.Code.POLICY_DENIED(TOOL-16, version0.4.0-draft) is a new value in a hashedTOOL_RESULT. It needs no SQLite schema version of its own: the new value is its only on-disk difference, and the version 8 stamp that ships with it in0.4.0-draftis forverified_approver. Only a host with a policy hook that refuses a call definitively writes it; journals without one are unchanged. A build older than version 8 refuses the journal at Open. A writer built beforePOLICY_DENIED(v0.3.0 and older) that already had the journal open still serves every session that holds noPOLICY_DENIEDreceipt. For a session that holds one, that writer canonicalizes the stored value as a number, so hash verification fails at that record (CHAIN-12,DATA_LOSS):Exec,Resume,VerifyJournaland reconstruction replay (controller.Replay) refuse the session instead of serving the receipt. TheReplayRPC (§6.6) does not verify, so it does not refuse: it streams the stored record, with the code as the unknown enum number 3. An unreleased version 7 build that already includesTOOL-16verifies and serves these receipts; it fails only on an approver-bearing record, as the version 8 note above describes. A verifier schema built before the value fails the same record. An older harness rejects the receipt on the wire (WIRE-15). Upgrade every host sharing a journal, every harness, and every audit schema before installing a hook that can refuse definitively; after one is recorded, rolling a host back leaves that session unusable to it, except as raw records fromReplay.ToolResult.Code.NOT_EXECUTEDandOUTCOME_UNKNOWN(APR-18, version0.4.0-draft) are new values in a hashedTOOL_RESULT, written only byCloseApproval. They need no SQLite schema version: journals without a close are unchanged, and a build older than version 9 refuses the journal at Open. An unreleased version 9 build without the codes still serves every session that holds no close receipt. For a session that holds one, it canonicalizes the stored value as a number, so hash verification fails at that record (CHAIN-12):VerifyJournaland the controller’sExec,Resumeandcontroller.Replayrefuse the session (DATA_LOSS). ItsExecandResumeRPCs inspect the approval before verifying the chain, so they failINTERNALwith a replay divergence instead. TheReplayRPC (§6.6) does not verify: it streams the stored record with the code as the unknown number 4 or 5. An older harness rejects the receipt on the wire (WIRE-15) and receives the number inStart.history. Upgrade every host sharing a journal and every harness before callingCloseApproval; after a close, rolling a host back leaves that session unusable to it except as raw records fromReplay.
19. Open questions
Section titled “19. Open questions”Each item is also marked inline where it applies.
- Open question: Should a store reject a
fencegreater than the last minted value (§6.4)? - Open question: External head anchor for tail truncation (§7.3).
- Open question: Python verifier parity for inexact or exponent-form float
Structnumbers, negative zero, and fractional timestamps (§7.4). - Open question: Language-neutral
input_hash(§8.3). - Open question: Authoritative invariant numbering,
I4andI5(§8.6). - Open question: Recovery of an execution an unmediated harness’s memory has no record of (§8.8).
- Open question: Time for a substrate
Execto fail after mid-turn actor loss (§8.8). - Open question: Compare re-reported
IN_HARNESS_REPORTEDresults on reconstruction (§9.3). - Open question: Whether a close ends the closed execution with
EVENT_ENDorEVENT_ERROR(§10.5). - Open question: Approval repair during a checkpoint (§11.1).
- Open question: Repeated
SuspendandResumewithoutSuspend(§11.5). - Open question: Fork journal atomicity and
at_seq > head(§11.7). - Open question: Unknown
Resumabilitynumbers read asSTATELESS_REPLAY(§12.1). - Open question: Session check and stickiness for model reply correlation failures (§12.2).
- Open question: Black-box conformance packaging (§16.2).
- Open question: End-to-end egress credential injection and policy enforcement for an unmediated harness (§17).
20. References
Section titled “20. References”20.1 Normative
Section titled “20.1 Normative”- BCP 14: RFC 2119 and RFC 8174
- RFC 8785: JSON Canonicalization Scheme (JCS)
- Protocol Buffers proto3 JSON mapping
- FIPS 180-4: Secure Hash Standard (SHA-256)
- RFC 1123: Requirements for Internet Hosts (label syntax)
- The protobuf definitions in
api/