Design principles: the rules weft keeps
weft keeps 13 rules for its loop and 5 for its sessions, and a test or a gate pins each one. They exist because each answers a way agent loops fail in production: a runaway that looks like success, a tool error that aborts a run, a transcript the provider rejects, a hook that changes behaviour by registration order. This page states each rule, the failure it prevents, and where it is enforced. The rules are restated from AGENTS.md at v0.20.2, with detail checked against the code; the reasons come from the ADRs and the agent-loop deep dive.
The loop rules
Section titled “The loop rules”1. Tool error = data the model sees; run error = Go error. A handler error, a panic, an unknown tool or bad arguments becomes a tool result with IsError: true, and the step’s other calls keep running. A model failure, cancellation, a budget breach, a malformed tool-source snapshot (ErrDuplicateTool, ErrNilTool) or a misconfigured run (ErrInvalidRunOption, ErrInvalidSteer, a Resolve on a call that is not pending, an invalid ToolChoice or Params, a PrepareStep error) fails the run, always as a *weft.RunError with the partial transcript on .Result. Why: the model asked for several things and can recover from one failure if it is told what went wrong; cancelling the siblings, as errgroup would, throws away finished work, and failing the run throws away all of it (ADR 0002). Pinned by TestToolErrorIsDataTheModelSees, TestPanickingToolIsContained, TestUnknownToolBecomesErrorResult.
2. Messages are role plus typed parts; events are tagged structs. Both carry a type discriminator on the wire, and an unknown type is an error on decode, never a silent drop. The roles are user, assistant and tool; there is no system role, because instructions belong to the agent. A file is a FilePart; an adapter that cannot carry one fails wrapping ErrUnsupported. A transcript fed back in is repaired first: every call gets a result, orphans are dropped (weft.Repair). Why: a stored transcript or event stream must replay exactly what happened; a decoder that skips what it does not know loses data without saying so (ADR 0001, ADR 0004). Pinned by TestMessageJSONRejectsUnknownPart, TestUnmarshalEventRejectsUnknownType, TestEventJSONRoundTrip, TestRepairSynthesisesMissingResults.
3. Tools start in call order, results land in call order, events carry Seq. Sequential() runs calls one at a time; a tap sees the same order as Events(). Why: with parallel tools, start order, result order and observation order are three separate questions. Answering each one with a fixed rule, and assigning Seq under the same lock that emits, makes a recorded stream replay exactly (ADR 0004). Pinned by TestToolStartsInCallOrder, TestStreamEventOrdering, TestSequentialToolIsABarrier.
4. Every run has an id. RunStart is the first event and RunFinish the last event of a successful run. The id is minted before anything runs, so a caller can hand it to a client first, and every tool call learns its own run, step and call id through weft.CallFromContext(ctx). Why: records, child runs, approvals and Studio’s links all key on it; adding ids later is a breaking change (ADR 0004). Pinned by TestRunIDsAreGeneratedAndStreamed.
5. Model-visible behaviour is a contract. Tool result text, schemas and transcript shape change only with an ADR. Why: a model’s behaviour depends on the exact strings it reads, such as DENIED: no decision or INVALID_INPUT: tool "x": field "days": expected integer, got string. A reworded error is a behaviour change for every deployed agent. Pinned by the pinned-bytes tests, for example TestDecodeErrorsNameTheField.
6. Nothing above the core is imported by the core. No HTTP, no database, no tracing backend; the OpenTelemetry API is the one permitted dependency (ADR 0016). Why: a loop that imports its own recorder or UI cannot be used without them. Since ADR 0027 the core is its own module, so the rule is visible in core/go.mod. Held by the module boundary and the release gate: clause k1 of scripts/ux-gate/gate8.sh fails when core depends on a package outside the core module or core/go.mod changes. How weft is put together shows the layers.
7. The loop enforces the Model stream contract. Exactly one ModelFinish, nothing after it, no call with an empty id or name, no repeated id in a step, and a panic in the adapter becomes a run error; all wrap ErrModelContract. Why: a broken adapter must not corrupt a transcript. Nothing from a failed model turn is appended, so RunError.Result.Messages is always valid input for a retry. Pinned by TestModelStreamContractViolations.
8. Truncation is visible, never silent. A max_tokens finish is recorded on RunResult.StopReason and the run still succeeds; a tool result over 64 KiB (the default weft.MaxResultBytes, per agent or per tool, 0 for none) is cut on a rune boundary and ends with …[truncated N bytes]. Why: a cut the model cannot see becomes a wrong answer the model believes. Pinned by TestMaxResultBytes.
9. A hung tool never hangs the run. With weft.Timeout on a tool or an agent, an overdue call becomes the error result tool "X" timed out after 5s (the configured duration) and its goroutine is abandoned. Why: one stuck network call otherwise holds the step, the run and the caller. The handler is abandoned, not stopped, so handlers must honour ctx. Pinned by TestToolTimeout.
10. Two behavioural seams, one tap, no more. WrapModel and WrapTools (first listed is outermost) are where behaviour attaches; Tap observes. The loop’s spans and log lines are reporting at its own phases, not seams. Panic containment and timeouts sit outside the tool chain, so no middleware can turn a panic into a run failure. Why: every lifecycle hook is a contract that can never be removed, and hooks that change behaviour make registration order part of the semantics. A third seam needs an ADR (ADR 0006). Pinned by TestWrapToolsDenialAndPanicAreToolErrors.
11. A max_tokens step with tool calls executes none of them. Each call gets tool call X was not executed: the response hit the output token limit, and the model retries with a full budget. Why: an intact-looking call may be the first of several the model never finished issuing; running it acts on half a plan. Pinned by TestMaxTokensWithToolCallsFailsThemWithoutExecuting.
12. Approval is a run boundary. Pending calls end the run successfully with RunResult.Pending and RunFinish.Pending set; the next run resumes with Approve or Deny, and a call left undecided gets DENIED: no decision. Why: the person deciding is rarely in the process; a decision that may arrive over HTTP a day later cannot be a blocked goroutine. The boundary needs no persistence in the core. It is a policy seam, not a security boundary (ADR 0007). Pinned by TestApprovalPendingStopsTheRunAndResumes, TestApprovalWithoutDecisionsIsRepairedAsInterrupted, TestCanceledRunWithPendingCallsFails.
13. Budgets fail at the continuation point. MaxSteps, UsageLimit, MaxModelRetries and DetectLoops are checked only when the loop would call the model again, so a step that ends the run succeeds even if it overshot. A breach is a *RunError with the partial transcript. Child runs are tools: their failure is data, their usage is the parent’s. The exception is a thread/pool child, which is a session: its usage is on its receipt and in the parent session’s Usage.Delegated, never on the parent run’s RunResult.Usage. Why: a budget stops further spend; it does not discard finished work, and it never makes a runaway look like a success (ADR 0002). Pinned by TestMaxStepsExceeded, TestStopWhenStepCountIsSucceedsWhereMaxStepsFails, TestUsageLimitFinalStepMayOvershoot, TestUsageLimitIncludesSubagents, TestCancellationBeatsMaxSteps.
The rules that matter
Section titled “The rules that matter”The README states the same rules from the user’s side, with four facts the numbered list leaves implicit:
- Tools are generic functions.
weft.Tool[In, Out]takesfunc(ctx, In) (Out, error)and reflects the schema fromIn’s struct tags: the same shape the official Go MCP SDK’sAddTool[In, Out]uses, so a weft tool can be served over MCP without a second definition (ADR 0003). - Parallel by default, bounded at 4. Calls of one step run up to
weft.Parallelism(n)at once, 4 by default, and always start in call order;weft.Sequential()runs them one at a time when they share state. The deep dive records an unbounded default, every emitted call started at once, as the choice weft declined. - String outputs are sent verbatim, everything else as JSON. A tool that returns
stringcontrols the exact text the model reads. - One dependency in the core module. The OpenTelemetry API, trace and logs, a no-op until an SDK registers. The vendor SDKs, the OpenTelemetry SDK and exporters, and the SQLite and ClickHouse drivers are dependencies of the framework module, never of
core(ADR 0027).
The README also gives a reason for rule 8’s first half: the run succeeds on a truncated text answer because only the caller knows what truncated text means for its task.
The thread rules
Section titled “The thread rules”Sessions (weft/thread) add durable state, so they need rules a stateless loop does not. What is a session? explains the model; these are its guarantees.
- T1. One writer per Session. A
thread.Sessiontakes its session’s writer lease with its first write (CreateandForkare one) and holds it untilClose. Another Session’s write fails withErrLockedand changes nothing; one whose view fell behind fails withErrStaleand must open the session again. Why: an append-only tree with two writers forks silently. A lease makes the second writer fail loudly before it writes. Pinned byTestSecondOpenIsLocked,TestClaim. - T2. Close what you opened to write.
s.Close(ctx)stops new work, drains the running turn and the queue, seals the Session (ErrClosed) and gives the lease up. Why: the lease is what keeps the next writer out, and it has no expiry. A Session never closed holds it until its process exits (jsonl’s file lock drops with the process; on sqlite a dead holder on the same host is taken over, while a lock row from another host stays untilsqlite.BreakLock). Pinned byTestCloseDrainsRunningTurnAndQueue. - T3.
Openis read-only. It writes no entry, takes no lock and starts no run; what a stopped writer left queued is restored tos.Queue()and runs with the nextSendors.Continue(ctx). Why: reading a session (for Studio, a list page, a support tool) must never compete with its writer. Pinned byTestOpenStartsNoRun,TestQueuedSendSurvivesARestart,TestCompactionMarkerOpenEmitsNothing. - T4. Accepted input is durable input. A
Sendthat returns aTurnhas written and flushed its prompt or receipt entry; a run’s messages are appended as they join, each step once; nothing is deleted or rewritten in place. Why: a process can die at any instant. A prompt the caller was told was accepted must survive it, and a log that is only appended can be read back after any crash. Pinned byTestSendPromptDurableWhenRunNeverStarts,TestPerStepDurableWhileRunning. - T5. Readers fail loudly. An unknown entry kind or a newer
"v"isErrNewerFormat, never skipped, withthread.Salvage()or without. A damaged line isErrCorrupt; underSalvageit is skipped and the skip reported ins.LoadReport(), as a dropped torn tail always is. The format is documented in ADR 0011 and is not frozen before 1.0. Why: an older binary that skipped a newer entry kind would derive the session’s state without it and append on top of a state it misread. Pinned byTestUnmarshalEntryLoud,TestMemoryWithoutSalvageIsLoud,TestLoadReportTornTail.
A consequence of T1: a write made with st.Append on a session a thread.Session holds bypasses the lease, so the rule holds only for writes that go through the Session (Operate sessions in production).
Principles with evidence
Section titled “Principles with evidence”The agent-loop deep dive (Part V) distils the rules into fifteen principles for anyone designing an agent library. Restated against v0.20.2:
- The loop is forty lines; the rules are the product. Every framework has the same loop; what differs is the answers to the questions in The agent loop, from first principles. Write the answers down before the code, as weft’s ADRs do.
- One error rule. Tool error is data, run error is an error; retries, hints, approvals and budgets all hang off it.
- Budgets fail, stop conditions succeed. Ship bounded defaults: 10 steps, 4 parallel calls, 64 KiB per result.
- Decide the three orderings separately, start, result and event, and number events under the lock that emits them.
- Cancellation is a cause, not a budget. No tool starts after it, nothing is emitted after it, and it wins over
ErrMaxSteps. - The transcript is always valid input. Repair on the way in, visibly; never append an empty turn.
- Pin the bytes the model sees. A change is an ADR and a test.
- Two seams, one tap. Refuse the third hook, and write down why.
- Approval is a run boundary in a stateless core, and it is policy, not security.
- Delegation is a tool, with usage attribution, lineage, nested events and a cycle guard; no handoff primitive and no graph.
- Ids first: runs, calls, children.
- Additive change, gated.
apidiffin CI, no renames, sealed interfaces, a CHANGELOG that lists model-visible changes. Pre-1.0 the gate enforcescoreand reports the framework module (repository). - Imports point down. The core depends on the OpenTelemetry API and nothing else.
- Say no in writing. The refused designs (lifecycle hooks, a graph DSL, an unbounded default) are recorded with their reasons.
- Pin behaviour with scripted tests and pinned bytes: a scripted
Model, a conformance suite per adapter, a golden manifest,-raceon every run.
The edge-case catalog
Section titled “The edge-case catalog”The deep dive’s catalog is the test plan for any loop, in five groups. weft’s core/contract_test.go, seams_test.go, agent_test.go, tooloption_test.go (timeouts) and fuzz_test.go cover them:
| Group | Cases |
|---|---|
| Stopping | no tools → success; tools after the last step → budget error with the transcript; cancel during the last step → cancellation, not budget; max_tokens on text → success; max_tokens with calls → none executed; a stop condition on a call; a zero-step run that only resolves approvals |
| Tool failure | handler error, handler panic, middleware panic → error results, siblings finish; unknown tool, bad arguments, unknown field under StrictInput → coded results naming the field; cooperative and hung handlers under a timeout; a huge result capped with a marker; a *ToolError whose cause stays out of the transcript |
| Concurrency and events | four parallel tools in call order; a barrier in the middle of a batch; Parallelism(1) sets the provider hint; cancel before a slot → error result, no events; every ToolFinish after its ToolStart; taps in stream order; every event type round-trips on the wire |
| Transcript and approval | a dangling call → no result recorded: the call was interrupted; orphaned results dropped; empty turns not appended, reasoning-only turns kept; approve, deny and no decision → three visible results in call order; cancel while pending → cancellation with Pending on the result |
| Subagents | nested event order and Seq; usage rolled up, a failed child’s partial usage counted; SUBAGENT_FAILED, SUBAGENT_PENDING, SUBAGENT_CYCLE; parent cancel stops the child; an Output[T] child returns its JSON; the lineage id on the nested RunStart |
The harness that runs the catalog
Section titled “The harness that runs the catalog”wefttest.Script is the scripted Model that plays these cases offline: Say, ToolCalls, Fail, MaxTokens compose a run’s turns, usage is deterministic, and it ignores WEFT_MODEL_REQUESTS=deny so tests never depend on the environment. wefttest.Golden pins files byte for byte and owns the -update flag. Each adapter runs wefttest/conformance, 18 cases from text_only through cancel_mid_stream, max_tokens, idle_timeout and kill_switch to never_contract_violation, with capability gaps declared in conformance.Caps rather than skipped quietly. The core has six fuzz targets (FuzzRepair, FuzzUnmarshalEvent, FuzzMessageUnmarshal, FuzzToolInvokeArgs, FuzzPartialJSON, FuzzRawRedaction) and thread five more. Test agents offline applies the harness to your own agents.
How to read weft’s source
Section titled “How to read weft’s source”| To understand | Read | Then the test |
|---|---|---|
| The loop | core/loop.go: execute, execTools, callTool | core/contract_test.go |
| The phases of a step and a call | docs/life-of-a-call.md | |
| Messages and repair | ADR 0001, core/message.go, core/repair.go | TestRepairSynthesisesMissingResults |
| Errors | ADR 0002, core/errors.go | TestToolErrorIsDataTheModelSees |
| Tools and schemas | ADR 0003, core/tool.go, core/schema.go | core/schema_test.go |
| Events and ordering | ADR 0004, core/events.go, core/run.go | TestStreamEventOrdering, TestEventJSONRoundTrip |
| Seams | ADR 0006, core/agent.go, core/tool.go, core/mw/ | core/seams_test.go |
| Approval | ADR 0007, core/loop.go (resolvePending) | TestApprovalPendingStopsTheRunAndResumes |
| Structured output | ADR 0008, core/output.go | core/output_test.go |
| Subagents | ADR 0014, core/subagent.go | TestSubagentUsageRollsUp |
| Adapters | ADR 0013, openai/, anthropic/, google/, core/wefttest/conformance/ | the conformance suites |
| The manifest | ADR 0012, core/manifest.go | TestManifestIsStable |
The manifest: the agent as a diffable artifact
Section titled “The manifest: the agent as a diffable artifact”weft.Manifest renders weft.json: per agent its name, model, instructions and policy (parallelism, max_steps, max_result_bytes, max_model_retries, stop_when by name, usage_limit, detect_loops); per tool its description, input and output schemas, policy flags, replay_policy, subagent and where it was defined (since 0.20.0 the import-path form, github.com/x/app/tools.go:12). Since 0.20.0 it also lists each agent’s model and tool middleware outer to inner and its hooks, an Output’s output_type and the params (The onion in the record). It is generated from code, committed, and compared by a golden test, so a review shows any schema or instruction change as a diff. It is output, never input: the code is the configuration. Stop conditions print their names (has_tool_call:submit) because the built-ins implement fmt.Stringer for this file. Describe your agents in weft.json shows how to generate it.
See also
Section titled “See also”- The agent loop, from first principles
- Architecture decision records
- Tool errors are data, run errors are yours
- How does a run stop?
- Operate sessions in production
Symbols used: weft.RunError · weft.Repair · weft.Timeout · weft.Tool · weft.Parallelism · weft.Sequential · weft.MaxResultBytes · weft.WrapModel · weft.WrapTools · weft.Tap · weft.Manifest · wefttest.Script · wefttest.Golden · thread.Session · thread.Salvage