---
title: 'A governed agent stack: every seam on one run'
description: Compose a token limiter and a response cache on the model seam with an audit log, an allowlist, a rate limiter, an error mapper and a PII scrubber on the tool seam, plus an approval gate and a recording content policy, on one weft agent.
url: https://weftgo.dev/docs/examples/governed-stack/
type: how-to
sources:
  - weft/README.md:183-206 (Seams are the product)
  - 'weft/AGENTS.md:701-706 (rule 10: two seams, first listed is outermost)'
  - weft/docs/adr/0006-seams.md
  - weft/core/agent.go:271 (WrapModel), weft/core/tool.go:580 (WrapTools)
  - weft/core/mw/tool.go:25 (Allow), 53 (Audit), 104 (MapErrors passes ToolError, context errors and ErrApprovalRequired through)
  - weft/core/mw/governance_test.go:34 (Example_piiScrubMiddleware), 75 (Example_tokenLimitMiddleware), 118 (Example_responseCacheMiddleware)
  - weft/mw/example_test.go:180 (Example_rateLimitMiddleware)
  - weft/core/errors.go:91 (ErrApprovalRequired)
  - 'weft/otel/options.go:22-54 (ContentConfig; 32-49: the parts Redact sees and never sees), weft/otel/proc.go:279-287, 140 (Local)'
  - weft/obsdb/db.go:44 (DB.Transcript)
  - weft/docs/record-contract.md (a content-off destination stores no messages record)
  - 'weft-arena/internal/suites/realworld_more.go: rwGovernedEnterprise (inspiration only)'
  - docs-site/examples/cookbook/governed/main.go, main_test.go TestGoverned, TestNothingLeaksToTheModel, TestNaiveScrubberBreaksParking
---

# A governed agent stack: every seam on one run

Governance in weft is middleware on its two seams, not a separate layer. [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) wraps every model call and [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) every tool call; in both lists the first entry is the outermost. A token limiter, a cache, an audit log, an allowlist, a rate limiter and a PII scrubber are each a closure at one of them, and recording has its own content policy on the observability pipeline.

The stack in `cookbook/governed/main.go`:

```go title="cookbook/governed/main.go"
opts := append(tools(),
	weft.Name("payments"),
	weft.MaxSteps(8),
	weft.WrapModel( // first listed = outermost
		tokenLimit(2048), // refuse before the provider bills
		c.middleware,     // a hit never reaches the provider
	),
	weft.WrapTools( // first listed = outermost
		mw.Audit(audit), // sees every call, denied ones included
		mw.Allow(func(call weft.Call) bool { return call.Name != "wire_transfer" }),
		rateLimit(20*time.Millisecond),
		mw.MapErrors(nil), // a raw error becomes INTERNAL; its text stays the cause Audit logs
		scrubPII,          // innermost: masks results and errors before any layer above sees them
	),
)
agt := weft.New(model, opts...)
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

## How it works

The shape comes from the weft-arena scenario `rw.governed-enterprise`. A payments agent looks a customer up, then asks in one step to wire money, refund an order and export a report. Every call passes the stack:

```text
model call:  tokenLimit → cache → provider
tool call:   Audit → Allow → rateLimit → MapErrors → scrubPII → (approval check) → handler
```

- `mw.Audit` is outermost, so it logs every call, the ones `mw.Allow` refuses included.
- `mw.Allow` refuses `wire_transfer`. The handler never runs, and the model sees `DENIED: tool "wire_transfer" is not allowed`.
- `rateLimit` spaces the calls that pass, across every run of the agent.
- `mw.MapErrors(nil)` turns `export_report`'s raw database error into `INTERNAL: tool "export_report" failed` and keeps the original as the cause, which `mw.Audit` logs.
- `scrubPII` is innermost, so no layer above it, and not the model, sees an e-mail address.
- `issue_refund` is built with `weft.RequireApproval`. Its check sits at the base of the chain, inside every middleware, so the call parks after passing the stack, and runs on resume.

## Seams are the product

The governance features other frameworks ship as processors need no processor layer here ([README](https://github.com/weftgo/weft/blob/v0.20.2/README.md#seams-are-the-product), [ADR 0006](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0006-seams.md)). Each is a closure at one of the two [seams](https://weftgo.dev/docs/reference/glossary/#seam), carrying its own dependencies and policy instead of importing yours. Package `mw` stays a reference set, and the patterns live as tested examples:

| Pattern | Seam | In weft |
|---|---|---|
| PII scrub | tool | an example: [`Example_piiScrubMiddleware`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/mw#example-package-PiiScrubMiddleware) |
| Allowlist | tool | shipped: [`mw.Allow(permit)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) |
| Token limiter | model | an example: [`Example_tokenLimitMiddleware`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/mw#example-package-TokenLimitMiddleware); `weft.UsageLimit` covers the measured side |
| Response cache | model | an example: [`Example_responseCacheMiddleware`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/mw#example-package-ResponseCacheMiddleware); invalidation is the caller's policy |
| Rate limit | tool | an example: [`Example_rateLimitMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-package-RateLimitMiddleware) |

A named `mw` middleware ships only when a pattern needs a dependency or a policy stance weft should own. Rate limiting is the precedent: it stays an example because `golang.org/x/time` would be the module's first dependency. The README says to revisit that when a consumer asks for one by name. This recipe's versions of the four patterns follow.

## Token limiter

A token limiter refuses a model call before the provider bills it, when the transcript the request carries is over budget. Bytes stand in for tokens here: the real count arrives with the step's finish, and by then [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) covers it.

```go title="cookbook/governed/main.go"
// tokenLimit refuses a model call before the provider bills it when the
// request's transcript is over budget, bytes standing in for tokens.
// weft.UsageLimit covers the measured side, after each step.
func tokenLimit(maxBytes int) weft.ModelMiddleware {
	return func(next weft.Model) weft.Model { return limited{next, maxBytes} }
}

type limited struct {
	next weft.Model
	max  int
}

func (m limited) Info() weft.ModelInfo { return weft.InfoOf(m.next) }

func (m limited) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	n := 0
	for _, msg := range req.Messages {
		n += len(msg.Text())
	}
	if n > m.max {
		return func(yield func(weft.ModelEvent, error) bool) {
			yield(nil, fmt.Errorf("token limit: request transcript is %d bytes, over the %d-byte budget", n, m.max))
		}
	}
	return m.next.Stream(ctx, req)
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

The refusal is a model failure, so the run fails at step 0 with `token limit: request transcript is 2700 bytes, over the 2048-byte budget` inside a `*weft.RunError`. Forwarding `Info` keeps the provider and model name on the run's record.

## Response cache

A response cache is model middleware keyed on the [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest): the same system prompt, messages and tool names replay the recorded events without a provider call.

```go title="cookbook/governed/main.go"
// cache replays a recorded answer for a request it has seen: the system
// prompt, the messages and the tool names are the key, so any change
// misses. The mutex is there because one Agent serves concurrent runs.
type cache struct {
	mu   sync.Mutex
	seen map[string][]weft.ModelEvent
	hits int
}

func (c *cache) middleware(next weft.Model) weft.Model { return cached{next, c} }

type cached struct {
	next weft.Model
	c    *cache
}

func (m cached) Info() weft.ModelInfo { return weft.InfoOf(m.next) }

func (m cached) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	names := make([]string, len(req.Tools))
	for i, td := range req.Tools {
		names[i] = td.Name
	}
	b, _ := json.Marshal(struct {
		System   string
		Messages []weft.Message
		Tools    []string
	}{req.System, req.Messages, names})
	sum := sha256.Sum256(b)
	key := hex.EncodeToString(sum[:8])

	m.c.mu.Lock()
	events, ok := m.c.seen[key]
	if ok {
		m.c.hits++
	}
	m.c.mu.Unlock()
	if ok {
		return func(yield func(weft.ModelEvent, error) bool) {
			for _, ev := range events {
				if !yield(ev, nil) {
					return
				}
			}
		}
	}
	return func(yield func(weft.ModelEvent, error) bool) {
		var got []weft.ModelEvent
		for ev, err := range m.next.Stream(ctx, req) {
			if err != nil {
				yield(nil, err) // a failure is never cached
				return
			}
			got = append(got, ev)
			if !yield(ev, nil) {
				return
			}
		}
		m.c.mu.Lock()
		m.c.seen[key] = got
		m.c.mu.Unlock()
	}
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

Invalidation is yours: here any change to the request misses. A failed stream is never stored. The map has a mutex because one agent serves concurrent runs, and the cache is shared by all of them. In the program the same question asked twice makes one provider call.

## PII scrub

A scrubber on the tool seam masks what the model, and so every transcript downstream, is shown. It scrubs both channels, because the loop renders an error's text into the transcript too:

```go title="cookbook/governed/main.go"
var email = regexp.MustCompile(`[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}`)

// scrubPII masks e-mail addresses in what a tool returns, on both
// channels: the loop renders an error's text into the transcript too.
// The errors the loop itself reads pass through untouched: rewriting
// ErrApprovalRequired would stop a RequireApproval call from parking.
func scrubPII(next weft.ToolCaller) weft.ToolCaller {
	return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
		out, err := next(ctx, tc)
		if err != nil {
			if errors.Is(err, weft.ErrApprovalRequired) || ctx.Err() != nil {
				return "", err
			}
			var te *weft.ToolError
			if errors.As(err, &te) { // keep the code the model branches on
				return "", &weft.ToolError{Code: te.Code, Message: email.ReplaceAllString(te.Message, "[redacted]")}
			}
			return "", errors.New(email.ReplaceAllString(err.Error(), "[redacted]"))
		}
		return email.ReplaceAllString(out, "[redacted]"), nil
	}
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

Two choices differ from weft's own example. The errors the loop reads itself, `weft.ErrApprovalRequired` and the context errors, pass through untouched: rewriting them would stop a `RequireApproval` call from parking. A `*weft.ToolError` from the handler keeps its code (for example `ORDER_NOT_FOUND`), so the model can still branch on it. The cause chain is dropped on purpose: a scrubber that keeps the original reachable is no scrubber.

## Rate limit

A limiter on the tool seam spaces calls at least an interval apart, with nothing but the standard library:

```go title="cookbook/governed/main.go"
// rateLimit spaces tool calls at least interval apart, across every run
// of the agent, with the standard library alone. A call waiting for its
// slot gives up when its ctx ends.
func rateLimit(interval time.Duration) weft.ToolMiddleware {
	var mu sync.Mutex
	var next time.Time // the next free slot
	reserve := func() time.Duration {
		mu.Lock()
		defer mu.Unlock()
		now := time.Now()
		if next.Before(now) {
			next = now // idle time is never banked
		}
		wait := next.Sub(now)
		next = next.Add(interval)
		return wait
	}
	return func(call weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
			if wait := reserve(); wait > 0 {
				t := time.NewTimer(wait)
				defer t.Stop()
				select {
				case <-t.C:
				case <-ctx.Done():
					return "", ctx.Err()
				}
			}
			return call(ctx, tc)
		}
	}
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

A slot in the past is pulled up to now, so idle time is never banked and the calls after a quiet stretch are still spaced. A call waiting for its slot gives up when its `ctx` ends. The limiter's state is shared by every run of the agent, so it bounds the agent's total call rate.

## Park a refund and record with a content policy

The refund parks inside the stack; the program resumes it with `weft.Approve`, and the approved call passes the stack again, `mw.Audit` logging it under step 0 of the resuming run. See [Support desk with human approval](https://weftgo.dev/docs/examples/support-desk/) for the boundary itself.

What the model sees and what is recorded are different policies. The customer's prompt carries a card number, and the model needs it. The record does not: the local sink's content policy redacts it on every content field it is given before it is written (a tools record is capped, never redacted).

```go title="cookbook/governed/main.go"
var card = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)

// redactCards is the local sink's content policy: it runs on every
// content field before it is recorded, never on what the model sees.
func redactCards(_ weft.ContentKind, s string) string {
	return card.ReplaceAllString(s, "[card]")
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

```go title="cookbook/governed/main.go"
defer otel.Install(
	otel.Local(""), // the local sink; content on
	otel.Content(otel.ContentConfig{Redact: redactCards}),
)()
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

[`otel.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Content) sets the pipeline-wide default for destinations with content on, and `otel.Local` is one. `Redact` sees the content fields of events and deltas; in a transcript record, every text, reasoning, tool-argument and tool-result part, never file parts, ids, names, roles, signatures or hashes; a prompt record's text; each stop sequence of a request record; bridged app log lines; and, in dev only, raw wire bodies (`otel.RawBodies`). It never runs on what the model is sent. The program reads the parked run's transcript back from the local sink: `[card]` is there and the number is not.

## What to look at in Studio

- **The audit line per call.** The program prints them: the denied transfer, the `pending=true` refund, the export with its `cause`, and the approved refund in the resuming run.
- **Problem counters.** The run page counts the denied transfer under `denied` and the export under `tool_errors`, read `INTERNAL ← plain error`: `MapErrors` hid a plain Go error (the attribute records `*errors.errorString`); see [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/).
- **The redacted transcript.** Studio reads what the sink stored, so the run's prompt shows `[card]`. A destination with content off stores no transcript at all; see [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/).
- **The resume link.** The resuming run names the parked one, as in the support desk.

![The governed payments run in Studio, parked: the header counts one INTERNAL tool error and one denied call, the prompt shows the card number redacted as \[card\], and step 1's wire_transfer reads DENIED, issue_refund pending and export_report INTERNAL](https://weftgo.dev/docs/_astro/studio-run-governed.light.ILXOS4Na.webp)

*The payments run, parked: the prompt reads [card], the header counts one INTERNAL ← plain error tool error and one denied call, wire_transfer is DENIED and issue_refund waits as pending.*

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `weft.WrapModel`, `weft.WrapTools` | the two seams, outermost first | [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) |
| `mw.Audit`, `mw.Allow`, `mw.MapErrors` | the shipped reference middleware | [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) |
| `weft.RequireApproval` | parks the refund inside the stack | [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) |
| `weft.UsageLimit` | the measured token budget beside the limiter | [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) |
| `otel.Content` with `Redact` | what the record keeps | [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/) |

## The program

```go title="cookbook/governed/main.go"
// Command governed is the recipe "A governed agent stack: every seam on
// one run": go run ./cookbook/governed. A payments agent runs inside a
// token limiter and a response cache on the model seam, and an audit
// log, an allowlist, a rate limiter, a PII scrubber and an error mapper
// on the tool seam. A refund waits for a human, and the local sink's
// content policy redacts card numbers from what is recorded. The models
// are scripted with wefttest, so it runs offline; the runs are recorded
// to the local sink ($WEFT_DB, else ./.weft/weft.db).
package main

import (
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"iter"
	"log/slog"
	"os"
	"regexp"
	"slices"
	"strings"
	"sync"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/mw"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

// ---- the model seam ----

// tokenLimit refuses a model call before the provider bills it when the
// request's transcript is over budget, bytes standing in for tokens.
// weft.UsageLimit covers the measured side, after each step.
func tokenLimit(maxBytes int) weft.ModelMiddleware {
	return func(next weft.Model) weft.Model { return limited{next, maxBytes} }
}

type limited struct {
	next weft.Model
	max  int
}

func (m limited) Info() weft.ModelInfo { return weft.InfoOf(m.next) }

func (m limited) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	n := 0
	for _, msg := range req.Messages {
		n += len(msg.Text())
	}
	if n > m.max {
		return func(yield func(weft.ModelEvent, error) bool) {
			yield(nil, fmt.Errorf("token limit: request transcript is %d bytes, over the %d-byte budget", n, m.max))
		}
	}
	return m.next.Stream(ctx, req)
}

// cache replays a recorded answer for a request it has seen: the system
// prompt, the messages and the tool names are the key, so any change
// misses. The mutex is there because one Agent serves concurrent runs.
type cache struct {
	mu   sync.Mutex
	seen map[string][]weft.ModelEvent
	hits int
}

func (c *cache) middleware(next weft.Model) weft.Model { return cached{next, c} }

type cached struct {
	next weft.Model
	c    *cache
}

func (m cached) Info() weft.ModelInfo { return weft.InfoOf(m.next) }

func (m cached) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	names := make([]string, len(req.Tools))
	for i, td := range req.Tools {
		names[i] = td.Name
	}
	b, _ := json.Marshal(struct {
		System   string
		Messages []weft.Message
		Tools    []string
	}{req.System, req.Messages, names})
	sum := sha256.Sum256(b)
	key := hex.EncodeToString(sum[:8])

	m.c.mu.Lock()
	events, ok := m.c.seen[key]
	if ok {
		m.c.hits++
	}
	m.c.mu.Unlock()
	if ok {
		return func(yield func(weft.ModelEvent, error) bool) {
			for _, ev := range events {
				if !yield(ev, nil) {
					return
				}
			}
		}
	}
	return func(yield func(weft.ModelEvent, error) bool) {
		var got []weft.ModelEvent
		for ev, err := range m.next.Stream(ctx, req) {
			if err != nil {
				yield(nil, err) // a failure is never cached
				return
			}
			got = append(got, ev)
			if !yield(ev, nil) {
				return
			}
		}
		m.c.mu.Lock()
		m.c.seen[key] = got
		m.c.mu.Unlock()
	}
}

// ---- the tool seam ----

var email = regexp.MustCompile(`[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}`)

// scrubPII masks e-mail addresses in what a tool returns, on both
// channels: the loop renders an error's text into the transcript too.
// The errors the loop itself reads pass through untouched: rewriting
// ErrApprovalRequired would stop a RequireApproval call from parking.
func scrubPII(next weft.ToolCaller) weft.ToolCaller {
	return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
		out, err := next(ctx, tc)
		if err != nil {
			if errors.Is(err, weft.ErrApprovalRequired) || ctx.Err() != nil {
				return "", err
			}
			var te *weft.ToolError
			if errors.As(err, &te) { // keep the code the model branches on
				return "", &weft.ToolError{Code: te.Code, Message: email.ReplaceAllString(te.Message, "[redacted]")}
			}
			return "", errors.New(email.ReplaceAllString(err.Error(), "[redacted]"))
		}
		return email.ReplaceAllString(out, "[redacted]"), nil
	}
}

// rateLimit spaces tool calls at least interval apart, across every run
// of the agent, with the standard library alone. A call waiting for its
// slot gives up when its ctx ends.
func rateLimit(interval time.Duration) weft.ToolMiddleware {
	var mu sync.Mutex
	var next time.Time // the next free slot
	reserve := func() time.Duration {
		mu.Lock()
		defer mu.Unlock()
		now := time.Now()
		if next.Before(now) {
			next = now // idle time is never banked
		}
		wait := next.Sub(now)
		next = next.Add(interval)
		return wait
	}
	return func(call weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, tc weft.ToolCallPart) (string, error) {
			if wait := reserve(); wait > 0 {
				t := time.NewTimer(wait)
				defer t.Stop()
				select {
				case <-t.C:
				case <-ctx.Done():
					return "", ctx.Err()
				}
			}
			return call(ctx, tc)
		}
	}
}

type CustomerInput struct {
	CustomerID string `json:"customer_id" jsonschema:"the customer id"`
}

type WireInput struct {
	ToAccount string  `json:"to_account" jsonschema:"IBAN"`
	Amount    float64 `json:"amount" jsonschema:"amount in EUR"`
}

type RefundInput struct {
	OrderID string  `json:"order_id" jsonschema:"the order id"`
	Amount  float64 `json:"amount" jsonschema:"amount in EUR"`
}

// tools are the payments agent's four tools.
func tools() []weft.Option {
	getCustomer := weft.Tool("get_customer", "Customer record by id.",
		func(_ context.Context, in CustomerInput) (map[string]string, error) {
			return map[string]string{"id": in.CustomerID, "name": "Jane Doe", "email": "jane.doe@example.com", "plan": "pro"}, nil
		})
	wire := weft.Tool("wire_transfer", "Send money to an account.",
		func(_ context.Context, _ WireInput) (string, error) {
			return "sent", nil
		})
	refund := weft.Tool("issue_refund", "Refund an order. A human approves every refund.",
		func(_ context.Context, in RefundInput) (string, error) {
			return fmt.Sprintf("refunded %.2f EUR on order %s", in.Amount, in.OrderID), nil
		}, weft.RequireApproval())
	export := weft.Tool("export_report", "Account report for a customer.",
		func(_ context.Context, _ CustomerInput) (string, error) {
			return "", errors.New("pq: connection refused (host 10.0.4.7, user reports_rw)")
		})
	return []weft.Option{getCustomer, wire, refund, export}
}

// newAgent builds the governed agent. audit receives one line per tool
// call; c is the response cache, shared by every run of the agent.
func newAgent(model weft.Model, audit *slog.Logger, c *cache) *weft.Agent {
	opts := append(tools(),
		weft.Name("payments"),
		weft.MaxSteps(8),
		weft.WrapModel( // first listed = outermost
			tokenLimit(2048), // refuse before the provider bills
			c.middleware,     // a hit never reaches the provider
		),
		weft.WrapTools( // first listed = outermost
			mw.Audit(audit), // sees every call, denied ones included
			mw.Allow(func(call weft.Call) bool { return call.Name != "wire_transfer" }),
			rateLimit(20*time.Millisecond),
			mw.MapErrors(nil), // a raw error becomes INTERNAL; its text stays the cause Audit logs
			scrubPII,          // innermost: masks results and errors before any layer above sees them
		),
	)
	agt := weft.New(model, opts...)
	return agt
}

// auditLogger writes mw.Audit's lines without the fields that change
// from run to run (time, run id, duration).
func auditLogger(w io.Writer) *slog.Logger {
	return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
		ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
			switch a.Key {
			case slog.TimeKey, slog.LevelKey, "run", "dur":
				return slog.Attr{}
			}
			return a
		},
	}))
}

var card = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)

// redactCards is the local sink's content policy: it runs on every
// content field before it is recorded, never on what the model sees.
func redactCards(_ weft.ContentKind, s string) string {
	return card.ReplaceAllString(s, "[card]")
}

func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(
		otel.Local(""), // the local sink; content on
		otel.Content(otel.ContentConfig{Redact: redactCards}),
	)()

	var audit bytes.Buffer
	c := &cache{seen: map[string][]weft.ModelEvent{}}
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "get_customer", Args: `{"customer_id":"7"}`}),
		wefttest.ToolCalls(
			wefttest.Call{ID: "c2", Name: "wire_transfer", Args: `{"to_account":"FR76-0001","amount":500}`},
			wefttest.Call{ID: "c3", Name: "issue_refund", Args: `{"order_id":"A-1","amount":59}`},
			wefttest.Call{ID: "c4", Name: "export_report", Args: `{"customer_id":"7"}`},
		),
		wefttest.Say("Refunded 59 EUR. The wire transfer is not allowed and the report failed."),
		wefttest.Say("We open at 9:00."),
	)
	agt := newAgent(model, auditLogger(&audit), c)

	start := time.Now()
	parked, err := agt.Generate(ctx, weft.Prompt("Customer 7 paid with card 4242 4242 4242 4242. Wire 500 EUR to FR76-0001, refund order A-1 and export the report."))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "== run 1")
	for _, st := range parked.Steps {
		for _, r := range st.Results {
			fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content)
		}
	}
	for _, pc := range parked.Pending {
		fmt.Fprintln(w, "parked:", pc.ID, pc.Name)
	}
	fmt.Fprintln(w, "rate limiter spaced the calls:", time.Since(start) >= 2*20*time.Millisecond)

	run1Audit := audit.Len() // run 1's audit lines end here
	fmt.Fprintln(w, "== run 2: the refund approved")
	res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), weft.Approve("c3"), weft.ResumeOf(parked.ID))
	if err != nil {
		return err
	}
	for _, m := range res.Messages {
		for _, p := range m.Content {
			if r, ok := p.(weft.ToolResultPart); ok && r.CallID == "c3" {
				fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content)
			}
		}
	}
	fmt.Fprintln(w, "answer:", res.Text())

	fmt.Fprintln(w, "== audit")
	// One step's calls log as they finish, so their order varies between
	// runs: print each run's lines sorted.
	for _, part := range []string{audit.String()[:run1Audit], audit.String()[run1Audit:]} {
		lines := strings.Split(strings.TrimSpace(part), "\n")
		slices.Sort(lines)
		fmt.Fprintln(w, strings.Join(lines, "\n"))
	}

	fmt.Fprintln(w, "== content policy")
	sent := strings.Contains(model.Requests()[0].Messages[0].Text(), "4242 4242 4242 4242")
	bodies, err := otel.LocalDB().Transcript(ctx, parked.ID)
	if err != nil {
		return err
	}
	var recorded string
	for _, b := range bodies {
		recorded += string(b)
	}
	fmt.Fprintln(w, "the model saw the card:", sent)
	fmt.Fprintln(w, "the record holds the card:", strings.Contains(recorded, "4242 4242"),
		"holds [card]:", strings.Contains(recorded, "[card]"))

	fmt.Fprintln(w, "== cache and token limit")
	for range 2 {
		if _, err := agt.Generate(ctx, weft.Prompt("When do you open?")); err != nil {
			return err
		}
	}
	fmt.Fprintln(w, "provider calls:", len(model.Requests()), "cache hits:", c.hits)
	_, err = agt.Generate(ctx, weft.Prompt(strings.Repeat("too long ", 300)))
	fmt.Fprintln(w, "oversized prompt:", err)
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[cookbook/governed/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/governed/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/governed) · run it from `docs-site/examples`:

```sh
go run ./cookbook/governed
go test ./cookbook/governed
```

```text
== run 1
get_customer → {"email":"[redacted]","id":"7","name":"Jane Doe","plan":"pro"}
wire_transfer → DENIED: tool "wire_transfer" is not allowed
export_report → INTERNAL: tool "export_report" failed
parked: c3 issue_refund
rate limiter spaced the calls: true
== run 2: the refund approved
issue_refund → refunded 59.00 EUR on order A-1
answer: Refunded 59 EUR. The wire transfer is not allowed and the report failed.
== audit
msg="tool call" step=0 call=c1 tool=get_customer result_bytes=62
msg="tool call" step=1 call=c2 tool=wire_transfer err="DENIED: tool \"wire_transfer\" is not allowed"
msg="tool call" step=1 call=c3 tool=issue_refund pending=true
msg="tool call" step=1 call=c4 tool=export_report err="INTERNAL: tool \"export_report\" failed" cause="pq: connection refused (host 10.0.4.7, user reports_rw)"
msg="tool call" step=0 call=c3 tool=issue_refund result_bytes=31
== content policy
the model saw the card: true
the record holds the card: false holds [card]: true
== cache and token limit
provider calls: 4 cache hits: 1
oversized prompt: weft: run failed at step 0: model stream: token limit: request transcript is 2700 bytes, over the 2048-byte budget
```

The audit logger drops the time, the level, the run id and the duration, and the program prints each run's lines sorted: calls of one step log as they finish, so their order varies. The lines are then stable. The tests also pin that no e-mail address or database detail reaches the transcript, and that a scrubber which rewrites every error stops the refund from parking.

## Best practices & gotchas

- **Pass `ErrApprovalRequired` and context errors through any middleware that rewrites errors.** Turned into a plain error, a park becomes an ordinary error result and the refund never waits for a person. `mw.MapErrors` passes them through; weft's own `Example_piiScrubMiddleware` rewrites every error and would not. (Source: `weft/core/mw/tool.go:104` godoc, test `TestNaiveScrubberBreaksParking`)
- **Order the tool chain on purpose.** First listed is outermost: `mw.Audit` outside `mw.Allow` logs refused calls, and a scrubber innermost hides PII from every layer above it. (Source: AGENTS.md rule 10)
- **Put `mw.MapErrors` outside the scrubber to keep a cause.** The scrubber drops the cause chain; `MapErrors` outside it keeps the scrubbed raw error as the cause `mw.Audit` logs. (Source: `weft/core/mw/tool.go:53`, 95 godoc)
- **Share middleware state safely.** A cache or a limiter built once is used by every concurrent run of the agent: guard it with a mutex. (Source: `weft/core/mw/governance_test.go:111-117`)
- **Redact in the pipeline, scrub in the chain.** `otel.Content`'s `Redact` shapes only what is recorded; tool middleware shapes what the model sees. Each needs its own rule. (Source: `weft/otel/options.go:22-54`)

## See also

- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/): the seams and the shipped middleware
- [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/): per-destination content, redaction, content kinds
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)
- [Design principles: the rules weft keeps](https://weftgo.dev/docs/explanation/design-principles/)

Symbols used: [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware) · [`weft.ToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolMiddleware) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.ContentKind`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentKind) · [`mw.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) · [`mw.Allow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) · [`mw.MapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Content) · [`otel.ContentConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentConfig) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
